Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(stamphog): log repo config changes to the activity log (#93108)

Julian Bez1cbe1adc5fb6
diff --git a/frontend/src/lib/components/ActivityLog/describers.tsx b/frontend/src/lib/components/ActivityLog/describers.tsx
index 46f0e5e0bb8e..897878f46c73 100644
--- a/frontend/src/lib/components/ActivityLog/describers.tsx
+++ b/frontend/src/lib/components/ActivityLog/describers.tsx
@@ -46,6 +46,7 @@ import { ticketActivityDescriber } from 'products/conversations/frontend/activit
import { externalDataSourceActivityDescriber } from 'products/data_warehouse/frontend/shared/components/activityDescriptions'
import { endpointActivityDescriber } from 'products/endpoints/frontend/activityDescriber'
import { signalScoutConfigActivityDescriber } from 'products/signals/frontend/activityDescriber'
+import { stamphogRepoConfigActivityDescriber } from 'products/stamphog/frontend/activityDescriber'
import { workflowActivityDescriber } from 'products/workflows/frontend/Workflows/misc/workflowActivityDescriber'
export const describerFor = (logItem?: ActivityLogItem): Describer | undefined => {
@@ -138,6 +139,8 @@ export const describerFor = (logItem?: ActivityLogItem): Describer | undefined =
return promptActivityDescriber
case ActivityScope.LLM_PROMPT_LABEL:
return promptLabelActivityDescriber
+ case ActivityScope.STAMPHOG_REPO_CONFIG:
+ return stamphogRepoConfigActivityDescriber
default:
return defaultDescriber
}
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 84edf7c822fd..10add52049aa 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -935,7 +935,7 @@ export const productConfiguration: Record<string, any> = {
layout: 'app-container',
iconType: 'llm_prompts',
},
- Stamphog: { projectBased: true, name: 'Stamphog', iconType: 'stamphog' },
+ Stamphog: { projectBased: true, name: 'Stamphog', iconType: 'stamphog', activityScope: 'StamphogRepoConfig' },
StamphogRuns: { projectBased: true, name: 'Stamphog runs', iconType: 'stamphog' },
StamphogDigests: { projectBased: true, name: 'Stamphog digests', iconType: 'stamphog' },
StreamlitApps: {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 71c66d9a7136..0eed0873feff 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6182,6 +6182,7 @@ export enum ActivityScope {
INSTANCE_SETTING = 'InstanceSetting',
SIGNAL_SCOUT_CONFIG = 'SignalScoutConfig',
SIGNAL_TEAM_CONFIG = 'SignalTeamConfig',
+ STAMPHOG_REPO_CONFIG = 'StamphogRepoConfig',
}
export type CommentType = {
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 7c999953211a..f83028e8c964 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -113,6 +113,7 @@ ActivityScope = Literal[
"DataQualityCheck",
"Billing",
"Loop",
+ "StamphogRepoConfig",
]
ChangeAction = Literal[
"changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out", "copied"
@@ -514,6 +515,11 @@ activity_visibility_restrictions: list[dict[str, Any]] = [
]
field_exclusions: dict[AuditableScope, list[str]] = {
+ "StamphogRepoConfig": [
+ # Reverse relation to the repo's review history. The diff would read every pull request row
+ # on each settings toggle, and none of it is configuration.
+ "pull_requests",
+ ],
"HogFlow": [
# System-maintained skip-forward map for deleted steps, refreshed as a side effect of graph
# writes — bookkeeping, not a user edit, so keep it out of change diffs.
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 1befc3202237..8688ac410534 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -42,6 +42,7 @@ model_activity:products.logs.backend.activity_logging.handle_logs_sampling_rule_
model_activity:products.managed_migrations.backend.activity_logging.handle_batch_import_change
model_activity:products.signals.backend.activity_logging.handle_signal_scout_config_change
model_activity:products.signals.backend.activity_logging.handle_signal_team_config_change
+model_activity:products.stamphog.backend.activity_logging.handle_stamphog_repo_config_change
model_activity:products.tasks.backend.activity_logging.handle_loop_change
model_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_schema_change
model_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_source_change
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 66f47cde3a2a..6fbba5114c2c 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1398,6 +1398,7 @@ export type ActivityLogListParams = {
* * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
+ * * `StamphogRepoConfig` - StamphogRepoConfig
* @minLength 1
*/
scope?: ActivityLogListScope
@@ -1494,6 +1495,7 @@ export const ActivityLogListScope = {
DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
+ StamphogRepoConfig: 'StamphogRepoConfig',
} as const
/**
@@ -1577,6 +1579,7 @@ export const ActivityLogListScope = {
* * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
+ * * `StamphogRepoConfig` - StamphogRepoConfig
*/
export type ActivityLogListScopesItem = (typeof ActivityLogListScopesItem)[keyof typeof ActivityLogListScopesItem]
@@ -1661,6 +1664,7 @@ export const ActivityLogListScopesItem = {
DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
+ StamphogRepoConfig: 'StamphogRepoConfig',
} as const
export type AdvancedActivityLogsListParams = {
diff --git a/products/stamphog/backend/activity_logging.py b/products/stamphog/backend/activity_logging.py
new file mode 100644
index 000000000000..3aff05264f18
--- /dev/null
+++ b/products/stamphog/backend/activity_logging.py
@@ -0,0 +1,303 @@
+"""Activity-log receiver and bulk-write helpers for stamphog repo configs.
+
+The module stays import-light because `apps.py` imports it at `ready()`, and a repo config is
+written from web requests, webhook Celery tasks, and management commands alike. Every call passes
+`using=`, because the repo config lives on the stamphog database: the audit row must wait for that
+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 typing import TYPE_CHECKING, Any
+from uuid import UUID
+
+from django.conf import settings
+from django.db import router, transaction
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.activity_logging.activity_log import (
+ AuditableScope,
+ Detail,
+ LogActivityEntry,
+ Trigger,
+ bulk_log_activity,
+ changes_between,
+ dict_changes_between,
+ log_activity,
+)
+from posthog.models.signals import model_activity_signal, mutable_receiver
+from posthog.models.team import Team
+
+from products.stamphog.backend.models import StamphogRepoConfig
+
+if TYPE_CHECKING:
+ from posthog.models.user import User
+
+logger = structlog.get_logger(__name__)
+
+# The fields a webhook disable changes on a repo config. A caller reads them from the writer
+# 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
+ # main database. One lookup per logging call, never one per row.
+ return Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()
+
+
+def _log_after_product_commit(write_row: Callable[[], None], *, write_db: str, **log_context: Any) -> None:
+ """Run an audit write once the stamphog database commits, and never fail the caller.
+
+ A caller wraps its product write and the work that must follow it (superseding in-flight runs)
+ in one transaction. Keep the Team lookup and the insert out of that transaction: they run on
+ the main database, and a stall there would hold the product row's lock and widen the window in
+ which a run that is being stopped can still post its verdict. Deferring also drops the audit
+ row when the product write rolls back.
+
+ The guard mirrors `_handle_activity_log_transaction`, so with the setting off (tests) the write
+ stays inline and the row is there right after the request.
+ """
+
+ def _guarded() -> None:
+ # The product row is committed by now, so a failed audit write must not escape.
+ try:
+ write_row()
+ except Exception as e:
+ logger.warning("stamphog_activity_log_failed", exception=e, **log_context)
+ capture_exception(e)
+ if settings.TEST:
+ raise
+
+ if not transaction.get_autocommit(using=write_db) and getattr(
+ settings, "ACTIVITY_LOG_TRANSACTION_MANAGEMENT", True
+ ):
+ transaction.on_commit(_guarded, using=write_db)
+ else:
+ _guarded()
+
+
+@mutable_receiver(model_activity_signal, sender=StamphogRepoConfig)
+def handle_stamphog_repo_config_change(
+ sender: type[StamphogRepoConfig],
+ scope: AuditableScope,
+ before_update: StamphogRepoConfig | None,
+ after_update: StamphogRepoConfig | None,
+ activity: str,
+ user: "User | None",
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance = after_update or before_update
+ 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:
+ # Diff now, write later. `after_update` is the caller's live instance, so a later save in
+ # the same transaction would otherwise rewrite this row's changes.
+ changes = changes_between(scope, previous=before_update, current=after_update)
+ if activity == "updated" and not changes:
+ # log_activity drops an update that moved nothing, so the organization lookup is wasted.
+ return
+
+ detail = Detail(
+ changes=changes,
+ name=instance.repository,
+ # A row created by the API carries no installation until a sync binds it, so the
+ # describer must not call it connected.
+ type="connected" if instance.installation_id else "placeholder",
+ )
+ team_id = instance.team_id
+ item_id = instance.id
+ write_db = router.db_for_write(StamphogRepoConfig)
+
+ def _write_row() -> None:
+ log_activity(
+ organization_id=_organization_id_for_team(team_id),
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=item_id,
+ scope=scope,
+ activity=activity,
+ detail=detail,
+ using=write_db,
+ )
+
+ _log_after_product_commit(_write_row, write_db=write_db, team_id=team_id, item_id=str(item_id))
+ except Exception as e:
+ logger.warning("stamphog_activity_log_failed", team_id=instance.team_id, item_id=str(instance.id), exception=e)
+ capture_exception(e)
+ if settings.TEST:
+ raise
+
+
+def log_repo_config_bulk_update(
+ team_id: int,
+ before_rows: list[dict[str, Any]],
+ after_values: dict[str, Any],
+ *,
+ user: "User | None" = None,
+ was_impersonated: bool = False,
+ trigger: Trigger | None = None,
+) -> None:
+ """Log a queryset update of repo configs, which the model signal cannot see.
+
+ `before_rows` holds the rows as the writer had them before the update, each with `id`,
+ `repository`, and the updated fields. `after_values` holds what the update set on all of
+ them. A row whose values did not move produces no log row.
+ """
+ # Same rule as the receiver: the rows are already written, so a failed audit write must not
+ # escape into the caller.
+ try:
+ entries: list[LogActivityEntry] = []
+
+ for row in before_rows:
+ changes = dict_changes_between(
+ "StamphogRepoConfig",
+ previous={field: row.get(field) for field in after_values},
+ new=after_values,
+ )
+ if not changes:
+ continue
+ entries.append(
+ LogActivityEntry(
+ organization_id=None,
+ team_id=team_id,
+ user=user,
+ item_id=row["id"],
+ scope="StamphogRepoConfig",
+ activity="updated",
+ detail=Detail(changes=changes, name=row["repository"], trigger=trigger),
+ was_impersonated=was_impersonated,
+ )
+ )
+
+ if not entries:
+ return
+
+ write_db = router.db_for_write(StamphogRepoConfig)
+
+ def _write_rows() -> None:
+ # One lookup for the batch, and only when there is a row to write.
+ organization_id = _organization_id_for_team(team_id)
+ for entry in entries:
+ entry["organization_id"] = organization_id
+
+ bulk_log_activity(entries, using=write_db)
+
+ _log_after_product_commit(_write_rows, write_db=write_db, team_id=team_id)
+ except Exception as e:
+ logger.warning("stamphog_activity_log_failed", team_id=team_id, exception=e)
+ capture_exception(e)
+ if settings.TEST:
+ raise
+
+
+def installation_webhook_trigger(*, delivery_id: str, action: str, installation_id: str) -> Trigger:
+ """Name the GitHub delivery behind a row a webhook wrote.
+
+ A webhook carries no PostHog user, so its rows are system rows. The trigger is what lets a
+ reader tie a batch of repos back to the one event that touched them.
+ """
+ return Trigger(
+ job_type="github_installation_webhook",
+ job_id=delivery_id,
+ payload={"action": action, "installation_id": installation_id},
+ )
+
+
+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]],
+ *,
+ delivery_id: str,
+ action: str,
+ installation_id: str,
+) -> None:
+ """Log the disable that a GitHub installation webhook applies with one queryset update.
+
+ The row is a system row: a webhook carries no PostHog user. The trigger names the delivery, so
+ a reader can tie every disabled repo back to the one GitHub event that caused it.
+ """
+ log_repo_config_bulk_update(
+ team_id,
+ before_rows,
+ dict.fromkeys(DISABLED_FIELDS, False),
+ trigger=installation_webhook_trigger(delivery_id=delivery_id, action=action, installation_id=installation_id),
+ )
diff --git a/products/stamphog/backend/apps.py b/products/stamphog/backend/apps.py
index b07e8536d3ed..7996921bfed1 100644
--- a/products/stamphog/backend/apps.py
+++ b/products/stamphog/backend/apps.py
@@ -6,3 +6,8 @@ from django.apps import AppConfig
class StamphogConfig(AppConfig):
name = "products.stamphog.backend"
label = "stamphog"
+
+ def ready(self) -> None:
+ # Repo configs are written by webhook Celery tasks too, so the receiver must connect in
+ # every process, not only where the API router is built.
+ from products.stamphog.backend import activity_logging # noqa: F401, PLC0415
diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.py
index c8af510bd082..57c8a526cf47 100644
--- a/products/stamphog/backend/facade/api.py
+++ b/products/stamphog/backend/facade/api.py
@@ -11,7 +11,7 @@ from __future__ import annotations
from collections.abc import Callable, Iterator, Sequence
from typing import Any, TypeVar, overload
-from django.db import IntegrityError
+from django.db import IntegrityError, router, transaction
from django.db.models import Q, QuerySet
from django.utils import timezone
@@ -294,13 +294,21 @@ def update_repo_config(team_id: int, config_id: str, **fields: object) -> contra
fields.pop("provider", None)
fields.pop("repository", None)
fields.pop("installation_id", None)
- obj = StamphogRepoConfig.objects.for_team(team_id).get(id=config_id)
- was_enabled = obj.enabled
- for name, value in fields.items():
- setattr(obj, name, value)
- obj.save()
- if was_enabled and not obj.enabled:
- _supersede_active_runs(team_id, obj)
+ write_db = router.db_for_write(StamphogRepoConfig)
+ # One transaction for the read, the save and the supersede. The row is locked because a save
+ # writes every field: two overlapping PATCHes that each read first would otherwise overwrite
+ # each other from stale objects, and each would log only the change it thinks it made. The
+ # supersede belongs here too, because a caller must never observe a disabled repo whose
+ # in-flight runs are still live, and the activity-log receiver then waits for this commit
+ # rather than running its cross-database write between the two statements.
+ with transaction.atomic(using=write_db):
+ obj = StamphogRepoConfig.objects.for_team(team_id).using(write_db).select_for_update().get(id=config_id)
+ was_enabled = obj.enabled
+ for name, value in fields.items():
+ setattr(obj, name, value)
+ obj.save()
+ if was_enabled and not obj.enabled:
+ _supersede_active_runs(team_id, obj)
return _repo_config_to_dto(obj)
@@ -312,11 +320,14 @@ def disable_repo_config(team_id: int, config_id: str) -> None:
leaving it satisfying required reviews forever. A disabled row keeps webhooks resolvable, and
the disabled-repo skip path retracts standing approvals on the next head change.
"""
- obj = StamphogRepoConfig.objects.for_team(team_id).get(id=config_id)
- obj.enabled = False
- obj.digest_enabled = False
- obj.save(update_fields=["enabled", "digest_enabled", "updated_at"])
- _supersede_active_runs(team_id, obj)
+ write_db = router.db_for_write(StamphogRepoConfig)
+ # Same locked transaction as update_repo_config, for the same reasons.
+ with transaction.atomic(using=write_db):
+ obj = StamphogRepoConfig.objects.for_team(team_id).using(write_db).select_for_update().get(id=config_id)
+ obj.enabled = False
+ obj.digest_enabled = False
+ obj.save(update_fields=["enabled", "digest_enabled", "updated_at"])
+ _supersede_active_runs(team_id, obj)
def _supersede_active_runs(team_id: int, config: StamphogRepoConfig) -> None:
diff --git a/products/stamphog/backend/facade/github.py b/products/stamphog/backend/facade/github.py
index 5f266ff3fc35..89cb5320125a 100644
--- a/products/stamphog/backend/facade/github.py
+++ b/products/stamphog/backend/facade/github.py
@@ -10,9 +10,18 @@ GitHub App auth stack, which must stay off the module review_hog's settings seri
imports on every request.
"""
+from typing import Any
+
from django.db import IntegrityError, router, transaction
from django.utils import timezone
+from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated
+
+from products.stamphog.backend.activity_logging import (
+ log_repo_config_bulk_update,
+ log_repo_configs_created,
+ suppress_created_activity,
+)
from products.stamphog.backend.facade import contracts
from products.stamphog.backend.facade.api import _repo_config_to_dto
from products.stamphog.backend.facade.contracts import StamphogGitHubError
@@ -95,44 +104,88 @@ def sync_installation_repositories(
"""
repositories = list_user_accessible_repositories(installation_id, user_token)
synced: list[StamphogRepoConfig] = []
+ created_rows: list[dict[str, Any]] = []
skipped: list[str] = []
# Bind the per-row savepoint to the model's routed DB (stamphog_db_writer when the product DB is
# configured, else default) — a bare atomic() opens on the default connection, so the get_or_create
# would run outside any transaction on the product DB.
write_db = router.db_for_write(StamphogRepoConfig)
- for full_name in repositories:
- # Per-row savepoint: an IntegrityError only rolls back that row, leaving the rest of the
- # batch (and the outer autocommit context) intact.
- try:
- with transaction.atomic(using=write_db):
- config, _ = StamphogRepoConfig.objects.for_team(team_id).get_or_create(
- provider="github",
- installation_id=installation_id,
- repository=full_name,
- # for_team() scopes the read but not row creation, so team_id is explicit here.
- # Bind disabled: an installation can surface hundreds of repos, so connect them
- # but don't start reviewing until a human toggles each on. enabled only seeds new
- # rows; an existing row's toggle is never flipped.
- defaults={"team_id": team_id, "enabled": False},
- )
- except IntegrityError:
- # The unique (team, repository) constraint tripped: a same-team row for this repo already
- # exists under a different installation_id — the manually-created config (blank
- # installation) finally being bound. Adopt it instead of skipping; only a real conflict
- # (already bound to another installation) stays skipped.
- adopted = _adopt_preexisting_config(team_id, full_name, installation_id)
- if adopted is None:
- skipped.append(full_name)
- else:
- synced.append(adopted)
- continue
- synced.append(config)
-
- # .update() bypasses auto_now, so updated_at is set by hand.
- restamp_ids = [config.id for config in synced if config.connected_by_user_id != connected_by_user_id]
- if restamp_ids:
- StamphogRepoConfig.objects.for_team(team_id).filter(id__in=restamp_ids).update(
- connected_by_user_id=connected_by_user_id, updated_at=timezone.now()
+ # One installation can expose thousands of repositories. Let the loop 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 loop 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():
+ for full_name in repositories:
+ # Per-row savepoint: an IntegrityError only rolls back that row, leaving the rest of the
+ # batch (and the outer autocommit context) intact.
+ try:
+ with transaction.atomic(using=write_db):
+ config, was_created = StamphogRepoConfig.objects.for_team(team_id).get_or_create(
+ provider="github",
+ installation_id=installation_id,
+ repository=full_name,
+ # for_team() scopes the read but not row creation, so team_id is explicit
+ # here. Bind disabled: an installation can surface hundreds of repos, so
+ # connect them but don't start reviewing until a human toggles each on.
+ # enabled only seeds new rows; an existing row's toggle is never flipped.
+ # The connecting user is seeded here too, 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.
+ defaults={
+ "team_id": team_id,
+ "enabled": False,
+ "connected_by_user_id": connected_by_user_id,
+ },
+ )
+ except IntegrityError:
+ # The unique (team, repository) constraint tripped: a same-team row for this repo
+ # already exists under a different installation_id — the manually-created config
+ # (blank installation) finally being bound. Adopt it instead of skipping; only a
+ # real conflict (already bound to another installation) stays skipped.
+ adopted = _adopt_preexisting_config(team_id, full_name, installation_id)
+ if adopted is None:
+ skipped.append(full_name)
+ else:
+ synced.append(adopted)
+ continue
+ synced.append(config)
+ if was_created:
+ created_rows.append({"id": config.id, "repository": config.repository})
+ finally:
+ log_repo_configs_created(
+ team_id, created_rows, user=get_current_user(), was_impersonated=get_was_impersonated()
)
+ if synced:
+ with transaction.atomic(using=write_db):
+ # Lock the rows and re-read the connector rather than trusting the objects above: two
+ # syncs of the same installation running at once both hold the same stale value, so a
+ # real A -> B handover would be logged twice, as C -> A and C -> B.
+ locked = (
+ StamphogRepoConfig.objects.for_team(team_id)
+ .using(write_db)
+ .select_for_update()
+ .filter(id__in=[c.id for c in synced])
+ .values_list("id", "repository", "connected_by_user_id")
+ )
+ restamped: list[dict[str, Any]] = [
+ {"id": row_id, "repository": repository, "connected_by_user_id": connector}
+ for row_id, repository, connector in locked
+ if connector != connected_by_user_id
+ ]
+ if restamped:
+ # .update() bypasses auto_now, so updated_at is set by hand.
+ StamphogRepoConfig.objects.for_team(team_id).filter(id__in=[row["id"] for row in restamped]).update(
+ connected_by_user_id=connected_by_user_id, updated_at=timezone.now()
+ )
+ # update() bypasses the model signal, so the change is logged here.
+ log_repo_config_bulk_update(
+ team_id,
+ restamped,
+ {"connected_by_user_id": connected_by_user_id},
+ user=get_current_user(),
+ was_impersonated=get_was_impersonated(),
+ )
+
return [_repo_config_to_dto(c) for c in synced], skipped
diff --git a/products/stamphog/backend/models.py b/products/stamphog/backend/models.py
index f6caafae2db7..793338507c49 100644
--- a/products/stamphog/backend/models.py
+++ b/products/stamphog/backend/models.py
@@ -12,6 +12,7 @@ from __future__ import annotations
from django.db import models
from django.db.models import Q
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.product_mixin import ProductTeamModel
from posthog.models.utils import uuid7
@@ -28,7 +29,7 @@ from .facade.enums import (
# Lives on a separate product database (see products/db_routing.yaml), so it
# inherits ProductTeamModel: team_id is a plain BigIntegerField (no cross-DB FK
# to Team) and the manager is fail-closed. See posthog/models/scoping/README.md.
-class StamphogRepoConfig(ProductTeamModel):
+class StamphogRepoConfig(ModelActivityMixin, ProductTeamModel):
id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
# SCM provider this config talks to. GitHub is the only implemented provider
# today, but the installation/repository identity is provider-scoped so the
diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.py
index d9b03fc175a4..dae542262e4b 100644
--- a/products/stamphog/backend/tasks/tasks.py
+++ b/products/stamphog/backend/tasks/tasks.py
@@ -22,6 +22,13 @@ from celery import shared_task
from posthog.egress.github.transport import GitHubRateLimitError
from 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.facade.enums import (
TERMINAL_STATUSES,
ReviewMode,
@@ -849,7 +856,9 @@ def _resolve_installation_team_ids(installation_id: str) -> list[int]:
)
-def _add_installation_repos(team_id: int, installation_id: str, repos: list[dict[str, Any]]) -> None:
+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
@@ -872,30 +881,47 @@ def _add_installation_repos(team_id: int, installation_id: str, repos: list[dict
.values_list("connected_by_user_id", flat=True)
.first()
)
- 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):
- 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,
+ 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()
)
- except IntegrityError:
- logger.info("stamphog_installation_repo_add_conflict", repository=full_name, team_id=team_id)
+ 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
+ ),
+ )
def _supersede_runs_for_configs(team_id: int, config_ids: list[Any]) -> None:
@@ -917,27 +943,54 @@ def _supersede_runs_for_configs(team_id: int, config_ids: list[Any]) -> None:
logger.info("stamphog_repo_removal_superseded_runs", team_id=team_id, superseded=superseded)
-def _disable_installation_repos(team_id: int, installation_id: str, repos: list[dict[str, Any]]) -> None:
- """Tombstone configs for repos removed from the installation: disable, keep the rows and history."""
- names = [name for repo in repos if (name := (repo or {}).get("full_name"))]
- if not names:
+def _disable_installation_repos(
+ team_id: int,
+ installation_id: str,
+ *,
+ action: str,
+ delivery_id: str,
+ repository_names: list[str] | None = None,
+) -> None:
+ """Tombstone configs for repos that left the installation: disable, keep the rows and history.
+
+ `repository_names` names the repos that were removed. `None` means every repo of the
+ installation, which is what an uninstall takes away.
+ """
+ if repository_names is not None and not repository_names:
return
- # Writer pin: this lookup gates the disable + supersede side effects; a lagged reader missing a
- # just-restamped row would leave the removed repo's config live and its runs posting.
- config_ids = list(
- StamphogRepoConfig.objects.for_team(team_id)
- .using(router.db_for_write(StamphogRepoConfig))
- .filter(provider="github", installation_id=installation_id, repository__in=names)
- .values_list("id", flat=True)
- )
- # updated_at explicitly: auto_now doesn't fire on queryset update().
- disabled = (
- StamphogRepoConfig.objects.for_team(team_id)
- .filter(id__in=config_ids)
- .update(enabled=False, digest_enabled=False, updated_at=timezone.now())
+ write_db = router.db_for_write(StamphogRepoConfig)
+ # One transaction over the snapshot, the disable and the supersede, with the rows locked: a
+ # concurrent API write between the read and the update would otherwise be logged as this
+ # webhook's change, or lost. Writer pin: a lagged reader missing a just-restamped row would
+ # leave the removed repo's config live and its runs posting. The full rows, not just the ids:
+ # they are the before-state the activity log needs.
+ with transaction.atomic(using=write_db):
+ configs = (
+ StamphogRepoConfig.objects.for_team(team_id)
+ .using(write_db)
+ .select_for_update()
+ .filter(provider="github", installation_id=installation_id)
+ )
+ if repository_names is not None:
+ configs = configs.filter(repository__in=repository_names)
+ before_rows = list(configs.values("id", "repository", *DISABLED_FIELDS))
+ config_ids = [row["id"] for row in before_rows]
+ # updated_at explicitly: auto_now doesn't fire on queryset update().
+ disabled = (
+ StamphogRepoConfig.objects.for_team(team_id)
+ .filter(id__in=config_ids)
+ .update(enabled=False, digest_enabled=False, updated_at=timezone.now())
+ )
+ # Supersede first: an in-flight run must stop before anything that can fail, or a retry
+ # finds it terminal and the approval it posted meanwhile stands.
+ _supersede_runs_for_configs(team_id, config_ids)
+ log_repo_configs_disabled_by_webhook(
+ team_id, before_rows, delivery_id=delivery_id, action=action, installation_id=installation_id
+ )
+ event = (
+ "stamphog_installation_repos_removed" if repository_names is not None else "stamphog_installation_uninstalled"
)
- _supersede_runs_for_configs(team_id, config_ids)
- logger.info("stamphog_installation_repos_removed", installation_id=installation_id, disabled=disabled)
+ logger.info(event, installation_id=installation_id, team_id=team_id, disabled=disabled)
@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)
@@ -987,7 +1040,7 @@ def process_installation_event(payload: dict[str, Any], delivery_id: str) -> Non
added = payload.get("repositories_added") or []
if added:
if len(team_ids) == 1:
- _add_installation_repos(team_ids[0], installation_id, added)
+ _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(
@@ -996,28 +1049,14 @@ def process_installation_event(payload: dict[str, Any], delivery_id: str) -> Non
team_count=len(team_ids),
)
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:
- _disable_installation_repos(team_id, installation_id, removed)
+ _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:
- uninstalled_ids = list(
- StamphogRepoConfig.objects.for_team(team_id)
- .using(router.db_for_write(StamphogRepoConfig))
- .filter(provider="github", installation_id=installation_id)
- .values_list("id", flat=True)
- )
- disabled = (
- StamphogRepoConfig.objects.for_team(team_id)
- .filter(id__in=uninstalled_ids)
- .update(enabled=False, digest_enabled=False, updated_at=timezone.now())
- )
- _supersede_runs_for_configs(team_id, uninstalled_ids)
- logger.info(
- "stamphog_installation_uninstalled",
- installation_id=installation_id,
- team_id=team_id,
- disabled=disabled,
- )
+ _disable_installation_repos(team_id, installation_id, action=action, delivery_id=delivery_id)
else:
logger.info("stamphog_installation_event_ignored", action=action)
except Exception as e:
diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.py
index 8691d2125ed8..e93f1ff783c9 100644
--- a/products/stamphog/backend/tests/test_api.py
+++ b/products/stamphog/backend/tests/test_api.py
@@ -1,12 +1,17 @@
+from typing import Any
+
+import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.core import signing
-from django.test import SimpleTestCase
+from django.db import transaction
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework import status
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.team import Team
from posthog.models.utils import generate_random_token_personal, uuid7
@@ -70,6 +75,43 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert body["provider"] == "github"
assert body["enabled"] is False
+ def test_toggling_enabled_writes_an_activity_log_row(self) -> None:
+ created = self.client.post(self.url, {"repository": "PostHog/posthog", "enabled": True}, format="json").json()
+ # Review history hangs off the config as a reverse relation; the diff must leave it out.
+ PullRequest.objects.create(team_id=self.team.id, repo_config_id=created["id"], pr_number=1)
+ self.client.patch(f"{self.url}{created['id']}/", {"enabled": False}, format="json")
+
+ log = ActivityLog.objects.get(scope="StamphogRepoConfig", item_id=created["id"], activity="updated")
+ assert log.team_id == self.team.id
+ assert log.user == self.user
+ assert log.detail is not None
+ assert log.detail["name"] == "PostHog/posthog"
+ assert log.detail["changes"] == [
+ {"type": "StamphogRepoConfig", "action": "changed", "field": "enabled", "before": True, "after": False}
+ ]
+
+ def test_rolled_back_config_write_leaves_no_activity_row(self) -> None:
+ # Repo configs live on the stamphog database while the audit row lives on the main one, so
+ # the audit write has to ride that connection's commit rather than landing immediately.
+ created = self.client.post(self.url, {"repository": "PostHog/posthog", "enabled": True}, format="json").json()
+ config = StamphogRepoConfig.objects.for_team(self.team.id).get(id=created["id"])
+ updates = ActivityLog.objects.filter(scope="StamphogRepoConfig", item_id=created["id"], activity="updated")
+
+ with override_settings(ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True):
+ with self.captureOnCommitCallbacks(using="stamphog_db_writer", execute=True):
+ with pytest.raises(RuntimeError):
+ with transaction.atomic(using="stamphog_db_writer"):
+ config.enabled = False
+ config.save()
+ raise RuntimeError("the write this audits failed")
+ assert not updates.exists()
+
+ with self.captureOnCommitCallbacks(using="stamphog_db_writer", execute=True):
+ with transaction.atomic(using="stamphog_db_writer"):
+ config.enabled = False
+ config.save()
+ assert updates.exists()
+
def test_blank_installation_does_not_reserve_repo_across_teams(self) -> None:
# A manual placeholder carries a blank installation and proves no ownership, so it must not
# globally reserve a repo. Two teams can each hold their own unsynced placeholder for the same
@@ -150,11 +192,21 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
assert StamphogRepoConfig.objects.unscoped().filter(id=theirs.id).exists()
- def test_delete_soft_disables_as_tombstone(self) -> None:
+ @parameterized.expand(
+ [
+ ("delete", "delete", None, status.HTTP_204_NO_CONTENT),
+ ("patch", "patch", {"enabled": False}, status.HTTP_200_OK),
+ ]
+ )
+ def test_disabling_a_repo_tombstones_supersedes_and_records_it(
+ self, _name: str, method: str, body: dict[str, Any] | None, expected_status: int
+ ) -> None:
# A hard delete would cascade away the PRs and review runs (including posted_review_id), so a
# push to a previously approved PR could no longer resolve the config or dismiss the stale
# approval — deleting a repo must not launder a standing approval. In-flight runs are
# superseded too: their workflows never re-check enabled and could still post an approval.
+ # Both routes disable through the same facade transaction, so both must land the supersede
+ # and the audit row.
mine = StamphogRepoConfig.objects.unscoped().create(
team_id=self.team.id, repository="PostHog/mine", installation_id="3", enabled=True, digest_enabled=True
)
@@ -164,14 +216,20 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):
in_flight = ReviewRun.objects.unscoped().create(
team_id=self.team.id, pull_request=pull_request, head_sha="sha-live", status=ReviewRunStatus.REVIEWING
)
- response = self.client.delete(f"{self.url}{mine.id}/")
- assert response.status_code == status.HTTP_204_NO_CONTENT, response.content
+ response = getattr(self.client, method)(f"{self.url}{mine.id}/", body, format="json")
+ assert response.status_code == expected_status, response.content
mine.refresh_from_db()
in_flight.refresh_from_db()
assert mine.enabled is False
assert mine.digest_enabled is False
assert in_flight.status == ReviewRunStatus.SUPERSEDED
+ log = ActivityLog.objects.get(scope="StamphogRepoConfig", item_id=str(mine.id), activity="updated")
+ assert log.user == self.user
+ assert log.detail is not None
+ enabled_change = next(change for change in log.detail["changes"] if change["field"] == "enabled")
+ assert (enabled_change["before"], enabled_change["after"]) == (True, False)
+
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
@@ -398,6 +456,17 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
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"}
@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories", return_value=["PostHog/posthog"])
@patch(f"{_VIEWS}.user_can_access_installation", return_value=True)
@@ -431,8 +500,13 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
# An uninstall/reinstall cycle mints a new installation id; the old binding is dead (the app
# can only be installed once per repo). Re-syncing the verified new installation must rebind
# the team's existing row instead of skipping it and leaving the repo dead forever.
+ previous_connector_id = 4242
stale = StamphogRepoConfig.objects.unscoped().create(
- team_id=self.team.id, repository="PostHog/posthog", installation_id="41", enabled=True
+ team_id=self.team.id,
+ repository="PostHog/posthog",
+ installation_id="41",
+ enabled=True,
+ connected_by_user_id=previous_connector_id,
)
response = self.client.post(
self.url, {"installation_id": "42", "code": "oauth-code", "state": self.state}, format="json"
@@ -443,6 +517,19 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
stale.refresh_from_db()
assert stale.installation_id == "42"
assert stale.enabled is True # settings survive the rebind
+ assert stale.connected_by_user_id == self.user.id
+ # The restamp reads its before-value from the locked row, so the log names who held the
+ # connection before this sync took it over.
+ updates = ActivityLog.objects.filter(scope="StamphogRepoConfig", item_id=str(stale.id), activity="updated")
+ connector_changes = []
+ for log in updates:
+ assert log.detail is not None
+ connector_changes += [c for c in log.detail["changes"] if c["field"] == "connected_by_user_id"]
+ assert len(connector_changes) == 1
+ assert (connector_changes[0]["before"], connector_changes[0]["after"]) == (
+ previous_connector_id,
+ self.user.id,
+ )
@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories")
@patch(f"{_VIEWS}.user_can_access_installation", return_value=False)
diff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.py
index f9eead42efe9..7a794c4f36aa 100644
--- a/products/stamphog/backend/tests/test_tasks.py
+++ b/products/stamphog/backend/tests/test_tasks.py
@@ -9,6 +9,7 @@ from django.core.cache import cache
from django.utils.dateparse import parse_datetime
from posthog.models import Project, Team
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.instance_setting import override_instance_config
from posthog.models.scoping import team_scope
@@ -700,6 +701,18 @@ def test_installation_repos_added_creates_disabled_rows_and_skips_existing(team,
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"
+
@pytest.mark.parametrize(
"payload_kwargs,expect_disabled",
@@ -769,6 +782,13 @@ def test_installation_uninstall_tombstones_every_owning_team(team, repo_config):
with team_scope(team.id):
repo_config.digest_enabled = True
repo_config.save()
+ dormant_config = StamphogRepoConfig.objects.create(
+ team_id=team.id,
+ repository="acme/dormant",
+ installation_id=INSTALLATION_ID,
+ enabled=False,
+ digest_enabled=False,
+ )
process_installation_event(_installation_payload(action="deleted"), "delivery-multi-uninstall")
@@ -779,6 +799,21 @@ def test_installation_uninstall_tombstones_every_owning_team(team, repo_config):
assert (repo_config.enabled, repo_config.digest_enabled) == (False, False)
assert (second_config.enabled, second_config.digest_enabled) == (False, False)
+ # The uninstall runs as a queryset update, which the model signal cannot see, so the task logs
+ # it by hand. No PostHog user is behind a webhook, so each row is a system row, and the already
+ # disabled config moved nothing and gets no row.
+ logs = list(ActivityLog.objects.filter(detail__trigger__job_id="delivery-multi-uninstall"))
+ assert {log.item_id for log in logs} == {str(repo_config.id), str(second_config.id)}
+ assert str(dormant_config.id) not in {log.item_id for log in logs}
+ for log in logs:
+ assert log.scope == "StamphogRepoConfig"
+ assert log.activity == "updated"
+ assert log.user is None
+ assert log.is_system is True
+ assert log.detail is not None
+ enabled_change = next(change for change in log.detail["changes"] if change["field"] == "enabled")
+ assert (enabled_change["before"], enabled_change["after"]) == (True, False)
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_installation_repos_added_skips_when_installation_spans_multiple_teams(team, repo_config):
diff --git a/products/stamphog/frontend/activityDescriber.tsx b/products/stamphog/frontend/activityDescriber.tsx
new file mode 100644
index 000000000000..56cef0bcc2b6
--- /dev/null
+++ b/products/stamphog/frontend/activityDescriber.tsx
@@ -0,0 +1,96 @@
+import {
+ ActivityChange,
+ ActivityLogItem,
+ Description,
+ HumanizedChange,
+ defaultDescriber,
+ userNameForLogItem,
+} from 'lib/components/ActivityLog/humanizeActivity'
+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
+
+import { ReviewModeEnumApi } from './generated/api.schemas'
+import { REVIEW_MODE_LABELS } from './reviewModeLabels'
+
+// A GitHub installation webhook writes a system row, so the actor reads "PostHog". Say which
+// GitHub event caused it, or the reader cannot tell why reviews stopped.
+const WEBHOOK_REASON: Record<string, string> = {
+ removed: 'after GitHub removed it from the installation',
+ deleted: 'after the GitHub app was uninstalled',
+}
+
+// Sentences leave out the repository name: it is appended once, after the whole list.
+function repoConfigFieldCopy(change: ActivityChange): Description | null {
+ switch (change.field) {
+ case 'enabled':
+ return change.after ? <>turned reviews on</> : <>turned reviews off</>
+ case 'digest_enabled':
+ return change.after ? <>turned the digest on</> : <>turned the digest off</>
+ case 'review_mode': {
+ const mode = String(change.after)
+ return (
+ <>
+ changed the review mode to <strong>{REVIEW_MODE_LABELS[mode as ReviewModeEnumApi] ?? mode}</strong>
+ </>
+ )
+ }
+ case 'trigger_label':
+ return (
+ <>
+ changed the trigger label to <strong>{String(change.after)}</strong>
+ </>
+ )
+ case 'installation_id':
+ return <>connected a new GitHub installation</>
+ case 'connected_by_user_id':
+ return <>became the connecting user</>
+ default:
+ return null
+ }
+}
+
+export function stamphogRepoConfigActivityDescriber(
+ logItem: ActivityLogItem,
+ asNotification?: boolean
+): HumanizedChange {
+ if (logItem.scope !== 'StamphogRepoConfig') {
+ console.error('stamphog describer received a non-repo-config activity')
+ return { description: null }
+ }
+
+ const actor = <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>
+ const repository = <strong>{logItem.detail.name || 'a repository'}</strong>
+
+ if (logItem.activity === 'created') {
+ // A row created through the API has no installation until a sync binds it.
+ const verb = logItem.detail.type === 'connected' ? 'connected' : 'added'
+ return {
+ description: (
+ <>
+ {actor} {verb} {repository}
+ </>
+ ),
+ }
+ }
+
+ const parts = (logItem.detail.changes || []).map(repoConfigFieldCopy).filter(Boolean) as Description[]
+ if (logItem.activity !== 'updated' || parts.length === 0) {
+ return defaultDescriber(logItem, asNotification, repository)
+ }
+
+ const webhookAction = logItem.detail.trigger?.payload?.action
+ const reason = typeof webhookAction === 'string' ? WEBHOOK_REASON[webhookAction] : undefined
+ return {
+ description: (
+ <SentenceList
+ listParts={parts}
+ prefix={actor}
+ suffix={
+ <>
+ for {repository}
+ {reason ? ` ${reason}` : null}
+ </>
+ }
+ />
+ ),
+ }
+}
diff --git a/products/stamphog/frontend/reviewModeLabels.ts b/products/stamphog/frontend/reviewModeLabels.ts
new file mode 100644
index 000000000000..5d315b2423d5
--- /dev/null
+++ b/products/stamphog/frontend/reviewModeLabels.ts
@@ -0,0 +1,7 @@
+import { ReviewModeEnumApi } from './generated/api.schemas'
+
+// The repo settings and the activity log both name the review mode, so they read from one map.
+export const REVIEW_MODE_LABELS: Record<ReviewModeEnumApi, string> = {
+ [ReviewModeEnumApi.All]: 'All PRs',
+ [ReviewModeEnumApi.Label]: 'Label-triggered',
+}
diff --git a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
index 69a9de5f9805..9b2f5de992e0 100644
--- a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
+++ b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
@@ -12,6 +12,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { StamphogTabs } from '../../components/StamphogTabs'
import { ReviewModeEnumApi, type StamphogRepoConfigApi } from '../../generated/api.schemas'
+import { REVIEW_MODE_LABELS } from '../../reviewModeLabels'
import { stamphogSceneLogic } from './stamphogSceneLogic'
export const scene: SceneExport = {
@@ -137,8 +138,8 @@ function ReviewModeCell({ repo, updating }: { repo: StamphogRepoConfigApi; updat
disabledReason={updating ? 'Updating' : undefined}
onChange={(mode) => setReviewMode(repo.id, mode)}
options={[
- { value: ReviewModeEnumApi.All, label: 'All PRs' },
- { value: ReviewModeEnumApi.Label, label: 'Label-triggered' },
+ { value: ReviewModeEnumApi.All, label: REVIEW_MODE_LABELS[ReviewModeEnumApi.All] },
+ { value: ReviewModeEnumApi.Label, label: REVIEW_MODE_LABELS[ReviewModeEnumApi.Label] },
]}
/>
{repo.review_mode === ReviewModeEnumApi.Label && (
diff --git a/products/stamphog/manifest.tsx b/products/stamphog/manifest.tsx
index 4a9bcf27ec1a..4bc85fa374bf 100644
--- a/products/stamphog/manifest.tsx
+++ b/products/stamphog/manifest.tsx
@@ -15,6 +15,7 @@ export const manifest: ProductManifest = {
projectBased: true,
name: 'Stamphog',
iconType: 'stamphog',
+ activityScope: 'StamphogRepoConfig',
},
StamphogRuns: {
import: () => import('./frontend/scenes/StamphogRunsScene/StamphogRunsScene'),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index acd905707cdc..074f0f47726d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -91084,6 +91084,7 @@ export namespace Schemas {
* * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
+ * * `StamphogRepoConfig` - StamphogRepoConfig
* @minLength 1
*/
scope?: ActivityLogListScope;
@@ -91181,6 +91182,7 @@ export namespace Schemas {
DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
+ StamphogRepoConfig: 'StamphogRepoConfig',
} as const;
/**
@@ -91264,6 +91266,7 @@ export namespace Schemas {
* * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
+ * * `StamphogRepoConfig` - StamphogRepoConfig
*/
export type ActivityLogListScopesItem = typeof ActivityLogListScopesItem[keyof typeof ActivityLogListScopesItem];
@@ -91349,6 +91352,7 @@ export namespace Schemas {
DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
+ StamphogRepoConfig: 'StamphogRepoConfig',
} as const;
export type AdvancedActivityLogsListParams = {