:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(stamphog): add repositories from an installation snapshot (#105351)
Julian Bez4ed5635f1e5d
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex fc5748e86fd1..630f27e85c22 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -141,6 +141,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st# stamphog lives on a separate product DB; every model is a ProductTeamModel whose# fail-closed manager (.for_team / safely_get_queryset) scopes every query by team_id."StamphogRepoConfig",+ "StamphogInstallation","PullRequest","ReviewRun","DigestChannel",diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex eafece4f7d28..91f84243cd03 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -182,17 +182,29 @@ A refusal writes nothing to GitHub and creates no run, so it cannot leave or rem## Trust boundaries-- The review-gating fields (`enabled`, `review_mode`, `trigger_label`) and the soft-delete need the- `manager` level on the `stamphog` resource, because they decide whether a pull request is reviewed- at all. Naming one of those fields on a create takes `manager` too. Connecting a repository- without them, and the digest toggle, stay at `editor`.+- Turning reviews **off** (`enabled=False`, the soft-delete) and changing when they run (`review_mode`,+ `trigger_label`) need the `manager` level on the `stamphog` resource, on an update or a create alike. Turning reviews+ **on** (`enabled=True`, or `add_repository`) needs `editor`, so an editor can re-enable a repository+ a manager paused; that is the requested self-serve direction. A supplied value counts even when it+ matches the stored one, because the view's snapshot of the row is stale by the time the facade+ saves. The digest toggle stays at `editor`. Service credentials are refused at both levels.+- A sync records what the member's own GitHub token lists in the team's `StamphogInstallation`+ snapshot and creates no repo config. `add_repository` binds only a repository in that snapshot,+ taking the installation id and the connecting user from the record, never from the request.+ Never list an installation's repositories with the installation token for this: an outside+ collaborator on one repository can reach the installation, and that token shows every private+ repository in it. The snapshot is a union across members' syncs, and only the removal and+ uninstall webhooks shrink it. A `repositories_added` webhook never grows it: the webhook carries+ no user, so nobody on the team proved access to that repository. It becomes addable when a member+ syncs again.- Review policy is read from the repo's **default branch**, never the PR head — a PR must not beable to rewrite the policy that gates it. Same for the `digest:` channel declaration and theroot `owners.yaml` team registry the digest routes through.- A manually-created repo config (blank `installation_id`) binds **disabled** when a sync adopts it,and its review policy (`review_mode`, `trigger_label`) resets to the model defaults: all of thosefields were set by someone who never proved GitHub access, so a pre-selected label mode would- otherwise go live the moment a manager enables the row. Reinstall rebinds keep settings — those+ otherwise go live the moment someone enables the row. `add_repository` resets a placeholder's+ policy the same way when it binds one. Reinstall rebinds keep settings — thosewere configured under a verified binding. Such a row is also kept out of the digest candidates:a blank installation can fetch no routing file, and every candidate is read, so leaving it in letone placeholder silence the whole team's digest.diff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 1084b406d7de..c661a6644cc7 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -48,13 +48,19 @@ Every other rule still applies: drafts, closed PRs, bot-authored PRs, PRs from o## Connect a repository1. Install the Stamphog GitHub App on your GitHub organization.-2. Open Stamphog in the PostHog app and select **Connect a repository**. The install callback syncs the repositories the installation can reach.-3. Turn on **Enabled** for each repository you want reviewed. A connected repository reviews nothing until you do.+2. Open Stamphog in the PostHog app and connect GitHub. The callback records the repositories you can reach with your own GitHub account. It adds none of them yet.+3. Add each repository you want reviewed (`POST repo_configs/add_repository`). Adding a repository turns its reviews on. The list of repositories you can add comes from `GET repo_configs/available_repositories`.4. Pick a **review mode**: "All PRs" reviews every pull request, "Label-triggered" reviews only PRs carrying the trigger label. Set the trigger label name next to the mode.5. Turn on **Digest enabled** if you want the daily Slack digest of merged PRs. The project needs a connected Slack integration first, or the digest run stops silently before posting.-Connecting a repository and the digest toggle need the `editor` level on the `stamphog` resource.-The gating fields, which are enabled, review mode and trigger label, need `manager`, because they decide whether a pull request is reviewed at all.+The repositories you can add are the ones a project member reached with their own GitHub account, not every repository the installation can reach.+Each member who connects adds the repositories they can reach, and connecting again refreshes the list.+Repositories removed from the installation on GitHub leave the list on their own.+A repository added to the installation later shows up after a member connects again, because only a member's own GitHub account can prove they can reach it.++Adding a repository, turning reviews back on, and the digest toggle need the `editor` level on the `stamphog` resource.+Turning reviews off, removing a repository, and changing the review mode or trigger label need `manager`.+So an editor can turn reviews back on for a repository a manager paused.## Customize the review for your repositorydiff --git a/products/stamphog/backend/activity_logging.py b/products/stamphog/backend/activity_logging.pyindex 3aff05264f18..4ae8fb456bc5 100644--- a/products/stamphog/backend/activity_logging.py+++ b/products/stamphog/backend/activity_logging.py@@ -6,9 +6,7 @@ written from web requests, webhook Celery tasks, and management commands alike.connection's commit, and it must be dropped when that connection rolls back."""-from collections.abc import Callable, Iterator-from contextlib import contextmanager-from contextvars import ContextVar+from collections.abc import Callablefrom typing import TYPE_CHECKING, Anyfrom uuid import UUID@@ -42,27 +40,6 @@ logger = structlog.get_logger(__name__)# before the update, so the logged change list carries the real previous values.DISABLED_FIELDS = ("enabled", "digest_enabled")-# Set while a caller creates repo configs in bulk and logs them itself. Per task, not per process,-# so one request cannot silence another's audit rows.-_created_activity_suppressed: ContextVar[bool] = ContextVar("stamphog_created_activity_suppressed", default=False)---@contextmanager-def suppress_created_activity() -> Iterator[None]:- """Stop the receiver writing one row per create inside this block.-- The installation sync creates a row per repository, and one installation can expose thousands of- them. Each receiver call is a Team lookup, an insert and an internal event, in the request. The- caller logs the batch itself instead. Updates still log per row: an adoption is rare and its diff- is what a reader wants. A ContextVar, not `mute_selected_signals()`, because that flag is- process-wide and would silence every other request the process serves at that moment.- """- token = _created_activity_suppressed.set(True)- try:- yield- finally:- _created_activity_suppressed.reset(token)-def _organization_id_for_team(team_id: int) -> UUID | None:# A repo config has no `team` accessor: team_id is a plain integer, and Team lives on the@@ -116,10 +93,6 @@ def handle_stamphog_repo_config_change(if instance is None:return- if activity == "created" and _created_activity_suppressed.get():- # The caller writes these rows in one batch. See suppress_created_activity.- return-# The receiver runs inside save(). An error here must not escape: the caller's post-save work# (superseding in-flight runs on a disable) would be skipped for a row that is already written.try:@@ -237,51 +210,6 @@ def installation_webhook_trigger(*, delivery_id: str, action: str, installation_)-def log_repo_configs_created(- team_id: int,- rows: list[dict[str, Any]],- *,- user: "User | None" = None,- was_impersonated: bool = False,- trigger: Trigger | None = None,-) -> None:- """Log the repo configs one pass connected, in a single batch.-- Pairs with `suppress_created_activity`: the caller silences the per-row receiver and calls this- once. `notify=False` drops the internal-event fan-out, because one event per connected repo- would put thousands of messages on the topic for a single click. The rows themselves still- reach the activity feed. A webhook caller passes `user=None` and a `trigger` naming the- delivery, so the batch reads as a system row a reader can trace back to one GitHub event.- """- if not rows:- return-- write_db = router.db_for_write(StamphogRepoConfig)-- def _write_rows() -> None:- organization_id = _organization_id_for_team(team_id)- bulk_log_activity(- [- LogActivityEntry(- organization_id=organization_id,- team_id=team_id,- user=user,- item_id=row["id"],- scope="StamphogRepoConfig",- activity="created",- # The sync binds the installation as it creates the row, so it is connected.- detail=Detail(name=row["repository"], type="connected", trigger=trigger),- was_impersonated=was_impersonated,- )- for row in rows- ],- using=write_db,- notify=False,- )-- _log_after_product_commit(_write_rows, write_db=write_db, team_id=team_id)--def log_repo_configs_disabled_by_webhook(team_id: int,before_rows: list[dict[str, Any]],diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.pyindex bbf1d64d9eee..b5a8f7d0511b 100644--- a/products/stamphog/backend/facade/api.py+++ b/products/stamphog/backend/facade/api.py@@ -19,10 +19,11 @@ from django.utils import timezoneimport structlog+from ..logic.installations import reset_unverified_review_policyfrom ..logic.review_trigger import derive_review_triggerfrom ..logic.reviewer import parse_reviewer_outputfrom ..logic.scrubbing import neutralize_active_markdown, scrub_credentials-from ..models import DigestRun, PullRequest, ReviewRun, StamphogRepoConfig+from ..models import DigestRun, PullRequest, ReviewRun, StamphogInstallation, StamphogRepoConfigfrom . import contractsfrom .enums import (TERMINAL_STATUSES,@@ -375,6 +376,114 @@ def create_repo_config(return _repo_config_to_dto(obj)+def list_available_repositories(team_id: int, *, search: str = "", limit: int) -> contracts.AvailableRepositoriesDTO:+ """Repositories in the team's installation snapshots that the team has not added yet.++ A repository another team holds under the same installation is left out too, because the+ cross-team unique constraint would refuse it. ``search`` is a case-insensitive substring.+ """+ # A record without a connecting user cannot mint review credentials, so add_repository refuses it.+ snapshots = list(+ StamphogInstallation.objects.for_team(team_id)+ .filter(provider="github", connected_by_user_id__isnull=False)+ .values_list("installation_id", "repositories")+ )+ if not snapshots:+ return contracts.AvailableRepositoriesDTO(repositories=[], total_count=0, has_installation=False)++ added = set(StamphogRepoConfig.objects.for_team(team_id).values_list("repository", flat=True))+ candidates = {+ (installation_id, repository)+ for installation_id, repositories in snapshots+ for repository in repositories+ if repository not in added+ }+ # The one cross-team read here: which of these repositories another team already owns. It+ # returns only names this team's own snapshots hold, so nothing about the other team leaks.+ claimed = set(+ StamphogRepoConfig.objects.unscoped()+ .filter(+ provider="github",+ installation_id__in={installation_id for installation_id, _ in candidates},+ repository__in={repository for _, repository in candidates},+ )+ .exclude(team_id=team_id)+ .values_list("installation_id", "repository")+ )+ addable = {repository for _, repository in candidates - claimed}+ needle = search.strip().lower()+ available = sorted((repository for repository in addable if needle in repository.lower()), key=str.lower)+ return contracts.AvailableRepositoriesDTO(+ repositories=available[:limit], total_count=len(available), has_installation=True+ )+++def add_repository(team_id: int, repository: str) -> contracts.AddRepositoryResultDTO:+ """Turn reviews on for a repository from the team's installation snapshot.++ The installation and the connecting user come from the snapshot record, never from the caller:+ the record is what a member's GitHub token proved. A row the team already has for the+ repository is turned on and bound to that installation rather than refused, so a paused or+ removed repository can be added again.+ """+ write_db = router.db_for_write(StamphogRepoConfig)+ try:+ with transaction.atomic(using=write_db):+ # Writer pin: this read decides which installation the row binds to. The lock is the one a+ # removal or uninstall webhook takes first. Without it, a webhook can drop the repository+ # and tombstone the team's rows between this read and the create below, and the new row+ # then stays enabled for a repository that left the installation. A record without a+ # connecting user cannot mint review credentials, so a member has to sync it first.+ installation = (+ StamphogInstallation.objects.for_team(team_id)+ .using(write_db)+ .select_for_update()+ .filter(provider="github", repositories__contains=[repository], connected_by_user_id__isnull=False)+ .order_by("-updated_at")+ .first()+ )+ if installation is None:+ raise contracts.RepositoryNotInstalledError(repository)+ existing = (+ StamphogRepoConfig.objects.for_team(team_id)+ .using(write_db)+ .select_for_update()+ .filter(repository=repository)+ .first()+ )+ if existing is None:+ config = (+ StamphogRepoConfig.objects.for_team(team_id)+ .using(write_db)+ .create(+ # for_team() scopes a read but not row creation, so team_id is explicit here.+ team_id=team_id,+ provider="github",+ repository=repository,+ installation_id=installation.installation_id,+ enabled=True,+ connected_by_user_id=installation.connected_by_user_id,+ )+ )+ return contracts.AddRepositoryResultDTO(config=_repo_config_to_dto(config), created=True)++ update_fields = ["enabled", "updated_at"]+ if existing.installation_id != installation.installation_id:+ # A reinstall row keeps its settings, because a verified binding configured them.+ if not existing.installation_id:+ update_fields += reset_unverified_review_policy(existing)+ existing.installation_id = installation.installation_id+ update_fields.append("installation_id")+ existing.connected_by_user_id = installation.connected_by_user_id+ update_fields.append("connected_by_user_id")+ existing.enabled = True+ existing.save(update_fields=update_fields)+ return contracts.AddRepositoryResultDTO(config=_repo_config_to_dto(existing), created=False)+ except IntegrityError:+ # unique_stamphog_installation_repo: another team holds this repository under the installation.+ raise contracts.RepoAlreadyClaimedError(repository)++def update_repo_config(team_id: int, config_id: str, **fields: object) -> contracts.RepoConfigDTO:"""Apply an update, superseding in-flight runs when the repo goes from enabled to disabled.diff --git a/products/stamphog/backend/facade/contracts.py b/products/stamphog/backend/facade/contracts.pyindex a36b14bedc6e..c0c04ec62acd 100644--- a/products/stamphog/backend/facade/contracts.py+++ b/products/stamphog/backend/facade/contracts.py@@ -43,6 +43,26 @@ class RepoConfigDTO:updated_at: datetime | None = None+@dataclass(frozen=True)+class AvailableRepositoriesDTO:+ """Repositories a team can add from its connected installations, one page of them."""++ repositories: list[str]+ # Every addable repository that matches the search, not only the ones on this page.+ total_count: int+ # False means nobody on the team connected GitHub yet, so nothing can be added.+ has_installation: bool+++@dataclass(frozen=True)+class AddRepositoryResultDTO:+ """The repo config an add turned on, and whether the add created it."""++ config: RepoConfigDTO+ # False when the team already had a row for the repository and the add turned it on.+ created: bool++@dataclass(frozen=True)class PullRequestDTO:"""A pull request stamphog knows about, including merge state once it merges."""@@ -155,6 +175,10 @@ class RepoAlreadyClaimedError(Exception):"""Another team already owns this repository under this GitHub installation."""+class RepositoryNotInstalledError(Exception):+ """The repository is in none of the team's installation snapshots, so it cannot be added."""++class StamphogGitHubError(Exception):"""A Stamphog GitHub API call failed for a non-rate-limit reason (auth failure, unexpected status,malformed response). Rate limits raise ``GitHubRateLimitError`` from the egress layer instead."""diff --git a/products/stamphog/backend/facade/github.py b/products/stamphog/backend/facade/github.pyindex 3ba0ef07d2bf..30347bae1ab2 100644--- a/products/stamphog/backend/facade/github.py+++ b/products/stamphog/backend/facade/github.py@@ -18,11 +18,7 @@ from django.utils import timezonefrom posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonatedfrom posthog.models.scoping.manager import resolve_effective_team_id-from products.stamphog.backend.activity_logging import (- log_repo_config_bulk_update,- log_repo_configs_created,- suppress_created_activity,-)+from products.stamphog.backend.activity_logging import log_repo_config_bulk_updatefrom products.stamphog.backend.facade import contractsfrom products.stamphog.backend.facade.api import _repo_config_to_dtofrom products.stamphog.backend.facade.contracts import StamphogGitHubError@@ -32,6 +28,7 @@ from products.stamphog.backend.logic.github_client import (list_user_installations,user_can_access_installation,)+from products.stamphog.backend.logic.installations import record_installation_sync, reset_unverified_review_policyfrom products.stamphog.backend.models import StamphogRepoConfig__all__ = [@@ -43,18 +40,13 @@ __all__ = ["user_can_access_installation",]-# How many repo-config rows go into one INSERT. An installation can expose thousands of-# repositories, and every row in a statement adds its columns to that statement's bind-parameter-# list, so the batch is chunked to stay clear of Postgres' per-statement parameter ceiling.-_CREATE_BATCH_SIZE = 500-def _adopt_preexisting_config(team_id: int, repository: str, installation_id: str) -> StamphogRepoConfig | None:"""Bind a manually-created (installation-less) config to a now-verified installation.- Reached when the installation sync hits the unique (team, repository) constraint: a row for this- repo already exists on the team, created through the plain API/MCP path with a blank installation_id- — or bound to a PREVIOUS installation after an uninstall/reinstall cycle (each reinstall mints a new+ Reached when the installation sync lists a repository the team already has a row for under+ another installation_id: a row created through the plain API/MCP path with a blank installation_id+ — or one bound to a PREVIOUS installation after an uninstall/reinstall cycle (each reinstall mints a newinstallation id, and the app can only be installed once per repo, so the old binding is dead).Stamp the verified installation onto it so it starts resolving webhooks again, rather than reportingit skipped and leaving it unbound forever. Safe to rebind: this helper is team-scoped and only@@ -83,10 +75,7 @@ def _adopt_preexisting_config(team_id: int, repository: str, installation_id: stif not existing.installation_id:existing.enabled = Falseexisting.digest_enabled = False- # Read the defaults off the model so the reset cannot drift from what a fresh row gets.- existing.review_mode = StamphogRepoConfig._meta.get_field("review_mode").get_default()- existing.trigger_label = StamphogRepoConfig._meta.get_field("trigger_label").get_default()- update_fields += ["enabled", "digest_enabled", "review_mode", "trigger_label"]+ update_fields += ["enabled", "digest_enabled", *reset_unverified_review_policy(existing)]existing.installation_id = installation_idtry:existing.save(update_fields=update_fields)@@ -102,118 +91,62 @@ def sync_installation_repositories(user_token: str,connected_by_user_id: int,) -> tuple[list[contracts.RepoConfigDTO], list[str]]:- """Bind every user-accessible repo in one installation to the team. Returns (synced, skipped).+ """Record the repos this user can reach in one installation. Returns (synced, skipped).- Enumerate with the USER token, not the app installation token: bind only the repos this user can- actually reach in the installation, so proving access to one repo can't attach repos they can't+ Enumerate with the USER token, not the app installation token: record only the repos this user can+ actually reach in the installation, so proving access to one repo can't expose repos they can'tsee. The app-token list would return every repo the installer selected regardless of this user.Raises :class:`StamphogGitHubError` on an enumeration failure so the caller fails closed.+ The listed repos go into the team's installation snapshot, and no repo config is created: a member+ adds the ones to review from the snapshot. `synced` is the team's existing rows for listed repos,+ bound to this installation. `skipped` is the listed repos another team holds under it.+Every synced row records the caller as its connecting user — the identity the review sandbox'sshort-lived gateway token is minted under. Re-syncs re-stamp on purpose: the latest human toprove installation ownership is the right principal (the original installer may be long gone)."""repositories = list_user_accessible_repositories(installation_id, user_token)- # bulk_create below skips ProductTeamModel.save(), which is what normally rewrites team_id to the- # canonical id, so resolve it here instead and pass canonical=True from then on. for_team()- # resolves per call, so this also holds the whole sync to one Team lookup.+ # for_team() resolves the canonical team per call, so resolve it once here and pass canonical=True+ # from then on.team_id = resolve_effective_team_id(team_id)# Pin the reads and the writes to the model's routed DB (stamphog_db_writer when the product DB- # is configured, else default). A lagged reader would miss a row this sync just wrote and try to- # create it again.+ # is configured, else default). A lagged reader would miss a row a concurrent sync just bound.write_db = router.db_for_write(StamphogRepoConfig)+ record_installation_sync(team_id, installation_id, repositories, connected_by_user_id=connected_by_user_id)+# One read for the whole installation rather than one per repository. An organization that# installs the App on all of its repositories can expose thousands of them, and a per-repository# round trip made the request cost grow with that count until it ran past the gateway timeout.- # A re-sync now finds every row here and does no write work at all.- resolved: dict[str, StamphogRepoConfig] = {- config.repository: config- for config in StamphogRepoConfig.objects.for_team(team_id, canonical=True)+ team_rows = (+ StamphogRepoConfig.objects.for_team(team_id, canonical=True)+ .using(write_db)+ .filter(provider="github", repository__in=repositories)+ )+ resolved: dict[str, StamphogRepoConfig] = {}+ skipped: set[str] = set(+ StamphogRepoConfig.objects.unscoped().using(write_db).filter(provider="github", installation_id=installation_id, repository__in=repositories)- }-- created_rows: list[dict[str, Any]] = []- skipped: list[str] = []- # Create the rows without a per-row audit write and log the creates in one batch below; an- # adoption still logs its own diff. The batch runs in a finally: a row that is already committed- # when the work dies would otherwise never be logged, and a retry sees it as pre-existing, so its- # creation is lost for good.- try:- with suppress_created_activity():- candidates = [- StamphogRepoConfig(- # for_team() scopes a read but not row creation, so team_id is explicit here.- team_id=team_id,- provider="github",- installation_id=installation_id,- repository=full_name,- # Bind disabled: an installation can surface hundreds of repos, so connect them- # but don't start reviewing until a human toggles each one on.- enabled=False,- # The connecting user is seeded here, so a new row does not need the restamp- # below and its activity log shows one "connected" entry instead of a create- # plus a connector change.- connected_by_user_id=connected_by_user_id,- )- for full_name in repositories- if full_name not in resolved- ]- if candidates:- # The rows and the record of which ones this call inserted have to commit together.- # An unwrapped bulk_create commits on its own, so a failure of the read-back would- # leave the rows in place with created_rows empty, and the retry would then see them- # as pre-existing and never write their audit entries.- with transaction.atomic(using=write_db):- # ON CONFLICT DO NOTHING, so both unique constraints still decide which rows land- # and a concurrent sync of the same installation cannot make this raise.- # bulk_create also sends no per-row save signal, which is the audit outcome the- # suppression above gives the rest of this block.- StamphogRepoConfig.objects.for_team(team_id, canonical=True).using(write_db).bulk_create(- candidates, ignore_conflicts=True, batch_size=_CREATE_BATCH_SIZE- )- # The primary keys are generated in Python, so reading them back says exactly- # which candidates this call inserted. ignore_conflicts reports nothing itself,- # and a row that lost to a conflict needs the per-row resolution below.- inserted_ids = set(- StamphogRepoConfig.objects.for_team(team_id, canonical=True)- .using(write_db)- .filter(id__in=[candidate.id for candidate in candidates])- .values_list("id", flat=True)- )- # Recorded before the resolution below, so a failure in it still logs every row that- # landed.- created_rows.extend(- {"id": candidate.id, "repository": candidate.repository}- for candidate in candidates- if candidate.id in inserted_ids- )- for candidate in candidates:- if candidate.id in inserted_ids:- resolved[candidate.repository] = candidate- continue- # A unique constraint holds this repository. Either the same team already has it- # under a different installation_id, which is the manually-created config (blank- # installation) finally being bound, so adopt it; or another team owns the triple,- # which stays skipped.- adopted = _adopt_preexisting_config(team_id, candidate.repository, installation_id)- if adopted is None:- skipped.append(candidate.repository)- else:- resolved[candidate.repository] = adopted- finally:- log_repo_configs_created(- team_id, created_rows, user=get_current_user(), was_impersonated=get_was_impersonated()- )+ .exclude(team_id=team_id)+ .values_list("repository", flat=True)+ )+ for config in team_rows:+ if config.installation_id == installation_id:+ resolved[config.repository] = config+ continue+ # A manual placeholder or a row from a previous installation. Adopting it binds the row to the+ # verified installation, and a conflict means another team owns the triple, so it stays skipped.+ adopted = _adopt_preexisting_config(team_id, config.repository, installation_id)+ if adopted is None:+ skipped.add(config.repository)+ else:+ resolved[config.repository] = adopted# Answer in the order GitHub listed the repositories, which is the order the connect screen renders.synced = [resolved[full_name] for full_name in repositories if full_name in resolved]- # A row this call inserted already carries the caller as its connector, so only a pre-existing row- # can need a restamp. Leaving the new ones out also keeps a first-time sync of a large installation- # from locking every row it just created.- created_ids = {row["id"] for row in created_rows}- restamp_ids = [config.id for config in synced if config.id not in created_ids]+ restamp_ids = [config.id for config in synced]if restamp_ids:with transaction.atomic(using=write_db):@@ -246,4 +179,4 @@ def sync_installation_repositories(was_impersonated=get_was_impersonated(),)- return [_repo_config_to_dto(c) for c in synced], skipped+ return [_repo_config_to_dto(c) for c in synced], [full_name for full_name in repositories if full_name in skipped]diff --git a/products/stamphog/backend/logic/installations.py b/products/stamphog/backend/logic/installations.pynew file mode 100644index 000000000000..f002e06f1cf5--- /dev/null+++ b/products/stamphog/backend/logic/installations.py@@ -0,0 +1,78 @@+"""Installation snapshots, the repositories a team can add to stamphog, and binding rows to them.++A snapshot holds only repositories a member proved access to with their own GitHub token. Every+write locks the installation row, because a sync and a webhook for the same installation can run at+once and each one rewrites the whole list.+"""++from __future__ import annotations++from collections.abc import Iterable++from django.db import router, transaction++from ..models import StamphogInstallation, StamphogRepoConfig+++def reset_unverified_review_policy(config: StamphogRepoConfig) -> list[str]:+ """Put a placeholder's review policy back at the model defaults. Returns the fields it changed.++ A placeholder (blank installation) was configured by someone who never proved GitHub access.+ A label mode with a label nobody uses would otherwise go live, reviewing nothing, the moment+ the row binds to a real installation and turns on.+ """+ # Read the defaults off the model so the reset cannot drift from what a fresh row gets.+ config.review_mode = StamphogRepoConfig._meta.get_field("review_mode").get_default()+ config.trigger_label = StamphogRepoConfig._meta.get_field("trigger_label").get_default()+ return ["review_mode", "trigger_label"]+++def _write_db() -> str:+ return router.db_for_write(StamphogInstallation)+++def record_installation_sync(+ team_id: int, installation_id: str, repositories: Iterable[str], *, connected_by_user_id: int+) -> None:+ """Merge a member's listed repositories into the team's snapshot, and make them its connector.++ The merge is a union, so a sync by a member who sees fewer repositories does not hide the ones+ a teammate listed. Repositories leave the snapshot only through the removal webhooks.+ """+ write_db = _write_db()+ with transaction.atomic(using=write_db):+ installation, _ = (+ StamphogInstallation.objects.for_team(team_id)+ .using(write_db)+ .select_for_update()+ # for_team() scopes a read but not row creation, so team_id is explicit here.+ .get_or_create(team_id=team_id, provider="github", installation_id=installation_id)+ )+ installation.repositories = sorted(set(installation.repositories) | set(repositories))+ installation.connected_by_user_id = connected_by_user_id+ installation.save(update_fields=["repositories", "connected_by_user_id", "updated_at"])+++def remove_from_installation_snapshot(team_id: int, installation_id: str, repositories: Iterable[str]) -> None:+ removed = set(repositories)+ if not removed:+ return+ write_db = _write_db()+ with transaction.atomic(using=write_db):+ installation = (+ StamphogInstallation.objects.for_team(team_id)+ .using(write_db)+ .select_for_update()+ .filter(provider="github", installation_id=installation_id)+ .first()+ )+ if installation is None:+ return+ installation.repositories = sorted(set(installation.repositories) - removed)+ installation.save(update_fields=["repositories", "updated_at"])+++def delete_installation(team_id: int, installation_id: str) -> None:+ StamphogInstallation.objects.for_team(team_id).using(_write_db()).filter(+ provider="github", installation_id=installation_id+ ).delete()diff --git a/products/stamphog/backend/migrations/0007_add_installations.py b/products/stamphog/backend/migrations/0007_add_installations.pynew file mode 100644index 000000000000..8f1a6f6aca2a--- /dev/null+++ b/products/stamphog/backend/migrations/0007_add_installations.py@@ -0,0 +1,55 @@+import django.db.models.manager+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ """Add the team-to-installation link that holds the repositories a team can add."""++ dependencies = [+ ("stamphog", "0006_change_summaries_hold_a_clause_per_team"),+ ]++ operations = [+ migrations.CreateModel(+ name="StamphogInstallation",+ fields=[+ ("team_id", models.BigIntegerField(db_index=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("provider", models.CharField(default="github", max_length=32)),+ ("installation_id", models.CharField(max_length=64)),+ ("repositories", models.JSONField(default=list)),+ ("connected_by_user_id", models.BigIntegerField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ],+ options={+ "abstract": False,+ "default_manager_name": "all_teams",+ "indexes": [+ models.Index(+ fields=["provider", "installation_id"],+ name="stamphog_installation_lookup",+ )+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("team_id", "provider", "installation_id"),+ name="unique_stamphog_installation_per_team",+ )+ ],+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ]diff --git a/products/stamphog/backend/migrations/0008_backfill_installations.py b/products/stamphog/backend/migrations/0008_backfill_installations.pynew file mode 100644index 000000000000..1f434bf7d53a--- /dev/null+++ b/products/stamphog/backend/migrations/0008_backfill_installations.py@@ -0,0 +1,57 @@+from django.db import migrations+++def backfill_installations(apps, schema_editor):+ """Create one installation record per team and bound installation, from the repo configs.++ Every existing row with an installation was created by a sync, so its repository is one a member+ proved access to. The newest non-null connecting user is the member who proved it last.+ """+ alias = schema_editor.connection.alias+ repo_config_model = apps.get_model("stamphog", "StamphogRepoConfig")+ installation_model = apps.get_model("stamphog", "StamphogInstallation")++ repositories: dict[tuple[int, str, str], set[str]] = {}+ connectors: dict[tuple[int, str, str], int] = {}+ rows = (+ repo_config_model._default_manager.using(alias)+ .exclude(installation_id="")+ .order_by("updated_at")+ .values_list("team_id", "provider", "installation_id", "repository", "connected_by_user_id")+ )+ for team_id, provider, installation_id, repository, connected_by_user_id in rows:+ key = (team_id, provider, installation_id)+ repositories.setdefault(key, set()).add(repository)+ if connected_by_user_id is not None:+ # Rows come oldest first, so the last write is the newest connector.+ connectors[key] = connected_by_user_id++ installation_model._default_manager.using(alias).bulk_create(+ [+ installation_model(+ team_id=team_id,+ provider=provider,+ installation_id=installation_id,+ repositories=sorted(names),+ connected_by_user_id=connectors.get((team_id, provider, installation_id)),+ )+ for (team_id, provider, installation_id), names in repositories.items()+ ],+ # A retried migration finds the records it wrote the first time.+ ignore_conflicts=True,+ batch_size=500,+ )+++class Migration(migrations.Migration):+ """Backfill installation records from the repo configs a sync created.++ Separate from 0007 because a data migration in the same file as schema changes is blocked: it+ can hold a lock while those changes wait on it.+ """++ dependencies = [("stamphog", "0007_add_installations")]++ operations = [+ migrations.RunPython(backfill_installations, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/stamphog/backend/migrations/0009_delete_unused_repo_configs.py b/products/stamphog/backend/migrations/0009_delete_unused_repo_configs.pynew file mode 100644index 000000000000..aa8079f22f65--- /dev/null+++ b/products/stamphog/backend/migrations/0009_delete_unused_repo_configs.py@@ -0,0 +1,41 @@+from django.db import migrations+++def delete_unused_repo_configs(apps, schema_editor):+ """Delete the repo configs a sync created and nobody turned on.++ A sync used to create a disabled row for every repository the member could reach. Those rows+ now live in the installation snapshot instead, so the repositories stay available to add. A row+ with a pull request keeps its review history and stays. A placeholder (blank installation) is in+ no snapshot, and a row with a changed review policy holds a choice someone made, so both stay.+ """+ alias = schema_editor.connection.alias+ repo_config_model = apps.get_model("stamphog", "StamphogRepoConfig")+ pull_request_model = apps.get_model("stamphog", "PullRequest")++ used_config_ids = pull_request_model._default_manager.using(alias).values("repo_config_id")+ (+ repo_config_model._default_manager.using(alias)+ .filter(+ enabled=False,+ digest_enabled=False,+ review_mode=repo_config_model._meta.get_field("review_mode").get_default(),+ trigger_label=repo_config_model._meta.get_field("trigger_label").get_default(),+ )+ .exclude(installation_id="")+ .exclude(id__in=used_config_ids)+ .delete()+ )+++class Migration(migrations.Migration):+ """Delete never-used repo configs, after 0008 copied their repositories into the snapshots.++ Separate from 0008 so the delete can be reviewed, or dropped, on its own.+ """++ dependencies = [("stamphog", "0008_backfill_installations")]++ operations = [+ migrations.RunPython(delete_unused_repo_configs, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/stamphog/backend/migrations/max_migration.txt b/products/stamphog/backend/migrations/max_migration.txtindex deba719591e4..2b35efdcb4e9 100644--- a/products/stamphog/backend/migrations/max_migration.txt+++ b/products/stamphog/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_change_summaries_hold_a_clause_per_team+0009_delete_unused_repo_configsdiff --git a/products/stamphog/backend/models.py b/products/stamphog/backend/models.pyindex 868e93ef973c..2c0d2bc8f66f 100644--- a/products/stamphog/backend/models.py+++ b/products/stamphog/backend/models.py@@ -83,6 +83,44 @@ class StamphogRepoConfig(ModelActivityMixin, ProductTeamModel):return self.repository+class StamphogInstallation(ProductTeamModel):+ """One GitHub App installation a team connected, and the repositories a member proved access to.++ `repositories` is a snapshot of what the connecting members could reach with their own GitHub+ token, merged across syncs. It is not the installation's full repository list: an outside+ collaborator on one repository can reach the installation, and the installation token would+ show them every private repository in it. Only a repository in this snapshot can be added to+ the team without a manual placeholder. A removal webhook shrinks it between syncs, and no webhook+ grows it, because a webhook carries no user who proved access.+ """++ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)+ provider = models.CharField(max_length=32, default="github")+ installation_id = models.CharField(max_length=64)+ # Full names in "owner/repo" form, matching StamphogRepoConfig.repository.+ repositories = models.JSONField(default=list)+ # The member who last proved access to this installation (plain id, no FK: multi-DB product).+ # A repository added from the snapshot takes this as its connecting user.+ connected_by_user_id = models.BigIntegerField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ # Inherit the base Meta so default_manager_name="all_teams" survives (see StamphogRepoConfig.Meta).+ class Meta(ProductTeamModel.Meta):+ constraints = [+ models.UniqueConstraint(+ fields=["team_id", "provider", "installation_id"], name="unique_stamphog_installation_per_team"+ ),+ ]+ indexes = [+ # Webhook team resolution reads every team that holds one installation.+ models.Index(fields=["provider", "installation_id"], name="stamphog_installation_lookup"),+ ]++ def __str__(self) -> str:+ return f"{self.provider} installation {self.installation_id}"++class PullRequest(ProductTeamModel):"""One pull request stamphog knows about — the PR-grain context every review run shares.diff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.pyindex 29d25e097513..214778cff820 100644--- a/products/stamphog/backend/presentation/serializers.py+++ b/products/stamphog/backend/presentation/serializers.py@@ -70,7 +70,8 @@ class StamphogRepoConfigSerializer(DataclassSerializer):read_only=True,help_text=("The caller's access level on the stamphog resource, resolved for the team that owns this "- "row. 'manager' is required to change enabled, review_mode, or trigger_label."+ "row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change "+ "review_mode or trigger_label."),)@@ -227,18 +228,28 @@ class StamphogDiscoveredInstallationSerializer(serializers.Serializer):class StamphogSyncInstallationResponseSerializer(serializers.Serializer):- """Result of syncing an installation: rows created/kept for this team, plus conflicting repos skipped."""+ """Result of syncing an installation: the team's rows bound to it, and what the team can add now."""synced = StamphogRepoConfigSerializer(many=True,read_only=True,- help_text="Repo configs now bound to this team for the installation (created this call or already present).",+ help_text=(+ "Repo configs this team already had for the installation's repositories, now bound to it. "+ "A sync creates no repo config: use add_repository to turn reviews on for a repository."+ ),)skipped = serializers.ListField(child=serializers.CharField(),read_only=True,help_text="Repository full names skipped because another team already owns them under this installation.",)+ available_count = serializers.IntegerField(+ read_only=True,+ help_text=(+ "How many repositories this team can add after the sync, across all its connected installations. "+ "List them with available_repositories."+ ),+ )app_not_installed = serializers.BooleanField(read_only=True,help_text=(@@ -259,6 +270,62 @@ class StamphogSyncInstallationResponseSerializer(serializers.Serializer):)+class StamphogAvailableRepositoriesQuerySerializer(serializers.Serializer):+ """Query parameters for listing the repositories a team can add."""++ search = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="Case-insensitive substring to match against the repository full name, e.g. 'posthog'.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=50,+ min_value=1,+ max_value=200,+ help_text="Maximum number of repositories to return. Defaults to 50, at most 200.",+ )+++class StamphogAvailableRepositoriesSerializer(serializers.Serializer):+ """Repositories from the team's connected GitHub installations that are not added to stamphog yet."""++ repositories = serializers.ListField(+ child=serializers.CharField(),+ read_only=True,+ help_text=(+ "Repository full names the team can add, sorted by name and capped by limit. Only repositories "+ "a project member proved access to on GitHub are listed, and never one another project already "+ "holds under the same installation."+ ),+ )+ total_count = serializers.IntegerField(+ read_only=True,+ help_text="How many repositories match the search in total, before limit applies.",+ )+ has_installation = serializers.BooleanField(+ read_only=True,+ help_text=(+ "Whether a project member connected a GitHub installation yet. False means GitHub must be "+ "connected before any repository can be added. True with a total_count of 0 and no search "+ "means no repository is left to add."+ ),+ )+++class StamphogAddRepositorySerializer(serializers.Serializer):+ """Request body for turning reviews on for a repository from a connected installation."""++ repository = serializers.CharField(+ help_text=(+ "Repository full name, e.g. 'PostHog/posthog'. It must be in one of the project's connected "+ "GitHub installations, as available_repositories lists them. A repository the project already "+ "has is turned back on."+ ),+ )++@extend_schema_serializer(component_name="StamphogPullRequest")class PullRequestSerializer(DataclassSerializer):repository = serializers.CharField(diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.pyindex 1c370d53b887..447e490c7be0 100644--- a/products/stamphog/backend/presentation/views.py+++ b/products/stamphog/backend/presentation/views.py@@ -6,7 +6,7 @@ return serialized responses. No business logic here."""from functools import cached_property-from typing import Any, cast+from typing import Any, Literal, castfrom urllib.parse import quotefrom django.conf import settings@@ -53,6 +53,9 @@ from .serializers import (ReviewRequestResponseSerializer,ReviewRequestSerializer,ReviewRunSerializer,+ StamphogAddRepositorySerializer,+ StamphogAvailableRepositoriesQuerySerializer,+ StamphogAvailableRepositoriesSerializer,StamphogInstallInfoSerializer,StamphogRepoConfigSerializer,StamphogRepoConfigWriteSerializer,@@ -69,8 +72,25 @@ logger = structlog.get_logger(__name__)_INSTALL_STATE_SALT = "stamphog-install-state"_INSTALL_STATE_MAX_AGE_SECONDS = 60 * 60-# These decide whether a pull request gets reviewed, so writing any of them takes the manager level.-REVIEW_GATE_FIELDS = ("enabled", "review_mode", "trigger_label")+# These decide when a pull request gets reviewed, so writing either of them takes the manager level.+# `enabled` is split by direction: turning reviews on takes editor, turning them off takes manager.+REVIEW_POLICY_FIELDS = ("review_mode", "trigger_label")++ReviewLevel = Literal["editor", "manager"]+++def _required_review_level(validated_data: dict[str, Any]) -> ReviewLevel | None:+ """The stamphog level a write needs because of the review fields it names, or None for none.++ A supplied value counts even when it matches the stored one: the view reads the row before the+ facade refetches and saves it, so a value that looks unchanged can still overwrite a manager's+ decision made in between. That is why a supplied `enabled=False` always takes manager.+ """+ if validated_data.get("enabled") is False or any(field in validated_data for field in REVIEW_POLICY_FIELDS):+ return "manager"+ if validated_data.get("enabled") is True:+ return "editor"+ return Noneclass StamphogCanonicalTeamAccessPermission(BasePermission):@@ -196,22 +216,29 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewraise NotFound()return config- def _require_review_gate_manager(self, request: Request) -> None:- """Refuse a review-gating write below the manager level on the stamphog resource.+ def _require_review_level(self, request: Request, level: ReviewLevel | None) -> None:+ """Refuse a review-gating write below `level` on the stamphog resource.Service credentials (project secret keys, team secret tokens) are synthetic users the RBAC- layer cannot resolve, and a key is never a manager, so they are refused here rather than- silently passed through by AccessControlPermission's service-auth shortcut.+ layer cannot resolve, so they are refused here rather than silently passed through by+ AccessControlPermission's service-auth shortcut. A review decision needs a person."""- if not is_service_auth(request) and self.user_access_control.check_access_level_for_resource(- "stamphog", "manager"- ):+ if level is None:+ return+ if not is_service_auth(request) and self.user_access_control.check_access_level_for_resource("stamphog", level):return+ if level == "manager":+ raise PermissionDenied(+ "Only a Stamphog manager can turn reviews off or change when they run. "+ "Ask an organization admin for manager access."+ )raise PermissionDenied(- "Only a Stamphog manager can change whether this repository is reviewed. "- "Ask an organization admin for manager access."+ "Only a Stamphog editor can turn reviews on. Ask an organization admin for editor access.")+ def _available_count(self) -> int:+ return facade_api.list_available_repositories(self.canonical_team_id, limit=0).total_count+def list(self, request: Request, **kwargs) -> Response:configs = facade_api.list_repo_configs(self.canonical_team_id)page = self.paginate_queryset(configs)@@ -222,15 +249,14 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView@extend_schema(request=StamphogRepoConfigWriteSerializer, responses={201: StamphogRepoConfigSerializer})def create(self, request: Request, **kwargs) -> Response:- # Naming a gate field takes manager here for the same reason it does on update: a caller- # spelling out a review policy is making the review decision, whichever verb carries it.- # Leaving them out stays at editor. The row is created without an installation, which binds- # it disabled at sync time and keeps it out of the digest candidates, so the defaults reach- # nothing on their own.+ # Naming a review field takes the same level here as it does on update: a caller spelling out+ # a review policy is making the review decision, whichever verb carries it. Leaving them out+ # stays at editor. The row is created without an installation, which binds it disabled at+ # sync time and keeps it out of the digest candidates, so the defaults reach nothing on their+ # own. add_repository is the path that binds a repository from a connected installation.serializer = StamphogRepoConfigWriteSerializer(data=request.data, context=self.get_serializer_context())serializer.is_valid(raise_exception=True)- if any(field in serializer.validated_data for field in REVIEW_GATE_FIELDS):- self._require_review_gate_manager(request)+ self._require_review_level(request, _required_review_level(serializer.validated_data))try:config = facade_api.create_repo_config(self.canonical_team_id, **serializer.validated_data)except contracts.RepoAlreadyClaimedError:@@ -250,11 +276,7 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewcontext=self.get_serializer_context(),)serializer.is_valid(raise_exception=True)- # A supplied gate field always takes manager, even when it matches what `current` holds:- # that snapshot was read before the facade refetches and saves, so a value that looks- # unchanged can still overwrite a manager's decision made in between.- if any(field in serializer.validated_data for field in REVIEW_GATE_FIELDS):- self._require_review_gate_manager(request)+ self._require_review_level(request, _required_review_level(serializer.validated_data))config = facade_api.update_repo_config(self.canonical_team_id, str(pk), **serializer.validated_data)return Response(self.get_serializer(config).data)@@ -264,11 +286,60 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewdef destroy(self, request: Request, pk: str | None = None, **kwargs) -> Response:self._get_or_404(pk)- # A soft delete flips `enabled`, so it is a review-gating write like the PATCH above.- self._require_review_gate_manager(request)+ # A soft delete turns reviews off, so it takes manager like a PATCH to enabled=False.+ self._require_review_level(request, "manager")facade_api.disable_repo_config(self.canonical_team_id, str(pk))return Response(status=204)+ @extend_schema(+ description=(+ "List repositories from the project's connected GitHub installations that are not added to "+ "stamphog yet, so they can be added with add_repository."+ ),+ parameters=[StamphogAvailableRepositoriesQuerySerializer],+ responses={200: StamphogAvailableRepositoriesSerializer},+ )+ @action(detail=False, methods=["GET"], url_path="available_repositories", required_scopes=["stamphog:read"])+ def available_repositories(self, request: Request, **kwargs) -> Response:+ # Reads the snapshots a sync stored and makes no GitHub call, so the page can load it on every visit.+ query = StamphogAvailableRepositoriesQuerySerializer(data=request.query_params)+ query.is_valid(raise_exception=True)+ available = facade_api.list_available_repositories(+ self.canonical_team_id, search=query.validated_data["search"], limit=query.validated_data["limit"]+ )+ return Response(StamphogAvailableRepositoriesSerializer(available).data)++ @extend_schema(+ description=(+ "Turn reviews on for a repository from the project's connected GitHub installations. Creates "+ "the repo config, or turns an existing one back on. Needs the editor level on stamphog."+ ),+ request=StamphogAddRepositorySerializer,+ responses={200: StamphogRepoConfigSerializer, 201: StamphogRepoConfigSerializer},+ )+ @action(detail=False, methods=["POST"], url_path="add_repository", required_scopes=["stamphog:write"])+ def add_repository(self, request: Request, **kwargs) -> Response:+ # Turning reviews on takes editor. The installation and the connecting user come from the+ # team's snapshot, never from the request, so an editor can only bind what a member proved.+ serializer = StamphogAddRepositorySerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ self._require_review_level(request, "editor")+ repository = serializer.validated_data["repository"]+ try:+ result = facade_api.add_repository(self.canonical_team_id, repository)+ except contracts.RepositoryNotInstalledError:+ raise ValidationError(+ {+ "repository": "This repository is not in a connected GitHub installation. "+ "Connect GitHub or refresh the repository list, then try again."+ }+ )+ except contracts.RepoAlreadyClaimedError:+ raise ValidationError(+ {"repository": "This repository is already configured under this GitHub installation by another team."}+ )+ return Response(self.get_serializer(result.config).data, status=201 if result.created else 200)+@extend_schema(responses={200: StamphogInstallInfoSerializer})@action(detail=False, methods=["GET"], url_path="install_info", required_scopes=["stamphog:read"])def install_info(self, request: Request, **kwargs) -> Response:@@ -396,7 +467,13 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView# The App isn't installed anywhere the user can see. Not an error: the frontend routes them# to the GitHub install page (install_url) off app_not_installed.data = StamphogSyncInstallationResponseSerializer(- {"synced": [], "skipped": [], "app_not_installed": True, "installations": []},+ {+ "synced": [],+ "skipped": [],+ "available_count": self._available_count(),+ "app_not_installed": True,+ "installations": [],+ },context=self.get_serializer_context(),).datareturn Response(data)@@ -407,7 +484,13 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView# connect. Bind nothing; the frontend re-runs the flow with an explicit installation_id# (which the explicit path above verifies).data = StamphogSyncInstallationResponseSerializer(- {"synced": [], "skipped": [], "app_not_installed": False, "installations": discovered},+ {+ "synced": [],+ "skipped": [],+ "available_count": self._available_count(),+ "app_not_installed": False,+ "installations": discovered,+ },context=self.get_serializer_context(),).datareturn Response(data)@@ -436,7 +519,13 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView# The nested repo config serializer reads user_access_level off the view, and DRF hands the# root's context down to it. Without the context every synced row reports a null level.data = StamphogSyncInstallationResponseSerializer(- {"synced": synced, "skipped": skipped, "app_not_installed": False, "installations": []},+ {+ "synced": synced,+ "skipped": skipped,+ "available_count": self._available_count(),+ "app_not_installed": False,+ "installations": [],+ },context=self.get_serializer_context(),).datareturn Response(data)diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.pyindex ae1c06cc275d..78c90debdb61 100644--- a/products/stamphog/backend/tasks/tasks.py+++ b/products/stamphog/backend/tasks/tasks.py@@ -24,13 +24,7 @@ from posthog.dataclasses import frozenfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.instance_setting import get_instance_setting-from products.stamphog.backend.activity_logging import (- DISABLED_FIELDS,- installation_webhook_trigger,- log_repo_configs_created,- log_repo_configs_disabled_by_webhook,- suppress_created_activity,-)+from products.stamphog.backend.activity_logging import DISABLED_FIELDS, log_repo_configs_disabled_by_webhookfrom products.stamphog.backend.facade.contracts import ReviewRequestRefusedError, StamphogGitHubErrorfrom products.stamphog.backend.facade.enums import (TERMINAL_STATUSES,@@ -50,8 +44,15 @@ from products.stamphog.backend.logic.approval_retention import (from products.stamphog.backend.logic.approvals import dismiss_stale_approvals_for_headfrom products.stamphog.backend.logic.audiences import ResolvedAudience, resolve_audiencesfrom products.stamphog.backend.logic.github_client import StamphogGitHubClient+from products.stamphog.backend.logic.installations import delete_installation, remove_from_installation_snapshotfrom products.stamphog.backend.logic.review_trigger import derive_review_trigger-from products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfig+from products.stamphog.backend.models import (+ PullRequest,+ PullRequestAudience,+ ReviewRun,+ StamphogInstallation,+ StamphogRepoConfig,+)from products.stamphog.backend.temporal.client import execute_stamphog_review_workflowfrom products.tasks.backend.facade.api import find_signal_implementation_run@@ -841,91 +842,32 @@ def _record_merged_pull_request(payload: dict[str, Any], delivery_id: str) -> Nodef _resolve_installation_team_ids(installation_id: str) -> list[int]:- """Every distinct team carrying this installation.+ """Every distinct team carrying this installation, through its installation record or a bound row.An installation's repos can legitimately be split across teams — each team syncs only the repos itsmembers can access — so lifecycle events must fan out to all owning teams, not just the oldestconfig's. Resolving to a single (oldest) team would leave other teams' rows live after an uninstall- and could bind a newly added repo to a team its adder never intended. unscoped(): the owning teams- are exactly what's being resolved here — the one cross-team read on this path (mirrors- _resolve_repo_config, writer pin included: a lagged reader returning no teams would silently and- permanently skip the lifecycle mutation for a just-synced installation).+ and could add a new repo to a team its adder never intended. The bound rows count too, so that a+ team whose record is gone still has its rows tombstoned. unscoped(): the owning teams are exactly+ what's being resolved here — the one cross-team read on this path (mirrors _resolve_repo_config,+ writer pin included: a lagged reader returning no teams would silently and permanently skip the+ lifecycle mutation for a just-synced installation)."""- return list(- StamphogRepoConfig.objects.unscoped()- .using(router.db_for_write(StamphogRepoConfig))+ write_db = router.db_for_write(StamphogInstallation)+ recorded = (+ StamphogInstallation.objects.unscoped()+ .using(write_db).filter(provider="github", installation_id=installation_id).values_list("team_id", flat=True)- .distinct())---def _add_installation_repos(- team_id: int, installation_id: str, repos: list[dict[str, Any]], *, delivery_id: str-) -> None:- """Create a disabled config row per newly installed repo, skipping any that already exist.-- Rows start disabled so a repo added on GitHub merely appears in the toggle list — enabling reviews- stays a human decision. Conflicts (another team owns the triple, or this team already has the repo)- skip that one repo, never the batch: the same cross-team uniqueness the sync endpoint enforces.- """- # Bind the transaction to the model's routed DB (stamphog_db_writer when the product DB is- # configured, else default) — a bare atomic() would open on the default connection and leave- # the create running outside any transaction on the product DB.- write_db = router.db_for_write(StamphogRepoConfig)- # New rows inherit the connecting user from a sibling of the same installation — webhooks carry- # no PostHog identity, and the sandbox token for reviews is minted under this user. No sibling- # with one set means the installation was never synced; the row stays null and reviews fail closed.- # Writer pin: an add arriving right after the sync/restamp must see the just-committed identity,- # or the new row is stored null and reviews fail at mint time once enabled.- connected_by_user_id = (- StamphogRepoConfig.objects.for_team(team_id)+ bound = (+ StamphogRepoConfig.objects.unscoped().using(write_db)- .filter(provider="github", installation_id=installation_id, connected_by_user_id__isnull=False)- .values_list("connected_by_user_id", flat=True)- .first()+ .filter(provider="github", installation_id=installation_id)+ .values_list("team_id", flat=True)+ .distinct())- created_rows: list[dict[str, Any]] = []- # One delivery can add many repos, so the rows are logged as one batch instead of one receiver- # call each. The batch runs in a finally: a row that is already committed when the loop dies- # would otherwise never be logged, and a retry skips it as existing, losing its creation.- try:- with suppress_created_activity():- for repo in repos:- full_name = (repo or {}).get("full_name") or ""- if not full_name:- continue- exists = (- StamphogRepoConfig.objects.unscoped()- .filter(provider="github", installation_id=installation_id, repository=full_name)- .exists()- )- if exists:- continue- try:- with transaction.atomic(using=write_db):- config = StamphogRepoConfig.objects.for_team(team_id).create(- team_id=team_id,- provider="github",- repository=full_name,- installation_id=installation_id,- enabled=False,- digest_enabled=False,- connected_by_user_id=connected_by_user_id,- )- except IntegrityError:- logger.info("stamphog_installation_repo_add_conflict", repository=full_name, team_id=team_id)- continue- created_rows.append({"id": config.id, "repository": config.repository})- finally:- # A webhook carries no PostHog user, so these are system rows; the trigger names the delivery.- log_repo_configs_created(- team_id,- created_rows,- trigger=installation_webhook_trigger(- delivery_id=delivery_id, action="added", installation_id=installation_id- ),- )+ return sorted(set(recorded) | set(bound))def _supersede_runs_for_configs(team_id: int, config_ids: list[Any]) -> None:@@ -999,19 +941,19 @@ def _disable_installation_repos(@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)def process_installation_event(payload: dict[str, Any], delivery_id: str) -> None:- """Mirror installation lifecycle changes (repos added/removed, app uninstalled) onto config rows.+ """Mirror installation lifecycle changes (repos removed, app uninstalled) onto snapshots and rows.- Without this, a repo added to the installation after the initial sync never appears in the toggle- list until a manual re-sync. `installation_repositories` payloads carry repositories_added/removed;- a plain `installation` event with action "deleted" means the app was uninstalled.+ `installation_repositories` payloads carry repositories_added/removed; a plain `installation`+ event with action "deleted" means the app was uninstalled.An installation's repos can be split across several teams, so removals and uninstalls fan out to- EVERY owning team (tombstone semantics — rows and history are kept). Auto-adding a newly installed- repo, on the other hand, is only a convenience for the unambiguous single-team case: when one team- owns the installation the new repo appears as a disabled row automatically. When multiple teams- share it, ownership is ambiguous — auto-binding could attach the repo to a team its adder never- intended — so the add is skipped and left to the authenticated sync flow, which verifies the acting- user's repo access. Rows always start disabled either way, so enabling reviews stays a human decision.+ EVERY owning team: the repos leave each snapshot, and their rows are tombstoned (rows and history+ are kept). An uninstall also deletes each team's installation record.++ A repo added on GitHub changes nothing. The snapshot holds only repos a member proved access to+ with their own GitHub token, and a webhook carries no user. An outside collaborator on one repo+ can connect the installation, so adding every later repo to their team's snapshot would let that+ team review private repos nobody on it can see. The repo becomes addable when a member syncs again."""if delivery_id and _is_duplicate_pr_event(delivery_id):logger.info("stamphog_installation_event_duplicate_skipped", delivery_id=delivery_id)@@ -1030,36 +972,36 @@ def process_installation_event(payload: dict[str, Any], delivery_id: str) -> Nonlogger.exception("stamphog_installation_team_resolution_failed", delivery_id=delivery_id, error=str(e))raise cast(Any, process_installation_event).retry(exc=e)if not team_ids:- # No config carries this installation yet — the user-driven sync flow will bind it to a team.+ # No team holds this installation yet. The user-driven sync flow binds it to a team.logger.info("stamphog_installation_event_unbound", installation_id=installation_id)returnaction = payload.get("action", "")# Retry on failure like the review path: the webhook is already ACKed, so a transient product-DB- # blip during the config mutations must not permanently drop the lifecycle event (a repo added on- # GitHub would then never appear in the toggle list until a manual re-sync). Mark the delivery+ # blip during the config mutations must not permanently drop the lifecycle event (a repo removed+ # on GitHub would then stay live and addable). Mark the delivery# processed only after the mutations succeed, so a retried delivery still does its work.try:if "repositories_added" in payload or "repositories_removed" in payload:- added = payload.get("repositories_added") or []- if added:- if len(team_ids) == 1:- _add_installation_repos(team_ids[0], installation_id, added, delivery_id=delivery_id)- else:- # Ambiguous ownership: skip the auto-add, defer to the authenticated sync flow.- logger.info(- "stamphog_installation_repo_add_ambiguous",- installation_id=installation_id,- team_count=len(team_ids),- )+ if payload.get("repositories_added"):+ logger.info(+ "stamphog_installation_repos_added_awaiting_sync",+ installation_id=installation_id,+ added=len(payload["repositories_added"]),+ )removed = payload.get("repositories_removed") or []names = [name for repo in removed if (name := (repo or {}).get("full_name"))]for team_id in team_ids:+ remove_from_installation_snapshot(team_id, installation_id, names)_disable_installation_repos(team_id, installation_id, action="removed", delivery_id=delivery_id, repository_names=names)elif action == "deleted":for team_id in team_ids:+ # Record first: the delete waits for an add_repository that holds the record's lock, so+ # the disable below sees the row that add created. A retry still finds this team+ # through its bound rows.+ delete_installation(team_id, installation_id)_disable_installation_repos(team_id, installation_id, action=action, delivery_id=delivery_id)else:logger.info("stamphog_installation_event_ignored", action=action)diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.pyindex 2dca79f16217..4fe364b0a77b 100644--- a/products/stamphog/backend/tests/test_api.py+++ b/products/stamphog/backend/tests/test_api.py@@ -23,7 +23,7 @@ from posthog.models.utils import generate_random_token_personal, uuid7from products.access_control.backend.models.access_control import AccessControlfrom products.stamphog.backend.facade import contractsfrom products.stamphog.backend.facade.enums import ChannelResolutionSource, DigestRunStatus, ReviewMode, ReviewRunStatus-from products.stamphog.backend.models import DigestRun, PullRequest, ReviewRun, StamphogRepoConfig+from products.stamphog.backend.models import DigestRun, PullRequest, ReviewRun, StamphogInstallation, StamphogRepoConfigfrom products.stamphog.backend.presentation.serializers import StamphogRepoConfigWriteSerializerfrom products.stamphog.backend.presentation.views import _INSTALL_STATE_SALTfrom products.stamphog.backend.tests import fakes@@ -91,20 +91,29 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert "manager" in response.json()["detail"]assert StamphogRepoConfig.objects.unscoped().get(id=config_id).enabled is True- def test_member_can_still_change_the_digest_toggle(self) -> None:- # The digest only decides who reads about merges, so gating it on manager too would take a- # setting away from editors that was never a review decision.+ @parameterized.expand(+ [+ # The digest only decides who reads about merges, so it was never a review decision.+ ("digest_toggle", True, {"digest_enabled": True}),+ # Turning reviews on is the self-serve direction. Only turning them off takes manager.+ ("turn_reviews_on", False, {"enabled": True}),+ ]+ )+ def test_member_can_make_a_non_manager_write(self, _name: str, enabled: bool, payload: dict) -> None:config_id = self._create_config()+ StamphogRepoConfig.objects.unscoped().filter(id=config_id).update(enabled=enabled)self._login_as_member()- response = self.client.patch(f"{self.url}{config_id}/", {"digest_enabled": True}, format="json")+ response = self.client.patch(f"{self.url}{config_id}/", payload, format="json")assert response.status_code == status.HTTP_200_OK, response.content- assert response.json()["digest_enabled"] is True+ assert {field: response.json()[field] for field in payload} == payload@parameterized.expand([- ("names_a_gate_field", {"enabled": True}, status.HTTP_403_FORBIDDEN),+ ("names_the_review_mode", {"review_mode": ReviewMode.LABEL}, status.HTTP_403_FORBIDDEN),+ ("turns_reviews_off", {"enabled": False}, status.HTTP_403_FORBIDDEN),+ ("turns_reviews_on", {"enabled": True}, status.HTTP_201_CREATED),("leaves_the_defaults", {}, status.HTTP_201_CREATED),])@@ -112,8 +121,8 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):self, _name: str, extra: dict, expected_status: int) -> None:# Spelling out a review policy is the same decision whichever verb carries it, so create- # gates on the field being present, like update does. Connecting a repository without one- # stays an editor's job: the row binds disabled at sync and routes no digest until then.+ # gates on the field being present, like update does. Turning reviews on, or leaving the+ # fields out, stays an editor's job: the row binds disabled at sync and routes no digest.self._login_as_member()response = self.client.post(self.url, {"repository": "PostHog/new", **extra}, format="json")@@ -428,6 +437,102 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):enabled_change = next(change for change in log.detail["changes"] if change["field"] == "enabled")assert (enabled_change["before"], enabled_change["after"]) == (True, False)+ def _record_installation(self, repositories: list[str], *, installation_id: str = "42") -> None:+ StamphogInstallation.objects.unscoped().create(+ team_id=self.team.id,+ installation_id=installation_id,+ repositories=repositories,+ connected_by_user_id=self.user.id,+ )++ @parameterized.expand(+ [+ ("everything_addable", True, {}, ["acme/alpha", "acme/Beta"], 2),+ ("search_ignores_case", True, {"search": "BET"}, ["acme/Beta"], 1),+ ("limit_keeps_the_total", True, {"limit": 1}, ["acme/alpha"], 2),+ ("nothing_connected", False, {}, [], 0),+ ]+ )+ def test_available_repositories_offers_only_what_the_team_can_add(+ self, _name: str, connected: bool, query: dict, expected: list[str], expected_total: int+ ) -> None:+ # A repository the team already added, or one another team holds under the same installation,+ # must not be offered: adding the first is a no-op, and the second fails the unique constraint.+ if connected:+ self._record_installation(["acme/Beta", "acme/added", "acme/alpha", "acme/theirs"])+ StamphogRepoConfig.objects.unscoped().create(+ team_id=self.team.id, repository="acme/added", installation_id="42"+ )+ other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)+ StamphogRepoConfig.objects.unscoped().create(+ team_id=other_team.id, repository="acme/theirs", installation_id="42"+ )++ response = self.client.get(f"{self.url}available_repositories/", query)++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json() == {+ "repositories": expected,+ "total_count": expected_total,+ "has_installation": connected,+ }++ @parameterized.expand(+ [+ ("new_row", None, status.HTTP_201_CREATED),+ ("paused_row", "42", status.HTTP_200_OK),+ # A placeholder's label mode was set without proving GitHub access, so it resets on binding.+ ("placeholder_row", "", status.HTTP_200_OK),+ ]+ )+ def test_member_adds_a_repository_from_the_snapshot(+ self, _name: str, existing_installation: str | None, expected_status: int+ ) -> None:+ # The row must bind the snapshot's installation and connector, which a member proved on GitHub.+ # A row without them never resolves webhooks, and a review without a connector fails to mint.+ self._record_installation(["acme/alpha"])+ if existing_installation is not None:+ StamphogRepoConfig.objects.unscoped().create(+ team_id=self.team.id,+ repository="acme/alpha",+ installation_id=existing_installation,+ enabled=False,+ review_mode=ReviewMode.LABEL,+ )+ self._login_as_member()++ response = self.client.post(f"{self.url}add_repository/", {"repository": "acme/alpha"}, format="json")++ assert response.status_code == expected_status, response.content+ config = StamphogRepoConfig.objects.unscoped().get(team_id=self.team.id, repository="acme/alpha")+ assert (config.enabled, config.installation_id, config.connected_by_user_id) == (True, "42", self.user.id)+ expected_mode = ReviewMode.ALL if existing_installation in (None, "") else ReviewMode.LABEL+ assert config.review_mode == expected_mode++ @parameterized.expand(+ [+ # The API never trusts a client-supplied repository: only the snapshot proves access.+ ("outside_the_snapshot", "acme/unknown"),+ ("held_by_another_team", "acme/theirs"),+ # A backfilled record can lack a connector, and a row bound from it never mints review credentials.+ ("no_connecting_user", "acme/unsynced"),+ ]+ )+ def test_add_repository_refuses_what_the_team_cannot_bind(self, _name: str, repository: str) -> None:+ self._record_installation(["acme/theirs"])+ StamphogInstallation.objects.unscoped().create(+ team_id=self.team.id, installation_id="43", repositories=["acme/unsynced"], connected_by_user_id=None+ )+ other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)+ StamphogRepoConfig.objects.unscoped().create(+ team_id=other_team.id, repository="acme/theirs", installation_id="42"+ )++ response = self.client.post(f"{self.url}add_repository/", {"repository": repository}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert not StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).exists()+def test_cannot_enable_digest_without_reviews(self) -> None:# Wiring guard for the serializer matrix below: the viewset must actually reject the# combination. A digest-on/review-off repo captures no merges at all, so it would look@@ -807,41 +912,34 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):self.url = f"/api/projects/{self.team.id}/stamphog/repo_configs/sync_installation/"self.state = _install_state(self.team.id, self.user.id)- @patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories", return_value=["PostHog/posthog", "PostHog/other"])+ @patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories")@patch(f"{_VIEWS}.user_can_access_installation", return_value=True)@patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")- def test_verified_installation_binds_repos(self, mock_exchange, mock_verify, mock_list) -> None:- response = self.client.post(- self.url, {"installation_id": "42", "code": "oauth-code", "state": self.state}, format="json"- )+ def test_syncs_merge_into_the_snapshot_without_rows(self, mock_exchange, mock_verify, mock_list) -> None:+ # An install can surface hundreds of repos, so a sync only records what the member can reach.+ # A second member who sees fewer repos must not hide the ones the first member listed.+ payload = {"installation_id": "42", "code": "oauth-code", "state": self.state}+ mock_list.return_value = ["PostHog/posthog", "PostHog/other"]+ assert self.client.post(self.url, payload, format="json").status_code == status.HTTP_200_OK+ mock_list.return_value = ["PostHog/posthog", "PostHog/third"]++ response = self.client.post(self.url, payload, format="json")assert response.status_code == status.HTTP_200_OK, response.content- mock_exchange.assert_called_once_with("oauth-code")- mock_verify.assert_called_once_with("42", "user-token")+ mock_verify.assert_called_with("42", "user-token")+ body = response.json()# The explicit-id path never discovers, so app_not_installed is always false there.- assert response.json()["app_not_installed"] is False- synced = sorted(row["repository"] for row in response.json()["synced"])- assert synced == ["PostHog/other", "PostHog/posthog"]- # The scene disables the review controls off this field, and it renders these rows straight- # from the sync response. A null here would leave every control disabled right after connecting.- assert {row["user_access_level"] for row in response.json()["synced"]} == {"editor"}- bound = StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id, installation_id="42")- assert bound.count() == 2- # Bind disabled: an install can surface hundreds of repos, so none starts reviewing until toggled.- assert all(not config.enabled for config in bound)- # The caller becomes the connecting user — the identity review-sandbox credentials are minted under.- assert all(config.connected_by_user_id == self.user.id for config in bound)- # One audit row per connected repo, written as a batch: the per-row receiver is silenced for- # the sync loop because an installation can expose thousands of repositories.- created = ActivityLog.objects.filter(scope="StamphogRepoConfig", activity="created")- assert created.count() == 2- connected_names = set()- for log in created:- assert log.user == self.user- assert log.detail is not None- assert log.detail["type"] == "connected"- connected_names.add(log.detail["name"])- assert connected_names == {"PostHog/other", "PostHog/posthog"}+ assert (body["synced"], body["skipped"], body["available_count"], body["app_not_installed"]) == (+ [],+ [],+ 3,+ False,+ )+ installation = StamphogInstallation.objects.unscoped().get(team_id=self.team.id, installation_id="42")+ assert installation.repositories == ["PostHog/other", "PostHog/posthog", "PostHog/third"]+ # The caller becomes the connector, the identity an added repo's review credentials are minted under.+ assert installation.connected_by_user_id == self.user.id+ assert not StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).exists()@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories",@@ -850,8 +948,8 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):@patch(f"{_VIEWS}.user_can_access_installation", return_value=True)@patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")def test_sync_skips_a_repo_another_team_already_owns(self, mock_exchange, mock_verify, mock_list) -> None:- # Without the read-back that says which rows landed, a repo another team holds under this- # installation answers as synced and its webhooks resolve to the wrong team.+ # A repo another team holds under this installation must answer as skipped and never be+ # offered for adding, or its webhooks would resolve to the wrong team.other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)theirs = StamphogRepoConfig.objects.unscoped().create(team_id=other_team.id, repository="PostHog/theirs", installation_id="42"@@ -863,34 +961,13 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.contentbody = response.json()- assert [row["repository"] for row in body["synced"]] == ["PostHog/mine"]- assert body["skipped"] == ["PostHog/theirs"]+ assert (body["synced"], body["skipped"], body["available_count"]) == ([], ["PostHog/theirs"], 1)theirs.refresh_from_db()assert theirs.team_id == other_team.idassert not (StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id, repository="PostHog/theirs").exists())- @patch(- f"{_GITHUB_FACADE}.list_user_accessible_repositories",- return_value=["PostHog/posthog", "PostHog/other"],- )- @patch(f"{_VIEWS}.user_can_access_installation", return_value=True)- @patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")- def test_resyncing_an_installation_creates_nothing_new(self, mock_exchange, mock_verify, mock_list) -> None:- # A regression here duplicates the connected audit entries and makes each re-sync cost grow.- payload = {"installation_id": "42", "code": "oauth-code", "state": self.state}- assert self.client.post(self.url, payload, format="json").status_code == status.HTTP_200_OK-- response = self.client.post(self.url, payload, format="json")-- assert response.status_code == status.HTTP_200_OK, response.content- body = response.json()- assert sorted(row["repository"] for row in body["synced"]) == ["PostHog/other", "PostHog/posthog"]- assert body["skipped"] == []- assert StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).count() == 2- assert ActivityLog.objects.filter(scope="StamphogRepoConfig", activity="created").count() == 2-@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories", return_value=["PostHog/posthog"])@patch(f"{_VIEWS}.user_can_access_installation", return_value=True)@patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")@@ -1044,11 +1121,10 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.contentmock_discover.assert_called_once_with("user-token")body = response.json()- assert [row["repository"] for row in body["synced"]] == ["PostHog/posthog"]assert body["app_not_installed"] is Falseassert body["installations"] == []- bound = StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id, installation_id="42")- assert bound.count() == 1+ installation = StamphogInstallation.objects.unscoped().get(team_id=self.team.id)+ assert (installation.installation_id, installation.repositories) == ("42", ["PostHog/posthog"])@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories")@patch(@@ -1074,7 +1150,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):{"id": "200", "account_login": "SharedOrg"},]mock_list.assert_not_called()- assert not StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).exists()+ assert not StamphogInstallation.objects.unscoped().filter(team_id=self.team.id).exists()@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories")@patch(f"{_VIEWS}.list_user_installations", return_value=[])diff --git a/products/stamphog/backend/tests/test_models.py b/products/stamphog/backend/tests/test_models.pyindex 5c28c6955356..51b1d4c89c7c 100644--- a/products/stamphog/backend/tests/test_models.py+++ b/products/stamphog/backend/tests/test_models.py@@ -1,13 +1,18 @@+import importlib+from datetime import UTC, datetime+from types import SimpleNamespace+import pytestfrom posthog.test.base import APIBaseTest-from django.db import IntegrityError+from django.apps import apps+from django.db import IntegrityError, routerfrom posthog.models.scoping import reset_current_team_id, set_current_team_idfrom posthog.models.scoping.manager import TeamScopeErrorfrom posthog.models.team import Team-from products.stamphog.backend.models import PullRequest, ReviewRun, StamphogRepoConfig+from products.stamphog.backend.models import PullRequest, ReviewRun, StamphogInstallation, StamphogRepoConfigfrom products.stamphog.backend.tests.conftest import PRODUCT_DATABASES, StamphogTeamScopedTestMixin@@ -113,3 +118,56 @@ class TestReviewRunModel(StamphogTeamScopedTestMixin, APIBaseTest):results = list(ReviewRun.objects.for_team(self.team.id))assert results == [mine]+++class TestInstallationMigrations(StamphogTeamScopedTestMixin, APIBaseTest):+ databases = PRODUCT_DATABASES++ def _run_migration(self, module_name: str, function_name: str) -> None:+ module = importlib.import_module(f"products.stamphog.backend.migrations.{module_name}")+ schema_editor = SimpleNamespace(connection=SimpleNamespace(alias=router.db_for_write(StamphogRepoConfig)))+ getattr(module, function_name)(apps, schema_editor)++ def test_backfill_keeps_every_repository_addable_before_the_cleanup_deletes_unused_rows(self) -> None:+ # The cleanup deletes rows a sync created and nobody turned on. The backfill must first copy+ # their repositories into the snapshot, or those repositories can never be added again.+ rows = {+ name: StamphogRepoConfig.objects.unscoped().create(+ team_id=self.team.id,+ repository=name,+ installation_id=installation_id,+ enabled=enabled,+ connected_by_user_id=connector,+ )+ for name, installation_id, enabled, connector in [+ ("acme/reviewed", "1", True, 5),+ ("acme/unused", "1", False, 7),+ ("acme/with-history", "1", False, None),+ ("acme/placeholder", "", False, None),+ ("acme/label-mode", "1", False, None),+ ]+ }+ StamphogRepoConfig.objects.unscoped().filter(id=rows["acme/label-mode"].id).update(review_mode="label")+ for day, name in enumerate(rows, start=1):+ StamphogRepoConfig.objects.unscoped().filter(id=rows[name].id).update(+ updated_at=datetime(2026, 1, day, tzinfo=UTC)+ )+ _make_pull_request(self.team, rows["acme/with-history"])++ # Twice, because bin/migrate retries a migration that failed part of the way.+ self._run_migration("0008_backfill_installations", "backfill_installations")+ self._run_migration("0008_backfill_installations", "backfill_installations")+ self._run_migration("0009_delete_unused_repo_configs", "delete_unused_repo_configs")++ installation = StamphogInstallation.objects.unscoped().get(team_id=self.team.id)+ assert installation.installation_id == "1"+ assert installation.repositories == ["acme/label-mode", "acme/reviewed", "acme/unused", "acme/with-history"]+ # The newest non-null connector, which the newer row with no connector does not overwrite.+ assert installation.connected_by_user_id == 7+ remaining = StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id)+ assert sorted(remaining.values_list("repository", flat=True)) == [+ "acme/label-mode",+ "acme/placeholder",+ "acme/reviewed",+ "acme/with-history",+ ]diff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.pyindex 7a794c4f36aa..70b712612e65 100644--- a/products/stamphog/backend/tests/test_tasks.py+++ b/products/stamphog/backend/tests/test_tasks.py@@ -15,7 +15,13 @@ from posthog.models.scoping import team_scopefrom products.stamphog.backend.facade.enums import AudienceReason, ReviewMode, ReviewRunStatus, ReviewVerdictfrom products.stamphog.backend.logic.audiences import ResolvedAudience-from products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfig+from products.stamphog.backend.models import (+ PullRequest,+ PullRequestAudience,+ ReviewRun,+ StamphogInstallation,+ StamphogRepoConfig,+)from products.stamphog.backend.tasks.tasks import (_INBOX_OPT_OUT_DISMISS_MESSAGE,_parse_pr_url,@@ -679,52 +685,38 @@ def _installation_payload(return payload+def _record_installation(team_id: int, repositories: list[str]) -> StamphogInstallation:+ with team_scope(team_id):+ return StamphogInstallation.objects.create(+ team_id=team_id, installation_id=INSTALLATION_ID, repositories=repositories, connected_by_user_id=4242+ )++@pytest.mark.django_db(databases=PRODUCT_DATABASES)-def test_installation_repos_added_creates_disabled_rows_and_skips_existing(team, repo_config):- # A repo added to the installation after the initial sync must appear in the toggle list without a- # manual re-sync — as a disabled row, since enabling reviews stays a human decision. An already- # registered repo is left untouched (no duplicate, no settings reset).- with team_scope(team.id):- # Webhooks carry no PostHog identity, so the new row must inherit the connecting user- # (the review-credential principal) from its synced sibling.- StamphogRepoConfig.objects.filter(id=repo_config.id).update(connected_by_user_id=4242)- payload = _installation_payload(action="added", added=["acme/new-repo", REPO])- process_installation_event(payload, "delivery-inst-added")+def test_installation_repos_added_leave_the_snapshot_alone(team, repo_config):+ # The webhook carries no user, so no member proved access to the new repo. An outside collaborator+ # who connected the installation would otherwise be offered every private repo installed later.+ installation = _record_installation(team.id, [REPO])- with team_scope(team.id):- new_row = StamphogRepoConfig.objects.get(repository="acme/new-repo")- assert new_row.enabled is False- assert new_row.digest_enabled is False- assert new_row.installation_id == INSTALLATION_ID- assert new_row.connected_by_user_id == 4242- repo_config.refresh_from_db()- assert repo_config.enabled is True # existing row untouched- assert StamphogRepoConfig.objects.count() == 2-- # One batch audit row per repo the delivery actually added: the per-row receiver is silenced for- # the loop, and the skipped repo writes nothing. No PostHog user is behind a webhook.- created = list(ActivityLog.objects.filter(detail__trigger__job_id="delivery-inst-added"))- assert [log.item_id for log in created] == [str(new_row.id)]- for log in created:- assert log.scope == "StamphogRepoConfig"- assert log.activity == "created"- assert log.user is None- assert log.is_system is True- assert log.detail is not None- assert log.detail["name"] == "acme/new-repo"+ process_installation_event(_installation_payload(action="added", added=["acme/new-repo"]), "delivery-inst-added")++ installation.refresh_from_db()+ assert installation.repositories == [REPO]+ assert not StamphogRepoConfig.objects.unscoped().filter(repository="acme/new-repo").exists()@pytest.mark.parametrize(- "payload_kwargs,expect_disabled",+ "payload_kwargs,expect_disabled,expected_snapshot",[- ({"action": "removed", "removed": [REPO]}, True),- ({"action": "deleted"}, True),- ({"action": "suspend"}, False),+ ({"action": "removed", "removed": [REPO]}, True, ["acme/other"]),+ # An uninstall deletes the record, so nothing is offered for adding under a dead installation.+ ({"action": "deleted"}, True, None),+ ({"action": "suspend"}, False, ["acme/other", REPO]),],ids=["repo_removed_disables_row", "uninstall_disables_all_rows", "other_installation_action_ignored"],)@pytest.mark.django_db(databases=PRODUCT_DATABASES)-def test_installation_removal_tombstones_rows(team, repo_config, payload_kwargs, expect_disabled):+def test_installation_removal_tombstones_rows(team, repo_config, payload_kwargs, expect_disabled, expected_snapshot):# Removed repos and a full uninstall tombstone the configs (disabled, rows and history kept);# other installation actions are acked and ignored. In-flight runs must be superseded too —# workflows never re-check `enabled`, so a run already in the sandbox would otherwise still@@ -741,6 +733,7 @@ def test_installation_removal_tombstones_rows(team, repo_config, payload_kwargs,terminal = ReviewRun.objects.create(team_id=team.id, pull_request=pull_request, head_sha="sha-0", status=ReviewRunStatus.COMPLETED)+ _record_installation(team.id, ["acme/other", REPO])process_installation_event(_installation_payload(**payload_kwargs), f"delivery-inst-{payload_kwargs['action']}")@@ -753,6 +746,8 @@ def test_installation_removal_tombstones_rows(team, repo_config, payload_kwargs,expected_in_flight = ReviewRunStatus.SUPERSEDED if expect_disabled else ReviewRunStatus.REVIEWINGassert in_flight.status == expected_in_flightassert terminal.status == ReviewRunStatus.COMPLETED+ snapshots = list(StamphogInstallation.objects.unscoped().values_list("repositories", flat=True))+ assert snapshots == ([] if expected_snapshot is None else [expected_snapshot])@pytest.mark.django_db(databases=PRODUCT_DATABASES)@@ -815,23 +810,6 @@ def test_installation_uninstall_tombstones_every_owning_team(team, repo_config):assert (enabled_change["before"], enabled_change["after"]) == (True, False)[email protected]_db(databases=PRODUCT_DATABASES)-def test_installation_repos_added_skips_when_installation_spans_multiple_teams(team, repo_config):- # Ambiguous ownership: two teams share the installation, so auto-binding a newly added repo could- # attach it to a team its adder never intended. The webhook add is skipped and left to the- # authenticated sync flow — no row is created for either team.- second_team = _make_second_team(team.organization)- with team_scope(second_team.id):- StamphogRepoConfig.objects.create(- team_id=second_team.id, repository="acme/other", installation_id=INSTALLATION_ID- )-- payload = _installation_payload(action="added", added=["acme/brand-new"])- process_installation_event(payload, "delivery-multi-add")-- assert StamphogRepoConfig.objects.unscoped().filter(repository="acme/brand-new").exists() is False--def _selfdriving_payload(**overrides: Any) -> dict[str, Any]:"""A synchronize delivery shaped like a self-driving inbox PR: bot-authored draft, repo-native branch."""kwargs: dict[str, Any] = {diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.tsindex 5dcb8f9b5d94..1ff90c42744d 100644--- a/products/stamphog/frontend/generated/api.schemas.ts+++ b/products/stamphog/frontend/generated/api.schemas.ts@@ -155,7 +155,7 @@ export interface StamphogRepoConfigApi {/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string/**- * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'manager' is required to change enabled, review_mode, or trigger_label.+ * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change review_mode or trigger_label.* @nullable*/readonly user_access_level: string | null@@ -232,6 +232,26 @@ export interface PatchedStamphogRepoConfigWriteApi {trigger_label?: string}+/**+ * Request body for turning reviews on for a repository from a connected installation.+ */+export interface StamphogAddRepositoryApi {+ /** Repository full name, e.g. 'PostHog/posthog'. It must be in one of the project's connected GitHub installations, as available_repositories lists them. A repository the project already has is turned back on. */+ repository: string+}++/**+ * Repositories from the team's connected GitHub installations that are not added to stamphog yet.+ */+export interface StamphogAvailableRepositoriesApi {+ /** Repository full names the team can add, sorted by name and capped by limit. Only repositories a project member proved access to on GitHub are listed, and never one another project already holds under the same installation. */+ readonly repositories: readonly string[]+ /** How many repositories match the search in total, before limit applies. */+ readonly total_count: number+ /** Whether a project member connected a GitHub installation yet. False means GitHub must be connected before any repository can be added. True with a total_count of 0 and no search means no repository is left to add. */+ readonly has_installation: boolean+}+/*** Static info the frontend needs to render the 'Connect a repository' button.*/@@ -273,13 +293,15 @@ export interface StamphogDiscoveredInstallationApi {}/**- * Result of syncing an installation: rows created/kept for this team, plus conflicting repos skipped.+ * Result of syncing an installation: the team's rows bound to it, and what the team can add now.*/export interface StamphogSyncInstallationResponseApi {- /** Repo configs now bound to this team for the installation (created this call or already present). */+ /** Repo configs this team already had for the installation's repositories, now bound to it. A sync creates no repo config: use add_repository to turn reviews on for a repository. */readonly synced: readonly StamphogRepoConfigApi[]/** Repository full names skipped because another team already owns them under this installation. */readonly skipped: readonly string[]+ /** How many repositories this team can add after the sync, across all its connected installations. List them with available_repositories. */+ readonly available_count: number/** True only on the discovery path (no installation_id) when the caller can reach no installation of this App — it isn't installed anywhere they can see. The frontend should route the user to the GitHub install page (install_url). Always false on the explicit installation_id path. */readonly app_not_installed: boolean/** Populated only on the discovery path when the caller can reach MORE than one installation of this App: nothing was bound, and the user must pick which installation to connect. The frontend re-runs the authorize flow and calls back with the chosen installation_id, which the explicit path verifies. Empty whenever a bind happened (or nothing was found). */@@ -553,6 +575,19 @@ export type StamphogRepoConfigsListParams = {offset?: number}+export type StamphogRepoConfigsAvailableRepositoriesRetrieveParams = {+ /**+ * Maximum number of repositories to return. Defaults to 50, at most 200.+ * @minimum 1+ * @maximum 200+ */+ limit?: number+ /**+ * Case-insensitive substring to match against the repository full name, e.g. 'posthog'.+ */+ search?: string+}+export type StamphogReviewRunsListParams = {/*** Number of results to return per page.diff --git a/products/stamphog/frontend/generated/api.ts b/products/stamphog/frontend/generated/api.tsindex 6b703f6694b0..a41d26f340f0 100644--- a/products/stamphog/frontend/generated/api.ts+++ b/products/stamphog/frontend/generated/api.ts@@ -18,12 +18,15 @@ import type {ReviewRequestApi,ReviewRequestResponseApi,ReviewRunApi,+ StamphogAddRepositoryApi,+ StamphogAvailableRepositoriesApi,StamphogDigestRunsListParams,StamphogInstallInfoApi,StamphogPullRequestApi,StamphogPullRequestsListParams,StamphogRepoConfigApi,StamphogRepoConfigWriteApi,+ StamphogRepoConfigsAvailableRepositoriesRetrieveParams,StamphogRepoConfigsListParams,StamphogReviewRunsListParams,StamphogSyncInstallationRequestApi,@@ -254,6 +257,62 @@ export const stamphogRepoConfigsDestroy = async (})}+export const getStamphogRepoConfigsAddRepositoryCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/stamphog/repo_configs/add_repository/`+}++/**+ * Turn reviews on for a repository from the project's connected GitHub installations. Creates the repo config, or turns an existing one back on. Needs the editor level on stamphog.+ */+export const stamphogRepoConfigsAddRepositoryCreate = async (+ projectId: string,+ stamphogAddRepositoryApi: StamphogAddRepositoryApi,+ options?: RequestInit+): Promise<StamphogRepoConfigApi> => {+ return apiMutator<StamphogRepoConfigApi>(getStamphogRepoConfigsAddRepositoryCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(stamphogAddRepositoryApi),+ })+}++export const getStamphogRepoConfigsAvailableRepositoriesRetrieveUrl = (+ projectId: string,+ params?: StamphogRepoConfigsAvailableRepositoriesRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/stamphog/repo_configs/available_repositories/?${stringifiedParams}`+ : `/api/projects/${projectId}/stamphog/repo_configs/available_repositories/`+}++/**+ * List repositories from the project's connected GitHub installations that are not added to stamphog yet, so they can be added with add_repository.+ */+export const stamphogRepoConfigsAvailableRepositoriesRetrieve = async (+ projectId: string,+ params?: StamphogRepoConfigsAvailableRepositoriesRetrieveParams,+ options?: RequestInit+): Promise<StamphogAvailableRepositoriesApi> => {+ return apiMutator<StamphogAvailableRepositoriesApi>(+ getStamphogRepoConfigsAvailableRepositoriesRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getStamphogRepoConfigsInstallInfoRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/stamphog/repo_configs/install_info/`}diff --git a/products/stamphog/frontend/generated/api.zod.ts b/products/stamphog/frontend/generated/api.zod.tsindex cb0aebc98d17..dfc42232f30e 100644--- a/products/stamphog/frontend/generated/api.zod.ts+++ b/products/stamphog/frontend/generated/api.zod.ts@@ -93,6 +93,19 @@ export const StamphogRepoConfigsPartialUpdateBody = /* @__PURE__ */ zod"Input shape for creating\/updating a repo config.\n\nSeparate from the read serializer because the contract is an output shape: it carries a\nrequired id, which a create request has no way to supply. Same split as visual_review's\ninput serializers.\n\ninstallation_id is deliberately absent: it may only ever be set by the verified\nsync_installation flow, which proves the caller owns the installation before binding it. A\nclient-supplied value on this path is ignored, so a manually created config carries no\ninstallation and simply won't resolve webhooks until synced.")+/**+ * Turn reviews on for a repository from the project's connected GitHub installations. Creates the repo config, or turns an existing one back on. Needs the editor level on stamphog.+ */+export const StamphogRepoConfigsAddRepositoryCreateBody = /* @__PURE__ */ zod+ .object({+ repository: zod+ .string()+ .describe(+ "Repository full name, e.g. 'PostHog\/posthog'. It must be in one of the project's connected GitHub installations, as available_repositories lists them. A repository the project already has is turned back on."+ ),+ })+ .describe('Request body for turning reviews on for a repository from a connected installation.')+/*** Per-repo stamphog settings — enable/disable review, GitHub App installation, policy overrides.*/diff --git a/products/stamphog/mcp/tools.yaml b/products/stamphog/mcp/tools.yamlindex 76a48fd23035..8aead27a7b19 100644--- a/products/stamphog/mcp/tools.yaml+++ b/products/stamphog/mcp/tools.yaml@@ -63,6 +63,12 @@ tools:or by `merged` (true/false) to separate open work from merged history. Each entry includes the repository,author, head branch, merge state, and diff size (additions/deletions/changed_files) once merged.feature_flag: stamphog+ stamphog-repo-configs-add-repository:+ operation: stamphog_repo_configs_add_repository_create+ enabled: false+ stamphog-repo-configs-available-repositories:+ operation: stamphog_repo_configs_available_repositories_retrieve+ enabled: falsestamphog-repo-configs-create:operation: stamphog_repo_configs_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a018d32d012a..273039abbf4b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -66137,7 +66137,7 @@ export namespace Schemas {/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */trigger_label?: string;/**- * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'manager' is required to change enabled, review_mode, or trigger_label.+ * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'editor' can turn reviews on. 'manager' is required to turn them off or to change review_mode or trigger_label.* @nullable*/readonly user_access_level: string | null;@@ -94488,6 +94488,26 @@ export namespace Schemas {run: StaffWarmRun | null;}+ /**+ * Request body for turning reviews on for a repository from a connected installation.+ */+ export interface StamphogAddRepository {+ /** Repository full name, e.g. 'PostHog/posthog'. It must be in one of the project's connected GitHub installations, as available_repositories lists them. A repository the project already has is turned back on. */+ repository: string;+ }++ /**+ * Repositories from the team's connected GitHub installations that are not added to stamphog yet.+ */+ export interface StamphogAvailableRepositories {+ /** Repository full names the team can add, sorted by name and capped by limit. Only repositories a project member proved access to on GitHub are listed, and never one another project already holds under the same installation. */+ readonly repositories: readonly string[];+ /** How many repositories match the search in total, before limit applies. */+ readonly total_count: number;+ /** Whether a project member connected a GitHub installation yet. False means GitHub must be connected before any repository can be added. True with a total_count of 0 and no search means no repository is left to add. */+ readonly has_installation: boolean;+ }+/*** One installation of the App the authorizing user can reach, offered for an explicit pick.*/@@ -94559,13 +94579,15 @@ export namespace Schemas {}/**- * Result of syncing an installation: rows created/kept for this team, plus conflicting repos skipped.+ * Result of syncing an installation: the team's rows bound to it, and what the team can add now.*/export interface StamphogSyncInstallationResponse {- /** Repo configs now bound to this team for the installation (created this call or already present). */+ /** Repo configs this team already had for the installation's repositories, now bound to it. A sync creates no repo config: use add_repository to turn reviews on for a repository. */readonly synced: readonly StamphogRepoConfig[];/** Repository full names skipped because another team already owns them under this installation. */readonly skipped: readonly string[];+ /** How many repositories this team can add after the sync, across all its connected installations. List them with available_repositories. */+ readonly available_count: number;/** True only on the discovery path (no installation_id) when the caller can reach no installation of this App — it isn't installed anywhere they can see. The frontend should route the user to the GitHub install page (install_url). Always false on the explicit installation_id path. */readonly app_not_installed: boolean;/** Populated only on the discovery path when the caller can reach MORE than one installation of this App: nothing was bound, and the user must pick which installation to connect. The frontend re-runs the authorize flow and calls back with the chosen installation_id, which the explicit path verifies. Empty whenever a bind happened (or nothing was found). */@@ -114095,6 +114117,19 @@ export namespace Schemas {offset?: number;};+ export type StamphogRepoConfigsAvailableRepositoriesRetrieveParams = {+ /**+ * Maximum number of repositories to return. Defaults to 50, at most 200.+ * @minimum 1+ * @maximum 200+ */+ limit?: number;+ /**+ * Case-insensitive substring to match against the repository full name, e.g. 'posthog'.+ */+ search?: string;+ };+export type StamphogReviewRunsListParams = {/*** Number of results to return per page.