: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
fix(signals): close the remaining scout lifecycle lock bypasses (#115256)
posthog[bot]2ef26e00f434
diff --git a/products/signals/backend/apps.py b/products/signals/backend/apps.pyindex 523699942863..b69a6065b290 100644--- a/products/signals/backend/apps.py+++ b/products/signals/backend/apps.py@@ -25,6 +25,7 @@ class SignalsConfig(AppConfig):receivers.connect_task_run_assignment_sync()self._register_signal_emission_gate()self._register_scout_skill_archive_guard()+ self._register_scout_skill_rename_hook()def _register_signal_emission_gate(self) -> None:"""Let the data-import pipeline ask whether to emit signals for a source without@@ -60,3 +61,29 @@ class SignalsConfig(AppConfig):raise SkillArchiveRefused(str(err)) from errregister_skill_archive_guard(_guard)++ def _register_scout_skill_rename_hook(self) -> None:+ """Let the skills product move or refuse a scout's config on rename without importing this one."""+ from products.skills.backend.api.archive_guards import (+ SkillRenameConflict,+ SkillRenameRefused,+ register_skill_rename_hook,+ )++ def _hook(team: "Team", skill_name: str, new_name: str, user: "User | None", authenticator: object) -> None:+ from products.signals.backend.scout_harness.lifecycle_lock import ( # noqa: PLC0415+ ScoutConfigNameTaken,+ ScoutLifecycleLocked,+ rename_scout_with_skill,+ )++ try:+ rename_scout_with_skill(+ team=team, skill_name=skill_name, new_name=new_name, user=user, authenticator=authenticator+ )+ except ScoutLifecycleLocked as err:+ raise SkillRenameRefused(str(err)) from err+ except ScoutConfigNameTaken as err:+ raise SkillRenameConflict(str(err)) from err++ register_skill_rename_hook(_hook)diff --git a/products/signals/backend/scout_harness/lifecycle_lock.py b/products/signals/backend/scout_harness/lifecycle_lock.pyindex 66474c2e07ae..297b603ed9ed 100644--- a/products/signals/backend/scout_harness/lifecycle_lock.py+++ b/products/signals/backend/scout_harness/lifecycle_lock.py@@ -15,6 +15,8 @@ scout's skill stops the scout just as surely as deleting its config does.from collections.abc import Mapping+from django.db.models import Subquery+import structlogfrom prometheus_client import Counter@@ -25,7 +27,8 @@ from posthog.models.user import Userfrom posthog.user_permissions import UserPermissionsfrom products.signals.backend.models import SignalScoutConfig-from products.signals.backend.scout_harness.skill_loader import resolve_scout_acting_user_id+from products.signals.backend.scout_harness.skill_loader import earliest_member_author_id, resolve_scout_acting_user_id+from products.skills.backend.models.skills import LLMSkilllogger = structlog.get_logger(__name__)@@ -48,6 +51,10 @@ class ScoutLifecycleLocked(Exception):"""+class ScoutConfigNameTaken(Exception):+ """A skill rename would move a scout's config onto a name another config already holds."""++def resolve_auth_kind(authenticator: object) -> str:"""How a caller authenticated, as a bounded metric label.@@ -87,6 +94,25 @@ def lock_protected_changes(requested: object, *, config: SignalScoutConfig | Nonreturn changed if config.lifecycle_locked or "lifecycle_locked" in changed else []+def resolve_scout_lifecycle_owner_id(team: Team, skill_name: str, config: SignalScoutConfig) -> int | None:+ """The person the lock protects: the acting user, also after the skill is archived.++ The delete flow archives the skill before it deletes the config. The acting-user lookup reads+ live versions only, so without this fallback the skill author loses the claim between the two+ steps and gets a refusal for their own scout. Only the most recent archive counts: an archive+ stamps one `updated_at` on every version it tombstones, and an older skill that once used the+ name must not give its author the claim.+ """+ if LLMSkill.objects.filter(team=team, name=skill_name, deleted=False).exists():+ return resolve_scout_acting_user_id(team, skill_name, config)+ archived = LLMSkill.objects.filter(team=team, name=skill_name, deleted=True)+ last_archive = archived.filter(updated_at=Subquery(archived.order_by("-updated_at").values("updated_at")[:1]))+ archived_author_id = earliest_member_author_id(team, last_archive)+ if archived_author_id is not None:+ return archived_author_id+ return resolve_scout_acting_user_id(team, skill_name, config)++def user_holds_scout_lifecycle_claim(*,team: Team,@@ -103,7 +129,7 @@ def user_holds_scout_lifecycle_claim(level = UserPermissions(user=user, team=team).current_team.effective_membership_levelif level is not None and level >= OrganizationMembership.Level.ADMIN:return True- return resolve_scout_acting_user_id(team, skill_name, config) == user.pk+ return resolve_scout_lifecycle_owner_id(team, skill_name, config) == user.pkdef record_lifecycle_refusal(@@ -128,6 +154,33 @@ def record_lifecycle_refusal()+def _refuse_without_claim(+ *,+ team: Team,+ skill_name: str,+ config: SignalScoutConfig,+ user: User,+ authenticator: object,+ action: str,+ verb: str,+) -> None:+ """Raise `ScoutLifecycleLocked` for a locked scout unless the caller holds its claim."""+ if not config.lifecycle_locked:+ return+ if user_holds_scout_lifecycle_claim(team=team, skill_name=skill_name, config=config, user=user):+ return+ record_lifecycle_refusal(+ team=team,+ skill_name=skill_name,+ action=action,+ auth_kind=resolve_auth_kind(authenticator),+ user_id=user.pk,+ )+ raise ScoutLifecycleLocked(+ f"This scout is locked, so only the person its runs act as or a project admin can {verb} it."+ )++def assert_can_archive_scout_skill(*,team: Team,@@ -145,17 +198,54 @@ def assert_can_archive_scout_skill("""scoped_team = canonical_team(team)config = SignalScoutConfig.objects.for_team(scoped_team.id).filter(skill_name=skill_name).first()- if config is None or not config.lifecycle_locked:- return- if user_holds_scout_lifecycle_claim(team=scoped_team, skill_name=skill_name, config=config, user=user):+ if config is None:return- record_lifecycle_refusal(+ _refuse_without_claim(team=scoped_team,skill_name=skill_name,+ config=config,+ user=user,+ authenticator=authenticator,action="archive_skill",- auth_kind=resolve_auth_kind(authenticator),- user_id=user.pk,- )- raise ScoutLifecycleLocked(- "This scout is locked, so only the person its runs act as or a project admin can delete it."+ verb="delete",)+++def rename_scout_with_skill(+ *,+ team: Team,+ skill_name: str,+ new_name: str,+ user: User | None,+ authenticator: object = None,+) -> None:+ """Move a scout's config to its skill's new name, behind the same gate as archiving.++ The config is keyed on the skill name. A rename that left it behind would orphan the config+ and stop the scout, so a rename removes a scout as surely as an archive does. Call it inside+ the rename transaction, before the skill rows move: the owner lookup reads the old name.++ A no-op for a skill that is not a scout. A caller with no acting user is a system path, so it+ is not gated.+ """+ scoped_team = canonical_team(team)+ configs = SignalScoutConfig.objects.for_team(scoped_team.id)+ config = configs.select_for_update().filter(skill_name=skill_name).first()+ if config is None:+ return+ if user is not None:+ _refuse_without_claim(+ team=scoped_team,+ skill_name=skill_name,+ config=config,+ user=user,+ authenticator=authenticator,+ action="rename_skill",+ verb="rename",+ )+ if configs.filter(skill_name=new_name).exists():+ raise ScoutConfigNameTaken(+ "Another scout config already uses this name. Delete that config or pick another name."+ )+ config.skill_name = new_name+ config.save(update_fields=["skill_name", "updated_at"])diff --git a/products/signals/backend/scout_harness/skill_loader.py b/products/signals/backend/scout_harness/skill_loader.pyindex a5cec5c81818..7de6e764bb67 100644--- a/products/signals/backend/scout_harness/skill_loader.py+++ b/products/signals/backend/scout_harness/skill_loader.py@@ -4,7 +4,7 @@ from dataclasses import dataclassfrom datetime import datetimefrom typing import TYPE_CHECKING, Literal-from django.db.models import Max, Min+from django.db.models import Max, Min, QuerySetfrom posthog.models.team.team import Team@@ -176,6 +176,16 @@ def resolve_skill_owner_user_uuids(team: Team, skill_name: str) -> list[str]:]+def earliest_member_author_id(team: Team, versions: QuerySet[LLMSkill]) -> int | None:+ """The author of the earliest version in `versions` who is still an active member of `team`."""+ return (+ versions.filter(created_by__isnull=False, created_by__in=team.all_users_with_access())+ .order_by("created_at", "id")+ .values_list("created_by_id", flat=True)+ .first()+ )++def resolve_scout_acting_user_id(team: Team, skill_name: str, config: SignalScoutConfig | None) -> int | None:"""User id a scout run acts as, which is also where its AI spend is attributed.@@ -196,18 +206,7 @@ def resolve_scout_acting_user_id(team: Team, skill_name: str, config: SignalScoumints a sandbox token as this user. Returns None when no path resolves a member; the runnerthen falls back to the team-level default (`resolve_acting_user_id_for_team`)."""- creator_id = (- LLMSkill.objects.filter(- team=team,- name=skill_name,- deleted=False,- created_by__isnull=False,- created_by__in=team.all_users_with_access(),- )- .order_by("created_at", "id")- .values_list("created_by_id", flat=True)- .first()- )+ creator_id = earliest_member_author_id(team, LLMSkill.objects.filter(team=team, name=skill_name, deleted=False))if creator_id is not None:return creator_idif config is None:diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 7730eeb74e37..4ef72e999e7a 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -3170,12 +3170,17 @@ def guard_scout_lifecycle_fields(requested: object,action: str,) -> None:- """Apply the lock gate to a write body. A no-op unless the body changes a protected field."""- fields = lock_protected_changes(requested, config=config)- if config is None or not fields:+ """Apply the lock gate to a write body. A no-op unless the body changes a protected field.++ With no config yet, the gate checks the row the write would create. So a lock set at+ registration asks for the same claim as a lock set afterwards.+ """+ target = config or SignalScoutConfig(team_id=team.id, skill_name=skill_name, created_by=cast(User, request.user))+ fields = lock_protected_changes(requested, config=target)+ if not fields:returnassert_can_change_scout_lifecycle(- request=request, team=team, skill_name=skill_name, config=config, action=action, fields=fields+ request=request, team=team, skill_name=skill_name, config=target, action=action, fields=fields)diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 093fc7c505ae..955b5b2ab0c7 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -1979,6 +1979,64 @@ class TestScoutHarnessConfigLifecycleLockAPI(APIBaseTest):assert response.status_code == status.HTTP_204_NO_CONTENT, response.contentassert not LLMSkill.objects.filter(name="not-a-scout", deleted=False).exists()+ @parameterized.expand(+ [+ ("scout_author", True, status.HTTP_201_CREATED),+ ("plain_member", False, status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_registering_a_locked_config_needs_the_acting_user_or_an_admin(+ self, _name: str, is_author: bool, expected: int+ ) -> None:+ self._authored_by(self.user if is_author else self._other_member())++ response = self.client.post(+ self._list_url(),+ data={"skill_name": "signals-scout-hygiene", "enabled": False, "lifecycle_locked": True},+ format="json",+ )++ assert response.status_code == expected, response.json()+ assert SignalScoutConfig.objects.filter(skill_name="signals-scout-hygiene").exists() is (+ expected == status.HTTP_201_CREATED+ )++ @parameterized.expand(+ [+ ("scout_author", True, status.HTTP_200_OK),+ ("plain_member", False, status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_renaming_a_locked_scouts_skill_needs_the_acting_user_and_moves_the_config(+ self, _name: str, is_author: bool, expected: int+ ) -> None:+ author = self.user if is_author else self._other_member()+ LLMSkill.objects.create(team=self.team, name="custom-watch", description="", body="", created_by=author)+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="custom-watch", lifecycle_locked=True)++ response = self.client.post(+ f"/api/projects/{self.team.id}/llm_skills/name/custom-watch/rename",+ data={"new_name": "custom-watch-renamed"},+ format="json",+ )++ assert response.status_code == expected, response.content+ config.refresh_from_db()+ renamed = expected == status.HTTP_200_OK+ assert config.skill_name == ("custom-watch-renamed" if renamed else "custom-watch")+ assert LLMSkill.objects.filter(name="custom-watch-renamed", deleted=False).exists() is renamed++ def test_the_owner_deletes_a_locked_scout_after_archiving_its_skill(self) -> None:+ config = self._config(lifecycle_locked=True, created_by=self._other_member())+ self._authored_by(self.user)++ archive = self.client.post(self._archive_url())+ destroy = self.client.delete(self._detail_url(str(config.id)))++ assert archive.status_code == status.HTTP_204_NO_CONTENT, archive.content+ assert destroy.status_code == status.HTTP_204_NO_CONTENT, destroy.content+ assert not SignalScoutConfig.objects.filter(id=config.id).exists()+def test_the_owner_locks_the_scout_and_the_read_surfaces_it(self) -> None:# Wiring guard: the flag has to round-trip through the update serializer and the read# shape, or the settings UI cannot show or set the lock at all.diff --git a/products/skills/backend/api/archive_guards.py b/products/skills/backend/api/archive_guards.pyindex 9b6f33a43fff..19abf026882d 100644--- a/products/skills/backend/api/archive_guards.py+++ b/products/skills/backend/api/archive_guards.py@@ -1,4 +1,4 @@-"""Hook inversion for skill archival, so another product can refuse one.+"""Hook inversion for skill archival and rename, so another product can refuse one.Archiving is permanent — there is no unarchive endpoint — and a skill can be the definitionanother product runs. That product knows when removing it is not the caller's call to make, but@@ -7,6 +7,10 @@ which siblings fill during ``django.setup()`` (in ``AppConfig.ready()``).Signals registers the only guard today: a scout that locked its lifecycle refuses to be archivedby anyone but the person its runs act as, or a project admin.++A rename gets the same treatment, because another product can key its rows on the skill name.+A rename hook runs inside the rename transaction, before the skill rows move. It can refuse the+rename, or move its own rows to the new name in the same transaction."""from collections.abc import Callable@@ -47,3 +51,35 @@ def assert_skill_archive_allowed(returnfor guard in _archive_guards:guard(team, skill_name, user, authenticator)+++class SkillRenameRefused(Exception):+ """A registered rename hook refused this rename. Carries the message to show the caller."""+++class SkillRenameConflict(Exception):+ """A registered rename hook found its own rows already under the new name."""+++# (team, skill_name, new_name, user, authenticator) -> None, raising SkillRenameRefused or+# SkillRenameConflict to stop the rename. `user` is None for a system path.+SkillRenameHook = Callable[[Team, str, str, User | None, object], None]++_rename_hooks: list[SkillRenameHook] = []+++def register_skill_rename_hook(fn: SkillRenameHook) -> None:+ _rename_hooks.append(fn)+++def run_skill_rename_hooks(+ *,+ team: Team,+ skill_name: str,+ new_name: str,+ user: User | None,+ authenticator: object = None,+) -> None:+ """Run every registered rename hook. Call it inside the rename transaction."""+ for hook in _rename_hooks:+ hook(team, skill_name, new_name, user, authenticator)diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.pyindex adb44c04d44c..47b39a43c36d 100644--- a/products/skills/backend/api/skill_services.py+++ b/products/skills/backend/api/skill_services.py@@ -20,7 +20,7 @@ from ..models.skills import (annotate_llm_skill_version_history_metadata,category_for_skill_name,)-from .archive_guards import assert_skill_archive_allowed+from .archive_guards import assert_skill_archive_allowed, run_skill_rename_hooks_DigestModel = TypeVar("_DigestModel", LLMSkill, LLMSkillFile)@@ -898,16 +898,17 @@ def rename_skill_file(return _refresh_with_annotations(team, next_skill)-def archive_skill(team: Team, skill_name: str, *, acting_user: User | None) -> list[int]:+def archive_skill(team: Team, skill_name: str, *, acting_user: User | None, authenticator: object = None) -> list[int]:"""Tombstone every version of a logical skill.`acting_user` is the person asking, or None for a system path. It is keyword-only and has nodefault so a new caller has to say which it is: a guard can refuse the archive (see- `archive_guards`), and a silent default would let a fresh entrypoint skip that.+ `archive_guards`), and a silent default would let a fresh entrypoint skip that. An endpoint+ passes its DRF `authenticator` too, so a refusal records how the caller signed in."""with transaction.atomic():# Before the select_for_update below, so a refusal costs no row locks.- assert_skill_archive_allowed(team=team, skill_name=skill_name, user=acting_user)+ assert_skill_archive_allowed(team=team, skill_name=skill_name, user=acting_user, authenticator=authenticator)skill_versions = list(LLMSkill.objects.select_for_update().filter(team=team, name=skill_name, deleted=False)@@ -935,12 +936,21 @@ def _product_owned_name_prefix(name: str) -> str:return next((prefix for prefix, _ in CATEGORY_BY_NAME_PREFIX if name.startswith(prefix)), "")-def rename_skill(team: Team, *, skill_name: str, new_name: str) -> LLMSkill:+def rename_skill(+ team: Team,+ *,+ skill_name: str,+ new_name: str,+ acting_user: User | None,+ authenticator: object = None,+) -> LLMSkill:"""Move a logical skill to `new_name`, keeping its versions, files, and owners.Every version row carries the name, and owners are keyed on `(team, skill_name)`, so the renamehas to move all of them together or it loses history and ownership — which is exactly what the- duplicate-then-archive workaround did.+ duplicate-then-archive workaround did. Rows another product keys on the name move through its+ rename hook (see `archive_guards`), which can also refuse the rename. `acting_user` has no+ default for the same reason as on `archive_skill`."""blocked_prefix = _product_owned_name_prefix(skill_name) or _product_owned_name_prefix(new_name)if blocked_prefix:@@ -958,6 +968,9 @@ def rename_skill(team: Team, *, skill_name: str, new_name: str) -> LLMSkill:return _renamed_skill_or_missing(team, new_name)if LLMSkill.objects.filter(team=team, name=new_name, deleted=False).exists():raise LLMSkillDuplicateNameConflictError()+ run_skill_rename_hooks(+ team=team, skill_name=skill_name, new_name=new_name, user=acting_user, authenticator=authenticator+ )# Stamp each locked row rather than issuing one `.update()`: the name is the first# frontmatter key of the rendered SKILL.md, so a rename changes the bytes a host downloads,diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 1de72c093f4e..6d017cd72354 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -76,7 +76,7 @@ from ..marketplace.packaging import ()from ..models.community_skills import CommunitySkillKindfrom ..models.skills import SCOUT_SKILL_CATEGORY, LLMSkill, LLMSkillFile-from .archive_guards import SkillArchiveRefused+from .archive_guards import SkillArchiveRefused, SkillRenameConflict, SkillRenameRefusedfrom .community_publish_services import (CommunitySkillPublishError,CommunitySkillPublishNotConfiguredError,@@ -1653,7 +1653,12 @@ class LLMSkillViewSet(return access_errortry:- skill_versions = archive_skill(self.team, skill_name, acting_user=cast(User, request.user))+ skill_versions = archive_skill(+ self.team,+ skill_name,+ acting_user=cast(User, request.user),+ authenticator=request.successful_authenticator,+ )except SkillArchiveRefused as err:# A sibling product owns what this skill runs and says this caller may not remove it.return Response({"detail": str(err)}, status=status.HTTP_403_FORBIDDEN)@@ -1746,7 +1751,15 @@ class LLMSkillViewSet()return Response(self._serialize_skill(new_skill), status=status.HTTP_201_CREATED)- @extend_schema(request=LLMSkillRenameSerializer, responses={200: LLMSkillSerializer})+ @extend_schema(+ request=LLMSkillRenameSerializer,+ responses={+ 200: LLMSkillSerializer,+ 403: OpenApiResponse(+ description="Another product owns what this skill runs and refuses this caller's rename."+ ),+ },+ )@action(methods=["POST"],detail=False,@@ -1769,7 +1782,17 @@ class LLMSkillViewSet(new_name = payload.validated_data["new_name"]try:- renamed_skill = rename_skill(self.team, skill_name=skill_name, new_name=new_name)+ renamed_skill = rename_skill(+ self.team,+ skill_name=skill_name,+ new_name=new_name,+ acting_user=cast(User, request.user),+ authenticator=request.successful_authenticator,+ )+ except SkillRenameRefused as err:+ return Response({"detail": str(err)}, status=status.HTTP_403_FORBIDDEN)+ except SkillRenameConflict as err:+ raise serializers.ValidationError({"new_name": str(err)}, code="unique")except LLMSkillNotFoundError:return self._skill_not_found_response(skill_name)except LLMSkillDuplicateNameConflictError: