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(signals): attribute scout runs to the skill creator or first owner (#83341)

Andrew Maguirec5beb4e03cba
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index af277494e677..0258f1dc238b 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -47,6 +47,7 @@ from products.signals.backend.scout_harness.skill_loader import (
LoadedSkill,
load_skill_for_run,
resolve_report_channel_variant,
+ resolve_scout_acting_user_id,
skill_uses_report_channel,
)
from products.signals.backend.scout_harness.team_limits import github_read_access_for_team, withheld_skills_for_team
@@ -244,14 +245,21 @@ async def arun_signals_scout(
skip_reason="prior run still in progress",
)
- # Resolve the acting user up front. Scouts don't clone a repo on the cadence path, so they
- # don't need a GitHub integration — `resolve_acting_user_id_for_team` prefers the GitHub
- # creator when present but falls back to any active org member, so a team that never connected
- # GitHub still runs (these dominated the fleet failure rate when the run instead crashed ~5s
- # into `_spawn_and_run` and booked a bogus `failed`). The only remaining short-circuit is the
- # genuine "no active user to act as" case; like the withheld / in-flight skips it leaves no
- # row, no lifecycle event, and a `skip_reason` the coordinator can surface — not a failure.
- user_id = await database_sync_to_async(resolve_acting_user_id_for_team, thread_sensitive=False)(team.id)
+ # Resolve the acting user up front: the skill's creator (else the config's enabler/creator)
+ # when one resolves, so a scout's runs, and the AI spend attributed off the task row, land on
+ # the human who authored or enabled the scout instead of pooling on one team-level default
+ # user. Scouts don't clone a repo on the cadence path, so they don't need a GitHub integration
+ # — the `resolve_acting_user_id_for_team` fallback prefers the GitHub creator when present but
+ # falls back to any active org member, so a team that never connected GitHub still runs (these
+ # dominated the fleet failure rate when the run instead crashed ~5s into `_spawn_and_run` and
+ # booked a bogus `failed`). The only remaining short-circuit is the genuine "no active user to
+ # act as" case; like the withheld / in-flight skips it leaves no row, no lifecycle event, and
+ # a `skip_reason` the coordinator can surface — not a failure.
+ user_id = await database_sync_to_async(resolve_scout_acting_user_id, thread_sensitive=False)(
+ team, skill.name, config
+ )
+ if user_id is None:
+ user_id = await database_sync_to_async(resolve_acting_user_id_for_team, thread_sensitive=False)(team.id)
if user_id is None:
logger.info(
"signals_scout: skipping run, no active user to act as for team",
diff --git a/products/signals/backend/scout_harness/skill_loader.py b/products/signals/backend/scout_harness/skill_loader.py
index 6333e2945d8d..a9936059c604 100644
--- a/products/signals/backend/scout_harness/skill_loader.py
+++ b/products/signals/backend/scout_harness/skill_loader.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from django.db.models import Max, Min
@@ -10,6 +10,9 @@ from posthog.models.team.team import Team
from products.skills.backend.models.skills import LLMSkill, LLMSkillFile, LLMSkillOwner
+if TYPE_CHECKING:
+ from products.signals.backend.models import SignalScoutConfig
+
# Naming contract for skills that steer a Signals-agent run.
SIGNALS_SCOUT_SKILL_PREFIX = "signals-scout-"
@@ -132,6 +135,49 @@ def resolve_skill_owner_user_uuids(team: Team, skill_name: str) -> list[str]:
]
+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.
+
+ The version-history creator (earliest version row with a known author) wins: they wrote the
+ prompt the run executes, so acting as them mirrors how user-triggered runs act as the
+ triggering user. For skills with no attributable version author, such as a pristine canonical
+ scout whose seeded versions are all system-authored, the fallback is the config's `enabled_by`
+ (who last switched the scout on) and then its `created_by`, both stamped server-side from the
+ authenticated requester, so each candidate identity took the enabling action themselves.
+
+ Every identity source here must be self-consenting or editor-proof. `LLMSkillOwner` is
+ deliberately NOT one: any skill editor can rewrite the owner list without publishing a
+ version, so consulting it would let an editor choose which teammate's identity the run mints
+ (the same escalation `auto_start._resolve_autostart_assignee` excludes owner-provenance
+ reviewers for).
+
+ Every path restricts to `team.all_users_with_access()` (active members only), because the run
+ mints a sandbox token as this user. Returns None when no path resolves a member; the runner
+ then 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()
+ )
+ if creator_id is not None:
+ return creator_id
+ if config is None:
+ return None
+ candidate_ids = [user_id for user_id in (config.enabled_by_id, config.created_by_id) if user_id is not None]
+ if not candidate_ids:
+ return None
+ members = set(team.all_users_with_access().filter(id__in=candidate_ids).values_list("id", flat=True))
+ return next((user_id for user_id in candidate_ids if user_id in members), None)
+
+
def _skill_has_owner_rows(team: Team, skill_name: str) -> bool:
"""Whether the logical skill has any owner rows at all — including owners who lost access.
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index c2b9ee262efc..6fe34f650a1e 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -55,6 +55,7 @@ from products.signals.backend.scout_harness.skill_loader import (
SkillNotFoundError,
is_signals_scout_skill,
load_skill_for_run,
+ resolve_scout_acting_user_id,
)
from products.signals.backend.scout_harness.tools.runs import _build_task_url, _to_detail, _to_summary
from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, run_signals_scout_activity
@@ -276,6 +277,60 @@ class TestSkillLoader(BaseTest):
loaded = load_skill_for_run(self.team, "signals-scout-errors", include_authors=True)
assert loaded.authors == []
+ def _create_config(self, **kwargs) -> SignalScoutConfig:
+ return SignalScoutConfig.objects.unscoped().create(
+ team_id=self.team.id, skill_name="signals-scout-errors", **kwargs
+ )
+
+ def test_acting_user_is_creator_even_when_config_names_an_enabler(self) -> None:
+ # The creator authored the prompt the run executes, so they must win over whoever
+ # merely switched the scout on.
+ ben = User.objects.create_and_join(self.organization, "[email protected]", None, "Ben")
+ v1 = self._create_skill("signals-scout-errors")
+ v1.created_by = ben
+ v1.is_latest = False
+ v1.save()
+ LLMSkill.objects.create(
+ team=self.team,
+ name="signals-scout-errors",
+ description="A test skill",
+ body="edited body",
+ version=2,
+ is_latest=True,
+ created_by=self.user,
+ )
+ config = self._create_config(enabled_by=self.user)
+ assert resolve_scout_acting_user_id(self.team, "signals-scout-errors", config) == ben.id
+
+ def test_acting_user_falls_back_to_config_enabler_for_authorless_skill(self) -> None:
+ # A pristine canonical scout's versions are all system-authored, so without the config
+ # fallback its runs pool on the team-level default user, which is the cost-allocation
+ # bug this resolver exists to fix. `enabled_by` outranks `created_by`: switching a
+ # scout on is the spend decision.
+ ben = User.objects.create_and_join(self.organization, "[email protected]", None, "Ben")
+ self._create_skill("signals-scout-errors")
+ config = self._create_config(enabled_by=ben, created_by=self.user)
+ assert resolve_scout_acting_user_id(self.team, "signals-scout-errors", config) == ben.id
+
+ def test_acting_user_skips_config_enabler_without_access(self) -> None:
+ # The run mints a sandbox token as the resolved user, so a revoked member must never
+ # resolve; the next self-consenting candidate (the config creator) takes over.
+ ben = User.objects.create_and_join(self.organization, "[email protected]", None, "Ben")
+ self._create_skill("signals-scout-errors")
+ config = self._create_config(enabled_by=ben, created_by=self.user)
+ OrganizationMembership.objects.filter(user=ben).delete()
+ assert resolve_scout_acting_user_id(self.team, "signals-scout-errors", config) == self.user.id
+
+ def test_acting_user_none_when_creator_lost_access(self) -> None:
+ # A revoked skill creator with no config candidates must resolve to nothing, so the
+ # runner falls back to the team-level default instead of minting for a removed member.
+ ben = User.objects.create_and_join(self.organization, "[email protected]", None, "Ben")
+ skill = self._create_skill("signals-scout-errors")
+ skill.created_by = ben
+ skill.save()
+ OrganizationMembership.objects.filter(user=ben).delete()
+ assert resolve_scout_acting_user_id(self.team, "signals-scout-errors", self._create_config()) is None
+
def test_signals_scout_prefix_check(self) -> None:
match = self._create_skill("signals-scout-errors")
non_match = self._create_skill("custom-research-helper")
@@ -1034,6 +1089,44 @@ async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):
assert captured["ai_stage"] == "scout:custom"
+async def test_run_acts_as_the_skill_creator_when_one_resolves(ateam, aorganization, aerrors_skill):
+ # Spend attribution follows the task row's user, so a run whose skill has a creator must
+ # mint under them; falling through to the team-level default (42 here) re-pools every
+ # scout's spend on one user, the bug the skill-based resolution exists to fix.
+ def _set_creator() -> User:
+ creator = User.objects.create_and_join(aorganization, f"creator-{random.randint(1, 99999)}@example.com", None)
+ aerrors_skill.created_by = creator
+ aerrors_skill.save()
+ return creator
+
+ creator = await database_sync_to_async(_set_creator, thread_sensitive=False)()
+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)
+ captured: dict = {}
+
+ async def _capture_start(*args, on_task_run_created=None, **kwargs):
+ captured.update(kwargs)
+ if on_task_run_created is not None:
+ await on_task_run_created(session.task_run)
+ return session, result
+
+ with (
+ patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start", new=_capture_start),
+ patch(
+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",
+ return_value="env-id",
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",
+ return_value=42,
+ ),
+ ):
+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ assert captured["context"].user_id == creator.id
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_run_passes_the_per_scout_server_selection_and_no_credential_owner(ateam, aerrors_skill):