: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(signals): scope inbox scout stats to each scout's last 25 runs (#80426)
Andrew Maguireb47fae70276d
diff --git a/products/signals/backend/migrations/0090_signal_scout_run_recent_idx.py b/products/signals/backend/migrations/0090_signal_scout_run_recent_idx.pynew file mode 100644index 000000000000..7a12275a1498--- /dev/null+++ b/products/signals/backend/migrations/0090_signal_scout_run_recent_idx.py@@ -0,0 +1,21 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("signals", "0089_signalreportaction"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="signalscoutrun",+ index=models.Index(+ fields=["team", "skill_name", "-created_at"],+ name="signal_scout_run_recent_idx",+ ),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex e981c43e7591..e3027c4830bc 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0089_signalreportaction+0090_signal_scout_run_recent_idxdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex e26f454df566..abc20a28dfaa 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1756,6 +1756,15 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):default_manager_name = "all_teams"indexes = [models.Index(fields=["team", "skill_name"], name="signal_scout_run_skill_idx"),+ # The per-scout run window ("last N runs of each scout") probes one scout at a time,+ # constraining all three keys, so each probe reads only the entries it returns. The+ # index above stops at the partition key, which leaves the planner sorting every one of+ # a scout's runs to take the newest N — on a table that only ever grows, and a read the+ # inbox repeats every 60 seconds.+ models.Index(+ fields=["team", "skill_name", "-created_at"],+ name="signal_scout_run_recent_idx",+ ),# "which run authored this report?" is a jsonb containment lookup (`@>`) that# `dismissal_notes` runs on the dismissal request path, batched into one OR'd query per# request. Without these the planner can only seq-scan the team's runs, and this tablediff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex e5eb5a263695..e2f021834354 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -41,7 +41,15 @@ from products.signals.backend.scout_harness.tools.emit import ()from products.signals.backend.scout_harness.tools.notes import MAX_NOTE_CONTENT_LENGTH, MAX_NOTES_LIST_LIMITfrom products.signals.backend.scout_harness.tools.report import MAX_REPORT_TITLE_LENGTH, MAX_SUGGESTED_REVIEWERS-from products.signals.backend.scout_harness.tools.runs import DEFAULT_FINDINGS_WINDOW_HOURS, MAX_FINDINGS_WINDOW_HOURS+from products.signals.backend.scout_harness.tools.runs import (+ DEFAULT_FINDINGS_WINDOW_HOURS,+ DEFAULT_RUNS_PER_SCOUT,+ DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,+ MAX_FINDINGS_WINDOW_HOURS,+ MAX_RUNS_PER_SCOUT,+ MAX_RUNS_PER_SCOUT_MAX_AGE_DAYS,+ STALENESS_INTERVAL_MULTIPLE,+)from products.signals.backend.scout_harness.tools.scratchpad import MAX_SCRATCHPAD_CONTENT_LENGTHfrom products.signals.backend.scout_harness.tools.structured_output import (MAX_RECORDS_PER_CALL,@@ -511,6 +519,35 @@ class FleetFindingsSummaryQuerySerializer(serializers.Serializer):)+class RecentRunsPerScoutQuerySerializer(serializers.Serializer):+ """Query parameters for the `recent-per-scout` action."""++ per_scout_limit = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=MAX_RUNS_PER_SCOUT,+ help_text=(+ f"How many of each scout's most recent runs to return (default {DEFAULT_RUNS_PER_SCOUT}, "+ f"hard cap {MAX_RUNS_PER_SCOUT}). The count is per scout, so a scout's history depth "+ f"does not depend on how often the rest of the fleet runs."+ ),+ )+ max_age_days = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=MAX_RUNS_PER_SCOUT_MAX_AGE_DAYS,+ help_text=(+ f"Floor for the staleness guard on `created_at`, in days (default "+ f"{DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS}, hard cap {MAX_RUNS_PER_SCOUT_MAX_AGE_DAYS}). "+ f"Runs older than the guard are excluded even when a scout has fewer than "+ f"`per_scout_limit` newer ones, so a scout that stopped running doesn't report its last "+ f"runs as current. Each scout's own cadence extends its guard to cover "+ f"{STALENESS_INTERVAL_MULTIPLE} runs' worth of its schedule, so a slow scout on a "+ f"monthly cron or a 30-day interval keeps its history."+ ),+ )++class SearchRecentRunsQuerySerializer(serializers.Serializer):"""Query parameters for `search-recent-runs`."""diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex 4e4608f3a1cc..f62a00589473 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -20,13 +20,20 @@ from dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any+from django.db import connectionfrom django.db.models import Qfrom django.db.models.functions import Coalescefrom django.utils import timezone-from products.signals.backend.models import SignalScoutRun+import structlog+from croniter import CroniterError, croniter++from products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAMfrom products.tasks.backend.facade import api as tasks_facade+logger = structlog.get_logger(__name__)+if TYPE_CHECKING:from products.tasks.backend.models import TaskRun@@ -34,6 +41,29 @@ if TYPE_CHECKING:DEFAULT_RUN_SEARCH_LIMIT = 20MAX_RUN_SEARCH_LIMIT = 100+# The per-scout run window backing the inbox scout surfaces. 25 runs covers a day for an hourly+# scout and a month for a daily one — the point being that both get enough history to judge, which+# a single fleet-wide time window can't do.+DEFAULT_RUNS_PER_SCOUT = 25+MAX_RUNS_PER_SCOUT = 100++# The staleness guard, so a scout that stopped running doesn't render its last runs as current.+# `..._MAX_AGE_DAYS` is a floor rather than a fixed cutoff: `run_interval_minutes` allows up to+# 43200 (30 days), which is the floor exactly, so a scout on the slowest supported cadence would+# have its whole history cut the moment dispatch slipped by a minute. Each scout's own cadence+# extends its lookback to `STALENESS_INTERVAL_MULTIPLE` runs' worth, capped at the ceiling.+DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS = 30+MAX_RUNS_PER_SCOUT_MAX_AGE_DAYS = 365+STALENESS_INTERVAL_MULTIPLE = 3+# A cron schedule has no interval to read, so sample its next few gaps and take the widest — a+# monthly cron reads as ~31 days, a weekday-only one as the weekend gap.+CRON_GAP_SAMPLES = 4++# Bounds the fan-out of the per-scout probe. Deliberately a limit on *scouts* rather than on rows:+# capping rows after the per-scout ranking would drop the slowest scouts' history, which is the+# exact crowd-out this query exists to remove. A scout that makes the cut gets its full history.+MAX_SCOUTS_PER_RUNS_QUERY = MAX_ENABLED_SCOUTS_PER_TEAM+# The "Scout findings" callout summary tallies findings over a fixed lookback window. The default# window, the run cap, and the report cap mirror the cloud/desktop frontend# (`SCOUT_RUNS_WINDOW_HOURS = 72` / `MAX_FLEET_EMITTED_RUNS = 120` / `MAX_FLEET_TOUCHED_REPORTS = 50`)@@ -186,6 +216,130 @@ def search_recent_runs(return [_to_summary(row, team_id=team_id) for row in qs]+def _schedule_gap_minutes(config: SignalScoutConfig) -> int:+ """How long this scout is expected to go between runs, in minutes.++ A cron schedule has no interval field, so sample its next few occurrences and take the widest+ gap — an irregular expression (weekdays only, monthly) has to be judged by its longest quiet+ stretch, not its shortest. Falls back to the rolling interval when the expression can't be read.+ """+ if not config.run_cron_schedule:+ return config.run_interval_minutes+ try:+ iterator = croniter(config.run_cron_schedule, timezone.now())+ previous: datetime = iterator.get_next(datetime)+ widest = 0.0+ for _ in range(CRON_GAP_SAMPLES):+ occurrence: datetime = iterator.get_next(datetime)+ widest = max(widest, (occurrence - previous).total_seconds() / 60)+ previous = occurrence+ return int(widest) or config.run_interval_minutes+ except (CroniterError, ValueError):+ # A stored expression the coordinator can't read either — the scout isn't running on it,+ # so its rolling interval is the honest estimate.+ return config.run_interval_minutes+++def _staleness_cutoff(config: SignalScoutConfig, *, now: datetime, floor_days: int) -> datetime:+ """The oldest run worth showing for this scout.++ Cadence-aware on purpose: a fixed cutoff at the floor would erase the entire history of a scout+ on the slowest supported cadence (`run_interval_minutes` allows exactly 43200, i.e. the 30-day+ default), or on a monthly cron, the moment dispatch slipped past it — reporting "no runs" for a+ scout running exactly as configured.+ """+ cadence_days = (_schedule_gap_minutes(config) * STALENESS_INTERVAL_MULTIPLE) / (60 * 24)+ lookback_days = min(max(floor_days, cadence_days), MAX_RUNS_PER_SCOUT_MAX_AGE_DAYS)+ return now - timedelta(days=lookback_days)+++def recent_runs_per_scout(+ *,+ team_id: int,+ per_scout_limit: int = DEFAULT_RUNS_PER_SCOUT,+ max_age_days: int = DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,+) -> list[RunSummary]:+ """Return each configured scout's most recent runs, newest first across the fleet.++ A cadence-invariant alternative to `search_recent_runs`' fixed time window. A fleet-wide+ lookback has to serve an hourly scout and a weekly one from one budget: widen it and the busy+ scouts fill the result cap, leaving the sparse ones with a history that gets shorter the+ healthier the rest of the fleet is. Probing per scout gives every scout the same depth of+ history no matter its schedule, and bounds the read at scouts x `per_scout_limit` instead of at+ "however many runs the fleet happened to do".++ The scouts come from `SignalScoutConfig`, which does three things at once: it constrains+ `skill_name` so the `(team, skill_name, created_at)` index can bound each probe to the rows it+ returns (a fleet-wide scan can't, since an unconstrained `skill_name` sits between the two+ predicates); it keeps runs of deleted and renamed scouts out of the fleet rollups, which read+ their stats off whatever skill names appear here; and it carries the schedule each scout's+ staleness cutoff is derived from.++ `max_age_days` is the floor of that cutoff, not a fixed window — see `_staleness_cutoff`.+ """+ per_scout_limit = max(1, min(per_scout_limit, MAX_RUNS_PER_SCOUT))+ floor_days = max(1, min(max_age_days, MAX_RUNS_PER_SCOUT_MAX_AGE_DAYS))+ now = timezone.now()++ # Enabled first so that if a fleet ever exceeds the bound, the scouts dropped are the ones+ # nobody is watching run. Ordered within each group for a deterministic cut.+ configs = list(+ SignalScoutConfig.objects.filter(team_id=team_id)+ .order_by("-enabled", "skill_name")+ .only("skill_name", "run_interval_minutes", "run_cron_schedule", "enabled")+ )+ if len(configs) > MAX_SCOUTS_PER_RUNS_QUERY:+ # Never silently: a truncated fleet reads as a complete one on every surface downstream.+ logger.warning(+ "signals_scout_runs_per_scout_fleet_truncated",+ team_id=team_id,+ scout_count=len(configs),+ bound=MAX_SCOUTS_PER_RUNS_QUERY,+ dropped=[config.skill_name for config in configs[MAX_SCOUTS_PER_RUNS_QUERY:]],+ )+ configs = configs[:MAX_SCOUTS_PER_RUNS_QUERY]+ if not configs:+ return []++ # One probe per scout via LATERAL, each an indexed top-N over+ # `(team_id, skill_name, created_at DESC)` — all three keys constrained, so a probe reads+ # `per_scout_limit` index entries rather than walking the team's whole run history and+ # filtering. The ORM has no LATERAL, and the alternatives are worse: a window function over the+ # fleet can't bound its scan, and a query per scout is one round trip per scout on a 60s poll.+ # Team scoping is explicit in the predicate, standing in for the fail-closed manager raw SQL+ # bypasses; `skill_name` and the cutoffs are bound parameters, never interpolated.+ probe_values = ", ".join(["(%s::text, %s::timestamptz)"] * len(configs))+ params: list[Any] = []+ for config in configs:+ params.extend([config.skill_name, _staleness_cutoff(config, now=now, floor_days=floor_days)])+ params.extend([team_id, per_scout_limit])+ sql = f"""+ SELECT probe.id+ FROM (VALUES {probe_values}) AS scout(skill_name, cutoff)+ CROSS JOIN LATERAL (+ SELECT run.id+ FROM {SignalScoutRun._meta.db_table} run+ WHERE run.team_id = %s+ AND run.skill_name = scout.skill_name+ AND run.created_at >= scout.cutoff+ ORDER BY run.created_at DESC+ LIMIT %s+ ) probe+ """+ with connection.cursor() as cursor:+ cursor.execute(sql, params)+ run_ids = [row[0] for row in cursor.fetchall()]+ if not run_ids:+ return []++ rows = (+ SignalScoutRun.objects.filter(team_id=team_id, id__in=run_ids)+ .select_related("task_run")+ .order_by("-created_at")+ )+ return [_to_summary(row, team_id=team_id) for row in rows]++@dataclass(frozen=True)class FleetFindingsSummary:"""Cheap fleet-wide tally of recent scout output — what the "Scout findings" callout reads.diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 2c419f2ee58c..3c0dd0b6e02f 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -86,6 +86,7 @@ from products.signals.backend.scout_harness.serializers import (ProjectProfileQuerySerializer,ProjectProfileSerializer,RecentEmissionsQuerySerializer,+ RecentRunsPerScoutQuerySerializer,RecordStructuredOutputRequestSerializer,RecordStructuredOutputResponseSerializer,RememberRequestSerializer,@@ -148,8 +149,11 @@ from products.signals.backend.scout_harness.tools.report import ()from products.signals.backend.scout_harness.tools.runs import (DEFAULT_FINDINGS_WINDOW_HOURS,+ DEFAULT_RUNS_PER_SCOUT,+ DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,fleet_findings_summary,get_run,+ recent_runs_per_scout,search_recent_runs,)from products.signals.backend.scout_harness.tools.scratchpad import (@@ -516,6 +520,47 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)return Response(SignalScoutRunSummarySerializer([row.as_dict() for row in rows], many=True).data)+ @validated_request(+ query_serializer=RecentRunsPerScoutQuerySerializer,+ responses={+ 200: OpenApiResponse(+ response=SignalScoutRunSummarySerializer(many=True),+ description="Each scout's most recent runs, newest-first across the fleet.",+ ),+ },+ summary="List each scout's most recent runs",+ description=(+ "Return the most recent `per_scout_limit` runs of *every* configured scout on the "+ "project (default 25), newest-first across the fleet. The per-scout probe is the point: "+ "a fleet-wide time window has to serve hourly and weekly scouts from one result cap, so "+ "the busy scouts crowd out the sparse ones and a scout's visible history shrinks as the "+ "rest of the fleet gets busier. Probing each `skill_name` gives every scout the same "+ "depth of history whatever its schedule, and bounds the response at scouts x "+ "`per_scout_limit` rather than at the fleet's run rate. Only scouts that still have a "+ "config are covered, so runs left behind by a deleted or renamed scout are excluded. "+ "Runs older than the staleness guard are excluded too, so a scout that stopped running "+ "reads as stale instead of healthy — `max_age_days` (default 30) is that guard's floor, "+ "which each scout's own cadence extends. Use `list` instead when you want a literal "+ "time window or a text/emitted filter. Strictly team-scoped."+ ),+ operation_id="signals_scout_runs_recent_per_scout",+ )+ @action(+ detail=False,+ methods=["get"],+ url_path="recent-per-scout",+ required_scopes=["signal_scout:read"],+ pagination_class=None,+ )+ def recent_per_scout(self, request: Request, **kwargs) -> Response:+ validated = getattr(request, "validated_query_data", {}) or {}+ rows = recent_runs_per_scout(+ team_id=_canonical_team_id(self),+ per_scout_limit=validated.get("per_scout_limit") or DEFAULT_RUNS_PER_SCOUT,+ max_age_days=validated.get("max_age_days") or DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,+ )+ return Response(SignalScoutRunSummarySerializer([row.as_dict() for row in rows], many=True).data)+@validated_request(query_serializer=FleetFindingsSummaryQuerySerializer,responses={diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex f5c9ff6dbb91..2fa64fa7f8c0 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -538,6 +538,26 @@ class TestScoutHarnessRecentEmissionsAPI(APIBaseTest):assert [row["finding_id"] for row in response.json()] == ["older"]+class TestScoutHarnessRecentPerScoutAPI(APIBaseTest):+ def _url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/recent-per-scout/"++ def test_returns_each_scouts_newest_runs(self) -> None:+ # Wiring guard: the action reaches `recent_runs_per_scout` and honours `per_scout_limit`.+ # The probe rules themselves are covered against the helper in test_scout_harness_tools.+ for skill_name in ("signals-scout-errors", "signals-scout-surveys"):+ SignalScoutConfig.objects.create(team=self.team, skill_name=skill_name)+ busy = [_make_run(self.team, skill_name="signals-scout-errors") for _ in range(3)]+ quiet = _make_run(self.team, skill_name="signals-scout-surveys")+ response = self.client.get(self._url(), data={"per_scout_limit": 1})+ assert response.status_code == status.HTTP_200_OK+ assert {row["run_id"] for row in response.json()} == {str(busy[-1].id), str(quiet.id)}++ def test_rejects_a_per_scout_limit_over_the_cap(self) -> None:+ response = self.client.get(self._url(), data={"per_scout_limit": 5000})+ assert response.status_code == status.HTTP_400_BAD_REQUEST++class TestScoutHarnessFindingsSummaryAPI(APIBaseTest):def _url(self) -> str:return f"/api/projects/{self.team.id}/signals/scout/runs/findings/summary/"diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pyindex 850f5f309268..2de63d9dfb94 100644--- a/products/signals/backend/test/test_scout_harness_tools.py+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -53,7 +53,11 @@ from products.signals.backend.scout_harness.tools.report import (_forwarded_summary,_report_event_uuid,)-from products.signals.backend.scout_harness.tools.runs import MAX_FAILURE_REASON_LENGTH, MAX_RUN_SEARCH_LIMIT+from products.signals.backend.scout_harness.tools.runs import (+ MAX_FAILURE_REASON_LENGTH,+ MAX_RUN_SEARCH_LIMIT,+ recent_runs_per_scout,+)from products.signals.backend.scout_harness.tools.scratchpad import (MAX_SCRATCHPAD_CONTENT_LENGTH,MAX_SCRATCHPAD_SEARCH_LIMIT,@@ -322,6 +326,103 @@ class TestSearchRecentRuns(BaseTest):assert len(hit.failure_reason or "") == MAX_FAILURE_REASON_LENGTH # derived reason bounded+class TestRecentRunsPerScout(BaseTest):+ def _configure(self, skill_name: str, *, team=None, **overrides) -> SignalScoutConfig:+ return SignalScoutConfig.objects.create(team=team or self.team, skill_name=skill_name, **overrides)++ def _run_at(self, *, skill_name: str, hours_ago: float, team=None) -> SignalScoutRun:+ run = _create_run(team or self.team, skill_name=skill_name)+ SignalScoutRun.objects.filter(id=run.id).update(created_at=timezone.now() - timedelta(hours=hours_ago))+ return run++ def test_a_busy_scout_does_not_crowd_out_a_sparse_one(self) -> None:+ # The reason this helper exists: under a fleet-wide window with a shared row cap, the hourly+ # scout's runs consume the budget and the daily scout's history shrinks as the fleet gets+ # busier. Probing per scout has to give both the same depth.+ self._configure("signals-scout-hourly", run_interval_minutes=60)+ self._configure("signals-scout-daily", run_interval_minutes=1440)+ for hour in range(20):+ self._run_at(skill_name="signals-scout-hourly", hours_ago=hour)+ daily = [self._run_at(skill_name="signals-scout-daily", hours_ago=24 * day) for day in range(1, 4)]++ hits = recent_runs_per_scout(team_id=self.team.id, per_scout_limit=5)++ per_skill: dict[str, list[str]] = {}+ for hit in hits:+ per_skill.setdefault(hit.skill_name, []).append(hit.run_id)+ assert len(per_skill["signals-scout-hourly"]) == 5+ assert per_skill["signals-scout-daily"] == [str(run.id) for run in daily]++ def test_keeps_each_scouts_newest_runs_and_orders_the_fleet_newest_first(self) -> None:+ self._configure("signals-scout-errors")+ self._configure("signals-scout-surveys")+ newest = self._run_at(skill_name="signals-scout-errors", hours_ago=1)+ older = self._run_at(skill_name="signals-scout-errors", hours_ago=2)+ dropped = self._run_at(skill_name="signals-scout-errors", hours_ago=3)+ other_scout = self._run_at(skill_name="signals-scout-surveys", hours_ago=1.5)++ hits = recent_runs_per_scout(team_id=self.team.id, per_scout_limit=2)++ assert [hit.run_id for hit in hits] == [str(newest.id), str(other_scout.id), str(older.id)]+ assert str(dropped.id) not in {hit.run_id for hit in hits}++ def test_excludes_runs_older_than_the_age_guard(self) -> None:+ # A scout that stopped running weeks ago must read as stale, not render its last runs as+ # current just because it has fewer than `per_scout_limit` of them.+ self._configure("signals-scout-errors")+ self._configure("signals-scout-abandoned")+ recent = self._run_at(skill_name="signals-scout-errors", hours_ago=1)+ self._run_at(skill_name="signals-scout-abandoned", hours_ago=24 * 40)++ hits = recent_runs_per_scout(team_id=self.team.id, per_scout_limit=25, max_age_days=30)++ assert [hit.run_id for hit in hits] == [str(recent.id)]++ @parameterized.expand(+ [+ # `run_interval_minutes` allows exactly 43200 (30 days), which is the guard's floor, so a+ # fixed cutoff erased a correctly-running scout's whole history the moment dispatch+ # slipped. A monthly cron is the same failure with more headroom.+ ("slowest supported interval", {"run_interval_minutes": 43200}, 24 * 35),+ ("monthly cron", {"run_cron_schedule": "0 9 1 * *"}, 24 * 40),+ ]+ )+ def test_a_slow_scout_keeps_history_past_the_guard_floor(+ self, _name: str, schedule: dict, run_age_hours: float+ ) -> None:+ self._configure("signals-scout-slow", **schedule)+ run = self._run_at(skill_name="signals-scout-slow", hours_ago=run_age_hours)++ hits = recent_runs_per_scout(team_id=self.team.id, max_age_days=30)++ assert [hit.run_id for hit in hits] == [str(run.id)]++ def test_ignores_runs_left_behind_by_a_scout_with_no_config(self) -> None:+ # Runs outlive their config, and the fleet rollups derive success/emit rates from whatever+ # skill names come back — so a deleted or renamed scout would keep moving the live fleet's+ # numbers for as long as its runs stay inside the window.+ self._configure("signals-scout-errors")+ live = self._run_at(skill_name="signals-scout-errors", hours_ago=1)+ self._run_at(skill_name="signals-scout-deleted", hours_ago=24 * 5)++ hits = recent_runs_per_scout(team_id=self.team.id)++ assert [hit.run_id for hit in hits] == [str(live.id)]++ def test_does_not_leak_runs_from_other_teams(self) -> None:+ from posthog.models import Team++ other = Team.objects.create(organization=self.organization, name="other")+ self._configure("signals-scout-errors")+ self._configure("signals-scout-errors", team=other)+ mine = self._run_at(skill_name="signals-scout-errors", hours_ago=1)+ self._run_at(skill_name="signals-scout-errors", hours_ago=1, team=other)++ hits = recent_runs_per_scout(team_id=self.team.id)++ assert [hit.run_id for hit in hits] == [str(mine.id)]++class TestGetRun(BaseTest):def test_returns_full_run_payload(self) -> None:run = _create_run(self.team)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 609af29e5f98..d58d4e6e5c5f 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -4121,6 +4121,21 @@ export type SignalsScoutRunsFindingsSummaryParams = {window_hours?: number}+export type SignalsScoutRunsRecentPerScoutParams = {+ /**+ * Floor for the staleness guard on `created_at`, in days (default 30, hard cap 365). Runs older than the guard are excluded even when a scout has fewer than `per_scout_limit` newer ones, so a scout that stopped running doesn't report its last runs as current. Each scout's own cadence extends its guard to cover 3 runs' worth of its schedule, so a slow scout on a monthly cron or a 30-day interval keeps its history.+ * @minimum 1+ * @maximum 365+ */+ max_age_days?: number+ /**+ * How many of each scout's most recent runs to return (default 25, hard cap 100). The count is per scout, so a scout's history depth does not depend on how often the rest of the fleet runs.+ * @minimum 1+ * @maximum 100+ */+ per_scout_limit?: number+}+export type SignalsScoutScratchpadSearchParams = {/*** Truncate each entry's `content` to the first N characters (a preview). Omit for the full body. Ignored when `keys_only=true`.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 1787b5538c8c..f82f5360d3a6 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -80,6 +80,7 @@ import type {SignalsScoutRunsFindingsSummaryParams,SignalsScoutRunsListParams,SignalsScoutRunsRecentEmissionsParams,+ SignalsScoutRunsRecentPerScoutParams,SignalsScoutScratchpadSearchParams,SignalsSourceConfigsListParams,} from './api.schemas'@@ -1281,6 +1282,40 @@ export const signalsScoutRunsFindingsSummary = async (})}+export const getSignalsScoutRunsRecentPerScoutUrl = (+ projectId: string,+ params?: SignalsScoutRunsRecentPerScoutParams+) => {+ 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}/signals/scout/runs/recent-per-scout/?${stringifiedParams}`+ : `/api/projects/${projectId}/signals/scout/runs/recent-per-scout/`+}++/**+ * Return the most recent `per_scout_limit` runs of *every* configured scout on the project (default 25), newest-first across the fleet. The per-scout probe is the point: a fleet-wide time window has to serve hourly and weekly scouts from one result cap, so the busy scouts crowd out the sparse ones and a scout's visible history shrinks as the rest of the fleet gets busier. Probing each `skill_name` gives every scout the same depth of history whatever its schedule, and bounds the response at scouts x `per_scout_limit` rather than at the fleet's run rate. Only scouts that still have a config are covered, so runs left behind by a deleted or renamed scout are excluded. Runs older than the staleness guard are excluded too, so a scout that stopped running reads as stale instead of healthy — `max_age_days` (default 30) is that guard's floor, which each scout's own cadence extends. Use `list` instead when you want a literal time window or a text/emitted filter. Strictly team-scoped.+ * @summary List each scout's most recent runs+ */+export const signalsScoutRunsRecentPerScout = async (+ projectId: string,+ params?: SignalsScoutRunsRecentPerScoutParams,+ options?: RequestInit+): Promise<SignalScoutRunSummaryApi[]> => {+ return apiMutator<SignalScoutRunSummaryApi[]>(getSignalsScoutRunsRecentPerScoutUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsScoutScratchpadSearchUrl = (projectId: string, params?: SignalsScoutScratchpadSearchParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/frontend/inbox/InboxScene.stories.tsx b/products/signals/frontend/inbox/InboxScene.stories.tsxindex 5c97a752e3dd..297ca1c19a72 100644--- a/products/signals/frontend/inbox/InboxScene.stories.tsx+++ b/products/signals/frontend/inbox/InboxScene.stories.tsx@@ -39,6 +39,7 @@ const sceneMocks = mswDecorator({'/api/projects/:id/signals/config': () => [200, mockTeamConfig],'/api/projects/:id/signals/scout/configs': () => [200, []],'/api/projects/:id/signals/scout/runs': () => [200, []],+ '/api/projects/:id/signals/scout/runs/recent-per-scout': () => [200, []],'/api/projects/:id/external_data_sources': () => [200, { results: [], count: 0 }],'/api/projects/:id/external_data_sources/': () => [200, { results: [], count: 0 }],},diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsxindex cdb48370ba50..b81cc3515feb 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx@@ -10,7 +10,7 @@ import { captureScoutDetailViewed } from '../../../inboxAnalytics'import { inboxSceneLogic } from '../../../inboxSceneLogic'import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'-import { SCOUT_RUNS_WINDOW_SPAN, scoutRunsWindowLabel } from '../../../utils/scoutRunsWindow'+import { SCOUT_NO_RECENT_RUNS, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'import { ScoutEmissionCard } from './ScoutEmissionCard'import { ScoutReportCard } from './ScoutReportCard'import { ScoutRowCard } from './ScoutRowCard'@@ -22,7 +22,7 @@ import { ScoutRunHistorySection } from './ScoutRunHistorySection'* rollup line. The Signals section (emission cards) and per-scout run history land next (W2/W3).*/export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Element {- const { scoutConfigs, rollups, runsWindowComplete, updatingScoutIds } = useValues(scoutFleetLogic)+ const { scoutConfigs, rollups, updatingScoutIds } = useValues(scoutFleetLogic)const { updateScoutConfig, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)const { setSelectedScoutSkillName } = useActions(inboxSceneLogic)@@ -92,7 +92,7 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Eleme<div className="flex flex-col gap-1"><span className="text-xs font-medium text-default uppercase tracking-wide">- Last {SCOUT_RUNS_WINDOW_SPAN}+ {SCOUT_RUNS_PER_SCOUT_LABEL}</span><span className="text-sm text-secondary">{rollup && rollup.runCount > 0 ? (@@ -107,10 +107,7 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Eleme)}</>) : (- 'No runs in this window.'- )}- {!runsWindowComplete && (- <span className="text-muted"> · {scoutRunsWindowLabel(runsWindowComplete)}</span>+ SCOUT_NO_RECENT_RUNS)}</span></div>@@ -133,7 +130,7 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Eleme* that never authors a report, so it only appears for report-channel scouts.*/function ScoutReportsSection({ skillName }: { skillName: string }): JSX.Element | null {- const { reportRows, touchedReports, scoutReportsLoading, runsWindowLoadedOnce } = useValues(+ const { reportRows, touchedReports, scoutReportsLoading, scoutRunsLoadedOnce } = useValues(scoutDetailLogic({ skillName }))@@ -142,7 +139,7 @@ function ScoutReportsSection({ skillName }: { skillName: string }): JSX.Elementreturn null}- const loading = !runsWindowLoadedOnce || (scoutReportsLoading && reportRows.length === 0)+ const loading = !scoutRunsLoadedOnce || (scoutReportsLoading && reportRows.length === 0)return (<div className="flex flex-col gap-2">@@ -170,29 +167,24 @@ function ScoutReportsSection({ skillName }: { skillName: string }): JSX.Element* so the section is hidden entirely when nothing emitted, rather than showing an empty box.*/function ScoutSignalsSection({ skillName }: { skillName: string }): JSX.Element | null {- const {- emissionRows,- emissionsLoading,- emissionsLoadFailed,- emittedRuns,- runsWindowLoadedOnce,- runsWindowComplete,- } = useValues(scoutDetailLogic({ skillName }))+ const { emissionRows, emissionsLoading, emissionsLoadFailed, emittedRuns, scoutRunsLoadedOnce } = useValues(+ scoutDetailLogic({ skillName })+ )const { selectedScoutFindingId } = useValues(inboxSceneLogic)- // No run in the window emitted anything — keep the section out entirely rather than show an+ // No run in this scout's window emitted anything — keep the section out entirely rather than show an// empty box (mirrors the Reports section above). Only once the runs window has settled, though:// before that, `emittedRuns` is empty by default and hiding would skip the loading skeleton// for scouts that do have signals.- if (runsWindowLoadedOnce && emittedRuns.length === 0) {+ if (scoutRunsLoadedOnce && emittedRuns.length === 0) {return null}- // "Loading" until the fleet's runs window has settled once AND this scout's emissions have+ // "Loading" until the fleet's per-scout runs have settled once AND this scout's emissions have// resolved — otherwise a fresh deep-link would flash the empty state before we know the// emitted runs. Gating on the fleet's first-load flag (not its per-poll loading) keeps the// quiet-scout empty state from flickering to a skeleton every 60s poll.- const loading = !runsWindowLoadedOnce || emissionsLoading+ const loading = !scoutRunsLoadedOnce || emissionsLoadingconst hasRows = emissionRows.length > 0// The unique emission the deep-link resolves to: the newest row whose finding matches.const deepLinkedEmissionId = selectedScoutFindingId@@ -212,9 +204,7 @@ function ScoutSignalsSection({ skillName }: { skillName: string }): JSX.Element</div>) : !hasRows ? (<div className="rounded border border-dashed border-primary bg-bg-light px-4 py-6 text-center text-sm text-muted">- {runsWindowComplete- ? `No signals emitted in the last ${SCOUT_RUNS_WINDOW_SPAN}.`- : `No signals emitted in the recent runs we could load (the last ${SCOUT_RUNS_WINDOW_SPAN} is truncated).`}+ {`No signals emitted in the ${SCOUT_RUNS_PER_SCOUT_LABEL}.`}</div>) : (<>@@ -231,11 +221,6 @@ function ScoutSignalsSection({ skillName }: { skillName: string }): JSX.ElementisDeepLinked={emission.id === deepLinkedEmissionId}/>))}- {!runsWindowComplete && (- <span className="text-xs text-muted">- Older signals beyond the loaded {SCOUT_RUNS_WINDOW_SPAN} window aren’t shown.- </span>- )}</>)}</div>diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsxindex e769e8bcd084..872834059092 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx@@ -21,7 +21,8 @@ import {runReportActivity,ScoutRunFilter,scoutReportActivityLabel,- SCOUT_RUNS_WINDOW_SPAN,+ SCOUT_NO_RECENT_RUNS,+ SCOUT_RUNS_PER_SCOUT_LABEL,} from '../../../utils/scoutRunsWindow'import { ScoutTimestamp } from './ScoutTimestamp'@@ -197,11 +198,11 @@ const ScoutRunRow = memo(function ScoutRunRow({/*** The Runs section on the scout detail surface: this scout's runs in the recent window, newest* first, with All/Emitted/Quiet/Failed filter chips (each showing its match count). Runs come- * from `scoutFleetLogic`'s already-polled window rollup (oldest-first timeline order, reversed- * here) — there's no per-scout runs endpoint yet (api gap 1), so the window is filtered client-side.+ * from `scoutFleetLogic`'s already-polled per-scout rollup (oldest-first timeline order, reversed+ * here); the filter chips narrow that set client-side.*/export function ScoutRunHistorySection({ skillName }: { skillName: string }): JSX.Element {- const { rollups, runsWindowLoadedOnce, runsWindowComplete } = useValues(scoutFleetLogic)+ const { rollups, scoutRunsLoadedOnce } = useValues(scoutFleetLogic)const [filter, setFilter] = useState<ScoutRunFilter>('all')// Newest first for a history list; the rollup keeps runs oldest-first for the header timeline.@@ -220,9 +221,9 @@ export function ScoutRunHistorySection({ skillName }: { skillName: string }): JSconst filteredRuns = useMemo(() => runs.filter((run) => runMatchesFilter(run, filter)), [runs, filter])- // Hold the skeleton until the fleet's runs window has settled once — otherwise a fresh deep-link- // flashes the empty state before we know this scout's runs.- const loading = !runsWindowLoadedOnce+ // Hold the skeleton until the fleet's per-scout runs have settled once — otherwise a fresh+ // deep-link flashes the empty state before we know this scout's runs.+ const loading = !scoutRunsLoadedOncereturn (<div className="flex flex-col gap-2">@@ -258,21 +259,14 @@ export function ScoutRunHistorySection({ skillName }: { skillName: string }): JS) : filteredRuns.length === 0 ? (<div className="rounded border border-dashed border-primary bg-bg-light px-4 py-6 text-center text-sm text-muted">{runs.length > 0- ? `No runs match this filter in the last ${SCOUT_RUNS_WINDOW_SPAN}.`- : runsWindowComplete- ? `No runs in the last ${SCOUT_RUNS_WINDOW_SPAN}.`- : `No runs in the recent window we could load (the last ${SCOUT_RUNS_WINDOW_SPAN} is truncated).`}+ ? `No runs match this filter in the ${SCOUT_RUNS_PER_SCOUT_LABEL}.`+ : SCOUT_NO_RECENT_RUNS}</div>) : (<>{filteredRuns.map((run) => (<ScoutRunRow key={run.run_id} run={run} skillName={skillName} />))}- {!runsWindowComplete && (- <span className="text-xs text-muted">- Older runs beyond the loaded {SCOUT_RUNS_WINDOW_SPAN} window aren’t shown.- </span>- )}</>)}</div>diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsxindex d094a17037ad..317054a0e4d2 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx@@ -17,8 +17,7 @@ import {FleetSummary,SCOUT_FLEET_OVERVIEW_PROMPT,SCOUT_RECENT_SIGNALS_PROMPT,- SCOUT_RUNS_WINDOW_SPAN,- scoutRunsWindowLabel,+ SCOUT_RUNS_PER_SCOUT_LABEL,} from '../../../utils/scoutRunsWindow'import { agentSetupModalLogic } from '../../shell/agentSetupModalLogic'import { FleetFindingsCallout } from './FleetFindingsCallout'@@ -172,7 +171,7 @@ function summarize(summary: FleetSummary | null): string {* leads with "what the troop is" before its controls.*/function FleetStatsHeader(): JSX.Element {- const { scoutConfigs, enabledCount, lastRunAt, fleetSummary, runsWindowComplete } = useValues(scoutFleetLogic)+ const { scoutConfigs, enabledCount, lastRunAt, fleetSummary } = useValues(scoutFleetLogic)return (<div className="flex flex-col gap-0.5">@@ -187,7 +186,7 @@ function FleetStatsHeader(): JSX.Element {) : null}</div><span className="text-xs text-muted">- {summarize(fleetSummary)} · {scoutRunsWindowLabel(runsWindowComplete)}+ {summarize(fleetSummary)} · {SCOUT_RUNS_PER_SCOUT_LABEL} per scout</span></div>)@@ -269,9 +268,9 @@ function ScoutsFleetList(): JSX.Element {<div className="flex flex-col gap-1"><span className="text-xs text-muted">- Run counts and emitted totals cover the last {SCOUT_RUNS_WINDOW_SPAN} of troop runs. New scouts are- created as <span className="font-mono text-[11px]">signals-scout-*</span> skills in your PostHog- project.+ Run counts and emitted totals cover each scout’s {SCOUT_RUNS_PER_SCOUT_LABEL}, so scouts on+ different schedules are comparable. New scouts are created as{' '}+ <span className="font-mono text-[11px]">signals-scout-*</span> skills in your PostHog project.</span><ScoutHelperSkillLinks /></div>diff --git a/products/signals/frontend/inbox/logics/findingsLogic.ts b/products/signals/frontend/inbox/logics/findingsLogic.tsindex 3efaadaeaf5f..6e876088fc76 100644--- a/products/signals/frontend/inbox/logics/findingsLogic.ts+++ b/products/signals/frontend/inbox/logics/findingsLogic.ts@@ -60,7 +60,6 @@ export interface findingsLogicValues {complete: booleanruns: SignalScoutRunSummary[]} // scoutFleetLogic- runsWindowComplete: boolean // scoutFleetLogicrunsWindowLoadedOnce: boolean // scoutFleetLogicauthoredReportCount: numberavailableScouts: {@@ -307,7 +306,7 @@ export const findingsLogic = kea<findingsLogicType>([path(['scenes', 'inbox', 'logics', 'findingsLogic']),connect(() => ({- values: [scoutFleetLogic, ['runsWindow', 'runsWindowLoadedOnce', 'runsWindowComplete']],+ values: [scoutFleetLogic, ['runsWindow', 'runsWindowLoadedOnce']],})),actions({diff --git a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts b/products/signals/frontend/inbox/logics/scoutDetailLogic.tsindex c5dfcd0c3313..6359ab6dea19 100644--- a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutDetailLogic.ts@@ -59,8 +59,7 @@ export interface ScoutEmissionRow {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutDetailLogicValues {rollups: Map<string, ScoutRollup> // scoutFleetLogic- runsWindowComplete: boolean // scoutFleetLogic- runsWindowLoadedOnce: boolean // scoutFleetLogic+ scoutRunsLoadedOnce: boolean // scoutFleetLogicemissionReports: SignalScoutEmissionReportLink[]emissionReportsLoading: booleanemissionRows: ScoutEmissionRow[]@@ -184,7 +183,7 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([key((props) => props.skillName),connect(() => ({- values: [scoutFleetLogic, ['rollups', 'runsWindowLoadedOnce', 'runsWindowComplete']],+ values: [scoutFleetLogic, ['rollups', 'scoutRunsLoadedOnce']],})),loaders(({ values }) => ({@@ -300,7 +299,7 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([.slice(0, MAX_EMITTED_RUNS),],// Stable string key over the emitted runs — refetch emissions only when the set actually- // changes, not on every 60s runs-window poll that returns the same runs. Includes+ // changes, not on every 60s per-scout runs poll that returns the same runs. Includes// `emitted_count` so a run that emits more findings while still in progress retriggers.emittedRunsKey: [(s) => [s.emittedRuns],@@ -417,11 +416,11 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([})),listeners(({ actions, values }) => ({- // Report grouping resolves asynchronously after emission, so ride the fleet's 60s runs-window- // poll to keep refetching the links — but only while a recently-emitted finding is still+ // Report grouping resolves asynchronously after emission, so ride the fleet's 60s per-scout+ // runs poll to keep refetching the links — but only while a recently-emitted finding is still// unlinked. Computed fresh here (not a memoized selector) so the recency cutoff advances with// wall-clock time and a never-grouping finding stops the poll once it ages out of the window.- [scoutFleetLogic.actionTypes.loadRunsWindowSuccess]: () => {+ [scoutFleetLogic.actionTypes.loadScoutRunsSuccess]: () => {const cutoff = dayjs().subtract(REPORT_LINK_RETRY_WINDOW_MINUTES, 'minute')const hasRecentUnlinked = values.emissionRows.some((row) =>diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex 62d0457edda8..12b14915fbaf 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -18,6 +18,7 @@ import {signalsScoutMetadataGet,signalsScoutRunsFindingsSummary,signalsScoutRunsList,+ signalsScoutRunsRecentPerScout,} from 'products/signals/frontend/generated/api'import type {FleetFindingsSummaryApi,@@ -46,6 +47,7 @@ import {SCOUT_AUTHOR_PROMPT,SCOUT_FLEET_OVERVIEW_PROMPT,SCOUT_RECENT_SIGNALS_PROMPT,+ SCOUT_RUNS_PER_SCOUT,SCOUT_RUNS_WINDOW_HOURS,ScoutRollup,sortConfigsForDisplay,@@ -88,10 +90,11 @@ function captureScoutConfigUpdates(// Fleet runs are refetched on a slow cadence so "running now" / recent emissions// stay live without hammering the capped runs endpoint (desktop: 60s).const RUNS_REFETCH_INTERVAL_MS = 60_000-// The runs endpoint caps each page at 100 rows newest-first. To cover the whole-// window we walk back page-by-page via a `date_to` cursor (the oldest run's-// `started_at`, as the backend documents). MAX_RUNS_PAGES bounds the walk so a-// pathologically busy fleet can't spin forever — hitting it flags the window truncated.+// The findings feed's fixed lookback: the runs endpoint caps each page at 100 rows newest-first, so+// covering the whole window means walking back page-by-page via a `date_to` cursor (the oldest run's+// `started_at`, as the backend documents). MAX_RUNS_PAGES bounds the walk so a pathologically busy+// fleet can't spin forever — hitting it flags the window truncated. Per-scout stats don't pay this:+// `loadScoutRuns` gets each scout's last N runs from one ranked query.const RUNS_PAGE_LIMIT = 100const MAX_RUNS_PAGES = 15@@ -124,7 +127,6 @@ export interface scoutFleetLogicValues {complete: booleanruns: SignalScoutRunSummary[]}- runsWindowComplete: booleanrunsWindowLoadedOnce: booleanrunsWindowLoading: booleanscoutBannerMessage: string | null@@ -132,6 +134,9 @@ export interface scoutFleetLogicValues {scoutConfigsLoading: booleanscoutMetadata: ScoutMetadataApi | nullscoutMetadataLoading: boolean+ scoutRuns: SignalScoutRunSummary[]+ scoutRunsLoadedOnce: boolean+ scoutRunsLoading: booleanscoutTagOptions: ScoutTagOption[]selectedScoutTags: string[]updatingScoutIds: string[]@@ -212,6 +217,21 @@ export interface scoutFleetLogicActions {scoutMetadata: ScoutMetadataApi | nullpayload?: any}+ loadScoutRuns: () => any+ loadScoutRunsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadScoutRunsSuccess: (+ scoutRuns: SignalScoutRunSummary[],+ payload?: any+ ) => {+ scoutRuns: SignalScoutRunSummary[]+ payload?: any+ }patchScoutConfigLocally: (configId: string,updates: SignalScoutConfigUpdate@@ -272,7 +292,7 @@ export interface scoutFleetLogicMeta {dataProcessingApprovalDisabledReason: string | null) => string | nullscoutBannerMessage: (scoutMetadata: ScoutMetadataApi | null) => string | null- rollups: (runsWindow: { complete: boolean; runs: SignalScoutRunSummary[] }) => Map<string, ScoutRollup>+ rollups: (scoutRuns: SignalScoutRunSummary[]) => Map<string, ScoutRollup>fleetSummary: (scoutConfigs: SignalScoutConfigApi[] | null,rollups: Map<string, ScoutRollup>@@ -286,7 +306,6 @@ export interface scoutFleetLogicMeta {hideDisabled: boolean,activeScoutTags: string[]) => SignalScoutConfig[]- runsWindowComplete: (runsWindow: { complete: boolean; runs: SignalScoutRunSummary[] }) => booleanemittedFindingsSummary: (fleetFindingsSummary: FleetFindingsSummaryApi | null) => {authoredReportCount: numbercount: number@@ -387,6 +406,28 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([},},],+ // Each scout's most recent runs — what every per-scout stat (rollups, run history, fleet+ // success/emit rate) is computed over. One ranked query, so no page walk and no truncation:+ // the response is bounded by the fleet size, not by how often the fleet runs.+ scoutRuns: [+ [] as SignalScoutRunSummary[],+ {+ loadScoutRuns: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return values.scoutRuns+ }+ const runs = await signalsScoutRunsRecentPerScout(String(teamId), {+ per_scout_limit: SCOUT_RUNS_PER_SCOUT,+ })+ // Reuse prior references for unchanged runs so the 60s poll doesn't churn every+ // run's identity and needlessly re-render the memoized run/emission rows. Live+ // (running/queued) runs are never reused: their rows show a wall-clock duration+ // that must keep advancing with each poll.+ return reconcileById(values.scoutRuns, runs, (run) => run.run_id, isSettledRun)+ },+ },+ ],runsWindow: [{ runs: [] as SignalScoutRunSummary[], complete: true } as {runs: SignalScoutRunSummary[]@@ -518,6 +559,15 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([loadRunsWindowSuccess: () => true,},],+ // Same "loaded once, never on failure" contract as `runsWindowLoadedOnce`, for the per-scout+ // surfaces: it's what lets the scout detail sections tell "not loaded yet" from "loaded,+ // genuinely empty" without flashing a skeleton on every poll.+ scoutRunsLoadedOnce: [+ false,+ {+ loadScoutRunsSuccess: () => true,+ },+ ],// Flips true once the cheap findings summary lands, so the callout can tell "not loaded yet"// from "loaded, genuinely zero" without the full runs window. Like `runsWindowLoadedOnce`,// deliberately NOT set on failure: a failed load keeps the callout hidden, not falsely empty.@@ -541,9 +591,8 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([(scoutMetadata: ScoutMetadataApi | null): string | null => scoutMetadata?.banner_message ?? null,],rollups: [- (s) => [s.runsWindow],- (runsWindow: { complete: boolean; runs: SignalScoutRunSummary[] }): Map<string, ScoutRollup> =>- computeScoutRollups(runsWindow.runs),+ (s) => [s.scoutRuns],+ (scoutRuns: SignalScoutRunSummary[]): Map<string, ScoutRollup> => computeScoutRollups(scoutRuns),],fleetSummary: [(s) => [s.scoutConfigs, s.rollups],@@ -590,10 +639,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([return sorted.filter((config) => configMatchesScoutTags(config, activeScoutTags))},],- runsWindowComplete: [- (s) => [s.runsWindow],- (runsWindow: { complete: boolean; runs: SignalScoutRunSummary[] }): boolean => runsWindow.complete,- ],// Fleet-wide output tally for the "Scout findings" callout, read from the cheap backend// summary rather than the paginated runs window. Covers both emit channels — legacy findings// and reports authored/edited via the report channel — over the same capped set the findings@@ -830,13 +875,14 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([// Fetch once immediately, then a slow poll keeps "running now" + recent emissions// fresh. The keyed disposable replaces any prior poll and is torn down on// stopRunsPolling / unmount / tab hide. The cheap findings summary rides the same- // cadence so the "Scout findings" callout fills in on its own fast query rather than- // waiting on the paginated runs-window walk.- actions.loadRunsWindow()+ // cadence so the "Scout findings" callout fills in on its own fast query. The fleet+ // list needs only the per-scout runs; the paginated window is the findings page's own+ // source and is polled there.+ actions.loadScoutRuns()actions.loadFleetFindingsSummary()cache.disposables.add(() => {const interval = setInterval(() => {- actions.loadRunsWindow()+ actions.loadScoutRuns()actions.loadFleetFindingsSummary()}, RUNS_REFETCH_INTERVAL_MS)return () => clearInterval(interval)diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.tsindex d189f8f2dce8..dd7468749551 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts@@ -1,9 +1,9 @@// Ported from PostHog Desktop `packages/core/src/scouts/scoutRunsWindow.ts`// and `scoutPresentation.ts`. Pure metrics + display helpers over scout runs and-// configs; no I/O. The runs endpoint caps each response at 100 rows newest-first;-// `scoutFleetLogic.loadRunsWindow` assembles the full window by walking the-// `date_to` cursor (same as desktop), and these helpers frame all numbers as-// "the recent window" with a "truncated" suffix when that walk hits its page cap.+// configs; no I/O. Two different run sets feed them: the per-scout stats read+// `scoutFleetLogic.loadScoutRuns` (each scout's last N runs, one request), while the+// fleet findings feed reads `loadRunsWindow` (a fixed lookback assembled by walking+// the runs endpoint's `date_to` cursor past its 100-row page cap).import { humanFriendlyDuration } from 'lib/utils/durations'import { objectsEqual } from 'lib/utils/objects'@@ -14,13 +14,34 @@ import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signalsimport { SignalScoutRunStatus, SignalScoutRunSummary } from '../types'/**- * The window every scout stat describes. The cloud runs endpoint caps each list- * response at 100 rows newest-first; we frame all numbers as "the recent window- * we can see", matching desktop's fixed-window framing.+ * How many of each scout's most recent runs the per-scout stats describe — the count the+ * `recent-per-scout` endpoint is asked for, mirrored here so the labels match the data.+ *+ * Scouts run on their own schedules, so a shared time window can't serve them all: an hourly scout+ * fills a fleet-wide result cap on its own, and the daily and weekly ones end up with a history+ * that gets shorter the busier the rest of the fleet is. Counting per scout gives each the same+ * depth whatever its cadence.+ */+export const SCOUT_RUNS_PER_SCOUT = 25++/** Label for per-scout stats, e.g. "last 25 runs". */+export const SCOUT_RUNS_PER_SCOUT_LABEL = `last ${SCOUT_RUNS_PER_SCOUT} runs`++/**+ * Empty-state copy for a scout the window returned nothing for. Deliberately not "no runs in the+ * last 30 days": the endpoint's staleness guard stretches with each scout's own cadence, so the+ * cutoff a given scout was judged against is not a number the client knows.+ */+export const SCOUT_NO_RECENT_RUNS = 'No recent runs.'++/**+ * The time window the fleet-wide findings feed describes. Unlike the per-scout stats, that feed+ * answers "what has the troop surfaced lately?", which is a recency question — so it stays on a+ * fixed lookback, walked page by page from the runs endpoint's 100-row cap.*/export const SCOUT_RUNS_WINDOW_HOURS = 72-/** Human-friendly span the window covers, e.g. "3 days". */+/** Human-friendly span the findings window covers, e.g. "3 days". */export const SCOUT_RUNS_WINDOW_SPAN = ((): string => {if (SCOUT_RUNS_WINDOW_HOURS % 24 !== 0) {return `${SCOUT_RUNS_WINDOW_HOURS}h`@@ -29,12 +50,6 @@ export const SCOUT_RUNS_WINDOW_SPAN = ((): string => {return `${days} day${days === 1 ? '' : 's'}`})()-/** Label for stats derived from a window, e.g. "last 3 days". */-export function scoutRunsWindowLabel(complete: boolean): string {- const base = `last ${SCOUT_RUNS_WINDOW_SPAN}`- return complete ? base : `${base} · truncated`-}-// Fleet-wide findings views fetch/tally only the most recent N emitted runs, to bound the per-run// fan-out. Shared so the page (`findingsLogic`) and the callout summary count the exact same set.export const MAX_FLEET_EMITTED_RUNS = 120diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 0503f2670f2b..5d755a771303 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -1077,6 +1077,9 @@ tools:description:'DEPRECATED: renamed to scout-runs-recent-emissions. This alias forwards to the same endpoint and will beremoved. Call scout-runs-recent-emissions directly with the same arguments.'+ signals-scout-runs-recent-per-scout:+ operation: signals_scout_runs_recent_per_scout+ enabled: falsesignals-scout-runs-retrieve:operation: signals_scout_runs_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8907b19f10b1..1a16feee580d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -88529,6 +88529,21 @@ export namespace Schemas {window_hours?: number;};+ export type SignalsScoutRunsRecentPerScoutParams = {+ /**+ * Floor for the staleness guard on `created_at`, in days (default 30, hard cap 365). Runs older than the guard are excluded even when a scout has fewer than `per_scout_limit` newer ones, so a scout that stopped running doesn't report its last runs as current. Each scout's own cadence extends its guard to cover 3 runs' worth of its schedule, so a slow scout on a monthly cron or a 30-day interval keeps its history.+ * @minimum 1+ * @maximum 365+ */+ max_age_days?: number;+ /**+ * How many of each scout's most recent runs to return (default 25, hard cap 100). The count is per scout, so a scout's history depth does not depend on how often the rest of the fleet runs.+ * @minimum 1+ * @maximum 100+ */+ per_scout_limit?: number;+ };+export type SignalsScoutScratchpadSearchParams = {/*** Truncate each entry's `content` to the first N characters (a preview). Omit for the full body. Ignored when `keys_only=true`.