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): scout fleet + per-scout scheduling (5/7) (#57759)

Andrew Maguirea3d4f3fe8214
diff --git a/frontend/src/lib/components/ActivityLog/activityLogLogic.tsx b/frontend/src/lib/components/ActivityLog/activityLogLogic.tsx
index 3f7f333102ca..f1b6f874e0f4 100644
--- a/frontend/src/lib/components/ActivityLog/activityLogLogic.tsx
+++ b/frontend/src/lib/components/ActivityLog/activityLogLogic.tsx
@@ -50,6 +50,7 @@ import { ActivityScope } from '~/types'
import { ticketActivityDescriber } from 'products/conversations/frontend/activityDescriber'
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 { workflowActivityDescriber } from 'products/workflows/frontend/Workflows/misc/workflowActivityDescriber'
import type { activityLogLogicType } from './activityLogLogicType'
@@ -186,6 +187,8 @@ export const describerFor = (logItem?: ActivityLogItem): Describer | undefined =
return productTourActivityDescriber
case ActivityScope.TICKET:
return ticketActivityDescriber
+ case ActivityScope.SIGNAL_SCOUT_CONFIG:
+ return signalScoutConfigActivityDescriber
default:
return (logActivity, asNotification) => defaultDescriber(logActivity, asNotification)
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 9fed194ef31d..af97dfd5879a 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5630,6 +5630,7 @@ export enum ActivityScope {
PRODUCT_TOUR = 'ProductTour',
TICKET = 'Ticket',
INSTANCE_SETTING = 'InstanceSetting',
+ SIGNAL_SCOUT_CONFIG = 'SignalScoutConfig',
}
export type CommentType = {
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 72904298e363..2011dd56b13e 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -87,6 +87,7 @@ ActivityScope = Literal[
"ProductTour",
"Ticket",
"InstanceSetting",
+ "SignalScoutConfig",
]
ChangeAction = Literal[
"changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out", "copied"
@@ -285,6 +286,10 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {
"ExternalDataSchema": {
"should_sync": "enabled",
},
+ "SignalScoutConfig": {
+ "run_interval_minutes": "run interval (minutes)",
+ "emit": "emit findings",
+ },
"OrganizationDomain": {
"jit_provisioning_enabled": "just-in-time provisioning",
"sso_enforcement": "SSO enforcement",
@@ -330,6 +335,12 @@ signal_exclusions: dict[ActivityScope, list[str]] = {
"Subscription": [
"next_delivery_date",
],
+ # `last_run_at` is written by the scout coordinator on every tick (~every 15 min per scout).
+ # When that is the only change, suppress the activity signal entirely so run bookkeeping
+ # never spams the audit log.
+ "SignalScoutConfig": [
+ "last_run_at",
+ ],
}
# Activity visibility restrictions - controls which users can see certain activity logs
@@ -626,6 +637,13 @@ field_exclusions: dict[AuditableScope, list[str]] = {
# Reverse relations — auto-managed by FK creates, not user intent.
"reports",
],
+ "SignalScoutConfig": [
+ # Run bookkeeping, not user intent — keep it out of change detection even when it
+ # rides along with a real change (belt-and-suspenders with signal_exclusions above).
+ "last_run_at",
+ # Reverse relations auto-managed by FK creates, not user-initiated config changes.
+ "runs",
+ ],
}
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 88de0d3027ea..c01287a6470b 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -904,6 +904,7 @@ export type ActivityLogListParams = {
* `ProductTour` - ProductTour
* `Ticket` - Ticket
* `InstanceSetting` - InstanceSetting
+* `SignalScoutConfig` - SignalScoutConfig
* @minLength 1
*/
scope?: ActivityLogListScope
@@ -981,6 +982,7 @@ export const ActivityLogListScope = {
ProductTour: 'ProductTour',
Ticket: 'Ticket',
InstanceSetting: 'InstanceSetting',
+ SignalScoutConfig: 'SignalScoutConfig',
} as const
/**
@@ -1045,6 +1047,7 @@ export const ActivityLogListScope = {
* `ProductTour` - ProductTour
* `Ticket` - Ticket
* `InstanceSetting` - InstanceSetting
+ * `SignalScoutConfig` - SignalScoutConfig
*/
export type ActivityLogListScopesItem = (typeof ActivityLogListScopesItem)[keyof typeof ActivityLogListScopesItem]
@@ -1110,6 +1113,7 @@ export const ActivityLogListScopesItem = {
ProductTour: 'ProductTour',
Ticket: 'Ticket',
InstanceSetting: 'InstanceSetting',
+ SignalScoutConfig: 'SignalScoutConfig',
} as const
export type AdvancedActivityLogsListParams = {
diff --git a/products/signals/backend/activity_logging.py b/products/signals/backend/activity_logging.py
new file mode 100644
index 000000000000..238a98121423
--- /dev/null
+++ b/products/signals/backend/activity_logging.py
@@ -0,0 +1,62 @@
+"""Activity-log hook for SignalScoutConfig create/update/delete.
+
+`ModelActivityMixin.save()` only *emits* `model_activity_signal` — it does not persist
+anything. This receiver is the consumer that turns the emitted signal into a stored
+`ActivityLog` row. Without it, nothing about SignalScoutConfig would ever appear in the
+activity log. Imported from `SignalsConfig.ready()` so it registers at startup.
+"""
+
+import dataclasses
+from typing import Any
+
+import structlog
+
+from posthog.models.activity_logging.activity_log import (
+ ActivityContextBase,
+ ActivityScope,
+ Detail,
+ changes_between,
+ log_activity,
+)
+from posthog.models.signals import model_activity_signal, mutable_receiver
+from posthog.models.user import User
+
+from .models import SignalScoutConfig
+
+logger = structlog.get_logger(__name__)
+
+
[email protected](frozen=True)
+class SignalScoutConfigContext(ActivityContextBase):
+ skill_name: str
+
+
+@mutable_receiver(model_activity_signal, sender=SignalScoutConfig)
+def handle_signal_scout_config_change(
+ sender: type[SignalScoutConfig],
+ scope: ActivityScope,
+ before_update: SignalScoutConfig | None,
+ after_update: SignalScoutConfig | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance: SignalScoutConfig | None = after_update or before_update
+ if instance is None:
+ return
+
+ log_activity(
+ organization_id=None,
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=instance.id,
+ scope=scope,
+ activity=activity,
+ detail=Detail(
+ changes=changes_between(scope, previous=before_update, current=after_update),
+ name=instance.skill_name,
+ context=SignalScoutConfigContext(skill_name=instance.skill_name),
+ ),
+ )
diff --git a/products/signals/backend/admin.py b/products/signals/backend/admin.py
index f3bffc9cb95f..a96519cbbfa3 100644
--- a/products/signals/backend/admin.py
+++ b/products/signals/backend/admin.py
@@ -72,12 +72,21 @@ class SignalReportAdmin(admin.ModelAdmin):
@admin.register(SignalScoutConfig)
class SignalScoutConfigAdmin(admin.ModelAdmin):
- list_display = ("id", "team_link", "enabled", "created_at", "updated_at")
+ list_display = (
+ "id",
+ "team_link",
+ "skill_name",
+ "enabled",
+ "emit",
+ "run_interval_minutes",
+ "last_run_at",
+ "updated_at",
+ )
list_display_links = ("id",)
- list_filter = ("enabled",)
- search_fields = ("id", "team__name", "team__organization__name")
- raw_id_fields = ("team", "created_by")
- readonly_fields = ("id", "created_at", "updated_at")
+ list_filter = ("enabled", "emit")
+ search_fields = ("id", "skill_name", "team__name", "team__organization__name")
+ raw_id_fields = ("team", "created_by", "enabled_by")
+ readonly_fields = ("id", "created_at", "updated_at", "last_run_at")
list_select_related = ("team", "team__organization")
show_full_result_count = False
diff --git a/products/signals/backend/apps.py b/products/signals/backend/apps.py
index 144b56fa7c6d..9f4c46f75743 100644
--- a/products/signals/backend/apps.py
+++ b/products/signals/backend/apps.py
@@ -5,3 +5,8 @@ class SignalsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "products.signals.backend"
label = "signals"
+
+ def ready(self) -> None:
+ # Registers the model_activity_signal receiver that persists SignalScoutConfig
+ # audit-log entries. ModelActivityMixin only emits the signal; this is the consumer.
+ from . import activity_logging # noqa: F401
diff --git a/products/signals/backend/migrations/0028_reshape_scout_config_per_scout.py b/products/signals/backend/migrations/0028_reshape_scout_config_per_scout.py
new file mode 100644
index 000000000000..3af4fdc6b931
--- /dev/null
+++ b/products/signals/backend/migrations/0028_reshape_scout_config_per_scout.py
@@ -0,0 +1,89 @@
+# Generated by Django 5.2.14 on 2026-06-03 09:54
+
+import django.core.validators
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1205_delete_batch_export_models"),
+ ("signals", "0027_migrate_posthog_ai_models"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ # State-only removal: drop `enabled_skill_names` from Django's model state to match
+ # the reshaped model, but leave the (nullable) Postgres column in place. Avoids the
+ # backwards-incompatible, non-rollback-able `DROP COLUMN` during a rolling deploy —
+ # the orphaned column is harmless (new rows leave it NULL) and can be dropped in a
+ # later migration once this has shipped.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="signalscoutconfig",
+ name="enabled_skill_names",
+ ),
+ ],
+ ),
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="emit",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="enabled_by",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="last_run_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="run_interval_minutes",
+ field=models.PositiveIntegerField(
+ db_default=1440,
+ default=1440,
+ validators=[
+ django.core.validators.MinValueValidator(10),
+ django.core.validators.MaxValueValidator(43200),
+ ],
+ ),
+ ),
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="skill_name",
+ field=models.CharField(default="", max_length=200),
+ preserve_default=False,
+ ),
+ migrations.AlterField(
+ model_name="signalscoutconfig",
+ name="enabled",
+ field=models.BooleanField(db_default=True, default=True),
+ ),
+ migrations.AlterField(
+ model_name="signalscoutconfig",
+ name="team",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="signal_scout_configs",
+ to="posthog.team",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="signalscoutconfig",
+ constraint=models.UniqueConstraint(
+ fields=("team", "skill_name"), name="unique_scout_config_per_team_skill"
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/0029_wipe_legacy_scout_configs.py b/products/signals/backend/migrations/0029_wipe_legacy_scout_configs.py
new file mode 100644
index 000000000000..c4bea629cf47
--- /dev/null
+++ b/products/signals/backend/migrations/0029_wipe_legacy_scout_configs.py
@@ -0,0 +1,20 @@
+from django.db import migrations
+
+
+def _wipe_scout_configs(apps, schema_editor):
+ # Old rows were one-per-team; the reshaped table is one-per-(team, skill). There's no
+ # meaningful fan-out to preserve, and the table is dogfood-stage, so reset it — the
+ # coordinator re-registers a row per scout skill on the next tick. Kept in its own
+ # migration (separate transaction from the 0028 schema changes) so the data delete
+ # doesn't share a transaction with the ALTER TABLEs.
+ apps.get_model("signals", "SignalScoutConfig")._default_manager.all().delete()
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0028_reshape_scout_config_per_scout"),
+ ]
+
+ operations = [
+ migrations.RunPython(_wipe_scout_configs, migrations.RunPython.noop),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index bcf3247dd676..c7cdf568197c 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0027_migrate_posthog_ai_models
+0029_wipe_legacy_scout_configs
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index ee1ea9644919..c3fd0eb22ac4 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1,11 +1,14 @@
import logging
+from typing import Any
from django.contrib.postgres.fields import ArrayField
+from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils import timezone
from django_deprecate_fields import deprecate_field
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.team.extensions import register_team_extension_signal
from posthog.models.utils import UUIDModel
@@ -386,8 +389,15 @@ class SignalReportTask(UUIDModel):
# - SignalScratchpad: working notes the scout reads in future runs.
-class SignalScoutConfig(TeamScopedRootMixin, UUIDModel):
- """Per-team binding for the headless Signals scout. One row per team."""
+class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
+ """One row per (team, scout skill): schedule + emit posture for a `signals-scout-*` skill.
+
+ Changes are activity-logged (they drive spend). Team-level participation in the
+ dogfood program is gated by the `signals-scout` flag at the coordinator, not here.
+ """
+
+ # ModelActivityMixin only logs deletes when this is set.
+ activity_logging_on_delete = True
# `objects` (TeamScopedManager) inherited from TeamScopedRootMixin stays fail-closed for
# explicit user code. `all_teams` is the unscoped sibling for Django framework internals
@@ -397,20 +407,33 @@ class SignalScoutConfig(TeamScopedRootMixin, UUIDModel):
# doesn't bake it in (most callers don't need it).
all_teams = models.Manager() # noqa: DJ012
- team = models.OneToOneField(
+ team = models.ForeignKey(
"posthog.Team",
on_delete=models.CASCADE,
- related_name="signal_scout_config",
+ related_name="signal_scout_configs",
)
- enabled = models.BooleanField(default=False)
- # null = run all `signals-scout-*` skills the team has access to. A list narrows
- # the set; the harness still intersects with what's available in PHS.
- enabled_skill_names = ArrayField(
- base_field=models.CharField(max_length=200),
- null=True,
- blank=True,
- default=None,
+ # The `signals-scout-*` LLMSkill this row references (controlling only its scheduling /
+ # enablement, not the skill itself). The coordinator auto-creates a
+ # row when it discovers a scout skill on a participating team, so a user authoring
+ # `signals-scout-foo` gets a row (on the default schedule) on the next tick.
+ skill_name = models.CharField(max_length=200)
+ enabled = models.BooleanField(default=True, db_default=True)
+ # Dry-run vs emit. When False the scout runs and logs but `emit_finding` writes
+ # nothing — lets a scout be validated on a team before its findings reach the inbox.
+ emit = models.BooleanField(default=False, db_default=False)
+ # Minutes between runs. The coordinator dispatches this scout when
+ # `last_run_at is None or now - last_run_at >= run_interval_minutes`. Deterministic —
+ # no sampling. Floor of 10 keeps one scout from monopolising the worker pool; default
+ # 1440 = once a day. Ceiling 43200 = 30 days. `PositiveIntegerField` (int4) not
+ # `PositiveSmallIntegerField` (smallint, max 32767) so the documented 30-day ceiling fits.
+ run_interval_minutes = models.PositiveIntegerField(
+ default=1440,
+ db_default=1440,
+ validators=[MinValueValidator(10), MaxValueValidator(43200)],
)
+ # Stamped by the coordinator after each dispatch; drives the due-check. Written every
+ # run, so it is excluded from activity logging (see field_exclusions below).
+ last_run_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(
@@ -420,11 +443,31 @@ class SignalScoutConfig(TeamScopedRootMixin, UUIDModel):
blank=True,
related_name="+",
)
+ # Who last flipped `enabled` on. Tracked because enablement drives spend.
+ enabled_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ )
class Meta:
verbose_name = "Signal scout config"
verbose_name_plural = "Signal scout configs"
default_manager_name = "all_teams"
+ constraints = [
+ models.UniqueConstraint(fields=["team", "skill_name"], name="unique_scout_config_per_team_skill"),
+ ]
+
+ def _get_before_update(self, **kwargs: Any) -> "SignalScoutConfig | None":
+ # ModelActivityMixin's prior-state lookup goes through `objects` (the fail-closed
+ # TeamScopedManager). Edits from Django admin / the coordinator / a shell run with no
+ # team scope set, so route the lookup through the unscoped `all_teams` manager to avoid
+ # a TeamScopeError when logging the change.
+ if not self.pk:
+ return None
+ return type(self).all_teams.filter(pk=self.pk).first()
class SignalScoutRun(TeamScopedRootMixin, UUIDModel):
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index 8fd14f479e1a..6bc0b5d8c3ed 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -3,6 +3,7 @@ from posthog.api.routing import RouterRegistry
import products.signals.backend.views as signals
from products.signals.backend.scout_harness.views import (
SignalProjectProfileViewSet,
+ SignalScoutConfigViewSet,
SignalScoutRunViewSet,
SignalScratchpadViewSet,
)
@@ -38,6 +39,9 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"signals/scout/runs", SignalScoutRunViewSet, "environment_signals_scout_runs", ["team_id"]
)
+ routers.projects.register(
+ r"signals/scout/configs", SignalScoutConfigViewSet, "environment_signals_scout_configs", ["team_id"]
+ )
routers.projects.register(
r"signals/scout/scratchpad", SignalScratchpadViewSet, "environment_signals_scout_scratchpad", ["team_id"]
)
diff --git a/products/signals/backend/scout_harness/lazy_seed.py b/products/signals/backend/scout_harness/lazy_seed.py
index 271697513eaa..a09f92857c85 100644
--- a/products/signals/backend/scout_harness/lazy_seed.py
+++ b/products/signals/backend/scout_harness/lazy_seed.py
@@ -25,10 +25,14 @@ _SKILLS_DIR = Path(__file__).resolve().parent.parent.parent / "skills"
# Mirrors the regex in `products/posthog_ai/scripts/build_skills.py` so frontmatter parsing
# stays consistent across the two consumers. Keep these in sync if the skill spec evolves.
_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
-# Bundled subdirs (references / scripts) are walked recursively when seeding.
+# Bundled subdirs walked recursively. Kept in lockstep with `_ALLOWED_SUBDIRS` in
+# `products/posthog_ai/scripts/build_skills.py` — diverging here means a file format
+# `hogli build:skills` ignores would silently land in the team's `LLMSkillFile` rows
+# (or vice versa). The agentskills.io spec also defines `assets/`; if we ever want to
+# support binary attachments, add to both consumers in the same change.
_ALLOWED_BUNDLE_SUBDIRS = ("references", "scripts")
# Mirror the per-skill contract limits enforced by the REST API at
-# `products/llm_analytics/backend/api/skill_services.py` (`MAX_SKILL_*`). The seed
+# `products/ai_observability/backend/api/skill_services.py` (`MAX_SKILL_*`). The seed
# bypasses the service layer (no "create from scratch with files" helper exists), so
# these are inlined and checked at parse time. Inlined rather than imported because
# `skill_services.py` pulls in Django app surface that triggers a circular import
@@ -54,7 +58,9 @@ class CanonicalSkill:
`name` and `description` come from SKILL.md frontmatter. `body` is the markdown after the
frontmatter. `allowed_tools` is optional in frontmatter — defaults to empty (no narrowing).
- `files` is the recursive content of `references/` and `scripts/` subdirs alongside SKILL.md.
+ The agentskills.io spec uses `allowed-tools` (hyphen); we accept both, preferring the
+ spec form. `files` is the recursive content of the `_ALLOWED_BUNDLE_SUBDIRS` directories
+ alongside SKILL.md.
"""
name: str
@@ -105,9 +111,29 @@ def _parse_canonical_skill(skill_dir: Path) -> CanonicalSkill:
f"Canonical skill name must start with '{SIGNALS_SCOUT_SKILL_PREFIX}': got {name!r} in {skill_file}"
)
- raw_allowed = frontmatter.get("allowed_tools", []) or []
+ # The agentskills.io spec uses `allowed-tools` (hyphen). We prefer the spec form, but accept
+ # the underscore form too — it predated the spec alignment in this codebase and is used by
+ # other PHS skills. Reject if both keys are set so a future divergence doesn't go unnoticed.
+ if "allowed-tools" in frontmatter and "allowed_tools" in frontmatter:
+ raise CanonicalSkillParseError(
+ f"SKILL.md frontmatter has both 'allowed-tools' and 'allowed_tools'; pick one: {skill_file}"
+ )
+ # Branch on key presence rather than truthiness: a falsy-but-invalid value
+ # (`allowed-tools:` / null, `false`, `""`) must fail validation, not silently
+ # fall back to `[]` — which means "no narrowing" and would broaden tool access.
+ if "allowed-tools" in frontmatter:
+ raw_allowed = frontmatter["allowed-tools"]
+ elif "allowed_tools" in frontmatter:
+ raw_allowed = frontmatter["allowed_tools"]
+ else:
+ raw_allowed = []
if not isinstance(raw_allowed, list) or not all(isinstance(t, str) for t in raw_allowed):
- raise CanonicalSkillParseError(f"SKILL.md frontmatter 'allowed_tools' must be a list of strings: {skill_file}")
+ # Mention both accepted keys. The validator runs after we've merged the two forms
+ # above, so we can't tell which the author wrote — naming only the spec form would
+ # send authors using the underscore form looking for a key they didn't write.
+ raise CanonicalSkillParseError(
+ f"SKILL.md frontmatter 'allowed-tools'/'allowed_tools' must be a list of strings: {skill_file}"
+ )
body = raw[match.end() :]
# Enforce the same per-skill limits the REST API uses (skill_services.py). The seed
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 62837028a167..13885ed84f2c 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -86,10 +86,8 @@ async def arun_signals_scout(
) -> RunResult:
"""Async core. Safe to call from inside a running event loop (Temporal activity)."""
team = await database_sync_to_async(_get_team, thread_sensitive=False)(team_id)
- config = await database_sync_to_async(_resolve_config, thread_sensitive=False)(team)
# Lazy-seed canonical signals-scout-* skills if the team has none yet, so the run
- # has something to load. Failures here should not crash the run — we log and continue
- # with whatever skills the team already has.
+ # has something to load. Failures here are logged, not fatal.
try:
await database_sync_to_async(seed_canonical_skills, thread_sensitive=False)(team)
except Exception:
@@ -100,6 +98,7 @@ async def arun_signals_scout(
skill = await database_sync_to_async(load_skill_for_run, thread_sensitive=False)(
team, skill_name, version=skill_version
)
+ config = await database_sync_to_async(_resolve_config, thread_sensitive=False)(team, skill.name)
# Skip-if-running guard. Best-effort — there is a race window between this check
# and the row insert below (a second trigger could land in between), which we
@@ -273,16 +272,16 @@ def _get_team(team_id: int) -> Team:
return Team.objects.select_related("organization").get(id=team_id)
-def _resolve_config(team: Team) -> SignalScoutConfig:
- """Get-or-create the config row keyed on the canonical (parent) team.
+def _resolve_config(team: Team, skill_name: str) -> SignalScoutConfig:
+ """Get-or-create the (team, skill) config row, keyed on the canonical (parent) team.
- Default is safe (enabled=False). `SignalScoutConfig` is `TeamScopedRootMixin`, so
- `save()` rewrites a child-environment team to its parent — but the *lookup* half of
- `get_or_create` is not canonicalized. A child-team lookup would miss an existing
- parent row and then try to `create` a duplicate `OneToOne(team)` record, raising
- `IntegrityError`. Resolve to the canonical id so the lookup matches the stored row.
+ `get_or_create`'s lookup half isn't canonicalized by the TeamScopedRootMixin `save()`,
+ so resolve to the parent id ourselves — else a child-team lookup misses the stored row
+ and tries to create a duplicate, raising IntegrityError on the unique constraint.
"""
- config, _ = SignalScoutConfig.objects.unscoped().get_or_create(team_id=team.parent_team_id or team.id)
+ config, _ = SignalScoutConfig.objects.unscoped().get_or_create(
+ team_id=team.parent_team_id or team.id, skill_name=skill_name
+ )
return config
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 19cc5c409808..906d27fa9527 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -12,6 +12,7 @@ from rest_framework import serializers
from posthog.schema import Severity
+from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.tools.scratchpad import MAX_SCRATCHPAD_CONTENT_LENGTH
# --- Run history -----------------------------------------------------------
@@ -804,3 +805,43 @@ class ProjectProfileSerializer(serializers.Serializer):
payload = ProjectProfilePayloadSerializer(
help_text="Structured profile content. v1 has `inventory` only.",
)
+
+
+# --- Scout config ----------------------------------------------------------
+
+
+class SignalScoutConfigSerializer(serializers.ModelSerializer):
+ """Per-(team, skill) scout config: schedule, enablement, and emit posture.
+
+ One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
+ when it discovers a scout skill; this serializer lets agents tune the row.
+ """
+
+ skill_name = serializers.CharField(
+ read_only=True,
+ help_text="The `signals-scout-*` skill this config controls. Set at creation, not editable.",
+ )
+ enabled = serializers.BooleanField(
+ required=False,
+ help_text="Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator.",
+ )
+ emit = serializers.BooleanField(
+ required=False,
+ help_text="Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing.",
+ )
+ run_interval_minutes = serializers.IntegerField(
+ required=False,
+ min_value=10,
+ max_value=43200,
+ help_text="Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.",
+ )
+ last_run_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When the coordinator last dispatched this scout. Null if it has never run.",
+ )
+
+ class Meta:
+ model = SignalScoutConfig
+ fields = ["id", "skill_name", "enabled", "emit", "run_interval_minutes", "last_run_at", "created_at"]
+ read_only_fields = ["id", "created_at"]
diff --git a/products/signals/backend/scout_harness/tools/emit.py b/products/signals/backend/scout_harness/tools/emit.py
index 0353715f6388..e92cfc43c632 100644
--- a/products/signals/backend/scout_harness/tools/emit.py
+++ b/products/signals/backend/scout_harness/tools/emit.py
@@ -26,7 +26,7 @@ from typing import Any
from posthog.models import Team
from posthog.sync import database_sync_to_async
-from products.signals.backend.models import SignalScoutRun, SignalSourceConfig
+from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalSourceConfig
logger = logging.getLogger(__name__)
@@ -62,6 +62,8 @@ class EmitResult:
Possible `skipped_reason` values:
- None: emit fired
+ - "scout_config_missing": no SignalScoutConfig row for this (team, skill) — fail closed
+ - "scout_emit_disabled": the scout's config has emit=False (dry-run)
- "ai_processing_not_approved": team's organization has not approved AI processing
- "source_disabled": SignalSourceConfig disables the signals_scout source for this team
"""
@@ -120,7 +122,7 @@ async def emit_finding(
)
logger.info("signals_scout.emit: attempt", extra=attempt_extra)
- preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team)
+ preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)
if preflight is not None:
logger.warning(
"signals_scout.emit: skipped %s",
@@ -200,7 +202,7 @@ def emit_finding_sync(
)
logger.info("signals_scout.emit: attempt", extra=attempt_extra)
- preflight = _preflight_emit_gates(team)
+ preflight = _preflight_emit_gates(team, run)
if preflight is not None:
logger.warning(
"signals_scout.emit: skipped %s",
@@ -330,15 +332,24 @@ def _log_extra(
}
-def _preflight_emit_gates(team: Team) -> str | None:
- """Return the matching skipped_reason if a downstream gate would silently drop
- the emit; otherwise return None.
+def _preflight_emit_gates(team: Team, run: SignalScoutRun) -> str | None:
+ """Return the matching skipped_reason if a gate would drop the emit; else None.
`emit_signal()` returns silently when the team's organization has not approved
AI processing or when `SignalSourceConfig.is_source_enabled(...)` is False.
Surfacing the gate result here lets the view return a useful skipped_reason
- instead of "emitted" for an emit the pipeline silently dropped.
+ instead of "emitted" for an emit the pipeline silently dropped. The per-scout
+ `emit` toggle is checked first: a dry-run scout runs and logs but emits nothing.
+
+ Fails closed when no config row exists: `SignalScoutRun.scout_config` is nullable and a
+ config can be deleted mid-run, but a recreated config defaults to dry-run (`emit=False`),
+ so a missing config must not be treated as "emit allowed".
"""
+ config = SignalScoutConfig.all_teams.filter(team_id=team.id, skill_name=run.skill_name).first()
+ if config is None:
+ return "scout_config_missing"
+ if not config.emit:
+ return "scout_emit_disabled"
organization = team.organization
if not organization.is_ai_data_processing_approved:
return "ai_processing_not_approved"
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 9e2dfe401ef5..cfbe2361cdb0 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -39,7 +39,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.permissions import APIScopePermission
-from products.signals.backend.models import SignalProjectProfile, SignalScoutRun
+from products.signals.backend.models import SignalProjectProfile, SignalScoutConfig, SignalScoutRun
from products.signals.backend.scout_harness.serializers import (
EmitFindingRequestSerializer,
EmitFindingResponseSerializer,
@@ -52,6 +52,7 @@ from products.signals.backend.scout_harness.serializers import (
ScratchpadEntrySerializer,
SearchMemoryQuerySerializer,
SearchRecentRunsQuerySerializer,
+ SignalScoutConfigSerializer,
SignalScoutRunDetailSerializer,
SignalScoutRunSummarySerializer,
)
@@ -482,3 +483,66 @@ class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
if profile is None:
raise exceptions.NotFound("No project profile has been built for this team yet.")
return Response(ProjectProfileSerializer(profile.as_dict()).data)
+
+
+class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Per-scout config: list and tune each scout's schedule, enablement, and emit posture.
+
+ `list` is read (`signal_scout:read`); `partial_update` is a user-grantable write
+ (`signal_scout:write`) — config changes drive spend, so enablement is activity-logged
+ and `enabled_by` records who flipped it on.
+ """
+
+ serializer_class = SignalScoutConfigSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "signal_scout"
+ queryset = SignalScoutConfig.objects.unscoped()
+ lookup_field = "id"
+ pagination_class = None
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=SignalScoutConfigSerializer(many=True),
+ description="Per-scout configs for this project, ordered by skill name.",
+ ),
+ },
+ summary="List scout configs",
+ description=(
+ "List the per-(team, skill) scout configs for this project — schedule "
+ "(`run_interval_minutes`), `enabled`, and `emit` posture per scout."
+ ),
+ operation_id="signals_scout_config_list",
+ )
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ configs = SignalScoutConfig.objects.unscoped().filter(team_id=_canonical_team_id(self)).order_by("skill_name")
+ return Response(SignalScoutConfigSerializer(configs, many=True).data)
+
+ @extend_schema(
+ request=SignalScoutConfigSerializer,
+ responses={
+ 200: OpenApiResponse(response=SignalScoutConfigSerializer, description="Updated config."),
+ 404: OpenApiResponse(description="Config not found for this project."),
+ },
+ summary="Update a scout config",
+ description=(
+ "Tune one scout: change its schedule (`run_interval_minutes`), `enabled`, or `emit` "
+ "(dry-run) posture. `skill_name` is fixed. Enabling records `enabled_by` and is "
+ "activity-logged since it drives spend."
+ ),
+ operation_id="signals_scout_config_update",
+ )
+ def partial_update(self, request: Request, *args, **kwargs) -> Response:
+ config_id = _parse_run_id_or_404(kwargs)
+ config = SignalScoutConfig.objects.unscoped().filter(team_id=_canonical_team_id(self), id=config_id).first()
+ if config is None:
+ raise exceptions.NotFound()
+ serializer = SignalScoutConfigSerializer(config, data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ # Fold `enabled_by` into the same save so enabling logs one activity entry, not two.
+ save_kwargs = {}
+ if not config.enabled and serializer.validated_data.get("enabled"):
+ save_kwargs["enabled_by"] = request.user
+ instance = serializer.save(**save_kwargs)
+ return Response(SignalScoutConfigSerializer(instance).data)
diff --git a/products/signals/backend/temporal/agentic/schedule.py b/products/signals/backend/temporal/agentic/schedule.py
index 9acabf72c6f1..26dfc038b868 100644
--- a/products/signals/backend/temporal/agentic/schedule.py
+++ b/products/signals/backend/temporal/agentic/schedule.py
@@ -29,7 +29,7 @@ SIGNALS_SCOUT_COORDINATOR_WORKFLOW_NAME = "run-signals-scout-coordinator"
async def create_signals_scout_coordinator_schedule(client: Client) -> None:
- """Create or update the hourly schedule that drives the Signals agent coordinator.
+ """Create or update the schedule that drives the Signals agent coordinator.
The coordinator runs on the existing signals task queue (currently
`VIDEO_EXPORT_TASK_QUEUE`, shared with the rest of the signals temporal worker).
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index ea1b6e875e14..406dc856b712 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -1,15 +1,18 @@
from __future__ import annotations
import json
-import random
from dataclasses import dataclass
-from datetime import timedelta
+from datetime import datetime, timedelta
+
+from django.utils import timezone
import structlog
+import posthoganalytics
from temporalio import activity, workflow
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
@@ -21,14 +24,17 @@ from products.signals.backend.temporal.agentic.scout_scheduler import RunSignals
logger = structlog.get_logger(__name__)
-# Hard cap on planned runs per coordinator tick. Defends against a config explosion
-# (e.g. someone seeds 50 skills) overwhelming the worker pool. If we exceed this we
-# truncate after sorting; the next tick picks up where we left off because the runner
-# is idempotent on (team, skill).
+# Team-level dogfood gate. The single team gate (no per-team model boolean): the flag
+# picks which teams run scouts; per-scout SignalScoutConfig rows pick which scouts/schedules.
+SIGNALS_SCOUT_DOGFOOD_FLAG = "signals-scout"
+
+# Hard cap on dispatches per tick. The cost bound: when more scouts are due than this,
+# we run the most-overdue first and the rest catch up next tick (a poor-man's queue).
MAX_RUNS_PER_TICK = 50
-# Default schedule cadence. v1 spec: "stagger schedule, ~1 run per agent per hour".
-COORDINATOR_INTERVAL_MINUTES = 60
+# Coordinator tick cadence. Per-scout schedules are enforced via the due-check, so this is
+# just the polling granularity — the floor on how often any scout can run.
+COORDINATOR_INTERVAL_MINUTES = 15
@dataclass
@@ -69,11 +75,11 @@ class CoordinatorWorkflowOutput:
async def fetch_enabled_signals_scout_runs_activity(
_input: FetchEnabledRunsInput,
) -> FetchEnabledRunsOutput:
- """Resolve the set of (team, skill) runs to trigger this tick.
+ """Resolve the set of (team, skill) runs to dispatch this tick.
- Reads enabled `SignalScoutConfig` rows; for each one, expands to the configured
- skill list, falling back to a glob over the team's `signals-scout-*` skills when
- `enabled_skill_names` is null. Skips configs where the resulting skill list is empty.
+ Scans dogfood teams (gated by the `signals-scout` flag), auto-registers a config row
+ for any `signals-scout-*` skill missing one, and dispatches each enabled scout whose
+ schedule is due — most-overdue first, capped at MAX_RUNS_PER_TICK.
"""
async with Heartbeater():
planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)()
@@ -81,94 +87,118 @@ async def fetch_enabled_signals_scout_runs_activity(
return FetchEnabledRunsOutput(planned_runs=planned)
+@dataclass
+class _DueRun:
+ overdue_s: float
+ config_pk: str
+ team_id: int
+ skill_name: str
+
+
def _collect_planned_runs() -> list[PlannedRun]:
"""Sync DB scan. Runs in a worker thread via Django's per-thread connection mgmt."""
- # TODO(phase 4): gate behind the `signals-scout-dogfood` feature flag once it
- # exists. For now the `enabled=False` default on `SignalScoutConfig` is the gate.
- # `.unscoped()` is intentional: the coordinator scans every team's config to plan
- # cross-team runs. The default `.objects` manager is fail-closed (TeamScopedRootMixin)
- # and would raise without an active team_scope — but this is the one caller for
- # which "every team" is the correct answer, not a footgun.
- configs = list(
- SignalScoutConfig.objects.unscoped().filter(enabled=True).select_related("team").order_by("team__id")
- )
- planned: list[PlannedRun] = []
- for config in configs:
- team = config.team
- team_id = team.id
- # Lazy-seed canonical signals-scout-* skills before we resolve the skill list.
- # Without this, a brand-new team with `enabled_skill_names=None` and zero
- # LLMSkill rows would produce an empty planned set, no child runs would fan
- # out, and the runner-level lazy seed would never be reached — the cadence
- # path would silently never start. No-op when the team already has any
- # signals-scout-* row. Failures don't abort the tick: log and continue.
+ now = timezone.now()
+ due: list[_DueRun] = []
+ for team in _participating_teams():
+ # Seed canonical scouts so a freshly-enrolled team has skills to register on.
+ # Idempotent; a failure here doesn't abort the tick.
try:
seed_canonical_skills(team)
except Exception:
logger.exception(
- "signals_scout coordinator: lazy seed failed for team; continuing",
- team_id=team_id,
- )
- skill_names = _resolve_skill_names_for_config(config, team_id=team_id)
- for skill_name in skill_names:
- planned.append(
- PlannedRun(
- team_id=team_id,
- skill_name=skill_name,
- )
+ "signals_scout coordinator: canonical skill seed failed for team; continuing",
+ team_id=team.id,
)
- if len(planned) > MAX_RUNS_PER_TICK:
+ live_skills = _register_missing_configs(team)
+ # Skip enabled configs whose `signals-scout-*` skill was deleted or is no longer the
+ # latest version: dispatching them would spawn a child workflow that fails fast in
+ # load_skill_for_run on every tick.
+ for config in SignalScoutConfig.all_teams.filter(team_id=team.id, enabled=True, skill_name__in=live_skills):
+ overdue_s = _overdue_seconds(config, now)
+ if overdue_s is None:
+ continue
+ due.append(_DueRun(overdue_s, str(config.pk), team.id, config.skill_name))
+
+ if not due:
+ return []
+
+ # Cost bound: when more scouts are due than the cap, run the most-overdue first and let
+ # the rest catch up next tick. Deterministic — no sampling.
+ due.sort(key=lambda d: d.overdue_s, reverse=True)
+ if len(due) > MAX_RUNS_PER_TICK:
logger.warning(
- "signals_scout coordinator: sampling planned runs down to hard cap",
- planned=len(planned),
+ "signals_scout coordinator: more due than cap, deferring overflow",
+ due=len(due),
cap=MAX_RUNS_PER_TICK,
)
- # Randomly sample which runs make the cap rather than slicing a sorted prefix —
- # a deterministic cut by (team_id, skill_name) permanently starves the highest
- # team_ids whenever the plan exceeds the cap. This runs in an activity (not the
- # workflow), so non-deterministic sampling is allowed; per-tick child workflow ids
- # stay unique via tick_id regardless of order.
- planned = random.sample(planned, MAX_RUNS_PER_TICK)
- # Stable order (team_id, skill_name) for a predictable dispatch order + child-id idx
- # within the tick. Applied after sampling so the cap is a fair random subset.
+ due = due[:MAX_RUNS_PER_TICK]
+
+ # Advance the schedule for everything we dispatch. `.update()` bypasses save(), so this
+ # per-tick write never hits the activity log.
+ SignalScoutConfig.all_teams.filter(pk__in=[d.config_pk for d in due]).update(last_run_at=now)
+
+ planned = [PlannedRun(team_id=d.team_id, skill_name=d.skill_name) for d in due]
+ # Stable order for predictable child-workflow ids within the tick.
planned.sort(key=lambda p: (p.team_id, p.skill_name))
return planned
-def _resolve_skill_names_for_config(config: SignalScoutConfig, *, team_id: int) -> list[str]:
- """Return the ordered list of skill names to run for this team's config.
+def _participating_teams() -> list[Team]:
+ """Canonical dogfood teams: those with a scout skill or config, gated by the flag.
- `enabled_skill_names = None` → glob all `signals-scout-*` skills on the team.
- `enabled_skill_names = [list]` → use the list verbatim, but still validate each
- name actually exists on the team so the activity output is grounded in reality.
- Duplicates in the configured list are collapsed (preserving first-seen order) so
- a noisy config row can't fan out the same skill twice in one tick.
+ Bounded to teams that have opted into scouts (canonical fleet seeded or a user-authored
+ `signals-scout-*` skill) so the flag isn't evaluated against every team.
"""
- available = set(
+ team_ids = set(
LLMSkill.objects.filter(
- team_id=team_id,
+ name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,
+ is_latest=True,
+ deleted=False,
+ )
+ .values_list("team_id", flat=True)
+ .distinct()
+ )
+ team_ids |= set(SignalScoutConfig.all_teams.values_list("team_id", flat=True).distinct())
+ candidates = Team.objects.filter(id__in=team_ids)
+ canonical_ids = {team.parent_team_id or team.id for team in candidates}
+ canonical_teams = Team.objects.filter(id__in=canonical_ids).order_by("id")
+ return [
+ team for team in canonical_teams if posthoganalytics.feature_enabled(SIGNALS_SCOUT_DOGFOOD_FLAG, str(team.id))
+ ]
+
+
+def _register_missing_configs(team: Team) -> set[str]:
+ """Auto-create an enabled, default-schedule config for each scout skill lacking a row.
+
+ The "author a skill, get a scout" path: a user-authored `signals-scout-foo` skill gets
+ a row on the next tick with no further wiring. Returns the set of live `signals-scout-*`
+ skill names for the team, so the caller can skip dispatching configs whose skill is gone.
+ """
+ skill_names = set(
+ LLMSkill.objects.filter(
+ team_id=team.id,
name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,
is_latest=True,
deleted=False,
).values_list("name", flat=True)
)
- if config.enabled_skill_names is None:
- return sorted(available)
- requested = list(dict.fromkeys(config.enabled_skill_names))
- resolved = [name for name in requested if name in available]
- missing = [name for name in requested if name not in available]
- if missing:
- logger.warning(
- "signals_scout coordinator: configured skill names not found on team",
- team_id=team_id,
- missing=missing,
- )
- return resolved
+ existing = set(SignalScoutConfig.all_teams.filter(team_id=team.id).values_list("skill_name", flat=True))
+ for name in sorted(skill_names - existing):
+ SignalScoutConfig.all_teams.get_or_create(team_id=team.id, skill_name=name)
+ return skill_names
+
+
+def _overdue_seconds(config: SignalScoutConfig, now: datetime) -> float | None:
+ """Seconds past due, or None if not yet due. Never-run rows are maximally overdue."""
+ if config.last_run_at is None:
+ return float("inf")
+ overdue = (now - config.last_run_at).total_seconds() - config.run_interval_minutes * 60
+ return overdue if overdue >= 0 else None
@workflow.defn(name="run-signals-scout-coordinator")
class SignalsScoutCoordinatorWorkflow:
- """Hourly coordinator: scans enabled configs, fans out per-(team, skill) child runs.
+ """Coordinator: scans dogfood teams, fans out per-(team, skill) child runs for due scouts.
Dispatch is fire-and-forget: each child is started with `ParentClosePolicy.ABANDON`
so it outlives this workflow, and the coordinator returns immediately after the
@@ -202,7 +232,7 @@ class SignalsScoutCoordinatorWorkflow:
return CoordinatorWorkflowOutput(0, 0, 0)
# `workflow_id` (not `run_id`) is the correct per-tick key. Temporal appends the
- # scheduled time to a schedule-started workflow's id, so each hourly tick gets a
+ # scheduled time to a schedule-started workflow's id, so each tick gets a
# distinct `workflow_id` (`signals-scout-coordinator-schedule-<scheduled-time>`) —
# unique across ticks, which is what lets a later tick relaunch the same (team, skill).
# It's also stable across a coordinator retry/replay within the same tick (only
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index c602eb884368..a6cceb2b8bf9 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -1,10 +1,14 @@
from __future__ import annotations
import random
+from datetime import timedelta
+from typing import Any
import pytest
from unittest.mock import AsyncMock, patch
+from django.utils import timezone
+
import pytest_asyncio
from asgiref.sync import sync_to_async
from temporalio.exceptions import WorkflowAlreadyStartedError
@@ -16,8 +20,8 @@ from posthog.sync import database_sync_to_async
from products.ai_observability.backend.models.skills import LLMSkill
from products.signals.backend.models import SignalScoutConfig
+from products.signals.backend.scout_harness.lazy_seed import seed_canonical_skills
from products.signals.backend.temporal.agentic.scout_coordinator import (
- MAX_RUNS_PER_TICK,
CoordinatorWorkflowInput,
CoordinatorWorkflowOutput,
FetchEnabledRunsInput,
@@ -26,6 +30,13 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (
fetch_enabled_signals_scout_runs_activity,
)
+_FLAG_PATH = "products.signals.backend.temporal.agentic.scout_coordinator.posthoganalytics.feature_enabled"
+
+# The coordinator scans every team in the DB. These async tests commit (no transaction
+# rollback across the worker thread), so leftover teams from other modules can leak into
+# the scan. Flag only the teams this module created to keep the scan deterministic.
+_FLAGGED_TEAM_IDS: set[str] = set()
+
@pytest_asyncio.fixture
async def aorganization():
@@ -46,21 +57,24 @@ async def ateam(aorganization):
# Scout models use TeamScopedRootMixin (fail-closed); yield inside team_scope
# so test bodies that touch `Model.objects.X()` find a context.
# `canonical=True` skips the sync DB resolution lookup (illegal from async).
+ _FLAGGED_TEAM_IDS.add(str(team.id))
with team_scope(team.id, canonical=True):
yield team
+ _FLAGGED_TEAM_IDS.discard(str(team.id))
await sync_to_async(team.delete)()
@pytest_asyncio.fixture
async def aother_team(aorganization):
- # Sibling team used by cross-team tests; do NOT enter `team_scope` for it
- # (only one scope can be active at a time, and `ateam` is the primary one).
- # Cross-team writes should use `team_scope(aother_team.id, canonical=True)` explicitly.
+ # Sibling team for cross-team tests; not entered into team_scope (only one scope
+ # can be active at a time). Cross-team writes use team_scope(...) explicitly.
team = await sync_to_async(Team.objects.create)(
organization=aorganization,
name=f"SignalsCoordinatorOtherTeam-{random.randint(1, 99999)}",
)
+ _FLAGGED_TEAM_IDS.add(str(team.id))
yield team
+ _FLAGGED_TEAM_IDS.discard(str(team.id))
await sync_to_async(team.delete)()
@@ -68,153 +82,250 @@ def _create_skill(team: Team, name: str) -> LLMSkill:
return LLMSkill.objects.create(team=team, name=name, description="d", body="b")
+def _create_config(team: Team, skill_name: str, **kwargs: Any) -> SignalScoutConfig:
+ return SignalScoutConfig.objects.create(team=team, skill_name=skill_name, **kwargs)
+
+
[email protected](autouse=True)
+def _flag_on(request):
+ """Treat every team as in the dogfood flag by default.
+
+ Tests covering the gate itself opt out with `@pytest.mark.flag_off` and set their own
+ `feature_enabled` behavior.
+ """
+ if request.node.get_closest_marker("flag_off"):
+ yield
+ return
+ with patch(_FLAG_PATH, side_effect=lambda key, distinct_id, *a, **k: distinct_id in _FLAGGED_TEAM_IDS):
+ yield
+
+
[email protected](autouse=True)
+def _stub_canonical_seed(request):
+ """Stub `seed_canonical_skills` to a no-op so tests assert on hand-authored skills only.
+
+ Tests that exercise the real sync opt out via `@pytest.mark.real_canonical_seed`.
+ """
+ if request.node.get_closest_marker("real_canonical_seed"):
+ yield
+ return
+ with patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.seed_canonical_skills",
+ return_value=None,
+ ):
+ yield
+
+
+async def _run_activity() -> list[PlannedRun]:
+ env = ActivityEnvironment()
+ output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ return output.planned_runs
+
+
+# ── Gate: the signals-scout flag is the single team-level gate ───────────────────
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_disabled_config_is_skipped(ateam):
- # enabled defaults to False — get_or_create gives a disabled row.
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam, enabled=False)
+async def test_team_not_in_flag_is_skipped(ateam):
await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
+ await database_sync_to_async(_create_config)(ateam, "signals-scout-errors", enabled=True)
- env = ActivityEnvironment()
- output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ with patch(_FLAG_PATH, return_value=False):
+ planned = await _run_activity()
- assert output.planned_runs == []
+ assert planned == []
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_null_skill_list_globs_signals_scout_prefix(ateam):
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam, enabled=True, enabled_skill_names=None)
+async def test_disabled_config_is_skipped(ateam):
await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
- await database_sync_to_async(_create_skill)(ateam, "signals-scout-llm")
- # Non-matching prefix is ignored.
+ await database_sync_to_async(_create_config)(ateam, "signals-scout-errors", enabled=False)
+
+ assert await _run_activity() == []
+
+
+# ── Auto-register: author a skill, get a scout ──────────────────────────────────
+
+
+async def test_authoring_skill_auto_registers_enabled_config_and_runs(ateam):
+ # No config yet — just the authored skill.
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")
+
+ planned = await _run_activity()
+
+ config = await database_sync_to_async(SignalScoutConfig.all_teams.get)(team=ateam, skill_name="signals-scout-foo")
+ assert config.enabled is True
+ assert config.run_interval_minutes == 1440
+ assert config.emit is False
+ # Never-run row is immediately due, so it's dispatched this tick.
+ assert [(p.team_id, p.skill_name) for p in planned] == [(ateam.id, "signals-scout-foo")]
+
+
+async def test_non_scout_skills_are_ignored(ateam):
await database_sync_to_async(_create_skill)(ateam, "custom-helper")
- env = ActivityEnvironment()
- output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ assert await _run_activity() == []
+ count = await database_sync_to_async(SignalScoutConfig.all_teams.filter(team=ateam).count)()
+ assert count == 0
+
+
+async def test_config_whose_skill_is_gone_is_skipped(ateam):
+ # A config whose `signals-scout-*` skill was deleted (or is no longer latest) must not be
+ # dispatched — its child workflow would only fail in load_skill_for_run every tick.
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-live")
+ await database_sync_to_async(_create_config)(ateam, "signals-scout-live", enabled=True)
+ await database_sync_to_async(_create_config)(ateam, "signals-scout-ghost", enabled=True)
- names = [p.skill_name for p in output.planned_runs]
- assert names == ["signals-scout-errors", "signals-scout-llm"]
- assert all(p.team_id == ateam.id for p in output.planned_runs)
+ planned = await _run_activity()
+
+ assert [p.skill_name for p in planned] == ["signals-scout-live"]
+
+
+# ── Schedule: deterministic due-check, no sampling ──────────────────────────────
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_explicit_skill_list_filters_to_existing_only(ateam):
- await database_sync_to_async(SignalScoutConfig.objects.create)(
- team=ateam,
- enabled=True,
- enabled_skill_names=["signals-scout-errors", "signals-scout-typo"],
+async def test_config_within_interval_is_not_due(ateam):
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")
+ await database_sync_to_async(_create_config)(
+ ateam, "signals-scout-foo", enabled=True, run_interval_minutes=1440, last_run_at=timezone.now()
)
- await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
- await database_sync_to_async(_create_skill)(ateam, "signals-scout-llm") # not in list
- env = ActivityEnvironment()
- output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ assert await _run_activity() == []
- assert [p.skill_name for p in output.planned_runs] == ["signals-scout-errors"]
+
+async def test_overdue_config_runs_and_stamps_last_run_at(ateam):
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")
+ old = timezone.now() - timedelta(minutes=2000)
+ config = await database_sync_to_async(_create_config)(
+ ateam, "signals-scout-foo", enabled=True, run_interval_minutes=1440, last_run_at=old
+ )
+
+ before = timezone.now()
+ planned = await _run_activity()
+
+ assert [p.skill_name for p in planned] == ["signals-scout-foo"]
+ refreshed = await database_sync_to_async(SignalScoutConfig.all_teams.get)(pk=config.pk)
+ assert refreshed.last_run_at is not None and refreshed.last_run_at >= before
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_planned_runs_sort_by_team_then_skill(ateam, aother_team):
- # Insert in the "wrong" order to verify sort behavior.
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=aother_team, enabled=True)
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam, enabled=True)
- await database_sync_to_async(_create_skill)(aother_team, "signals-scout-errors")
- await database_sync_to_async(_create_skill)(ateam, "signals-scout-zeta")
- await database_sync_to_async(_create_skill)(ateam, "signals-scout-alpha")
+async def test_all_due_skills_run_no_sampling(ateam):
+ # Every due scout runs — there's no per-tick sampling anymore.
+ names = ["signals-scout-alpha", "signals-scout-beta", "signals-scout-gamma"]
+ for name in names:
+ await database_sync_to_async(_create_skill)(ateam, name)
- env = ActivityEnvironment()
- output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ planned = await _run_activity()
- pairs = [(p.team_id, p.skill_name) for p in output.planned_runs]
- # Sort key: (team_id, skill_name) — primary by team, secondary by skill name.
- assert pairs == sorted(pairs)
- assert set(pairs) == {
- (ateam.id, "signals-scout-alpha"),
- (ateam.id, "signals-scout-zeta"),
- (aother_team.id, "signals-scout-errors"),
- }
+ assert sorted(p.skill_name for p in planned) == names
+
+
+# ── Cost bound: most-overdue first under the cap ────────────────────────────────
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_lazy_seeds_canonical_skills_for_brand_new_team(ateam):
- # An enabled config on a brand-new team (no signals-scout-* skills yet) should
- # still produce planned runs: the coordinator lazy-seeds the canonical set on
- # first encounter so the cadence path doesn't depend on a manual seed step.
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam, enabled=True, enabled_skill_names=None)
-
- pre = await database_sync_to_async(
- lambda: list(
- LLMSkill.objects.filter(team=ateam, name__startswith="signals-scout-").values_list("name", flat=True)
- )
- )()
- assert pre == []
+async def test_cap_dispatches_most_overdue_first(ateam):
+ now = timezone.now()
+ # Three due scouts, descending overdue-ness; cap to 2 → the two most overdue win.
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-most")
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-mid")
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-least")
+ await database_sync_to_async(_create_config)(
+ ateam, "signals-scout-most", enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=10)
+ )
+ await database_sync_to_async(_create_config)(
+ ateam, "signals-scout-mid", enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=5)
+ )
+ await database_sync_to_async(_create_config)(
+ ateam, "signals-scout-least", enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=2)
+ )
- env = ActivityEnvironment()
- output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ with patch("products.signals.backend.temporal.agentic.scout_coordinator.MAX_RUNS_PER_TICK", 2):
+ planned = await _run_activity()
- seeded = await database_sync_to_async(
- lambda: list(
- LLMSkill.objects.filter(team=ateam, name__startswith="signals-scout-").values_list("name", flat=True)
- )
- )()
- # The canonical fleet ships `signals-scout-general` (cross-product generalist) plus
- # specialists; assert at least one canonical skill was seeded and made it into
- # planned runs, rather than naming a specific one (so future canonical additions
- # or renames don't break this test).
- assert any(name.startswith("signals-scout-") for name in seeded)
- assert any(p.skill_name.startswith("signals-scout-") for p in output.planned_runs)
+ assert sorted(p.skill_name for p in planned) == ["signals-scout-mid", "signals-scout-most"]
+
+
+async def test_planned_runs_sorted_by_team_then_skill(ateam, aother_team):
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-zeta")
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-alpha")
+
+ def _seed_other():
+ with team_scope(aother_team.id, canonical=True):
+ _create_skill(aother_team, "signals-scout-errors")
+
+ await database_sync_to_async(_seed_other)()
+
+ planned = await _run_activity()
+
+ keys = [(p.team_id, p.skill_name) for p in planned]
+ assert keys == sorted(keys)
+ assert set(keys) == {
+ (ateam.id, "signals-scout-alpha"),
+ (ateam.id, "signals-scout-zeta"),
+ (aother_team.id, "signals-scout-errors"),
+ }
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_lazy_seed_failure_does_not_abort_tick(ateam, aother_team):
- # If lazy seed fails for one team, the coordinator should still plan runs for
- # other teams and for skills that already exist on the failing team.
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam, enabled=True)
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=aother_team, enabled=True)
- # ateam already has a hand-authored skill — the seed call shouldn't even fire
- # for them (existing-rows short-circuit) but if it did and somehow raised,
- # we still want planning to succeed.
+async def test_seed_failure_does_not_abort_tick(ateam):
await database_sync_to_async(_create_skill)(ateam, "signals-scout-existing")
with patch(
"products.signals.backend.temporal.agentic.scout_coordinator.seed_canonical_skills",
side_effect=RuntimeError("simulated seed failure"),
):
- env = ActivityEnvironment()
- output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ planned = await _run_activity()
- # ateam's existing skill is still plannable; aother_team has no skills and
- # the failed seed left it empty, so it contributes nothing — but the tick
- # didn't crash.
- assert any(p.team_id == ateam.id and p.skill_name == "signals-scout-existing" for p in output.planned_runs)
+ assert any(p.team_id == ateam.id and p.skill_name == "signals-scout-existing" for p in planned)
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_truncates_above_hard_cap(ateam):
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam, enabled=True)
- # Exceed the cap.
- for i in range(MAX_RUNS_PER_TICK + 5):
- await database_sync_to_async(_create_skill)(ateam, f"signals-scout-{i:03d}")
[email protected]_canonical_seed
+async def test_enrolled_team_registers_and_runs_canonical_fleet(ateam):
+ # Enrolling a team seeds the canonical fleet; the coordinator then auto-registers a
+ # config per seeded skill and dispatches the due ones.
+ await database_sync_to_async(seed_canonical_skills)(ateam)
+ seeded = await database_sync_to_async(
+ lambda: set(
+ LLMSkill.objects.filter(team=ateam, name__startswith="signals-scout-").values_list("name", flat=True)
+ )
+ )()
+ assert seeded
- env = ActivityEnvironment()
- output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())
+ planned = await _run_activity()
- assert len(output.planned_runs) == MAX_RUNS_PER_TICK
+ config_names = await database_sync_to_async(
+ lambda: set(SignalScoutConfig.all_teams.filter(team=ateam).values_list("skill_name", flat=True))
+ )()
+ assert config_names == seeded
+ assert {p.skill_name for p in planned} == seeded
-# ── Workflow-level tests ────────────────────────────────────────────────────────
+# ── Workflow-level dispatch ─────────────────────────────────────────────────────
#
-# The coordinator dispatches child workflows fire-and-forget via `start_child_workflow`
-# with `ParentClosePolicy.ABANDON`, so it returns as soon as the last dispatch resolves.
-# We patch the activity + `start_child_workflow` and assert dispatch counts (started vs
-# already-running skip) rather than completion outcomes — child runtime success is the
-# child workflow's contract, not the coordinator's.
+# The coordinator dispatches children fire-and-forget via `start_child_workflow` with
+# `ParentClosePolicy.ABANDON`. We patch the activity + `start_child_workflow` and assert
+# dispatch counts (started vs already-running skip), not completion outcomes.
@pytest.mark.asyncio
@@ -281,7 +392,6 @@ async def test_workflow_dispatches_children_fire_and_forget():
assert output.planned_count == 3
assert output.started_count == 2
assert output.skipped_count == 1
- # All three planned runs were dispatched in order, even though one was a dedupe-skip.
assert dispatch_calls == [
(1, "signals-scout-a"),
(1, "signals-scout-b"),
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index f0123dc3fa15..f559f07c38b6 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -239,8 +239,9 @@ async def test_successful_run_creates_bridge_row_pointing_at_task_run(ateam, aer
# Agent close-out is persisted on the bridge row so future runs can dedupe
# against non-emitting runs via the runs-list ILIKE filter.
assert bridge.summary == "I would investigate /checkout 500s next."
- config = await database_sync_to_async(SignalScoutConfig.objects.get)(team=ateam)
- assert config.enabled is False
+ config = await database_sync_to_async(SignalScoutConfig.objects.get)(team=ateam, skill_name="signals-scout-errors")
+ # Auto-created configs default to enabled (the dogfood flag is the team-level gate).
+ assert config.enabled is True
assert bridge.scout_config_id == config.id
@@ -286,7 +287,9 @@ async def test_missing_skill_does_not_create_run_row(ateam):
@pytest.mark.django_db
async def test_skip_if_running_prevents_concurrent_runs(ateam, aerrors_skill):
# Seed an in-progress run for the same (team, skill) so the skip-if-running guard fires.
- config = await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam)
+ config = await database_sync_to_async(SignalScoutConfig.objects.create)(
+ team=ateam, skill_name="signals-scout-errors"
+ )
task_run = await database_sync_to_async(_make_task_run)(ateam)
# Force the TaskRun into IN_PROGRESS so the running-check returns True.
await database_sync_to_async(TaskRun.objects.filter(id=task_run.id).update)(status=TaskRun.Status.IN_PROGRESS)
@@ -415,7 +418,7 @@ def test_to_summary_and_detail_surface_task_url_from_bridge():
name=f"surface-team-{random.randint(1, 99999)}",
)
with team_scope(team.id, canonical=True):
- config = SignalScoutConfig.objects.create(team=team)
+ config = SignalScoutConfig.objects.create(team=team, skill_name="signals-scout-errors")
task_run = _make_task_run(team)
run = SignalScoutRun.objects.create(
task_run=task_run,
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 80e29098ab9b..8e024828a932 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -73,7 +73,9 @@ def _make_task_run(team: Team, *, status: str | None = None) -> TaskRun:
def _make_run(team: Team, *, task_run_status: str = TaskRun.Status.IN_PROGRESS, **overrides) -> SignalScoutRun:
"""Build a SignalScoutRun bridge row whose TaskRun is in the given status."""
- config, _ = SignalScoutConfig.objects.get_or_create(team=team)
+ config, _ = SignalScoutConfig.objects.get_or_create(
+ team=team, skill_name="signals-scout-general", defaults={"emit": True}
+ )
task_run = _make_task_run(team, status=task_run_status)
defaults: dict = {
"task_run": task_run,
@@ -466,3 +468,63 @@ class TestAgentHarnessProjectProfileAPI(APIBaseTest):
"recent_actions",
"top_events",
}
+
+
+class TestScoutHarnessConfigAPI(APIBaseTest):
+ def _list_url(self) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/configs/"
+
+ def _detail_url(self, config_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/configs/{config_id}/"
+
+ def test_list_returns_team_configs_ordered_by_skill(self) -> None:
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-beta")
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-alpha")
+
+ response = self.client.get(self._list_url())
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert [c["skill_name"] for c in body] == ["signals-scout-alpha", "signals-scout-beta"]
+ assert body[0]["enabled"] is True
+ assert body[0]["emit"] is False
+ assert body[0]["run_interval_minutes"] == 1440
+
+ def test_partial_update_changes_schedule_emit_and_records_enabled_by(self) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=False)
+
+ response = self.client.patch(
+ self._detail_url(str(config.id)),
+ data={"enabled": True, "emit": True, "run_interval_minutes": 60},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ config.refresh_from_db()
+ assert config.enabled is True
+ assert config.emit is True
+ assert config.run_interval_minutes == 60
+ assert config.enabled_by_id == self.user.id
+
+ def test_partial_update_rejects_interval_below_min(self) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ response = self.client.patch(self._detail_url(str(config.id)), data={"run_interval_minutes": 5}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_partial_update_cannot_change_skill_name(self) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ self.client.patch(self._detail_url(str(config.id)), data={"skill_name": "signals-scout-bar"}, format="json")
+ config.refresh_from_db()
+ assert config.skill_name == "signals-scout-foo"
+
+ def test_partial_update_unknown_id_returns_404(self) -> None:
+ response = self.client.patch(
+ self._detail_url("00000000-0000-0000-0000-000000000000"), data={"enabled": False}, format="json"
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_partial_update_other_teams_config_returns_404(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ config = SignalScoutConfig.all_teams.create(team=other_team, skill_name="signals-scout-foo")
+ response = self.client.patch(self._detail_url(str(config.id)), data={"enabled": False}, format="json")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
diff --git a/products/signals/backend/test/test_scout_harness_lazy_seed.py b/products/signals/backend/test/test_scout_harness_lazy_seed.py
index eb2accbd0f93..c338f7205b7a 100644
--- a/products/signals/backend/test/test_scout_harness_lazy_seed.py
+++ b/products/signals/backend/test/test_scout_harness_lazy_seed.py
@@ -66,15 +66,25 @@ class TestDiscoverCanonicalSkills:
skills = discover_canonical_skills(tmp_path)
assert [s.name for s in skills] == ["signals-scout-foo"]
- def test_parses_allowed_tools_when_present(self, tmp_path: Path) -> None:
+ @pytest.mark.parametrize(
+ "frontmatter_key",
+ [
+ # Backwards-compat form. Predates the agentskills.io spec alignment in this
+ # codebase and is still in use by other PHS skills.
+ "allowed_tools",
+ # Spec form per agentskills.io — preferred for new canonical skills.
+ "allowed-tools",
+ ],
+ )
+ def test_parses_allowed_tools_in_either_frontmatter_form(self, tmp_path: Path, frontmatter_key: str) -> None:
_write_canonical_skill(
tmp_path,
dir_name="signals-scout-bar",
- frontmatter="""
+ frontmatter=f"""
---
name: signals-scout-bar
description: bar skill
- allowed_tools:
+ {frontmatter_key}:
- remember
- search_scratchpad
---
@@ -84,7 +94,57 @@ class TestDiscoverCanonicalSkills:
skills = discover_canonical_skills(tmp_path)
assert skills[0].allowed_tools == ("remember", "search_scratchpad")
- def test_parses_bundled_files_under_references_and_scripts(self, tmp_path: Path) -> None:
+ def test_rejects_both_allowed_tools_keys_set(self, tmp_path: Path) -> None:
+ _write_canonical_skill(
+ tmp_path,
+ dir_name="signals-scout-bar",
+ frontmatter="""
+ ---
+ name: signals-scout-bar
+ description: bar skill
+ allowed-tools:
+ - remember
+ allowed_tools:
+ - search_scratchpad
+ ---
+ """,
+ body="# Bar\n",
+ )
+ with pytest.raises(CanonicalSkillParseError, match="both 'allowed-tools' and 'allowed_tools'"):
+ discover_canonical_skills(tmp_path)
+
+ @pytest.mark.parametrize(
+ "allowed_tools_value",
+ [
+ # YAML null — `allowed-tools:` with no value.
+ "",
+ " false",
+ ' ""',
+ ],
+ )
+ def test_rejects_falsy_non_list_allowed_tools(self, tmp_path: Path, allowed_tools_value: str) -> None:
+ # A falsy-but-invalid value must fail fast, not silently fall back to `[]`
+ # (which means "no tool narrowing" and would broaden tool access).
+ _write_canonical_skill(
+ tmp_path,
+ dir_name="signals-scout-bar",
+ frontmatter=f"""
+ ---
+ name: signals-scout-bar
+ description: bar skill
+ allowed-tools:{allowed_tools_value}
+ ---
+ """,
+ body="# Bar\n",
+ )
+ with pytest.raises(CanonicalSkillParseError, match="must be a list of strings"):
+ discover_canonical_skills(tmp_path)
+
+ def test_parses_bundled_files_under_allowed_subdirs(self, tmp_path: Path) -> None:
+ # `_ALLOWED_BUNDLE_SUBDIRS` is kept in lockstep with `hogli build:skills` —
+ # `references/` and `scripts/` only. `assets/` and any other subdir are intentionally
+ # ignored: silently bundling them here while the AI plugin build skips them would
+ # produce different runtime behavior from the same source skill.
_write_canonical_skill(
tmp_path,
dir_name="signals-scout-bar",
@@ -98,6 +158,8 @@ class TestDiscoverCanonicalSkills:
bundled_files={
"references/playbook.md": "# Playbook\n",
"scripts/check.py": "print('hi')\n",
+ "assets/template.txt": "hello {{name}}\n",
+ "extras/notes.txt": "ignored\n",
},
)
skills = discover_canonical_skills(tmp_path)
@@ -105,6 +167,9 @@ class TestDiscoverCanonicalSkills:
assert "references/playbook.md" in files_by_path
assert files_by_path["references/playbook.md"].content == "# Playbook\n"
assert "scripts/check.py" in files_by_path
+ # Files outside the allowlist must not leak in — guards the consumer divergence.
+ assert "assets/template.txt" not in files_by_path
+ assert "extras/notes.txt" not in files_by_path
def test_missing_frontmatter_raises(self, tmp_path: Path) -> None:
skill_dir = tmp_path / "signals-scout-foo"
diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.py
index 33b3ae80c051..03f25418208c 100644
--- a/products/signals/backend/test/test_scout_harness_tools.py
+++ b/products/signals/backend/test/test_scout_harness_tools.py
@@ -439,8 +439,10 @@ async def ateam_emit(aorganization_emit):
source_type="cross_source_issue",
enabled=True,
)
- # Seed a SignalScoutConfig so the run row's FK is valid.
- await database_sync_to_async(SignalScoutConfig.objects.create)(team=team)
+ # Seed a SignalScoutConfig (emit on) so the run's FK is valid and emits aren't dry-run.
+ await database_sync_to_async(SignalScoutConfig.objects.create)(
+ team=team, skill_name="signals-scout-errors", emit=True
+ )
yield team
@@ -603,6 +605,55 @@ async def test_emit_finding_returns_skipped_when_source_disabled(arun_emit, atea
mock_emit.assert_not_called()
+async def test_emit_finding_returns_skipped_when_scout_emit_disabled(arun_emit, ateam_emit):
+ # Fixture seeds an emit-on config; flip it to dry-run to exercise the per-scout gate.
+ await database_sync_to_async(
+ SignalScoutConfig.all_teams.filter(team=ateam_emit, skill_name=arun_emit.skill_name).update
+ )(emit=False)
+
+ with patch("products.signals.backend.facade.api.emit_signal", new=AsyncMock()) as mock_emit:
+ result = await emit_finding(
+ team=ateam_emit,
+ run=arun_emit,
+ description="d",
+ weight=0.5,
+ confidence=0.5,
+ evidence=[EvidenceEntry(source_product="logs", summary="x")],
+ finding_id="f-dry-run",
+ )
+
+ assert result.emitted is False
+ assert result.skipped_reason == "scout_emit_disabled"
+ mock_emit.assert_not_called()
+
+
+async def test_emit_finding_fails_closed_when_config_missing(arun_emit, ateam_emit):
+ # scout_config is nullable and a config can be deleted mid-run; a missing config must
+ # NOT emit (a recreated config defaults to dry-run), so it fails closed.
+ await database_sync_to_async(
+ SignalScoutConfig.all_teams.filter(team=ateam_emit, skill_name=arun_emit.skill_name).delete
+ )()
+
+ with patch("products.signals.backend.facade.api.emit_signal", new=AsyncMock()) as mock_emit:
+ result = await emit_finding(
+ team=ateam_emit,
+ run=arun_emit,
+ description="d",
+ weight=0.5,
+ confidence=0.5,
+ evidence=[EvidenceEntry(source_product="logs", summary="x")],
+ finding_id="f-no-config",
+ )
+
+ assert result.emitted is False
+ assert result.skipped_reason == "scout_config_missing"
+ mock_emit.assert_not_called()
+
+
# --- emit_finding (team, run) ownership guard tests ---
@@ -640,7 +691,7 @@ def test_emit_finding_sync_rejects_team_run_mismatch(db) -> None:
owning_team = Team.objects.create(organization=org, name="owner")
other_team = Team.objects.create(organization=org, name="other")
with team_scope(owning_team.id, canonical=True):
- config = SignalScoutConfig.objects.create(team=owning_team)
+ config = SignalScoutConfig.objects.create(team=owning_team, skill_name="signals-scout-errors")
task_run = _make_task_run(owning_team, status=TaskRun.Status.IN_PROGRESS)
run = SignalScoutRun.objects.create(
task_run=task_run,
diff --git a/products/signals/backend/test/test_signal_scout_models.py b/products/signals/backend/test/test_signal_scout_models.py
index 84788e18d1f2..2f964ff1f10f 100644
--- a/products/signals/backend/test/test_signal_scout_models.py
+++ b/products/signals/backend/test/test_signal_scout_models.py
@@ -4,7 +4,10 @@ import pytest
from posthog.test.base import BaseTest
from django.db import IntegrityError
+from django.utils import timezone
+from posthog.models import Organization, Team
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.scoping import team_scope
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad
@@ -36,28 +39,57 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
def test_signal_scout_config_round_trip(self) -> None:
config = SignalScoutConfig.objects.create(
team=self.team,
+ skill_name="signals-scout-errors",
enabled=True,
- enabled_skill_names=["signals-scout-errors", "signals-scout-llm"],
+ emit=True,
+ run_interval_minutes=60,
created_by=self.user,
+ enabled_by=self.user,
)
loaded = SignalScoutConfig.objects.get(pk=config.pk)
assert loaded.team_id == self.team.id
+ assert loaded.skill_name == "signals-scout-errors"
assert loaded.enabled is True
- assert loaded.enabled_skill_names == ["signals-scout-errors", "signals-scout-llm"]
+ assert loaded.emit is True
+ assert loaded.run_interval_minutes == 60
assert loaded.created_by_id == self.user.id
+ assert loaded.enabled_by_id == self.user.id
def test_signal_scout_config_defaults(self) -> None:
- config = SignalScoutConfig.objects.create(team=self.team)
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
loaded = SignalScoutConfig.objects.get(pk=config.pk)
- # Defaults: disabled, no skill narrowing.
- assert loaded.enabled is False
- assert loaded.enabled_skill_names is None
+ # Auto-created scouts run on a daily cadence but stay in dry-run until emit is flipped.
+ assert loaded.enabled is True
+ assert loaded.emit is False
+ assert loaded.run_interval_minutes == 1440
+ assert loaded.last_run_at is None
- def test_signal_scout_config_one_per_team(self) -> None:
- SignalScoutConfig.objects.create(team=self.team)
+ def test_signal_scout_config_one_per_team_skill(self) -> None:
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
with pytest.raises(IntegrityError):
- SignalScoutConfig.objects.create(team=self.team)
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+
+ def test_signal_scout_config_multiple_skills_per_team(self) -> None:
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-bar")
+ assert SignalScoutConfig.objects.filter(team=self.team).count() == 2
+
+ def test_enabling_scout_logs_activity(self) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=False)
+ config.enabled = True
+ config.save()
+ assert ActivityLog.objects.filter(
+ scope="SignalScoutConfig", item_id=str(config.id), activity="updated"
+ ).exists()
+
+ def test_last_run_at_update_skips_activity_log(self) -> None:
+ # The coordinator stamps last_run_at via .update() every tick; that hot write must
+ # not flood the audit log.
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ ActivityLog.objects.filter(scope="SignalScoutConfig").delete()
+ SignalScoutConfig.all_teams.filter(pk=config.pk).update(last_run_at=timezone.now())
+ assert not ActivityLog.objects.filter(scope="SignalScoutConfig", item_id=str(config.id)).exists()
def _make_task_run(self) -> TaskRun:
"""Minimal Task + TaskRun pair scoped to this test's team."""
@@ -70,7 +102,7 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
return TaskRun.objects.create(task=task, team=self.team)
def test_signal_scout_run_round_trip(self) -> None:
- config = SignalScoutConfig.objects.create(team=self.team, enabled=True)
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-errors", enabled=True)
task_run = self._make_task_run()
run = SignalScoutRun.objects.create(
task_run=task_run,
@@ -101,7 +133,7 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
def test_signal_scout_run_survives_config_deletion(self) -> None:
# SET_NULL on scout_config: deleting the config row keeps run history intact for audit.
- config = SignalScoutConfig.objects.create(team=self.team)
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-errors")
task_run = self._make_task_run()
run = SignalScoutRun.objects.create(
task_run=task_run,
@@ -138,3 +170,21 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
SignalScratchpad.objects.create(team=self.team, key="dup", content="first")
with pytest.raises(IntegrityError):
SignalScratchpad.objects.create(team=self.team, key="dup", content="second")
+
+
+def test_scout_config_update_without_team_scope_logs_activity() -> None:
+ # Django admin / coordinator / shell edits run with no team context. The activity-logging
+ # prior-state lookup must use the unscoped manager, not the fail-closed `objects`, or the
+ # save raises TeamScopeError before the change is persisted. Function-style (not BaseTest)
+ # so the conftest's auto team_scope does not apply.
+ org = Organization.objects.create(name="ScoutScopeTestOrg")
+ team = Team.objects.create(organization=org, name="ScoutScopeTestTeam")
+ config = SignalScoutConfig.all_teams.create(team=team, skill_name="signals-scout-x", emit=False)
+
+ config.emit = True
+ config.save()
+
+ config.refresh_from_db()
+ assert config.emit is True
+ assert ActivityLog.objects.filter(scope="SignalScoutConfig", item_id=str(config.id), activity="updated").exists()
diff --git a/products/signals/frontend/activityDescriber.tsx b/products/signals/frontend/activityDescriber.tsx
new file mode 100644
index 000000000000..518fa702264e
--- /dev/null
+++ b/products/signals/frontend/activityDescriber.tsx
@@ -0,0 +1,43 @@
+import {
+ ActivityLogItem,
+ HumanizedChange,
+ defaultDescriber,
+ userNameForLogItem,
+} from 'lib/components/ActivityLog/humanizeActivity'
+
+const scoutName = (logItem: ActivityLogItem): string =>
+ logItem?.detail?.name || (logItem?.detail?.context as any)?.skill_name || 'scout'
+
+// Descriptions are plain strings (no JSX): the signals product package doesn't declare
+// `react`, so a `.tsx` file using JSX can't resolve `react/jsx-runtime`. `Description`
+// accepts `string`, which keeps this describer dependency-free.
+export function signalScoutConfigActivityDescriber(
+ logItem: ActivityLogItem,
+ asNotification?: boolean
+): HumanizedChange {
+ const name = scoutName(logItem)
+ const user = userNameForLogItem(logItem)
+
+ if (logItem.activity === 'created') {
+ return { description: `${user} created scout ${name}` }
+ }
+
+ if (logItem.activity === 'deleted') {
+ return { description: `${user} deleted scout ${name}` }
+ }
+
+ if (logItem.activity === 'updated') {
+ const changes = logItem.detail?.changes ?? []
+ const enabledChange = changes.find((change) => change.field === 'enabled')
+
+ // Single-field enable/disable toggle gets a dedicated phrasing.
+ if (enabledChange && changes.length === 1) {
+ const verb = enabledChange.after ? 'enabled' : 'disabled'
+ return { description: `${user} ${verb} scout ${name}` }
+ }
+
+ return { description: `${user} updated scout ${name}` }
+ }
+
+ return defaultDescriber(logItem, asNotification, name)
+}
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 275774dbab18..1ec73e6037ce 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -141,6 +141,62 @@ export interface SignalReportStateRequestApi {
snooze_for?: number
}
+/**
+ * Per-(team, skill) scout config: schedule, enablement, and emit posture.
+
+One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
+when it discovers a scout skill; this serializer lets agents tune the row.
+ */
+export interface SignalScoutConfigApi {
+ readonly id: string
+ /** The `signals-scout-*` skill this config controls. Set at creation, not editable. */
+ readonly skill_name: string
+ /** Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator. */
+ enabled?: boolean
+ /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. */
+ emit?: boolean
+ /**
+ * Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.
+ * @minimum 10
+ * @maximum 43200
+ */
+ run_interval_minutes?: number
+ /**
+ * When the coordinator last dispatched this scout. Null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at: string | null
+ readonly created_at: string
+}
+
+/**
+ * Per-(team, skill) scout config: schedule, enablement, and emit posture.
+
+One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
+when it discovers a scout skill; this serializer lets agents tune the row.
+ */
+export interface PatchedSignalScoutConfigApi {
+ readonly id?: string
+ /** The `signals-scout-*` skill this config controls. Set at creation, not editable. */
+ readonly skill_name?: string
+ /** Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator. */
+ enabled?: boolean
+ /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. */
+ emit?: boolean
+ /**
+ * Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.
+ * @minimum 10
+ * @maximum 43200
+ */
+ run_interval_minutes?: number
+ /**
+ * When the coordinator last dispatched this scout. Null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at?: string | null
+ readonly created_at?: string
+}
+
/**
* `inventory.project_context` — free-form orientation about the project's product.
*/
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 193c09351f36..2524415fe123 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -16,6 +16,7 @@ import type {
PaginatedPauseStateResponseListApi,
PaginatedSignalReportListApi,
PaginatedSignalSourceConfigListApi,
+ PatchedSignalScoutConfigApi,
PatchedSignalSourceConfigApi,
PauseResponseApi,
PauseUntilRequestApi,
@@ -24,6 +25,7 @@ import type {
ScratchpadEntryApi,
SignalReportApi,
SignalReportStateRequestApi,
+ SignalScoutConfigApi,
SignalScoutRunDetailApi,
SignalScoutRunSummaryApi,
SignalSourceConfigApi,
@@ -197,6 +199,46 @@ export const signalsReportsStateCreate = async (
})
}
+export const getSignalsScoutConfigListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/signals/scout/configs/`
+}
+
+/**
+ * List the per-(team, skill) scout configs for this project — schedule (`run_interval_minutes`), `enabled`, and `emit` posture per scout.
+ * @summary List scout configs
+ */
+export const signalsScoutConfigList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<SignalScoutConfigApi[]> => {
+ return apiMutator<SignalScoutConfigApi[]>(getSignalsScoutConfigListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSignalsScoutConfigUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/scout/configs/${id}/`
+}
+
+/**
+ * Tune one scout: change its schedule (`run_interval_minutes`), `enabled`, or `emit` (dry-run) posture. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
+ * @summary Update a scout config
+ */
+export const signalsScoutConfigUpdate = async (
+ projectId: string,
+ id: string,
+ patchedSignalScoutConfigApi?: NonReadonly<PatchedSignalScoutConfigApi>,
+ options?: RequestInit
+): Promise<SignalScoutConfigApi> => {
+ return apiMutator<SignalScoutConfigApi>(getSignalsScoutConfigUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedSignalScoutConfigApi),
+ })
+}
+
export const getSignalsScoutProjectProfileGetUrl = (
projectId: string,
params?: SignalsScoutProjectProfileGetParams
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 9af82f533dbd..a52efff1542c 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -67,6 +67,38 @@ export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Tune one scout: change its schedule (`run_interval_minutes`), `enabled`, or `emit` (dry-run) posture. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
+ * @summary Update a scout config
+ */
+export const signalsScoutConfigUpdateBodyRunIntervalMinutesMin = 10
+export const signalsScoutConfigUpdateBodyRunIntervalMinutesMax = 43200
+
+export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
+ .object({
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe('Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator.'),
+ emit: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing.'
+ ),
+ run_interval_minutes: zod
+ .number()
+ .min(signalsScoutConfigUpdateBodyRunIntervalMinutesMin)
+ .max(signalsScoutConfigUpdateBodyRunIntervalMinutesMax)
+ .optional()
+ .describe(
+ 'Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.'
+ ),
+ })
+ .describe(
+ 'Per-(team, skill) scout config: schedule, enablement, and emit posture.\n\nOne row per `signals-scout-\*` skill on the team. The coordinator auto-creates a row\nwhen it discovers a scout skill; this serializer lets agents tune the row.'
+ )
+
/**
* Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so do not retry an emit that may have already succeeded.
* @summary Emit a finding for a run
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index e5b842c93d1e..ecbd491c47c3 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -137,6 +137,37 @@ tools:
inbox-source-configs-update:
operation: signals_source_configs_update
enabled: false
+ signals-scout-config-list:
+ operation: signals_scout_config_list
+ enabled: true
+ scopes:
+ - signal_scout:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List scout configs
+ description: >
+ List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule
+ (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. Use this to see which scouts run,
+ how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune
+ them.
+ signals-scout-config-update:
+ operation: signals_scout_config_update
+ enabled: true
+ scopes:
+ - signal_scout:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ title: Update a scout config
+ description: >
+ Tune one scout by its config `id`: change its schedule (`run_interval_minutes`, 10–43200), `enabled`, or
+ `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). `skill_name` is fixed.
+ Enabling records who flipped it on and is activity-logged, since running a scout drives spend.
signals-scout-emit-signal:
operation: signals_scout_emit_signal
enabled: true
diff --git a/products/signals/skills/signals-scout-csp-violations/SKILL.md b/products/signals/skills/signals-scout-csp-violations/SKILL.md
new file mode 100644
index 000000000000..de218cc99cbc
--- /dev/null
+++ b/products/signals/skills/signals-scout-csp-violations/SKILL.md
@@ -0,0 +1,296 @@
+---
+name: signals-scout-csp-violations
+description: >
+ Focused Signals scout for PostHog projects collecting Content Security Policy (CSP)
+ violation reports. Watches `$csp_violation` events for fresh blocked-URL clusters,
+ per-directive bursts, page-scoped regressions after deploys, and suspicious
+ third-party domains that may indicate a compromised script. Emits aggregated
+ findings only when a cluster clears the confidence bar; otherwise writes durable
+ memory and closes out empty. Self-contained peer in the signals-scout-* fleet — no
+ dependencies on other skills. Picked uniformly at random by the coordinator
+ alongside `signals-scout-general` and other specialists.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes (mostly read-only, plus
+ signal_scout_internal:write for scratchpad-remember/forget and emit-signal). Assumes the signals-scout MCP family (project-profile-get, runs-list,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus
+ standard analytics tools (execute-sql, read-data-schema, activity-log-list,
+ inbox-reports-list).
+metadata:
+ owner_team: signals
+ scope: csp_violations
+ credits: pauldambra (PR #58596 — push-based CSP signal emission, encoded here as pull)
+---
+
+# Signals scout: CSP violations
+
+You are a focused CSP scout. Spot meaningful changes in this team's
+`$csp_violation` event stream — fresh blocked-URL domains, per-directive bursts,
+deploy-correlated page regressions, suspicious third-party scripts — and emit findings
+only when a cluster clears the confidence bar.
+
+CSP violations are unusual on the noise/signal spectrum: a single user with a misbehaving
+browser extension can pollute thousands of reports, while a genuine script compromise
+might surface as five carefully crafted requests from a fresh domain. **Reach (distinct
+users + distinct documents) matters more than raw count**. Internalize that shape.
+
+## Quick close-out: is CSP reporting even active?
+
+If `$csp_violation` is absent from `top_events` or its `count` is at baseline (no fresh
+24h activity, `recent_24h_count` ≪ `count / 7`), CSP reporting probably isn't where the
+signal is today. Cheap scratchpad entry + close out:
+
+- key: `pattern:csp_violations:baseline-team{team_id}`
+- content: `"$csp_violation baseline ~{count}/day, no fresh 24h burst at {timestamp}"`
+
+If `$csp_violation` is absent from `top_events` entirely (project doesn't ship a CSP
+reporting endpoint at all):
+
+- key: `not-in-use:csp_violations:team{team_id}`
+- content: brief note (`"no $csp_violation events in 7d window at {timestamp}"`)
+
+Close out empty in both cases. Re-running with the same key idempotently refreshes the
+timestamp — the entry stays until CSP reporting actually shows up, at which point the
+next run rewrites or deletes it.
+
+## How a run works
+
+Cycle between these moves; skip what's not useful.
+
+### Get oriented
+
+Three cheap reads cold-start a run:
+
+- `signals-scout-scratchpad-search` (`text=csp` or `text=blocked`) — durable team steering
+ from past CSP runs. Entries with `pattern:`, `noise:`, `addressed:`, `dedupe:`, or
+ `allowlist:` key prefixes tell you the team's healthy domains, recurring
+ browser-extension noise, fingerprints already surfaced, and what to skip.
+- `signals-scout-runs-list` (last 7d) — what prior CSP scouts found and ruled out.
+- `signals-scout-project-profile-get` — the `$csp_violation` row in `top_events` carries
+ `count`, `distinct_users`, `recent_24h_count`, `recent_24h_users`. Pattern the
+ count/users ratio against the table below.
+
+### Profile shape — count vs distinct_users
+
+| Pattern | What it usually means |
+| ------------------------------------------------------- | ---------------------------------------------------------------- |
+| Both `count` and `distinct_users` spike in 24h | Fresh broad-impact CSP regression — deploy missed an allowlist |
+| `recent_24h_count / count` ≫ `1/7`, users also spike | Today's burst is unusually broad — investigate first |
+| `count` very high, `distinct_users` very low (≤ 5) | Single user / bot / browser extension — usually skip |
+| `count` ~ `distinct_users` for one blocked URL | Per-pageload violation hitting every visitor — broken policy |
+| Steady high `count` across many users + many directives | Mature CSP policy in `report-only` mode — high baseline expected |
+| `count` and `distinct_users` both quiet | Nothing fresh today — close out |
+
+### Explore
+
+Patterns to watch — starting points, not a checklist. Group violations along four
+dimensions and look for clusters worth a finding. The team's existing push-based
+emission (PR #58596) already deduplicates _individual_ violations at
+`sha1(violated_directive | blocked_url | document_url | source_file)` granularity with a
+24h Redis TTL; your job is to _aggregate_ across that grain into higher-confidence
+findings the inbox wouldn't surface on its own.
+
+#### Fresh blocked-URL domain
+
+The single highest-value CSP pattern. Group by `domain(properties.$csp_blocked_url)` over
+the last 24–48h. A domain with `first_seen` inside the window, ≥ 10 distinct pageviews,
+and not in the team's `allowlist`-tagged memory is the strongest scout signal.
+
+```sql
+SELECT
+ domain(JSONExtractString(properties, '$csp_blocked_url')) AS blocked_domain,
+ count() AS occurrences,
+ uniq(person_id) AS distinct_users,
+ uniq(JSONExtractString(properties, '$csp_document_url')) AS distinct_documents,
+ min(timestamp) AS first_seen,
+ max(timestamp) AS last_seen,
+ groupArray(DISTINCT JSONExtractString(properties, '$csp_effective_directive'))[1:5] AS directives
+FROM events
+WHERE event = '$csp_violation'
+ AND timestamp > now() - INTERVAL 48 HOUR
+ AND JSONExtractString(properties, '$csp_blocked_url') != ''
+GROUP BY blocked_domain
+HAVING first_seen > now() - INTERVAL 24 HOUR
+ AND distinct_users >= 10
+ORDER BY occurrences DESC
+LIMIT 20
+```
+
+Three lenses for triage — copy these directly from PR #58596's `_build_description`,
+they're the prompt the team needs:
+
+1. **Legitimate — CSP policy needs widening.** New CDN, new analytics provider, new
+ marketing tag the team rolled out and forgot to add to the allowlist.
+2. **Compromised — injected or third-party script indicating a security incident.**
+ Fresh domain nobody recognizes, especially script-src violations on a small number of
+ high-traffic pages, especially with `disposition=enforce` and a `source_file` that
+ points at the team's own JS bundle.
+3. **Third-party drift — vendor script the team should remove.** Old analytics SDK still
+ loaded from a deprecated bundle, ad pixel from a churned vendor, etc.
+
+Emit only when one of these lenses fits with high confidence (≥ 0.85). If you're
+genuinely unsure which of the three it is, write a `pattern:csp_violations:<entity>`
+scratchpad entry for the next run and close out.
+
+#### Per-directive burst
+
+Group by `properties.$csp_effective_directive`. A directive whose recent 24h count is
+materially above its 7d-prior baseline (≥ 3×) with reach across multiple documents is a
+strong "policy regression after deploy" signal. Pair with `activity-log-list` filtered to
+the last 24–48h — a deploy or hog-flow change correlating to the burst timestamp is the
+clean cross-source convergence.
+
+Top directives to expect (rough share-of-violations on a typical SPA): `script-src`,
+`script-src-elem`, `img-src`, `style-src`, `connect-src`, `frame-src`. `script-src`
+violations are weighted highest for security relevance; `img-src` and `style-src` more
+often indicate vendor / CDN drift.
+
+#### Document-scoped regression
+
+Group by `properties.$csp_document_url`. A document with no violations in the
+7d-prior window and a sudden burst in the recent 24h is almost always a deploy regression
+on that route — a new script tag or inline style that the existing policy doesn't allow.
+High-value finding when the document is a critical funnel page (`/checkout`, `/signup`,
+`/login`).
+
+#### Stuck loop / single-user noise
+
+`count` very high but `distinct_users` ≤ 5 over the recent window. Almost always a single
+user with a misbehaving browser extension, or a bot probing the page. Skip — write a
+`noise:csp_violations:<blocked_domain>` scratchpad entry so future runs short-circuit.
+
+Common skippable patterns:
+
+- `chrome-extension://` / `moz-extension://` / `safari-extension://` blocked URLs
+- Brave / DuckDuckGo / privacy-browser injected scripts
+- `about:blank`, `data:` URIs from translation tooling or password managers
+
+#### Disposition shift
+
+Group by `properties.$csp_disposition`. A team running `report-only` for a long time and
+then flipping to `enforce` will see violations turn into actual blocks. If the project
+profile shows `count` for `disposition='enforce'` rising sharply (`recent_24h_count`
+materially above baseline) while `report-only` shows a corresponding fall, the team has
+flipped enforcement — write a `pattern:csp_violations:disposition-flip` scratchpad entry
+and emit only if a critical page is suddenly seeing enforced blocks.
+
+### Save memory as you go
+
+Memory is a continuous activity. Write a scratchpad entry whenever you observe something
+a future CSP run should know. Encode the "category" in the key prefix — `pattern:`,
+`noise:`, `addressed:`, `dedupe:`, `allowlist:` — so future runs find it with a single
+`text=` search:
+
+- key `pattern:csp_violations:baseline` — _"Project's healthy `$csp_violation` baseline:
+ ~800/day across ~120 distinct users, mostly `img-src` from `*.googletagmanager.com`
+ and `*.googlesyndication.com`. Anything above 1.5× this baseline is fresh."_
+- key `allowlist:csp_violations:gtm` — _"`*.googletagmanager.com`,
+ `*.googlesyndication.com`, `*.doubleclick.net` are the team's expected analytics/ads
+ domains — known, vetted, do not re-surface."_
+- key `noise:csp_violations:chrome-extension-scheme` — _"Blocked URL pattern
+ `chrome-extension://*` is a recurring browser-extension noise source for this team —
+ skip unless `disposition=enforce` and `effective_directive=script-src`."_
+- key `addressed:csp_violations:cdn.suspicious.example.com-2026-05-13` — _"Surfaced fresh
+ `script-src` cluster from `cdn.suspicious.example.com` on 2026-05-12; team confirmed
+ it was a legitimate new vendor, allowlisted in policy on 2026-05-13. Do not re-emit
+ unless the domain re-appears after policy was widened."_
+- key `dedupe:csp_violations:a1b2c3d4` — _"Fingerprint `a1b2c3d4...` (`script-src` |
+ `evil.example.com/x.js` | `/checkout` | `bundle.js`) — surfaced 2026-05-08, finding
+ still open in inbox. If this exact fingerprint fires again, attach to the existing
+ report; don't emit fresh."_
+
+By run #5 you'll have a per-team domain allowlist in the scratchpad, known
+browser-extension noise patterns, and the typical per-directive shape — and burn
+near-zero time on cold-start exploration.
+
+### Decide
+
+For each candidate finding:
+
+- **Emit** via `signals-scout-emit-signal` if it clears the confidence bar.
+ Strong scout findings: weight ≥ 0.7, confidence ≥ 0.85, with concrete blocked domain,
+ effective directive(s), document URL(s), distinct-user count, time-range evidence,
+ and an explicit lens (policy / compromise / vendor drift).
+- **Remember** if below the bar but worth carrying forward (e.g. fresh domain with only
+ 3 distinct users — let it ripen).
+- **Skip** with a one-line note if a scratchpad entry with a `noise:`, `allowlist:`,
+ `addressed:`, or `dedupe:` key prefix already covers it.
+
+Cross-check `inbox-reports-list` filtered to `source_product=csp_reporting` before
+emitting — the push-based emission already drops individual fingerprints into the inbox
+at weight 0.5. Your aggregated finding should reference those source signals as evidence
+(by fingerprint) rather than re-stating them.
+
+### Close out
+
+**Summarize the run** — one paragraph: looked at what, emitted what, remembered what,
+ruled out what. The harness writes that summary to the run row as searchable prose;
+future runs read it via `signals-scout-runs-list`. Do **not** write a separate
+"run metadata" scratchpad entry — the run summary already serves that role.
+
+## Disqualifiers (skip these)
+
+- **Single user, single document, single fingerprint** — almost always a personal
+ browser extension or a niche client. Low `count` AND `distinct_users` ≤ 2.
+- **Blocked URL scheme is `chrome-extension://` / `moz-extension://` / `about:` /
+ `data:`** — browser-side, not server-side; team can't fix.
+- **Domain matches an `allowlist:` scratchpad entry** — the team has already
+ vetted this vendor; skip without re-surfacing.
+- **`disposition=report-only` with no enforcement signal** — the team is deliberately
+ collecting violations to refine policy. Emit only when reach / freshness / domain
+ novelty is exceptional.
+- **Fingerprint matches a `dedupe:` scratchpad entry from an open inbox report** —
+ the push-emission path already covered it; don't double-up.
+- **Team has no `signal_source_config` row for `csp_reporting`** — push emission is
+ off for this team. Scout can still find clusters, but the user signal is "team
+ hasn't opted in to CSP signals yet"; raise the confidence bar (≥ 0.9) accordingly.
+
+When in doubt, write a memory entry instead of emitting.
+
+## MCP tools
+
+Direct calls (read-only):
+
+- `execute-sql` against `events` (filtered to `event = '$csp_violation'`) — primary
+ drill-down. Group by `domain($csp_blocked_url)`, `$csp_effective_directive`,
+ `$csp_document_url`, `$csp_source_file`. The full property list is in `posthog/api/csp.py`.
+- `read-data-schema` (`kind: event_properties`, `event_name: '$csp_violation'`) — discover
+ the team's actual `$csp_*` property surface and sample values.
+- `activity-log-list` — pair burst timestamps with recent deploys or feature-flag
+ changes for cross-source convergence.
+- `inbox-reports-list` filtered to `source_product=csp_reporting` — verify a cluster
+ isn't already in the inbox via the push path before emitting.
+
+Harness-level:
+
+- `signals-scout-project-profile-get` / `signals-scout-scratchpad-search` /
+ `signals-scout-runs-list` / `signals-scout-runs-retrieve` — orientation + dedupe.
+- `signals-scout-emit-signal` / `signals-scout-scratchpad-remember` — emit / remember.
+
+## When to stop
+
+- `$csp_violation` row in profile is at baseline → close out empty.
+- A candidate matches a scratchpad entry with `noise:` / `allowlist:` / `addressed:` /
+ `dedupe:` key prefix → skip.
+- You've validated some hypotheses and emitted what's solid → close out, even if
+ there's more you could look at. Fewer, better signals.
+
+"Looked but found nothing meaningful" is a real outcome.
+
+## How this relates to the push-based source (PR #58596)
+
+The companion push path (`posthog/tasks/csp_signal.py`, behind per-team
+`SignalSourceConfig` opt-in) emits **one signal per unique violation fingerprint** at
+weight 0.5 with a 24h Redis dedup TTL. That gives the inbox raw coverage of every fresh
+`(directive, blocked_url, document_url, source_file)` tuple, but at low weight and
+without cross-fingerprint context.
+
+This scout is the **aggregation layer above it.** Its findings should:
+
+- Bundle multiple raw fingerprints into a single higher-weight finding with shared root
+ cause (one new domain across many pages, one deploy regression across many directives,
+ one compromise pattern across many users).
+- Use the push path's existing signals as evidence in the finding's body (referenced by
+ fingerprint / source_id) rather than re-deriving them.
+- Stay quiet when the push path's coverage is sufficient — a single fingerprint already
+ in the inbox with weight 0.5 does not need a parallel scout finding unless the
+ aggregation adds new context.
diff --git a/products/signals/skills/signals-scout-error-tracking/SKILL.md b/products/signals/skills/signals-scout-error-tracking/SKILL.md
new file mode 100644
index 000000000000..b381f01f467e
--- /dev/null
+++ b/products/signals/skills/signals-scout-error-tracking/SKILL.md
@@ -0,0 +1,201 @@
+---
+name: signals-scout-error-tracking
+description: >
+ Focused Signals scout for PostHog projects using error tracking. Watches `$exception`
+ bursts, stuck loops, multi-fingerprint clusters, status regressions, and stack-trace
+ activity-name patterns. Emits findings only when they clear the confidence bar;
+ otherwise writes durable memory and closes out empty. Self-contained peer in the
+ signals-scout-* fleet — no dependencies on other skills. Picked uniformly at random
+ by the coordinator alongside `signals-scout-general` and other specialists.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes (mostly read-only, plus
+ signal_scout_internal:write for scratchpad-remember/forget and emit-signal). Assumes the signals-scout MCP family (project-profile-get, runs-list,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus
+ error-tracking + analytics tools (query-error-tracking-issues-list, query-error-tracking-issue,
+ execute-sql, activity-log-list, inbox-reports-list).
+metadata:
+ owner_team: signals
+ scope: error_tracking
+---
+
+# Signals scout: error tracking
+
+You are a focused error tracking scout. Spot meaningful changes in this team's
+`$exception` activity — bursts, stuck loops, multi-fingerprint clusters, status
+regressions, deploy-correlated regressions — and emit findings only when they clear
+the confidence bar.
+
+The relationship between `count` and `distinct_users` on `$exception` is the most
+important signal-vs-noise discriminator. Internalize that shape.
+
+## Quick close-out: is error tracking even loud?
+
+If `$exception` is absent from `top_events` or its `count` is at baseline (no fresh
+24h activity, `recent_24h_count` ≪ `count / 7`), error tracking probably isn't where
+the signal is today. Cheap scratchpad entry + close out:
+
+- key: `not-in-use:error_tracking:team{team_id}` (if `$exception` is absent entirely)
+ **or** `pattern:error_tracking:baseline-team{team_id}` (if it fires at a steady baseline
+ with no fresh burst)
+- content: `"$exception baseline ~{count}/day, no fresh 24h burst at {timestamp}"`
+
+Close out empty. Re-running with the same key idempotently refreshes the timestamp; the
+next run reads the entry cold and short-circuits.
+
+## How a run works
+
+Cycle between these moves; skip what's not useful.
+
+### Get oriented
+
+Three cheap reads cold-start a run:
+
+- `signals-scout-scratchpad-search` (`text=error` or `text=exception`) — durable team
+ steering from past error-tracking runs. Entries with `pattern:`, `noise:`, `addressed:`,
+ or `dedupe:` key prefixes tell you what's normal, what's already surfaced, what to skip.
+- `signals-scout-runs-list` (last 7d) — what prior error-tracking scouts found and
+ ruled out.
+- `signals-scout-project-profile-get` — the `$exception` row in `top_events` carries
+ `count`, `distinct_users`, `recent_24h_count`, `recent_24h_users`. Pattern the
+ count/users ratio against the table below.
+
+### Profile shape — count vs distinct_users
+
+| Pattern | What it usually means |
+| ------------------------------------------------------- | -------------------------------------------- |
+| `count` and `distinct_users` both spike in 24h | Fresh broad-reach issue — investigate first |
+| `recent_24h_count / count` ≫ `1/7` and users also spike | Today's burst is unusually broad |
+| `count` very high, `distinct_users` very low | Stuck loop / retry storm — may not be urgent |
+| `count` ~ `distinct_users` for a single fingerprint | Per-request server path (one hit per user) |
+| `count` and `distinct_users` both quiet | Nothing fresh on this product |
+
+### Explore
+
+Patterns to watch — starting points, not a checklist.
+
+#### Burst with broad reach
+
+`recent_24h_count` and `recent_24h_users` both spike together. Usually a fresh
+regression — many users hitting it independently. Drill in:
+
+1. `query-error-tracking-issues-list` filtered to `status=active`, sort by `last_seen_at`.
+2. `execute-sql` against `events` with `event = '$exception' AND
+properties.$exception_issue_id = '<id>'` grouped by `toStartOfHour(timestamp)`.
+3. Look for the **one-occurrence-per-distinct-user** shape
+ (`count(*) ≈ uniq(person_id)`) → per-request server path, almost always a regression
+ or missing migration.
+
+#### Stuck loop (narrow reach)
+
+`recent_24h_count` very high but `recent_24h_users` is small. A worker, cron, websocket,
+or retry is looping. Look at the issue's stack trace for the activity / job name. Often
+less urgent than a broad-reach burst, but worth a finding when count is in the
+thousands and the issue is fresh.
+
+#### Multi-fingerprint cluster
+
+Multiple fresh fingerprints (different `entity_id`s in `query-error-tracking-issues-list`)
+appearing in the same time window with overlapping stack traces, modules, or call sites
+→ likely shared root cause. Bundle them in one finding (single description, evidence
+list with all fingerprint ids, dedupe key per fingerprint).
+
+#### Status regression
+
+An issue with `status=resolved` that's now firing again. Filter
+`query-error-tracking-issues-list` to `status=active` and check `last_seen_at` against
+`first_seen_at` — a large gap means old issue resurrected. High-confidence findings:
+the team explicitly closed them once.
+
+#### Stack-trace activity name
+
+When the issue is server-side, the stack trace usually names the failing
+activity / view / management command. Extract it (top frame, look for
+`<activity>_activity`, `def view_name`, etc.) and pair with `activity-log-list` to find
+a recent deploy or model change correlation. Cross-source convergence is where this
+scout earns its keep.
+
+### Save memory as you go
+
+Memory is a continuous activity. Write a scratchpad entry whenever you observe something
+a future error-tracking run should know. Encode the "category" in the key prefix —
+`pattern:`, `noise:`, `addressed:`, `dedupe:` — so future runs find it with a single
+`text=` search:
+
+- key `pattern:error_tracking:baseline` — _"Project's normal `$exception` baseline:
+ ~50/day across ~30 distinct users. Anything materially above that is fresh."_
+- key `dedupe:error_tracking:019de34e` — _"Issue 019de34e — surfaced 2026-05-01
+ 11:31–13:22Z, then quiet. If quiet next run, treat as already-surfaced; if firing,
+ escalate."_
+- key `noise:error_tracking:sandbox-timeoutexpired` — _"Sandbox `TimeoutExpired` Docker
+ errors are recurring noise on this team — internal harness ops, not user-facing."_
+- key `pattern:error_tracking:fetch_signals_for_report_activity` — _"Server activity
+ `fetch_signals_for_report_activity` was a regression source on 2026-05-01 — if it
+ appears in a fresh stack trace, double-check it's not the same root cause."_
+
+By run #5 you'll have a local map of what's normal versus what warrants investigation,
+and burn less time on cold-start exploration.
+
+### Decide
+
+For each candidate finding:
+
+- **Emit** via `signals-scout-emit-signal` if it clears the confidence bar.
+ Strong scout findings: weight ≥ 0.7, confidence ≥ 0.85, with concrete issue ids,
+ hourly count, distinct-user counts in the evidence.
+- **Remember** if below the bar but worth carrying forward.
+- **Skip** with a one-line note if a scratchpad entry with a `noise:` or `addressed:`
+ key prefix already covers it.
+
+Cross-check `inbox-reports-list` before emitting — if an issue is already in the inbox,
+emit only if the _new angle_ (broader reach, status regression, deploy correlation) is
+materially different. Otherwise the existing report's signals will pick yours up via
+cross-source clustering.
+
+### Close out
+
+**Summarize the run** — one paragraph: looked at what, emitted what, remembered what,
+ruled out what. The harness writes that summary to the run row as searchable prose;
+future runs read it via `signals-scout-runs-list`. Do **not** write a separate
+"run metadata" scratchpad entry — the run summary already serves that role.
+
+## Disqualifiers (skip these)
+
+- **Single user, single session, single occurrence** — almost always a personal
+ browser quirk. Confirmed via low `count` AND low `distinct_users`.
+- **Sandbox-internal exceptions** — KEA store-path errors, Docker `TimeoutExpired`,
+ `agentsh` failures. Internal harness operations, not user-facing.
+- **Known upstream provider errors** — Anthropic / OpenAI rate limits, third-party
+ API outages already covered by past memory. Skip unless volume / shape changes
+ meaningfully.
+
+When in doubt, write a memory entry instead of emitting.
+
+## MCP tools
+
+Direct calls (read-only):
+
+- `query-error-tracking-issues-list` — start here. Filter `status=active`, sort by
+ `last_seen_at` desc.
+- `query-error-tracking-issue` — drill into one issue (frames, sample events,
+ occurrence counts).
+- `execute-sql` against `events` — for hourly breakdowns, distinct-user counts,
+ per-fingerprint correlation, time-window aggregations.
+- `inbox-reports-list` — check whether the issue is already in the inbox before emitting.
+- `activity-log-list` — pair stack-trace activity names with recent deploys or model
+ changes for cross-source convergence.
+
+Harness-level:
+
+- `signals-scout-project-profile-get` / `signals-scout-scratchpad-search` /
+ `signals-scout-runs-list` / `signals-scout-runs-retrieve` — orientation + dedupe.
+- `signals-scout-emit-signal` / `signals-scout-scratchpad-remember` — emit / remember.
+
+## When to stop
+
+- `$exception` row in profile is at baseline → close out empty.
+- A candidate matches a scratchpad entry with `noise:` / `addressed:` / `dedupe:` key
+ prefix → skip.
+- You've validated some hypotheses and emitted what's solid → close out, even if
+ there's more you could look at. Fewer, better signals.
+
+"Looked but found nothing meaningful" is a real outcome.
diff --git a/products/signals/skills/signals-scout-general/SKILL.md b/products/signals/skills/signals-scout-general/SKILL.md
index 057925b65d38..f82251100bf2 100644
--- a/products/signals/skills/signals-scout-general/SKILL.md
+++ b/products/signals/skills/signals-scout-general/SKILL.md
@@ -1,69 +1,90 @@
---
name: signals-scout-general
description: >
- Generic Signals scout — examines a PostHog project end-to-end (errors, replays, web analytics,
- experiments, warehouse, integrations) and emits a small number of high-confidence findings
- via emit_finding(). Use when you want a broad first-pass look at a project to surface anything
- worth a closer look. Designed for the headless Signals agent harness, but useful as a manual
- starting point for any agent exploring a new PostHog project.
+ General Signals scout for PostHog projects. Cross-product explorer that scans a
+ team's project and emits findings into the Signals inbox. Sibling specialists
+ (signals-scout-llm-analytics, -logs, -error-tracking, -revenue-analytics, -surveys,
+ -observability-gaps, -csp-violations) cover individual product surfaces; this
+ scout looks for cross-product correlations and explores what specialists don't
+ cover. The coordinator samples one scout per (team, tick) at random, so general
+ fires intermixed with specialists over time.
+compatibility: >
+ Runs as the PostHog Signals scout in a Claude sandbox with PostHog MCP scopes: signal_scout:read + signal_scout_internal:write (for
+ scratchpad-remember/forget and emit-signal), llm_skill:read, plus standard analytics reads. Uses the
+ signals-scout MCP family: project-profile-get, runs-list, runs-retrieve,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal.
+metadata:
+ owner_team: signals
---
# Signals scout
-You are a Signals scout. Your job is to spend a small amount of time looking across a PostHog
-project's surface area and surface a handful of high-confidence findings — things that look like
-real signals, not noise.
+You are a Signals scout. Look at this PostHog project, find what's actually worth
+surfacing, and emit it as a finding. Skip what's noise. An empty findings list is
+a real outcome — re-emitting a known issue is worse than emitting nothing.
-## What "good" looks like
+## Orient
-A good run produces:
+Three cheap reads cold-start a run:
-- **One to three findings**, each backed by concrete evidence the human reviewer can verify.
-- A **summary** that lists what you looked at, what you ruled out, and why the findings made the cut.
-- **Memory entries** (`remember`) for anything worth carrying into the next run — known false positives,
- recurring patterns, team steering you've absorbed.
+- `signals-scout-project-profile-get` — deterministic snapshot of products in use,
+ recent activity, integrations, top events with reach + burst metrics, inbox
+ report counts.
+- `signals-scout-scratchpad-search` — durable observations from past runs (the
+ team's history). Search with `text=<keyword>` (ILIKE on key + content).
+- `signals-scout-runs-list` — recent summaries from this scout and siblings. Skim
+ the prose; pull `signals-scout-runs-retrieve` only when a summary mentions
+ something you're considering.
-A good run does _not_:
+## Explore
-- Emit findings without evidence.
-- Re-emit a finding that's already in the recent run history (check `search_recent_runs` first).
-- Try to look at every source — go where the signal is, ignore the rest.
+Pick what looks interesting and follow it. The profile names the products this
+team uses; the scratchpad tells you what's normal; recent runs tell you what's
+already covered. Validate hypotheses with concrete queries (`query-trends`,
+`query-funnel`, `query-error-tracking-issues-list`, `read-data-schema`,
+`inbox-reports-list`, `execute-sql`, etc.) before emitting.
-## Workflow
+If a sibling specialist already covers a surface in depth (LLM analytics, logs,
+error tracking, revenue, surveys, observability gaps, CSP), leave the deep dive
+to it on a future tick. Spend your time on **cross-product correlations** or on
+**surfaces no specialist covers**.
-1. **Read the lay of the land.** Use `project-get`, `external-data-sources-list`,
- `integrations-list`, and `activity-log-list` (last 24h) to understand what this project has and
- what's been touched recently.
+## Decide
-2. **Read recent agent history.** Call `search_recent_runs(since=last_7_days)` to see what prior
- runs surfaced. Skip anything already covered unless you have new evidence.
+For each candidate finding:
-3. **Read durable memory.** Call `search_scratchpad()` for known false positives, team steering, and
- prior context. Do not re-emit anything memory tells you to ignore.
+- **Emit** via `signals-scout-emit-signal` if it clears the confidence
+ bar. The emit contract — schema, weight/confidence rubrics, severity, dedupe
+ keys, worked example — lives in [`references/emit.md`](references/emit.md).
+- **Remember** via `signals-scout-scratchpad-remember` if it's below the bar but
+ worth carrying forward, or to record what you ruled out and why.
+- **Skip** if the scratchpad already covers it.
-4. **Pick one or two areas to investigate.** Don't fan out. Errors that spiked? A new
- experiment? A warehouse sync that's been failing? Pick where the signal is loudest.
+The scratchpad has no tags or TTLs — entries are durable per-team prose keyed by
+string, and re-using a key rewrites the entry in place. Encode the category in
+the key prefix:
-5. **Investigate with concrete queries.** Use the existing PostHog MCP tools (`query-trends`,
- `query-funnel`, `read-data-schema`, `inbox-reports-list`, etc.) to verify what you suspect.
- If the data doesn't support the hypothesis, drop it — do not stretch.
+| Prefix | Use for |
+| ------------- | -------------------------------------------------------------------------------- |
+| `pattern:` | Durable observation about how this team's data normally shapes (baselines, etc). |
+| `noise:` | Patterns to ignore (single-user, dev-only, recurring with no fix path). |
+| `addressed:` | Team-confirmed fix shipped or topic the team has moved on from. |
+| `dedupe:` | Gates future emits on a specific issue / fingerprint / finding id. |
+| `allowlist:` | Vetted entities the scout should never re-surface. |
+| `not-in-use:` | Close-out memo for "product not in use on this team". |
-6. **Emit findings via `emit_finding()`.** Keep findings tight: one paragraph, a weight in
- `[0, 1]`, evidence list with concrete entity IDs.
+Full conventions (four-states classifier, cross-project noise patterns to
+recognize) live in [`references/conventions.md`](references/conventions.md).
-7. **Write memory if worth it.** If you ruled something out, `remember()` why so the next run
- doesn't waste time on the same path.
+## Avoid lens-lock
-## Budget discipline
+If the last few runs returned to the same lens, deliberately pick a different
+one. The coordinator already rotates which scout runs each tick — your job
+within a run is to follow what's interesting in the data, not to ceremonially
+rotate lenses.
-You have a hard cap of ~30 minutes and a small tool-call budget. Plan accordingly:
+## Close out
-- Cheap reads first (project info, recent activity, run history, memory).
-- Expensive reads (full HogQL queries, paths analysis) only after you have a concrete hypothesis.
-- If you've made >20 tool calls without converging on a finding, stop and write a "looked but
- found nothing meaningful" summary — that's a useful run too.
-
-## Stop early
-
-If memory or recent-run history says the team already knows about this issue, stop. Empty runs
-are fine. Re-emitting a known issue is worse than emitting nothing.
+If you emitted findings, summarize in one paragraph: what + why. If you didn't,
+one sentence is enough. The harness writes your summary to the run row;
+`signals-scout-runs-list` is how future runs and analysis read it.
diff --git a/products/signals/skills/signals-scout-general/references/conventions.md b/products/signals/skills/signals-scout-general/references/conventions.md
new file mode 100644
index 000000000000..8ba36edfa45b
--- /dev/null
+++ b/products/signals/skills/signals-scout-general/references/conventions.md
@@ -0,0 +1,107 @@
+# Conventions
+
+How to decide what to do with a candidate observation, how to write durable
+scratchpad entries, and noise patterns common across PostHog projects.
+
+## The four states
+
+Classify every candidate finding against prior runs and the scratchpad before
+emitting:
+
+1. **Net new** — no prior run mentions this topic, no scratchpad entry covers it.
+ → Emit if it clears the confidence bar (≥ 0.65; see
+ [emit.md](emit.md)).
+
+2. **Material update on a prior run** — a prior run covered the topic, but you
+ have new evidence: a different source corroborating, a fresh deploy
+ correlation, contradicting data, a meaningful escalation in scope.
+ → **Emit fresh, citing the prior `finding_id` in the description and the
+ evidence list** (`source_product: signals_scout`, `entity_id: <prior_id>`).
+ The inbox groups by dedupe key.
+
+3. **Same fact already covered** — a prior run already emitted with the same
+ evidence shape. → Skip. Optionally rewrite an existing scratchpad entry
+ confirming the topic stayed quiet (same key + new content = idempotent
+ refresh).
+
+4. **Already-addressed or noise** — a scratchpad entry has `addressed:` /
+ `noise:` / `dedupe:` prefix and names the issue id with a "team aware" note.
+ → Skip; note in your summary that the scratchpad covered it.
+
+## Scratchpad key prefixes
+
+The scratchpad has no tags. Encode the category in the **key prefix** so future
+runs can find an entry with a single `text=` search:
+
+| Prefix | Use for |
+| ------------- | -------------------------------------------------------------------------------- |
+| `pattern:` | Durable observation about how this team's data normally shapes (baselines, etc). |
+| `noise:` | Patterns to ignore (single-user, dev-only, recurring with no fix path). |
+| `addressed:` | Team-confirmed fix shipped or topic the team has moved on from. |
+| `dedupe:` | Gates future emits on a specific issue / fingerprint / finding id. |
+| `allowlist:` | Vetted entities the scout should never re-surface. |
+| `not-in-use:` | Close-out memo for "product not in use on this team". |
+| `mcp-gap:` | Scout-noticed gap in the MCP surface worth raising in a future review. |
+
+Format: `<prefix>:<domain>:<entity>` (e.g. `pattern:error_tracking:baseline`,
+`noise:logs:rabbitmq-deploy-window`, `dedupe:csp_violations:a1b2c3d4`).
+
+Canonical `<domain>` values: `error_tracking`, `warehouse`, `experiments`,
+`llm_analytics`, `web_analytics`, `feature_flags`, `logs`, `surveys`,
+`revenue_analytics`, `csp_violations`, `observability_gaps`.
+
+Re-using a key updates the entry in place and refreshes `updated_at` — that's
+the idempotent refresh pattern. Use it to confirm a quiet observation without
+duplicating entries.
+
+## When to write a scratchpad entry vs emit
+
+| Situation | Action |
+| ------------------------------------------------------------------- | ----------------------------------------------------------------------- |
+| Confirmed real signal, not yet emitted by anyone. | Emit (new). |
+| Confirmed real signal, prior run covered it, you have new evidence. | Emit (cite prior `finding_id`). |
+| Pattern observed but `confidence < 0.65`. | Scratchpad entry with `pattern:` prefix. |
+| Investigated and ruled out; would waste a future run if rechecked. | Scratchpad entry with `noise:` or `addressed:` prefix. |
+| Scratchpad already covers this; no change. | Skip; note in summary. |
+| Issue currently quiet but worth re-checking later. | Rewrite the existing entry (same key) with fresh timestamp + condition. |
+
+## Entry shape that pays off
+
+Good entries are **future-run actionable**. The next scout reads them and
+changes behavior because of them:
+
+```text
+key: dedupe:error_tracking:019de34e-2026-05-01
+content: "2026-05-01: surfaced UndefinedTable on access_control_propertyaccesscontrol
+ (issue 019de34e-e2a3-7e53-80d0-8ccdd0866a36) — 434 users hit it 11:31-13:22 UTC,
+ then stopped. If a future run sees this issue still firing, escalate; if it's
+ been quiet since 13:22, treat as already-surfaced."
+```
+
+Why this works: dated, names the entity id, gives a clear conditional ("still
+firing → escalate; quiet → skip"), bounded by a precise time anchor. The key
+prefix makes it findable via `text=dedupe:` or `text=error_tracking`.
+
+Bad entry: key `note-1`, content "we have errors today, FYI". No actionability,
+no entity, no condition, key carries no category — the next run can't find it
+or act on it.
+
+## Cross-project noise patterns
+
+These are noise across all PostHog projects. Skip them unless you see a real
+escalation:
+
+- **Single-user, single-session errors** — one user, one occurrence, no other
+ signal. Almost always a personal browser quirk.
+- **Dev-environment exception bursts** — high counts on `$exception` events
+ whose `service` or `properties.env` is `dev` / `local` / `test`. Filter before
+ weighing.
+- **Sandbox-internal Docker / agentsh errors** — Docker `TimeoutExpired`,
+ sandbox sync failures. Internal harness operations, not user-facing.
+- **KEA store-path errors with single-session reach** — frontend logic state
+ quirks; not user-impacting unless distinct_user counts climb.
+- **Pre-known upstream provider errors** (Anthropic / OpenAI rate limits, etc.)
+ — already covered by past scratchpad entries; don't re-emit unless volume or
+ shape changes meaningfully.
+
+The team's scratchpad extends this list per-project as the scout learns.
diff --git a/products/signals/skills/signals-scout-general/references/emit.md b/products/signals/skills/signals-scout-general/references/emit.md
new file mode 100644
index 000000000000..74b0572d4157
--- /dev/null
+++ b/products/signals/skills/signals-scout-general/references/emit.md
@@ -0,0 +1,193 @@
+# Emit: how to call `signals-scout-emit-signal`
+
+Read this before your first emit. The harness validates request shape but doesn't
+grade prose quality — that's on you.
+
+## Required fields
+
+| Field | Type | Constraint |
+| ------------- | ------ | --------------- |
+| `description` | string | non-empty prose |
+| `weight` | float | `[0.0, 1.0]` |
+| `confidence` | float | `[0.0, 1.0]` |
+| `evidence` | list | 0-20 entries |
+
+## Recommended fields (use them; the inbox uses them)
+
+| Field | Type | When |
+| -------------- | ---------------------- | -------------------------------------------------------------------- |
+| `hypothesis` | string | Always — one-line root-cause hypothesis the finding tests. |
+| `severity` | `P0`-`P4` | Always — informational; calibrates downstream review. |
+| `dedupe_keys` | list of strings | Always — see "Dedupe keys" below. |
+| `time_range` | `{date_from, date_to}` | When the finding has a clear window (burst, deploy, experiment). |
+| `finding_id` | string | Always — stable trace id (not a dedupe key); see "Finding ID" below. |
+| `mcp_trace_id` | string | When you used MCP queries you'd want a reviewer to replay. |
+
+## Description prose contract
+
+The description becomes the inbox surface and the dedupe target. A busy human
+reads it in a feed of 30 other findings. Aim for one tight paragraph (3-6
+sentences):
+
+1. **Hook** — what's happening, quantified.
+ _"High-volume UndefinedTable errors started firing at 11:31 UTC today — 434
+ occurrences across 434 distinct users."_
+
+2. **Pattern** — the shape that makes this signal not noise.
+ _"One occurrence per user, all on the same fingerprint, confined to a 2-hour
+ window — indicates a per-request server path, not a stray exception."_
+
+3. **Hypothesis** — what you think the cause is.
+ _"Likely an ORM query against a `PropertyAccessControl` model whose Postgres
+ migration didn't ship to this environment."_
+
+4. **Lineage** — if a prior run touched a related topic, cite its `finding_id`.
+
+5. **Recommendation** — what action would resolve it.
+
+Quantify ("434 users") over qualitative ("many users"). Cite entity IDs (issue
+ids, recording ids, dashboard ids) inline so a human can pivot straight from
+prose to source.
+
+## Weight rubric (ranking score)
+
+`weight` ranks findings within the inbox feed. Higher = more attention-worthy to
+a human reviewer, not "more confident" — that's `confidence`.
+
+| Range | Use when |
+| ----------- | ------------------------------------------------------------------------------------ |
+| `0.85-1.00` | Active customer impact, large blast radius, or a deploy regression with a clear fix. |
+| `0.65-0.84` | Material pattern worth investigating today; not yet user-impacting at scale. |
+| `0.40-0.64` | Notable but speculative; or a confirmed minor issue worth the team knowing about. |
+| `0.20-0.39` | Curiosity-level. |
+| `0.00-0.19` | Don't emit. Skip or write a scratchpad entry instead. |
+
+## Confidence rubric (epistemic certainty)
+
+`confidence` is your certainty the finding is _real_ — independent of weight.
+
+| Range | Use when |
+| ----------- | ----------------------------------------------------------------------------------------- |
+| `0.85-1.00` | Multiple corroborating queries; pattern unambiguous; verified not in inbox or scratchpad. |
+| `0.65-0.84` | One strong query + plausible hypothesis; minor unknowns remain. |
+| `0.40-0.64` | Suggestive pattern with material gaps you'd want a human to validate. |
+| `0.00-0.39` | Don't emit. Gather more evidence or skip. |
+
+If you can't get to `confidence ≥ 0.65`, prefer a scratchpad entry over emitting.
+
+## Severity mapping
+
+`P0`-`P4` is informational only — no automated routing — but use it consistently:
+
+| Severity | Meaning |
+| -------- | --------------------------------------------------------------------- |
+| `P0` | Active critical impact (data loss, total outage, security exposure). |
+| `P1` | Active material impact (errors hitting many users, billing affected). |
+| `P2` | Confirmed issue, contained scope or non-urgent mitigation path. |
+| `P3` | Suspected issue or minor confirmed issue. |
+| `P4` | Curiosity / FYI. |
+
+## Evidence list shape
+
+Each entry: `{source_product, summary, entity_id?}`. The harness caps at 20.
+
+- `source_product` — short string identifying where the citation came from. Common
+ values: `error_tracking`, `session_replay`, `logs`, `feature_flag`, `experiment`,
+ `web_analytics`, `data_warehouse`, `query_runs`, `signals_scout` (cite a prior
+ run / finding), `inbox` (cite a SignalReport).
+- `summary` — one sentence on _why this evidence supports the finding_.
+- `entity_id` — the citable id. Pin issue UUIDs, recording IDs, dashboard
+ short_ids, insight short_ids, prior `scout_run_id`s, prior `finding_id`s.
+
+Include a citation for every concrete claim in the description.
+
+## Dedupe keys
+
+Stable strings the inbox uses to group related findings across runs and sources.
+Format: `<kind>:<entity_id>` or `<kind>:<entity_id>:<qualifier>`.
+
+Common kinds: `error_tracking_issue:<id>`, `experiment:<id>`, `feature_flag:<key>`,
+`warehouse_source:<id>`, `dashboard:<id>`, `insight:<short_id>`,
+`missing_migration:<table_name>`, `traffic_anomaly:<event_name>`.
+
+Include 1-2 keys per finding. Multiple is fine when a finding spans entities.
+
+## Finding ID
+
+`finding_id` is a stable, human-readable trace id — it ties the emitted signal
+back to the run that produced it (stored in the signal's `source_id` metadata). It
+is **not** a dedupe key: `emit_signal` dedupes on its own generated `document_id`
+(and your `dedupe_keys`), never on `finding_id`. Re-calling emit with the same
+`finding_id` writes a _second_ signal — so never retry an emit that may already
+have succeeded. Format: `<topic>-<entity>-<date>` is a safe default.
+
+Examples:
+
+- `missing-migration-access-control-propertyaccesscontrol-2026-05-01`
+- `experiment-checkout-flow-conversion-drop-2026-04-29`
+- `warehouse-stripe-charges-stuck-2026-04-30`
+
+Stable, human-readable, dated. A recurrence on a later day becomes a new finding
+(cite the prior `finding_id` in the description).
+
+## Worked example
+
+Real finding from a shadow run on 2026-05-01:
+
+```yaml
+finding_id: missing-migration-access-control-propertyaccesscontrol-2026-05-01
+weight: 0.92
+confidence: 0.9
+severity: P1
+hypothesis: >
+ A new access_control.PropertyAccessControl model is referenced in production
+ code paths without its Postgres migration applied — every per-request ORM
+ check hits the missing table.
+evidence:
+ - source_product: error_tracking
+ entity_id: 019de34e-e2a3-7e53-80d0-8ccdd0866a36
+ summary: >
+ Primary issue UndefinedTable on access_control_propertyaccesscontrol —
+ 434 occurrences across 434 distinct users between 11:31 and 13:22 UTC.
+ - source_product: error_tracking
+ entity_id: 019de34e-48ea-7e12-b76a-106d06e2f153
+ summary: >
+ POST /api/environments/1/query/HogQLQuery/ returning 500, first seen at
+ 11:30:49Z — same window, likely same root cause.
+ - source_product: signals_scout
+ entity_id: 019de09b-bd36-78a7-b3ff-fba34c252187
+ summary: >
+ Prior run on 2026-04-30 surfaced the same class of bug (signals refactor
+ missing migration) — internal-only blast radius. Today's pattern is the
+ end-user-facing equivalent.
+time_range:
+ date_from: 2026-05-01T11:31:30Z
+ date_to: 2026-05-01T13:22:02Z
+dedupe_keys:
+ - error_tracking_issue:019de34e-e2a3-7e53-80d0-8ccdd0866a36
+ - missing_migration:access_control_propertyaccesscontrol
+description: |
+ High-volume UndefinedTable / ProgrammingError: relation
+ "access_control_propertyaccesscontrol" does not exist started firing at
+ 2026-05-01T11:31:30Z (issue 019de34e-e2a3-7e53-80d0-8ccdd0866a36, active, no
+ assignee). 434 occurrences across 434 distinct users between 11:31 and 13:22
+ UTC — one hit per user indicates a per-request code path (likely an ORM check
+ on the new access_control.PropertyAccessControl model). Continuation of
+ yesterday's signals-backend refactor cluster (run
+ 019de09b-bd36-78a7-b3ff-fba34c252187, internal-only) but with much wider
+ blast radius. Recommend confirming the migration adding
+ access_control_propertyaccesscontrol is in the deployed set, running it, then
+ verifying the issue stops firing. None of these are in the inbox.
+```
+
+Why this is a good finding:
+
+- **Quantified hook**: 434/434 in a precise 2-hour window.
+- **Pattern explained**: "one hit per user" rules out alternatives.
+- **Lineage**: cites prior run id; the inbox groups them.
+- **Recommendation**: actionable.
+- **Evidence**: diverse sources strengthen confidence.
+- **Dedupe keys**: both issue-id and topic-keyed, dedupes either way.
+- **Severity**: P1 justified by 434-user blast.
+- **Confidence 0.9**: pattern unambiguous; remaining uncertainty is "did the
+ migration actually not ship, or is something else mocking this table?"
diff --git a/products/signals/skills/signals-scout-llm-analytics/SKILL.md b/products/signals/skills/signals-scout-llm-analytics/SKILL.md
new file mode 100644
index 000000000000..e2fcf5df44bf
--- /dev/null
+++ b/products/signals/skills/signals-scout-llm-analytics/SKILL.md
@@ -0,0 +1,200 @@
+---
+name: signals-scout-llm-analytics
+description: >
+ Focused Signals scout for PostHog projects using LLM analytics. Watches `$ai_generation`,
+ `$ai_evaluation`, `$ai_trace` and related events for cost spikes, latency drift, eval
+ pass-rate drops, runaway loops, and error rates. Emits findings only when they clear
+ the confidence bar; otherwise writes durable memory and closes out empty. Self-contained
+ peer in the signals-scout-* fleet — no dependencies on other skills. Picked uniformly
+ at random by the coordinator alongside `signals-scout-general` and other specialists.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes (mostly read-only, plus
+ signal_scout_internal:write for scratchpad-remember/forget and emit-signal). Assumes the signals-scout MCP family is available (project-profile-get, runs-list,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus
+ standard analytics + LLM tools (query-llm-traces-list, query-llm-trace, llma-evaluation-list,
+ get-llm-total-costs-for-project).
+metadata:
+ owner_team: signals
+ scope: llm_analytics
+---
+
+# Signals scout: LLM analytics
+
+You are a focused LLM analytics scout. Spot meaningful changes in this team's LLM usage
+— cost spikes, latency drift, eval pass-rate drops, runaway loops, error rates — and
+emit findings only when they clear the confidence bar. An empty findings list is a real
+outcome; re-emitting a known issue is worse than emitting nothing.
+
+## Quick close-out: is LLM analytics even in use?
+
+If `$ai_generation`, `$ai_evaluation`, `$ai_trace`, `$ai_span`, `$ai_metric`, `$ai_feedback`
+are all absent from `top_events` **and** `get-llm-total-costs-for-project` shows
+near-zero spend, this team isn't using LLM analytics. Write one scratchpad entry:
+
+- key: `not-in-use:llm_analytics:team{team_id}`
+- content: brief note ("checked at {timestamp}, no LLM events in top_events, $0 cost")
+
+Close out empty. Future LLM-analytics runs will read this entry cold and short-circuit
+in seconds. Re-running with the same key idempotently refreshes the timestamp — the
+entry stays until LLM analytics actually shows up, at which point the next run rewrites
+or deletes it.
+
+## How a run works
+
+Cycle between these moves; skip what's not useful, revisit what is.
+
+### Get oriented
+
+Three cheap reads cold-start a run:
+
+- `signals-scout-scratchpad-search` (`text=llm` or `text=ai_`) — durable team
+ steering inherited from past LLM-focused runs. **Entries with `pattern:`, `noise:`,
+ `addressed:`, or `dedupe:` key prefixes tell you what's normal, what's already
+ surfaced, what to skip.**
+- `signals-scout-runs-list` (last 7d) — what prior LLM-analytics scouts found and ruled
+ out. Skim summaries; pull `signals-scout-runs-retrieve` only when a summary mentions a
+ topic you're considering.
+- `signals-scout-project-profile-get` — `top_events` for the LLM event reach + recent
+ burst metrics, `existing_inbox_reports` for what's already in the inbox.
+
+### Explore
+
+The patterns below are starting points, not a checklist. Pick what looks interesting
+from the orientation reads and follow it.
+
+#### Cost spike
+
+`get-llm-total-costs-for-project` shows cost rising materially (≥ 2x baseline) over the
+recent window. Common causes: a model swap (e.g. Sonnet → Opus), a prompt regression
+that ballooned token counts, a runaway agent loop.
+
+Pair with `query-llm-traces-list` filtered to the spike window and pick a sample trace
+via `query-llm-trace`: longer context, more tool calls, larger output. Convergence with
+a recent deploy in `activity-log-list` is high-signal.
+
+#### Eval pass-rate drop
+
+`llma-evaluation-list` plus the latest evaluation results show pass-rate dropping below
+baseline. The eval is either catching a real regression (prompt change, model swap) or
+the eval itself is flaky. Surface it; let the team triage.
+
+#### Runaway loop / power-user pattern
+
+`$ai_generation` `count` very high vs `distinct_users` very low. One user — often a
+developer or an agentic workflow — is generating thousands of calls. Validate with
+`query-llm-traces-list` filtered to the top user. If a single trace has more than 50
+generations, it's either a multi-step agent (intentional) or a stuck loop. Memory
+probably already records which side of this the team is on.
+
+#### Trace-level failure spike
+
+`query-llm-traces-list` filtered to traces with errors or non-2xx responses. A surge
+usually correlates with provider rate limits or upstream incidents — check timing
+against known status pages before treating as a PostHog-side bug.
+
+#### New model adoption
+
+Traces from a model that wasn't in the previous profile snapshot. Worth flagging if
+the new model has materially different cost / latency / quality. Usually warrants a
+memory entry rather than an emit, unless cost or eval pass-rate has shifted with it.
+
+#### Cluster-level pattern
+
+`llma-clustering-job-list` exposes clustering jobs over recent generations. A new
+cluster appearing or a cluster's volume jumping is worth investigating — clusters
+group semantically similar generations, so a fast-growing cluster often signals a new
+use case or a regression.
+
+### Save memory as you go
+
+Memory is a continuous activity, not an end-of-run wrap-up. Write a scratchpad entry
+whenever you observe something a future LLM-analytics run should know. Encode the
+"category" in the key prefix — `pattern:`, `noise:`, `addressed:`, `dedupe:` — so future
+runs can find it with a single `text=` search:
+
+- key `pattern:llm_analytics:generation-baseline` — _"This team's `$ai_generation` baseline
+ is ~5k/day across ~3k distinct users; 1.6:1 ratio is normal for their multi-step agent."_
+- key `noise:llm_analytics:relevance-judge` — _"Eval `relevance-judge` flakes ~5% per run —
+ flag only if pass-rate drops below 80%."_
+- key `pattern:llm_analytics:nightly-batch-eval` — _"Nightly batch eval runs ~02:00–04:00
+ UTC and accounts for ~40% of daily cost — not a runaway, recurring."_
+- key `addressed:llm_analytics:model-swap-2026-04-28` — _"Switched primary model from Sonnet
+ to Opus 2026-04-28; cost ~2.1x baseline expected."_
+
+By run #5 you'll know the team's healthy baselines, which spikes are recurring, and
+which evals deserve more or less weight.
+
+### Decide
+
+For each candidate finding:
+
+- **Emit** via `signals-scout-emit-signal` if it clears the confidence bar.
+ Findings carry a hypothesis, evidence, severity, weight ∈ [0, 1], and confidence ∈ [0, 1].
+ Strong scout findings: weight ≥ 0.7, confidence ≥ 0.85, with concrete trace IDs or
+ query results in the evidence.
+- **Remember** if it's below the bar but worth carrying forward, or to record what you
+ ruled out and why.
+- **Skip** with a one-line note in your final summary if a scratchpad entry with a
+ `noise:` or `addressed:` key prefix already covers it.
+
+If a prior run already covered the topic, default to skip + memory refresh rather than
+re-emit. Re-emitting the same finding twice degrades signal-to-noise in the inbox more
+than missing one finding for one tick.
+
+### Close out
+
+**Summarize the run** — one paragraph: what you looked at, what you emitted, what you
+remembered, what you ruled out and why. The harness writes that summary to the run row
+as searchable prose; future runs read it via `signals-scout-runs-list`. Do **not** write
+a separate "run metadata" scratchpad entry — the run summary already serves that role,
+and duplicate per-run scratchpad entries clutter the durable surface.
+
+## Disqualifiers (skip these)
+
+- **Anthropic / OpenAI rate-limit errors** — surface in the error-tracking lens too. If
+ the scratchpad has a `noise:` entry for them, skip; otherwise leave one.
+- **Single developer testing locally** — `properties.environment ∈ {dev, local}` or
+ internal user. Filter before weighing.
+- **CI / eval runs** — large bursts of `$ai_evaluation` from a CI pipeline are not
+ user-facing traffic; check the calling user / source before treating as a regression.
+- **Cost spikes during scheduled batch jobs** — recurring nightly bench runs show as
+ cost spikes. Memory should record their cadence.
+
+When in doubt, write a memory entry instead of emitting. Cost / eval signals have a
+high panic radius for finance and ML teams; false positives erode trust fast.
+
+## MCP tools
+
+Direct calls (read-only):
+
+- `query-llm-traces-list` — start here. Recent traces, filterable by user / model / cost / error.
+- `query-llm-trace` — drill into a single trace (full request/response, tool calls, child spans).
+- `llma-evaluation-list` — what evals exist on this team.
+- `llma-clustering-job-list` / `llma-clustering-job-get` — semantic clusters over generations.
+- `get-llm-total-costs-for-project` — top-level cost surface.
+- `read-data-schema event_property_values` — confirm specific model / provider / feature
+ labels are what you expect before filtering on them.
+
+Harness-level:
+
+- `signals-scout-project-profile-get` — cold orientation snapshot.
+- `signals-scout-scratchpad-search` / `signals-scout-scratchpad-remember` — durable steering across runs.
+- `signals-scout-runs-list` / `signals-scout-runs-retrieve` — what prior runs found.
+- `signals-scout-emit-signal` — emit a finding.
+
+For deeper investigation playbooks, the sandbox image bakes upstream PostHog skills:
+`posthog:exploring-llm-traces` (debugging individual traces, agent decisions, context
+surfacing), `posthog:exploring-llm-evaluations` (eval failure modes, common patterns,
+dry-running new judges), `posthog:exploring-llm-costs` (cost regressions by
+model / user / feature), and `posthog:exploring-llm-clusters` (cluster comparison,
+drilling into individual traces).
+
+## When to stop
+
+- Scratchpad + recent runs + profile are quiet → close out empty.
+- A candidate matches a scratchpad entry with `noise:` / `addressed:` / `dedupe:` key
+ prefix → skip with a one-line note.
+- You've validated some hypotheses and emitted what's solid → close out, even if
+ there's more you could look at. Fewer, better signals.
+
+"Looked but found nothing meaningful" is a real outcome, not a failure.
diff --git a/products/signals/skills/signals-scout-logs/SKILL.md b/products/signals/skills/signals-scout-logs/SKILL.md
new file mode 100644
index 000000000000..28a7b11dc9a2
--- /dev/null
+++ b/products/signals/skills/signals-scout-logs/SKILL.md
@@ -0,0 +1,207 @@
+---
+name: signals-scout-logs
+description: >
+ Focused Signals scout for PostHog projects using logs. Watches for volume bursts,
+ severity-distribution shifts, service silence, fresh message patterns, and
+ trace-correlated bursts via the logs ingestion pipeline. Emits findings only when
+ they clear the confidence bar; otherwise writes durable memory and closes out empty.
+ Self-contained peer in the signals-scout-* fleet — no dependencies on other skills.
+ Picked uniformly at random by the coordinator alongside `signals-scout-general` and
+ other specialists.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes (mostly read-only, plus
+ signal_scout_internal:write for scratchpad-remember/forget and emit-signal). Assumes the signals-scout MCP family is available (project-profile-get, runs-list,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus
+ the logs tool family (logs-count, logs-count-ranges, logs-sparkline-query, query-logs,
+ logs-attributes-list, logs-attribute-values-list, logs-alerts-list).
+metadata:
+ owner_team: signals
+ scope: logs
+---
+
+# Signals scout: logs
+
+You are a focused logs scout. Spot meaningful changes in this team's log volume,
+severity distribution, service activity, and fresh message patterns — and emit findings
+only when they clear the confidence bar. Logs live in their own ingestion pipeline
+distinct from `top_events`, so the project profile won't tell you whether logs are
+loud today; you have to ask.
+
+## Quick close-out: are logs even in use?
+
+If `logs-count` over the last 24h returns zero or near-zero, this team isn't using
+logs. Write one scratchpad entry:
+
+- key: `not-in-use:logs:team{team_id}`
+- content: brief note ("checked at {timestamp}, logs-count over 24h ≈ 0")
+
+Close out empty. Future logs runs will read this entry cold and short-circuit in
+seconds. Re-running with the same key idempotently refreshes the timestamp — the entry
+stays until logs ingestion actually shows up, at which point the next run rewrites or
+deletes it.
+
+## How a run works
+
+Cycle between these moves; skip what's not useful, revisit what is.
+
+### Get oriented
+
+Three cheap reads cold-start a run:
+
+- `signals-scout-scratchpad-search` (`text=logs` or `text=service`) — durable team steering
+ from past logs-focused runs. **Entries with `pattern:`, `noise:`, `addressed:`, or
+ `dedupe:` key prefixes tell you what's normal, what's already surfaced, what to skip.**
+- `signals-scout-runs-list` (last 7d) — what prior logs scouts found and ruled out.
+- `logs-count` over 24h vs `logs-count` over 7d-prior 24h baseline — the cheap
+ is-anything-loud-today check. `logs-count-ranges` adds severity / service breakdown.
+
+### Explore
+
+Patterns to watch — these are starting points, not a checklist.
+
+#### Volume burst
+
+`logs-count` over 24h is materially above the 7d-prior baseline (≥ 2x). Localize by
+re-running `logs-count` (or `logs-count-ranges` for the time-bucketed shape) filtered
+by `severity` and by `service` — these tools count a filter, they don't group, so
+narrow with the filter and compare. Common causes: a stuck retry loop logging at
+`info`, a feature deploy that bumped log verbosity, a misconfigured logger emitting
+at `debug` in prod.
+
+Cross-source convergence: if `top_events` shows `$exception` flat over the same window,
+this is logs-exclusive — handled-but-real failures the application catches and logs but
+doesn't re-raise. Distinct from anything error tracking will surface.
+
+#### Severity distribution shift
+
+Total volume flat but `error` / `fatal` proportion rising. Captures the kind of failure
+error tracking misses: caught-and-logged exceptions, retry-with-eventual-success patterns,
+degraded-but-functional dependencies (slow DB, cold cache, partial third-party outage).
+
+Validate via `query-logs` filtered to `severity ∈ {error, fatal}` over the recent window,
+grouped by `service` or `module`. A single service accounting for the rise is
+high-confidence; a uniform rise across services suggests an upstream platform issue.
+
+#### Service silence
+
+A service that normally accounts for a meaningful share of total log volume drops to
+near-zero. Different shape from error tracking entirely — there's no exception, the
+service is just gone.
+
+Validate: `logs-attribute-values-list` on `service` for active services, then
+`logs-count-ranges` per service over today vs 7d-prior to confirm the missing service
+was active before. Cross-check `top_events` for the service's expected user-facing
+events — if those also dropped, the service is genuinely down.
+
+#### Fresh message pattern
+
+`query-logs` for records with high count and `first_seen` in the last few days. A
+fresh message text repeated thousands of times indicates a new code path firing at
+scale. Pull `logs-attributes-list` to see what structured fields the record carries
+(`error_code`, `module`, stack-frame fields).
+
+If the message references an exception, cross-check `query-error-tracking-issues-list` first
+— if an issue already covers it, error tracking owns the finding.
+
+#### Trace-correlated burst
+
+Log records carrying `trace_id` correlating to slow or failing traces. When a
+`query-llm-traces-list` failure spike, an `query-error-tracking-issues-list` burst, and a
+`query-logs` burst all share the same trace ids — that's the cleanest cross-source
+convergence pattern logs enables.
+
+#### Alert without inbox coverage
+
+`logs-alerts-list` exposes the team's configured alerts. An alert with `state =
+firing` whose underlying condition isn't already in `inbox-reports-list` is a
+high-confidence finding — the team has the alert plumbing but not the inbox surface.
+
+### Save memory as you go
+
+Memory is a continuous activity. Write a scratchpad entry whenever you observe something
+a future logs run should know. Encode the "category" in the key prefix — `pattern:`,
+`noise:`, `addressed:`, `dedupe:` — so future runs can find it with a single `text=` search:
+
+- key `pattern:logs:temporal-worker` — _"Service `temporal-worker` typical log volume:
+ ~12k/hour with ~3% error severity. Anything > 10% error in the recent window is fresh
+ degradation."_
+- key `noise:logs:rabbitmq-deploy-window` — _"Log message `connection refused: rabbitmq:5672`
+ is recurring noise during deploy windows (Mon/Wed 14:00 UTC) — auto-recovers within 5 min."_
+- key `pattern:logs:alert-47` — _"Logs alert `db-connection-pool-saturated` (id 47) auto-mutes
+ 02:00–04:00 UTC for nightly batch — firing outside that window is real."_
+- key `addressed:logs:cdp-worker-2026-04-30` — _"Service `cdp-worker` migrated to a new
+ runtime on 2026-04-30 — log volume baseline shifted from 8k/hour to 14k/hour, treat new
+ baseline as normal."_
+
+By run #5 you'll know per-service volume and severity baselines, which alerts are
+intentional outliers, and only surface fresh shifts.
+
+### Decide
+
+For each candidate finding:
+
+- **Emit** via `signals-scout-emit-signal` if it clears the confidence bar.
+ Strong scout findings: weight ≥ 0.7, confidence ≥ 0.85, with concrete service /
+ message / time-range evidence.
+- **Remember** if below the bar but worth carrying forward.
+- **Skip** with a one-line note if a scratchpad entry with a `noise:` or `addressed:`
+ key prefix already covers it.
+
+If a prior run already covered the topic, default to skip + scratchpad refresh rather
+than re-emit. Same fact twice in the inbox degrades signal-to-noise more than missing
+one finding for one tick.
+
+### Close out
+
+**Summarize the run** — one paragraph: looked at what, emitted what, remembered what,
+ruled out what. The harness writes this to the run row as searchable prose; future runs
+read it via `signals-scout-runs-list`. Do **not** write a separate "run metadata"
+scratchpad entry — the run summary already serves that role.
+
+## Disqualifiers (skip these)
+
+- **Routine debug logs from internal services** — `severity = debug` records from
+ sandbox / internal tooling. Filter before counting.
+- **Dev / local / test environment logs** — `service` or attribute values matching
+ dev-style patterns (`*-dev`, `*-local`, `*-test`). Filter on the team's expected
+ service allowlist.
+- **One-off deploy log floods** — temporary spike during a deploy that subsides within
+ 30–60 minutes. Memory should record the team's typical deploy windows.
+- **Logs alerts in muted / snoozed state** — explicit team decision; don't override.
+- **Log error already covered by error tracking** — if a log record correlates 1:1
+ with an `$exception` issue already surfaced, that issue's finding (or a scratchpad
+ entry with `dedupe:` key prefix) governs. Don't double-emit.
+
+When in doubt, write a memory entry instead of emitting.
+
+## MCP tools
+
+Direct calls (read-only):
+
+- `logs-count` — start here. Total volume over a window.
+- `logs-count-ranges` — compare windows (today vs 7d-prior, this hour vs same hour
+ yesterday); supports breakdowns.
+- `logs-sparkline-query` — sparkline shape; useful for spotting a sharp burst vs a
+ sustained shift.
+- `query-logs` — drill into individual records. Filter by severity, service, message
+ text, attribute values, time range.
+- `logs-attributes-list` / `logs-attribute-values-list` — discover the team's log shape.
+- `logs-alerts-list` / `logs-alerts-retrieve` — configured alerts and current state.
+- `inbox-reports-list` — verify a finding isn't already in the inbox.
+- `query-error-tracking-issues-list` — cross-check whether a log error already has an issue;
+ error tracking owns those findings.
+
+Harness-level:
+
+- `signals-scout-project-profile-get` / `signals-scout-scratchpad-search` /
+ `signals-scout-runs-list` / `signals-scout-runs-retrieve` — orientation + dedupe.
+- `signals-scout-emit-signal` / `signals-scout-scratchpad-remember` — emit / remember.
+
+## When to stop
+
+- Volume + severity at baseline, no fresh patterns → close out empty.
+- A candidate matches a scratchpad entry with `noise:` / `addressed:` / `dedupe:` key
+ prefix → skip with a one-line note.
+- You've validated some hypotheses and emitted what's solid → close out.
+
+"Looked but found nothing meaningful" is a real outcome.
diff --git a/products/signals/skills/signals-scout-observability-gaps/SKILL.md b/products/signals/skills/signals-scout-observability-gaps/SKILL.md
new file mode 100644
index 000000000000..fd54a90eb53d
--- /dev/null
+++ b/products/signals/skills/signals-scout-observability-gaps/SKILL.md
@@ -0,0 +1,266 @@
+---
+name: signals-scout-observability-gaps
+description: >
+ Focused Signals scout for finding observability gaps in PostHog itself — significant
+ event volumes the team isn't tracking, custom events with no insight or dashboard
+ coverage, insights pointing at events that have stopped firing, dashboards missing
+ related context, critical events with no alerts. Watches the event-stream-vs-saved-
+ inventory delta as the team's product evolves and emits findings recommending new
+ insights, dashboard additions, or alerts when gaps clear the confidence bar.
+ Self-contained peer in the signals-scout-* fleet — picked uniformly at random by the
+ coordinator alongside `signals-scout-general` and other specialists.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes (mostly read-only, plus
+ signal_scout_internal:write for scratchpad-remember/forget and emit-signal). Assumes the signals-scout MCP family is available (project-profile-get, runs-list,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus
+ standard analytics + entity tools (read-data-schema, query-trends, insights-list,
+ dashboards-get-all, event-definitions-list, alerts-list, execute-sql).
+metadata:
+ owner_team: signals
+ scope: observability_gaps
+---
+
+# Signals scout: observability gaps
+
+You are a focused observability-gaps scout. Spot meaningful gaps between **what events
+this team is producing** and **what they have set up to observe** — and emit findings
+that recommend new insights, dashboard additions, or alerts when a gap clears the
+confidence bar. An empty findings list is a real outcome; recommending things the team
+already has, or recommending coverage for noise events, is worse than recommending
+nothing.
+
+The shape of this scout is different from the other specialists: the findings are
+**recommendations**, not **problems**. The confidence bar is correspondingly higher —
+a noisy "you should track X" stream destroys the inbox's signal-to-noise ratio. Prefer
+fewer, well-evidenced recommendations.
+
+## Quick close-out: is this team big enough to have gaps?
+
+If `top_events` in the project profile is null or shows fewer than ~5 events firing
+above 100/day, the project is too quiet for observability-gap analysis to surface real
+recommendations. Write one scratchpad entry:
+
+- key: `not-applicable:observability_gaps:team{team_id}`
+- content: brief note ("checked at {timestamp}, top_events count <5 above 100/day, too
+ quiet for gap analysis")
+
+Close out empty. Future observability-gaps runs read this entry cold and short-circuit
+in seconds. Re-running with the same key idempotently refreshes the timestamp — the
+entry stays until the team grows into meaningful volume, at which point the next run
+rewrites or deletes it.
+
+## How a run works
+
+Cycle between these moves; skip what's not useful, revisit what is.
+
+### Get oriented
+
+Three cheap reads cold-start a run:
+
+- `signals-scout-scratchpad-search` (`text=gap` or `text=observability`) — durable team
+ steering inherited from past observability runs. **Entries with `pattern:`, `noise:`,
+ `addressed:`, or `dedupe:` key prefixes tell you what's normal, what's already
+ surfaced, what to skip.** Critical here because the same gap should never be re-emitted
+ across runs.
+- `signals-scout-runs-list` (last 14d) — what prior observability-gap scouts found and
+ what was ruled out. Skim summaries; pull `signals-scout-runs-retrieve` only when a
+ summary mentions a recommendation you're considering.
+- `signals-scout-project-profile-get` — `top_events` for volume + reach, `popular_insights`
+ for what's already saved, `recent_dashboards` for the dashboards in active use. This
+ one read tells you most of what you need to detect gaps.
+
+### Explore — what good observability gaps look like
+
+Six families of gap, ordered by typical signal density. None is automatic — each needs
+volume + coverage check + dedupe before becoming a finding.
+
+#### 1. High-volume custom event with no insight coverage
+
+Custom event (not a `$builtin` like `$pageview` / `$identify`) firing meaningful
+volume per day, no saved insight references it.
+
+Direct calls:
+
+- `read-data-schema events` — surface event names + 24h volumes.
+- `execute-sql` against `system.insights` — find insights mentioning the event name in
+ `name`, `description`, or `query` JSON. Pattern: `query::text ILIKE '%{event_name}%'`.
+- Check `event-definitions-list` for `last_seen_at` recency and the `verified` flag —
+ the team flagged it as worth tracking.
+
+Strong signal: event > 1000/day, no insight, `verified=true`. Weak signal: event
+< 100/day, untyped, sporadic.
+
+#### 2. Insight drift — saved insights pointing at zero-volume events
+
+An existing insight filters on event X, but X has 0 (or near-zero) firings in the last
+7 days. Often a sign of:
+
+- Event renamed (e.g. `signed_up` → `sign_up_completed`) and the insight wasn't updated.
+- Event sunset (deprecated by product change) and the insight is stale.
+- Capture broken upstream (different lens — let error-tracking own this).
+
+Direct calls:
+
+- `execute-sql` over `system.insights` to extract the events series each insight
+ filters on.
+- `query-trends` to measure recent volume of those events.
+- For zero-volume events, search `event-definitions-list` for similar names suggesting
+ a rename (Levenshtein-close, same prefix, same property shape).
+
+Strong signal: insight has been viewed in the last 30d AND its primary event has 0
+firings in 7d AND a similar-named event is firing > 100/day.
+
+#### 3. Critical event with no alerts configured
+
+Some events name themselves — `payment_failed`, `signup_failed`, `*_error`, `*_blocked`.
+If they fire at all and no alert exists, that's a gap. Use the project's own
+patterns: search the event vocabulary for terms like `failed`, `error`, `blocked`,
+`denied`, `rejected`, `timeout`, `crashed`.
+
+Direct calls:
+
+- `read-data-schema events` filtered by name pattern (`failed`, `error`, etc).
+- `alerts-list` — what alerts exist and what they target.
+- `query-trends` to confirm volume is non-trivial (not just one-off).
+
+Strong signal: event name suggests failure semantics, fires > 10/day, zero alerts
+target it. Weak signal: name has `error` but the event is benign developer telemetry.
+
+#### 4. Dashboard scope gap
+
+A dashboard exists for a topic (name + description match a domain like "Onboarding",
+"Revenue", "Conversion"), but high-volume events related to that topic are not on any
+of its insights.
+
+Direct calls:
+
+- `dashboards-get-all` — current dashboards + tags + descriptions.
+- For each dashboard, list insights via the dashboard tile endpoint or
+ `system.insights WHERE id IN (dashboard.insight_ids)`.
+- Match domain-themed events to dashboards by name overlap.
+
+Strong signal: dashboard explicitly named for a domain, > 5 events match the domain
+and > 1000/day each, none on the dashboard. Weak signal: arbitrary keyword overlap.
+
+#### 5. Funnel candidate — sequential event pattern with no funnel insight
+
+Three or more events that frequently co-occur in user sessions in a fixed order, no
+funnel insight tracks the sequence. Usually an onboarding flow, signup flow, checkout
+flow, etc.
+
+Direct calls:
+
+- `query-paths` (one call) on top distinct events to surface common sequences.
+- `execute-sql` against `system.insights WHERE filters::text ILIKE '%FunnelsQuery%'`
+ to find existing funnels.
+- Check sequence length + retention (% users completing each step).
+
+Strong signal: 3-step sequence with > 1000 users completing step 1, > 50% reaching
+step 2, no existing funnel covering the sequence. Confidence threshold is high here
+because funnels are subjective — a common sequence isn't always a meaningful funnel.
+
+#### 6. Property cardinality / missing breakdown
+
+A high-cardinality property on a high-volume event, and existing insights tracking
+the event use no breakdown — the team is losing dimension by aggregation.
+
+Direct calls:
+
+- `read-data-schema event_property_values` — see distinct values for a property.
+- `execute-sql` over `system.insights` for the event — extract `breakdownFilter` shape.
+- Compare property cardinality to whether any insight breaks down by it.
+
+Strong signal: property has 5-50 distinct values (not unbounded), event > 5000/day,
+no insight breaks down by it. Weak signal: property has 1000+ distinct values
+(would explode the chart) or ≤ 2 values (no information added).
+
+### Recommend — emit a finding
+
+A finding here recommends an action, not surfaces a problem. Required elements:
+
+- **Specific event(s) / insight(s) / dashboard(s)** — entity IDs in the evidence list
+ so a human can click straight to them.
+- **Volume + reach numbers** — the gap matters because of _N_ events affecting _M_
+ users; quote both.
+- **Suggested action** — "create a trends insight on event X" / "update insight Y to
+ point at event Z" / "add insight A to dashboard B" / "configure an alert on event C".
+ Concrete is better than abstract.
+- **Why now** — if this gap has existed for weeks, why is it surfacing now? Because
+ volume just crossed a threshold? Because a new event class emerged? Volume + recency
+ is the dedupe key.
+
+Severity for observability-gap findings is almost always **P3** (suggestion). The
+confidence bar trades off:
+
+- **Volume threshold** — gap is structurally interesting only at scale. Below 100/day,
+ the recommendation is noise.
+- **Stable-not-spurious** — gap has been present for at least 7 days. Avoid flagging
+ events that just appeared yesterday.
+- **No prior coverage** — search `popular_insights` and `existing_inbox_reports`
+ before emitting. If a previous run already recommended this gap, don't re-emit.
+
+### Close out
+
+**Summarize the run** — one paragraph: what you looked at, what you emitted, what you
+remembered, what you ruled out and why. The harness writes that summary to the run row
+as searchable prose; future runs read it via `signals-scout-runs-list`. Do **not** write
+a separate "run metadata" scratchpad entry — the run summary already serves that role.
+
+## Disqualifiers (skip these)
+
+- **Builtin events without saved insights** — `$pageview`, `$autocapture`, `$identify`,
+ `$set`, `$opt_in`, `$groupidentify`, `$feature_flag_called` are surfaced through
+ PostHog's product views (Web Analytics, Feature Flags) without needing a custom
+ insight. Don't recommend creating one.
+- **Test events from internal users** — pin a `noise:observability_gaps:internal-distinct-ids`
+ scratchpad entry for known internal distinct_ids and skip them in volume counts.
+- **Events from disabled feature flags** — if the event only fires when a flag is
+ disabled or only for a tiny rollout %, the volume is artificially low.
+- **Events on ad-hoc one-off dashboards** — a private dashboard with one viewer doesn't
+ count as "covered." Use the `popular_insights` viewer-count threshold.
+
+When in doubt, write a scratchpad entry instead of emitting. Recommendations have a
+high panic radius for whoever owns the observability surface — false positives erode
+trust fast.
+
+## MCP tools
+
+Direct calls (read-only):
+
+- `read-data-schema` — `kind=events` for volumes, `kind=event_properties` /
+ `event_property_values` for cardinality and breakdowns.
+- `query-trends` — confirm recent-window volume + reach numbers cited in evidence.
+- `query-paths` — sequence detection for funnel candidates.
+- `insights-list` — paginated insight catalog (use sparingly; SQL is faster).
+- `dashboards-get-all` — active dashboards + tags.
+- `event-definitions-list` — event-definition metadata: `verified` flag, `last_seen_at`,
+ `created_at`, custom-vs-builtin marker.
+- `alerts-list` — existing alert configurations and what events they target.
+- `execute-sql` over `system.insights` / `system.dashboards` / `system.cohorts` —
+ the fast path for "does an insight reference event X?" type queries.
+
+Harness-level:
+
+- `signals-scout-project-profile-get` — cold orientation snapshot. Has `top_events`,
+ `popular_insights[13]`, `recent_dashboards`, `existing_inbox_reports` already.
+- `signals-scout-scratchpad-search` / `signals-scout-scratchpad-remember` — durable steering.
+- `signals-scout-runs-list` / `signals-scout-runs-retrieve` — what prior runs found.
+- `signals-scout-emit-signal` — emit a recommendation finding.
+
+For deeper investigation playbooks, the sandbox image bakes upstream PostHog skills:
+`posthog:querying-posthog-data` (HogQL syntax + system.\* search patterns) and
+`posthog:exploring-autocapture-events` (custom-event vs autocapture distinctions, when
+each lens applies).
+
+## When to stop
+
+- Scratchpad + recent runs + profile show every domain you've considered already has
+ coverage or has been recommended → close out empty.
+- A candidate matches a scratchpad entry with `addressed:` (recommendation actioned) or
+ `noise:` (recommended but ignored) key prefix → skip with a one-line note.
+- You've validated 1-2 high-confidence gaps and emitted them → close out, even if
+ there's more you could look at. Quality over volume — recommendations are a budget,
+ not a target.
+
+"Looked but found nothing meaningful" is a real outcome, not a failure. Every
+recommendation that doesn't ship is one fewer false positive eroding the inbox.
diff --git a/products/signals/skills/signals-scout-revenue-analytics/SKILL.md b/products/signals/skills/signals-scout-revenue-analytics/SKILL.md
new file mode 100644
index 000000000000..774265e431b8
--- /dev/null
+++ b/products/signals/skills/signals-scout-revenue-analytics/SKILL.md
@@ -0,0 +1,299 @@
+---
+name: signals-scout-revenue-analytics
+description: >
+ Focused Signals scout for PostHog projects using revenue analytics. Watches the
+ derived revenue product for upstream failures (Stripe sync stalls, capture
+ regressions), config drift (missing subscription property, currency mix surprises,
+ broken Stripe↔person joins, deferred-revenue gaps), and goal-miss escalations.
+ Emits findings only when they clear the confidence bar; otherwise writes durable
+ memory and closes out empty. Self-contained peer in the signals-scout-* fleet —
+ no dependencies on other skills. Picked uniformly at random by the coordinator
+ alongside `signals-scout-general` and other specialists.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes (mostly read-only, plus
+ signal_scout_internal:write for scratchpad-remember/forget and emit-signal). Assumes the signals-scout MCP family (project-profile-get, runs-list,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus
+ warehouse + analytics tools (external-data-sources-list, external-data-sync-logs,
+ query-trends, execute-sql, read-data-schema, dashboards-get-all,
+ data-warehouse-data-health-issues-retrieve).
+metadata:
+ owner_team: signals
+ scope: revenue_analytics
+---
+
+# Signals scout: revenue analytics
+
+You are a focused revenue analytics scout. Revenue analytics is a **derived product** —
+it doesn't have its own event stream; it standardizes data from two upstream paths into
+the `revenue_analytics_*` managed views (charge, customer, mrr, product, revenue_item,
+subscription):
+
+- **Events source** — team-configured revenue events (e.g. `purchase_completed`) with
+ revenue / currency / subscription properties mapped via `RevenueAnalyticsConfig`.
+- **Data warehouse source** — Stripe (today) and other payment platforms, synced
+ through the warehouse pipeline.
+
+Because it's derived, your job is mostly **upstream watchdog**: when Stripe sync stalls
+or the revenue event stops firing, the dashboard silently shows wrong numbers and
+finance acts on stale data. That's the high-impact class. Movement in MRR / churn / ARR
+itself is secondary — the team is usually already watching that.
+
+Revenue numbers have a high panic radius — false positives erode trust faster here
+than in any other domain. When in doubt, memory entry, not emit.
+
+## Quick close-out: is revenue analytics even active?
+
+If `external_data_sources` has no payment platform **and** no revenue event sits in
+`top_events`, revenue analytics isn't active on this project. Write one scratchpad entry:
+
+- key: `not-in-use:revenue_analytics:team{team_id}`
+- content: brief note ("checked at {timestamp}, no payment platform, no revenue events")
+
+Close out empty. Future revenue runs read this entry cold and short-circuit fast.
+Re-running with the same key idempotently refreshes the timestamp — the entry stays
+until revenue analytics actually becomes active, at which point the next run rewrites
+or deletes it.
+
+## How a run works
+
+Cycle between these moves; skip what's not useful.
+
+### Get oriented
+
+Three cheap reads cold-start a run:
+
+- `signals-scout-scratchpad-search` (`text=revenue` or `text=stripe`) — durable team
+ steering. Entries with `pattern:`, `noise:`, `addressed:`, or `dedupe:` key prefixes,
+ plus the team's known revenue event name, Stripe source label, currency mix, and goals.
+- `signals-scout-runs-list` (last 7d) — what prior revenue runs found and ruled out.
+- `signals-scout-project-profile-get` — `external_data_sources` (Stripe status),
+ `top_events` (configured revenue event reach), `popular_insights` /
+ `recent_dashboards` (revenue chart load-bearingness), `product_intents` (stuck
+ onboarding).
+
+### Profile shape — what's loud today?
+
+| Pattern | What it usually means |
+| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
+| Stripe-shaped `external_data_sources` row with `status = failed` or stuck `running` | Revenue dashboard silently stale — high-impact upstream watchdog |
+| Configured revenue event missing or sharply down in `top_events` | Capture regression — MRR / gross revenue dropping artificially |
+| `popular_insights` includes revenue chart and chart's source is unhealthy | Confirmed downstream impact — high-confidence finding |
+| `product_intents` lists revenue analytics but no Stripe source and no event configured | Stuck onboarding — write memory, don't emit |
+| Recent revenue dashboard view counts unchanged after a known revenue movement | Team isn't watching — dashboard exists but isn't load-bearing |
+
+### Explore
+
+Patterns to watch — starting points, not a checklist.
+
+#### Upstream sync stale, dashboard reads wrong
+
+Stripe (or another payment platform) source is failed / stuck / cancelled. The
+dashboard at `/revenue` keeps rendering yesterday's MRR as today's. **Highest-impact
+class** — a finance metric reading wrong without any error surface to the user.
+
+1. `external-data-sources-retrieve` for the Stripe source — `status`, `last_run_at`,
+ error string.
+2. `external-data-sync-logs` for the failure pattern — one-off vs recurring.
+3. `execute-sql` against `system.insights` filtered to `name ILIKE '%revenue%' OR
+query::text ILIKE '%revenue_analytics%'` for blast radius.
+4. Cross-check `existing_inbox_reports` for an open warehouse-source report — if so,
+ surface the **revenue-specific** angle (which finance metrics are wrong) rather
+ than re-emitting the same warehouse failure.
+
+The warehouse failure is the recovery action; the revenue angle is the **business
+impact** prose: which dashboards, who reads them, what's wrong by how much.
+
+#### Revenue event capture regression
+
+Team configured `purchase_completed` (or similar) as their revenue event. Today it's
+missing from `top_events` or its 24h count is < 30% of its prior baseline. MRR for
+event-source customers will be artificially low; the gross revenue chart will look
+like a step-change drop.
+
+Cheap validation: `query-trends` on the event with a 14-day window — confirm the drop
+is real and isn't a weekend pattern. Pair with `read-data-schema event_properties` to
+check whether the revenue property itself stopped flowing (event still firing but with
+`null` revenue) — different upstream cause, same downstream symptom.
+
+High-confidence finding when:
+
+- 14-day trend shows a clear inflection, not a normal weekly cycle.
+- Event still defined in `RevenueAnalyticsConfig` (team didn't intentionally rename it).
+- Recent deploy / SDK upgrade timing matches the inflection (hint, not proof).
+
+#### Subscription property missing → MRR is empty
+
+Event source configured for a subscription business, but
+`RevenueAnalyticsConfig.events[].subscriptionProperty` is null. The MRR view will be
+empty because PostHog can't tell which charges belong to the same subscription. The
+dashboard renders but only gross revenue is meaningful.
+
+Detect: events configured with revenue + currency but no subscription property;
+gross-revenue chart populated, MRR chart empty. Scratchpad-level finding for
+new-onboarding teams; emit-worthy if the team has been live long enough that they
+should have noticed.
+
+#### Currency mix surprise
+
+`execute-sql` on `revenue_analytics.all.revenue_analytics_charge`:
+
+```sql
+SELECT original_currency, count(), sum(original_amount)
+FROM revenue_analytics.all.revenue_analytics_charge
+WHERE timestamp > now() - INTERVAL 30 DAY
+GROUP BY 1 ORDER BY 2 DESC
+```
+
+A currency that's never appeared before, or whose share suddenly jumped, usually means
+either (a) the team is selling into a new market — write a scratchpad entry, no emit,
+or (b) currency property is misconfigured and revenue is being mis-tagged. The (b) case
+shows up as a single dominant currency on a non-USD team or vice versa. Cross-reference
+with `RevenueAnalyticsEventItem.currencyProperty` to tell them apart.
+
+#### Stripe-customer ↔ PostHog-person join broken
+
+Stripe customers should carry `posthog_person_distinct_id` metadata so PostHog can
+attach revenue to the person profile. If newly-created customers stop carrying that
+metadata (post-deploy regression in checkout flow), aggregate views still work but
+person-level revenue (group analytics, customer journeys) goes dark.
+
+Detect via the `customer` view: count of customers with non-null
+`posthog_person_distinct_id` in last 30d vs the 30d before. Scratchpad-worthy if the
+team isn't using person-level revenue features; emit-worthy if they are (check
+`popular_insights` for person-breakdown revenue charts).
+
+#### Deferred revenue not deferring
+
+Stripe source healthy, but invoice line items missing the `period` property. The
+dashboard will show monthly revenue lumpy (annual subscriptions land in one month)
+instead of spread across the service period. Check the `revenue_item` view: rows where
+`is_recurring = true` and `period_start` / `period_end` are null. Emit when more than
+~20% of recurring rows are missing period info — finance reporting wrong in a subtle
+way.
+
+#### Goal miss without escalation
+
+`RevenueAnalyticsConfig.goals` carries `due_date` + `goal` + `mrr_or_gross`. If a
+goal's `due_date` is < 14 days out and current MRR (or gross revenue) is trending
+under the goal, the team should already be reacting. If recent dashboard views haven't
+ticked up, they aren't watching. Surface the gap; let the team decide.
+
+Disqualifier: goals with `due_date` already past, where the team hasn't updated them —
+config debt, not active targets. Scratchpad entry, skip emit.
+
+#### Test-account contamination
+
+`RevenueAnalyticsConfig.filter_test_accounts = false` on a project with a
+`person.properties.email` filter set up for test accounts. Internal QA charges are
+being counted as real revenue. Easy scratchpad entry; emit-worthy if the scratchpad
+shows the team has historically asked about "revenue jumped overnight" incidents and
+the cause was QA traffic.
+
+### Save memory as you go
+
+Memory is a continuous activity. Write a scratchpad entry whenever you observe something
+a future revenue run should know. Encode the "category" in the key prefix — `pattern:`,
+`noise:`, `addressed:`, `dedupe:` — so future runs find it with a single `text=` search:
+
+- key `pattern:revenue_analytics:event-config` — _"Revenue event is `purchase_completed`;
+ revenue prop is `revenue` (cents), currency prop is `currency`, subscription prop is
+ `subscription_id`."_
+- key `pattern:revenue_analytics:stripe_prod` — _"Stripe source `stripe_prod` is the
+ team's primary; `stripe_test` is sandbox and its failures are expected."_
+- key `pattern:revenue_analytics:currency-mix` — _"Reporting currency is USD;
+ `original_currency` regularly includes EUR / GBP / CAD — multi-currency mix is normal
+ for this team."_
+- key `pattern:revenue_analytics:q3-arr-goal` — _"Team has revenue analytics goals
+ configured; Q3 ARR target is $X by due_date 2026-09-30 — re-check progress monthly."_
+- key `pattern:revenue_analytics:dashboard-staleness` — _"Revenue dashboard at `/revenue`
+ was last viewed 2026-04-22; team isn't actively watching — emit at higher confidence
+ threshold."_
+- key `addressed:revenue_analytics:test-accounts` — _"`filter_test_accounts` is off; QA
+ charges from `@example.com` accounts appear in revenue — already raised, team aware."_
+
+By run #5 the scratchpad knows the team's revenue config, currency mix, which
+dashboards are load-bearing, and whether finance is actively watching — so when something
+regresses, the finding lands with the right context already attached.
+
+### Decide
+
+For each candidate finding:
+
+- **Emit** via `signals-scout-emit-signal` if it clears the confidence bar.
+ Strong scout findings: weight ≥ 0.7, confidence ≥ 0.85, with concrete dashboard ids,
+ source labels, view names, and quantified impact in the evidence.
+- **Remember** if below the bar but worth carrying forward.
+- **Skip** with a one-line note if a scratchpad entry with a `noise:` or `addressed:`
+ key prefix already covers it.
+
+Cross-check `inbox-reports-list` before emitting — if a warehouse-source failure is
+already in the inbox, surface only the revenue-specific business impact angle (which
+metrics are wrong, who reads them) rather than re-emitting the same upstream failure.
+
+### Close out
+
+**Summarize the run** — one paragraph: looked at what, emitted what, remembered what,
+ruled out what. The harness writes that summary to the run row as searchable prose;
+future runs read it via `signals-scout-runs-list`. Do **not** write a separate
+"run metadata" scratchpad entry — the run summary already serves that role.
+
+## Disqualifiers (skip these)
+
+- **Reporting currency just changed** — apparent step-change in all charts; not a
+ regression. A `pattern:` scratchpad entry from a prior run usually flags this.
+- **Revenue analytics in beta on the team's plan** — some teams use it as preview-only.
+ The scratchpad should record this; if no entry exists, write one and skip.
+- **Sandbox / test Stripe source** — `prefix` like `test_` or `sandbox_` means the team
+ is wiring up integration; failures here aren't production signal.
+- **Revenue event renamed by the team** — `RevenueAnalyticsConfig.events[].eventName`
+ was updated recently; the "missing event" is the old name. Cross-check config recency
+ before flagging.
+- **Goal expired with no follow-up** — config debt, not an active target. Scratchpad
+ entry, skip.
+
+When in doubt, write a memory entry instead of emitting.
+
+## MCP tools
+
+Direct calls (read-only):
+
+- `external-data-sources-list` / `external-data-sources-retrieve` — Stripe source
+ health. Filter `source_type` to payment platforms.
+- `external-data-sync-logs` — failure history; one-off vs recurring upstream issues.
+- `read-data-schema events` / `read-data-schema event_properties` — confirm revenue
+ event + properties still flow.
+- `query-trends` — validate event-volume drops with a 14-day window and weekly comparison.
+- `execute-sql` against `revenue_analytics.all.revenue_analytics_<charge|customer|mrr|revenue_item|subscription>`
+ — managed views are the source of truth. Per-source views also exist:
+ `<source>.<prefix>.revenue_analytics_<view_type>` (data warehouse) and
+ `revenue_analytics.events.<event_name>.revenue_analytics_<view_type>` (events).
+- `execute-sql` against `system.insights` / `system.dashboards` — find revenue insights
+ and dashboards that depend on a failing source (blast radius).
+- `dashboards-get-all` / `dashboard-get` — the built-in revenue dashboard and any
+ custom revenue dashboards.
+- `data-warehouse-data-health-issues-retrieve` — platform-detected issues on warehouse
+ sources; revenue is one of the highest-priority downstream consumers.
+
+Harness-level:
+
+- `signals-scout-project-profile-get` / `signals-scout-scratchpad-search` /
+ `signals-scout-runs-list` / `signals-scout-runs-retrieve` — orientation + dedupe.
+- `signals-scout-emit-signal` / `signals-scout-scratchpad-remember` — emit / remember.
+
+For deeper investigation, the sandbox image bakes
+`posthog:auditing-warehouse-data-health` (catches Stripe-source failures upstream of
+revenue analytics) and `posthog:diagnosing-failed-warehouse-syncs` (recovery actions
+for a failing sync).
+
+## When to stop
+
+- No payment platform + no revenue event → close out empty (after writing the
+ `not-in-use:` scratchpad entry).
+- Profile + scratchpad show a stable picture → close out empty.
+- A candidate matches a scratchpad entry with `noise:` / `addressed:` / `dedupe:` key
+ prefix → skip.
+- You've validated some hypotheses and emitted what's solid → close out, even if
+ there's more you could look at. Fewer, better signals — especially here, where
+ panic radius is high.
+
+"Looked but found nothing meaningful" is a real outcome.
diff --git a/products/signals/skills/signals-scout-surveys/SKILL.md b/products/signals/skills/signals-scout-surveys/SKILL.md
new file mode 100644
index 000000000000..f966691cb2fb
--- /dev/null
+++ b/products/signals/skills/signals-scout-surveys/SKILL.md
@@ -0,0 +1,525 @@
+---
+name: signals-scout-surveys
+description: >
+ Focused Signals scout for PostHog projects running surveys. Watches active surveys for
+ score regressions (NPS / CSAT / rating drops), response-volume drops, abandonment
+ spikes, and targeting drift, AND aggregates open-text responses into recurring themes
+ the team should know about (clusters of complaints, praise, feature requests). Emits
+ findings only when a theme or anomaly clears the confidence bar; otherwise writes
+ durable memory and closes out empty. Self-contained peer in the signals-scout-* fleet
+ — no dependencies on other skills. Picked uniformly at random by the coordinator
+ alongside `signals-scout-general` and other specialists.
+compatibility: >
+ Designed for the PostHog Signals agent in a Claude sandbox with PostHog MCP scopes (mostly read-only, plus
+ signal_scout_internal:write for scratchpad-remember/forget and emit-signal). Assumes the signals-scout MCP family (project-profile-get, runs-list,
+ scratchpad-search, scratchpad-remember, scratchpad-forget, emit-signal) plus
+ the surveys MCP tools (surveys-get-all, survey-get, survey-stats, surveys-global-stats)
+ and standard analytics tools (execute-sql, query-trends, read-data-schema,
+ activity-log-list).
+metadata:
+ owner_team: signals
+ scope: surveys
+---
+
+# Signals scout: surveys
+
+You are a focused surveys scout. Your job has two halves and they're equally important:
+
+1. **Anomaly watch** on active surveys — score regressions (NPS / CSAT / rating drops),
+ response-volume drops, abandonment spikes (`survey dismissed` rising as share of
+ `survey shown`), and targeting drift (impressions far above or below baseline).
+2. **Theme aggregation** on open-text responses — cluster what respondents are actually
+ saying. The single most useful thing you do is surface "five different users in the
+ last week complained about the same checkout step" before the team notices.
+
+Surveys are direct user voice. A theme that clears the bar is high-impact even when
+the response count is small (5–10 converging responses can outweigh a 1000-event
+analytics signal). Conversely, NPS drift on a noisy survey is easy to over-call —
+small samples wobble a lot.
+
+When in doubt, write a memory entry instead of emitting. Surveys are personal data; the
+panic radius for a wrong "users hate feature X" finding is high.
+
+## Quick close-out: are surveys even active?
+
+If `surveys-get-all` (with `archived: false`) returns an empty list **and**
+`surveys-global-stats` shows zero events in the last 30 days, surveys aren't active on
+this project. Write one scratchpad entry:
+
+- key: `not-in-use:surveys:team{team_id}`
+- content: brief note ("checked at {timestamp}, no active surveys, no survey events")
+
+Close out empty. Future surveys runs read this entry cold and short-circuit fast.
+Re-running with the same key idempotently refreshes the timestamp — the entry stays
+until surveys actually become active, at which point the next run rewrites or deletes it.
+
+## How a run works
+
+Cycle between these moves; skip what's not useful.
+
+### Get oriented
+
+Three cheap reads cold-start a run:
+
+- `signals-scout-scratchpad-search` (`text=survey` or `text=nps`) — durable team steering.
+ Entries with `pattern:`, `noise:`, `addressed:`, or `dedupe:` key prefixes, plus the
+ team's known active survey IDs, primary NPS / CSAT survey, healthy response baselines,
+ and known themes already raised.
+- `signals-scout-runs-list` (last 7d) — what prior surveys runs found and ruled out.
+- `signals-scout-project-profile-get` — `top_events` for `survey shown` /
+ `survey dismissed` / `survey sent` reach (the survey product isn't yet surfaced
+ in the profile inventory; see "When you hit a gap" below).
+
+Then orient on surveys specifically. Order matters — busy projects can have 100+
+active surveys, and `surveys-get-all` is **never the right cold-start move** there.
+Each survey object is 30–50 KB (questions, internal targeting flag, appearance
+theme, creator metadata) and even `limit: 5` returns ~30 KB. Listing the lot blows
+the token budget before you've made a single decision.
+
+Right order:
+
+1. `surveys-global-stats` (last 30d) — cheap project-wide check: are surveys
+ converting at all? If `survey sent` total is zero, close out empty.
+2. **Rank candidates by recent activity, not by config.** Use `execute-sql` to find
+ the top survey ids by `survey sent` volume in the last 30d:
+
+ ```sql
+ SELECT
+ JSONExtractString(properties, '$survey_id') AS survey_id,
+ count() AS sent_count,
+ max(timestamp) AS last_sent
+ FROM events
+ WHERE event = 'survey sent'
+ AND timestamp > now() - INTERVAL 30 DAY
+ GROUP BY survey_id
+ ORDER BY sent_count DESC
+ LIMIT 20
+ ```
+
+3. `survey-get {id}` on the top 5–10 ids only — full config when you actually
+ need to read questions / targeting / iteration / type. Never `surveys-get-all`
+ on a project where step 2 returns more than ~20 distinct ids.
+4. `survey-stats {id}` per candidate for `shown` / `dismissed` / `sent` counts.
+
+Use `surveys-get-all {"limit": 5}` only as a last resort when discovering a survey
+by name, and prefer `surveys-get-all {"search": "..."}` over a blind page walk.
+
+### Profile shape — what's loud today?
+
+| Pattern | What it usually means |
+| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
+| `survey-stats` shows `dismissed / shown` ratio sharply above the trailing baseline | Targeting / fatigue regression — the survey is wearing out |
+| `survey-stats` shows `sent / shown` (response rate) cratering on a previously-converting survey | Question changed, UX regression, or audience shift |
+| Open-text responses cluster around a single recent product change | Highest-value finding — qualitative confirmation of a user impact |
+| Rating score drops materially against the survey's own trailing baseline | Emit-worthy if the drop clears the tiered bar (see Score regression section) |
+| Survey running > 90 days with steadily declining responses | Stale survey — recommendation to retire / refresh, not an anomaly |
+| `survey shown` count diverges sharply from prior baseline (up or down) | Targeting drift — feature flag / cohort condition changed upstream |
+| Recent activity-log entries near the inflection point of a score drop | Connect the qualitative to a deploy — emit with timing as evidence |
+
+### Explore
+
+Patterns to watch — starting points, not a checklist.
+
+#### Score regression on an NPS / CSAT / rating survey
+
+Surveys with rating questions (NPS 0–10, CSAT 1–5, single rating) are the cleanest
+quantitative signal. For each rating-style active survey, pull the last 30 days of
+`survey sent` events and compute the score trend.
+
+**Resolving the response value — coalesce both key schemes.** PostHog writes each
+answer under two property keys and the product reads them with a `coalesce`
+(`getSurveyResponse()` in `frontend/src/scenes/surveys/utils.ts`). Query the same way
+or you will miss responses. Read `survey-get` for the question's `id` **and** its
+position in the `questions` array:
+
+- **id-based** (modern posthog-js): `$survey_response_<question_id>` — the question's UUID.
+- **index-based** (legacy, still emitted): bare `$survey_response` for the first
+ question (index 0), `$survey_response_<n>` (numeric) for question index _n_.
+
+A survey whose responses are only index-based — common when the rating is the first
+question, so the key is bare `$survey_response` — returns all-NULL under the id-based
+key alone, which reads as "no responses." Always coalesce id-based over the
+index-based fallback:
+
+```sql
+SELECT
+ toDate(timestamp) AS day,
+ avg(toFloat64OrNull(coalesce(
+ nullIf(JSONExtractString(properties, '$survey_response_<question_id>'), ''), -- id-based (modern)
+ nullIf(JSONExtractString(properties, '<index_based_key>'), '') -- '$survey_response' (index 0) or '$survey_response_<n>'
+ ))) AS avg_score,
+ count() AS responses
+FROM events
+WHERE event = 'survey sent'
+ AND JSONExtractString(properties, '$survey_id') = '<survey_id>'
+ AND timestamp > now() - INTERVAL 30 DAY
+GROUP BY day
+ORDER BY day
+```
+
+Always dedupe by `$survey_submission_id` for surveys collected after that property
+shipped — the legacy path is one row per submission, but newer client versions can
+emit multiple `survey sent` events per submission and you'll over-count rating
+responses. Pattern (from `products/surveys/backend/util.py`):
+
+```sql
+-- Inside the WHERE clause
+AND uuid IN (
+ SELECT argMax(uuid, timestamp) FROM events
+ WHERE event = 'survey sent'
+ AND JSONExtractString(properties, '$survey_id') = '<survey_id>'
+ AND timestamp > now() - INTERVAL 30 DAY
+ GROUP BY CASE
+ WHEN COALESCE(JSONExtractString(properties, '$survey_submission_id'), '') = ''
+ THEN toString(uuid)
+ ELSE JSONExtractString(properties, '$survey_submission_id')
+ END
+)
+```
+
+What counts as "enough responses" depends on the survey's normal volume. Flagship
+NPS surveys can hit 100+/week; a feature-specific widget survey running at 15–25
+responses/month is also normal. Use a tiered bar:
+
+- **High-volume surveys** (baseline ≥ 30 responses/week): require ≥ 30 in the
+ recent week, score drop ≥ 10% of scale (1 point NPS, 0.5 CSAT), holds across
+ the most recent 7 days vs the prior trailing 21 days.
+- **Low-volume surveys** (baseline 5–30/week): require ≥ 8 in the recent 14 days,
+ score drop ≥ 15% of scale, comparing against the survey's own trailing 60-day
+ baseline rather than week-over-week. Smaller samples need a larger effect to
+ outrun noise.
+- **Very low-volume surveys** (< 5/week): rating trends are too noisy to act on.
+ Treat as theme-aggregation only; memory entry, not emit.
+
+In all tiers, anchor on the survey's own trailing baseline before any global rule
+of thumb. A widget survey with a 6.0 trailing average that drops to 5.2 on N=12 is
+more interesting than a popover at NPS 32 → 31 on N=400 — and the scout's job is to
+spot the meaningful one.
+
+#### Response-rate cratering
+
+`survey-stats` returns `shown` and `sent` counts. A survey that converted at 8% last
+month and 0.5% this week is broken — usually because the question wording changed, the
+target audience changed, or the survey is being shown in a different context (a flag
+flipped, a page was redesigned). Pair the stats with `survey-get` to check the
+`updated_at` and questions; if the survey config was edited near the inflection,
+that's the cause. If not, suspect upstream.
+
+Disqualifier: a survey at the end of its scheduled window naturally tails off. Check
+`schedule.end_date` before treating low recent response rate as a regression.
+
+#### Abandonment spike (dismissed / shown ratio)
+
+`survey shown` events are impressions; `survey dismissed` are explicit close-outs;
+`survey sent` are completions. Their meaning **depends on the survey's `type`**, and
+the scout has to read `type` from `survey-get` before interpreting any ratio:
+
+- **`popover`** — `survey shown` fires when the popover auto-renders. A high
+ dismiss rate is genuine signal: users are seeing it and immediately killing it.
+- **`widget`** — `survey shown` only fires when the user clicks the widget
+ trigger. A high dismiss rate means users opened the widget and changed their
+ mind, not that the team is spamming them. Baseline dismiss rates are naturally
+ higher (50–70% is common; the Logs Feedback widget on PostHog itself runs at
+ 64% with healthy NPS) and shouldn't be flagged as fatigue.
+- **`api`** — `survey shown` fires from SDK calls. Semantics depend on the
+ integrating product; check `survey-get` to see how it's wired before
+ interpreting trends.
+
+If the dismiss rate jumps sharply on a `popover` survey (e.g. baseline 30%, recent
+70%), users are seeing it and immediately killing it. Common causes: the survey
+now appears at a worse moment in the user journey, or fatigue from displaying too
+often.
+
+For `widget` and `api` surveys, treat dismiss-rate shifts as low signal unless
+they're paired with a response-volume drop — that's when something upstream of
+the click changed.
+
+```sql
+SELECT
+ toDate(timestamp) AS day,
+ countIf(event = 'survey shown') AS shown,
+ countIf(event = 'survey dismissed') AS dismissed,
+ countIf(event = 'survey sent') AS sent,
+ dismissed / nullIf(shown, 0) AS dismiss_rate
+FROM events
+WHERE event IN ('survey shown', 'survey dismissed', 'survey sent')
+ AND JSONExtractString(properties, '$survey_id') = '<survey_id>'
+ AND timestamp > now() - INTERVAL 30 DAY
+GROUP BY day
+ORDER BY day
+```
+
+Memory note when a dismiss rate is structurally high (e.g. an exit-intent survey
+naturally has high dismiss); don't re-flag every run.
+
+#### Recurring theme in open-text responses
+
+This is the highest-value pattern — and the one with the highest false-positive risk.
+For each survey with at least one open-text question, pull recent responses and look
+for clustering.
+
+```sql
+SELECT
+ coalesce(
+ nullIf(JSONExtractString(properties, '$survey_response_<question_id>'), ''), -- id-based (modern)
+ nullIf(JSONExtractString(properties, '<index_based_key>'), '') -- '$survey_response' (index 0) or '$survey_response_<n>'
+ ) AS response,
+ person_id,
+ timestamp
+FROM events
+WHERE event = 'survey sent'
+ AND JSONExtractString(properties, '$survey_id') = '<survey_id>'
+ AND timestamp > now() - INTERVAL 14 DAY
+ AND coalesce(
+ nullIf(JSONExtractString(properties, '$survey_response_<question_id>'), ''),
+ nullIf(JSONExtractString(properties, '<index_based_key>'), '')
+ ) != ''
+ -- dedupe by submission as above
+ORDER BY timestamp DESC
+LIMIT 200
+```
+
+Read the responses. Look for:
+
+- **Convergence on a noun phrase or feature name** — five users mentioning "checkout",
+ "the new editor", "API key page" within 14 days is a real theme.
+- **Sentiment polarity** — separate complaints from praise from feature requests.
+ Don't combine them into a single "users said things" finding.
+- **Specificity** — "it's slow" is too generic; "the dashboard list page is slow when
+ I have > 10 dashboards" is concrete. The latter is emit-worthy.
+
+Theme is emit-worthy when:
+
+- ≥ 5 distinct respondents converge on the same theme within 14 days, OR
+- ≥ 3 distinct respondents converge AND the theme matches a recent activity-log entry
+ (deploy, flag flip, new feature) within the same window — strong qualitative
+ confirmation of an impact.
+
+When you emit, quote 2–3 representative responses verbatim in the evidence (no PII;
+truncate at sentence level if a response is long). Name the theme as a concrete claim
+("Users report the dashboard list is slow with > 10 dashboards"), not a vague summary
+("Users have feedback about dashboards").
+
+Don't emit when:
+
+- Responses are mostly NPS rating-only with no text — there's no theme to find.
+- Themes are evenly split (some users complaining, others praising the same feature) —
+ the signal cancels itself; memory entry instead.
+- A memory entry tagged `addressed` already covers the same theme.
+
+#### Targeting drift
+
+`survey shown` count diverging sharply from baseline (up 5x or down 5x) usually
+means an upstream targeting condition changed. Four sources to check via
+`survey-get`:
+
+- **`linked_flag_id`** — survey shows only when this flag evaluates true. A flag
+ rollout change directly resizes the audience.
+- **`targeting_flag_id`** — user-configured cohort / property targeting. Same
+ effect; also subject to cohort recomputation lag.
+- **`linked_insight_id`** — survey gates on viewing a specific insight. If the
+ insight is deleted or its query is broken, the survey goes dead. Cross-check
+ with `insight-get` and `inbox-reports-list` for any insight-side issues.
+- **`conditions`** — URL pattern, event-trigger, or `repeatedActivation` —
+ config changes here directly resize the trigger surface.
+
+If the upstream changed near the inflection, flag it as targeting drift, not a
+survey regression. (Note: the auto-managed `internal_targeting_flag` is a
+separate construct that suppresses already-responded / already-dismissed users —
+not a targeting source the team controls, and changes to it are usually
+expected.)
+
+Memory-worthy unless the survey is load-bearing (e.g. NPS the team reports on
+publicly) — then emit so the team knows the sample frame changed.
+
+#### Stale or abandoned surveys
+
+A survey created > 90 days ago with steadily declining response volume and no
+`updated_at` activity is probably forgotten. P3 recommendation, not an anomaly:
+suggest the team retire it, refresh the question, or rotate the audience. Don't
+re-emit if a memory entry already flagged it.
+
+#### Theme correlated with recent change
+
+When a theme emerges, cross-check `activity-log-list` for the period around the
+inflection. If a deploy / flag flip / feature change in the same week matches the
+theme content, the finding lands much harder ("4 users complained about checkout
+slowness on $date; deploy of `checkout-rewrite-v2` flag rolled to 100% on
+$date-1"). Timing is hint, not proof — say "matches" rather than "caused by".
+
+#### Theme drift across survey iterations
+
+Recurring surveys (`schedule: recurring`, `iteration_count > 1`,
+`iteration_frequency_days > 0`) cycle iterations every N days, and each
+iteration's responses are tagged with `$survey_iteration`. Comparing themes
+across iterations on the same survey is itself a signal:
+
+- Theme volume rising in iteration N+1 vs N on the same survey = the issue is
+ growing, not new.
+- New theme appearing in iteration N+1 that wasn't in earlier iterations =
+ recent product change introduced something.
+- Score baseline shifting between iterations = sustainable change in user
+ perception, more interesting than within-iteration noise.
+
+Filter open-text and rating queries by `$survey_iteration` to compare cleanly:
+
+```sql
+AND JSONExtractString(properties, '$survey_iteration') = '<n>'
+```
+
+When emitting on a recurring survey, name the iteration explicitly in the
+evidence ("iteration 3 of `nps-q1-2026`, last 14d") so the team reads it against
+the right baseline.
+
+### Save memory as you go
+
+Memory is a continuous activity. Write a scratchpad entry whenever you observe something
+a future surveys run should know. Encode the "category" in the key prefix — `pattern:`,
+`noise:`, `addressed:`, `dedupe:` — so future runs find it with a single `text=` search:
+
+- key `pattern:surveys:active-inventory` — _"Active surveys: `nps-q1-2026` (id `abc`,
+ NPS 0–10), `feedback-modal` (id `def`, open text), `csat-after-purchase` (id `ghi`,
+ 1–5 rating)."_
+- key `pattern:surveys:nps-q1-2026` — _"Primary NPS survey is `nps-q1-2026`; healthy
+ baseline 32 ± 5 over last 90 days, ~120 responses/week. Score < 25 or responses
+ < 60/week is the alert bar."_
+- key `noise:surveys:feedback-modal` — _"`feedback-modal` exit-intent survey naturally
+ has 70% dismiss rate — that's expected behavior for this trigger, not a regression."_
+- key `addressed:surveys:theme-checkout-step-2-2026-05-04` — _"Theme
+ `checkout-step-2-confusion` raised in run on 2026-04-30; team acknowledged, fix shipped
+ 2026-05-04. Don't re-emit unless theme reappears post-2026-05-04."_
+- key `addressed:surveys:csat-old-stale` — _"Survey `csat-old` last got responses
+ 2026-02; appears abandoned but the team still has it active. P3 recommendation already
+ filed; don't re-recommend."_
+
+By run #5 you'll know the team's active surveys, healthy response volumes, score
+baselines, which dismiss rates are structural, and which themes have already been
+raised — so when a real theme or regression appears, the finding lands with the right
+context already attached.
+
+### Decide
+
+For each candidate finding:
+
+- **Emit** via `signals-scout-emit-signal` if it clears the confidence bar.
+ Strong scout findings: weight ≥ 0.7, confidence ≥ 0.85, with concrete survey ids,
+ question ids, response counts, score deltas, and (for themes) 2–3 verbatim quotes
+ in the evidence. Sample-size matters here more than other domains — a finding on
+ 10 responses needs to be tighter than one on 200.
+- **Remember** if below the bar but worth carrying forward (a theme with only 3
+ respondents that might grow, a score wobble that didn't yet hold for two weeks).
+- **Skip** with a one-line note if a scratchpad entry with a `noise:` or `addressed:`
+ key prefix already covers it.
+
+Cross-check `inbox-reports-list` before emitting — if the same theme is already in the
+inbox from a prior run or another source, refresh the scratchpad rather than re-emit.
+
+### Close out
+
+**Summarize the run** — one paragraph: which surveys, what themes / anomalies you found,
+what you emitted, what you remembered, what you ruled out. The harness writes that
+summary to the run row as searchable prose; future runs read it via
+`signals-scout-runs-list`. Do **not** write a separate "run metadata" scratchpad entry —
+the run summary already serves that role.
+
+## Disqualifiers (skip these)
+
+- **Survey at the end of its scheduled window** — natural tail-off in responses;
+ not a regression. Check `schedule.end_date` before flagging.
+- **NPS / CSAT drift on < 30 responses in the recent window** — sample too small to
+ trust; memory entry only.
+- **Themes evenly split between positive and negative** — they cancel each other; no
+ single direction to surface.
+- **Theme matching an `addressed:` scratchpad entry** — the team already saw it and
+ acted; re-emitting wastes inbox space.
+- **One-off rant or off-topic response** — a single user typing "AAAA" or
+ quoting song lyrics isn't signal. Themes need ≥ 3 distinct respondents.
+- **Internal test / placeholder responses** — `TEST`, `TEST FEEDBACK DELETE!`,
+ `qwe`, `asdf`, single-character submissions, repeated submissions from the
+ survey author or the host org's own users. These are endemic on real projects
+ and will skew theme counts if you don't strip them. A `WHERE
+length(response) > 5 AND lower(response) NOT IN ('test', 'qwe', 'asdf')`
+ guard plus an `email NOT LIKE '%@<host_org_domain>%'` person-property filter
+ catches most of it.
+- **Survey paused or in draft** — not user-facing right now; check
+ `archived` / status / `start_date` before treating zero responses as a regression.
+- **PII or sensitive content in responses** — never emit verbatim PII. Quote the
+ themed claim, not the raw text, if responses contain personal data.
+
+When in doubt, write a memory entry instead of emitting.
+
+## MCP tools
+
+Direct calls (read-only):
+
+- `surveys-global-stats` — project-wide aggregate. **Start here** every cold
+ start; cheap sanity check on overall survey health before any per-survey work.
+- `survey-stats` — per-survey response statistics: `shown` / `dismissed` / `sent`
+ counts, unique respondents, conversion rates, timing. Date-filterable.
+- `survey-get` — full survey config for a candidate: questions (with ids and
+ types), `type` (popover / widget / api — affects how `survey shown` semantics
+ read), targeting (`linked_flag_id` / `targeting_flag_id` / `linked_insight_id`
+ / `conditions`), schedule (`start_date`, `end_date`), iteration config,
+ `updated_at`. Read this before drawing conclusions about score changes —
+ question wording changes invalidate trend comparisons.
+- `surveys-get-all` — last-resort discovery. Each survey object is 30–50 KB and
+ busy projects have 100+ active surveys; calling this with `limit > 5` will
+ blow your token budget. Prefer `surveys-global-stats` + an `execute-sql`
+ ranking query (see "Get oriented" above) to find the candidate set, then
+ `survey-get` per id. Use `surveys-get-all {"search": "..."}` if you need to
+ resolve a name from a memory entry.
+- `execute-sql` against `events` — for raw response analysis (rating trends, theme
+ aggregation, dedupe by `$survey_submission_id`). The properties to extract:
+ - `$survey_id` — which survey
+ - `$survey_iteration` — which iteration of a recurring survey
+ - `$survey_submission_id` — dedupe key (newer events; older events lack this)
+ - `$survey_response` — first question's response, index-based legacy key (index 0)
+ - `$survey_response_<n>` — index-based key for question index _n_ > 0 (numeric suffix)
+ - `$survey_response_<question_id>` — id-based per-question key (question UUID; preferred,
+ but coalesce over the index-based keys above — see "Resolving the response value")
+ - `$survey_completed`, `$survey_partially_completed`, `$survey_dismissed` — status
+ - `$survey_responded` — whether the user responded at all
+- `read-data-schema event_property_values` — sample response values to confirm
+ property keys exist and have the shape you expect before running heavy aggregations.
+- `query-trends` — confirm `survey shown` / `survey sent` volume trends with weekly
+ comparisons. Cheaper than a full SQL aggregation when you just need the shape.
+- `activity-log-list` — correlate themes / score drops with recent product changes.
+
+Harness-level:
+
+- `signals-scout-project-profile-get` / `signals-scout-scratchpad-search` /
+ `signals-scout-runs-list` / `signals-scout-runs-retrieve` — orientation + dedupe.
+- `signals-scout-emit-signal` / `signals-scout-scratchpad-remember` — emit / remember.
+
+### When you hit a gap
+
+Two MCP gaps are known and may be worth flagging in a separate PR rather than working
+around in-skill:
+
+- **Project profile doesn't include surveys.** Cold-start orientation has to call
+ `surveys-get-all` directly. Adding a `_surveys` builder to
+ `products/signals/backend/scout_harness/profile/builders.py` (a few rows: active
+ count, top surveys by recent volume, primary NPS / CSAT survey if any) would let
+ every scout — not just this one — see surveys at orientation time. Worth a P3.
+- **Survey summarization isn't MCP-callable.** The product has a summarization
+ pipeline at `products/surveys/backend/summarization/` but it's not exposed as an
+ MCP tool. If it were, this scout could lean on cached summaries instead of
+ re-aggregating themes from scratch each run. Worth a P2 for accuracy and cost.
+
+If you notice a third gap during a run that would meaningfully unlock this scout,
+write a scratchpad entry with key `mcp-gap:surveys:<short-name>` so the gap surfaces in
+the next review via `text=mcp-gap`.
+
+## When to stop
+
+- No active surveys + no recent survey events → close out empty (after writing the
+ `not-in-use:` scratchpad entry).
+- Profile + scratchpad show a stable picture (known baselines, no recent inflection) →
+ close out empty.
+- A candidate matches a scratchpad entry with `noise:` / `addressed:` / `dedupe:` key
+ prefix → skip.
+- You've validated some hypotheses and emitted what's solid → close out, even if
+ there's more you could look at. Themes especially — fewer, sharper findings beat
+ a long list of weak clusters.
+
+"Looked but found nothing meaningful" is a real outcome.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ed72989b4ddf..48cce9e0c26c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4584,6 +4584,34 @@
"readOnlyHint": true
}
},
+ "signals-scout-config-list": {
+ "description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "List scout configs",
+ "title": "List scout configs",
+ "required_scopes": ["signal_scout:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "signals-scout-config-update": {
+ "description": "Tune one scout by its config `id`: change its schedule (`run_interval_minutes`, 10–43200), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Update a scout config",
+ "title": "Update a scout config",
+ "required_scopes": ["signal_scout:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"signals-scout-emit-signal": {
"description": "Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so emit each finding exactly once and never retry an emit.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 07fe9b53766b..9d097746b9be 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4911,6 +4911,34 @@
"readOnlyHint": true
}
},
+ "signals-scout-config-list": {
+ "description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "List scout configs",
+ "title": "List scout configs",
+ "required_scopes": ["signal_scout:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "signals-scout-config-update": {
+ "description": "Tune one scout by its config `id`: change its schedule (`run_interval_minutes`, 10–43200), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Update a scout config",
+ "title": "Update a scout config",
+ "required_scopes": ["signal_scout:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"signals-scout-emit-signal": {
"description": "Fire `emit_signal` with `source_product = signals_scout`. The `finding_id` is baked into the deterministic `Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with the same `finding_id` emits a second signal, so emit each finding exactly once and never retry an emit.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 24298b75ac39..7e806272ad1b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30918,6 +30918,34 @@ export namespace Schemas {
custom_tags?: PatchedSessionSummariesConfigCustomTags;
}
+ /**
+ * Per-(team, skill) scout config: schedule, enablement, and emit posture.
+
+ One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
+ when it discovers a scout skill; this serializer lets agents tune the row.
+ */
+ export interface PatchedSignalScoutConfig {
+ readonly id?: string;
+ /** The `signals-scout-*` skill this config controls. Set at creation, not editable. */
+ readonly skill_name?: string;
+ /** Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator. */
+ enabled?: boolean;
+ /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. */
+ emit?: boolean;
+ /**
+ * Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.
+ * @minimum 10
+ * @maximum 43200
+ */
+ run_interval_minutes?: number;
+ /**
+ * When the coordinator last dispatched this scout. Null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at?: string | null;
+ readonly created_at?: string;
+ }
+
export interface PatchedSignalSourceConfig {
readonly id?: string;
source_product?: SourceProductEnum;
@@ -37054,6 +37082,34 @@ export namespace Schemas {
snooze_for?: number;
}
+ /**
+ * Per-(team, skill) scout config: schedule, enablement, and emit posture.
+
+ One row per `signals-scout-*` skill on the team. The coordinator auto-creates a row
+ when it discovers a scout skill; this serializer lets agents tune the row.
+ */
+ export interface SignalScoutConfig {
+ readonly id: string;
+ /** The `signals-scout-*` skill this config controls. Set at creation, not editable. */
+ readonly skill_name: string;
+ /** Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator. */
+ enabled?: boolean;
+ /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. */
+ emit?: boolean;
+ /**
+ * Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.
+ * @minimum 10
+ * @maximum 43200
+ */
+ run_interval_minutes?: number;
+ /**
+ * When the coordinator last dispatched this scout. Null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at: string | null;
+ readonly created_at: string;
+ }
+
/**
* Full `SignalScoutRun` projection used by `get-run`. Same shape as the summary
today; kept distinct so future detail-only extensions (linked Signal rows,
@@ -44636,6 +44692,7 @@ export namespace Schemas {
* `ProductTour` - ProductTour
* `Ticket` - Ticket
* `InstanceSetting` - InstanceSetting
+ * `SignalScoutConfig` - SignalScoutConfig
* @minLength 1
*/
scope?: ActivityLogListScope;
@@ -44714,6 +44771,7 @@ export namespace Schemas {
ProductTour: 'ProductTour',
Ticket: 'Ticket',
InstanceSetting: 'InstanceSetting',
+ SignalScoutConfig: 'SignalScoutConfig',
} as const;
/**
@@ -44778,6 +44836,7 @@ export namespace Schemas {
* `ProductTour` - ProductTour
* `Ticket` - Ticket
* `InstanceSetting` - InstanceSetting
+ * `SignalScoutConfig` - SignalScoutConfig
*/
export type ActivityLogListScopesItem = typeof ActivityLogListScopesItem[keyof typeof ActivityLogListScopesItem];
@@ -44844,6 +44903,7 @@ export namespace Schemas {
ProductTour: 'ProductTour',
Ticket: 'Ticket',
InstanceSetting: 'InstanceSetting',
+ SignalScoutConfig: 'SignalScoutConfig',
} as const;
export type AdvancedActivityLogsListParams = {
diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.ts
index bdfe807bf485..32029fa1dc95 100644
--- a/services/mcp/src/generated/platform_features/api.ts
+++ b/services/mcp/src/generated/platform_features/api.ts
@@ -162,10 +162,11 @@ export const ActivityLogListQueryParams = /* @__PURE__ */ zod.object({
'ProductTour',
'Ticket',
'InstanceSetting',
+ 'SignalScoutConfig',
])
.optional()
.describe(
- 'Filter by a single activity scope, e.g. "FeatureFlag", "Insight", "Dashboard", "Experiment".\n\n* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting'
+ 'Filter by a single activity scope, e.g. "FeatureFlag", "Insight", "Dashboard", "Experiment".\n\n* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting\n* `SignalScoutConfig` - SignalScoutConfig'
),
scopes: zod
.array(
@@ -232,9 +233,10 @@ export const ActivityLogListQueryParams = /* @__PURE__ */ zod.object({
'ProductTour',
'Ticket',
'InstanceSetting',
+ 'SignalScoutConfig',
])
.describe(
- '* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting'
+ '* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting\n* `SignalScoutConfig` - SignalScoutConfig'
)
)
.optional()
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 098592267b9e..45744ff127b3 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 12 enabled ops
+ * PostHog API - MCP 14 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -113,6 +113,59 @@ export const SignalsReportsStateCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * List the per-(team, skill) scout configs for this project — schedule (`run_interval_minutes`), `enabled`, and `emit` posture per scout.
+ * @summary List scout configs
+ */
+export const SignalsScoutConfigListParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+/**
+ * Tune one scout: change its schedule (`run_interval_minutes`), `enabled`, or `emit` (dry-run) posture. `skill_name` is fixed. Enabling records `enabled_by` and is activity-logged since it drives spend.
+ * @summary Update a scout config
+ */
+export const SignalsScoutConfigUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this Signal scout config.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const signalsScoutConfigUpdateBodyRunIntervalMinutesMin = 10
+export const signalsScoutConfigUpdateBodyRunIntervalMinutesMax = 43200
+
+export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
+ .object({
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe('Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator.'),
+ emit: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing.'
+ ),
+ run_interval_minutes: zod
+ .number()
+ .min(signalsScoutConfigUpdateBodyRunIntervalMinutesMin)
+ .max(signalsScoutConfigUpdateBodyRunIntervalMinutesMax)
+ .optional()
+ .describe(
+ 'Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.'
+ ),
+ })
+ .describe(
+ 'Per-(team, skill) scout config: schedule, enablement, and emit posture.\n\nOne row per `signals-scout-*` skill on the team. The coordinator auto-creates a row\nwhen it discovers a scout skill; this serializer lets agents tune the row.'
+ )
+
/**
* Return the team's deterministic project profile. For the internal scout token the response reflects the newest non-expired cached row or a freshly-built one (lazy compute on cache miss); `force_refresh=true` skips the cache and rebuilds from authoritative sources. Public read callers (session auth or a `signal_scout:read` PAK) get the newest cached profile, or 404 if none has been built yet — they never trigger a rebuild. Read this at the start of a run to orient on the team's product mix, integrations, warehouse sources, signal coverage, and existing inbox surface.
* @summary Get the current project profile
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index aaf7a035078d..80911b25510f 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -7,6 +7,8 @@ import {
SignalsReportsRetrieveParams,
SignalsReportsStateCreateBody,
SignalsReportsStateCreateParams,
+ SignalsScoutConfigUpdateBody,
+ SignalsScoutConfigUpdateParams,
SignalsScoutEmitSignalBody,
SignalsScoutEmitSignalParams,
SignalsScoutProjectProfileGetQueryParams,
@@ -178,6 +180,56 @@ const inboxSourceConfigsRetrieve = (): ToolBase<
},
})
+const SignalsScoutConfigListSchema = z.object({})
+
+const signalsScoutConfigList = (): ToolBase<
+ typeof SignalsScoutConfigListSchema,
+ WithPostHogUrl<Schemas.SignalScoutConfig[]>
+> => ({
+ name: 'signals-scout-config-list',
+ schema: SignalsScoutConfigListSchema,
+ // eslint-disable-next-line no-unused-vars
+ handler: async (context: Context, params: z.infer<typeof SignalsScoutConfigListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SignalScoutConfig[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/`,
+ })
+ return await withPostHogUrl(context, result, '/inbox')
+ },
+})
+
+const SignalsScoutConfigUpdateSchema = SignalsScoutConfigUpdateParams.omit({ project_id: true }).extend(
+ SignalsScoutConfigUpdateBody.shape
+)
+
+const signalsScoutConfigUpdate = (): ToolBase<
+ typeof SignalsScoutConfigUpdateSchema,
+ WithPostHogUrl<Schemas.SignalScoutConfig>
+> => ({
+ name: 'signals-scout-config-update',
+ schema: SignalsScoutConfigUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof SignalsScoutConfigUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.enabled !== undefined) {
+ body['enabled'] = params.enabled
+ }
+ if (params.emit !== undefined) {
+ body['emit'] = params.emit
+ }
+ if (params.run_interval_minutes !== undefined) {
+ body['run_interval_minutes'] = params.run_interval_minutes
+ }
+ const result = await context.api.request<Schemas.SignalScoutConfig>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/inbox/${result.id}`)
+ },
+})
+
const SignalsScoutEmitSignalSchema = SignalsScoutEmitSignalParams.omit({ project_id: true }).extend(
SignalsScoutEmitSignalBody.shape
)
@@ -367,6 +419,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'inbox-reports-set-state': inboxReportsSetState,
'inbox-source-configs-list': inboxSourceConfigsList,
'inbox-source-configs-retrieve': inboxSourceConfigsRetrieve,
+ 'signals-scout-config-list': signalsScoutConfigList,
+ 'signals-scout-config-update': signalsScoutConfigUpdate,
'signals-scout-emit-signal': signalsScoutEmitSignal,
'signals-scout-project-profile-get': signalsScoutProjectProfileGet,
'signals-scout-runs-list': signalsScoutRunsList,
diff --git a/services/mcp/src/tools/tool-utils.ts b/services/mcp/src/tools/tool-utils.ts
index 19885b38f793..bda2ffa6e50a 100644
--- a/services/mcp/src/tools/tool-utils.ts
+++ b/services/mcp/src/tools/tool-utils.ts
@@ -1,15 +1,25 @@
import type { Context } from '@/tools/types'
-/** Adds a _posthogUrl field to any type. Use instead of `T & { _posthogUrl: string }`. */
-export type WithPostHogUrl<T = unknown> = T & { _posthogUrl: string }
+/**
+ * Adds a _posthogUrl field to a result. For object results it's a sibling field; for raw
+ * array results the array is wrapped as `{ results, _posthogUrl }` — spreading an array into
+ * an object (`{ ...arr }`) would otherwise corrupt it into `{ 0: …, 1: …, _posthogUrl: … }`.
+ */
+export type WithPostHogUrl<T = unknown> = T extends readonly (infer U)[]
+ ? { results: U[]; _posthogUrl: string }
+ : T & { _posthogUrl: string }
-/** Adds _posthogUrl to a result object. */
+/** Adds _posthogUrl to a result. Wraps raw arrays in `{ results, _posthogUrl }` (see type above). */
export async function withPostHogUrl<T>(context: Context, result: T, path: string): Promise<WithPostHogUrl<T>> {
const projectId = await context.stateManager.getProjectId()
const baseUrl = context.api.getProjectBaseUrl(projectId)
const fullUrl = `${baseUrl}${path}`
+ if (Array.isArray(result)) {
+ return { results: result, _posthogUrl: fullUrl } as unknown as WithPostHogUrl<T>
+ }
+
return { ...result, _posthogUrl: fullUrl } as WithPostHogUrl<T>
}
diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.json
index fa4f574507a4..477085e9df89 100644
--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json
+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json
@@ -15,7 +15,7 @@
"properties": {
"command": {
"type": "string",
- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch-export\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox-reports\n- inbox-source-configs\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-personal-spend\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout-emit-signal\n- signals-scout-runs\n- signals-scout-scratchpad-forget\n- signals-scout-scratchpad-remember\n- signals-scout-scratchpad-search\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch-export\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox-reports\n- inbox-source-configs\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-personal-spend\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout-config\n- signals-scout-emit-signal\n- signals-scout-runs\n- signals-scout-scratchpad-forget\n- signals-scout-scratchpad-remember\n- signals-scout-scratchpad-search\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
}
},
"required": ["command"]
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/activity-log-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/activity-log-list.json
index 2537e181b140..0ee6c7d3f4bf 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/activity-log-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/activity-log-list.json
@@ -19,7 +19,7 @@
"type": "number"
},
"scope": {
- "description": "Filter by a single activity scope, e.g. \"FeatureFlag\", \"Insight\", \"Dashboard\", \"Experiment\".\n\n* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting",
+ "description": "Filter by a single activity scope, e.g. \"FeatureFlag\", \"Insight\", \"Dashboard\", \"Experiment\".\n\n* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting\n* `SignalScoutConfig` - SignalScoutConfig",
"enum": [
"Cohort",
"FeatureFlag",
@@ -81,14 +81,15 @@
"DashboardWidget",
"ProductTour",
"Ticket",
- "InstanceSetting"
+ "InstanceSetting",
+ "SignalScoutConfig"
],
"type": "string"
},
"scopes": {
"description": "Filter by multiple activity scopes, comma-separated. Values must be valid ActivityScope enum values. E.g. \"FeatureFlag,Insight\".",
"items": {
- "description": "* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting",
+ "description": "* `Cohort` - Cohort\n* `FeatureFlag` - FeatureFlag\n* `Person` - Person\n* `Group` - Group\n* `Insight` - Insight\n* `Plugin` - Plugin\n* `PluginConfig` - PluginConfig\n* `HogFunction` - HogFunction\n* `HogFlow` - HogFlow\n* `DataManagement` - DataManagement\n* `EventDefinition` - EventDefinition\n* `PropertyDefinition` - PropertyDefinition\n* `Notebook` - Notebook\n* `Endpoint` - Endpoint\n* `EndpointVersion` - EndpointVersion\n* `Dashboard` - Dashboard\n* `Replay` - Replay\n* `Experiment` - Experiment\n* `ExperimentHoldout` - ExperimentHoldout\n* `ExperimentSavedMetric` - ExperimentSavedMetric\n* `Survey` - Survey\n* `EarlyAccessFeature` - EarlyAccessFeature\n* `SessionRecordingPlaylist` - SessionRecordingPlaylist\n* `Comment` - Comment\n* `Team` - Team\n* `Project` - Project\n* `ErrorTrackingIssue` - ErrorTrackingIssue\n* `DataWarehouseSavedQuery` - DataWarehouseSavedQuery\n* `LegalDocument` - LegalDocument\n* `Organization` - Organization\n* `OrganizationDomain` - OrganizationDomain\n* `OrganizationMembership` - OrganizationMembership\n* `Role` - Role\n* `UserGroup` - UserGroup\n* `BatchExport` - BatchExport\n* `BatchImport` - BatchImport\n* `Integration` - Integration\n* `Annotation` - Annotation\n* `Tag` - Tag\n* `TaggedItem` - TaggedItem\n* `Subscription` - Subscription\n* `PersonalAPIKey` - PersonalAPIKey\n* `ProjectSecretAPIKey` - ProjectSecretAPIKey\n* `User` - User\n* `Action` - Action\n* `AlertConfiguration` - AlertConfiguration\n* `Threshold` - Threshold\n* `AlertSubscription` - AlertSubscription\n* `ExternalDataSource` - ExternalDataSource\n* `ExternalDataSchema` - ExternalDataSchema\n* `Evaluation` - Evaluation\n* `LLMTrace` - LLMTrace\n* `WebAnalyticsFilterPreset` - WebAnalyticsFilterPreset\n* `CustomerProfileConfig` - CustomerProfileConfig\n* `Log` - Log\n* `LogsAlertConfiguration` - LogsAlertConfiguration\n* `LogsExclusionRule` - LogsExclusionRule\n* `DashboardWidget` - DashboardWidget\n* `ProductTour` - ProductTour\n* `Ticket` - Ticket\n* `InstanceSetting` - InstanceSetting\n* `SignalScoutConfig` - SignalScoutConfig",
"enum": [
"Cohort",
"FeatureFlag",
@@ -150,7 +151,8 @@
"DashboardWidget",
"ProductTour",
"Ticket",
- "InstanceSetting"
+ "InstanceSetting",
+ "SignalScoutConfig"
],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-list.json
new file mode 100644
index 000000000000..7b7ea9186078
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-list.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {},
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
new file mode 100644
index 000000000000..ade8d3b007da
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "emit": {
+ "description": "Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing.",
+ "type": "boolean"
+ },
+ "enabled": {
+ "description": "Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator.",
+ "type": "boolean"
+ },
+ "id": {
+ "description": "A UUID string identifying this Signal scout config.",
+ "type": "string"
+ },
+ "run_interval_minutes": {
+ "description": "Minutes between runs (10–43200). The scout runs once this interval has elapsed since its last run.",
+ "maximum": 43200,
+ "minimum": 10,
+ "type": "number"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/utils.test.ts b/services/mcp/tests/unit/utils.test.ts
index f0e88b62ea38..912ccb133b10 100644
--- a/services/mcp/tests/unit/utils.test.ts
+++ b/services/mcp/tests/unit/utils.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from 'vitest'
import { formatPrompt, sanitizeHeaderValue } from '@/lib/utils'
-import { omitResponseFields, pickResponseFields } from '@/tools/tool-utils'
+import { omitResponseFields, pickResponseFields, withPostHogUrl } from '@/tools/tool-utils'
+import type { Context } from '@/tools/types'
describe('utils', () => {
describe('formatPrompt', () => {
@@ -206,4 +207,31 @@ describe('utils', () => {
expect(obj).toEqual({ id: 1, name: 'test', extra: { nested: true } })
})
})
+
+ describe('withPostHogUrl', () => {
+ const context = {
+ stateManager: { getProjectId: async () => 42 },
+ api: { getProjectBaseUrl: (id: number) => `https://app/project/${id}` },
+ } as unknown as Context
+
+ it('adds _posthogUrl as a sibling field on an object result', async () => {
+ const result = await withPostHogUrl(context, { id: 7, name: 'x' }, '/inbox/7')
+ expect(result).toEqual({ id: 7, name: 'x', _posthogUrl: 'https://app/project/42/inbox/7' })
+ })
+
+ // Regression: spreading an array into an object (`{ ...arr }`) corrupts a raw-array
+ // list response into `{ 0: …, 1: …, _posthogUrl: … }`. Arrays must be wrapped in
+ // `{ results, _posthogUrl }` so they stay iterable for the agent.
+ it('wraps a raw array result in { results, _posthogUrl }', async () => {
+ const arr = [{ id: 1 }, { id: 2 }]
+ const result = await withPostHogUrl(context, arr, '/inbox')
+ expect(result).toEqual({ results: [{ id: 1 }, { id: 2 }], _posthogUrl: 'https://app/project/42/inbox' })
+ })
+
+ it('does not corrupt the array into numeric-keyed object fields', async () => {
+ const result = await withPostHogUrl(context, [{ id: 1 }], '/inbox')
+ expect(result).not.toHaveProperty('0')
+ expect(Array.isArray((result as { results: unknown[] }).results)).toBe(true)
+ })
+ })
})