:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): headless scout backend (3/7) (#57757)
Andrew Maguire3a922e2f1419
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex f31498160b0f..7dcedda41f4c 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -140,6 +140,7 @@ export const API_SCOPES: APIScope[] = [),},},+ { key: 'signal_scout', objectName: 'Signals agent', objectPlural: 'signals agents' },{ key: 'task', objectName: 'Task', objectPlural: 'tasks' },{ key: 'visual_review', objectName: 'Visual review', objectPlural: 'visual reviews' },{diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex d9c57d49f945..80d990fcbf72 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5398,6 +5398,7 @@ export type APIScopeObject =| 'session_recording'| 'session_recording_playlist'| 'sharing_configuration'+ | 'signal_scout'| 'subscription'| 'survey'| 'task'diff --git a/playwright/snapshots.yml b/playwright/snapshots.ymlindex d01ae6845a63..46fdd0c8816f 100644--- a/playwright/snapshots.yml+++ b/playwright/snapshots.yml@@ -3,10 +3,4 @@ config:api: https://us.posthog.comteam: '2'repo: 3d760a0a-0763-477d-89ee-f1e4e92cdd78-snapshots:- tabs-after-close-frozen-chromium-linux:- hash: v1.k794b7964.2fca90256612fb00cd9acfae8212369d7d5c55c79934d67bf585fcde88544dba.ACLl0M4x2-BDmhIal2C0rYq943n8Iw0K2RurdONJC3U- tabs-after-mouse-leave-chromium-linux:- hash: v1.k794b7964.6460c310ea022cab5db9c9e83f7a0d6befc8124219d66119740132021bd41b66.TgtCEZ70Ouqrrn29tWCZwARG38NRUwBMaxNeiqjvkWw- tabs-before-close-chromium-linux:- hash: v1.k794b7964.390a720db821713b68967fce0e58c0353a8a8b75ffc06f0fc96365231e465765.q5cxWDQCSymsGK8OwJBx9_yVMQOnD_-2XreBkTtaaqM+snapshots: {}diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex a29791e353d0..68cdc7a5951c 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -1200,6 +1200,25 @@ projects_router.register(["team_id"],)+# Signals agent HTTP surface — exposed via MCP as `signals-scout-*` tools. Reads (runs,+# memory) are public-grantable via `signal_scout:read`; writes (findings, memory+# create/delete) are sandbox-scope only via `signal_scout_internal:write`, which lives+# in `INTERNAL_API_SCOPE_OBJECTS` and so is not selectable in the personal-API-key UI.+from products.signals.backend.scout_harness.views import SignalScoutRunViewSet, SignalScratchpadViewSet # noqa: E402++projects_router.register(+ r"signals/scout/runs",+ SignalScoutRunViewSet,+ "environment_signals_scout_runs",+ ["team_id"],+)+projects_router.register(+ r"signals/scout/scratchpad",+ SignalScratchpadViewSet,+ "environment_signals_scout_scratchpad",+ ["team_id"],+)+environments_router.register(r"quick_filters",quick_filters.QuickFilterViewSet,diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 9b363e343f7d..005d653ca6cf 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -27,7 +27,7 @@ from posthog.constants import AvailableFeaturefrom posthog.exceptions import Conflict, EnterpriseFeatureException, PaidFeatureExceptionfrom posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.rbac.user_access_control import AccessControlLevel, UserAccessControl, ordered_access_levels-from posthog.scopes import APIScopeObject, APIScopeObjectOrNotSupported+from posthog.scopes import INTERNAL_API_SCOPE_OBJECTS, APIScopeObject, APIScopeObjectOrNotSupportedfrom posthog.utils import get_can_create_orgCREATE_ACTIONS = ["create", "update"]@@ -490,6 +490,19 @@ class APIScopePermission(ScopeBasePermission):self.message = "OAuth token has no scopes and cannot access this resource"return Falseelse:+ # Session (and other non-token) auth normally bypasses API-scope checks — scopes+ # are a PAK/OAuth concept; logged-in users are gated by team membership + access+ # control instead. But INTERNAL scope objects are a programmatic-only security+ # boundary (e.g. `signal_scout_internal:write`, the sandbox-only scout write scope)+ # and must be unreachable via session auth — otherwise any logged-in team member+ # could bypass the boundary (e.g. write durable scout scratchpad that is read+ # verbatim into the scout's prompt). Mirror the internal-scope guard applied to the+ # `*` wildcard below.+ session_required_scopes = self._get_required_scopes(request, view) or []+ session_required_objects = {s.split(":", 1)[0] for s in session_required_scopes}+ if not session_required_objects.isdisjoint(INTERNAL_API_SCOPE_OBJECTS):+ self.message = "This action requires a programmatic token carrying an internal scope"+ return Falsereturn Truerequired_scopes = self._get_required_scopes(request, view)@@ -502,8 +515,15 @@ class APIScopePermission(ScopeBasePermission):# `*` is the "Full access to all scopes" consent option; INTERNAL viewsets# are programmatic-only and must not be reachable via user-consented tokens.+ # Also fall through when *any* required_scope on this action targets an+ # INTERNAL_API_SCOPE_OBJECTS object (e.g. `signal_scout_internal:write` on+ # a viewset whose own `scope_object` is the public sibling like `signal_scout`).+ # Those scope objects are intentionally not selectable in the consent UI, and+ # `*` must not be a backdoor past that.scope_object = self._get_scope_object(request, view)- if "*" in key_scopes and scope_object != "INTERNAL":+ required_scope_objects = {s.split(":", 1)[0] for s in required_scopes}+ action_targets_internal = not required_scope_objects.isdisjoint(INTERNAL_API_SCOPE_OBJECTS)+ if "*" in key_scopes and scope_object != "INTERNAL" and not action_targets_internal:return Truefor required_scope in required_scopes:diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 48fc3cd1b01d..b8c411cbc0fc 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -87,6 +87,8 @@ APIScopeObject = Literal["session_recording","session_recording_playlist","sharing_configuration",+ "signal_scout",+ "signal_scout_internal","streamlit_app","subscription","survey",@@ -123,7 +125,16 @@ API_SCOPE_ACTIONS: tuple[APIScopeActions, ...] = get_args(APIScopeActions)# Scope objects minted programmatically only — never via the OAuth consent flow,# the personal-API-key UI, the CLI authorize page, or RBAC. Filtered out of# `get_scope_descriptions()` and rejected by every user-facing scope validator.-INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"clickhouse_test_cluster_perf", "query_performance"})+INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(+ {+ "clickhouse_test_cluster_perf",+ "query_performance",+ # Sandbox-only writes for the headless Signals agent (memory create/delete,+ # finding emit). Read access for the same surface lives on the public+ # `signal_scout` object so user-grantable PAKs can still inspect runs/memory.+ "signal_scout_internal",+ }+)# Scope objects available via personal API keys but never advertised through# OAuth metadata. Used for alpha / not-yet-public products where a user can@@ -194,10 +205,18 @@ def get_oauth_scopes_supported() -> list[str]:(the latter generated at build time via `bin/build-mcp-oauth-scopes.py` sothe protected resource cannot drift out of subset of the AS).- Excludes scopes in `OAUTH_HIDDEN_SCOPE_OBJECTS` so OAuth-based clients- (MCP, third-party apps) don't discover scopes intended only for manually- issued personal API keys. PAT validation uses `get_scope_descriptions()`- directly and is unaffected.+ Strict-excludes both `INTERNAL_API_SCOPE_OBJECTS` (server-mint-only scopes+ like `signal_scout_internal` — never advertised, never user-grantable) and+ `OAUTH_HIDDEN_SCOPE_OBJECTS` (PAK-only alpha scopes). PAT validation uses+ `get_scope_descriptions()` directly and is unaffected.++ The Signals scout harness sandbox token carries `signal_scout_internal:write`,+ but it is minted by directly inserting an `OAuthAccessToken` row (see+ `posthog/temporal/oauth.py:create_oauth_access_token_for_user`) and never passes+ through `/authorize`, so the scope needs neither advertising here nor a place in+ `OAUTH2_PROVIDER["SCOPES"]`. Advertising it would let any OAuth client request it+ via user consent — a durable prompt-injection vector (scratchpad rows are read+ verbatim into every subsequent run's prompt)."""visible = (f"{obj}:{action}"diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 6715fc2c66d4..9b575cc8baf8 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -761,6 +761,10 @@ OAUTH2_PROVIDER = {"email": "Access to user's email address","introspection": "Access to introspect tokens","*": "Full access to all scopes",+ # Strict-excludes INTERNAL_API_SCOPE_OBJECTS (e.g. `signal_scout_internal`) so they+ # can never be granted via the OAuth consent flow. The Signals scout harness token+ # is minted by direct DB insert (posthog/temporal/oauth.py) and never hits /authorize,+ # so it does not need to appear here.**get_scope_descriptions(),},# Block dangerous URI schemes that could be used for attacksdiff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 5c8309a6cf75..b6925ef55e11 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -12,7 +12,7 @@ ARRAY_APP_CLIENT_ID_US = "HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W"ARRAY_APP_CLIENT_ID_EU = "AIvijgMS0dxKEmr5z6odvRd8Pkh5vts3nPTzgzU9"ARRAY_APP_CLIENT_ID_DEV = "DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ"-McpScopePreset = Literal["read_only", "full"]+McpScopePreset = Literal["read_only", "full", "signals_scout"]INTERNAL_SCOPES: list[str] = [@@ -21,6 +21,16 @@ INTERNAL_SCOPES: list[str] = []+# Writes for the Signals scout harness — sandbox-only because the scope object is in+# `INTERNAL_API_SCOPE_OBJECTS` and so cannot be minted via the personal API key UI or+# granted through the OAuth consent flow. Reads use the public `signal_scout:read` scope.+# Kept OUT of the global `INTERNAL_SCOPES` so it is added ONLY for the `signals_scout`+# preset — unrelated `full`/`read_only` task tokens must never carry scout write access.+SCOUT_INTERNAL_SCOPES: list[str] = [+ "signal_scout_internal:write",+]++# Derived from posthog.scopes so the token issued to a sandboxed agent cannot# drift out of subset of what the MCP server advertises in# `services/mcp/src/lib/oauth-scopes.generated.ts` (itself generated from@@ -44,7 +54,7 @@ TOKEN_EXPIRATION_SECONDS = 60 * 60 * 6 # 6 hoursPosthogMcpScopes = McpScopePreset | list[str]-MCP_SCOPE_PRESETS = ("read_only", "full")+MCP_SCOPE_PRESETS = ("read_only", "full", "signals_scout")def resolve_scopes(scopes: PosthogMcpScopes = "read_only", *, include_internal_scopes: bool = True) -> list[str]:@@ -52,7 +62,17 @@ def resolve_scopes(scopes: PosthogMcpScopes = "read_only", *, include_internal_sif isinstance(scopes, str):if scopes == "full":resolved = [*MCP_READ_SCOPES, *MCP_WRITE_SCOPES, *internal]+ elif scopes == "signals_scout":+ # The scout sandbox: reads + the scout's own internal write scope. The internal+ # scout-write scope is added ONLY here (not via the global `INTERNAL_SCOPES`), so+ # unrelated `full`/`read_only` task tokens never carry scout write access.+ # `has_write_scopes("signals_scout")` also reports True so the MCP server doesn't+ # enable read-only mode, which would otherwise strip the agent's own internal-write+ # tools (`signal_scout_internal:write` is annotated as not-read-only).+ scout_internal = list(SCOUT_INTERNAL_SCOPES) if include_internal_scopes else []+ resolved = [*MCP_READ_SCOPES, *internal, *scout_internal]else:+ # "read_only": reads + shared internal scopes only — no scout write scope.resolved = [*MCP_READ_SCOPES, *internal]else:resolved = [*scopes, *internal]@@ -61,7 +81,12 @@ def resolve_scopes(scopes: PosthogMcpScopes = "read_only", *, include_internal_sdef has_write_scopes(scopes: PosthogMcpScopes) -> bool:if isinstance(scopes, str):- return scopes == "full"+ # `signals_scout` reports True so the MCP server doesn't enable read-only mode for+ # the harness sandbox — the agent IS allowed to call its own internal-write tools+ # (remember, forget, emit_finding) even though it has no user-facing write scopes.+ # Read-only mode is a tool-annotation filter, not a scope filter, and would strip+ # those tools categorically without this opt-out.+ return scopes in ("full", "signals_scout")return any(s in MCP_WRITE_SCOPES for s in scopes)diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 1b34a3819ac5..902e85cc2983 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -77,6 +77,7 @@ from posthog.temporal.warehouse_sources_queue_partition_management.schedule impo)from posthog.temporal.weekly_digest.types import WeeklyDigestInput+from products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedulefrom products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInputfrom ee.billing.salesforce_enrichment.constants import DEFAULT_CHUNK_SIZE@@ -608,6 +609,7 @@ schedules = [create_schedule_due_alert_checks_schedule,create_run_investigation_safety_net_schedule,create_cleanup_alert_checks_schedule,+ create_signals_scout_coordinator_schedule,]if settings.CLOUD_DEPLOYMENT:diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 48d2a0853dbe..faea3d15e996 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -245,6 +245,8 @@ class TestSignalsProductModuleIntegrity:"TeamSignalReingestionWorkflow","SignalReportDeletionWorkflow","EmitEvalSignalWorkflow",+ "RunSignalsScoutWorkflow",+ "SignalsScoutCoordinatorWorkflow",]actual_workflow_names = [w.__name__ for w in SIGNALS_PRODUCT_WORKFLOWS]assert len(actual_workflow_names) == len(expected_workflows), (@@ -295,6 +297,8 @@ class TestSignalsProductModuleIntegrity:"soft_delete_report_signals_activity","verify_match_specificity_activity","wait_for_signal_in_clickhouse_activity",+ "fetch_enabled_signals_scout_runs_activity",+ "run_signals_scout_activity",]actual_activity_names = [a.__name__ for a in SIGNALS_PRODUCT_ACTIVITIES]assert len(actual_activity_names) == len(expected_activities), (diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.pyindex 378c76a21a15..eb0702bdd49d 100644--- a/posthog/temporal/tests/test_oauth.py+++ b/posthog/temporal/tests/test_oauth.py@@ -2,7 +2,14 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.temporal.oauth import INTERNAL_SCOPES, MCP_READ_SCOPES, MCP_WRITE_SCOPES, has_write_scopes, resolve_scopes+from posthog.temporal.oauth import (+ INTERNAL_SCOPES,+ MCP_READ_SCOPES,+ MCP_WRITE_SCOPES,+ SCOUT_INTERNAL_SCOPES,+ has_write_scopes,+ resolve_scopes,+)class TestResolveScopes(SimpleTestCase):@@ -18,6 +25,23 @@ class TestResolveScopes(SimpleTestCase):result = resolve_scopes("full")assert set(result) == set(MCP_READ_SCOPES + MCP_WRITE_SCOPES + INTERNAL_SCOPES)+ def test_signals_scout_preset_adds_scout_internal_write(self) -> None:+ # `signals_scout` = `read_only` content PLUS the scout's own internal write scope.+ # No user-facing write scopes (`action:write`) leak in.+ result = resolve_scopes("signals_scout")+ assert set(result) == set(MCP_READ_SCOPES + INTERNAL_SCOPES + SCOUT_INTERNAL_SCOPES)+ assert "signal_scout_internal:write" in result+ assert "action:write" not in result++ def test_scout_internal_write_only_on_signals_scout_preset(self) -> None:+ # Isolation invariant — the scout write scope must NOT leak onto unrelated+ # task tokens. Regular tasks default to `full`; neither `full` nor `read_only`+ # may carry `signal_scout_internal:write` (only the `signals_scout` preset does).+ assert "signal_scout_internal:write" not in resolve_scopes("full")+ assert "signal_scout_internal:write" not in resolve_scopes("read_only")+ assert "signal_scout_internal:write" not in resolve_scopes(["feature_flag:read"])+ assert "signal_scout_internal:write" in resolve_scopes("signals_scout")+def test_custom_scopes(self) -> None:custom = ["feature_flag:read", "feature_flag:write"]result = resolve_scopes(custom)@@ -69,6 +93,7 @@ class TestHasWriteScopes(SimpleTestCase):[("read_only_preset", "read_only", False),("full_preset", "full", True),+ ("signals_scout_preset", "signals_scout", True),("custom_with_mcp_write", ["feature_flag:read", "feature_flag:write"], True),("custom_read_only", ["feature_flag:read", "insight:read"], False),("custom_with_non_mcp_write", ["task:write"], False),diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.pyindex 0009602317eb..67e044bd086d 100644--- a/posthog/test/test_permissions.py+++ b/posthog/test/test_permissions.py@@ -623,6 +623,51 @@ class TestOAuthAccessTokenAPIScopePermission(BaseTest):)self.assertEqual(response.status_code, 200)+ def test_forbids_wildcard_scope_for_internal_required_scope_on_public_viewset(self):+ """Regression: when a viewset's `scope_object` is public (e.g. `signal_scout`) but a+ specific action's `required_scopes` targets an INTERNAL_API_SCOPE_OBJECTS object+ (e.g. `signal_scout_internal:write`), `*` must NOT satisfy that action. Otherwise+ a user-consented `*` token could write durable scout memory or emit findings —+ bypassing the threat model that those scopes are sandbox-only.+ """+ self.access_token.scope = "*"+ self.access_token.save()+ response = self._do_request(+ f"/api/projects/{self.team.id}/signals/scout/scratchpad/forget/",+ method="POST",+ data={"key": "noop"},+ )+ self.assertEqual(response.status_code, 403)+ self.assertIn("signal_scout_internal:write", response.json()["detail"])++ def test_allows_explicit_internal_write_scope_on_public_viewset(self):+ """Sibling to the above: a token with explicit `signal_scout_internal:write` reaches+ the same endpoint (validated_data parses, the forget tool reports deleted=false)."""+ self.access_token.scope = "signal_scout_internal:write"+ self.access_token.save()+ response = self._do_request(+ f"/api/projects/{self.team.id}/signals/scout/scratchpad/forget/",+ method="POST",+ data={"key": "noop"},+ )+ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json(), {"deleted": False})++ def test_session_auth_cannot_satisfy_internal_write_scope(self):+ """Session auth must NOT bypass an internal-scope requirement. A logged-in team member+ POSTing to a scout internal-write action (`signal_scout_internal:write`) via browser+ session is denied — otherwise any member could write durable scout scratchpad, which is+ read verbatim into the scout's prompt. No bearer token here, so SessionAuthentication is+ the successful authenticator and must hit the internal-scope guard."""+ self.client.force_login(self.user)+ response = self.client.post(+ f"/api/projects/{self.team.id}/signals/scout/scratchpad/forget/",+ data={"key": "noop"},+ format="json",+ )+ self.assertEqual(response.status_code, 403)+ self.assertIn("internal scope", response.json()["detail"])+def test_allows_derived_scope_for_read(self):"""OAuth token with feature_flag:read can read feature flags"""response = self._do_request(f"/api/projects/{self.team.id}/feature_flags/")diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pyindex e7ab5ffcaf1a..a980514e1e14 100644--- a/posthog/test/test_scopes.py+++ b/posthog/test/test_scopes.py@@ -1,5 +1,7 @@from posthog.test.base import BaseTest+from django.test import SimpleTestCase+from parameterized import parameterizedfrom posthog.scopes import (@@ -7,6 +9,8 @@ from posthog.scopes import (INTERNAL_API_SCOPE_OBJECTS,OAUTH_HIDDEN_SCOPE_OBJECTS,downgrade_scopes_to_read_only,+ get_oauth_scopes_supported,+ get_scope_descriptions,)@@ -58,3 +62,68 @@ class TestDowngradeScopesToReadOnly(BaseTest):# Bare `*` alone is the OAuth full-access shorthand and must NOT pass through.self.assertNotIn(":write", downgrade_scopes_to_read_only("*"))self.assertNotEqual(downgrade_scopes_to_read_only("*"), "*")+++class TestScopeBucketInvariants(SimpleTestCase):+ def test_signal_scout_internal_is_internal(self) -> None:+ # The scout internal scope must stay in INTERNAL_API_SCOPE_OBJECTS so it is+ # strict-excluded from PAK descriptions, OAuth metadata, and the /authorize+ # allowlist. It is minted server-side only (direct OAuthAccessToken insert).+ assert "signal_scout_internal" in INTERNAL_API_SCOPE_OBJECTS+++class TestGetOAuthScopesSupported(SimpleTestCase):+ def test_signal_scout_internal_write_is_not_advertised(self) -> None:+ # Security invariant — the scout sandbox token carries `signal_scout_internal:write`+ # but is minted by direct DB insert (posthog/temporal/oauth.py), never via /authorize.+ # Advertising it in OAuth metadata would let any OAuth client request it via user+ # consent, a durable prompt-injection vector (scratchpad rows are read verbatim into+ # every subsequent run's prompt). It must NOT appear in the advertised scope set.+ assert "signal_scout_internal:write" not in get_oauth_scopes_supported()+ assert "signal_scout_internal:read" not in get_oauth_scopes_supported()++ @parameterized.expand(+ [+ ("user_interview_DO_NOT_USE:read",),+ ("user_interview_DO_NOT_USE:write",),+ ]+ )+ def test_oauth_hidden_scopes_are_not_advertised(self, scope: str) -> None:+ assert scope not in get_oauth_scopes_supported()++ def test_internal_scopes_are_not_advertised(self) -> None:+ advertised = set(get_oauth_scopes_supported())+ for obj in INTERNAL_API_SCOPE_OBJECTS:+ for action in ("read", "write"):+ assert f"{obj}:{action}" not in advertised, (+ f"{obj}:{action} is in INTERNAL_API_SCOPE_OBJECTS but is being advertised in "+ "OAuth metadata — internal scopes must never be advertised or user-grantable."+ )++ def test_oidc_scopes_are_advertised(self) -> None:+ scopes = get_oauth_scopes_supported()+ for oidc in ("openid", "profile", "email"):+ assert oidc in scopes+++class TestGetScopeDescriptions(SimpleTestCase):+ @parameterized.expand(+ [+ ("signal_scout_internal:read",),+ ("signal_scout_internal:write",),+ ]+ )+ def test_signal_scout_internal_scopes_are_not_pak_descriptions(self, scope: str) -> None:+ # Critical security invariant — PAK validation reads from `get_scope_descriptions()`+ # and must reject `signal_scout_internal` (it's a prompt-injection vector if+ # user-grantable: scratchpad rows are read verbatim into every subsequent scout+ # run's prompt).+ assert scope not in get_scope_descriptions()++ def test_all_non_internal_objects_get_pak_descriptions(self) -> None:+ descriptions = get_scope_descriptions()+ for obj in API_SCOPE_OBJECTS:+ if obj in INTERNAL_API_SCOPE_OBJECTS:+ continue+ for action in ("read", "write"):+ assert f"{obj}:{action}" in descriptionsdiff --git a/products/signals/backend/management/commands/run_signals_scout.py b/products/signals/backend/management/commands/run_signals_scout.pynew file mode 100644index 000000000000..842a59431f7b--- /dev/null+++ b/products/signals/backend/management/commands/run_signals_scout.py@@ -0,0 +1,47 @@+"""Hand-trigger one Signals agent run against a team + skill.++Used during dogfood to exercise the harness end-to-end without waiting for the+Temporal scheduler. Inserts a `SignalScoutRun` row, spawns a sandbox, polls until+the agent finishes, and prints the resulting run id and final message.+"""++from __future__ import annotations++from django.core.management.base import BaseCommand, CommandError++from products.signals.backend.scout_harness.runner import run_signals_scout+from products.signals.backend.scout_harness.skill_loader import SkillNotFoundError+++class Command(BaseCommand):+ help = "Run one Signals scout against the given team using the given skill."++ def add_arguments(self, parser):+ parser.add_argument("--team-id", type=int, required=True)+ parser.add_argument("--skill-name", required=True)+ parser.add_argument("--skill-version", type=int, default=None)+ parser.add_argument(+ "--repository",+ default=None,+ help='GitHub repository for the sandbox (e.g. "posthog/posthog"). Optional.',+ )+ parser.add_argument("--verbose", action="store_true")++ def handle(self, *args, **options):+ try:+ result = run_signals_scout(+ team_id=options["team_id"],+ skill_name=options["skill_name"],+ skill_version=options["skill_version"],+ repository=options["repository"],+ verbose=options["verbose"],+ )+ except SkillNotFoundError as exc:+ raise CommandError(str(exc))++ self.stdout.write(self.style.SUCCESS(f"Run {result.run_id} {result.status}"))+ self.stdout.write(f" skill: {result.skill_name} v{result.skill_version}")+ self.stdout.write(f" runtime: {result.runtime_s:.1f}s")+ if result.last_message:+ self.stdout.write(" message:")+ self.stdout.write(result.last_message)diff --git a/products/signals/backend/migrations/0023_signalscoutrun_summary.py b/products/signals/backend/migrations/0023_signalscoutrun_summary.pynew file mode 100644index 000000000000..d365cb8f1971--- /dev/null+++ b/products/signals/backend/migrations/0023_signalscoutrun_summary.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-05-30 13:48++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0022_add_signal_scout_models"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalscoutrun",+ name="summary",+ field=models.TextField(blank=True, db_default="", default=""),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 76c4d29802b0..7029fcc273a8 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0022_add_signal_scout_models+0023_signalscoutrun_summarydiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex abd900950842..dc552a3f3ee3 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -464,6 +464,11 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):)skill_name = models.CharField(max_length=200)skill_version = models.IntegerField()+ # One-paragraph close-out the scout writes at end-of-run via `SignalScoutRunSummary`.+ # Searchable via ILIKE on the list endpoint — the dedupe path for runs that didn't+ # emit any findings (and so left no `Signal` row to query against). Empty default+ # so historical rows and mid-run reads return a string, not NULL.+ summary = models.TextField(blank=True, default="", db_default="")created_at = models.DateTimeField(auto_now_add=True)class Meta:diff --git a/products/signals/backend/scout_harness/__init__.py b/products/signals/backend/scout_harness/__init__.pynew file mode 100644index 000000000000..ed6917f711fe--- /dev/null+++ b/products/signals/backend/scout_harness/__init__.py@@ -0,0 +1,27 @@+"""Headless Signals agent harness.++Spawns sandbox agents from an hourly Temporal coordinator, persists run rows,+and emits signals via `emit_signal()`.+"""++from products.signals.backend.scout_harness.lazy_seed import (+ CanonicalSkill,+ CanonicalSkillFile,+ CanonicalSkillParseError,+ SeedResult,+ discover_canonical_skills,+ seed_canonical_skills,+)+from products.signals.backend.scout_harness.skill_loader import LoadedSkill, SkillNotFoundError, load_skill_for_run++__all__ = [+ "CanonicalSkill",+ "CanonicalSkillFile",+ "CanonicalSkillParseError",+ "LoadedSkill",+ "SeedResult",+ "SkillNotFoundError",+ "discover_canonical_skills",+ "load_skill_for_run",+ "seed_canonical_skills",+]diff --git a/products/signals/backend/scout_harness/lazy_seed.py b/products/signals/backend/scout_harness/lazy_seed.pynew file mode 100644index 000000000000..271697513eaa--- /dev/null+++ b/products/signals/backend/scout_harness/lazy_seed.py@@ -0,0 +1,255 @@+from __future__ import annotations++import re+import logging+from dataclasses import dataclass+from pathlib import Path++from django.db import IntegrityError, transaction++import yaml++from posthog.models.team.team import Team++from products.ai_observability.backend.models.skills import LLMSkill, LLMSkillFile+from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX++logger = logging.getLogger(__name__)++# Canonical signals-scout-* skills live on disk under `products/signals/skills/` so they're+# usable both as in-repo packaged skills (consumed by `hogli build:skills` for the AI plugin+# and shipped via the dist/skills.zip release) and seeded into each team's LLMSkill namespace+# by the headless harness. Single source of truth, two distribution paths.+_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.+_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+# 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+# from this module's call sites. Keep the values in sync with skill_services.py.+_MAX_SKILL_BODY_BYTES = 1_000_000+_MAX_SKILL_FILE_BYTES = 1_000_000+_MAX_SKILL_FILE_COUNT = 50+# Matches `LLMSkillFile.path` model `max_length` — checked at parse time so an oversized+# canonical path fails with a clear error instead of a Postgres `value too long` DataError.+_MAX_SKILL_FILE_PATH_LENGTH = 500+++@dataclass(frozen=True)+class CanonicalSkillFile:+ path: str+ content: str+ content_type: str = "text/plain"+++@dataclass(frozen=True)+class CanonicalSkill:+ """A canonical `signals-scout-*` skill discovered from `products/signals/skills/`.++ `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.+ """++ name: str+ description: str+ body: str+ allowed_tools: tuple[str, ...]+ files: tuple[CanonicalSkillFile, ...]+ source_path: Path+++@dataclass(frozen=True)+class SeedResult:+ """Outcome of `seed_canonical_skills`.++ `created_skill_names` is empty when the team already had at least one signals-scout-*+ skill (the seed is a no-op in that case — edits and forks on team copies are preserved).+ """++ created_skill_names: tuple[str, ...]+ skipped_reason: str | None = None+++class CanonicalSkillParseError(ValueError):+ """A canonical SKILL.md on disk is malformed (missing frontmatter, bad YAML, etc.)."""+++def _parse_canonical_skill(skill_dir: Path) -> CanonicalSkill:+ skill_file = skill_dir / "SKILL.md"+ raw = skill_file.read_text(encoding="utf-8")+ match = _FRONTMATTER_RE.match(raw)+ if not match:+ raise CanonicalSkillParseError(f"SKILL.md missing YAML frontmatter: {skill_file}")+ try:+ frontmatter = yaml.safe_load(match.group(1))+ except yaml.YAMLError as e:+ raise CanonicalSkillParseError(f"SKILL.md frontmatter is not valid YAML: {skill_file}: {e}") from e+ if not isinstance(frontmatter, dict):+ raise CanonicalSkillParseError(f"SKILL.md frontmatter must be a mapping: {skill_file}")++ name = frontmatter.get("name")+ description = frontmatter.get("description")+ if not isinstance(name, str) or not name:+ raise CanonicalSkillParseError(f"SKILL.md frontmatter missing 'name': {skill_file}")+ if not isinstance(description, str) or not description:+ raise CanonicalSkillParseError(f"SKILL.md frontmatter missing 'description': {skill_file}")+ if not name.startswith(SIGNALS_SCOUT_SKILL_PREFIX):+ raise CanonicalSkillParseError(+ f"Canonical skill name must start with '{SIGNALS_SCOUT_SKILL_PREFIX}': got {name!r} in {skill_file}"+ )++ raw_allowed = frontmatter.get("allowed_tools", []) or []+ 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}")++ body = raw[match.end() :]+ # Enforce the same per-skill limits the REST API uses (skill_services.py). The seed+ # bypasses `create_skill_file` (no service-layer "create from scratch with files"+ # helper exists), so check at parse time — a canonical too big to seed should fail+ # loudly in CI / local seed runs, not silently exceed the documented capacity.+ if len(body.encode("utf-8")) > _MAX_SKILL_BODY_BYTES:+ raise CanonicalSkillParseError(f"SKILL.md body exceeds the {_MAX_SKILL_BODY_BYTES} byte limit: {skill_file}")++ files: list[CanonicalSkillFile] = []+ for subdir_name in _ALLOWED_BUNDLE_SUBDIRS:+ subdir = skill_dir / subdir_name+ if not subdir.is_dir():+ continue+ for file_path in sorted(subdir.rglob("*")):+ if not file_path.is_file():+ continue+ rel_path = file_path.relative_to(skill_dir).as_posix()+ if len(rel_path) > _MAX_SKILL_FILE_PATH_LENGTH:+ raise CanonicalSkillParseError(+ f"Bundled file path '{rel_path}' exceeds the {_MAX_SKILL_FILE_PATH_LENGTH} char limit: {file_path}"+ )+ try:+ content = file_path.read_text(encoding="utf-8")+ except UnicodeDecodeError as e:+ raise CanonicalSkillParseError(f"Bundled skill file is not UTF-8 text: {file_path}: {e}") from e+ if len(content.encode("utf-8")) > _MAX_SKILL_FILE_BYTES:+ raise CanonicalSkillParseError(+ f"Bundled file '{rel_path}' exceeds the {_MAX_SKILL_FILE_BYTES} byte limit: {file_path}"+ )+ files.append(CanonicalSkillFile(path=rel_path, content=content))++ if len(files) > _MAX_SKILL_FILE_COUNT:+ raise CanonicalSkillParseError(+ f"Canonical skill has {len(files)} bundled files, exceeding the {_MAX_SKILL_FILE_COUNT} limit: {skill_dir}"+ )++ return CanonicalSkill(+ name=name,+ description=description.strip(),+ body=body,+ allowed_tools=tuple(raw_allowed),+ files=tuple(files),+ source_path=skill_dir,+ )+++def discover_canonical_skills(skills_dir: Path | None = None) -> tuple[CanonicalSkill, ...]:+ """Walk `products/signals/skills/signals-scout-*/` and return the parsed manifest.++ Skipping a malformed canonical entry would mask author errors; instead we let+ `CanonicalSkillParseError` propagate so the harness fails loud and the canonical source+ gets fixed.+ """+ base = skills_dir or _SKILLS_DIR+ if not base.is_dir():+ return ()+ discovered: list[CanonicalSkill] = []+ for entry in sorted(base.iterdir()):+ if not entry.is_dir():+ continue+ if not entry.name.startswith(SIGNALS_SCOUT_SKILL_PREFIX):+ continue+ if not (entry / "SKILL.md").is_file():+ continue+ discovered.append(_parse_canonical_skill(entry))+ return tuple(discovered)+++def seed_canonical_skills(team: Team) -> SeedResult:+ """Idempotently seed canonical `signals-scout-*` skills into a team's namespace.++ No-op when the team already has any `signals-scout-*` skill (deleted or live). Edits+ and forks on team copies are preserved across calls — once a team has been seeded+ (or has authored its own row under the prefix), the canonical set never overwrites+ their content. Existence of any row under the prefix counts as "already seeded",+ including archived (`deleted=True`) rows; re-seeding archived skills would resurrect+ content the team deliberately removed.++ Concurrent calls are safe: the create path uses `transaction.atomic()` plus the model's+ unique constraint (`unique_llm_skill_latest_per_team`) to drop duplicate inserts.+ """+ existing = list(+ LLMSkill.objects.filter(team=team, name__startswith=SIGNALS_SCOUT_SKILL_PREFIX).values_list("name", flat=True)+ )+ if existing:+ return SeedResult(+ created_skill_names=(),+ skipped_reason=f"team already has {len(set(existing))} signals-scout-* skill(s)",+ )++ canonicals = discover_canonical_skills()+ if not canonicals:+ return SeedResult(created_skill_names=(), skipped_reason="no canonical signals-scout-* skills on disk")++ created: list[str] = []+ # Seed the full set in one transaction: a mid-loop failure rolls back every insert, so the+ # next run retries the whole set instead of getting wedged with a partial seed the+ # "already seeded" guard above would treat as complete.+ # Direct ORM path is intentional: there's no `create_skill_from_scratch_with_files` helper at+ # the service layer, and the universal contract limits are enforced at parse time in+ # `_parse_canonical_skill` to match the REST API.+ try:+ with transaction.atomic():+ for canonical in canonicals:+ skill = LLMSkill.objects.create(+ team=team,+ name=canonical.name,+ description=canonical.description,+ body=canonical.body,+ allowed_tools=list(canonical.allowed_tools),+ metadata={+ "seeded_by": "signals_scout_harness",+ "source": "products/signals/skills",+ },+ version=1,+ is_latest=True,+ )+ if canonical.files:+ LLMSkillFile.objects.bulk_create(+ [+ LLMSkillFile(+ skill=skill,+ path=f.path,+ content=f.content,+ content_type=f.content_type,+ )+ for f in canonical.files+ ]+ )+ created.append(canonical.name)+ except IntegrityError:+ # A concurrent caller seeded this team first; their atomic stands, ours rolls back.+ logger.info(+ "signals_scout: concurrent seed dropped, canonical skills already created",+ extra={"team_id": team.id},+ )+ return SeedResult(created_skill_names=(), skipped_reason="concurrent seed won")++ if created:+ logger.info(+ "signals_scout: seeded canonical skills",+ extra={"team_id": team.id, "skill_names": created},+ )+ return SeedResult(created_skill_names=tuple(created))diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.pynew file mode 100644index 000000000000..df2089deda94--- /dev/null+++ b/products/signals/backend/scout_harness/limits.py@@ -0,0 +1,7 @@+from __future__ import annotations++# A scout run's hard runtime cap. Enforced via the Temporal activity's+# `start_to_close_timeout` in `scout_scheduler.py` — if the agent is still going+# at this point, the activity is killed and the run row is marked failed by the+# bridge. Tuning this is a config decision, not a per-run override knob.+DEFAULT_MAX_RUNTIME_S = 30 * 60diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pynew file mode 100644index 000000000000..e74f30f3e0b9--- /dev/null+++ b/products/signals/backend/scout_harness/prompt.py@@ -0,0 +1,152 @@+from __future__ import annotations++import json+from datetime import datetime++from pydantic import BaseModel, Field++from products.signals.backend.scout_harness.skill_loader import LoadedSkill+++class SignalScoutRunSummary(BaseModel):+ """Structured close-out the scout returns at end_turn.++ Mirrors the report agent's `MultiTurnSession.start` contract: the agent emits+ a JSON object matching this schema, the harness parses it, and `summary` is+ persisted on the run row as searchable prose.+ """++ summary: str = Field(+ description=(+ "One paragraph describing what was looked at, what was found, and what "+ "was skipped. An empty findings list is a real outcome — say so plainly."+ )+ )+++_BASE_PROMPT_INTRO = """You are a Signals scout agent for PostHog.++Your job: explore this PostHog project, decide what is worth surfacing, and emit+findings via `emit_signal` so the existing Signals pipeline can group, research,+and route them to the inbox. You are *one* of several scouts running on this+project — be selective. Aim for fewer, better signals.+"""++_BASE_PROMPT_TAIL = """# How a run works++1. **Read prior context.** Call `signals-scout-runs-list` to see what+ other recent runs concluded, and `signals-scout-scratchpad-search` to+ surface durable team memories ("known noise", "already addressed", "ignore+ X"). Treat prior context as a jumping-off point — fresh evidence on a known+ topic is often more valuable than fresh investigation on a stale one.+2. **Investigate.** Use the PostHog MCP read tools to gather evidence. Most of+ what you'll need across the project is exposed via the MCP — discover what's+ available at run time. Your skill body tells you *what* to look at.+3. **Decide.** For each hypothesis, decide whether to:+ - **Emit** a finding (call `signals-scout-emit-signal`).+ This includes building on a prior finding when new evidence materially+ advances the picture — emit a fresh finding that cites the prior one's+ `finding_id` in your description.+ - **Remember** a learning so you don't redo this work next run+ (call `signals-scout-scratchpad-remember`).+ - **Skip** with a one-line note in your final summary.+4. **Close out.** End your turn by emitting a JSON object matching the schema in+ the *Output format* section below. The `summary` field is one paragraph on+ what you looked at, what you found, and what you skipped. An empty findings+ list is a real outcome on a quiet day — "looked but found nothing meaningful"+ is a genuine, useful summary, not a failure. Don't manufacture findings to+ fill space. The harness parses the JSON and writes `summary` to the run row+ as searchable prose.++# Recency lens++Default to recent windows (~last 72h) when querying — fresh evidence is usually+more actionable. Widen for slower patterns (cycles, drift, accumulation,+multi-week experiments). Your skill body may set a different default for its+domain.++# Finding schema++When you call `signals-scout-emit-signal`:++- `description` — the inbox surface and the dedupe key. Your skill body owns+ the prose contract.+- `weight` ∈ [0, 1] — your ranking score.+- `confidence` ∈ [0, 1] — your certainty.+- `evidence` — list of citations, capped at 20 entries.+- `finding_id` — a stable id for this finding, echoed into the signal for+ traceability. It does NOT dedupe: emitting the same id twice creates two+ signals, so emit each finding exactly once and never retry an emit.++# Dedupe rules++- If a recent run already covers this hypothesis with the same evidence, don't+ re-emit — attach a `remember(...)` note or skip. But if you have new evidence+ (a different source, a fresh deploy correlation, a contradicting signal),+ emit a fresh finding that cites the prior finding's id. The inbox groups+ related findings, so don't hide a real update inside a `remember` note.+- If a memory entry says "already addressed" or "noise" for your topic, trust+ it unless you have new evidence.++# Ground rules++- Don't fabricate evidence. If a tool returns nothing, say so in the summary.+- Stay in scope: emits are tied to your own run; scratchpad entries are scoped+ to this team and durable.++# Output format++Respond at end_turn with a single JSON object matching this schema:++<jsonschema>+{schema_json}+</jsonschema>+"""+++def build_run_prompt(skill: LoadedSkill, *, run_id: str, team_id: int, started_at: datetime) -> str:+ """Render the opening prompt for one scout run.++ `run_id` is the UUID of the `SignalScoutRun` row the harness inserted before+ spawning the sandbox. The agent passes it back when it calls+ `signals-scout-emit-signal` so the emit attribution stays+ pinned to this run.++ `started_at` is the run row's insertion timestamp, surfaced as informational+ context (e.g. "how long have I been running"). It is NOT a stand-in for+ current clock time in tool queries — runs can take minutes, and fresh data+ that lands during the run is exactly what we want the agent to see.++ The skill body and file manifest are NOT inlined. The agent reads them at+ run time via `llma-skill-get` / `llma-skill-file-get` over the PostHog MCP+ — the bootstrap step makes that the first move. `LoadedSkill` is still+ passed in so the harness can pin the version the agent should request.+ """+ started_at_iso = started_at.replace(microsecond=0).isoformat()+ schema_json = json.dumps(SignalScoutRunSummary.model_json_schema(), indent=2)+ tail = _BASE_PROMPT_TAIL.format(schema_json=schema_json)+ return f"""{_BASE_PROMPT_INTRO}+# Your run identity++- **run_id**: `{run_id}` — pass this when calling+ `signals-scout-emit-signal`.+- **team_id**: `{team_id}` — implicit on every MCP call.+- **skill**: `{skill.name}` (v{skill.version}) — your steering layer.+- **started_at**: `{started_at_iso}` — when this run began (UTC). Informational;+ use current clock time for queries about "now".++# First: read your skill++Your bound skill is the brain of this run. Before doing anything else, call:++ llma-skill-get(skill_name="{skill.name}", version={skill.version})++Pin to v{skill.version} explicitly — the run row, your tool resolution, and+your budget were all snapshotted against that version. Fetching by name alone+would race against any new version published mid-run.++The body tells you what to investigate, in what order, with what hypotheses.+Pull files on demand with `llma-skill-file-get` only when the body references+them. Don't start investigating before you've read it.++{tail}"""diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pynew file mode 100644index 000000000000..62837028a167--- /dev/null+++ b/products/signals/backend/scout_harness/runner.py@@ -0,0 +1,340 @@+from __future__ import annotations++import time+import asyncio+import logging+from dataclasses import dataclass+from typing import Any++from django.utils import timezone++from posthog.models.team.team import Team+from posthog.models.utils import uuid7+from posthog.sync import database_sync_to_async++from products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.scout_harness.lazy_seed import seed_canonical_skills+from products.signals.backend.scout_harness.prompt import SignalScoutRunSummary, build_run_prompt+from products.signals.backend.scout_harness.skill_loader import LoadedSkill, load_skill_for_run+from products.signals.backend.temporal.agentic import (+ SIGNALS_REPORT_RESEARCH_ENV_NAME,+ get_or_create_signals_sandbox_env,+ resolve_user_id_for_team,+)+from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun+from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext+from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession++logger = logging.getLogger(__name__)++# Reuse the report-research sandbox env. Same posture: full repo on disk, restricted+# network, MCP read scopes injected. Split out later if the agent needs different policy.+SIGNALS_SCOUT_SANDBOX_ENV_NAME = SIGNALS_REPORT_RESEARCH_ENV_NAME+++@dataclass(frozen=True)+class RunResult:+ """Outcome of a run-trigger.++ `run_id` / `task_run_id` are None when the trigger was skipped without+ persisting a row (e.g. another run for the same team/skill is still in+ flight). `status` mirrors `TaskRun.Status` values as strings so callers+ don't need to import the tasks model.+ """++ run_id: str | None+ task_run_id: str | None+ status: str | None+ last_message: str | None+ runtime_s: float+ skill_name: str+ skill_version: int+ skip_reason: str | None = None+++def run_signals_scout(+ *,+ team_id: int,+ skill_name: str,+ skill_version: int | None = None,+ repository: str | None = None,+ verbose: bool = False,+) -> RunResult:+ """Synchronous entrypoint: resolves config, spawns sandbox, persists the run row.++ Wraps the async core for callers that aren't inside an event loop (management+ command, direct script). Temporal activities call `arun_signals_scout` directly.+ """+ return asyncio.run(+ arun_signals_scout(+ team_id=team_id,+ skill_name=skill_name,+ skill_version=skill_version,+ repository=repository,+ verbose=verbose,+ )+ )+++async def arun_signals_scout(+ *,+ team_id: int,+ skill_name: str,+ skill_version: int | None = None,+ repository: str | None = None,+ verbose: bool = False,+) -> 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.+ try:+ await database_sync_to_async(seed_canonical_skills, thread_sensitive=False)(team)+ except Exception:+ logger.exception(+ "signals_scout: canonical skill seed failed; continuing with existing team skills",+ extra={"team_id": team_id},+ )+ skill = await database_sync_to_async(load_skill_for_run, thread_sensitive=False)(+ team, skill_name, version=skill_version+ )++ # 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+ # accept until a claim/lease primitive lands.+ if await database_sync_to_async(_has_running_run, thread_sensitive=False)(+ team_id=team.parent_team_id or team.id, skill_name=skill.name+ ):+ logger.info(+ "signals_scout: skipping trigger, prior run still in progress",+ extra={"team_id": team_id, "skill_name": skill.name},+ )+ return RunResult(+ run_id=None,+ task_run_id=None,+ status=None,+ last_message=None,+ runtime_s=0.0,+ skill_name=skill.name,+ skill_version=skill.version,+ skip_reason="prior run still in progress",+ )++ started = time.monotonic()+ # Pre-mint the bridge row's UUID so the prompt can reference it before the row+ # exists. The TaskRun is created inside `MultiTurnSession.start`; the bridge row is+ # inserted via its `on_task_run_created` hook — after the TaskRun exists but before+ # the agent's first turn — so first-turn finding emits can resolve the run by id.+ run_id = uuid7()+ started_at = timezone.now()+ try:+ last_message, task_run_id = await _spawn_and_run(+ team=team,+ config=config,+ run_id=run_id,+ started_at=started_at,+ skill=skill,+ repository=repository,+ verbose=verbose,+ )+ runtime_s = time.monotonic() - started+ return RunResult(+ run_id=str(run_id),+ task_run_id=task_run_id,+ status=TaskRun.Status.COMPLETED.value,+ last_message=last_message,+ runtime_s=runtime_s,+ skill_name=skill.name,+ skill_version=skill.version,+ )+ except Exception:+ runtime_s = time.monotonic() - started+ # A failure before the on_task_run_created hook fires means no row was persisted —+ # don't hand callers a run_id that resolves to nothing.+ row_persisted = await database_sync_to_async(_run_row_exists, thread_sensitive=False)(+ run_id, team.parent_team_id or team.id+ )+ # Fail safe and silent: the TaskRun MultiTurnSession spans carries the error+ # context (status=FAILED, error_message, full chat log via LLMA). Nothing+ # additional to persist on the bridge row.+ logger.exception(+ "signals_scout: run failed",+ extra={+ "team_id": team_id,+ "run_id": str(run_id),+ "skill_name": skill.name,+ "row_persisted": row_persisted,+ },+ )+ return RunResult(+ run_id=str(run_id) if row_persisted else None,+ task_run_id=None,+ status=TaskRun.Status.FAILED.value,+ last_message=None,+ runtime_s=runtime_s,+ skill_name=skill.name,+ skill_version=skill.version,+ )+++async def _spawn_and_run(+ *,+ team: Team,+ config: SignalScoutConfig,+ run_id: Any,+ started_at: Any,+ skill: LoadedSkill,+ repository: str | None,+ verbose: bool,+) -> tuple[str, str]:+ """Spawn the sandbox, create the bridge row before the first turn, run the agent.++ Returns `(last_message, task_run_id)`.+ """+ user_id = await database_sync_to_async(resolve_user_id_for_team, thread_sensitive=False)(team.id)+ sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(+ team.id,+ SIGNALS_SCOUT_SANDBOX_ENV_NAME,+ SandboxEnvironment.NetworkAccessLevel.TRUSTED,+ )+ # `repository` is None on the cadence path — v1 doesn't clone a repo into the+ # sandbox. The kwarg stays wired so the management command can still pass+ # `--repository` for ad-hoc local investigations; productionised repo access+ # is deferred (see implementation plan).+ context = CustomPromptSandboxContext(+ team_id=team.id,+ user_id=user_id,+ repository=repository,+ sandbox_environment_id=sandbox_env_id,+ # `signals_scout` is the harness's own scope posture: same scope content as+ # `read_only` (project reads + INTERNAL_SCOPES, including+ # `signal_scout_internal:write`) but reports `has_write_scopes=True` so the+ # MCP server doesn't enable read-only-mode tool filtering. Without that+ # opt-out, the MCP layer would categorically strip every tool annotated+ # `readOnlyHint: false` — including the agent's own `remember`, `forget`,+ # and `emit_finding` tools — even though the OAuth token does carry the+ # right scope to call them.+ posthog_mcp_scopes="signals_scout",+ )+ prompt = build_run_prompt(skill, run_id=str(run_id), team_id=team.id, started_at=started_at)+ logger.info(+ "signals_scout: spawning sandbox",+ extra={+ "team_id": team.id,+ "skill_name": skill.name,+ "skill_version": skill.version,+ "skill_id": skill.skill_id,+ "allowed_tools": skill.allowed_tools,+ },+ )++ async def _create_bridge_row(task_run: TaskRun) -> None:+ # Create the bridge row after the TaskRun exists but BEFORE the agent's first+ # turn runs (via MultiTurnSession's on_task_run_created hook). The scout is+ # single-turn and may call `signals-scout-emit-signal` during that first turn;+ # the emit endpoint resolves the run by id, so the row must already exist or+ # first-turn emits 404. Creating it here (not after `start()` returns) also keeps+ # the cross-link queryable mid-run and surviving both success and failure exits.+ await database_sync_to_async(_create_run_row, thread_sensitive=False)(+ run_id=run_id,+ task_run=task_run,+ team=team,+ config=config,+ skill=skill,+ )++ session, result = await MultiTurnSession.start(+ prompt=prompt,+ context=context,+ model=SignalScoutRunSummary,+ step_name=_step_name(skill),+ verbose=verbose,+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,+ on_task_run_created=_create_bridge_row,+ )+ try:+ # Persist the agent's end-of-turn close-out so non-emitting runs leave a+ # discoverable trace for future-run dedupe. Failure paths skip this on+ # purpose — the bridge row keeps its empty default and the linked TaskRun+ # carries the error context.+ await database_sync_to_async(_finalize_run_summary, thread_sensitive=False)(+ run_id=run_id,+ team_id=team.parent_team_id or team.id,+ summary=result.summary,+ )+ return result.summary, str(session.task_run.id)+ finally:+ await session.end()+++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.++ 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.+ """+ config, _ = SignalScoutConfig.objects.unscoped().get_or_create(team_id=team.parent_team_id or team.id)+ return config+++def _has_running_run(*, team_id: int, skill_name: str) -> bool:+ # Locked on (canonical team, skill_name) — different skills for the same team are+ # allowed to fan out, which is the whole point of `runs_per_tick > 1`. Status flows+ # from the linked TaskRun now that SignalScoutRun is just a bridge; treat both QUEUED+ # and IN_PROGRESS as active, since a TaskRun sits in QUEUED before transitioning and a+ # second trigger landing in that window would otherwise slip past the guard. Not keyed+ # on `scout_config_id`: configs are `on_delete=SET_NULL`, so a config delete/recreate+ # mid-run would orphan the FK and silently defeat the dedupe in exactly the+ # config-churn case it should still cover.+ return (+ SignalScoutRun.objects.unscoped()+ .filter(+ team_id=team_id,+ skill_name=skill_name,+ task_run__status__in=(TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS),+ )+ .exists()+ )+++def _create_run_row(+ *,+ run_id: Any,+ task_run: TaskRun,+ team: Team,+ config: SignalScoutConfig,+ skill: LoadedSkill,+) -> SignalScoutRun:+ return SignalScoutRun.objects.unscoped().create(+ id=run_id,+ task_run=task_run,+ team=team,+ scout_config=config,+ skill_name=skill.name,+ skill_version=skill.version,+ )+++def _run_row_exists(run_id: Any, team_id: int) -> bool:+ return SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).exists()+++def _finalize_run_summary(*, run_id: Any, team_id: int, summary: str) -> None:+ # Targeted UPDATE rather than `.save()` — the row's other fields are untouched+ # by the agent's close-out, and `update()` skips the full model refresh.+ SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).update(summary=summary)+++def _step_name(skill: LoadedSkill) -> str:+ # Surfaces in the Task title and S3 log prefix. Keep terse — the sandbox truncates.+ safe = skill.name.replace(" ", "_")[:40]+ return f"signals_scout:{safe}"diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pynew file mode 100644index 000000000000..fd275c143ae8--- /dev/null+++ b/products/signals/backend/scout_harness/serializers.py@@ -0,0 +1,247 @@+"""DRF serializers for the Signals agent harness HTTP surface.++These serializers shape the harness-internal tools (`search_recent_runs`,+`get_run`, `search_scratchpad`, `remember`, `forget`, `emit_finding`) for MCP+exposure. They mirror the dataclasses returned by the underlying functions+in `scout_harness/tools/` so the wire shape and Python shape stay in lockstep.+"""++from __future__ import annotations++from rest_framework import serializers++from posthog.schema import Severity++from products.signals.backend.scout_harness.tools.scratchpad import MAX_SCRATCHPAD_CONTENT_LENGTH++# --- Run history -----------------------------------------------------------+++class SignalScoutRunSummarySerializer(serializers.Serializer):+ """Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.++ Status and timestamps flow from the linked `tasks.TaskRun`.+ """++ run_id = serializers.CharField(help_text="UUID of the bridge row.")+ skill_name = serializers.CharField(+ help_text="Canonical skill name the run executed (e.g. `signals-scout-general`)."+ )+ skill_version = serializers.IntegerField(help_text="Skill version snapshotted at run start.")+ status = serializers.CharField(+ help_text="Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled.",+ )+ started_at = serializers.CharField(help_text="ISO-8601 timestamp the TaskRun was created.")+ completed_at = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp the TaskRun completed; null while still running.",+ )+ task_id = serializers.CharField(+ allow_null=True,+ required=False,+ help_text="UUID of the Tasks `Task` the scout span ran inside.",+ )+ task_run_id = serializers.CharField(+ allow_null=True,+ required=False,+ help_text="UUID of the Tasks `TaskRun`. Pairs with `task_id` to deep-link.",+ )+ task_url = serializers.CharField(+ allow_null=True,+ required=False,+ help_text="Relative deep-link to the Tasks UI for this run, e.g. `/project/{team_id}/tasks/{task_id}?runId={task_run_id}`.",+ )+ summary = serializers.CharField(+ allow_blank=True,+ help_text=(+ "One-paragraph close-out the scout wrote at end-of-run. Empty string for "+ "runs that errored before close-out. The dedupe key for non-emitting runs."+ ),+ )+++class SignalScoutRunDetailSerializer(SignalScoutRunSummarySerializer):+ """Full `SignalScoutRun` projection used by `get-run`. Same shape as the summary+ today; kept distinct so future detail-only extensions (linked Signal rows,+ LLMA token-cost join) can land here without bloating the list response."""+++class SearchRecentRunsQuerySerializer(serializers.Serializer):+ """Query parameters for `search-recent-runs`."""++ date_from = serializers.DateTimeField(+ required=False,+ help_text="ISO-8601 inclusive lower bound on `created_at`. Omit to skip the lower bound.",+ )+ date_to = serializers.DateTimeField(+ required=False,+ help_text=(+ "ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result "+ "cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run "+ "from the prior page)."+ ),+ )+ text = serializers.CharField(+ required=False,+ help_text="Case-insensitive substring match on the scout's end-of-run `summary`. Omit to skip the filter.",+ )+ limit = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=100,+ help_text="Max rows to return (default 20, hard cap 100).",+ )+++# --- Memory ---------------------------------------------------------------+++class ScratchpadEntrySerializer(serializers.Serializer):+ """`SignalScratchpad` projection used by `search-memory` and `remember`."""++ key = serializers.CharField(help_text="Agent-chosen semantic key, unique per team.")+ content = serializers.CharField(help_text="Prose content for prompt injection.")+ created_at = serializers.CharField(allow_null=True, help_text="ISO-8601 creation timestamp.")+ updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-write timestamp.")+ created_by_run_id = serializers.CharField(+ allow_null=True,+ help_text="Run that wrote this entry, or null if human-authored.",+ )+++class SearchMemoryQuerySerializer(serializers.Serializer):+ """Query parameters for `search-memory`."""++ text = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="ILIKE substring match against `content`. Omit to return the most recent entries.",+ )+ limit = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=100,+ help_text="Max rows to return (default 20, hard cap 100).",+ )+++class RememberRequestSerializer(serializers.Serializer):+ """Request body for `remember`."""++ key = serializers.CharField(+ max_length=300,+ help_text="Agent-chosen semantic key. Re-using a key updates the existing entry in place.",+ )+ content = serializers.CharField(+ max_length=MAX_SCRATCHPAD_CONTENT_LENGTH,+ help_text="Prose to write. Read verbatim into future prompts.",+ )+ run_id = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text=(+ "Run that authored this memory; persisted as `created_by_run_id` for lineage. "+ "Must reference a run on this same project — cross-project run UUIDs are rejected."+ ),+ )+++class ForgetRequestSerializer(serializers.Serializer):+ """Request body for `forget`."""++ key = serializers.CharField(max_length=300, help_text="Memory key to delete.")+++class ForgetResponseSerializer(serializers.Serializer):+ deleted = serializers.BooleanField(help_text="Whether a row was actually removed (false if the key didn't exist).")+++# --- Emit -----------------------------------------------------------------++# Bounds the emitted finding prose so it can't approach the Temporal activity payload ceiling.+MAX_FINDING_DESCRIPTION_LENGTH = 50_000+++class EvidenceEntrySerializer(serializers.Serializer):+ """One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`."""++ source_product = serializers.CharField(+ help_text="Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...).",+ )+ summary = serializers.CharField(help_text="One-sentence prose about why this evidence supports the finding.")+ entity_id = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Optional ID of the cited entity (issue id, recording id, log query id).",+ )+++class TimeRangeSerializer(serializers.Serializer):+ date_from = serializers.CharField(help_text="ISO-8601 inclusive lower bound for the finding's window.")+ date_to = serializers.CharField(help_text="ISO-8601 inclusive upper bound for the finding's window.")+++class EmitFindingRequestSerializer(serializers.Serializer):+ """Request body for `emit-finding`. Run attribution is taken from the URL path."""++ description = serializers.CharField(+ max_length=MAX_FINDING_DESCRIPTION_LENGTH,+ help_text="Canonical evidence-bundle prose. Becomes the signal's `description`.",+ )+ weight = serializers.FloatField(+ min_value=0.0,+ max_value=1.0,+ help_text="Agent's weight for the signal in [0, 1]. Drives ranking in the inbox.",+ )+ confidence = serializers.FloatField(+ min_value=0.0,+ max_value=1.0,+ help_text="Agent's confidence the finding is real in [0, 1]. Persisted in `extra`.",+ )+ evidence = serializers.ListField(+ child=EvidenceEntrySerializer(),+ max_length=20,+ help_text="Citations supporting the finding. Capped at 20 entries.",+ )+ hypothesis = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Optional one-line hypothesis the finding tests.",+ )+ severity = serializers.ChoiceField(+ choices=[(s.value, s.value) for s in Severity],+ required=False,+ allow_null=True,+ help_text="Optional severity tag — one of P0, P1, P2, P3, P4. Informational only.",+ )+ dedupe_keys = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Optional keys for downstream dedupe (e.g. `error_tracking_issue:<id>`).",+ )+ time_range = TimeRangeSerializer(+ required=False,+ allow_null=True,+ help_text="Optional time window the finding refers to.",+ )+ mcp_trace_id = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Optional MCP trace id for cross-system debugging.",+ )+ finding_id = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal.",+ )+++class EmitFindingResponseSerializer(serializers.Serializer):+ finding_id = serializers.CharField(help_text="Stable id for the finding (echoed back from request, or generated).")+ emitted = serializers.BooleanField(help_text="Whether `emit_signal` was actually fired.")+ skipped_reason = serializers.CharField(+ allow_null=True,+ help_text="`ai_processing_not_approved` | `source_disabled` | null when emitted normally.",+ )diff --git a/products/signals/backend/scout_harness/skill_loader.py b/products/signals/backend/scout_harness/skill_loader.pynew file mode 100644index 000000000000..a8d3a7612780--- /dev/null+++ b/products/signals/backend/scout_harness/skill_loader.py@@ -0,0 +1,69 @@+from __future__ import annotations++from dataclasses import dataclass++from posthog.models.team.team import Team++from products.ai_observability.backend.models.skills import LLMSkill, LLMSkillFile++# Naming contract for skills that steer a Signals-agent run.+SIGNALS_SCOUT_SKILL_PREFIX = "signals-scout-"+++class SkillNotFoundError(LookupError):+ """The team has no skill matching the requested name."""+++@dataclass(frozen=True)+class LoadedSkillFile:+ path: str+ content_type: str+++@dataclass(frozen=True)+class LoadedSkill:+ name: str+ # Snapshotted onto the run row so a historical run can be reproduced even after re-versioning.+ version: int+ body: str+ description: str+ # Portable skill metadata — opaque to the harness. Logged on spawn for observability,+ # not consulted at runtime. Downstream consumers (e.g. Claude Code) may read this list+ # to narrow their own tool exposure; the scout harness itself gates via+ # `posthog_mcp_scopes` at the OAuth/MCP boundary (scope-level), not tool-level.+ allowed_tools: list[str]+ files: list[LoadedSkillFile]+ skill_id: str+++def is_signals_scout_skill(skill: LLMSkill) -> bool:+ return skill.name.startswith(SIGNALS_SCOUT_SKILL_PREFIX)+++def load_skill_for_run(team: Team, skill_name: str, *, version: int | None = None) -> LoadedSkill:+ """Resolve a skill on the team's namespace and load its body + file manifest.++ Pass `version=None` to follow-latest. The `signals-scout-*` prefix is not enforced+ here — the management command can hand-trigger any skill on the team.+ """+ # Lazy import: `products.ai_observability.backend.api` triggers a temporal module load+ # that this package is itself imported from at temporal-worker boot, so a top-level+ # import here cycles. Models only is fine.+ from products.ai_observability.backend.api.skill_services import get_skill_by_name_from_db++ skill = get_skill_by_name_from_db(team, skill_name, version=version)+ if skill is None:+ raise SkillNotFoundError(+ f"No skill named '{skill_name}' found on team {team.id}"+ + (f" (version {version})" if version is not None else "")+ )+ file_rows = LLMSkillFile.objects.filter(skill=skill).only("path", "content_type").order_by("path")+ return LoadedSkill(+ name=skill.name,+ version=skill.version,+ body=skill.body,+ description=skill.description,+ allowed_tools=list(skill.allowed_tools or []),+ files=[LoadedSkillFile(path=f.path, content_type=f.content_type) for f in file_rows],+ skill_id=str(skill.id),+ )diff --git a/products/signals/backend/scout_harness/tools/__init__.py b/products/signals/backend/scout_harness/tools/__init__.pynew file mode 100644index 000000000000..e16a3ffd5988--- /dev/null+++ b/products/signals/backend/scout_harness/tools/__init__.py@@ -0,0 +1,48 @@+"""Harness-internal tools the Signals agent calls during a run.++The harness wraps these as sync Python functions; the runner / agent-SDK glue+(Phase 3e) is responsible for adapting them into the tool registry seen by the+sandbox. Each tool is team-scoped and Postgres-backed.+"""++from products.signals.backend.scout_harness.tools.emit import (+ MAX_EVIDENCE_ENTRIES,+ EmitResult,+ EvidenceEntry,+ InvalidEmitError,+ emit_finding,+)+from products.signals.backend.scout_harness.tools.runs import (+ DEFAULT_RUN_SEARCH_LIMIT,+ MAX_RUN_SEARCH_LIMIT,+ RunDetail,+ RunSummary,+ get_run,+ search_recent_runs,+)+from products.signals.backend.scout_harness.tools.scratchpad import (+ InvalidScratchpadError,+ ScratchpadEntry,+ forget,+ remember,+ search_scratchpad,+)++__all__ = [+ "DEFAULT_RUN_SEARCH_LIMIT",+ "EmitResult",+ "EvidenceEntry",+ "InvalidEmitError",+ "InvalidScratchpadError",+ "MAX_EVIDENCE_ENTRIES",+ "MAX_RUN_SEARCH_LIMIT",+ "ScratchpadEntry",+ "RunDetail",+ "RunSummary",+ "emit_finding",+ "forget",+ "get_run",+ "remember",+ "search_scratchpad",+ "search_recent_runs",+]diff --git a/products/signals/backend/scout_harness/tools/emit.py b/products/signals/backend/scout_harness/tools/emit.pynew file mode 100644index 000000000000..f8f426573661--- /dev/null+++ b/products/signals/backend/scout_harness/tools/emit.py@@ -0,0 +1,348 @@+"""Emit adapter: agent-authored findings -> emit_signal() with attribution baked in.++Each finding is forwarded to `emit_signal` with a deterministic `source_id`:+`f"run:{run.id}:finding:{finding_id}"`. This is for traceability only — it is NOT+an idempotency barrier. The downstream pipeline assigns every signal a fresh random+`document_id` and dedupes on that, never on `source_id` (which it only stores in+metadata), so a re-call with the same `finding_id` emits a *second* signal. The+previous in-postgres idempotency layer (writing to `SignalScoutRun.findings` jsonb+pre-emit, marking `emitted=True` post-success) was dropped in PR 2 review along with+the `findings` field itself; this module no longer persists any scout-side state and+provides no dedupe, so callers must not retry an emit that may have already succeeded.++Attribution (`scout_run_id`, `finding_id`, `skill_name`, `skill_version`) is read+off the run row so the agent never has to plumb it through. The `SignalsScoutSignalExtra`+shape (defined in `posthog.schema`) is what the existing `_SIGNAL_VARIANT_LOOKUP`+in `products/signals/backend/api.py` validates against.+"""++from __future__ import annotations++import uuid+import logging+from dataclasses import asdict, dataclass+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++logger = logging.getLogger(__name__)++SOURCE_PRODUCT = SignalSourceConfig.SourceProduct.SIGNALS_SCOUT.value+SOURCE_TYPE = SignalSourceConfig.SourceType.CROSS_SOURCE_ISSUE.value++# Defensive cap on evidence list length — the agent shouldn't ship hundreds of+# citations per finding. The pydantic schema accepts any length; this is a harness+# circuit breaker.+MAX_EVIDENCE_ENTRIES = 20+++class InvalidEmitError(ValueError):+ """The agent tried to emit with an invalid shape (empty description, bad weight, etc)."""+++@dataclass(frozen=True)+class EvidenceEntry:+ """One citation the agent attaches to a finding. Mirrors `SignalsScoutEvidenceEntry`."""++ source_product: str+ summary: str+ entity_id: str | None = None+++@dataclass(frozen=True)+class EmitResult:+ """Outcome of an emit_finding call.++ `skipped_reason` is set when a preflight gate prevented the external emit;+ None means the call reached `emit_signal`. There is no dedupe — a repeat call+ with the same `finding_id` emits a second signal (see the module docstring).++ Possible `skipped_reason` values:+ - None: emit fired+ - "ai_processing_not_approved": team's organization has not approved AI processing+ - "source_disabled": SignalSourceConfig disables the signals_scout source for this team+ """++ finding_id: str+ emitted: bool+ skipped_reason: str | None+++async def emit_finding(+ *,+ team: Team,+ run: SignalScoutRun,+ description: str,+ weight: float,+ confidence: float,+ evidence: list[EvidenceEntry],+ hypothesis: str | None = None,+ severity: str | None = None,+ dedupe_keys: list[str] | None = None,+ time_range: tuple[str, str] | None = None,+ mcp_trace_id: str | None = None,+ finding_id: str | None = None,+) -> EmitResult:+ """Async entry: route DB calls through `database_sync_to_async` so async callers+ (the harness runner inside Temporal) don't block the event loop.++ Same (non-idempotent) emit behavior as `emit_finding_sync`.+ """+ _assert_team_owns_run(team, run)+ _validate_inputs(description, weight, confidence, evidence)+ finding_id = finding_id or _new_finding_id()+ extra = _build_extra(+ run_id=str(run.id),+ finding_id=finding_id,+ skill_name=run.skill_name,+ skill_version=run.skill_version,+ confidence=confidence,+ evidence=evidence,+ hypothesis=hypothesis,+ severity=severity,+ dedupe_keys=dedupe_keys,+ time_range=time_range,+ mcp_trace_id=mcp_trace_id,+ )+ attempt_extra = _log_extra(+ team_id=team.id,+ run_id=str(run.id),+ finding_id=finding_id,+ skill_name=run.skill_name,+ skill_version=run.skill_version,+ weight=weight,+ confidence=confidence,+ severity=severity,+ evidence_count=len(evidence),+ )+ logger.info("signals_scout.emit: attempt", extra=attempt_extra)++ preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team)+ if preflight is not None:+ logger.warning(+ "signals_scout.emit: skipped %s",+ preflight,+ extra={**attempt_extra, "skipped_reason": preflight},+ )+ return EmitResult(finding_id=finding_id, emitted=False, skipped_reason=preflight)++ # Defer the import: products.signals.backend.api transitively imports temporal+ # workflows, which we don't want loaded at module import time inside the harness.+ from products.signals.backend.api import emit_signal++ source_id = f"run:{run.id}:finding:{finding_id}"+ await emit_signal(+ team=team,+ source_product=SOURCE_PRODUCT,+ source_type=SOURCE_TYPE,+ source_id=source_id,+ description=description,+ weight=weight,+ extra=extra,+ )+ logger.info(+ "signals_scout.emit: emitted",+ extra={**attempt_extra, "source_id": source_id},+ )+ return EmitResult(finding_id=finding_id, emitted=True, skipped_reason=None)+++def emit_finding_sync(+ *,+ team: Team,+ run: SignalScoutRun,+ description: str,+ weight: float,+ confidence: float,+ evidence: list[EvidenceEntry],+ hypothesis: str | None = None,+ severity: str | None = None,+ dedupe_keys: list[str] | None = None,+ time_range: tuple[str, str] | None = None,+ mcp_trace_id: str | None = None,+ finding_id: str | None = None,+) -> EmitResult:+ """Sync entry used by the DRF view path.++ `time_range` is a `(date_from, date_to)` tuple; the harness normalizes it into+ the `{"date_from", "date_to"}` shape that `SignalsScoutSignalExtra` expects.+ """+ from asgiref.sync import async_to_sync++ _assert_team_owns_run(team, run)+ _validate_inputs(description, weight, confidence, evidence)+ finding_id = finding_id or _new_finding_id()+ extra = _build_extra(+ run_id=str(run.id),+ finding_id=finding_id,+ skill_name=run.skill_name,+ skill_version=run.skill_version,+ confidence=confidence,+ evidence=evidence,+ hypothesis=hypothesis,+ severity=severity,+ dedupe_keys=dedupe_keys,+ time_range=time_range,+ mcp_trace_id=mcp_trace_id,+ )+ attempt_extra = _log_extra(+ team_id=team.id,+ run_id=str(run.id),+ finding_id=finding_id,+ skill_name=run.skill_name,+ skill_version=run.skill_version,+ weight=weight,+ confidence=confidence,+ severity=severity,+ evidence_count=len(evidence),+ )+ logger.info("signals_scout.emit: attempt", extra=attempt_extra)++ preflight = _preflight_emit_gates(team)+ if preflight is not None:+ logger.warning(+ "signals_scout.emit: skipped %s",+ preflight,+ extra={**attempt_extra, "skipped_reason": preflight},+ )+ return EmitResult(finding_id=finding_id, emitted=False, skipped_reason=preflight)++ from products.signals.backend.api import emit_signal++ source_id = f"run:{run.id}:finding:{finding_id}"+ async_to_sync(emit_signal)(+ team=team,+ source_product=SOURCE_PRODUCT,+ source_type=SOURCE_TYPE,+ source_id=source_id,+ description=description,+ weight=weight,+ extra=extra,+ )+ logger.info(+ "signals_scout.emit: emitted",+ extra={**attempt_extra, "source_id": source_id},+ )+ return EmitResult(finding_id=finding_id, emitted=True, skipped_reason=None)+++def _assert_team_owns_run(team: Team, run: SignalScoutRun) -> None:+ """Defense-in-depth: confirm `team` actually owns `run`.++ The view path (`SignalScoutRunViewSet.emit_signal`) already filters the run+ lookup by `team_id`, so a foreign-team `run_id` returns 404 before this+ function is reached. This guard catches a future direct caller (in-process+ MCP path, management command, ...) that bypasses that filter, rather than+ relying on every caller to pre-validate the (team, run) pair.++ Raises `RuntimeError` (not `InvalidEmitError`) because a mismatch here is a+ server-side wiring bug, not a user-input shape issue — we want a 500, not+ a 400.+ """+ if team.id != run.team_id:+ raise RuntimeError(f"emit_finding: team {team.id} does not own run {run.id} (team {run.team_id})")+++def _validate_inputs(+ description: str,+ weight: float,+ confidence: float,+ evidence: list[EvidenceEntry],+) -> None:+ if not description or not description.strip():+ raise InvalidEmitError("description must not be empty")+ if not 0.0 <= weight <= 1.0:+ raise InvalidEmitError(f"weight must be in [0.0, 1.0], got {weight}")+ if not 0.0 <= confidence <= 1.0:+ raise InvalidEmitError(f"confidence must be in [0.0, 1.0], got {confidence}")+ if len(evidence) > MAX_EVIDENCE_ENTRIES:+ raise InvalidEmitError(f"evidence has {len(evidence)} entries, max is {MAX_EVIDENCE_ENTRIES}")+++def _build_extra(+ *,+ run_id: str,+ finding_id: str,+ skill_name: str,+ skill_version: int,+ confidence: float,+ evidence: list[EvidenceEntry],+ hypothesis: str | None,+ severity: str | None,+ dedupe_keys: list[str] | None,+ time_range: tuple[str, str] | None,+ mcp_trace_id: str | None,+) -> dict[str, Any]:+ """Shape the extra payload to match `SignalsScoutSignalExtra` (extra='forbid'),+ omitting optional fields when not provided so pydantic doesn't see a `None` for+ fields that don't accept it."""+ extra: dict[str, Any] = {+ "scout_run_id": run_id,+ "finding_id": finding_id,+ "skill_name": skill_name,+ "skill_version": float(skill_version),+ "confidence": confidence,+ "evidence": [asdict(e) for e in evidence],+ }+ if hypothesis is not None:+ extra["hypothesis"] = hypothesis+ if severity is not None:+ extra["severity"] = severity+ if dedupe_keys is not None:+ extra["dedupe_keys"] = list(dedupe_keys)+ if time_range is not None:+ extra["time_range"] = {"date_from": time_range[0], "date_to": time_range[1]}+ if mcp_trace_id is not None:+ extra["mcp_trace_id"] = mcp_trace_id+ return extra+++def _new_finding_id() -> str:+ return str(uuid.uuid4())+++def _log_extra(+ *,+ team_id: int,+ run_id: str,+ finding_id: str,+ skill_name: str,+ skill_version: int,+ weight: float,+ confidence: float,+ severity: str | None,+ evidence_count: int,+) -> dict[str, Any]:+ """Structured log fields for emit-lifecycle events. Description text is+ deliberately omitted — it can carry customer-derived strings."""+ return {+ "team_id": team_id,+ "run_id": run_id,+ "finding_id": finding_id,+ "skill_name": skill_name,+ "skill_version": skill_version,+ "weight": weight,+ "confidence": confidence,+ "severity": severity,+ "evidence_count": evidence_count,+ }+++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.++ `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.+ """+ organization = team.organization+ if not organization.is_ai_data_processing_approved:+ return "ai_processing_not_approved"+ if not SignalSourceConfig.is_source_enabled(team.id, SOURCE_PRODUCT, SOURCE_TYPE):+ return "source_disabled"+ return Nonediff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pynew file mode 100644index 000000000000..6db2aac628ae--- /dev/null+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -0,0 +1,154 @@+"""Run-history tools: read access to past `SignalScoutRun` rows for the team.++These are the agent's window into what previous runs concluded. Used for best-effort+dedupe ("have I seen this hypothesis recently?") and continuity ("what was I+working on yesterday?"). Strictly team-scoped — no cross-team reads.++`SignalScoutRun` is a thin bridge to `tasks.TaskRun`: status, timestamps, and+error all flow from the linked TaskRun via `select_related("task_run")`. The+only scout-owned content on the row itself is `summary` — the one-paragraph+close-out the agent emits at end_turn, used as the dedupe key for runs that+didn't emit any findings (and so left no `Signal` row to query against).+Findings are recoverable as emitted `Signal` rows keyed by+`source_id = run:<run_id>:finding:<finding_id>`.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass+from datetime import datetime+from typing import Any++from products.signals.backend.models import SignalScoutRun++# Defensive caps so a runaway agent loop can't pull thousands of rows in one call.+DEFAULT_RUN_SEARCH_LIMIT = 20+MAX_RUN_SEARCH_LIMIT = 100+++@dataclass(frozen=True)+class RunSummary:+ """Lightweight projection of a run row — what's needed to scan and pick one."""++ run_id: str+ skill_name: str+ skill_version: int+ status: str+ started_at: str+ completed_at: str | None+ summary: str+ task_id: str | None = None+ task_run_id: str | None = None+ task_url: str | None = None++ def as_dict(self) -> dict[str, Any]:+ return asdict(self)+++@dataclass(frozen=True)+class RunDetail:+ """Full run row — call `get_run` to fetch this when a `RunSummary` looks relevant.++ Same fields as `RunSummary` today; kept distinct so future detail-only+ extensions (linked Signal rows, LLMA token-cost join) can land here without+ bloating the list projection.+ """++ run_id: str+ skill_name: str+ skill_version: int+ status: str+ started_at: str+ completed_at: str | None+ summary: str+ task_id: str | None = None+ task_run_id: str | None = None+ task_url: str | None = None++ def as_dict(self) -> dict[str, Any]:+ return asdict(self)+++def search_recent_runs(+ *,+ team_id: int,+ date_from: datetime | None = None,+ date_to: datetime | None = None,+ text: str | None = None,+ limit: int = DEFAULT_RUN_SEARCH_LIMIT,+) -> list[RunSummary]:+ """Return the most recent runs for a team, newest first.++ `date_from` / `date_to` are a half-open time window on `created_at` (the+ bridge-row insert timestamp, which fires right after `MultiTurnSession.start`)+ — `created_at >= date_from` and `created_at < date_to`. Pass `date_to` to walk+ backwards past the result cap on subsequent calls (cursor-style iteration).+ `text` is a case-insensitive substring match on the agent's end-of-run+ `summary` — the primary dedupe path for runs that didn't emit findings.+ Results are capped at `MAX_RUN_SEARCH_LIMIT`.+ """+ clamped_limit = _clamp_limit(limit)+ qs = SignalScoutRun.objects.filter(team_id=team_id).select_related("task_run").order_by("-created_at")+ if date_from is not None:+ qs = qs.filter(created_at__gte=date_from)+ if date_to is not None:+ qs = qs.filter(created_at__lt=date_to)+ if text:+ qs = qs.filter(summary__icontains=text)+ qs = qs[:clamped_limit]+ return [_to_summary(row, team_id=team_id) for row in qs]+++def get_run(*, team_id: int, run_id: str) -> RunDetail | None:+ """Fetch a single run by ID, scoped to the team. Returns None if not found.++ Team scoping is non-negotiable: a run row from another team must not be+ readable, even if the caller knows the UUID.+ """+ row = SignalScoutRun.objects.select_related("task_run").filter(team_id=team_id, id=run_id).first()+ if row is None:+ return None+ return _to_detail(row, team_id=team_id)+++def _to_summary(row: SignalScoutRun, *, team_id: int) -> RunSummary:+ task_run = row.task_run+ task_id = str(task_run.task_id) if task_run is not None else None+ task_run_id = str(task_run.id) if task_run is not None else None+ return RunSummary(+ run_id=str(row.id),+ skill_name=row.skill_name,+ skill_version=row.skill_version,+ status=task_run.status if task_run is not None else "",+ started_at=task_run.created_at.isoformat() if task_run is not None else row.created_at.isoformat(),+ completed_at=task_run.completed_at.isoformat() if task_run is not None and task_run.completed_at else None,+ summary=row.summary,+ task_id=task_id,+ task_run_id=task_run_id,+ task_url=_build_task_url(team_id=team_id, task_id=task_id, task_run_id=task_run_id),+ )+++def _to_detail(row: SignalScoutRun, *, team_id: int) -> RunDetail:+ summary = _to_summary(row, team_id=team_id)+ return RunDetail(**asdict(summary))+++def _build_task_url(*, team_id: int, task_id: str | None, task_run_id: str | None) -> str | None:+ """Build the relative Tasks UI deep-link, or None if the linkage isn't captured.++ Path shape follows the project URL convention (no host, includes `/project/{id}/`+ for the front-end router; MCP clients render it against their own host). Both+ IDs must be present — a task without a run id can't be opened on the right tab.+ """+ if not task_id or not task_run_id:+ return None+ return f"/project/{team_id}/tasks/{task_id}?runId={task_run_id}"+++def _clamp_limit(limit: int) -> int:+ if limit < 1:+ return 1+ if limit > MAX_RUN_SEARCH_LIMIT:+ return MAX_RUN_SEARCH_LIMIT+ return limitdiff --git a/products/signals/backend/scout_harness/tools/scratchpad.py b/products/signals/backend/scout_harness/tools/scratchpad.pynew file mode 100644index 000000000000..c20223f91a8d--- /dev/null+++ b/products/signals/backend/scout_harness/tools/scratchpad.py@@ -0,0 +1,153 @@+"""Durable memory tools: read/write `SignalScratchpad` entries for the team.++The scout calls `remember`/`forget` via this module. Scratchpad is the narrow+per-team memory surface — MCP-readable across agents — that other scouts and+PostHog AI can read to see what the scout fleet has learned about a team.++Simplified in PR 2 review: `tags`, `scope`, `expires_at`, and `authority` were+dropped (none were earning their keep on the stack). Retrieval is ILIKE on+`content` and `key` only; all entries are durable per-team memory.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass+from typing import Any++from django.db import IntegrityError, transaction++from products.signals.backend.models import SignalScratchpad++# Defensive cap on search results.+DEFAULT_SCRATCHPAD_SEARCH_LIMIT = 20+MAX_SCRATCHPAD_SEARCH_LIMIT = 100++# Keys/content are agent-chosen prose. Match the model's column lengths so callers+# get a clean error before hitting the DB.+MAX_SCRATCHPAD_KEY_LENGTH = 300++# `content` is an unbounded TextField read verbatim into future-run prompts — cap it so a+# runaway write can't bloat the scratchpad or a later prompt. Generous for prose.+MAX_SCRATCHPAD_CONTENT_LENGTH = 50_000+++class InvalidScratchpadError(ValueError):+ """The agent tried to write a memory with invalid shape (empty key, oversized, etc)."""+++@dataclass(frozen=True)+class ScratchpadEntry:+ key: str+ content: str+ created_at: str | None = None+ updated_at: str | None = None+ created_by_run_id: str | None = None++ def as_dict(self) -> dict[str, Any]:+ return asdict(self)+++def search_scratchpad(+ *,+ team_id: int,+ text: str | None = None,+ limit: int = DEFAULT_SCRATCHPAD_SEARCH_LIMIT,+) -> list[ScratchpadEntry]:+ """Return memories the agent should consider when planning a run.++ `text` matches ILIKE against `content` and `key`. The previous `tags` filter+ + GIN index were dropped in PR 2 review.+ """+ clamped_limit = _clamp_search_limit(limit)+ qs = SignalScratchpad.objects.filter(team_id=team_id)+ if text:+ from django.db.models import Q++ qs = qs.filter(Q(content__icontains=text) | Q(key__icontains=text))+ qs = qs.order_by("-updated_at", "-id")[:clamped_limit]+ return [_to_entry(row) for row in qs]+++def remember(+ *,+ team_id: int,+ key: str,+ content: str,+ run_id: str | None = None,+) -> ScratchpadEntry:+ """Write or update a memory entry. Idempotent on `(team, key)`.++ The previous `human_confirmed` authority guard was dropped — the human-in-the-+ loop write path was reserved-for-future and never landed. Re-add if it ships.+ """+ _validate_key_content(key, content)++ try:+ row = _upsert_entry(team_id=team_id, key=key, content=content, run_id=run_id)+ except IntegrityError:+ # Lost the create race: our SELECT saw no row, but a concurrent request+ # committed an insert for the same `(team, key)` before ours, tripping the+ # unique constraint. The row now exists, so a single retry resolves to the+ # update branch and preserves the idempotent-upsert contract.+ row = _upsert_entry(team_id=team_id, key=key, content=content, run_id=run_id)+ return _to_entry(row)+++def _upsert_entry(*, team_id: int, key: str, content: str, run_id: str | None) -> SignalScratchpad:+ with transaction.atomic():+ existing = SignalScratchpad.objects.select_for_update().filter(team_id=team_id, key=key).first()+ if existing is None:+ return SignalScratchpad.objects.create(+ team_id=team_id,+ key=key,+ content=content,+ created_by_run_id=run_id,+ )+ existing.content = content+ # Don't overwrite `created_by_run` so we keep the original creator's lineage.+ existing.save(update_fields=["content", "updated_at"])+ return existing+++def forget(*, team_id: int, key: str) -> bool:+ """Delete an entry by key. Returns whether anything was removed (False = no-op)."""+ with transaction.atomic():+ existing = SignalScratchpad.objects.select_for_update().filter(team_id=team_id, key=key).first()+ if existing is None:+ return False+ existing.delete()+ return True+++def _validate_key_content(key: str, content: str) -> None:+ if not key or not key.strip():+ raise InvalidScratchpadError("memory key must be non-empty")+ if len(key) > MAX_SCRATCHPAD_KEY_LENGTH:+ raise InvalidScratchpadError(f"memory key length {len(key)} exceeds max {MAX_SCRATCHPAD_KEY_LENGTH}")+ if not content or not content.strip():+ raise InvalidScratchpadError("memory content must be non-empty")+ if len(content) > MAX_SCRATCHPAD_CONTENT_LENGTH:+ raise InvalidScratchpadError(+ f"memory content length {len(content)} exceeds max {MAX_SCRATCHPAD_CONTENT_LENGTH}"+ )+++def _clamp_search_limit(limit: int) -> int:+ if limit < 1:+ return 1+ if limit > MAX_SCRATCHPAD_SEARCH_LIMIT:+ return MAX_SCRATCHPAD_SEARCH_LIMIT+ return limit+++def _to_entry(row: SignalScratchpad) -> ScratchpadEntry:+ # Django's FK descriptor exposes both `created_by_run` (object) and `created_by_run_id`+ # (the raw FK column). `getattr` keeps Pyright happy without a join.+ run_pk = getattr(row, "created_by_run_id", None)+ return ScratchpadEntry(+ key=row.key,+ content=row.content,+ created_at=row.created_at.isoformat() if row.created_at else None,+ updated_at=row.updated_at.isoformat() if row.updated_at else None,+ created_by_run_id=str(run_pk) if run_pk else None,+ )diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pynew file mode 100644index 000000000000..e616b61518d2--- /dev/null+++ b/products/signals/backend/scout_harness/views.py@@ -0,0 +1,363 @@+"""DRF viewsets exposing the Signals scout surface over HTTP for MCP consumption.++These wrap the sync Python tools in `scout_harness/tools/` so the headless scout+(and any other agent on the team's PostHog MCP) can call the `signals-scout-*`+tools — `runs-list`, `runs-retrieve`, `emit-signal`, `scratchpad-search`,+`scratchpad-remember`, and `scratchpad-forget` — over the standard PostHog MCP+plumbing.++Auth uses two dedicated scope objects: `signal_scout:read` is user-grantable+via the personal-API-key picker (so a team can introspect runs/scratchpad from+their own clients), while `signal_scout_internal:write` is in+`INTERNAL_API_SCOPE_OBJECTS` and so can't be granted via PAK at all — the+sandbox gets it only via `INTERNAL_SCOPES` when its OAuth token is minted.+This blocks the prompt-injection vector where a user could mint a PAK,+write to the durable scratchpad, and have the scout read it back verbatim+on its next run. Every read filters on `team_id` first; the scout's MCP+token is already pinned to the team.+"""++from __future__ import annotations++import uuid++from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import exceptions, status, viewsets+from rest_framework.decorators import action+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.mixins import validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin++# PostHog's `SessionAuthentication` (not DRF's) calls `enforce_two_factor()`.+# Authenticators are tried in order and a browser-session request authenticates on+# the first matching class, so DRF's plain `SessionAuthentication` would let a+# password-only user in a 2FA-enforced org read scout runs/scratchpad without+# completing 2FA.+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.permissions import APIScopePermission++from products.signals.backend.models import SignalScoutRun+from products.signals.backend.scout_harness.serializers import (+ EmitFindingRequestSerializer,+ EmitFindingResponseSerializer,+ EvidenceEntrySerializer,+ ForgetRequestSerializer,+ ForgetResponseSerializer,+ RememberRequestSerializer,+ ScratchpadEntrySerializer,+ SearchMemoryQuerySerializer,+ SearchRecentRunsQuerySerializer,+ SignalScoutRunDetailSerializer,+ SignalScoutRunSummarySerializer,+)+from products.signals.backend.scout_harness.tools.emit import EvidenceEntry, InvalidEmitError, emit_finding_sync+from products.signals.backend.scout_harness.tools.runs import get_run, search_recent_runs+from products.signals.backend.scout_harness.tools.scratchpad import (+ InvalidScratchpadError,+ forget,+ remember,+ search_scratchpad,+)+++def _parse_run_id_or_404(kwargs: dict) -> uuid.UUID:+ """Parse the `id` URL kwarg as a UUID; raise 404 on missing or malformed.++ DRF routes any string the default `lookup_value_regex` accepts (anything+ except `/` and `.`) into the action, so the action is responsible for+ rejecting non-UUID inputs cleanly rather than letting them surface as+ 500s from `UUIDField.to_python()` on the underlying ORM query.+ """+ raw = kwargs.get("id")+ if raw is None:+ raise exceptions.NotFound()+ try:+ return uuid.UUID(str(raw))+ except (ValueError, TypeError):+ raise exceptions.NotFound()+++def _canonical_team_id(view: TeamAndOrgViewSetMixin) -> int:+ """Canonical (parent/project) team id for scout queries.++ `view.team_id` is the raw URL team and may be a child environment, but scout+ models are `TeamScopedRootMixin` and persist under the canonical parent team+ (`RootTeamMixin.save` rewrites child writes). `TeamAndOrgViewSetMixin` already+ scopes the manager to this canonical id; passing the raw child id to the harness+ helpers adds a contradictory `team_id` predicate, so list/retrieve return+ empty/404 for legitimate rows in child-environment requests. `self.team` is a+ cached_property loaded by the permission checks, so reading `parent_team_id` is+ free. Mirrors the canonicalization in `TeamAndOrgViewSetMixin.initial`.+ """+ return view.team.parent_team_id or view.team_id+++class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Run history + finding emission for the headless agent."""++ serializer_class = SignalScoutRunSummarySerializer+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission]+ scope_object = "signal_scout"+ # `.unscoped()` bypasses the fail-closed TeamScopedManager; this class-attribute queryset+ # evaluates at module-load time (before any request → no team context). All read paths+ # in this viewset filter by `team_id` explicitly via the harness helpers, so leaving+ # this unscoped is safe. Same shape `customer_analytics.AccountViewSet` uses.+ queryset = SignalScoutRun.objects.unscoped()+ # Lookup is the run's UUID PK; DRF parses with the default `pk` URL kwarg.+ # No `lookup_value_regex` — use DRF's default and let the view actions parse+ # the raw segment with `uuid.UUID()` (via `_parse_run_id_or_404`) so malformed+ # IDs return a clean 404 rather than hitting `.filter(id=…)` with a non-UUID+ # and blowing up on Django's UUIDField conversion.+ lookup_field = "id"+ # `list` returns a raw newest-first array (capped at limit=100 by the query serializer),+ # not a paginated wrapper. Generated TS clients infer pagination from the global default+ # otherwise, and the runtime shape diverges from the OpenAPI schema. Per-action overrides+ # on POSTs (emit-signal, forget) already disable pagination at the @action level.+ pagination_class = None++ @validated_request(+ query_serializer=SearchRecentRunsQuerySerializer,+ responses={+ 200: OpenApiResponse(+ response=SignalScoutRunSummarySerializer(many=True),+ description="Recent run summaries newest-first.",+ ),+ },+ summary="Search recent agent runs",+ description=(+ "Return the most recent `SignalScoutRun` summaries for this project, newest first. "+ "Used by the headless scout to dedupe against work other runs already covered. ILIKE "+ "matches on `summary`. `date_from` / `date_to` are a half-open window on `created_at` "+ "(`>= date_from`, `< date_to`); pass `date_to` on subsequent calls to walk past the "+ "100-row cap. Results capped at 100."+ ),+ )+ def list(self, request: Request, *args, **kwargs) -> Response:+ validated = getattr(request, "validated_query_data", {}) or {}+ date_from = validated.get("date_from")+ date_to = validated.get("date_to")+ text = validated.get("text") or None+ limit = validated.get("limit") or 20+ rows = search_recent_runs(+ team_id=_canonical_team_id(self),+ date_from=date_from,+ date_to=date_to,+ text=text,+ limit=limit,+ )+ return Response(SignalScoutRunSummarySerializer([row.as_dict() for row in rows], many=True).data)++ @extend_schema(+ responses={+ 200: OpenApiResponse(response=SignalScoutRunDetailSerializer, description="Full run detail."),+ 404: OpenApiResponse(description="Run not found or not visible to this project."),+ },+ summary="Get a run by ID",+ description=(+ "Return the full `SignalScoutRun` row. Status, timing, and error flow from the linked "+ "`tasks.TaskRun`. Strictly team-scoped — a UUID belonging to another team returns 404."+ ),+ )+ def retrieve(self, request: Request, *args, **kwargs) -> Response:+ run_id = _parse_run_id_or_404(kwargs)+ detail = get_run(team_id=_canonical_team_id(self), run_id=str(run_id))+ if detail is None:+ raise exceptions.NotFound()+ return Response(SignalScoutRunDetailSerializer(detail.as_dict()).data)++ @validated_request(+ request_serializer=EmitFindingRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=EmitFindingResponseSerializer, description="Finding emitted, or skipped by a preflight gate."+ ),+ 400: OpenApiResponse(description="Invalid emit shape (description, weight, confidence, evidence cap)."),+ 404: OpenApiResponse(description="Run not found for this project."),+ },+ summary="Emit a finding for a run",+ 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 do not retry "+ "an emit that may have already succeeded."+ ),+ operation_id="signals_scout_emit_signal",+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="emit-signal",+ required_scopes=["signal_scout_internal:write"],+ pagination_class=None,+ )+ def emit_signal(self, request: Request, **kwargs) -> Response:+ run_id = _parse_run_id_or_404(kwargs)+ from products.tasks.backend.models import TaskRun++ run = (+ SignalScoutRun.objects.select_related("scout_config", "task_run")+ .filter(team_id=_canonical_team_id(self), id=run_id)+ .first()+ )+ if run is None:+ raise exceptions.NotFound()+ if run.task_run.status != TaskRun.Status.IN_PROGRESS:+ raise exceptions.ValidationError(+ {"status": f"Findings can only be emitted on in-progress runs (current: {run.task_run.status})."}+ )++ data = request.validated_data+ time_range = data.get("time_range")+ time_range_tuple: tuple[str, str] | None = None+ if time_range:+ time_range_tuple = (time_range["date_from"], time_range["date_to"])++ evidence_payload = data.get("evidence") or []+ evidence = [+ EvidenceEntry(+ source_product=entry["source_product"],+ summary=entry["summary"],+ entity_id=entry.get("entity_id"),+ )+ for entry in evidence_payload+ ]++ try:+ result = emit_finding_sync(+ team=self.team,+ run=run,+ description=data["description"],+ weight=data["weight"],+ confidence=data["confidence"],+ evidence=evidence,+ hypothesis=data.get("hypothesis") or None,+ severity=data.get("severity") or None,+ dedupe_keys=data.get("dedupe_keys") or None,+ time_range=time_range_tuple,+ mcp_trace_id=data.get("mcp_trace_id") or None,+ finding_id=data.get("finding_id") or None,+ )+ except InvalidEmitError as exc:+ raise exceptions.ValidationError({"detail": str(exc)})++ return Response(+ EmitFindingResponseSerializer(+ {+ "finding_id": result.finding_id,+ "emitted": result.emitted,+ "skipped_reason": result.skipped_reason,+ }+ ).data,+ status=status.HTTP_200_OK,+ )++ # `EvidenceEntrySerializer` is referenced for OpenAPI nested-schema discovery; keep+ # the import live so drf-spectacular registers it even if the runtime never imports+ # it directly inside this module.+ _EVIDENCE_SHAPE = EvidenceEntrySerializer+++class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Durable agent memories (`SignalScratchpad`) — read, write, and delete.++ Reads (`list`) use the public `signal_scout:read` scope by inheriting the+ viewset's `scope_object`. Writes (`create`, `forget`) elevate to the+ internal-only `signal_scout_internal:write` scope — `forget` carries it+ on its `@action`, and `create` (a built-in DRF method) gets it via the+ `dangerously_get_required_scopes` hook below.+ """++ serializer_class = ScratchpadEntrySerializer+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission]+ scope_object = "signal_scout"+ # `list` returns a raw newest-first array (capped at limit=100 by the query serializer),+ # not a paginated wrapper. See SignalScoutRunViewSet for the same rationale.+ pagination_class = None++ def dangerously_get_required_scopes(self, request: Request, view) -> list[str] | None:+ # `create` is a default DRF action so it has no `@action` decorator to set+ # `required_scopes`; without this override the permission would resolve to+ # `signal_scout:write` (user-grantable) and let any team member with a PAK+ # write durable memories. Map it to the internal scope explicitly.+ if getattr(view, "action", None) == "create":+ return ["signal_scout_internal:write"]+ return None++ @validated_request(+ query_serializer=SearchMemoryQuerySerializer,+ responses={+ 200: OpenApiResponse(+ response=ScratchpadEntrySerializer(many=True),+ description="Matching memory entries newest-first.",+ ),+ },+ summary="Search the scout scratchpad",+ description=("Return `SignalScratchpad` entries for this project. ILIKE matches on `content` and `key`."),+ operation_id="signals_scout_scratchpad_search",+ )+ def list(self, request: Request, *args, **kwargs) -> Response:+ validated = getattr(request, "validated_query_data", {}) or {}+ text = validated.get("text") or None+ limit = validated.get("limit") or 20+ rows = search_scratchpad(team_id=_canonical_team_id(self), text=text, limit=limit)+ return Response(ScratchpadEntrySerializer([row.as_dict() for row in rows], many=True).data)++ @validated_request(+ request_serializer=RememberRequestSerializer,+ responses={+ 200: OpenApiResponse(response=ScratchpadEntrySerializer, description="Memory entry written or refreshed."),+ 400: OpenApiResponse(description="Invalid memory shape (empty key/content, key too long)."),+ },+ summary="Remember a scratchpad entry",+ description=("Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place."),+ operation_id="signals_scout_scratchpad_remember",+ )+ def create(self, request: Request, *args, **kwargs) -> Response:+ data = request.validated_data+ run_id = data.get("run_id") or None+ # Verify the run is on this project before accepting cross-team lineage:+ # the agent's MCP token already pins us to a team, but `run_id` is a free+ # field on the request body and a foreign-team UUID would otherwise create+ # a cross-team `created_by_run_id` reference on this team's memory row.+ # Bad UUIDs are blocked by `UUIDField` in the serializer.+ if (+ run_id is not None+ and not SignalScoutRun.objects.filter(id=run_id, team_id=_canonical_team_id(self)).exists()+ ):+ raise exceptions.ValidationError({"run_id": "run_id does not reference a run on this project"})+ try:+ entry = remember(+ team_id=_canonical_team_id(self),+ key=data["key"],+ content=data["content"],+ run_id=str(run_id) if run_id is not None else None,+ )+ except InvalidScratchpadError as exc:+ raise exceptions.ValidationError({"detail": str(exc)})+ return Response(ScratchpadEntrySerializer(entry.as_dict()).data, status=status.HTTP_200_OK)++ @validated_request(+ request_serializer=ForgetRequestSerializer,+ responses={+ 200: OpenApiResponse(response=ForgetResponseSerializer, description="Whether a row was removed."),+ },+ summary="Forget a scratchpad entry by key",+ description="Delete an entry by key. Returns `deleted=false` if no row matched.",+ operation_id="signals_scout_scratchpad_forget",+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="forget",+ required_scopes=["signal_scout_internal:write"],+ pagination_class=None,+ )+ def forget(self, request: Request, **kwargs) -> Response:+ data = request.validated_data+ removed = forget(team_id=_canonical_team_id(self), key=data["key"])+ return Response(ForgetResponseSerializer({"deleted": removed}).data)diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.pyindex 944835237d34..8a077b28cc67 100644--- a/products/signals/backend/temporal/__init__.py+++ b/products/signals/backend/temporal/__init__.py@@ -1,4 +1,12 @@from products.signals.backend.temporal.agentic.report import run_agentic_report_activity+from products.signals.backend.temporal.agentic.scout_coordinator import (+ SignalsScoutCoordinatorWorkflow,+ fetch_enabled_signals_scout_runs_activity,+)+from products.signals.backend.temporal.agentic.scout_scheduler import (+ RunSignalsScoutWorkflow,+ run_signals_scout_activity,+)from products.signals.backend.temporal.agentic.select_repository import select_repository_activityfrom products.signals.backend.temporal.backfill_error_tracking import (BackfillErrorTrackingWorkflow,@@ -66,12 +74,15 @@ WORKFLOWS = [TeamSignalReingestionWorkflow,SignalReportDeletionWorkflow,EmitEvalSignalWorkflow,+ RunSignalsScoutWorkflow,+ SignalsScoutCoordinatorWorkflow,]ACTIVITIES = [dispatch_inbox_slack_notifications_activity,emit_backfill_signal_activity,fetch_error_tracking_issues_activity,+ fetch_enabled_signals_scout_runs_activity,assign_and_emit_signal_activity,delete_report_activity,emit_eval_signal_activity,@@ -99,6 +110,7 @@ ACTIVITIES = [restore_grouping_pause_activity,run_agentic_report_activity,run_signal_semantic_search_activity,+ run_signals_scout_activity,report_safety_judge_activity,safety_filter_activity,select_repository_activity,diff --git a/products/signals/backend/temporal/agentic/schedule.py b/products/signals/backend/temporal/agentic/schedule.pynew file mode 100644index 000000000000..9acabf72c6f1--- /dev/null+++ b/products/signals/backend/temporal/agentic/schedule.py@@ -0,0 +1,59 @@+"""Schedule registration for the headless Signals agent coordinator."""++from __future__ import annotations++from dataclasses import asdict+from datetime import timedelta++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleIntervalSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++from products.signals.backend.temporal.agentic.scout_coordinator import (+ COORDINATOR_INTERVAL_MINUTES,+ CoordinatorWorkflowInput,+)++SIGNALS_SCOUT_COORDINATOR_SCHEDULE_ID = "signals-scout-coordinator-schedule"+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.++ The coordinator runs on the existing signals task queue (currently+ `VIDEO_EXPORT_TASK_QUEUE`, shared with the rest of the signals temporal worker).+ `ScheduleOverlapPolicy.SKIP` is a defense-in-depth guard against pathologically+ slow ticks; the coordinator itself dispatches children fire-and-forget so its+ lifetime is normally seconds and overlap should never fire in practice.+ """+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ SIGNALS_SCOUT_COORDINATOR_WORKFLOW_NAME,+ asdict(CoordinatorWorkflowInput()),+ id=SIGNALS_SCOUT_COORDINATOR_SCHEDULE_ID,+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ ),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(minutes=COORDINATOR_INTERVAL_MINUTES))]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, SIGNALS_SCOUT_COORDINATOR_SCHEDULE_ID):+ await a_update_schedule(client, SIGNALS_SCOUT_COORDINATOR_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(+ client,+ SIGNALS_SCOUT_COORDINATOR_SCHEDULE_ID,+ schedule,+ trigger_immediately=False,+ )diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pynew file mode 100644index 000000000000..ea1b6e875e14--- /dev/null+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -0,0 +1,266 @@+from __future__ import annotations++import json+import random+from dataclasses import dataclass+from datetime import timedelta++import structlog+from temporalio import activity, workflow+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.sync import database_sync_to_async+from posthog.temporal.common.heartbeat import Heartbeater++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.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX+from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, RunSignalsScoutWorkflow++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).+MAX_RUNS_PER_TICK = 50++# Default schedule cadence. v1 spec: "stagger schedule, ~1 run per agent per hour".+COORDINATOR_INTERVAL_MINUTES = 60+++@dataclass+class PlannedRun:+ """One unit of fan-out: a single (team, skill) pair the coordinator will trigger."""++ team_id: int+ skill_name: str+++@dataclass+class FetchEnabledRunsInput:+ """No fields today; placeholder for future filters (team allowlist, dry-run flags)."""++ pass+++@dataclass+class FetchEnabledRunsOutput:+ planned_runs: list[PlannedRun]+++@dataclass+class CoordinatorWorkflowInput:+ """Placeholder input for forward-compat (e.g. future dry-run / debug flags)."""++ pass+++@dataclass+class CoordinatorWorkflowOutput:+ planned_count: int+ started_count: int+ skipped_count: int+++async def fetch_enabled_signals_scout_runs_activity(+ _input: FetchEnabledRunsInput,+) -> FetchEnabledRunsOutput:+ """Resolve the set of (team, skill) runs to trigger 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.+ """+ async with Heartbeater():+ planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)()+ logger.info("signals_scout coordinator: planned runs", count=len(planned))+ return FetchEnabledRunsOutput(planned_runs=planned)+++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.+ 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,+ )+ )+ if len(planned) > MAX_RUNS_PER_TICK:+ logger.warning(+ "signals_scout coordinator: sampling planned runs down to hard cap",+ planned=len(planned),+ 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.+ 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.++ `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.+ """+ available = 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++[email protected](name="run-signals-scout-coordinator")+class SignalsScoutCoordinatorWorkflow:+ """Hourly coordinator: scans enabled configs, fans out per-(team, skill) child runs.++ Dispatch is fire-and-forget: each child is started with `ParentClosePolicy.ABANDON`+ so it outlives this workflow, and the coordinator returns immediately after the+ last `start_child_workflow` call. This keeps the coordinator's lifetime to seconds+ regardless of how many children are dispatched, so the schedule's `SKIP` overlap+ policy never collapses ticks at scale. Temporal's task queue + worker concurrency+ handles the throttling — if workers are saturated, the children just queue.++ Idempotency: child workflow IDs are deterministic per `(team_id, skill_name, tick_id)`,+ so a retried coordinator can't double-launch within a single tick. A separate+ skip-if-running guard inside the runner protects against tick-over-tick collisions.+ """++ @staticmethod+ def parse_inputs(inputs: list[str]) -> CoordinatorWorkflowInput:+ if not inputs:+ return CoordinatorWorkflowInput()+ loaded = json.loads(inputs[0])+ return CoordinatorWorkflowInput(**loaded)++ @workflow.run+ async def run(self, _input: CoordinatorWorkflowInput) -> CoordinatorWorkflowOutput:+ fetch_result = await workflow.execute_activity(+ fetch_enabled_signals_scout_runs_activity,+ FetchEnabledRunsInput(),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ planned_runs = fetch_result.planned_runs+ if not planned_runs:+ 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+ # 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+ # `run_id` changes on retry), so the deterministic child ids below + REJECT_DUPLICATE+ # dedupe a retry without re-launching. `run_id` would break that: a retry would mint+ # new child ids and double-launch.+ tick_id = workflow.info().workflow_id+ started = 0+ skipped = 0+ for idx, planned in enumerate(planned_runs):+ if await _start_child(planned=planned, tick_id=tick_id, idx=idx):+ started += 1+ else:+ skipped += 1+ return CoordinatorWorkflowOutput(+ planned_count=len(planned_runs),+ started_count=started,+ skipped_count=skipped,+ )+++async def _start_child(*, planned: PlannedRun, tick_id: str, idx: int) -> bool:+ """Fire-and-forget child dispatch. Returns True if started, False if dedupe-skipped.++ `REJECT_DUPLICATE` makes a re-dispatch of an already-started child for the same+ deterministic `(team, skill, tick, idx)` id raise `WorkflowAlreadyStartedError`+ whether that prior child is still running OR already closed — so a coordinator+ retry/replay within the same tick skips it instead of re-running it (`ALLOW_DUPLICATE`+ would re-launch a child that finished before the retry, double-running that team for+ the tick). Any other exception bubbles up: the coordinator's `RetryPolicy` re-dispatches+ idempotently because workflow IDs are deterministic.+ """+ child_id = _child_workflow_id(planned, tick_id, idx)+ try:+ await workflow.start_child_workflow(+ RunSignalsScoutWorkflow.run,+ RunSignalsScoutInput(+ team_id=planned.team_id,+ skill_name=planned.skill_name,+ ),+ id=child_id,+ id_reuse_policy=WorkflowIDReusePolicy.REJECT_DUPLICATE,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ )+ return True+ except WorkflowAlreadyStartedError:+ workflow.logger.info(+ "signals_scout coordinator: child already running, skipping",+ team_id=planned.team_id,+ skill_name=planned.skill_name,+ child_id=child_id,+ )+ return False+++def _child_workflow_id(planned: PlannedRun, tick_id: str, idx: int) -> str:+ # Tick_id makes the ID unique across coordinator runs; idx disambiguates if a team+ # somehow ends up with the same skill twice in a tick (defense-in-depth — the+ # planning step already dedupes via sorted unique).+ safe_skill = planned.skill_name.replace(" ", "_")[:60]+ return f"signals-scout-run-{planned.team_id}-{safe_skill}-{tick_id}-{idx}"diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.pynew file mode 100644index 000000000000..aad7efb56021--- /dev/null+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py@@ -0,0 +1,100 @@+from __future__ import annotations++from dataclasses import dataclass+from datetime import timedelta++import structlog+import temporalio+from temporalio.common import RetryPolicy++from posthog.temporal.common.heartbeat import Heartbeater++from products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S+from products.signals.backend.scout_harness.runner import RunResult, arun_signals_scout++logger = structlog.get_logger(__name__)++# Hard activity timeout = budget runtime + slack so heartbeat-based failures surface+# before Temporal's own timeout fires.+_ACTIVITY_SLACK_S = 60+++@dataclass+class RunSignalsScoutInput:+ team_id: int+ skill_name: str+ skill_version: int | None = None+ repository: str | None = None+++@dataclass+class RunSignalsScoutOutput:+ run_id: str | None+ task_run_id: str | None+ status: str | None+ runtime_s: float+ skill_name: str+ skill_version: int+ skip_reason: str | None = None+++def _to_output(result: RunResult) -> RunSignalsScoutOutput:+ return RunSignalsScoutOutput(+ run_id=result.run_id,+ task_run_id=result.task_run_id,+ status=result.status,+ runtime_s=result.runtime_s,+ skill_name=result.skill_name,+ skill_version=result.skill_version,+ skip_reason=result.skip_reason,+ )+++async def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsScoutOutput:+ """One scheduled scout run for a (team, skill) pair.++ The activity itself never raises — failures are persisted on the run row and the+ workflow sees a `status='failed'` outcome. This matches the spec's "fail safe and+ silent" rule: a bad run does not retry blindly.+ """+ async with Heartbeater():+ result = await arun_signals_scout(+ team_id=input.team_id,+ skill_name=input.skill_name,+ skill_version=input.skill_version,+ repository=input.repository,+ )+ logger.info(+ "signals_scout activity finished",+ team_id=input.team_id,+ skill_name=input.skill_name,+ run_id=result.run_id,+ status=result.status,+ runtime_s=result.runtime_s,+ skip_reason=result.skip_reason,+ )+ return _to_output(result)+++class RunSignalsScoutWorkflow:+ """Drives one scheduled scout run.++ The activity owns the run-row lifecycle (insert/update). The workflow's job is just+ to spawn the activity with the right timeout and retry posture, and surface the+ outcome to the scheduler.+ """++ @temporalio.workflow.run+ async def run(self, input: RunSignalsScoutInput) -> RunSignalsScoutOutput:+ return await temporalio.workflow.execute_activity(+ run_signals_scout_activity,+ input,+ start_to_close_timeout=timedelta(seconds=DEFAULT_MAX_RUNTIME_S + _ACTIVITY_SLACK_S),+ heartbeat_timeout=timedelta(minutes=2),+ # No retries: failures are persisted as `status='failed'` on the run row and+ # we don't want a bad skill / prompt to spin retry loops. The next scheduled+ # tick will try again.+ retry_policy=RetryPolicy(maximum_attempts=1),+ )diff --git a/products/signals/backend/test/conftest.py b/products/signals/backend/test/conftest.pynew file mode 100644index 000000000000..2afcb8a9d392--- /dev/null+++ b/products/signals/backend/test/conftest.py@@ -0,0 +1,32 @@+"""Test-suite fixtures for the signals backend.++`_scout_team_scope` auto-wraps every test that has a `self.team` (i.e. is built+on `BaseTest`/`APIBaseTest`) in `team_scope(self.team.id)`. The scout models+(`SignalScoutConfig`, `SignalScoutRun`, `SignalScratchpad`) use+`TeamScopedRootMixin`, so their default `.objects` manager is fail-closed and+raises `TeamScopeError` when called outside a team context. Test setUp / body+code that does `Model.objects.create(...)` directly (without going through a+DRF request that sets context via `TeamAndOrgViewSetMixin.initial`) would+otherwise need an explicit `with team_scope(...)` wrapper everywhere.++The fixture is a no-op for tests that don't have a `team` attribute (pure unit+tests, async harness tests with their own setup) — those keep working unchanged.+The fixture is also harmless for non-scout tests in this directory: the older+`Signal*` models don't read the ContextVar.+"""++from __future__ import annotations++import pytest++from posthog.models.scoping import team_scope++[email protected](autouse=True)+def _scout_team_scope(request: pytest.FixtureRequest):+ instance = getattr(request, "instance", None)+ if instance is None or not hasattr(instance, "team") or instance.team is None:+ yield+ return+ with team_scope(instance.team.id):+ yielddiff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pynew file mode 100644index 000000000000..c602eb884368--- /dev/null+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -0,0 +1,289 @@+from __future__ import annotations++import random++import pytest+from unittest.mock import AsyncMock, patch++import pytest_asyncio+from asgiref.sync import sync_to_async+from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.testing import ActivityEnvironment++from posthog.models import Organization, Team+from posthog.models.scoping import team_scope+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.temporal.agentic.scout_coordinator import (+ MAX_RUNS_PER_TICK,+ CoordinatorWorkflowInput,+ CoordinatorWorkflowOutput,+ FetchEnabledRunsInput,+ PlannedRun,+ SignalsScoutCoordinatorWorkflow,+ fetch_enabled_signals_scout_runs_activity,+)+++@pytest_asyncio.fixture+async def aorganization():+ organization = await sync_to_async(Organization.objects.create)(+ name=f"SignalsCoordinatorTestOrg-{random.randint(1, 99999)}",+ is_ai_data_processing_approved=True,+ )+ yield organization+ await sync_to_async(organization.delete)()+++@pytest_asyncio.fixture+async def ateam(aorganization):+ team = await sync_to_async(Team.objects.create)(+ organization=aorganization,+ name=f"SignalsCoordinatorTestTeam-{random.randint(1, 99999)}",+ )+ # 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).+ with team_scope(team.id, canonical=True):+ yield team+ 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.+ team = await sync_to_async(Team.objects.create)(+ organization=aorganization,+ name=f"SignalsCoordinatorOtherTeam-{random.randint(1, 99999)}",+ )+ yield team+ await sync_to_async(team.delete)()+++def _create_skill(team: Team, name: str) -> LLMSkill:+ return LLMSkill.objects.create(team=team, name=name, description="d", body="b")+++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)+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")++ env = ActivityEnvironment()+ output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())++ assert output.planned_runs == []+++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)+ 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_skill)(ateam, "custom-helper")++ env = ActivityEnvironment()+ output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())++ 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)+++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"],+ )+ 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 [p.skill_name for p in output.planned_runs] == ["signals-scout-errors"]+++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")++ env = ActivityEnvironment()+ output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())++ 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"),+ }+++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 == []++ env = ActivityEnvironment()+ output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())++ 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)+++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.+ 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())++ # 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)+++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}")++ env = ActivityEnvironment()+ output = await env.run(fetch_enabled_signals_scout_runs_activity, FetchEnabledRunsInput())++ assert len(output.planned_runs) == MAX_RUNS_PER_TICK+++# ── Workflow-level tests ────────────────────────────────────────────────────────+#+# 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.+++async def test_workflow_returns_zero_counts_when_no_planned_runs():+ coordinator = SignalsScoutCoordinatorWorkflow()+ fake_fetch_result = type("R", (), {"planned_runs": []})()++ with patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",+ new_callable=AsyncMock,+ return_value=fake_fetch_result,+ ):+ output = await coordinator.run(CoordinatorWorkflowInput())++ assert output == CoordinatorWorkflowOutput(0, 0, 0)+++async def test_workflow_dispatches_children_fire_and_forget():+ planned = [+ PlannedRun(team_id=1, skill_name="signals-scout-a"),+ PlannedRun(team_id=1, skill_name="signals-scout-b"),+ PlannedRun(team_id=2, skill_name="signals-scout-c"),+ ]+ fake_fetch_result = type("R", (), {"planned_runs": planned})()++ # Second dispatch raises WorkflowAlreadyStartedError → counted as skipped, others as started.+ dispatch_outcomes: list[BaseException | None] = [+ None,+ WorkflowAlreadyStartedError("dup", "signals-scout-run-1-signals-scout-b-tick-1-1"),+ None,+ ]+ dispatch_calls: list[tuple[int, str]] = []++ async def fake_start_child(_workflow_run, run_input, **kwargs):+ idx = len(dispatch_calls)+ dispatch_calls.append((run_input.team_id, run_input.skill_name))+ outcome = dispatch_outcomes[idx]+ if isinstance(outcome, BaseException):+ raise outcome+ return AsyncMock()++ coordinator = SignalsScoutCoordinatorWorkflow()+ with (+ patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",+ new_callable=AsyncMock,+ return_value=fake_fetch_result,+ ),+ patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.info",+ return_value=type("Info", (), {"workflow_id": "tick-1"})(),+ ),+ patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.logger",+ ),+ patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.start_child_workflow",+ side_effect=fake_start_child,+ ),+ ):+ output = await coordinator.run(CoordinatorWorkflowInput())++ 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"),+ (2, "signals-scout-c"),+ ]diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pynew file mode 100644index 000000000000..60c54d238cbe--- /dev/null+++ b/products/signals/backend/test/test_scout_harness.py@@ -0,0 +1,433 @@+from __future__ import annotations++import random+from datetime import UTC, datetime++import pytest+from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, patch++import pytest_asyncio+from asgiref.sync import sync_to_async+from temporalio.testing import ActivityEnvironment++from posthog.models import Organization, Team+from posthog.models.scoping import team_scope+from posthog.sync import database_sync_to_async++from products.ai_observability.backend.models.skills import LLMSkill, LLMSkillFile+from products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.scout_harness.prompt import build_run_prompt+from products.signals.backend.scout_harness.runner import RunResult, arun_signals_scout+from products.signals.backend.scout_harness.skill_loader import (+ SkillNotFoundError,+ is_signals_scout_skill,+ load_skill_for_run,+)+from products.signals.backend.scout_harness.tools.runs import _build_task_url, _to_detail, _to_summary+from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, run_signals_scout_activity+from products.tasks.backend.models import Task, TaskRun+++@pytest_asyncio.fixture+async def aorganization():+ organization = await sync_to_async(Organization.objects.create)(+ name=f"SignalsScoutTestOrg-{random.randint(1, 99999)}",+ is_ai_data_processing_approved=True,+ )+ yield organization+ await sync_to_async(organization.delete)()+++@pytest_asyncio.fixture+async def ateam(aorganization):+ team = await sync_to_async(Team.objects.create)(+ organization=aorganization,+ name=f"SignalsScoutTestTeam-{random.randint(1, 99999)}",+ )+ # Yield inside team_scope so dependent fixtures and test bodies have a team+ # context for the TeamScopedRootMixin-backed scout models.+ # `canonical=True` skips the sync DB resolution lookup (illegal from async).+ with team_scope(team.id, canonical=True):+ yield team+ await sync_to_async(team.delete)()+++@pytest_asyncio.fixture+async def aerrors_skill(ateam):+ skill = await sync_to_async(LLMSkill.objects.create)(+ team=ateam,+ name="signals-scout-errors",+ description="Errors scout",+ body="scout",+ )+ yield skill+++def _make_task_run(team: Team) -> TaskRun:+ """Minimal Task + TaskRun pair scoped to the given team."""+ task = Task.objects.create(+ team=team,+ title="scout run",+ description="scout run",+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,+ )+ return TaskRun.objects.create(task=task, team=team)+++class TestSkillLoader(BaseTest):+ def _create_skill(self, name: str, *, body: str = "skill body", file_paths: list[str] | None = None) -> LLMSkill:+ skill = LLMSkill.objects.create(+ team=self.team,+ name=name,+ description="A test skill",+ body=body,+ allowed_tools=["search_recent_runs", "remember"],+ )+ for path in file_paths or []:+ LLMSkillFile.objects.create(skill=skill, path=path, content=f"# {path}", content_type="text/plain")+ return skill++ def test_loads_latest_version_by_default(self) -> None:+ self._create_skill("signals-scout-errors", body="v1 body")+ loaded = load_skill_for_run(self.team, "signals-scout-errors")+ assert loaded.name == "signals-scout-errors"+ assert loaded.version == 1+ assert loaded.body == "v1 body"+ assert loaded.allowed_tools == ["search_recent_runs", "remember"]++ def test_loads_file_manifest_alongside_body(self) -> None:+ self._create_skill(+ "signals-scout-errors",+ file_paths=["references/playbook.md", "references/examples.md"],+ )+ loaded = load_skill_for_run(self.team, "signals-scout-errors")+ # Files come back sorted by path so the manifest is stable.+ assert [f.path for f in loaded.files] == [+ "references/examples.md",+ "references/playbook.md",+ ]++ def test_missing_skill_raises(self) -> None:+ with pytest.raises(SkillNotFoundError):+ load_skill_for_run(self.team, "signals-scout-does-not-exist")++ def test_signals_scout_prefix_check(self) -> None:+ match = self._create_skill("signals-scout-errors")+ non_match = self._create_skill("custom-research-helper")+ assert is_signals_scout_skill(match) is True+ assert is_signals_scout_skill(non_match) is False+++class TestPromptBuilder(BaseTest):+ def test_renders_identity_bootstrap_and_universal_sections(self) -> None:+ skill = LLMSkill.objects.create(+ team=self.team,+ name="signals-scout-errors",+ description="Errors scout",+ body="watch for spikes",+ )+ LLMSkillFile.objects.create(skill=skill, path="refs/playbook.md", content="x", content_type="text/plain")+ loaded = load_skill_for_run(self.team, "signals-scout-errors")+ started_at = datetime(2026, 5, 1, 12, 34, 56, tzinfo=UTC)+ prompt = build_run_prompt(+ loaded,+ run_id="00000000-0000-0000-0000-000000000abc",+ team_id=self.team.id,+ started_at=started_at,+ )+ # Identity carries the skill name + version so bootstrap can reference it.+ assert "signals-scout-errors" in prompt+ assert "(v1)" in prompt+ # The agent needs to know its own run id to attribute emits and memories.+ assert "00000000-0000-0000-0000-000000000abc" in prompt+ # Bootstrap section directs the agent to read the skill via MCP, not+ # from the prompt. Skill body + file manifest are deliberately NOT+ # inlined — they're discovered at run time.+ assert "First: read your skill" in prompt+ # Skill version is pinned explicitly — the run row + tool resolution + budget+ # were snapshotted against v1, so the bootstrap fetch must lock to v1 too.+ assert 'llma-skill-get(skill_name="signals-scout-errors", version=1)' in prompt+ assert "llma-skill-file-get" in prompt+ assert "watch for spikes" not in prompt+ assert "refs/playbook.md" not in prompt+ # The base prompt teaches the agent to call the harness MCP tools by name.+ assert "signals-scout-emit-signal" in prompt+ assert "signals-scout-scratchpad-search" in prompt+ # Recency lens references the started_at anchor.+ assert "Recency lens" in prompt+ assert "2026-05-01T12:34:56+00:00" in prompt+++# Orchestration tests run as plain pytest functions because the async runner uses+# `database_sync_to_async`, which requires the test team to be visible across threads.+# The fixture-based pattern (matching test_agentic_report_activity.py) gives us that.+++def _make_fake_session(team: Team, summary_text: str = "ok") -> tuple[MagicMock, object]:+ """Build a (session, summary_result) pair to return from `MultiTurnSession.start`.++ The session must carry a saved `task_run` so the bridge insert succeeds+ (FK requirement) and the runner's `session.task_run.id` access works.+ """+ task_run = _make_task_run(team)+ session = MagicMock()+ session.task_run = task_run+ session.end = AsyncMock()+ result = MagicMock()+ result.summary = summary_text+ return session, result+++def _fake_start_invoking_hook(session: MagicMock, result: object):+ """Stand-in for `MultiTurnSession.start` that fires the `on_task_run_created` hook.++ The real `start` awaits the hook (creating the SignalScoutRun bridge row) after the+ TaskRun exists but before the first agent turn. A plain `return_value` mock would skip+ that, so the bridge row would never be created — mirror the real contract here.+ """++ async def _start(*args, on_task_run_created=None, **kwargs):+ if on_task_run_created is not None:+ await on_task_run_created(session.task_run)+ return session, result++ return _start+++async def test_successful_run_creates_bridge_row_pointing_at_task_run(ateam, aerrors_skill):+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(+ ateam, "I would investigate /checkout 500s next."+ )++ with patch(+ "products.signals.backend.scout_harness.runner.MultiTurnSession.start",+ new=_fake_start_invoking_hook(session, result),+ ):+ # `_spawn_and_run` reaches for sandbox env + user-id resolution; stub the helpers.+ with (+ patch(+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",+ return_value="env-id",+ ),+ patch(+ "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",+ return_value=42,+ ),+ ):+ run_result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ assert run_result.status == TaskRun.Status.COMPLETED.value+ assert run_result.skill_name == "signals-scout-errors"+ assert run_result.skill_version == 1+ assert run_result.last_message and "checkout" in run_result.last_message+ assert run_result.task_run_id == str(session.task_run.id)++ bridge = await database_sync_to_async(SignalScoutRun.objects.select_related("task_run", "scout_config").get)(+ id=run_result.run_id+ )+ assert str(bridge.task_run_id) == str(session.task_run.id)+ assert bridge.skill_name == "signals-scout-errors"+ assert bridge.skill_version == 1+ # 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+ assert bridge.scout_config_id == config.id+++async def test_failed_run_returns_failed_outcome_and_skips_bridge_insert(ateam, aerrors_skill):+ # Failure inside MultiTurnSession.start means we never get a session.task_run+ # to bridge to — the runner's except path returns FAILED without persisting.+ with (+ patch(+ "products.signals.backend.scout_harness.runner.MultiTurnSession.start",+ new_callable=AsyncMock,+ side_effect=RuntimeError("sandbox refused to start"),+ ),+ patch(+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",+ return_value="env-id",+ ),+ patch(+ "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",+ return_value=42,+ ),+ ):+ run_result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ assert run_result.status == TaskRun.Status.FAILED.value+ assert run_result.last_message is None+ # No bridge row persisted on the failure path (TaskRun was never created).+ has_runs = await database_sync_to_async(SignalScoutRun.objects.filter(team=ateam).exists)()+ assert not has_runs+++async def test_missing_skill_does_not_create_run_row(ateam):+ with pytest.raises(SkillNotFoundError):+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-missing")+ has_runs = await database_sync_to_async(SignalScoutRun.objects.filter(team=ateam).exists)()+ assert not has_runs+++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)+ 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)+ await database_sync_to_async(SignalScoutRun.objects.create)(+ task_run=task_run,+ team=ateam,+ scout_config=config,+ skill_name="signals-scout-errors",+ skill_version=1,+ )++ with patch(+ "products.signals.backend.scout_harness.runner.MultiTurnSession.start",+ new_callable=AsyncMock,+ side_effect=AssertionError("session.start should not run while a prior run is IN_PROGRESS"),+ ):+ result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ assert result.run_id is None+ assert result.status is None+ assert result.skip_reason is not None+ count = await database_sync_to_async(SignalScoutRun.objects.filter(team=ateam).count)()+ assert count == 1+++async def test_activity_returns_completed_outcome(ateam):+ async def fake_arun(**_kwargs):+ return RunResult(+ run_id="abc",+ task_run_id="def",+ status=TaskRun.Status.COMPLETED.value,+ last_message="ok",+ runtime_s=1.5,+ skill_name="signals-scout-errors",+ skill_version=2,+ )++ with patch(+ "products.signals.backend.temporal.agentic.scout_scheduler.arun_signals_scout",+ side_effect=fake_arun,+ ):+ env = ActivityEnvironment()+ output = await env.run(+ run_signals_scout_activity,+ RunSignalsScoutInput(team_id=ateam.id, skill_name="signals-scout-errors"),+ )++ assert output.run_id == "abc"+ assert output.task_run_id == "def"+ assert output.status == "completed"+ assert output.skill_version == 2+ assert output.skip_reason is None+++async def test_activity_returns_skip_outcome_when_already_running(ateam):+ async def fake_arun(**_kwargs):+ return RunResult(+ run_id=None,+ task_run_id=None,+ status=None,+ last_message=None,+ runtime_s=0.0,+ skill_name="signals-scout-errors",+ skill_version=1,+ skip_reason="prior run still in progress",+ )++ with patch(+ "products.signals.backend.temporal.agentic.scout_scheduler.arun_signals_scout",+ side_effect=fake_arun,+ ):+ env = ActivityEnvironment()+ output = await env.run(+ run_signals_scout_activity,+ RunSignalsScoutInput(team_id=ateam.id, skill_name="signals-scout-errors"),+ )++ assert output.run_id is None+ assert output.task_run_id is None+ assert output.status is None+ assert output.skip_reason is not None+++# ── Tasks-UI cross-link: SignalScoutRun ─→ TaskRun ────────────────────────────+#+# Status, timestamps, and the task-id pair all live on the linked `TaskRun` now.+# The summary/detail projections join through it; `_build_task_url` produces the+# deep-link from the team + task ids.+++def test_build_task_url_renders_relative_path_when_both_ids_present():+ url = _build_task_url(+ team_id=42,+ task_id="aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",+ task_run_id="bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",+ )+ assert url == "/project/42/tasks/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa?runId=bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"+++ "task_id,task_run_id",+ [+ (None, None),+ ("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", None),+ (None, "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),+ ],+)+def test_build_task_url_returns_none_when_either_id_missing(task_id, task_run_id):+ # Cross-link only renders when both halves are captured — a half-link can't+ # reliably open the right tab in the Tasks UI, so we'd rather emit null and+ # let callers handle the absence than render a broken URL.+ assert _build_task_url(team_id=42, task_id=task_id, task_run_id=task_run_id) is None+++def test_to_summary_and_detail_surface_task_url_from_bridge():+ team = Team.objects.create(+ organization=Organization.objects.create(+ name=f"surface-org-{random.randint(1, 99999)}",+ is_ai_data_processing_approved=True,+ ),+ name=f"surface-team-{random.randint(1, 99999)}",+ )+ with team_scope(team.id, canonical=True):+ config = SignalScoutConfig.objects.create(team=team)+ task_run = _make_task_run(team)+ run = SignalScoutRun.objects.create(+ task_run=task_run,+ team=team,+ scout_config=config,+ skill_name="signals-scout-errors",+ skill_version=1,+ )++ summary = _to_summary(run, team_id=team.id)+ assert summary.task_id == str(task_run.task_id)+ assert summary.task_run_id == str(task_run.id)+ assert summary.task_url == f"/project/{team.id}/tasks/{task_run.task_id}?runId={task_run.id}"+ # Status flows from the linked TaskRun.+ assert summary.status == task_run.status++ detail = _to_detail(run, team_id=team.id)+ assert detail.task_id == summary.task_id+ assert detail.task_run_id == summary.task_run_id+ assert detail.task_url == summary.task_urldiff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pynew file mode 100644index 000000000000..eccde5b2bb86--- /dev/null+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -0,0 +1,356 @@+from __future__ import annotations++from posthog.test.base import APIBaseTest+from unittest.mock import AsyncMock, patch++from django.conf import settings+from django.test import override_settings++from rest_framework import status++from posthog.api.oauth.test_dcr import generate_rsa_key+from posthog.models import OAuthApplication+from posthog.models.team.team import Team+from posthog.temporal.oauth import (+ ARRAY_APP_CLIENT_ID_DEV,+ ARRAY_APP_CLIENT_ID_EU,+ ARRAY_APP_CLIENT_ID_US,+ create_oauth_access_token_for_user,+)++from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad+from products.tasks.backend.models import Task, TaskRun++# Fresh RSA key so RS256 OAuth apps validate in tests (OIDC_RSA_PRIVATE_KEY is unset by+# default). Same pattern as `posthog/test/test_permissions.py` and the OAuth provider tests.+_OIDC_RSA_KEY = generate_rsa_key()+++def _authenticate_as_scout(test: APIBaseTest) -> None:+ """Auth the test client with a scout-internal token, mirroring how the harness sandbox+ reaches these endpoints in production. The emit / scratchpad write actions require+ `signal_scout_internal:write`, which is server-mint-only and rejects session auth, so the+ default `APIBaseTest` force-login isn't enough for the write surface — only reads pass on+ a session. `logout()` first so the token is the sole credential on every request.+ """+ # `create_oauth_access_token_for_user` resolves the Array app by `get_instance_region()`,+ # which isn't deterministic across test contexts — create the app for every region client+ # id so the lookup always resolves.+ for client_id in (ARRAY_APP_CLIENT_ID_DEV, ARRAY_APP_CLIENT_ID_US, ARRAY_APP_CLIENT_ID_EU):+ OAuthApplication.objects.get_or_create(+ client_id=client_id,+ defaults={+ "name": "Array Test App",+ "client_type": OAuthApplication.CLIENT_PUBLIC,+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,+ "redirect_uris": "https://app.posthog.com/callback",+ # RS256 is enforced by the `enforce_rs256_algorithm` DB constraint; the+ # `_OIDC_RSA_KEY` override on the test class satisfies the signing-key requirement.+ "algorithm": "RS256",+ },+ )+ token = create_oauth_access_token_for_user(+ test.user, test.team.id, scopes="signals_scout", include_internal_scopes=True+ )+ test.client.logout()+ test.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")+++def _make_task_run(team: Team, *, status: str | None = None) -> TaskRun:+ task = Task.objects.create(+ team=team,+ title="scout run",+ description="scout run",+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,+ )+ task_run = TaskRun.objects.create(task=task, team=team)+ if status is not None:+ TaskRun.objects.filter(id=task_run.id).update(status=status)+ task_run.refresh_from_db()+ return task_run+++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)+ task_run = _make_task_run(team, status=task_run_status)+ defaults: dict = {+ "task_run": task_run,+ "scout_config": config,+ "skill_name": "signals-scout-general",+ "skill_version": 1,+ }+ defaults.update(overrides)+ return SignalScoutRun.objects.create(team=team, **defaults)+++class TestScoutHarnessRunsAPI(APIBaseTest):+ def _list_url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/"++ def _detail_url(self, run_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/"++ def test_list_returns_runs_for_team_newest_first(self) -> None:+ older = _make_run(self.team)+ newer = _make_run(self.team)+ response = self.client.get(self._list_url())+ assert response.status_code == status.HTTP_200_OK+ ids = [row["run_id"] for row in response.json()]+ # newer first (created_at desc).+ assert ids == [str(newer.id), str(older.id)]++ def test_list_does_not_leak_runs_from_another_team(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ _make_run(other)+ own = _make_run(self.team)+ response = self.client.get(self._list_url())+ assert response.status_code == status.HTTP_200_OK+ ids = [row["run_id"] for row in response.json()]+ assert ids == [str(own.id)]++ def test_list_limit_clamped_to_max(self) -> None:+ for _ in range(3):+ _make_run(self.team)+ response = self.client.get(f"{self._list_url()}?limit=2")+ assert response.status_code == status.HTTP_200_OK+ assert len(response.json()) == 2++ def test_list_text_filter_matches_summary_ilike(self) -> None:+ keep = _make_run(self.team, summary="emit-free /checkout pass")+ _make_run(self.team, summary="LLM cost scan, all normal")+ response = self.client.get(f"{self._list_url()}?text=checkout")+ assert response.status_code == status.HTTP_200_OK+ ids = [row["run_id"] for row in response.json()]+ assert ids == [str(keep.id)]++ def test_retrieve_returns_bridge_projection(self) -> None:+ run = _make_run(self.team, summary="looked at /checkout, nothing actionable")+ response = self.client.get(self._detail_url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["run_id"] == str(run.id)+ assert body["skill_name"] == "signals-scout-general"+ assert body["task_run_id"] == str(run.task_run_id)+ # Status flows from the linked TaskRun (default fixture sets IN_PROGRESS).+ assert body["status"] == TaskRun.Status.IN_PROGRESS+ assert body["summary"] == "looked at /checkout, nothing actionable"++ def test_retrieve_unknown_id_returns_404(self) -> None:+ response = self.client.get(self._detail_url("00000000-0000-0000-0000-000000000000"))+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_retrieve_other_teams_run_returns_404(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ run = _make_run(other)+ response = self.client.get(self._detail_url(str(run.id)))+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_retrieve_malformed_run_id_returns_404(self) -> None:+ # Anything URL-safe that isn't a UUID must 404 cleanly — not 500 from+ # Django's UUIDField conversion blowing up on `.filter(id=...)`.+ for bad in ("not-a-uuid", "abc-def-ghi", "123", "deadbeef"):+ response = self.client.get(self._detail_url(bad))+ assert response.status_code == status.HTTP_404_NOT_FOUND, (+ f"expected 404 for {bad!r}, got {response.status_code}"+ )+++@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _OIDC_RSA_KEY})+class TestScoutHarnessEmitFindingAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # The harness preflight mirrors `emit_signal()`'s downstream gates: the org+ # must have AI processing approved and the team must have an enabled+ # SignalSourceConfig for the signals_scout source. Without this setup, the+ # preflight short-circuits before `emit_signal` runs.+ from products.signals.backend.models import SignalSourceConfig++ self.organization.is_ai_data_processing_approved = True+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ SignalSourceConfig.objects.get_or_create(+ team=self.team,+ source_product="signals_scout",+ source_type="cross_source_issue",+ defaults={"enabled": True},+ )+ # emit-signal requires `signal_scout_internal:write` — session auth is rejected.+ _authenticate_as_scout(self)++ def _emit_signal_url(self, run_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/emit-signal/"++ def _payload(self, **overrides) -> dict:+ body: dict = {+ "description": "Checkout 500s spike correlates with payment-flag rollout",+ "weight": 0.6,+ "confidence": 0.7,+ "evidence": [+ {+ "source_product": "error_tracking",+ "summary": "issue id <abc> increased 4x after 14:00",+ "entity_id": "abc",+ },+ ],+ "finding_id": "f-1",+ }+ body.update(overrides)+ return body++ def test_emit_finding_calls_emit_signal_with_deterministic_source_id(self) -> None:+ run = _make_run(self.team)+ with patch("products.signals.backend.api.emit_signal", new_callable=AsyncMock) as mock_emit:+ response = self.client.post(self._emit_signal_url(str(run.id)), data=self._payload(), format="json")+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["emitted"] is True+ assert body["finding_id"] == "f-1"+ assert body["skipped_reason"] is None+ mock_emit.assert_awaited_once()+ assert mock_emit.await_args is not None+ # Idempotency is via the deterministic `source_id` keyed on (run, finding).+ assert mock_emit.await_args.kwargs["source_id"] == f"run:{run.id}:finding:f-1"++ def test_emit_finding_rejects_non_in_progress_run(self) -> None:+ run = _make_run(self.team, task_run_status=TaskRun.Status.COMPLETED)+ response = self.client.post(self._emit_signal_url(str(run.id)), data=self._payload(), format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_emit_finding_validates_weight_range(self) -> None:+ run = _make_run(self.team)+ response = self.client.post(self._emit_signal_url(str(run.id)), data=self._payload(weight=2.0), format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_emit_finding_unknown_run_returns_404(self) -> None:+ response = self.client.post(+ self._emit_signal_url("00000000-0000-0000-0000-000000000000"), data=self._payload(), format="json"+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_emit_finding_other_teams_run_returns_404(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ run = _make_run(other)+ response = self.client.post(self._emit_signal_url(str(run.id)), data=self._payload(), format="json")+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_emit_finding_malformed_run_id_returns_404(self) -> None:+ # Same guard as `retrieve`: a URL-safe non-UUID must 404 before any DB+ # call, not 500 from `.filter(id=...)` on a non-UUID string.+ for bad in ("not-a-uuid", "abc-def-ghi", "123", "deadbeef"):+ response = self.client.post(self._emit_signal_url(bad), data=self._payload(), format="json")+ assert response.status_code == status.HTTP_404_NOT_FOUND, (+ f"expected 404 for {bad!r}, got {response.status_code}"+ )+++@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _OIDC_RSA_KEY})+class TestScoutHarnessScratchpadAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # remember (create) and forget require `signal_scout_internal:write` — session auth+ # is rejected, so authenticate with the scout-internal token like the harness does.+ _authenticate_as_scout(self)++ def _list_url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/scratchpad/"++ def _forget_url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/scratchpad/forget/"++ def test_remember_creates_entry(self) -> None:+ body = {"key": "k1", "content": "checkout regression noise — already tracked"}+ response = self.client.post(self._list_url(), data=body, format="json")+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["key"] == "k1"+ assert data["content"] == "checkout regression noise — already tracked"++ def test_remember_idempotent_upsert_on_team_key(self) -> None:+ first = self.client.post(self._list_url(), data={"key": "k1", "content": "v1"}, format="json")+ second = self.client.post(self._list_url(), data={"key": "k1", "content": "v2"}, format="json")+ assert first.status_code == status.HTTP_200_OK+ assert second.status_code == status.HTTP_200_OK+ assert SignalScratchpad.objects.filter(team=self.team, key="k1").count() == 1+ assert SignalScratchpad.objects.get(team=self.team, key="k1").content == "v2"++ def test_search_returns_team_entries(self) -> None:+ SignalScratchpad.objects.create(team=self.team, key="active", content="still relevant")+ SignalScratchpad.objects.create(team=self.team, key="another", content="more memory")+ response = self.client.get(self._list_url())+ assert response.status_code == status.HTTP_200_OK+ keys = {row["key"] for row in response.json()}+ assert keys == {"active", "another"}++ def test_search_text_filter_uses_ilike(self) -> None:+ SignalScratchpad.objects.create(team=self.team, key="match", content="The CHECKOUT funnel is broken")+ SignalScratchpad.objects.create(team=self.team, key="miss", content="image loading is slow")+ response = self.client.get(f"{self._list_url()}?text=checkout")+ assert response.status_code == status.HTTP_200_OK+ keys = [row["key"] for row in response.json()]+ assert keys == ["match"]++ def test_search_does_not_leak_other_teams_memory(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ SignalScratchpad.objects.create(team=other, key="theirs", content="leaked?")+ SignalScratchpad.objects.create(team=self.team, key="ours", content="visible")+ response = self.client.get(self._list_url())+ keys = [row["key"] for row in response.json()]+ assert keys == ["ours"]++ def test_forget_removes_entry(self) -> None:+ SignalScratchpad.objects.create(team=self.team, key="k1", content="v")+ response = self.client.post(self._forget_url(), data={"key": "k1"}, format="json")+ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"deleted": True}+ assert not SignalScratchpad.objects.filter(team=self.team, key="k1").exists()++ def test_forget_returns_false_when_key_missing(self) -> None:+ response = self.client.post(self._forget_url(), data={"key": "ghost"}, format="json")+ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"deleted": False}++ def test_remember_accepts_run_id_belonging_to_same_team(self) -> None:+ run = _make_run(self.team)+ response = self.client.post(+ self._list_url(),+ data={"key": "k1", "content": "v", "run_id": str(run.id)},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ row = SignalScratchpad.objects.get(team=self.team, key="k1")+ assert str(row.created_by_run_id) == str(run.id)++ def test_remember_rejects_run_id_from_another_team(self) -> None:+ # A run UUID from another team must not create cross-team lineage on this+ # team's memory row — the agent's MCP token is team-scoped, but `run_id`+ # is a free body field and previously had no validation.+ other = Team.objects.create(organization=self.organization, name="Other")+ other_run = _make_run(other)+ response = self.client.post(+ self._list_url(),+ data={"key": "k1", "content": "v", "run_id": str(other_run.id)},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json().get("attr") == "run_id"+ assert not SignalScratchpad.objects.filter(team=self.team, key="k1").exists()++ def test_remember_rejects_unknown_run_id(self) -> None:+ # A well-formed UUID that doesn't reference any run row should also bounce —+ # don't let a typo silently produce orphan lineage on the memory table.+ response = self.client.post(+ self._list_url(),+ data={"key": "k1", "content": "v", "run_id": "00000000-0000-0000-0000-000000000000"},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json().get("attr") == "run_id"++ def test_remember_rejects_malformed_run_id(self) -> None:+ # UUIDField in the serializer rejects non-UUID strings before the view runs.+ response = self.client.post(+ self._list_url(),+ data={"key": "k1", "content": "v", "run_id": "not-a-uuid"},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUESTdiff --git a/products/signals/backend/test/test_scout_harness_lazy_seed.py b/products/signals/backend/test/test_scout_harness_lazy_seed.pynew file mode 100644index 000000000000..eb2accbd0f93--- /dev/null+++ b/products/signals/backend/test/test_scout_harness_lazy_seed.py@@ -0,0 +1,289 @@+from __future__ import annotations++import textwrap+from pathlib import Path++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from products.ai_observability.backend.models.skills import LLMSkill+from products.signals.backend.scout_harness.lazy_seed import (+ CanonicalSkill,+ CanonicalSkillParseError,+ discover_canonical_skills,+ seed_canonical_skills,+)+from products.signals.backend.scout_harness.skill_loader import load_skill_for_run+++def _write_canonical_skill(+ base: Path,+ *,+ dir_name: str,+ frontmatter: str,+ body: str = "# Body\n",+ bundled_files: dict[str, str] | None = None,+) -> Path:+ skill_dir = base / dir_name+ skill_dir.mkdir(parents=True, exist_ok=True)+ skill_md = textwrap.dedent(frontmatter).strip() + "\n" + body+ (skill_dir / "SKILL.md").write_text(skill_md, encoding="utf-8")+ for rel_path, content in (bundled_files or {}).items():+ target = skill_dir / rel_path+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(content, encoding="utf-8")+ return skill_dir+++class TestDiscoverCanonicalSkills:+ def test_returns_empty_for_missing_dir(self, tmp_path: Path) -> None:+ assert discover_canonical_skills(tmp_path / "does-not-exist") == ()++ def test_walks_signals_scout_prefix_skills_only(self, tmp_path: Path) -> None:+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-foo",+ frontmatter="""+ ---+ name: signals-scout-foo+ description: foo skill+ ---+ """,+ body="# Foo\n",+ )+ _write_canonical_skill(+ tmp_path,+ dir_name="some-other-skill",+ frontmatter="""+ ---+ name: some-other-skill+ description: not a signals-scout+ ---+ """,+ body="# nope\n",+ )+ 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:+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-bar",+ frontmatter="""+ ---+ name: signals-scout-bar+ description: bar skill+ allowed_tools:+ - remember+ - search_scratchpad+ ---+ """,+ body="# Bar\n",+ )+ 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:+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-bar",+ frontmatter="""+ ---+ name: signals-scout-bar+ description: bar skill+ ---+ """,+ body="# Bar\n",+ bundled_files={+ "references/playbook.md": "# Playbook\n",+ "scripts/check.py": "print('hi')\n",+ },+ )+ skills = discover_canonical_skills(tmp_path)+ files_by_path = {f.path: f for f in skills[0].files}+ 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++ def test_missing_frontmatter_raises(self, tmp_path: Path) -> None:+ skill_dir = tmp_path / "signals-scout-foo"+ skill_dir.mkdir()+ (skill_dir / "SKILL.md").write_text("# no frontmatter\n", encoding="utf-8")+ with pytest.raises(CanonicalSkillParseError):+ discover_canonical_skills(tmp_path)++ def test_wrong_name_prefix_in_frontmatter_raises(self, tmp_path: Path) -> None:+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-bar",+ frontmatter="""+ ---+ name: not-prefixed+ description: bar skill+ ---+ """,+ body="# Bar\n",+ )+ with pytest.raises(CanonicalSkillParseError):+ discover_canonical_skills(tmp_path)++ def test_in_repo_canonical_set_parses_cleanly(self) -> None:+ # Exercises the production manifest at `products/signals/skills/` — growing the+ # canonical set is a deliberate edit, so this serves as the lock.+ skills = discover_canonical_skills()+ assert any(s.name == "signals-scout-general" for s in skills)++ def test_oversized_body_raises(self, tmp_path: Path) -> None:+ # Body byte limit mirrors the REST API contract (MAX_SKILL_BODY_BYTES = 1 MB).+ # A canonical too big to seed should fail at parse time, not on DB write.+ body = "x" * (1_000_001)+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-big-body",+ frontmatter="""+ ---+ name: signals-scout-big-body+ description: oversized body+ ---+ """,+ body=body,+ )+ with pytest.raises(CanonicalSkillParseError, match="byte limit"):+ discover_canonical_skills(tmp_path)++ def test_oversized_bundled_file_raises(self, tmp_path: Path) -> None:+ # Per-file byte limit mirrors MAX_SKILL_FILE_BYTES (1 MB).+ oversized = "x" * (1_000_001)+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-big-file",+ frontmatter="""+ ---+ name: signals-scout-big-file+ description: oversized bundled file+ ---+ """,+ body="# Body\n",+ bundled_files={"references/huge.md": oversized},+ )+ with pytest.raises(CanonicalSkillParseError, match="byte limit"):+ discover_canonical_skills(tmp_path)++ def test_too_many_bundled_files_raises(self, tmp_path: Path) -> None:+ # File count limit mirrors MAX_SKILL_FILE_COUNT (50).+ bundled = {f"references/file_{i:03d}.md": f"# file {i}\n" for i in range(51)}+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-too-many",+ frontmatter="""+ ---+ name: signals-scout-too-many+ description: too many files+ ---+ """,+ body="# Body\n",+ bundled_files=bundled,+ )+ with pytest.raises(CanonicalSkillParseError, match="exceeding the 50 limit"):+ discover_canonical_skills(tmp_path)++ def test_overlong_path_raises(self, tmp_path: Path) -> None:+ # Path length matches LLMSkillFile.path max_length (500). Friendly parse-time+ # error beats the Postgres `value too long for type character varying(500)`.+ # Nested-dir construction because macOS rejects single filename segments >255 chars.+ nested_seg = "a" * 170+ rel_path = f"references/{nested_seg}/{nested_seg}/{nested_seg}/file.md"+ assert len(rel_path) > 500+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-long-path",+ frontmatter="""+ ---+ name: signals-scout-long-path+ description: overlong path+ ---+ """,+ body="# Body\n",+ bundled_files={rel_path: "x"},+ )+ with pytest.raises(CanonicalSkillParseError, match="char limit"):+ discover_canonical_skills(tmp_path)+++class TestSeedCanonicalSkills(BaseTest):+ def test_seeds_canonicals_when_team_has_no_signals_scout_skills(self) -> None:+ result = seed_canonical_skills(self.team)+ assert "signals-scout-general" in result.created_skill_names+ seeded = LLMSkill.objects.get(team=self.team, name="signals-scout-general")+ assert seeded.is_latest is True+ assert seeded.body # body copied from SKILL.md+ assert seeded.metadata["seeded_by"] == "signals_scout_harness"++ def test_no_op_when_team_already_has_signals_scout_skill(self) -> None:+ LLMSkill.objects.create(+ team=self.team,+ name="signals-scout-existing",+ description="team-edited copy",+ body="team body",+ )+ result = seed_canonical_skills(self.team)+ assert result.created_skill_names == ()+ assert result.skipped_reason and "already has" in result.skipped_reason+ existing = LLMSkill.objects.get(team=self.team, name="signals-scout-existing")+ assert existing.body == "team body"++ def test_no_op_preserves_archived_team_copies(self) -> None:+ LLMSkill.objects.create(+ team=self.team,+ name="signals-scout-archived",+ description="team archived this",+ body="team body",+ deleted=True,+ is_latest=False,+ )+ # Re-seeding archived rows would resurrect content the team deliberately removed.+ result = seed_canonical_skills(self.team)+ assert result.created_skill_names == ()+ assert not LLMSkill.objects.filter(team=self.team, name="signals-scout-general", deleted=False).exists()++ def test_idempotent_on_repeat_call(self) -> None:+ first = seed_canonical_skills(self.team)+ assert first.created_skill_names+ second = seed_canonical_skills(self.team)+ assert second.created_skill_names == ()+ count = LLMSkill.objects.filter(team=self.team, name__startswith="signals-scout-").count()+ assert count == len(first.created_skill_names)++ def test_seeded_skill_is_loadable_via_load_skill_for_run(self) -> None:+ seed_canonical_skills(self.team)+ loaded = load_skill_for_run(self.team, "signals-scout-general")+ assert loaded.name == "signals-scout-general"+ assert loaded.version == 1+ assert "Signals scout" in loaded.body++ def test_partial_failure_rolls_back_whole_seed_and_retries(self) -> None:+ # A mid-loop failure must roll back every insert, so the next run retries the full set+ # instead of getting wedged with a partial seed the "already seeded" guard treats as done.+ fakes = (+ CanonicalSkill("signals-scout-a", "d", "body", (), (), Path(".")),+ CanonicalSkill("signals-scout-b", "d", "body", (), (), Path(".")),+ )+ real_create = LLMSkill.objects.create+ seen = {"n": 0}++ def flaky_create(**kwargs: object) -> LLMSkill:+ seen["n"] += 1+ if seen["n"] == 2:+ raise RuntimeError("boom")+ return real_create(**kwargs)++ with patch("products.signals.backend.scout_harness.lazy_seed.discover_canonical_skills", return_value=fakes):+ with patch.object(LLMSkill.objects, "create", side_effect=flaky_create):+ with pytest.raises(RuntimeError):+ seed_canonical_skills(self.team)+ assert not LLMSkill.objects.filter(team=self.team, name__startswith="signals-scout-").exists()++ with patch("products.signals.backend.scout_harness.lazy_seed.discover_canonical_skills", return_value=fakes):+ result = seed_canonical_skills(self.team)+ assert set(result.created_skill_names) == {"signals-scout-a", "signals-scout-b"}diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pynew file mode 100644index 000000000000..e4173efdc965--- /dev/null+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -0,0 +1,663 @@+from __future__ import annotations++from datetime import timedelta++import pytest+from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, patch++from django.utils import timezone++import pytest_asyncio++from posthog.models.scoping import team_scope+from posthog.sync import database_sync_to_async++from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad+from products.signals.backend.scout_harness.tools import (+ MAX_EVIDENCE_ENTRIES,+ EvidenceEntry,+ InvalidEmitError,+ InvalidScratchpadError,+ emit_finding,+ forget,+ get_run,+ remember,+ search_recent_runs,+ search_scratchpad,+)+from products.signals.backend.scout_harness.tools.emit import (+ SOURCE_PRODUCT,+ SOURCE_TYPE,+ _build_extra,+ _validate_inputs,+ emit_finding_sync,+)+from products.signals.backend.scout_harness.tools.runs import MAX_RUN_SEARCH_LIMIT+from products.signals.backend.scout_harness.tools.scratchpad import (+ MAX_SCRATCHPAD_CONTENT_LENGTH,+ MAX_SCRATCHPAD_SEARCH_LIMIT,+)+from products.tasks.backend.models import Task, TaskRun+++def _make_task_run(team, *, status: str | None = None) -> TaskRun:+ task = Task.objects.create(+ team=team,+ title="scout run",+ description="scout run",+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,+ )+ task_run = TaskRun.objects.create(task=task, team=team)+ if status is not None:+ TaskRun.objects.filter(id=task_run.id).update(status=status)+ task_run.refresh_from_db()+ return task_run+++def _create_run(team, **overrides) -> SignalScoutRun:+ """Build a SignalScoutRun bridge row with a backing TaskRun.++ Default TaskRun status is COMPLETED so summary/detail surface a terminal+ state — tests that need IN_PROGRESS pass `task_run_status` explicitly.+ """+ task_run_status = overrides.pop("task_run_status", TaskRun.Status.COMPLETED)+ task_run = _make_task_run(team, status=task_run_status)+ defaults: dict = {+ "task_run": task_run,+ "skill_name": "signals-scout-errors",+ "skill_version": 1,+ }+ defaults.update(overrides)+ return SignalScoutRun.objects.create(team=team, **defaults)+++class TestSearchRecentRuns(BaseTest):+ def test_returns_runs_for_team_in_reverse_chronological_order(self) -> None:+ first = _create_run(self.team)+ second = _create_run(self.team)+ # Force ordering by tweaking the bridge `created_at` (auto_now_add can collide).+ SignalScoutRun.objects.filter(id=first.id).update(created_at=timezone.now() - timedelta(hours=2))+ SignalScoutRun.objects.filter(id=second.id).update(created_at=timezone.now() - timedelta(hours=1))++ results = search_recent_runs(team_id=self.team.id)++ assert [r.run_id for r in results] == [str(second.id), str(first.id)]++ def test_filters_by_date_from(self) -> None:+ old = _create_run(self.team)+ recent = _create_run(self.team)+ SignalScoutRun.objects.filter(id=old.id).update(created_at=timezone.now() - timedelta(days=10))+ SignalScoutRun.objects.filter(id=recent.id).update(created_at=timezone.now() - timedelta(hours=1))++ hits = search_recent_runs(team_id=self.team.id, date_from=timezone.now() - timedelta(days=1))++ assert [r.run_id for r in hits] == [str(recent.id)]++ def test_filters_by_date_to_for_cursor_iteration(self) -> None:+ """`date_to` is the upper bound the scout uses to walk past the result cap.++ Set it to the `created_at` of the oldest result on the prior page and the+ next call returns the *next* older slice.+ """+ old = _create_run(self.team)+ middle = _create_run(self.team)+ recent = _create_run(self.team)+ SignalScoutRun.objects.filter(id=old.id).update(created_at=timezone.now() - timedelta(days=14))+ middle_ts = timezone.now() - timedelta(days=7)+ SignalScoutRun.objects.filter(id=middle.id).update(created_at=middle_ts)+ SignalScoutRun.objects.filter(id=recent.id).update(created_at=timezone.now() - timedelta(hours=1))++ # Strict `<` bound: middle's own timestamp is excluded, only `old` is returned.+ hits = search_recent_runs(team_id=self.team.id, date_to=middle_ts)++ assert [r.run_id for r in hits] == [str(old.id)]++ def test_does_not_leak_runs_from_other_teams(self) -> None:+ from posthog.models import Team++ other = Team.objects.create(organization=self.organization, name="other")+ mine = _create_run(self.team)+ _create_run(other)++ hits = search_recent_runs(team_id=self.team.id)++ assert [r.run_id for r in hits] == [str(mine.id)]++ def test_limit_clamped_to_max(self) -> None:+ for _ in range(MAX_RUN_SEARCH_LIMIT + 5):+ _create_run(self.team)++ hits = search_recent_runs(team_id=self.team.id, limit=MAX_RUN_SEARCH_LIMIT + 50)++ assert len(hits) == MAX_RUN_SEARCH_LIMIT++ def test_summary_surfaces_status_from_linked_task_run(self) -> None:+ run = _create_run(self.team, task_run_status=TaskRun.Status.COMPLETED)++ hits = search_recent_runs(team_id=self.team.id, limit=1)++ assert hits[0].run_id == str(run.id)+ assert hits[0].status == TaskRun.Status.COMPLETED++ def test_text_filter_uses_ilike_on_summary(self) -> None:+ keep = _create_run(self.team, summary="Looked at /checkout 500s — nothing actionable")+ _create_run(self.team, summary="Scanned LLM costs, all normal")+ _create_run(self.team, summary="")++ hits = search_recent_runs(team_id=self.team.id, text="checkout")++ assert [h.run_id for h in hits] == [str(keep.id)]++ def test_summary_field_round_trips_through_projection(self) -> None:+ run = _create_run(self.team, summary="emit-free run; only known-noise patterns")++ hits = search_recent_runs(team_id=self.team.id, limit=1)++ assert hits[0].summary == "emit-free run; only known-noise patterns"+ detail = get_run(team_id=self.team.id, run_id=str(run.id))+ assert detail is not None+ assert detail.summary == "emit-free run; only known-noise patterns"+++class TestGetRun(BaseTest):+ def test_returns_full_run_payload(self) -> None:+ run = _create_run(self.team)++ detail = get_run(team_id=self.team.id, run_id=str(run.id))++ assert detail is not None+ assert detail.run_id == str(run.id)+ assert detail.skill_name == "signals-scout-errors"+ assert detail.skill_version == 1+ assert detail.task_run_id == str(run.task_run_id)+ # Default-empty summary on rows that didn't go through the runner's finalize step.+ assert detail.summary == ""++ def test_returns_none_for_unknown_id(self) -> None:+ detail = get_run(team_id=self.team.id, run_id="00000000-0000-0000-0000-000000000000")+ assert detail is None++ def test_does_not_leak_run_from_another_team(self) -> None:+ from posthog.models import Team++ other = Team.objects.create(organization=self.organization, name="other-team")+ run = _create_run(other)++ detail = get_run(team_id=self.team.id, run_id=str(run.id))++ assert detail is None # team scoping enforced even when caller knows the UUID+++class TestRemember(BaseTest):+ def test_creates_entry_with_default_lineage(self) -> None:+ entry = remember(team_id=self.team.id, key="known-noise", content="ignore /favicon 404s")++ row = SignalScratchpad.objects.get(team_id=self.team.id, key="known-noise")+ assert row.content == "ignore /favicon 404s"+ assert row.created_by_run_id is None+ assert entry.key == "known-noise"++ def test_idempotent_upsert_on_team_key(self) -> None:+ first = remember(team_id=self.team.id, key="k", content="v1")+ second = remember(team_id=self.team.id, key="k", content="v2")++ assert first.key == second.key+ rows = SignalScratchpad.objects.filter(team_id=self.team.id, key="k")+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.content == "v2"++ def test_upsert_preserves_original_creator_lineage(self) -> None:+ run = _create_run(self.team)+ # First write attributed to a run.+ remember(team_id=self.team.id, key="k", content="v1", run_id=str(run.id))+ # Second write has no run_id — must not overwrite the original creator.+ remember(team_id=self.team.id, key="k", content="v2")++ row = SignalScratchpad.objects.get(team_id=self.team.id, key="k")+ assert row.content == "v2"+ assert str(row.created_by_run_id) == str(run.id)++ def test_rejects_empty_key_or_content(self) -> None:+ with pytest.raises(InvalidScratchpadError):+ remember(team_id=self.team.id, key="", content="x")+ with pytest.raises(InvalidScratchpadError):+ remember(team_id=self.team.id, key=" ", content="x")+ with pytest.raises(InvalidScratchpadError):+ remember(team_id=self.team.id, key="k", content="")++ def test_rejects_content_over_max_length(self) -> None:+ remember(team_id=self.team.id, key="k", content="x" * MAX_SCRATCHPAD_CONTENT_LENGTH)+ with pytest.raises(InvalidScratchpadError):+ remember(team_id=self.team.id, key="k", content="x" * (MAX_SCRATCHPAD_CONTENT_LENGTH + 1))++ def test_links_to_creating_run(self) -> None:+ run = _create_run(self.team)+ entry = remember(+ team_id=self.team.id,+ key="lineage",+ content="x",+ run_id=str(run.id),+ )+ assert entry.created_by_run_id == str(run.id)+++class TestForget(BaseTest):+ def test_deletes_entry(self) -> None:+ remember(team_id=self.team.id, key="k", content="v")++ result = forget(team_id=self.team.id, key="k")++ assert result is True+ assert not SignalScratchpad.objects.filter(team_id=self.team.id, key="k").exists()++ def test_returns_false_when_key_missing(self) -> None:+ assert forget(team_id=self.team.id, key="never-existed") is False+++class TestSearchScratchpad(BaseTest):+ def test_returns_all_team_entries(self) -> None:+ SignalScratchpad.objects.create(team=self.team, key="a", content="alpha")+ SignalScratchpad.objects.create(team=self.team, key="b", content="beta")++ results = search_scratchpad(team_id=self.team.id)++ keys = {e.key for e in results}+ assert keys == {"a", "b"}++ def test_text_filter_uses_ilike_on_content_and_key(self) -> None:+ remember(team_id=self.team.id, key="k1", content="The CHECKOUT funnel is broken")+ remember(team_id=self.team.id, key="checkout-key", content="unrelated")+ remember(team_id=self.team.id, key="k2", content="Image loading is slow")++ results = search_scratchpad(team_id=self.team.id, text="checkout")++ keys = {e.key for e in results}+ # Matches on both content ('CHECKOUT' in k1) and key ('checkout-key').+ assert keys == {"k1", "checkout-key"}++ def test_does_not_leak_memories_from_other_teams(self) -> None:+ from posthog.models import Team++ other = Team.objects.create(organization=self.organization, name="other-team")+ remember(team_id=self.team.id, key="mine", content="mine")+ remember(team_id=other.id, key="theirs", content="theirs")++ results = search_scratchpad(team_id=self.team.id)++ assert all(e.key == "mine" for e in results)++ def test_limit_clamped_to_max(self) -> None:+ for i in range(MAX_SCRATCHPAD_SEARCH_LIMIT + 5):+ remember(team_id=self.team.id, key=f"k{i:03d}", content=f"c{i}")++ results = search_scratchpad(team_id=self.team.id, limit=MAX_SCRATCHPAD_SEARCH_LIMIT + 50)++ assert len(results) == MAX_SCRATCHPAD_SEARCH_LIMIT+++# --- emit adapter tests ---+++class TestValidateEmitInputs:+ """Pure validation — no DB."""++ def test_empty_description_raises(self) -> None:+ with pytest.raises(InvalidEmitError, match="description"):+ _validate_inputs("", 0.5, 0.5, [])++ def test_whitespace_only_description_raises(self) -> None:+ with pytest.raises(InvalidEmitError, match="description"):+ _validate_inputs(" \n\t", 0.5, 0.5, [])++ @pytest.mark.parametrize("weight", [-0.1, 1.1, 2.0])+ def test_weight_out_of_range_raises(self, weight: float) -> None:+ with pytest.raises(InvalidEmitError, match="weight"):+ _validate_inputs("ok", weight, 0.5, [])++ @pytest.mark.parametrize("confidence", [-0.1, 1.1])+ def test_confidence_out_of_range_raises(self, confidence: float) -> None:+ with pytest.raises(InvalidEmitError, match="confidence"):+ _validate_inputs("ok", 0.5, confidence, [])++ def test_too_many_evidence_entries_raises(self) -> None:+ many = [EvidenceEntry(source_product="logs", summary=f"e{i}") for i in range(MAX_EVIDENCE_ENTRIES + 1)]+ with pytest.raises(InvalidEmitError, match="evidence"):+ _validate_inputs("ok", 0.5, 0.5, many)++ def test_at_capacity_evidence_passes(self) -> None:+ many = [EvidenceEntry(source_product="logs", summary=f"e{i}") for i in range(MAX_EVIDENCE_ENTRIES)]+ # Should not raise.+ _validate_inputs("ok", 0.5, 0.5, many)+++class TestBuildEmitExtra:+ """Pure shaping — no DB. Asserts the dict matches what `SignalsScoutSignalExtra` expects."""++ def _minimal(self) -> dict:+ return _build_extra(+ run_id="run-uuid",+ finding_id="finding-uuid",+ skill_name="signals-scout-errors",+ skill_version=2,+ confidence=0.7,+ evidence=[EvidenceEntry(source_product="error_tracking", summary="500s on /checkout")],+ hypothesis=None,+ severity=None,+ dedupe_keys=None,+ time_range=None,+ mcp_trace_id=None,+ )++ def test_minimal_extra_has_only_required_fields(self) -> None:+ extra = self._minimal()+ # Required by schema:+ assert extra["scout_run_id"] == "run-uuid"+ assert extra["finding_id"] == "finding-uuid"+ assert extra["skill_name"] == "signals-scout-errors"+ assert extra["confidence"] == 0.7+ assert extra["evidence"] == [+ {"source_product": "error_tracking", "summary": "500s on /checkout", "entity_id": None}+ ]+ # Optional fields omitted, not None — pydantic with extra="forbid" tolerates absence+ # but rejects unexpected keys, so omission is the right shape.+ for opt in ("hypothesis", "severity", "dedupe_keys", "time_range", "mcp_trace_id"):+ assert opt not in extra++ def test_skill_version_cast_to_float(self) -> None:+ extra = self._minimal()+ # SignalsScoutSignalExtra.skill_version is float in posthog/schema.py.+ assert isinstance(extra["skill_version"], float)+ assert extra["skill_version"] == 2.0++ def test_full_extra_includes_all_optional_fields(self) -> None:+ extra = _build_extra(+ run_id="run-uuid",+ finding_id="finding-uuid",+ skill_name="signals-scout-errors",+ skill_version=1,+ confidence=0.9,+ evidence=[EvidenceEntry(source_product="logs", summary="bursts of 500s", entity_id="log-1")],+ hypothesis="checkout post-deploy regression",+ severity="P1",+ dedupe_keys=["checkout-500-spike"],+ time_range=("2026-04-29T00:00:00Z", "2026-04-30T00:00:00Z"),+ mcp_trace_id="trace-abc",+ )+ assert extra["hypothesis"] == "checkout post-deploy regression"+ assert extra["severity"] == "P1"+ assert extra["dedupe_keys"] == ["checkout-500-spike"]+ assert extra["time_range"] == {"date_from": "2026-04-29T00:00:00Z", "date_to": "2026-04-30T00:00:00Z"}+ assert extra["mcp_trace_id"] == "trace-abc"++ def test_built_extra_validates_against_schema_variant(self) -> None:+ """Round-trip: the extra we build must pass `SignalsScoutSignalInput` validation+ — this is the contract `emit_signal` checks via `_SIGNAL_VARIANT_LOOKUP`."""+ from posthog.schema import SignalsScoutSignalInput++ extra = self._minimal()+ SignalsScoutSignalInput.model_validate(+ {+ "source_product": SOURCE_PRODUCT,+ "source_type": SOURCE_TYPE,+ "source_id": "run:run-uuid:finding:finding-uuid",+ "description": "d",+ "weight": 0.5,+ "extra": extra,+ }+ )+++# --- emit_finding async tests ---+++@pytest_asyncio.fixture+async def aorganization_emit():+ from posthog.models import Organization++ org = await database_sync_to_async(Organization.objects.create)(+ name="signals-scout-emit", is_ai_data_processing_approved=True+ )+ return org+++@pytest_asyncio.fixture+async def ateam_emit(aorganization_emit):+ from posthog.models import Team++ from products.signals.backend.models import SignalSourceConfig++ team = await database_sync_to_async(Team.objects.create)(organization=aorganization_emit, name="emit-team")+ # The signals_scout source must be explicitly enabled per-team — emit_signal()+ # silently no-ops without it, and the harness preflight mirrors that gate.+ with team_scope(team.id, canonical=True):+ await database_sync_to_async(SignalSourceConfig.objects.create)(+ team=team,+ source_product="signals_scout",+ 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)+ yield team+++@pytest_asyncio.fixture+async def arun_emit(ateam_emit):+ config = await database_sync_to_async(SignalScoutConfig.objects.get)(team=ateam_emit)+ task_run = await database_sync_to_async(_make_task_run)(ateam_emit, status=TaskRun.Status.IN_PROGRESS)+ run = await database_sync_to_async(SignalScoutRun.objects.create)(+ task_run=task_run,+ team=ateam_emit,+ scout_config=config,+ skill_name="signals-scout-errors",+ skill_version=3,+ )+ return run+++async def test_emit_finding_happy_path_calls_emit_signal_with_deterministic_source_id(ateam_emit, arun_emit):+ evidence = [EvidenceEntry(source_product="error_tracking", summary="500s spike on /checkout")]++ with patch("products.signals.backend.api.emit_signal", new=AsyncMock()) as mock_emit:+ result = await emit_finding(+ team=ateam_emit,+ run=arun_emit,+ description="Checkout 500s post-deploy",+ weight=0.7,+ confidence=0.85,+ evidence=evidence,+ hypothesis="post-deploy regression",+ finding_id="f-happy",+ )++ assert result.emitted is True+ assert result.skipped_reason is None+ assert result.finding_id == "f-happy"+ mock_emit.assert_awaited_once()+ assert mock_emit.await_args is not None+ call_kwargs = mock_emit.await_args.kwargs+ assert call_kwargs["team"] is ateam_emit+ assert call_kwargs["source_product"] == SOURCE_PRODUCT+ assert call_kwargs["source_type"] == SOURCE_TYPE+ assert call_kwargs["source_id"] == f"run:{arun_emit.id}:finding:f-happy"+ assert call_kwargs["description"] == "Checkout 500s post-deploy"+ assert call_kwargs["weight"] == 0.7+ assert call_kwargs["extra"]["scout_run_id"] == str(arun_emit.id)+ assert call_kwargs["extra"]["finding_id"] == "f-happy"+ assert call_kwargs["extra"]["skill_name"] == "signals-scout-errors"+ assert call_kwargs["extra"]["skill_version"] == 3.0+++async def test_emit_finding_validation_error_does_not_emit(ateam_emit, arun_emit):+ with patch("products.signals.backend.api.emit_signal", new=AsyncMock()) as mock_emit:+ with pytest.raises(InvalidEmitError):+ await emit_finding(+ team=ateam_emit,+ run=arun_emit,+ description="", # empty -> validation error+ weight=0.5,+ confidence=0.5,+ evidence=[EvidenceEntry(source_product="logs", summary="x")],+ )++ mock_emit.assert_not_awaited()+++async def test_emit_finding_propagates_emit_signal_exception(ateam_emit, arun_emit):+ # Scout-side idempotency was dropped in PR 2 review and the downstream pipeline+ # does NOT dedupe on source_id — a failed downstream emit surfaces back to the+ # caller, and a retry with the same finding_id would emit a second signal.+ boom = AsyncMock(side_effect=RuntimeError("temporal exploded"))+ with patch("products.signals.backend.api.emit_signal", new=boom):+ with pytest.raises(RuntimeError, match="temporal"):+ 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-fails",+ )+++async def test_emit_finding_auto_generates_finding_id_when_not_provided(ateam_emit, arun_emit):+ with patch("products.signals.backend.api.emit_signal", new=AsyncMock()):+ 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")],+ )++ # Returned finding_id is a uuid string.+ import uuid++ uuid.UUID(result.finding_id) # raises ValueError if not a valid uuid+++async def test_emit_finding_returns_skipped_when_ai_processing_not_approved(arun_emit, ateam_emit):+ # Flip the org gate that emit_signal() checks. Without the harness preflight, the+ # emit_signal call would silently no-op and we'd report emitted=True; with the+ # preflight, we surface the truth.+ org = await database_sync_to_async(lambda: ateam_emit.organization)()+ org.is_ai_data_processing_approved = False+ await database_sync_to_async(org.save)()++ with patch("products.signals.backend.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-not-approved",+ )++ assert result.emitted is False+ assert result.skipped_reason == "ai_processing_not_approved"+ mock_emit.assert_not_called()+++async def test_emit_finding_returns_skipped_when_source_disabled(arun_emit, ateam_emit):+ # Fixture seeds an enabled config; flip it off to exercise the gate.+ from products.signals.backend.models import SignalSourceConfig++ await database_sync_to_async(+ SignalSourceConfig.objects.filter(+ team=ateam_emit, source_product=SOURCE_PRODUCT, source_type=SOURCE_TYPE+ ).update+ )(enabled=False)++ with patch("products.signals.backend.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-source-off",+ )++ assert result.emitted is False+ assert result.skipped_reason == "source_disabled"+ mock_emit.assert_not_called()+++# --- emit_finding (team, run) ownership guard tests ---+++async def test_emit_finding_rejects_team_run_mismatch(aorganization_emit, ateam_emit, arun_emit) -> None:+ """If `team` and `run.team_id` disagree, refuse before reaching `emit_signal`.++ The view filters by `team_id` so this can't happen via the API path today,+ but the function self-defends for future direct callers (in-process MCP,+ management commands).+ """+ from posthog.models import Team++ other_team = await database_sync_to_async(Team.objects.create)(organization=aorganization_emit, name="other-team")++ with patch("products.signals.backend.api.emit_signal", new=AsyncMock()) as mock_emit:+ with pytest.raises(RuntimeError, match="does not own run"):+ await emit_finding(+ team=other_team,+ run=arun_emit, # owned by ateam_emit, not other_team+ description="should be rejected",+ weight=0.5,+ confidence=0.5,+ evidence=[EvidenceEntry(source_product="logs", summary="x")],+ )+ mock_emit.assert_not_called()+++def test_emit_finding_sync_rejects_team_run_mismatch(db) -> None:+ """Same guard as the async path, exercised against `emit_finding_sync`."""+ from posthog.models import Organization, Team++ org = Organization.objects.create(name="sync-mismatch-org", is_ai_data_processing_approved=True)+ 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)+ task_run = _make_task_run(owning_team, status=TaskRun.Status.IN_PROGRESS)+ run = SignalScoutRun.objects.create(+ task_run=task_run,+ team=owning_team,+ scout_config=config,+ skill_name="signals-scout-errors",+ skill_version=1,+ )++ with patch("products.signals.backend.api.emit_signal", new=AsyncMock()) as mock_emit:+ with pytest.raises(RuntimeError, match="does not own run"):+ emit_finding_sync(+ team=other_team,+ run=run,+ description="should be rejected",+ weight=0.5,+ confidence=0.5,+ evidence=[EvidenceEntry(source_product="logs", summary="x")],+ )+ mock_emit.assert_not_called()diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex cc6bf6f3ba75..c7e18346adc9 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -108,6 +108,254 @@ export interface PaginatedSignalReportListApi {results: SignalReportApi[]}+/**+ * Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.++Status and timestamps flow from the linked `tasks.TaskRun`.+ */+export interface SignalScoutRunSummaryApi {+ /** UUID of the bridge row. */+ run_id: string+ /** Canonical skill name the run executed (e.g. `signals-scout-general`). */+ skill_name: string+ /** Skill version snapshotted at run start. */+ skill_version: number+ /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */+ status: string+ /** ISO-8601 timestamp the TaskRun was created. */+ started_at: string+ /**+ * ISO-8601 timestamp the TaskRun completed; null while still running.+ * @nullable+ */+ completed_at: string | null+ /**+ * UUID of the Tasks `Task` the scout span ran inside.+ * @nullable+ */+ task_id?: string | null+ /**+ * UUID of the Tasks `TaskRun`. Pairs with `task_id` to deep-link.+ * @nullable+ */+ task_run_id?: string | null+ /**+ * Relative deep-link to the Tasks UI for this run, e.g. `/project/{team_id}/tasks/{task_id}?runId={task_run_id}`.+ * @nullable+ */+ task_url?: string | null+ /** One-paragraph close-out the scout wrote at end-of-run. Empty string for runs that errored before close-out. The dedupe key for non-emitting runs. */+ summary: string+}++/**+ * Full `SignalScoutRun` projection used by `get-run`. Same shape as the summary+today; kept distinct so future detail-only extensions (linked Signal rows,+LLMA token-cost join) can land here without bloating the list response.+ */+export interface SignalScoutRunDetailApi {+ /** UUID of the bridge row. */+ run_id: string+ /** Canonical skill name the run executed (e.g. `signals-scout-general`). */+ skill_name: string+ /** Skill version snapshotted at run start. */+ skill_version: number+ /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */+ status: string+ /** ISO-8601 timestamp the TaskRun was created. */+ started_at: string+ /**+ * ISO-8601 timestamp the TaskRun completed; null while still running.+ * @nullable+ */+ completed_at: string | null+ /**+ * UUID of the Tasks `Task` the scout span ran inside.+ * @nullable+ */+ task_id?: string | null+ /**+ * UUID of the Tasks `TaskRun`. Pairs with `task_id` to deep-link.+ * @nullable+ */+ task_run_id?: string | null+ /**+ * Relative deep-link to the Tasks UI for this run, e.g. `/project/{team_id}/tasks/{task_id}?runId={task_run_id}`.+ * @nullable+ */+ task_url?: string | null+ /** One-paragraph close-out the scout wrote at end-of-run. Empty string for runs that errored before close-out. The dedupe key for non-emitting runs. */+ summary: string+}++/**+ * One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.+ */+export interface EvidenceEntryApi {+ /** Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...). */+ source_product: string+ /** One-sentence prose about why this evidence supports the finding. */+ summary: string+ /**+ * Optional ID of the cited entity (issue id, recording id, log query id).+ * @nullable+ */+ entity_id?: string | null+}++/**+ * * `P0` - P0+ * `P1` - P1+ * `P2` - P2+ * `P3` - P3+ * `P4` - P4+ */+export type AutonomyPriorityEnumApi = (typeof AutonomyPriorityEnumApi)[keyof typeof AutonomyPriorityEnumApi]++export const AutonomyPriorityEnumApi = {+ P0: 'P0',+ P1: 'P1',+ P2: 'P2',+ P3: 'P3',+ P4: 'P4',+} as const++export interface TimeRangeApi {+ /** ISO-8601 inclusive lower bound for the finding's window. */+ date_from: string+ /** ISO-8601 inclusive upper bound for the finding's window. */+ date_to: string+}++/**+ * Request body for `emit-finding`. Run attribution is taken from the URL path.+ */+export interface EmitFindingRequestApi {+ /**+ * Canonical evidence-bundle prose. Becomes the signal's `description`.+ * @maxLength 50000+ */+ description: string+ /**+ * Agent's weight for the signal in [0, 1]. Drives ranking in the inbox.+ * @minimum 0+ * @maximum 1+ */+ weight: number+ /**+ * Agent's confidence the finding is real in [0, 1]. Persisted in `extra`.+ * @minimum 0+ * @maximum 1+ */+ confidence: number+ /**+ * Citations supporting the finding. Capped at 20 entries.+ * @maxItems 20+ */+ evidence: EvidenceEntryApi[]+ /**+ * Optional one-line hypothesis the finding tests.+ * @nullable+ */+ hypothesis?: string | null+ /** Optional severity tag — one of P0, P1, P2, P3, P4. Informational only.++ * `P0` - P0+ * `P1` - P1+ * `P2` - P2+ * `P3` - P3+ * `P4` - P4 */+ severity?: AutonomyPriorityEnumApi | null+ /** Optional keys for downstream dedupe (e.g. `error_tracking_issue:<id>`). */+ dedupe_keys?: string[]+ /** Optional time window the finding refers to. */+ time_range?: TimeRangeApi | null+ /**+ * Optional MCP trace id for cross-system debugging.+ * @nullable+ */+ mcp_trace_id?: string | null+ /**+ * Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal.+ * @nullable+ */+ finding_id?: string | null+}++export interface EmitFindingResponseApi {+ /** Stable id for the finding (echoed back from request, or generated). */+ finding_id: string+ /** Whether `emit_signal` was actually fired. */+ emitted: boolean+ /**+ * `ai_processing_not_approved` | `source_disabled` | null when emitted normally.+ * @nullable+ */+ skipped_reason: string | null+}++/**+ * `SignalScratchpad` projection used by `search-memory` and `remember`.+ */+export interface ScratchpadEntryApi {+ /** Agent-chosen semantic key, unique per team. */+ key: string+ /** Prose content for prompt injection. */+ content: string+ /**+ * ISO-8601 creation timestamp.+ * @nullable+ */+ created_at: string | null+ /**+ * ISO-8601 last-write timestamp.+ * @nullable+ */+ updated_at: string | null+ /**+ * Run that wrote this entry, or null if human-authored.+ * @nullable+ */+ created_by_run_id: string | null+}++/**+ * Request body for `remember`.+ */+export interface RememberRequestApi {+ /**+ * Agent-chosen semantic key. Re-using a key updates the existing entry in place.+ * @maxLength 300+ */+ key: string+ /**+ * Prose to write. Read verbatim into future prompts.+ * @maxLength 50000+ */+ content: string+ /**+ * Run that authored this memory; persisted as `created_by_run_id` for lineage. Must reference a run on this same project — cross-project run UUIDs are rejected.+ * @nullable+ */+ run_id?: string | null+}++/**+ * Request body for `forget`.+ */+export interface ForgetRequestApi {+ /**+ * Memory key to delete.+ * @maxLength 300+ */+ key: string+}++export interface ForgetResponseApi {+ /** Whether a row was actually removed (false if the key didn't exist). */+ deleted: boolean+}+/*** * `session_replay` - Session replay* `llm_analytics` - LLM analytics@@ -198,23 +446,6 @@ export interface _UserApi {readonly email: string}-/**- * * `P0` - P0- * `P1` - P1- * `P2` - P2- * `P3` - P3- * `P4` - P4- */-export type AutonomyPriorityEnumApi = (typeof AutonomyPriorityEnumApi)[keyof typeof AutonomyPriorityEnumApi]--export const AutonomyPriorityEnumApi = {- P0: 'P0',- P1: 'P1',- P2: 'P2',- P3: 'P3',- P4: 'P4',-} as const-export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]export const BlankEnumApi = {@@ -290,6 +521,41 @@ export type SignalsReportsListParams = {suggested_reviewers?: string}+export type SignalsScoutRunsListParams = {+ /**+ * ISO-8601 inclusive lower bound on `created_at`. Omit to skip the lower bound.+ */+ date_from?: string+ /**+ * ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).+ */+ date_to?: string+ /**+ * Max rows to return (default 20, hard cap 100).+ * @minimum 1+ * @maximum 100+ */+ limit?: number+ /**+ * Case-insensitive substring match on the scout's end-of-run `summary`. Omit to skip the filter.+ * @minLength 1+ */+ text?: string+}++export type SignalsScoutScratchpadSearchParams = {+ /**+ * Max rows to return (default 20, hard cap 100).+ * @minimum 1+ * @maximum 100+ */+ limit?: number+ /**+ * ILIKE substring match against `content`. Omit to return the most recent entries.+ */+ text?: string+}+export type SignalsSourceConfigsListParams = {/*** Number of results to return per page.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 299d90b80a5d..063fc982e5dc 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -9,17 +9,27 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ EmitFindingRequestApi,+ EmitFindingResponseApi,+ ForgetRequestApi,+ ForgetResponseApi,PaginatedPauseStateResponseListApi,PaginatedSignalReportListApi,PaginatedSignalSourceConfigListApi,PatchedSignalSourceConfigApi,PauseResponseApi,PauseUntilRequestApi,+ RememberRequestApi,+ ScratchpadEntryApi,SignalReportApi,+ SignalScoutRunDetailApi,+ SignalScoutRunSummaryApi,SignalSourceConfigApi,SignalUserAutonomyConfigApi,SignalsProcessingListParams,SignalsReportsListParams,+ SignalsScoutRunsListParams,+ SignalsScoutScratchpadSearchParams,SignalsSourceConfigsListParams,} from './api.schemas'@@ -149,6 +159,151 @@ export const signalsReportsRetrieve = async (})}+export const getSignalsScoutRunsListUrl = (projectId: string, params?: SignalsScoutRunsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/signals/scout/runs/?${stringifiedParams}`+ : `/api/projects/${projectId}/signals/scout/runs/`+}++/**+ * Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scout to dedupe against work other runs already covered. ILIKE matches on `summary`. `date_from` / `date_to` are a half-open window on `created_at` (`>= date_from`, `< date_to`); pass `date_to` on subsequent calls to walk past the 100-row cap. Results capped at 100.+ * @summary Search recent agent runs+ */+export const signalsScoutRunsList = async (+ projectId: string,+ params?: SignalsScoutRunsListParams,+ options?: RequestInit+): Promise<SignalScoutRunSummaryApi[]> => {+ return apiMutator<SignalScoutRunSummaryApi[]>(getSignalsScoutRunsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getSignalsScoutRunsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/${id}/`+}++/**+ * Return the full `SignalScoutRun` row. Status, timing, and error flow from the linked `tasks.TaskRun`. Strictly team-scoped — a UUID belonging to another team returns 404.+ * @summary Get a run by ID+ */+export const signalsScoutRunsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<SignalScoutRunDetailApi> => {+ return apiMutator<SignalScoutRunDetailApi>(getSignalsScoutRunsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getSignalsScoutEmitSignalUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/${id}/emit-signal/`+}++/**+ * 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+ */+export const signalsScoutEmitSignal = async (+ projectId: string,+ id: string,+ emitFindingRequestApi: EmitFindingRequestApi,+ options?: RequestInit+): Promise<EmitFindingResponseApi> => {+ return apiMutator<EmitFindingResponseApi>(getSignalsScoutEmitSignalUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(emitFindingRequestApi),+ })+}++export const getSignalsScoutScratchpadSearchUrl = (projectId: string, params?: SignalsScoutScratchpadSearchParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/signals/scout/scratchpad/?${stringifiedParams}`+ : `/api/projects/${projectId}/signals/scout/scratchpad/`+}++/**+ * Return `SignalScratchpad` entries for this project. ILIKE matches on `content` and `key`.+ * @summary Search the scout scratchpad+ */+export const signalsScoutScratchpadSearch = async (+ projectId: string,+ params?: SignalsScoutScratchpadSearchParams,+ options?: RequestInit+): Promise<ScratchpadEntryApi[]> => {+ return apiMutator<ScratchpadEntryApi[]>(getSignalsScoutScratchpadSearchUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getSignalsScoutScratchpadRememberUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/scratchpad/`+}++/**+ * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place.+ * @summary Remember a scratchpad entry+ */+export const signalsScoutScratchpadRemember = async (+ projectId: string,+ rememberRequestApi: RememberRequestApi,+ options?: RequestInit+): Promise<ScratchpadEntryApi> => {+ return apiMutator<ScratchpadEntryApi>(getSignalsScoutScratchpadRememberUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(rememberRequestApi),+ })+}++export const getSignalsScoutScratchpadForgetUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/scratchpad/forget/`+}++/**+ * Delete an entry by key. Returns `deleted=false` if no row matched.+ * @summary Forget a scratchpad entry by key+ */+export const signalsScoutScratchpadForget = async (+ projectId: string,+ forgetRequestApi: ForgetRequestApi,+ options?: RequestInit+): Promise<ForgetResponseApi> => {+ return apiMutator<ForgetResponseApi>(getSignalsScoutScratchpadForgetUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(forgetRequestApi),+ })+}+export const getSignalsSourceConfigsListUrl = (projectId: string, params?: SignalsSourceConfigsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 0325bed14ab4..af2e951aaa64 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -18,6 +18,132 @@ export const SignalsProcessingPauseUpdateBody = /* @__PURE__ */ zod.object({.describe('Pause the grouping pipeline until this timestamp (ISO 8601).'),})+/**+ * 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+ */+export const signalsScoutEmitSignalBodyDescriptionMax = 50000++export const signalsScoutEmitSignalBodyWeightMin = 0+export const signalsScoutEmitSignalBodyWeightMax = 1++export const signalsScoutEmitSignalBodyConfidenceMin = 0+export const signalsScoutEmitSignalBodyConfidenceMax = 1++export const signalsScoutEmitSignalBodyEvidenceMax = 20++export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod+ .object({+ description: zod+ .string()+ .max(signalsScoutEmitSignalBodyDescriptionMax)+ .describe("Canonical evidence-bundle prose. Becomes the signal's `description`."),+ weight: zod+ .number()+ .min(signalsScoutEmitSignalBodyWeightMin)+ .max(signalsScoutEmitSignalBodyWeightMax)+ .describe("Agent's weight for the signal in [0, 1]. Drives ranking in the inbox."),+ confidence: zod+ .number()+ .min(signalsScoutEmitSignalBodyConfidenceMin)+ .max(signalsScoutEmitSignalBodyConfidenceMax)+ .describe("Agent's confidence the finding is real in [0, 1]. Persisted in `extra`."),+ evidence: zod+ .array(+ zod+ .object({+ source_product: zod+ .string()+ .describe(+ 'Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...).'+ ),+ summary: zod+ .string()+ .describe('One-sentence prose about why this evidence supports the finding.'),+ entity_id: zod+ .string()+ .nullish()+ .describe('Optional ID of the cited entity (issue id, recording id, log query id).'),+ })+ .describe('One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.')+ )+ .max(signalsScoutEmitSignalBodyEvidenceMax)+ .describe('Citations supporting the finding. Capped at 20 entries.'),+ hypothesis: zod.string().nullish().describe('Optional one-line hypothesis the finding tests.'),+ severity: zod+ .union([+ zod+ .enum(['P0', 'P1', 'P2', 'P3', 'P4'])+ .describe('\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional severity tag — one of P0, P1, P2, P3, P4. Informational only.\n\n\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'+ ),+ dedupe_keys: zod+ .array(zod.string())+ .optional()+ .describe('Optional keys for downstream dedupe (e.g. `error_tracking_issue:<id>`).'),+ time_range: zod+ .union([+ zod.object({+ date_from: zod.string().describe("ISO-8601 inclusive lower bound for the finding's window."),+ date_to: zod.string().describe("ISO-8601 inclusive upper bound for the finding's window."),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Optional time window the finding refers to.'),+ mcp_trace_id: zod.string().nullish().describe('Optional MCP trace id for cross-system debugging.'),+ finding_id: zod+ .string()+ .nullish()+ .describe(+ "Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal."+ ),+ })+ .describe('Request body for `emit-finding`. Run attribution is taken from the URL path.')++/**+ * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place.+ * @summary Remember a scratchpad entry+ */+export const signalsScoutScratchpadRememberBodyKeyMax = 300++export const signalsScoutScratchpadRememberBodyContentMax = 50000++export const SignalsScoutScratchpadRememberBody = /* @__PURE__ */ zod+ .object({+ key: zod+ .string()+ .max(signalsScoutScratchpadRememberBodyKeyMax)+ .describe('Agent-chosen semantic key. Re-using a key updates the existing entry in place.'),+ content: zod+ .string()+ .max(signalsScoutScratchpadRememberBodyContentMax)+ .describe('Prose to write. Read verbatim into future prompts.'),+ run_id: zod+ .uuid()+ .nullish()+ .describe(+ 'Run that authored this memory; persisted as `created_by_run_id` for lineage. Must reference a run on this same project — cross-project run UUIDs are rejected.'+ ),+ })+ .describe('Request body for `remember`.')++/**+ * Delete an entry by key. Returns `deleted=false` if no row matched.+ * @summary Forget a scratchpad entry by key+ */+export const signalsScoutScratchpadForgetBodyKeyMax = 300++export const SignalsScoutScratchpadForgetBody = /* @__PURE__ */ zod+ .object({+ key: zod.string().max(signalsScoutScratchpadForgetBodyKeyMax).describe('Memory key to delete.'),+ })+ .describe('Request body for `forget`.')+export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({source_product: zod.enum([diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex d9bee5ec6f69..d07c2456a629 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -119,6 +119,89 @@ tools:inbox-source-configs-update:operation: signals_source_configs_updateenabled: false+ signals-scout-emit-signal:+ operation: signals_scout_emit_signal+ enabled: true+ scopes:+ - signal_scout_internal:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Emit a finding for a run+ 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.+ signals-scout-runs-list:+ operation: signals_scout_runs_list+ enabled: true+ scopes:+ - signal_scout:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List recent scout runs+ description: >+ Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scout+ to dedupe against work other runs already covered. Pass `text` for a case-insensitive substring match on the+ run's `summary` (the primary dedupe key for runs that didn't emit findings). Pass `since` to scope to a+ recent window. Results capped at 100.+ signals-scout-runs-retrieve:+ operation: signals_scout_runs_retrieve+ enabled: true+ scopes:+ - signal_scout:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get a scout run by ID+ description: >+ Return the full `SignalScoutRun` row, including the agent's end-of-run `summary`. Status, timestamps, and+ error flow from the linked `tasks.TaskRun`; emitted findings live as `Signal` rows queryable by `source_id =+ run:<run_id>:finding:<finding_id>`. Strictly team-scoped — a UUID belonging to another team returns 404.+ signals-scout-scratchpad-forget:+ operation: signals_scout_scratchpad_forget+ enabled: true+ scopes:+ - signal_scout_internal:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Forget a scratchpad entry by key+ description: |+ Delete a scratchpad entry by key. Returns `deleted=false` if no row matched — the call is idempotent.+ signals-scout-scratchpad-remember:+ operation: signals_scout_scratchpad_remember+ enabled: true+ scopes:+ - signal_scout_internal:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Remember a scratchpad entry+ description: >+ Upsert a scratchpad entry keyed on `(team, key)` — re-using a key updates the existing entry in place, so+ this is an upsert rather than a strict create. Optionally pass `run_id` to record which run wrote it.+ signals-scout-scratchpad-search:+ operation: signals_scout_scratchpad_search+ enabled: true+ scopes:+ - signal_scout:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: Search the scout scratchpad+ description: >+ Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitive+ substring match on the entry's `content` and `key`. Results capped at 100.users-signal-autonomy-create:operation: users_signal_autonomy_createenabled: falsediff --git a/products/signals/skills/signals-scout-general/SKILL.md b/products/signals/skills/signals-scout-general/SKILL.mdnew file mode 100644index 000000000000..057925b65d38--- /dev/null+++ b/products/signals/skills/signals-scout-general/SKILL.md@@ -0,0 +1,69 @@+---+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.+---++# 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.++## What "good" looks like++A good run produces:++- **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.++A good run does _not_:++- 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.++## Workflow++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.++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.++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.++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.++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.++6. **Emit findings via `emit_finding()`.** Keep findings tight: one paragraph, a weight in+ `[0, 1]`, evidence list with concrete entity IDs.++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.++## Budget discipline++You have a hard cap of ~30 minutes and a small tool-call budget. Plan accordingly:++- 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.diff --git a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/services/custom_prompt_multi_turn_runner.pyindex c87b6fccf358..8c319566dd20 100644--- a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py+++ b/products/tasks/backend/services/custom_prompt_multi_turn_runner.py@@ -1,7 +1,9 @@from __future__ import annotationsimport time+import asyncioimport logging+from collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, TypeVar@@ -56,8 +58,16 @@ class MultiTurnSession:origin_product: Task.OriginProduct | None = None,signal_report_id: str | None = None,internal: bool = False,+ on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,) -> tuple[MultiTurnSession, _ModelT]:- """Start a multi-turn sandbox session and wait for the first response."""+ """Start a multi-turn sandbox session and wait for the first response.++ `on_task_run_created`, if given, is awaited once the `TaskRun` exists but+ BEFORE the agent's first turn runs. Callers that need a row linked to the+ TaskRun to be queryable during that first turn use this — e.g. the Signals+ scout creates its `SignalScoutRun` bridge here so first-turn finding emits+ can resolve the run by id instead of 404ing on a not-yet-created row.+ """task, task_run = await create_task_and_trigger(prompt,context,@@ -79,8 +89,20 @@ class MultiTurnSession:output_fn=output_fn,_workflow_handle=workflow_handle,)+ if on_task_run_created is not None:+ try:+ await on_task_run_created(task_run)+ except (Exception, asyncio.CancelledError) as e:+ # The TaskRun + sandbox workflow are already spawned. If the hook fails+ # (e.g. the caller's bridge-row insert hits a transient DB error), tear the+ # session down so we don't leak a running workflow/sandbox, then propagate.+ # CancelledError (BaseException, e.g. Temporal activity timeout) is caught too,+ # else the run stays IN_PROGRESS forever. Shield so the failure signal still+ # lands if the cancel re-fires mid-cleanup.+ await asyncio.shield(session.end(status="failed", error=str(e)))+ raise+ started_at = time.monotonic()try:- started_at = time.monotonic()last_message, _, session.log_lines_seen, session.printed_lines = await poll_for_turn(task_run, verbose=verbose, output_fn=output_fn, workflow_handle=workflow_handle)@@ -90,14 +112,15 @@ class MultiTurnSession:time.monotonic() - started_at,)parsed = cls._parse_and_validate(last_message, model, label="initial turn")- return session, parsed- except BaseException:- # Started the workflow but never returned a session for the caller to clean up.- logger.warning(- "multi_turn: startup failed for task=%s run=%s — cleaning up", task.id, task_run.id, exc_info=True- )- await session.end()+ except (Exception, asyncio.CancelledError) as e:+ # The session + sandbox workflow are already spawned, but `start()` is about to+ # raise so the caller never receives the session to run its own teardown. End it+ # here so a first-turn poll/parse failure (or a Temporal timeout, which raises+ # CancelledError — a BaseException) doesn't leave the run wedged in IN_PROGRESS.+ # Shield so the failure signal still lands if the cancel re-fires mid-cleanup.+ await asyncio.shield(session.end(status="failed", error=str(e)))raise+ return session, parsedasync def send_followup(self,@@ -174,12 +197,17 @@ class MultiTurnSession:json_data = extract_json_from_text(text=text, label=label)return model.model_validate(json_data)- async def end(self) -> None:- """Signal the workflow to shut down cleanly."""+ async def end(self, *, status: str = "completed", error: str | None = None) -> None:+ """Signal the workflow to shut down, recording `status` as the terminal TaskRun state.++ Pass `status="failed"` (with an `error` message) when ending because of an error, so+ the underlying `TaskRun` isn't recorded as `completed` — otherwise failed runs corrupt+ run-status metrics and mislead operational triage.+ """if not self._workflow_handle:raise RuntimeError("Workflow handle is not available in this session.")try:- await self._workflow_handle.signal(ProcessTaskWorkflow.complete_task, args=["completed", None])- logger.info("multi_turn: ended session run=%s", self.task_run.id)+ await self._workflow_handle.signal(ProcessTaskWorkflow.complete_task, args=[status, error])+ logger.info("multi_turn: ended session run=%s status=%s", self.task_run.id, status)except Exception:logger.warning("multi_turn: failed to signal completion run=%s", self.task_run.id, exc_info=True)diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex ada44f12b94c..c09d012f40cd 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4768,6 +4768,96 @@"readOnlyHint": true}},+ "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",+ "feature": "signals",+ "summary": "Emit a finding for a run",+ "title": "Emit a finding for a run",+ "required_scopes": ["signal_scout_internal:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "signals-scout-runs-list": {+ "description": "Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scout to dedupe against work other runs already covered. Pass `text` for a case-insensitive substring match on the run's `summary` (the primary dedupe key for runs that didn't emit findings). Pass `since` to scope to a recent window. Results capped at 100.",+ "category": "Signals",+ "feature": "signals",+ "summary": "List recent scout runs",+ "title": "List recent scout runs",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "signals-scout-runs-retrieve": {+ "description": "Return the full `SignalScoutRun` row, including the agent's end-of-run `summary`. Status, timestamps, and error flow from the linked `tasks.TaskRun`; emitted findings live as `Signal` rows queryable by `source_id = run:<run_id>:finding:<finding_id>`. Strictly team-scoped — a UUID belonging to another team returns 404.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get a scout run by ID",+ "title": "Get a scout run by ID",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "signals-scout-scratchpad-forget": {+ "description": "Delete a scratchpad entry by key. Returns `deleted=false` if no row matched — the call is idempotent.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Forget a scratchpad entry by key",+ "title": "Forget a scratchpad entry by key",+ "required_scopes": ["signal_scout_internal:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "signals-scout-scratchpad-remember": {+ "description": "Upsert a scratchpad entry keyed on `(team, key)` — re-using a key updates the existing entry in place, so this is an upsert rather than a strict create. Optionally pass `run_id` to record which run wrote it.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Remember a scratchpad entry",+ "title": "Remember a scratchpad entry",+ "required_scopes": ["signal_scout_internal:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "signals-scout-scratchpad-search": {+ "description": "Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitive substring match on the entry's `content` and `key`. Results capped at 100.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Search the scout scratchpad",+ "title": "Search the scout scratchpad",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"sql-variables-create": {"description": "Create a reusable SQL variable for HogQL queries. Provide a human-readable name and type. The code_name is generated from the name and is referenced in SQL as {variables.code_name}. For List variables, provide values as the allowed options.","category": "Data warehouse",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 47bcabf0c03c..9277fa26ab8c 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5235,6 +5235,96 @@"readOnlyHint": true}},+ "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",+ "feature": "signals",+ "summary": "Emit a finding for a run",+ "title": "Emit a finding for a run",+ "required_scopes": ["signal_scout_internal:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "signals-scout-runs-list": {+ "description": "Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scout to dedupe against work other runs already covered. Pass `text` for a case-insensitive substring match on the run's `summary` (the primary dedupe key for runs that didn't emit findings). Pass `since` to scope to a recent window. Results capped at 100.",+ "category": "Signals",+ "feature": "signals",+ "summary": "List recent scout runs",+ "title": "List recent scout runs",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "signals-scout-runs-retrieve": {+ "description": "Return the full `SignalScoutRun` row, including the agent's end-of-run `summary`. Status, timestamps, and error flow from the linked `tasks.TaskRun`; emitted findings live as `Signal` rows queryable by `source_id = run:<run_id>:finding:<finding_id>`. Strictly team-scoped — a UUID belonging to another team returns 404.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get a scout run by ID",+ "title": "Get a scout run by ID",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "signals-scout-scratchpad-forget": {+ "description": "Delete a scratchpad entry by key. Returns `deleted=false` if no row matched — the call is idempotent.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Forget a scratchpad entry by key",+ "title": "Forget a scratchpad entry by key",+ "required_scopes": ["signal_scout_internal:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "signals-scout-scratchpad-remember": {+ "description": "Upsert a scratchpad entry keyed on `(team, key)` — re-using a key updates the existing entry in place, so this is an upsert rather than a strict create. Optionally pass `run_id` to record which run wrote it.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Remember a scratchpad entry",+ "title": "Remember a scratchpad entry",+ "required_scopes": ["signal_scout_internal:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "signals-scout-scratchpad-search": {+ "description": "Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitive substring match on the entry's `content` and `key`. Results capped at 100.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Search the scout scratchpad",+ "title": "Search the scout scratchpad",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"sql-variables-create": {"description": "Create a reusable SQL variable for HogQL queries. Provide a human-readable name and type. The code_name is generated from the name and is referenced in SQL as {variables.code_name}. For List variables, provide values as the allowed options.","category": "Data warehouse",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 717e2fc5f7a6..3c9f284e0e08 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14043,6 +14043,95 @@ export namespace Schemas {design?: unknown;}+ /**+ * One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.+ */+ export interface EvidenceEntry {+ /** Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...). */+ source_product: string;+ /** One-sentence prose about why this evidence supports the finding. */+ summary: string;+ /**+ * Optional ID of the cited entity (issue id, recording id, log query id).+ * @nullable+ */+ entity_id?: string | null;+ }++ export interface TimeRange {+ /** ISO-8601 inclusive lower bound for the finding's window. */+ date_from: string;+ /** ISO-8601 inclusive upper bound for the finding's window. */+ date_to: string;+ }++ /**+ * Request body for `emit-finding`. Run attribution is taken from the URL path.+ */+ export interface EmitFindingRequest {+ /**+ * Canonical evidence-bundle prose. Becomes the signal's `description`.+ * @maxLength 50000+ */+ description: string;+ /**+ * Agent's weight for the signal in [0, 1]. Drives ranking in the inbox.+ * @minimum 0+ * @maximum 1+ */+ weight: number;+ /**+ * Agent's confidence the finding is real in [0, 1]. Persisted in `extra`.+ * @minimum 0+ * @maximum 1+ */+ confidence: number;+ /**+ * Citations supporting the finding. Capped at 20 entries.+ * @maxItems 20+ */+ evidence: EvidenceEntry[];+ /**+ * Optional one-line hypothesis the finding tests.+ * @nullable+ */+ hypothesis?: string | null;+ /** Optional severity tag — one of P0, P1, P2, P3, P4. Informational only.++ * `P0` - P0+ * `P1` - P1+ * `P2` - P2+ * `P3` - P3+ * `P4` - P4 */+ severity?: AutonomyPriorityEnum | null;+ /** Optional keys for downstream dedupe (e.g. `error_tracking_issue:<id>`). */+ dedupe_keys?: string[];+ /** Optional time window the finding refers to. */+ time_range?: TimeRange | null;+ /**+ * Optional MCP trace id for cross-system debugging.+ * @nullable+ */+ mcp_trace_id?: string | null;+ /**+ * Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal.+ * @nullable+ */+ finding_id?: string | null;+ }++ export interface EmitFindingResponse {+ /** Stable id for the finding (echoed back from request, or generated). */+ finding_id: string;+ /** Whether `emit_signal` was actually fired. */+ emitted: boolean;+ /**+ * `ai_processing_not_approved` | `source_disabled` | null when emitted normally.+ * @nullable+ */+ skipped_reason: string | null;+ }+export interface EndExperiment {/** The conclusion of the experiment.@@ -17983,6 +18072,22 @@ export namespace Schemas {refreshing: boolean;}+ /**+ * Request body for `forget`.+ */+ export interface ForgetRequest {+ /**+ * Memory key to delete.+ * @maxLength 300+ */+ key: string;+ }++ export interface ForgetResponse {+ /** Whether a row was actually removed (false if the key didn't exist). */+ deleted: boolean;+ }+export type GenerateRequestStepsItem = { [key: string]: unknown };export interface GenerateRequest {@@ -35770,6 +35875,27 @@ export namespace Schemas {ci_rerun_error?: string | null;}+ /**+ * Request body for `remember`.+ */+ export interface RememberRequest {+ /**+ * Agent-chosen semantic key. Re-using a key updates the existing entry in place.+ * @maxLength 300+ */+ key: string;+ /**+ * Prose to write. Read verbatim into future prompts.+ * @maxLength 50000+ */+ content: string;+ /**+ * Run that authored this memory; persisted as `created_by_run_id` for lineage. Must reference a run on this same project — cross-project run UUIDs are rejected.+ * @nullable+ */+ run_id?: string | null;+ }+export interface ReorderTilesRequest {/*** Array of tile IDs in the desired display order (top to bottom, left to right).@@ -36031,6 +36157,31 @@ export namespace Schemas {base_version?: number;}+ /**+ * `SignalScratchpad` projection used by `search-memory` and `remember`.+ */+ export interface ScratchpadEntry {+ /** Agent-chosen semantic key, unique per team. */+ key: string;+ /** Prose content for prompt injection. */+ content: string;+ /**+ * ISO-8601 creation timestamp.+ * @nullable+ */+ created_at: string | null;+ /**+ * ISO-8601 last-write timestamp.+ * @nullable+ */+ updated_at: string | null;+ /**+ * Run that wrote this entry, or null if human-authored.+ * @nullable+ */+ created_by_run_id: string | null;+ }+/*** * `none` - none* `warning` - warning@@ -36323,6 +36474,86 @@ export namespace Schemas {release_to_everyone?: boolean;}+ /**+ * Full `SignalScoutRun` projection used by `get-run`. Same shape as the summary+ today; kept distinct so future detail-only extensions (linked Signal rows,+ LLMA token-cost join) can land here without bloating the list response.+ */+ export interface SignalScoutRunDetail {+ /** UUID of the bridge row. */+ run_id: string;+ /** Canonical skill name the run executed (e.g. `signals-scout-general`). */+ skill_name: string;+ /** Skill version snapshotted at run start. */+ skill_version: number;+ /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */+ status: string;+ /** ISO-8601 timestamp the TaskRun was created. */+ started_at: string;+ /**+ * ISO-8601 timestamp the TaskRun completed; null while still running.+ * @nullable+ */+ completed_at: string | null;+ /**+ * UUID of the Tasks `Task` the scout span ran inside.+ * @nullable+ */+ task_id?: string | null;+ /**+ * UUID of the Tasks `TaskRun`. Pairs with `task_id` to deep-link.+ * @nullable+ */+ task_run_id?: string | null;+ /**+ * Relative deep-link to the Tasks UI for this run, e.g. `/project/{team_id}/tasks/{task_id}?runId={task_run_id}`.+ * @nullable+ */+ task_url?: string | null;+ /** One-paragraph close-out the scout wrote at end-of-run. Empty string for runs that errored before close-out. The dedupe key for non-emitting runs. */+ summary: string;+ }++ /**+ * Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.++ Status and timestamps flow from the linked `tasks.TaskRun`.+ */+ export interface SignalScoutRunSummary {+ /** UUID of the bridge row. */+ run_id: string;+ /** Canonical skill name the run executed (e.g. `signals-scout-general`). */+ skill_name: string;+ /** Skill version snapshotted at run start. */+ skill_version: number;+ /** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */+ status: string;+ /** ISO-8601 timestamp the TaskRun was created. */+ started_at: string;+ /**+ * ISO-8601 timestamp the TaskRun completed; null while still running.+ * @nullable+ */+ completed_at: string | null;+ /**+ * UUID of the Tasks `Task` the scout span ran inside.+ * @nullable+ */+ task_id?: string | null;+ /**+ * UUID of the Tasks `TaskRun`. Pairs with `task_id` to deep-link.+ * @nullable+ */+ task_run_id?: string | null;+ /**+ * Relative deep-link to the Tasks UI for this run, e.g. `/project/{team_id}/tasks/{task_id}?runId={task_run_id}`.+ * @nullable+ */+ task_url?: string | null;+ /** One-paragraph close-out the scout wrote at end-of-run. Empty string for runs that errored before close-out. The dedupe key for non-emitting runs. */+ summary: string;+ }+export interface _User {readonly id: number;readonly uuid: string;@@ -47362,6 +47593,41 @@ export namespace Schemas {suggested_reviewers?: string;};+ export type SignalsScoutRunsListParams = {+ /**+ * ISO-8601 inclusive lower bound on `created_at`. Omit to skip the lower bound.+ */+ date_from?: string;+ /**+ * ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).+ */+ date_to?: string;+ /**+ * Max rows to return (default 20, hard cap 100).+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ /**+ * Case-insensitive substring match on the scout's end-of-run `summary`. Omit to skip the filter.+ * @minLength 1+ */+ text?: string;+ };++ export type SignalsScoutScratchpadSearchParams = {+ /**+ * Max rows to return (default 20, hard cap 100).+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ /**+ * ILIKE substring match against `content`. Omit to return the most recent entries.+ */+ text?: string;+ };+export type SignalsSourceConfigsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex fad3bdc2fcb0..90345233f081 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 4 enabled ops+ * PostHog API - MCP 10 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -55,6 +55,235 @@ export const SignalsReportsRetrieveParams = /* @__PURE__ */ zod.object({),})+/**+ * Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scout to dedupe against work other runs already covered. ILIKE matches on `summary`. `date_from` / `date_to` are a half-open window on `created_at` (`>= date_from`, `< date_to`); pass `date_to` on subsequent calls to walk past the 100-row cap. Results capped at 100.+ * @summary Search recent agent runs+ */+export const SignalsScoutRunsListParams = /* @__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/."+ ),+})++export const signalsScoutRunsListQueryLimitMax = 100++export const SignalsScoutRunsListQueryParams = /* @__PURE__ */ zod.object({+ date_from: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('ISO-8601 inclusive lower bound on `created_at`. Omit to skip the lower bound.'),+ date_to: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).'+ ),+ limit: zod+ .number()+ .min(1)+ .max(signalsScoutRunsListQueryLimitMax)+ .optional()+ .describe('Max rows to return (default 20, hard cap 100).'),+ text: zod+ .string()+ .min(1)+ .optional()+ .describe("Case-insensitive substring match on the scout's end-of-run `summary`. Omit to skip the filter."),+})++/**+ * Return the full `SignalScoutRun` row. Status, timing, and error flow from the linked `tasks.TaskRun`. Strictly team-scoped — a UUID belonging to another team returns 404.+ * @summary Get a run by ID+ */+export const SignalsScoutRunsRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this Signal scout run.'),+ 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/."+ ),+})++/**+ * 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+ */+export const SignalsScoutEmitSignalParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this Signal scout run.'),+ 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 signalsScoutEmitSignalBodyDescriptionMax = 50000++export const signalsScoutEmitSignalBodyWeightMin = 0+export const signalsScoutEmitSignalBodyWeightMax = 1++export const signalsScoutEmitSignalBodyConfidenceMin = 0+export const signalsScoutEmitSignalBodyConfidenceMax = 1++export const signalsScoutEmitSignalBodyEvidenceMax = 20++export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod+ .object({+ description: zod+ .string()+ .max(signalsScoutEmitSignalBodyDescriptionMax)+ .describe("Canonical evidence-bundle prose. Becomes the signal's `description`."),+ weight: zod+ .number()+ .min(signalsScoutEmitSignalBodyWeightMin)+ .max(signalsScoutEmitSignalBodyWeightMax)+ .describe("Agent's weight for the signal in [0, 1]. Drives ranking in the inbox."),+ confidence: zod+ .number()+ .min(signalsScoutEmitSignalBodyConfidenceMin)+ .max(signalsScoutEmitSignalBodyConfidenceMax)+ .describe("Agent's confidence the finding is real in [0, 1]. Persisted in `extra`."),+ evidence: zod+ .array(+ zod+ .object({+ source_product: zod+ .string()+ .describe(+ 'Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...).'+ ),+ summary: zod+ .string()+ .describe('One-sentence prose about why this evidence supports the finding.'),+ entity_id: zod+ .string()+ .nullish()+ .describe('Optional ID of the cited entity (issue id, recording id, log query id).'),+ })+ .describe('One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.')+ )+ .max(signalsScoutEmitSignalBodyEvidenceMax)+ .describe('Citations supporting the finding. Capped at 20 entries.'),+ hypothesis: zod.string().nullish().describe('Optional one-line hypothesis the finding tests.'),+ severity: zod+ .union([+ zod+ .enum(['P0', 'P1', 'P2', 'P3', 'P4'])+ .describe('* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional severity tag — one of P0, P1, P2, P3, P4. Informational only.\n\n* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4'+ ),+ dedupe_keys: zod+ .array(zod.string())+ .optional()+ .describe('Optional keys for downstream dedupe (e.g. `error_tracking_issue:<id>`).'),+ time_range: zod+ .union([+ zod.object({+ date_from: zod.string().describe("ISO-8601 inclusive lower bound for the finding's window."),+ date_to: zod.string().describe("ISO-8601 inclusive upper bound for the finding's window."),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Optional time window the finding refers to.'),+ mcp_trace_id: zod.string().nullish().describe('Optional MCP trace id for cross-system debugging.'),+ finding_id: zod+ .string()+ .nullish()+ .describe(+ "Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal."+ ),+ })+ .describe('Request body for `emit-finding`. Run attribution is taken from the URL path.')++/**+ * Return `SignalScratchpad` entries for this project. ILIKE matches on `content` and `key`.+ * @summary Search the scout scratchpad+ */+export const SignalsScoutScratchpadSearchParams = /* @__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/."+ ),+})++export const signalsScoutScratchpadSearchQueryLimitMax = 100++export const SignalsScoutScratchpadSearchQueryParams = /* @__PURE__ */ zod.object({+ limit: zod+ .number()+ .min(1)+ .max(signalsScoutScratchpadSearchQueryLimitMax)+ .optional()+ .describe('Max rows to return (default 20, hard cap 100).'),+ text: zod+ .string()+ .optional()+ .describe('ILIKE substring match against `content`. Omit to return the most recent entries.'),+})++/**+ * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place.+ * @summary Remember a scratchpad entry+ */+export const SignalsScoutScratchpadRememberParams = /* @__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/."+ ),+})++export const signalsScoutScratchpadRememberBodyKeyMax = 300++export const signalsScoutScratchpadRememberBodyContentMax = 50000++export const SignalsScoutScratchpadRememberBody = /* @__PURE__ */ zod+ .object({+ key: zod+ .string()+ .max(signalsScoutScratchpadRememberBodyKeyMax)+ .describe('Agent-chosen semantic key. Re-using a key updates the existing entry in place.'),+ content: zod+ .string()+ .max(signalsScoutScratchpadRememberBodyContentMax)+ .describe('Prose to write. Read verbatim into future prompts.'),+ run_id: zod+ .uuid()+ .nullish()+ .describe(+ 'Run that authored this memory; persisted as `created_by_run_id` for lineage. Must reference a run on this same project — cross-project run UUIDs are rejected.'+ ),+ })+ .describe('Request body for `remember`.')++/**+ * Delete an entry by key. Returns `deleted=false` if no row matched.+ * @summary Forget a scratchpad entry by key+ */+export const SignalsScoutScratchpadForgetParams = /* @__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/."+ ),+})++export const signalsScoutScratchpadForgetBodyKeyMax = 300++export const SignalsScoutScratchpadForgetBody = /* @__PURE__ */ zod+ .object({+ key: zod.string().max(signalsScoutScratchpadForgetBodyKeyMax).describe('Memory key to delete.'),+ })+ .describe('Request body for `forget`.')+export const SignalsSourceConfigsListParams = /* @__PURE__ */ zod.object({project_id: zod.string()diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex f90a7a7d98b5..9088e81aec20 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -151,6 +151,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['session_recording_playlist:write','sharing_configuration:read','sharing_configuration:write',+ 'signal_scout:read',+ 'signal_scout:write','streamlit_app:read','streamlit_app:write','subscription:read',diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 52fee4405e62..b2f4eeccc37c 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -5,6 +5,13 @@ import type { Schemas } from '@/api/generated'import {SignalsReportsListQueryParams,SignalsReportsRetrieveParams,+ SignalsScoutEmitSignalBody,+ SignalsScoutEmitSignalParams,+ SignalsScoutRunsListQueryParams,+ SignalsScoutRunsRetrieveParams,+ SignalsScoutScratchpadForgetBody,+ SignalsScoutScratchpadRememberBody,+ SignalsScoutScratchpadSearchQueryParams,SignalsSourceConfigsListQueryParams,SignalsSourceConfigsRetrieveParams,} from '@/generated/signals/api'@@ -137,9 +144,177 @@ const inboxSourceConfigsRetrieve = (): ToolBase<},})+const SignalsScoutEmitSignalSchema = SignalsScoutEmitSignalParams.omit({ project_id: true }).extend(+ SignalsScoutEmitSignalBody.shape+)++const signalsScoutEmitSignal = (): ToolBase<typeof SignalsScoutEmitSignalSchema, Schemas.EmitFindingResponse> => ({+ name: 'signals-scout-emit-signal',+ schema: SignalsScoutEmitSignalSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutEmitSignalSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.weight !== undefined) {+ body['weight'] = params.weight+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.evidence !== undefined) {+ body['evidence'] = params.evidence+ }+ if (params.hypothesis !== undefined) {+ body['hypothesis'] = params.hypothesis+ }+ if (params.severity !== undefined) {+ body['severity'] = params.severity+ }+ if (params.dedupe_keys !== undefined) {+ body['dedupe_keys'] = params.dedupe_keys+ }+ if (params.time_range !== undefined) {+ body['time_range'] = params.time_range+ }+ if (params.mcp_trace_id !== undefined) {+ body['mcp_trace_id'] = params.mcp_trace_id+ }+ if (params.finding_id !== undefined) {+ body['finding_id'] = params.finding_id+ }+ const result = await context.api.request<Schemas.EmitFindingResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.id))}/emit-signal/`,+ body,+ })+ return result+ },+})++const SignalsScoutRunsListSchema = SignalsScoutRunsListQueryParams++const signalsScoutRunsList = (): ToolBase<+ typeof SignalsScoutRunsListSchema,+ WithPostHogUrl<Schemas.SignalScoutRunSummary[]>+> => ({+ name: 'signals-scout-runs-list',+ schema: SignalsScoutRunsListSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutRunsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SignalScoutRunSummary[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/`,+ query: {+ date_from: params.date_from,+ date_to: params.date_to,+ limit: params.limit,+ text: params.text,+ },+ })+ return await withPostHogUrl(context, result, '/inbox')+ },+})++const SignalsScoutRunsRetrieveSchema = SignalsScoutRunsRetrieveParams.omit({ project_id: true })++const signalsScoutRunsRetrieve = (): ToolBase<typeof SignalsScoutRunsRetrieveSchema, Schemas.SignalScoutRunDetail> => ({+ name: 'signals-scout-runs-retrieve',+ schema: SignalsScoutRunsRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutRunsRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SignalScoutRunDetail>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const SignalsScoutScratchpadForgetSchema = SignalsScoutScratchpadForgetBody++const signalsScoutScratchpadForget = (): ToolBase<+ typeof SignalsScoutScratchpadForgetSchema,+ Schemas.ForgetResponse+> => ({+ name: 'signals-scout-scratchpad-forget',+ schema: SignalsScoutScratchpadForgetSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutScratchpadForgetSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.key !== undefined) {+ body['key'] = params.key+ }+ const result = await context.api.request<Schemas.ForgetResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/scratchpad/forget/`,+ body,+ })+ return result+ },+})++const SignalsScoutScratchpadRememberSchema = SignalsScoutScratchpadRememberBody++const signalsScoutScratchpadRemember = (): ToolBase<+ typeof SignalsScoutScratchpadRememberSchema,+ Schemas.ScratchpadEntry+> => ({+ name: 'signals-scout-scratchpad-remember',+ schema: SignalsScoutScratchpadRememberSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutScratchpadRememberSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.key !== undefined) {+ body['key'] = params.key+ }+ if (params.content !== undefined) {+ body['content'] = params.content+ }+ if (params.run_id !== undefined) {+ body['run_id'] = params.run_id+ }+ const result = await context.api.request<Schemas.ScratchpadEntry>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/scratchpad/`,+ body,+ })+ return result+ },+})++const SignalsScoutScratchpadSearchSchema = SignalsScoutScratchpadSearchQueryParams++const signalsScoutScratchpadSearch = (): ToolBase<+ typeof SignalsScoutScratchpadSearchSchema,+ WithPostHogUrl<Schemas.ScratchpadEntry[]>+> => ({+ name: 'signals-scout-scratchpad-search',+ schema: SignalsScoutScratchpadSearchSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutScratchpadSearchSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ScratchpadEntry[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/scratchpad/`,+ query: {+ limit: params.limit,+ text: params.text,+ },+ })+ return await withPostHogUrl(context, result, '/inbox')+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'inbox-reports-list': inboxReportsList,'inbox-reports-retrieve': inboxReportsRetrieve,'inbox-source-configs-list': inboxSourceConfigsList,'inbox-source-configs-retrieve': inboxSourceConfigsRetrieve,+ 'signals-scout-emit-signal': signalsScoutEmitSignal,+ 'signals-scout-runs-list': signalsScoutRunsList,+ 'signals-scout-runs-retrieve': signalsScoutRunsRetrieve,+ 'signals-scout-scratchpad-forget': signalsScoutScratchpadForget,+ 'signals-scout-scratchpad-remember': signalsScoutScratchpadRemember,+ 'signals-scout-scratchpad-search': signalsScoutScratchpadSearch,}diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsonindex 681819416ea1..4c16c02f74ed 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\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- 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-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-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-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/common/signals-scout-emit-signal.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-emit-signal.jsonnew file mode 100644index 000000000000..3cbff0731c88--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-emit-signal.json@@ -0,0 +1,134 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "confidence": {+ "description": "Agent's confidence the finding is real in [0, 1]. Persisted in `extra`.",+ "maximum": 1,+ "minimum": 0,+ "type": "number"+ },+ "dedupe_keys": {+ "description": "Optional keys for downstream dedupe (e.g. `error_tracking_issue:<id>`).",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "description": {+ "description": "Canonical evidence-bundle prose. Becomes the signal's `description`.",+ "maxLength": 50000,+ "type": "string"+ },+ "evidence": {+ "description": "Citations supporting the finding. Capped at 20 entries.",+ "items": {+ "description": "One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.",+ "properties": {+ "entity_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional ID of the cited entity (issue id, recording id, log query id)."+ },+ "source_product": {+ "description": "Source the citation came from (`error_tracking`, `session_replay`, `logs`, ...).",+ "type": "string"+ },+ "summary": {+ "description": "One-sentence prose about why this evidence supports the finding.",+ "type": "string"+ }+ },+ "required": ["source_product", "summary"],+ "type": "object"+ },+ "maxItems": 20,+ "type": "array"+ },+ "finding_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Stable id for this finding, baked into the signal's source_id for traceability. NOT a dedupe key — re-emitting the same id creates another signal."+ },+ "hypothesis": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional one-line hypothesis the finding tests."+ },+ "id": {+ "description": "A UUID string identifying this Signal scout run.",+ "type": "string"+ },+ "mcp_trace_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional MCP trace id for cross-system debugging."+ },+ "severity": {+ "anyOf": [+ {+ "description": "* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4",+ "enum": ["P0", "P1", "P2", "P3", "P4"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional severity tag — one of P0, P1, P2, P3, P4. Informational only.\n\n* `P0` - P0\n* `P1` - P1\n* `P2` - P2\n* `P3` - P3\n* `P4` - P4"+ },+ "time_range": {+ "anyOf": [+ {+ "properties": {+ "date_from": {+ "description": "ISO-8601 inclusive lower bound for the finding's window.",+ "type": "string"+ },+ "date_to": {+ "description": "ISO-8601 inclusive upper bound for the finding's window.",+ "type": "string"+ }+ },+ "required": ["date_from", "date_to"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional time window the finding refers to."+ },+ "weight": {+ "description": "Agent's weight for the signal in [0, 1]. Drives ranking in the inbox.",+ "maximum": 1,+ "minimum": 0,+ "type": "number"+ }+ },+ "required": ["id", "description", "weight", "confidence", "evidence"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-runs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-runs-list.jsonnew file mode 100644index 000000000000..0ea252c1bfdd--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-runs-list.json@@ -0,0 +1,29 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "date_from": {+ "description": "ISO-8601 inclusive lower bound on `created_at`. Omit to skip the lower bound.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "date_to": {+ "description": "ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "limit": {+ "description": "Max rows to return (default 20, hard cap 100).",+ "maximum": 100,+ "minimum": 1,+ "type": "number"+ },+ "text": {+ "description": "Case-insensitive substring match on the scout's end-of-run `summary`. Omit to skip the filter.",+ "minLength": 1,+ "type": "string"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-runs-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-runs-retrieve.jsonnew file mode 100644index 000000000000..6bf8266d32be--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-runs-retrieve.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this Signal scout run.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-forget.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-forget.jsonnew file mode 100644index 000000000000..4d511752dc09--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-forget.json@@ -0,0 +1,13 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "description": "Request body for `forget`.",+ "properties": {+ "key": {+ "description": "Memory key to delete.",+ "maxLength": 300,+ "type": "string"+ }+ },+ "required": ["key"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-remember.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-remember.jsonnew file mode 100644index 000000000000..ad5ff7f8338c--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-remember.json@@ -0,0 +1,31 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "description": "Request body for `remember`.",+ "properties": {+ "content": {+ "description": "Prose to write. Read verbatim into future prompts.",+ "maxLength": 50000,+ "type": "string"+ },+ "key": {+ "description": "Agent-chosen semantic key. Re-using a key updates the existing entry in place.",+ "maxLength": 300,+ "type": "string"+ },+ "run_id": {+ "anyOf": [+ {+ "format": "uuid",+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Run that authored this memory; persisted as `created_by_run_id` for lineage. Must reference a run on this same project — cross-project run UUIDs are rejected."+ }+ },+ "required": ["key", "content"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-search.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-search.jsonnew file mode 100644index 000000000000..7f558d76c7ed--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-scratchpad-search.json@@ -0,0 +1,16 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "limit": {+ "description": "Max rows to return (default 20, hard cap 100).",+ "maximum": 100,+ "minimum": 1,+ "type": "number"+ },+ "text": {+ "description": "ILIKE substring match against `content`. Omit to return the most recent entries.",+ "type": "string"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 1d0c8f437200..3b14f2672e78 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -364,6 +364,11 @@ function expectAllToolsHaveNoRequiredScopes(toolNames: string[]): void {}describe('OAUTH_SCOPES_SUPPORTED completeness', () => {+ // Minted directly into a server-issued token, never advertised via OAuth metadata+ // (mirrors INTERNAL_API_SCOPE_OBJECTS in posthog/scopes.py). Tools may require them, but+ // they are intentionally absent from OAUTH_SCOPES_SUPPORTED, so exclude them here.+ const SERVER_MINT_ONLY_SCOPES = new Set(['signal_scout_internal:read', 'signal_scout_internal:write'])+it('should include every scope referenced in tool definitions', () => {const supportedScopes = new Set<string>(OAUTH_SCOPES_SUPPORTED)@@ -379,7 +384,9 @@ describe('OAUTH_SCOPES_SUPPORTED completeness', () => {}}- const missing = [...scopesFromTools].filter((s) => !supportedScopes.has(s)).sort()+ const missing = [...scopesFromTools]+ .filter((s) => !supportedScopes.has(s) && !SERVER_MINT_ONLY_SCOPES.has(s))+ .sort()expect(missing,diff --git a/tach.toml b/tach.tomlindex 1a792719a92f..aab36ba5d6b7 100644--- a/tach.toml+++ b/tach.toml@@ -496,6 +496,7 @@ layer = "modules"path = "products.signals"depends_on = ["posthog",+ "products.ai_observability","products.data_warehouse","products.error_tracking","products.tasks", "products.warehouse_sources",