: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): project profile (4/7) (#57758)
Andrew Maguiree5e7bfaf4a30
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 39867aafbf59..31532a438f74 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -202,6 +202,7 @@ rules:|SignalScoutConfig|SignalScoutRun|SignalScratchpad+ |SignalProjectProfile|SingleSessionSummary|SlackThreadTaskMapping|SourceBatch@@ -429,6 +430,7 @@ rules:|SignalScoutConfig|SignalScoutRun|SignalScratchpad+ |SignalProjectProfile|SingleSessionSummary|SlackThreadTaskMapping|SourceBatchdiff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 68cdc7a5951c..59f97f799cde 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -1201,10 +1201,14 @@ projects_router.register()# 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+# memory, project profile) 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 ( # noqa: E402+ SignalProjectProfileViewSet,+ SignalScoutRunViewSet,+ SignalScratchpadViewSet,+)projects_router.register(r"signals/scout/runs",@@ -1218,6 +1222,12 @@ projects_router.register("environment_signals_scout_scratchpad",["team_id"],)+projects_router.register(+ r"signals/scout/project_profile",+ SignalProjectProfileViewSet,+ "environment_signals_scout_project_profile",+ ["team_id"],+)environments_router.register(r"quick_filters",diff --git a/products/signals/backend/migrations/0024_signalprojectprofile.py b/products/signals/backend/migrations/0024_signalprojectprofile.pynew file mode 100644index 000000000000..d4c0e74d16aa--- /dev/null+++ b/products/signals/backend/migrations/0024_signalprojectprofile.py@@ -0,0 +1,57 @@+# Generated by Django 5.2.13 on 2026-05-01 16:32++import django.db.models.manager+import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1133_alter_integration_kind"),+ ("signals", "0023_signalscoutrun_summary"),+ ]++ operations = [+ migrations.CreateModel(+ name="SignalProjectProfile",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("computed_at", models.DateTimeField(auto_now_add=True)),+ ("expires_at", models.DateTimeField()),+ ("source_version", models.CharField(max_length=40)),+ ("payload", models.JSONField(blank=True, default=dict)),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="signal_project_profiles",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "verbose_name": "Signal project profile",+ "verbose_name_plural": "Signal project profiles",+ "default_manager_name": "all_teams",+ "indexes": [+ models.Index(+ fields=["team", "-computed_at"],+ name="signal_proj_profile_recent_idx",+ )+ ],+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 7029fcc273a8..5401201c1f87 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0023_signalscoutrun_summary+0024_signalprojectprofilediff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex dc552a3f3ee3..548c23557e06 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -528,3 +528,52 @@ class SignalScratchpad(TeamScopedRootMixin, UUIDModel):constraints = [models.UniqueConstraint(fields=["team", "key"], name="signal_scratchpad_unique_team_key"),]+++class SignalProjectProfile(TeamScopedRootMixin, UUIDModel):+ """Deterministic snapshot of "what's true about this project" — agent orientation surface.++ One row per (team, computed_at). Time-series so Phase 7 can diff a new profile against+ the previous row to populate `payload.deltas`. v1 (Phase 4a) writes inventory only;+ Phase 7 layers on deltas, activity_notes, and an LLM narrative section.++ Profile is the *deterministic ground truth* about a project (computed from authoritative+ tables). Distinct from `SignalScratchpad`, which is the *agent's inferred learnings* (possibly+ wrong, TTL'd). Profile feeds memory; memory does not update profile.+ """++ # See `SignalScoutConfig.all_teams` for the rationale on the unscoped sibling manager+ # and `default_manager_name`.+ all_teams = models.Manager() # noqa: DJ012++ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ related_name="signal_project_profiles",+ )+ computed_at = models.DateTimeField(auto_now_add=True)+ # Soft TTL — `get_project_profile` treats rows past expiry as cache misses and recomputes.+ # Aligned to the coordinator tick (`PROFILE_TTL`) so an active team's agent runs see+ # ground-truth that's at most one tick stale. Callers that know the underlying data+ # just changed can punch through the cache via `get_project_profile(force_refresh=True)`.+ expires_at = models.DateTimeField()+ # Bumps when the inventory schema changes meaningfully so `get_project_profile` can+ # invalidate stale rows without a manual backfill.+ source_version = models.CharField(max_length=40)+ # Structured payload: `{inventory: {...}}` in v1; `deltas`, `activity_notes`, `narrative`+ # slots reserved for Phase 7. Stored as jsonb because the payload is written by one+ # builder, read whole, and never field-queried — relational columns would buy no query+ # benefit and a migration per section as coverage grows. Not schemaless, though:+ # `build_inventory` returns a validated `Inventory` model (see+ # `scout_harness/profile/schema.py`), so the jsonb is schema-backed on write.+ payload = models.JSONField(default=dict, blank=True)++ class Meta:+ verbose_name = "Signal project profile"+ verbose_name_plural = "Signal project profiles"+ default_manager_name = "all_teams"+ indexes = [+ # `get_project_profile` reads the newest non-expired row for a team — supports the+ # ORDER BY computed_at DESC LIMIT 1 lookup pattern.+ models.Index(fields=["team", "-computed_at"], name="signal_proj_profile_recent_idx"),+ ]diff --git a/products/signals/backend/scout_harness/profile/__init__.py b/products/signals/backend/scout_harness/profile/__init__.pynew file mode 100644index 000000000000..346732542abd--- /dev/null+++ b/products/signals/backend/scout_harness/profile/__init__.py@@ -0,0 +1,11 @@+"""Project profile aggregator — reads authoritative sources to build the inventory layer.++The package is intentionally separate from `scout_harness/tools/` because the aggregator+grows over time (Phase 7 layers deltas, activity_notes, and an LLM narrative on top of+inventory). Keeping it module-scoped lets the source-readers stay small and testable.+"""++from products.signals.backend.scout_harness.profile.builders import INVENTORY_SOURCE_VERSION, build_inventory+from products.signals.backend.scout_harness.profile.schema import Inventory++__all__ = ["INVENTORY_SOURCE_VERSION", "Inventory", "build_inventory"]diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pynew file mode 100644index 000000000000..491fdad787e3--- /dev/null+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -0,0 +1,681 @@+"""Inventory builder for the project profile.++Reads only authoritative tables — no scout-style inference. Each source-reader is its own+private function so individual sources can be added, swapped, or stubbed out without+touching the orchestration. Output is a validated `Inventory` model (see `schema.py`);+the tools layer dumps it into the `SignalProjectProfile.payload` jsonb column.++Sections fall into three layers. **Capability / configured (sticky)** — `project_context`,+`products_in_use`, `product_intents`, `integrations`, `external_data_sources`,+`signal_source_configs`. Answers "what's turned on." **Aggregated recency** —+`recent_activity` (per-scope counts off the activity log, cross-cutting orientation+across every entity type). **Per-entity recent inventory** — `recent_dashboards`,+`recent_surveys`, `recent_feature_flags`, `recent_experiments`, `recent_alerts`,+`recent_hog_functions`, `recent_hog_flows`, `recent_notebooks`, `recent_cohorts`,+`recent_actions`, plus `top_events` and `existing_inbox_reports`. Light shape per+entity: counts + 5 most-recently-modified items with name + status + timestamp. The+agent gets MCP tools (`surveys-get-all`, `feature-flag-get-all`, `experiment-list`,+`insights-trending-retrieve`, etc.) for deep drilldowns; the profile only orients.++Per-entity ordering picks `updated_at` / `last_modified_at` where available, falling+back to `created_at` for entities that don't track modifications (cohorts, alerts).+"""++from __future__ import annotations++import logging+from datetime import timedelta+from typing import Any++from django.db.models import Count, F, Max, Q+from django.utils import timezone++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.cohort.cohort import Cohort+from posthog.models.integration import Integration+from posthog.models.product_intent.product_intent import ProductIntent+from posthog.models.team.team import Team++from products.actions.backend.models.action import Action+from products.alerts.backend.models.alert import AlertConfiguration+from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.dashboards.backend.models.dashboard import Dashboard++# `products.experiments` ships a facade (api.py + contracts.py) but the contract is+# not yet enforced by CI (no `backend:contract-check` script in package.json). The+# facade exposes `create_experiment` but no list/query helpers, so the read-only+# orientation reader here imports the model directly. When experiments isolation is+# enforced, migrate this to a facade `list_recent_experiments(team, limit)` helper.+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.notebooks.backend.models import Notebook+from products.signals.backend.models import SignalReport, SignalSourceConfig+from products.signals.backend.scout_harness.profile.schema import Inventory+from products.surveys.backend.models import Survey+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow++logger = logging.getLogger(__name__)++# Bumps when the inventory schema changes meaningfully — `get_project_profile` invalidates+# rows whose `source_version` doesn't match the current build, so adding a new key here+# (or restructuring an existing one) without bumping the version would silently mix old+# and new shapes in the cache.+INVENTORY_SOURCE_VERSION = "v5"++# Top-events ClickHouse query bounds. 7d is short enough to spot recent bursts and long+# enough to stabilize counts on low-traffic teams; 50 covers the long tail without+# bloating the profile payload. Adjust if shadow runs surface a clear ask.+TOP_EVENTS_LOOKBACK_DAYS = 7+TOP_EVENTS_RECENT_DAYS = 1+TOP_EVENTS_LIMIT = 50+# Cap below the 60s default so a high-volume team fails fast (and degrades to None) rather+# than burning a full minute of ClickHouse on a best-effort orientation query.+TOP_EVENTS_MAX_EXECUTION_S = 20++# Dashboard recency limit. Bounded by name-only orientation — the agent can+# `dashboard-get` on a specific id once the profile tells it what's worth pulling.+RECENT_DASHBOARDS_LIMIT = 20++# Per-entity recency lists are deliberately short. The profile orients the agent+# ("here are the 5 most-recently-touched X — does this team look active in this+# area?"); the agent calls the per-entity MCP list tools for the long tail when+# something looks worth investigating.+RECENT_ENTITY_LIMIT = 5++# Recent activity window — 14d captures weekly cadence (sprints, weekly reviews) and+# bi-weekly iterations without drowning in stale edits. 20 distinct scopes is more+# than any team realistically touches in two weeks; the long tail beyond that is+# noise. The query hits the partial index `idx_alog_team_scope_created` whose+# condition (`was_impersonated=False AND is_system=False`) matches the filter.+RECENT_ACTIVITY_WINDOW_DAYS = 14+RECENT_ACTIVITY_LIMIT = 20+++def build_inventory(team: Team) -> Inventory:+ """Aggregate the deterministic inventory layer for a team.++ Each source is read independently — a failure in one (e.g. warehouse temporarily+ unavailable) shouldn't tank the whole profile build. Errors propagate up so the+ caller can decide whether to retry or persist a partial profile; v1 just lets them+ raise, since all the sources read here are local Postgres queries on indexed columns.++ Returns a validated `Inventory` (see `schema.py`) rather than a bare dict — the shape+ is a contract the scout skills read by key, so validating it on the way out keeps the+ builders and consumers from drifting apart silently.+ """+ return Inventory.model_validate(+ {+ "project_context": _project_context(team),+ "products_in_use": _products_in_use(team),+ "product_intents": _product_intents(team),+ "integrations": _integrations(team),+ "external_data_sources": _external_data_sources(team),+ "signal_source_configs": _signal_source_configs(team),+ "existing_inbox_reports": _existing_inbox_reports(team),+ "recent_activity": _recent_activity(team),+ "recent_dashboards": _recent_dashboards(team),+ "recent_surveys": _recent_surveys(team),+ "recent_feature_flags": _recent_feature_flags(team),+ "recent_experiments": _recent_experiments(team),+ "recent_alerts": _recent_alerts(team),+ "recent_hog_functions": _recent_hog_functions(team),+ "recent_hog_flows": _recent_hog_flows(team),+ "recent_notebooks": _recent_notebooks(team),+ "recent_cohorts": _recent_cohorts(team),+ "recent_actions": _recent_actions(team),+ "top_events": _top_events(team),+ }+ )+++def _project_context(team: Team) -> dict[str, Any]:+ """Free-form orientation about the project's product and surface area.++ `product_description` is a human-set text field on the project (max 1000 chars) —+ when populated, it's the most direct "what does this team's product do" answer+ available without scraping. `app_urls` is the registered set of URLs (toolbar,+ replay) — useful as the team's actual product surface, complementing the event-+ based `$host` discovery the scout can do via MCP if it needs to.+ """+ project = team.project+ product_description = (project.product_description or "").strip() if project else ""+ app_urls = [url for url in (team.app_urls or []) if url]+ return {+ "product_description": product_description or None,+ "app_urls": app_urls,+ }+++def _products_in_use(team: Team) -> list[str]:+ """Products this team has completed onboarding for.++ `Team.has_completed_onboarding_for` is a JSON map of `{product_key: bool}` — keys+ we report are the ones the team explicitly finished onboarding. Missing or null+ field returns an empty list rather than raising.+ """+ onboarded = team.has_completed_onboarding_for or {}+ if not isinstance(onboarded, dict):+ return []+ return sorted(key for key, value in onboarded.items() if bool(value))+++def _product_intents(team: Team) -> list[dict[str, Any]]:+ """Products the team signaled intent to use, even if onboarding isn't done.++ Captures the gap between "tried" and "actually using" — useful context for a scout+ deciding whether a quiet product might be worth investigating (intent without+ activation suggests a stuck onboarding).+ """+ rows = ProductIntent.objects.filter(team=team).order_by("product_type")+ return [+ {+ "product_type": row.product_type,+ "activated_at": row.activated_at.isoformat() if row.activated_at else None,+ "created_at": row.created_at.isoformat() if row.created_at else None,+ }+ for row in rows+ ]+++def _integrations(team: Team) -> list[dict[str, Any]]:+ """Connected integrations (Slack, GitHub, Linear, etc.).++ Only the kind + creation timestamp — `Integration.config` and `Integration.sensitive_config`+ can hold tokens or workspace details we don't want to surface to the agent.+ """+ rows = Integration.objects.filter(team=team).order_by("kind", "id")+ return [+ {+ "kind": row.kind,+ "created_at": row.created_at.isoformat() if row.created_at else None,+ }+ for row in rows+ ]+++def _external_data_sources(team: Team) -> list[dict[str, Any]]:+ """Connected warehouse sources (Stripe, Postgres, BigQuery, etc.).++ Excludes soft-deleted rows. `status` and `prefix` give the agent enough context to+ spot a stuck or recently-added source without exposing credentials.+ """+ rows = (+ ExternalDataSource.objects.filter(team=team, deleted=False)+ .order_by("source_type", "id")+ .values("source_type", "status", "prefix", "created_at")+ )+ return [+ {+ "source_type": row["source_type"],+ "status": row["status"],+ "prefix": row["prefix"] or "",+ "created_at": row["created_at"].isoformat() if row.get("created_at") else None,+ }+ for row in rows+ ]+++def _signal_source_configs(team: Team) -> dict[str, list[dict[str, str]]]:+ """Signal source configs split by `enabled` flag.++ The `disabled` bucket matters too — it tells the scout which sources have been+ explicitly turned off, which is a different signal than "never wired up at all."+ """+ rows = SignalSourceConfig.objects.filter(team=team).order_by("source_product", "source_type")+ enabled: list[dict[str, str]] = []+ disabled: list[dict[str, str]] = []+ for row in rows:+ entry = {"source_product": row.source_product, "source_type": row.source_type}+ (enabled if row.enabled else disabled).append(entry)+ return {"enabled": enabled, "disabled": disabled}+++def _existing_inbox_reports(team: Team) -> dict[str, Any]:+ """Counts of existing inbox reports grouped by `status`.++ `SignalReport` doesn't carry source_product/source_type directly (those live on the+ upstream signals + emission records); status is what the scout actually wants —+ "how many things are already candidates vs ready vs in_progress in this team's+ inbox?" Suppressed and deleted statuses are excluded since they're not actively+ surfaced to humans.+ """+ excluded = {SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED}+ rows = (+ SignalReport.objects.filter(team=team)+ .exclude(status__in=excluded)+ .values("status")+ .annotate(count=Count("id"))+ .order_by("status")+ )+ by_status = [{"status": row["status"], "count": row["count"]} for row in rows]+ return {"total": sum(row["count"] for row in by_status), "by_status": by_status}+++def _recent_dashboards(team: Team) -> list[dict[str, Any]]:+ """Most recently accessed dashboards on this team.++ Sorted by `Dashboard.last_accessed_at` desc — recency, not popularity. We don't+ have a per-dashboard view *count* in Postgres (the `viewed dashboard` event would+ give us counts but only for PostHog-internal teams via project 2), so this surfaces+ "what's the team currently looking at" rather than "what's most trafficked." The+ name reflects what we actually have.+ """+ rows = (+ Dashboard.objects.filter(team=team, deleted=False, last_accessed_at__isnull=False)+ .order_by("-last_accessed_at")[:RECENT_DASHBOARDS_LIMIT]+ .values("id", "name", "last_accessed_at", "last_refresh", "created_at")+ )+ return [+ {+ "id": row["id"],+ "name": row["name"] or "",+ "last_accessed_at": row["last_accessed_at"].isoformat() if row["last_accessed_at"] else None,+ "last_refresh": row["last_refresh"].isoformat() if row["last_refresh"] else None,+ "created_at": row["created_at"].isoformat() if row["created_at"] else None,+ }+ for row in rows+ ]+++def _recent_surveys(team: Team) -> dict[str, Any]:+ """Surveys orientation — total + active count, plus the 5 most recently modified.++ "Active" matches PostHog's running semantics: not archived, already started+ (`start_date <= now`), and not yet ended. Drafts (`start_date IS NULL`) and+ future-scheduled surveys count as not-active. Sort by `updated_at` so freshly-edited+ surveys surface first; falls through to creation recency for never-edited rows.++ `type` carries the survey-mode hint (popover/widget/external/api) the surveys+ specialist scout cares about; agents pull full question shape via `survey-get`.+ """+ qs = Survey.objects.filter(team=team)+ total = qs.count()+ active = (+ qs.filter(+ archived=False,+ start_date__lte=timezone.now(),+ )+ .filter(Q(end_date__isnull=True) | Q(end_date__gt=timezone.now()))+ .count()+ )+ recent = qs.order_by("-updated_at")[:RECENT_ENTITY_LIMIT].values(+ "id", "name", "type", "archived", "start_date", "end_date", "updated_at"+ )+ return {+ "total_count": total,+ "active_count": active,+ "recent": [+ {+ "id": str(row["id"]),+ "name": row["name"] or "",+ "type": row["type"],+ "status": _survey_status(row),+ "updated_at": row["updated_at"].isoformat() if row["updated_at"] else None,+ }+ for row in recent+ ],+ }+++def _survey_status(row: dict[str, Any]) -> str:+ """Derive a single-word survey status from archive flag + start/end dates."""+ if row["archived"]:+ return "archived"+ if row["start_date"] is None:+ return "draft"+ if row["end_date"] is not None and row["end_date"] <= timezone.now():+ return "stopped"+ return "running"+++def _recent_feature_flags(team: Team) -> dict[str, Any]:+ """Feature flag orientation — total + active count, plus 5 most-recently-modified.++ `active` is the model's own boolean ("is this flag currently evaluating?"); it+ answers "could a user be hitting this code path?" — which is the question worth+ distinguishing from "does this flag exist?" Sort by `updated_at`, which captures+ both creation and rollout-percentage changes.+ """+ qs = FeatureFlag.objects.filter(team=team, deleted=False)+ total = qs.count()+ active = qs.filter(active=True).count()+ recent = qs.order_by("-updated_at")[:RECENT_ENTITY_LIMIT].values("id", "key", "name", "active", "updated_at")+ return {+ "total_count": total,+ "active_count": active,+ "recent": [+ {+ "id": row["id"],+ "key": row["key"],+ # `name` is the human-set description; falls back to key when blank+ # (matches the dashboards / insights pattern of "show whichever is set").+ "name": (row["name"] or "").strip() or row["key"],+ "active": row["active"],+ "updated_at": row["updated_at"].isoformat() if row["updated_at"] else None,+ }+ for row in recent+ ],+ }+++def _recent_experiments(team: Team) -> dict[str, Any]:+ """Experiment orientation — total + currently-running, plus 5 most-recently-modified.++ "Running" means `start_date` set + no `end_date` + not archived/deleted; matches+ the model's own `is_running` property. `feature_flag_key` is the cross-ref the+ agent uses to correlate experiments with the `recent_feature_flags` section.+ """+ qs = Experiment.objects.filter(team=team).filter(Q(deleted=False) | Q(deleted__isnull=True))+ total = qs.count()+ running = qs.filter(archived=False, start_date__isnull=False, end_date__isnull=True).count()+ recent = qs.select_related("feature_flag").order_by("-updated_at")[:RECENT_ENTITY_LIMIT]+ return {+ "total_count": total,+ "running_count": running,+ "recent": [+ {+ "id": exp.id,+ "name": exp.name,+ "status": _experiment_status(exp),+ "feature_flag_key": exp.feature_flag.key if exp.feature_flag_id else None,+ "updated_at": exp.updated_at.isoformat() if exp.updated_at else None,+ }+ for exp in recent+ ],+ }+++def _experiment_status(exp: Experiment) -> str:+ """Derive single-word experiment status from archive/start/end fields."""+ if exp.archived:+ return "archived"+ if exp.start_date is None:+ return "draft"+ if exp.end_date is not None:+ return "stopped"+ return "running"+++def _recent_alerts(team: Team) -> dict[str, Any]:+ """Insight alert orientation — total + currently-enabled, plus 5 most-recently-created.++ `AlertConfiguration` carries `created_at` from `CreatedMetaFields` but no+ `updated_at` — sorting by creation recency surfaces newly-configured alerts,+ which is the high-signal moment (someone setting up an alert today is actively+ monitoring something).+ """+ qs = AlertConfiguration.objects.filter(team=team)+ total = qs.count()+ enabled = qs.filter(enabled=True).count()+ recent = qs.order_by("-created_at")[:RECENT_ENTITY_LIMIT].values(+ "id", "name", "enabled", "state", "calculation_interval", "insight_id", "created_at"+ )+ return {+ "total_count": total,+ "enabled_count": enabled,+ "recent": [+ {+ "id": str(row["id"]),+ "name": row["name"] or "",+ "enabled": row["enabled"],+ "state": row["state"],+ "calculation_interval": row["calculation_interval"],+ "insight_id": row["insight_id"],+ "created_at": row["created_at"].isoformat() if row["created_at"] else None,+ }+ for row in recent+ ],+ }+++def _recent_hog_functions(team: Team) -> dict[str, Any]:+ """Hog function orientation — total + enabled, plus 5 most-recently-modified.++ `type` discriminates destinations vs transformations vs site apps — the agent+ pattern-matches on it to decide whether activity is "data plumbing" or "user+ surface" work.+ """+ qs = HogFunction.objects.filter(team=team, deleted=False)+ total = qs.count()+ enabled = qs.filter(enabled=True).count()+ recent = qs.order_by("-updated_at")[:RECENT_ENTITY_LIMIT].values(+ "id", "name", "type", "kind", "enabled", "updated_at"+ )+ return {+ "total_count": total,+ "enabled_count": enabled,+ "recent": [+ {+ "id": str(row["id"]),+ "name": row["name"] or "",+ "type": row["type"],+ "kind": row["kind"],+ "enabled": row["enabled"],+ "updated_at": row["updated_at"].isoformat() if row["updated_at"] else None,+ }+ for row in recent+ ],+ }+++def _recent_hog_flows(team: Team) -> dict[str, Any]:+ """Hog flow (workflow) orientation — total + non-archived, plus 5 most-recent.++ HogFlow's `status` enum carries the flow's lifecycle state directly; we surface+ it as-is so the agent can distinguish drafts from active flows.+ """+ qs = HogFlow.objects.filter(team=team)+ total = qs.count()+ active = qs.exclude(status="archived").count()+ recent = qs.order_by("-updated_at")[:RECENT_ENTITY_LIMIT].values("id", "name", "status", "updated_at")+ return {+ "total_count": total,+ "active_count": active,+ "recent": [+ {+ "id": str(row["id"]),+ "name": row["name"] or "",+ "status": row["status"],+ "updated_at": row["updated_at"].isoformat() if row["updated_at"] else None,+ }+ for row in recent+ ],+ }+++def _recent_notebooks(team: Team) -> dict[str, Any]:+ """Notebook orientation — total + 5 most-recently-modified.++ Notebooks don't really have an "active" state; they exist or are deleted. The+ activity-log mockup against project 2 showed Notebook as the highest-velocity+ scope (405 edits in 14d), so this section is high-signal even at small recent-+ list size.+ """+ qs = Notebook.objects.filter(team=team, deleted=False)+ total = qs.count()+ recent = qs.order_by("-last_modified_at")[:RECENT_ENTITY_LIMIT].values("short_id", "title", "last_modified_at")+ return {+ "total_count": total,+ "recent": [+ {+ "short_id": row["short_id"],+ "title": (row["title"] or "").strip(),+ "last_modified_at": row["last_modified_at"].isoformat() if row["last_modified_at"] else None,+ }+ for row in recent+ ],+ }+++def _recent_cohorts(team: Team) -> dict[str, Any]:+ """Cohort orientation — total + 5 most-recently-created.++ Cohorts have no `updated_at` field — the "creation" event is the high-signal+ moment (someone defining a new audience for analysis or targeting). Sort by+ `created_at` to surface fresh cohorts. `is_static` lets the agent distinguish+ one-shot snapshots from dynamic-filter cohorts; `count` is the membership size+ when last calculated (NULL if never calculated).+ """+ qs = Cohort.objects.filter(team=team, deleted=False)+ total = qs.count()+ recent = qs.order_by(F("created_at").desc(nulls_last=True))[:RECENT_ENTITY_LIMIT].values(+ "id", "name", "is_static", "count", "created_at"+ )+ return {+ "total_count": total,+ "recent": [+ {+ "id": row["id"],+ "name": (row["name"] or "").strip(),+ "is_static": row["is_static"],+ "count": row["count"],+ "created_at": row["created_at"].isoformat() if row["created_at"] else None,+ }+ for row in recent+ ],+ }+++def _recent_actions(team: Team) -> dict[str, Any]:+ """Action orientation — total + 5 most-recently-modified.++ Actions tag patterns of events; creating one is intentional ("I want to track+ this user behavior as a named thing"). Sort by `updated_at` so both new actions+ and edits to step definitions surface.+ """+ qs = Action.objects.filter(team=team, deleted=False)+ total = qs.count()+ recent = qs.order_by("-updated_at")[:RECENT_ENTITY_LIMIT].values("id", "name", "updated_at")+ return {+ "total_count": total,+ "recent": [+ {+ "id": row["id"],+ "name": (row["name"] or "").strip(),+ "updated_at": row["updated_at"].isoformat() if row["updated_at"] else None,+ }+ for row in recent+ ],+ }+++def _recent_activity(team: Team) -> dict[str, Any]:+ """Per-scope recency from the activity log over a `RECENT_ACTIVITY_WINDOW_DAYS` window.++ Cuts across every entity type the activity log knows about — surveys, feature flags,+ experiments, dashboards, insights, cohorts, notebooks, actions, etc. — so the agent+ gets one place to look for "where has this team been working lately?" without per-+ entity readers. The MCP tools `activity-log-list` / `advanced-activity-logs-list`+ do the drill-down once the agent decides a scope is worth investigating.++ `edits` is total log entries in the window (write velocity). `users` is distinct+ user count, so a single power-user looping is distinguishable from broad team+ activity. `last_edit` lets the agent sort/skim by recency as well as volume.++ The filter matches the partial index `idx_alog_team_scope_created` exactly — both+ sides use `was_impersonated=False AND is_system=False`, so this is a single cheap+ aggregate even on busy teams. Rows where either flag is NULL are intentionally+ skipped; the index treats them as not-real-user-activity, and we follow.+ """+ cutoff = timezone.now() - timedelta(days=RECENT_ACTIVITY_WINDOW_DAYS)+ rows = (+ ActivityLog.objects.filter(+ team_id=team.id,+ created_at__gte=cutoff,+ was_impersonated=False,+ is_system=False,+ )+ .values("scope")+ .annotate(+ edits=Count("id"),+ users=Count("user_id", distinct=True),+ last_edit=Max("created_at"),+ )+ .order_by("-edits")[:RECENT_ACTIVITY_LIMIT]+ )+ return {+ "window_days": RECENT_ACTIVITY_WINDOW_DAYS,+ "by_scope": [+ {+ "scope": row["scope"],+ "edits": row["edits"],+ "users": row["users"],+ "last_edit": row["last_edit"].isoformat() if row["last_edit"] else None,+ }+ for row in rows+ ],+ }+++def _top_events(team: Team) -> list[dict[str, Any]] | None:+ """Top events by count over the lookback window, with reach + burst signals.++ For each of the top 50 events in the last 7 days:+ - `count` — total occurrences in the window+ - `distinct_users` — `uniq(person_id)`; reach. Distinguishes a high-count event+ from one power user vs from many users.+ - `recent_24h_count` — count in the last 24h. Compare to `count / 7` to spot+ bursts: ratio well above 1/7 means the event is concentrated in the last day.+ - `recent_24h_users` — `uniq(person_id)` over the last 24h. A burst across many+ users is qualitatively different from one user looping.+ - `first_seen` / `last_seen` — both *within the window*. Recent `first_seen`+ suggests a new event type or fresh burst; near-window-edge `first_seen` just+ means it's been around at least that long (the window can't tell you the+ true first-ever timestamp).++ Returns `None` rather than `[]` if the query fails or times out, so the agent can+ distinguish "team has no captures" (`[]`) from "we couldn't compute it" (`None`).+ """+ query = parse_select(+ """+ SELECT+ event,+ count() AS count,+ uniq(person_id) AS distinct_users,+ countIf(timestamp >= now() - INTERVAL {recent_days} DAY) AS recent_24h_count,+ uniqIf(person_id, timestamp >= now() - INTERVAL {recent_days} DAY) AS recent_24h_users,+ min(timestamp) AS first_seen,+ max(timestamp) AS last_seen+ FROM events+ WHERE timestamp >= now() - INTERVAL {lookback_days} DAY+ GROUP BY event+ ORDER BY count DESC+ LIMIT {limit}+ """,+ placeholders={+ "lookback_days": ast.Constant(value=TOP_EVENTS_LOOKBACK_DAYS),+ "recent_days": ast.Constant(value=TOP_EVENTS_RECENT_DAYS),+ "limit": ast.Constant(value=TOP_EVENTS_LIMIT),+ },+ )+ try:+ response = execute_hogql_query(+ query=query,+ team=team,+ limit_context=None,+ settings=HogQLGlobalSettings(max_execution_time=TOP_EVENTS_MAX_EXECUTION_S),+ )+ except Exception:+ # Defensive: ClickHouse can be slow or unavailable. Profile build shouldn't+ # crash on this — the rest of the inventory is still valuable orientation.+ logger.warning("signals_scout_profile: top_events query failed for team_id=%s", team.id, exc_info=True)+ return None+ rows = response.results or []+ return [+ {+ "event": row[0],+ "count": int(row[1]),+ "distinct_users": int(row[2]),+ "recent_24h_count": int(row[3]),+ "recent_24h_users": int(row[4]),+ "first_seen": row[5].isoformat() if row[5] else None,+ "last_seen": row[6].isoformat() if row[6] else None,+ }+ for row in rows+ ]diff --git a/products/signals/backend/scout_harness/profile/schema.py b/products/signals/backend/scout_harness/profile/schema.pynew file mode 100644index 000000000000..c2628a6b83d2--- /dev/null+++ b/products/signals/backend/scout_harness/profile/schema.py@@ -0,0 +1,252 @@+"""Typed schema for the project profile inventory payload.++`build_inventory` returns an `Inventory` instance; `compute_project_profile` persists+`inventory.model_dump(mode="json")` into the `SignalProjectProfile.payload` jsonb column.++The model is the single source of truth for the payload shape. Storage stays jsonb — the+payload is written by one builder, read whole, and never field-queried, so relational+columns would buy no query benefit and a migration per section as coverage grows. But the+jsonb is *schema-backed*, not schemaless: the scout skills read the inventory by key, so+validating the shape on write keeps them from silently drifting when sections are added or+reshaped (`extra="forbid"` makes a builder emitting an unmodeled key fail loudly in tests+rather than dropping data a skill might depend on).++Nullability mirrors the underlying Django fields: every serialized timestamp is optional,+and columns that are `null=True` at the DB layer (`HogFunction.type`/`kind`,+`AlertConfiguration.calculation_interval`, `Cohort.count`) are optional here too. Bump+`INVENTORY_SOURCE_VERSION` in `builders.py` when the shape changes meaningfully so+`get_project_profile` invalidates cached rows built on the old shape.+"""++from __future__ import annotations++from pydantic import BaseModel, ConfigDict+++class _Section(BaseModel):+ # Forbid unmodeled keys so the builders and this schema can't drift apart unnoticed —+ # an extra key is a contract change the scout skills need to know about, so surface it.+ model_config = ConfigDict(extra="forbid")+++class ProjectContext(_Section):+ product_description: str | None+ app_urls: list[str]+++class ProductIntentEntry(_Section):+ product_type: str+ activated_at: str | None+ created_at: str | None+++class IntegrationEntry(_Section):+ kind: str+ created_at: str | None+++class ExternalDataSourceEntry(_Section):+ source_type: str+ status: str+ prefix: str+ created_at: str | None+++class SignalSourceConfigEntry(_Section):+ source_product: str+ source_type: str+++class SignalSourceConfigs(_Section):+ enabled: list[SignalSourceConfigEntry]+ disabled: list[SignalSourceConfigEntry]+++class StatusCount(_Section):+ status: str+ count: int+++class ExistingInboxReports(_Section):+ total: int+ by_status: list[StatusCount]+++class ScopeActivity(_Section):+ scope: str+ edits: int+ users: int+ last_edit: str | None+++class RecentActivity(_Section):+ window_days: int+ by_scope: list[ScopeActivity]+++class DashboardEntry(_Section):+ id: int+ name: str+ last_accessed_at: str | None+ last_refresh: str | None+ created_at: str | None+++class SurveyEntry(_Section):+ id: str+ name: str+ type: str+ status: str+ updated_at: str | None+++class RecentSurveys(_Section):+ total_count: int+ active_count: int+ recent: list[SurveyEntry]+++class FeatureFlagEntry(_Section):+ id: int+ key: str+ name: str+ active: bool+ updated_at: str | None+++class RecentFeatureFlags(_Section):+ total_count: int+ active_count: int+ recent: list[FeatureFlagEntry]+++class ExperimentEntry(_Section):+ id: int+ name: str+ status: str+ feature_flag_key: str | None+ updated_at: str | None+++class RecentExperiments(_Section):+ total_count: int+ running_count: int+ recent: list[ExperimentEntry]+++class AlertEntry(_Section):+ id: str+ name: str+ enabled: bool+ state: str+ calculation_interval: str | None+ insight_id: int | None+ created_at: str | None+++class RecentAlerts(_Section):+ total_count: int+ enabled_count: int+ recent: list[AlertEntry]+++class HogFunctionEntry(_Section):+ id: str+ name: str+ type: str | None+ kind: str | None+ enabled: bool+ updated_at: str | None+++class RecentHogFunctions(_Section):+ total_count: int+ enabled_count: int+ recent: list[HogFunctionEntry]+++class HogFlowEntry(_Section):+ id: str+ name: str+ status: str+ updated_at: str | None+++class RecentHogFlows(_Section):+ total_count: int+ active_count: int+ recent: list[HogFlowEntry]+++class NotebookEntry(_Section):+ short_id: str+ title: str+ last_modified_at: str | None+++class RecentNotebooks(_Section):+ total_count: int+ recent: list[NotebookEntry]+++class CohortEntry(_Section):+ id: int+ name: str+ is_static: bool+ count: int | None+ created_at: str | None+++class RecentCohorts(_Section):+ total_count: int+ recent: list[CohortEntry]+++class ActionEntry(_Section):+ id: int+ name: str+ updated_at: str | None+++class RecentActions(_Section):+ total_count: int+ recent: list[ActionEntry]+++class TopEvent(_Section):+ event: str+ count: int+ distinct_users: int+ recent_24h_count: int+ recent_24h_users: int+ first_seen: str | None+ last_seen: str | None+++class Inventory(_Section):+ """The deterministic inventory layer of a `SignalProjectProfile.payload`.++ Field order matches `build_inventory`'s assembly order so the serialized jsonb keeps a+ stable key order across builds. `top_events` is `None` (not `[]`) when the ClickHouse+ query fails, so the scout can tell "no captures" apart from "couldn't compute".+ """++ project_context: ProjectContext+ products_in_use: list[str]+ product_intents: list[ProductIntentEntry]+ integrations: list[IntegrationEntry]+ external_data_sources: list[ExternalDataSourceEntry]+ signal_source_configs: SignalSourceConfigs+ existing_inbox_reports: ExistingInboxReports+ recent_activity: RecentActivity+ recent_dashboards: list[DashboardEntry]+ recent_surveys: RecentSurveys+ recent_feature_flags: RecentFeatureFlags+ recent_experiments: RecentExperiments+ recent_alerts: RecentAlerts+ recent_hog_functions: RecentHogFunctions+ recent_hog_flows: RecentHogFlows+ recent_notebooks: RecentNotebooks+ recent_cohorts: RecentCohorts+ recent_actions: RecentActions+ top_events: list[TopEvent] | Nonediff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex e74f30f3e0b9..4121819e2418 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -149,4 +149,17 @@ 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 referencesthem. Don't start investigating before you've read it.+# Then: orient on this project++Once you've read your skill, call:++ signals-scout-project-profile-get++That returns a deterministic snapshot of this team — products in use, connected+integrations, warehouse sources, signal source configs (split enabled/disabled),+and counts of existing inbox reports. One call gives you the orientation that+would otherwise take 4-5 discovery calls. Treat it as ground truth: it's+computed from authoritative tables, distinct from the scout-inferred notes+in `signals-scout-scratchpad-search`.+{tail}"""diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex fd275c143ae8..19cc5c409808 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -245,3 +245,562 @@ class EmitFindingResponseSerializer(serializers.Serializer):allow_null=True,help_text="`ai_processing_not_approved` | `source_disabled` | null when emitted normally.",)+++# --- Project profile ------------------------------------------------------+++class ProductIntentEntrySerializer(serializers.Serializer):+ """One row in `inventory.product_intents`."""++ product_type = serializers.CharField(help_text="Product key the team signaled intent to use.")+ activated_at = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp the team activated the product, or null if intent only.",+ )+ created_at = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp the intent was first recorded.",+ )+++class IntegrationEntrySerializer(serializers.Serializer):+ """One row in `inventory.integrations`. Sensitive config is intentionally excluded."""++ kind = serializers.CharField(help_text="Integration kind (e.g. `slack`, `github`, `linear`).")+ created_at = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp the integration was connected.",+ )+++class ExternalDataSourceEntrySerializer(serializers.Serializer):+ """One row in `inventory.external_data_sources`."""++ source_type = serializers.CharField(help_text="Warehouse source type (e.g. `Stripe`, `Postgres`, `BigQuery`).")+ status = serializers.CharField(help_text="Current sync status (`Running`, `Failed`, `Paused`, etc.).")+ prefix = serializers.CharField(allow_blank=True, help_text="Schema prefix used by this source, if any.")+ created_at = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp the source was connected.",+ )+++class SignalSourceConfigEntrySerializer(serializers.Serializer):+ """One row in either bucket of `inventory.signal_source_configs`."""++ source_product = serializers.CharField(help_text="Source product the config applies to.")+ source_type = serializers.CharField(help_text="Source type within the product.")+++class SignalSourceConfigsBucketsSerializer(serializers.Serializer):+ """`inventory.signal_source_configs` split into enabled and disabled buckets."""++ enabled = serializers.ListField(+ child=SignalSourceConfigEntrySerializer(),+ help_text="Source configs the team has explicitly enabled.",+ )+ disabled = serializers.ListField(+ child=SignalSourceConfigEntrySerializer(),+ help_text="Source configs the team has explicitly disabled (different from never wired up).",+ )+++class InboxReportStatusBucketSerializer(serializers.Serializer):+ """One bucket in `inventory.existing_inbox_reports.by_status`."""++ status = serializers.CharField(help_text="Report status (e.g. `potential`, `candidate`, `ready`).")+ count = serializers.IntegerField(help_text="Number of reports in this status (excludes deleted/suppressed).")+++class ExistingInboxReportsSerializer(serializers.Serializer):+ """`inventory.existing_inbox_reports` — what's already been surfaced to the inbox."""++ total = serializers.IntegerField(help_text="Total non-deleted, non-suppressed reports for this team.")+ by_status = serializers.ListField(+ child=InboxReportStatusBucketSerializer(),+ help_text="Per-status breakdown of inbox reports.",+ )+++class RecentDashboardEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_dashboards`."""++ id = serializers.IntegerField(help_text="Dashboard ID — pass to `dashboard-get` to pull the full payload.")+ name = serializers.CharField(allow_blank=True, help_text="Dashboard name (may be blank if unnamed).")+ last_accessed_at = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp of the most recent view in the PostHog UI.",+ )+ last_refresh = serializers.CharField(+ allow_null=True,+ help_text=(+ "ISO-8601 timestamp of the most recent data refresh. Distinct from access — "+ "a dashboard can be refreshed without anyone viewing it."+ ),+ )+ created_at = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp the dashboard was created.",+ )+++class TopEventEntrySerializer(serializers.Serializer):+ """One row in `inventory.top_events`."""++ event = serializers.CharField(help_text="Event name as captured.")+ count = serializers.IntegerField(help_text="Number of occurrences in the lookback window (last 7 days).")+ distinct_users = serializers.IntegerField(+ help_text=(+ "`uniq(person_id)` over the window — reach. Distinguishes a high-count "+ "event firing on one power user from one firing on many users."+ ),+ )+ recent_24h_count = serializers.IntegerField(+ help_text=(+ "Count in just the last 24 hours. Compare to `count / 7` to spot bursts: "+ "a ratio well above 1/7 means the event is concentrated in the last day."+ ),+ )+ recent_24h_users = serializers.IntegerField(+ help_text=(+ "`uniq(person_id)` over just the last 24 hours. A burst across many "+ "users is qualitatively different from one user in a loop."+ ),+ )+ first_seen = serializers.CharField(+ allow_null=True,+ help_text=(+ "ISO-8601 timestamp of the earliest occurrence within the lookback window. "+ "Compare to the window start to spot new event types: `first_seen` close to "+ "`now` ⇒ likely new or recently bursting; close to the window edge ⇒ has "+ "been around at least that long (the window can't tell you when the event "+ "*truly* first appeared)."+ ),+ )+ last_seen = serializers.CharField(+ allow_null=True,+ help_text="ISO-8601 timestamp of the most recent occurrence within the lookback window.",+ )+++class ProjectContextSerializer(serializers.Serializer):+ """`inventory.project_context` — free-form orientation about the project's product."""++ product_description = serializers.CharField(+ allow_null=True,+ allow_blank=False,+ help_text=(+ "Human-set product description on the project (max 1000 chars). When present, "+ 'the most direct "what does this team\'s product do" answer. `null` when unset.'+ ),+ )+ app_urls = serializers.ListField(+ child=serializers.CharField(),+ help_text=(+ "Registered app URLs for this team (toolbar / replay). The team's actual "+ "product surface; complements `$pageview.$host` discovery via `read-data-schema`."+ ),+ )+++# The per-entity `recent_*` sections below mirror the Pydantic models in+# `scout_harness/profile/schema.py` one-for-one (that schema is what the builder+# validates against on write; these serializers are what types the MCP/HTTP response).+# Keeping them as explicit nested serializers — rather than bare `JSONField` — is what+# makes the generated TS/Zod clients carry real shapes instead of `unknown`. When a+# section's shape changes in `schema.py`, update the matching serializer here too.+++class ScopeActivityEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_activity.by_scope`."""++ scope = serializers.CharField(+ help_text="Activity-log scope (entity type), e.g. `FeatureFlag`, `Dashboard`, `Survey`."+ )+ edits = serializers.IntegerField(+ help_text="Total activity-log entries for this scope in the window (write velocity)."+ )+ users = serializers.IntegerField(help_text="Distinct users who edited this scope in the window.")+ last_edit = serializers.CharField(+ allow_null=True, help_text="ISO-8601 timestamp of the most recent edit in the window."+ )+++class RecentActivitySerializer(serializers.Serializer):+ """`inventory.recent_activity` — per-scope counts off the activity log."""++ window_days = serializers.IntegerField(help_text="Lookback window in days the per-scope counts cover.")+ by_scope = serializers.ListField(+ child=ScopeActivityEntrySerializer(),+ help_text="Per-scope activity rows, busiest scope first. Triage which entity type the team has worked in lately.",+ )+++class RecentSurveyEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_surveys.recent`."""++ id = serializers.CharField(help_text="Survey UUID — pass to `survey-get` for full question shape.")+ name = serializers.CharField(allow_blank=True, help_text="Survey name (may be blank if unnamed).")+ type = serializers.CharField(help_text="Survey mode: `popover`, `widget`, `external_survey`, or `api`.")+ status = serializers.CharField(help_text="Derived status: `draft`, `running`, `stopped`, or `archived`.")+ updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-modified timestamp.")+++class RecentSurveysSerializer(serializers.Serializer):+ """`inventory.recent_surveys` — total + active count, plus the 5 most recently modified."""++ total_count = serializers.IntegerField(help_text="Total surveys on the team.")+ active_count = serializers.IntegerField(+ help_text="Surveys that are live (not archived, started, and not yet ended)."+ )+ recent = serializers.ListField(+ child=RecentSurveyEntrySerializer(),+ help_text="The 5 most recently updated surveys.",+ )+++class RecentFeatureFlagEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_feature_flags.recent`."""++ id = serializers.IntegerField(help_text="Feature flag ID.")+ key = serializers.CharField(help_text="Flag key used in code (`posthog.isFeatureEnabled('<key>')`).")+ name = serializers.CharField(allow_blank=True, help_text="Human-set description; falls back to the key when blank.")+ active = serializers.BooleanField(+ help_text="Whether the flag is currently evaluating (a user could be hitting it)."+ )+ updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-modified timestamp.")+++class RecentFeatureFlagsSerializer(serializers.Serializer):+ """`inventory.recent_feature_flags` — total + active count, plus the 5 most recently modified."""++ total_count = serializers.IntegerField(help_text="Total non-deleted feature flags on the team.")+ active_count = serializers.IntegerField(help_text="Flags currently evaluating (`active=true`).")+ recent = serializers.ListField(+ child=RecentFeatureFlagEntrySerializer(),+ help_text="The 5 most recently updated non-deleted flags.",+ )+++class RecentExperimentEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_experiments.recent`."""++ id = serializers.IntegerField(help_text="Experiment ID.")+ name = serializers.CharField(allow_blank=True, help_text="Experiment name.")+ status = serializers.CharField(help_text="Derived status: `draft`, `running`, `stopped`, or `archived`.")+ feature_flag_key = serializers.CharField(+ allow_null=True,+ help_text="Key of the experiment's feature flag — cross-ref into `recent_feature_flags`. Null if unlinked.",+ )+ updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-modified timestamp.")+++class RecentExperimentsSerializer(serializers.Serializer):+ """`inventory.recent_experiments` — total + currently-running count, plus the 5 most recently modified."""++ total_count = serializers.IntegerField(help_text="Total experiments on the team.")+ running_count = serializers.IntegerField(+ help_text="Experiments currently running (started, not ended, not archived).",+ )+ recent = serializers.ListField(+ child=RecentExperimentEntrySerializer(),+ help_text="The 5 most recently updated experiments.",+ )+++class RecentAlertEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_alerts.recent`."""++ id = serializers.CharField(help_text="Alert configuration UUID.")+ name = serializers.CharField(allow_blank=True, help_text="Alert name.")+ enabled = serializers.BooleanField(help_text="Whether the alert is currently armed.")+ state = serializers.CharField(help_text="Alert state (e.g. `not_firing`, `firing`).")+ calculation_interval = serializers.CharField(+ allow_null=True,+ help_text="How often the alert is evaluated (e.g. `daily`, `hourly`); null if unset.",+ )+ insight_id = serializers.IntegerField(+ allow_null=True, help_text="ID of the insight the alert watches; null if none."+ )+ created_at = serializers.CharField(allow_null=True, help_text="ISO-8601 creation timestamp.")+++class RecentAlertsSerializer(serializers.Serializer):+ """`inventory.recent_alerts` — total + currently-enabled count, plus the 5 most recently created."""++ total_count = serializers.IntegerField(help_text="Total insight alerts on the team.")+ enabled_count = serializers.IntegerField(help_text="Alerts currently armed (`enabled=true`).")+ recent = serializers.ListField(+ child=RecentAlertEntrySerializer(),+ help_text="The 5 most recently created alerts.",+ )+++class RecentHogFunctionEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_hog_functions.recent`."""++ id = serializers.CharField(help_text="Hog function UUID.")+ name = serializers.CharField(allow_blank=True, help_text="Hog function name.")+ type = serializers.CharField(+ allow_null=True,+ help_text="Function type: `destination`, `transformation`, `site_app`, etc. Null if unset.",+ )+ kind = serializers.CharField(allow_null=True, help_text="Function kind sub-classifier; null if unset.")+ enabled = serializers.BooleanField(help_text="Whether the function is currently enabled.")+ updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-modified timestamp.")+++class RecentHogFunctionsSerializer(serializers.Serializer):+ """`inventory.recent_hog_functions` — total + enabled count, plus the 5 most recently modified."""++ total_count = serializers.IntegerField(help_text="Total non-deleted hog functions on the team.")+ enabled_count = serializers.IntegerField(help_text="Hog functions currently enabled (`enabled=true`).")+ recent = serializers.ListField(+ child=RecentHogFunctionEntrySerializer(),+ help_text="The 5 most recently updated hog functions.",+ )+++class RecentHogFlowEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_hog_flows.recent`."""++ id = serializers.CharField(help_text="Hog flow UUID.")+ name = serializers.CharField(allow_blank=True, help_text="Hog flow name.")+ status = serializers.CharField(help_text="Flow lifecycle state (e.g. `draft`, `active`, `archived`).")+ updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-modified timestamp.")+++class RecentHogFlowsSerializer(serializers.Serializer):+ """`inventory.recent_hog_flows` — total + non-archived count, plus the 5 most recently modified."""++ total_count = serializers.IntegerField(help_text="Total hog flows on the team.")+ active_count = serializers.IntegerField(help_text="Hog flows that are not archived.")+ recent = serializers.ListField(+ child=RecentHogFlowEntrySerializer(),+ help_text="The 5 most recently updated hog flows.",+ )+++class RecentNotebookEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_notebooks.recent`."""++ short_id = serializers.CharField(help_text="Notebook short ID — pass to the notebooks API to open it.")+ title = serializers.CharField(allow_blank=True, help_text="Notebook title (may be blank if untitled).")+ last_modified_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-modified timestamp.")+++class RecentNotebooksSerializer(serializers.Serializer):+ """`inventory.recent_notebooks` — total + the 5 most recently modified."""++ total_count = serializers.IntegerField(help_text="Total non-deleted notebooks on the team.")+ recent = serializers.ListField(+ child=RecentNotebookEntrySerializer(),+ help_text="The 5 most recently modified notebooks.",+ )+++class RecentCohortEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_cohorts.recent`."""++ id = serializers.IntegerField(help_text="Cohort ID.")+ name = serializers.CharField(allow_blank=True, help_text="Cohort name.")+ is_static = serializers.BooleanField(+ help_text="True for a one-shot snapshot cohort; false for a dynamic-filter cohort."+ )+ count = serializers.IntegerField(+ allow_null=True,+ help_text="Membership size when last calculated; null if never calculated.",+ )+ created_at = serializers.CharField(allow_null=True, help_text="ISO-8601 creation timestamp.")+++class RecentCohortsSerializer(serializers.Serializer):+ """`inventory.recent_cohorts` — total + the 5 most recently created."""++ total_count = serializers.IntegerField(help_text="Total non-deleted cohorts on the team.")+ recent = serializers.ListField(+ child=RecentCohortEntrySerializer(),+ help_text="The 5 most recently created cohorts.",+ )+++class RecentActionEntrySerializer(serializers.Serializer):+ """One row in `inventory.recent_actions.recent`."""++ id = serializers.IntegerField(help_text="Action ID.")+ name = serializers.CharField(allow_blank=True, help_text="Action name.")+ updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-modified timestamp.")+++class RecentActionsSerializer(serializers.Serializer):+ """`inventory.recent_actions` — total + the 5 most recently modified."""++ total_count = serializers.IntegerField(help_text="Total non-deleted actions on the team.")+ recent = serializers.ListField(+ child=RecentActionEntrySerializer(),+ help_text="The 5 most recently updated actions.",+ )+++class ProjectProfileInventorySerializer(serializers.Serializer):+ """The deterministic inventory layer of a project profile.++ Read this to orient on the team's product mix, integrations, warehouse sources, signal+ coverage, and existing inbox surface in one tool call. Distinct from `SignalScratchpad`:+ profile is ground truth from authoritative tables; memory is agent inference.+ """++ project_context = ProjectContextSerializer(+ help_text="Free-form orientation: human-set product description + registered app URLs.",+ )+ products_in_use = serializers.ListField(+ child=serializers.CharField(),+ help_text="Product keys this team has completed onboarding for, sorted alphabetically.",+ )+ product_intents = serializers.ListField(+ child=ProductIntentEntrySerializer(),+ help_text="Products the team signaled intent to use; useful for spotting stuck onboardings.",+ )+ integrations = serializers.ListField(+ child=IntegrationEntrySerializer(),+ help_text="Connected integrations (kind + connection time only — config never surfaced).",+ )+ external_data_sources = serializers.ListField(+ child=ExternalDataSourceEntrySerializer(),+ help_text="Connected warehouse sources (excludes soft-deleted).",+ )+ signal_source_configs = SignalSourceConfigsBucketsSerializer(+ help_text="Signal source configs split into enabled / disabled buckets.",+ )+ existing_inbox_reports = ExistingInboxReportsSerializer(+ help_text="Counts of reports already in the inbox, grouped by status.",+ )+ recent_activity = RecentActivitySerializer(+ help_text=(+ "Per-scope counts off the activity log over the recent-activity window — "+ "cross-cutting orientation across every entity type (surveys, feature flags, "+ "experiments, dashboards, insights, cohorts, notebooks, actions, etc.). Each "+ "scope reports `edits` (total log entries), `users` (distinct user count), "+ "and `last_edit` (ISO-8601). Use to triage which scope a team has been working "+ "in lately before drilling down via the per-entity readers or `activity-log-list`."+ ),+ )+ recent_dashboards = serializers.ListField(+ child=RecentDashboardEntrySerializer(),+ help_text=(+ "Up to 20 dashboards on this team sorted by `last_accessed_at` desc — "+ "what the team is currently looking at, not necessarily the most-trafficked. "+ "We don't have per-dashboard view counts in Postgres, only the timestamp of "+ "the most recent access."+ ),+ )+ recent_surveys = RecentSurveysSerializer(+ help_text=(+ "Surveys orientation: total + active count, plus the 5 most recently updated "+ "surveys with id, name, type, status (draft / running / stopped / archived), and updated_at."+ ),+ )+ recent_feature_flags = RecentFeatureFlagsSerializer(+ help_text=(+ "Feature flag orientation: total + active count, plus the 5 most recently "+ "updated non-deleted flags with id, key, name, active, and updated_at."+ ),+ )+ recent_experiments = RecentExperimentsSerializer(+ help_text=(+ "Experiment orientation: total + running count, plus the 5 most recently "+ "updated experiments. The feature_flag_key on each row lets the scout correlate "+ "experiments with the `recent_feature_flags` section."+ ),+ )+ recent_alerts = RecentAlertsSerializer(+ help_text=(+ "Alert orientation: total + enabled count, plus the 5 most recently created "+ "alerts with their state and threshold metadata."+ ),+ )+ recent_hog_functions = RecentHogFunctionsSerializer(+ help_text=(+ "Hog function orientation: total + enabled count, plus the 5 most recently "+ "updated destinations / transformations the team has wired up via the CDP pipelines."+ ),+ )+ recent_hog_flows = RecentHogFlowsSerializer(+ help_text=(+ "Hog flow orientation: total + non-archived count, plus the 5 most recently updated automation flows."+ ),+ )+ recent_notebooks = RecentNotebooksSerializer(+ help_text=(+ "Notebook orientation: total + the 5 most recently modified notebooks — "+ "useful signal for what the team has been investigating."+ ),+ )+ recent_cohorts = RecentCohortsSerializer(+ help_text="Cohort orientation: total + the 5 most recently created cohorts on the team.",+ )+ recent_actions = RecentActionsSerializer(+ help_text=(+ "Action orientation: total + the 5 most recently updated actions — useful to "+ "anchor agent reasoning about what the team treats as a meaningful interaction."+ ),+ )+ top_events = serializers.ListField(+ child=TopEventEntrySerializer(),+ allow_null=True,+ help_text=(+ "Top ~50 events by count over the last 7 days, with first/last seen "+ "timestamps within the window. `null` if the underlying ClickHouse query "+ "failed or timed out (distinct from `[]`, which means the team has no "+ "captures in the window). Use the gap between `first_seen` and `now` to "+ "spot new event types or recent bursts."+ ),+ )+++class ProjectProfilePayloadSerializer(serializers.Serializer):+ """Top-level `payload` shape on a `SignalProjectProfile` row.++ v1 carries `inventory` only. Phase 7 will add `deltas`, `activity_notes`, and+ `narrative` slots — they're absent (not null) in v1 responses.+ """++ inventory = ProjectProfileInventorySerializer(help_text="Deterministic snapshot of what's true about the project.")+++class ProjectProfileQuerySerializer(serializers.Serializer):+ """Query parameters for the `current` action on `SignalProjectProfileViewSet`."""++ force_refresh = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "When true, skip the cache and rebuild the profile from authoritative sources before "+ "responding. Use after seeding events, importing data, or any other change the caller "+ "knows just landed but hasn't surfaced through natural cache expiry yet. Honored only "+ "for the internal scout token — public read callers get the cached profile regardless. "+ "Concurrent forced rebuilds are serialized by the team-keyed advisory lock — at most "+ "one extra `build_inventory` per simultaneous request."+ ),+ )+++class ProjectProfileSerializer(serializers.Serializer):+ """Wire shape for the project profile returned by `signals-scout-harness-project-profile-list`.++ Read this once at the start of a run (after `skill-get`) to orient on the team. Cache+ is per-team with a soft TTL (`PROFILE_TTL`); the response always reflects either the+ latest cached profile or a freshly-built one if the cache was stale or the caller passed+ `force_refresh=true`.+ """++ profile_id = serializers.CharField(help_text="UUID of the `SignalProjectProfile` row.")+ computed_at = serializers.CharField(help_text="ISO-8601 timestamp the profile was built.")+ expires_at = serializers.CharField(help_text="ISO-8601 timestamp after which the profile is considered stale.")+ source_version = serializers.CharField(+ help_text="Schema version of the inventory builder. Bumps invalidate older cached rows.",+ )+ payload = ProjectProfilePayloadSerializer(+ help_text="Structured profile content. v1 has `inventory` only.",+ )diff --git a/products/signals/backend/scout_harness/tools/__init__.py b/products/signals/backend/scout_harness/tools/__init__.pyindex e16a3ffd5988..86bab9fa8d1b 100644--- a/products/signals/backend/scout_harness/tools/__init__.py+++ b/products/signals/backend/scout_harness/tools/__init__.py@@ -12,6 +12,12 @@ from products.signals.backend.scout_harness.tools.emit import (InvalidEmitError,emit_finding,)+from products.signals.backend.scout_harness.tools.profile import (+ PROFILE_TTL,+ ProjectProfile,+ compute_project_profile,+ get_project_profile,+)from products.signals.backend.scout_harness.tools.runs import (DEFAULT_RUN_SEARCH_LIMIT,MAX_RUN_SEARCH_LIMIT,@@ -36,11 +42,15 @@ __all__ = ["InvalidScratchpadError","MAX_EVIDENCE_ENTRIES","MAX_RUN_SEARCH_LIMIT",+ "PROFILE_TTL",+ "ProjectProfile","ScratchpadEntry","RunDetail","RunSummary",+ "compute_project_profile","emit_finding","forget",+ "get_project_profile","get_run","remember","search_scratchpad",diff --git a/products/signals/backend/scout_harness/tools/profile.py b/products/signals/backend/scout_harness/tools/profile.pynew file mode 100644index 000000000000..b438b1eb70df--- /dev/null+++ b/products/signals/backend/scout_harness/tools/profile.py@@ -0,0 +1,225 @@+"""Project profile tool: a deterministic snapshot of "what's true about this project".++The agent calls `get_project_profile` (via the MCP wrapper) right after reading its skill,+so a fresh scout doesn't burn 4-5 orientation tool calls on `inbox-source-configs-list` /+`inbox-reports-list` / `read-data-schema` before having a baseline picture of the team.++`get_project_profile` returns the newest non-expired `SignalProjectProfile` row for the+team, or builds a fresh one on cache miss. `compute_project_profile` is the explicit+build path used by the cache-miss branch and (in Phase 7) by the daily Temporal workflow.++Profile is *deterministic ground truth* (computed from authoritative tables). Distinct+from `SignalScratchpad`, which is the *scout's inferred learnings* (TTL'd, possibly wrong).+Profile feeds the scratchpad; the scratchpad does not update profile.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass, field+from datetime import timedelta+from typing import Any++from django.db import connection, transaction+from django.utils import timezone++from posthog.models.scoping.manager import resolve_effective_team_id+from posthog.models.team.team import Team++from products.signals.backend.models import SignalProjectProfile+from products.signals.backend.scout_harness.profile import INVENTORY_SOURCE_VERSION, build_inventory++# Soft cache TTL — `get_project_profile` recomputes when the newest row is older than this.+# Aligned to the coordinator tick (60min in prod, 15min in dev) so an active team's+# agent runs see fresh ground-truth at most one tick stale. The TTL is a freshness+# floor, not a smoothing knob — smoothing comes from the time windows the inventory+# builders themselves query. Profile builds are single-flighted under the advisory+# lock below, so per-team build rate is bounded by 1/TTL regardless of fan-out width.+# Callers that *know* the underlying data just changed can bypass the cache via+# `get_project_profile(..., force_refresh=True)`.+PROFILE_TTL = timedelta(hours=1)++# Keep the last N profiles per team. The table is append-only on cache miss; without+# pruning a single active team accumulates indefinitely. Phase 7 diff logic only needs+# the previous row, so N=10 leaves comfortable slack for diff windows and debugging+# without unbounded growth.+PROFILE_KEEP_N = 10++# Advisory-lock namespace key for `pg_advisory_xact_lock(ns, team_id)`. Picked+# arbitrarily but stable so concurrent workers serialize on the same lock. The+# 32-bit namespace + 32-bit team_id form Postgres' 2-int advisory key.+_PROFILE_LOCK_NAMESPACE = 0x5191A1A6 # "SIGNAL"-ish leetspeak; just needs to be unique enough.+++@dataclass(frozen=True)+class ProjectProfile:+ """Wire shape for a `SignalProjectProfile` row.++ `payload` is the structured snapshot — currently `{inventory: {...}}`; Phase 7 fills+ in `deltas`, `activity_notes`, and `narrative`. Surfaced as a dict because consumers+ (the agent, the scout's prompts) read it as JSON, but the `inventory` block is+ validated against the `Inventory` schema on write (see `profile/schema.py`), so the+ stored jsonb is schema-backed rather than free-form.+ """++ profile_id: str+ computed_at: str+ expires_at: str+ source_version: str+ payload: dict[str, Any] = field(default_factory=dict)++ def as_dict(self) -> dict[str, Any]:+ return asdict(self)+++def get_project_profile(*, team_id: int, force_refresh: bool = False, lazy_build: bool = True) -> ProjectProfile | None:+ """Return a fresh project profile for a team, computing on cache miss.++ Reads the newest `SignalProjectProfile` row; if expired or absent, recomputes inline+ and persists. The lazy compute path keeps brand-new teams (no profile yet) usable+ without waiting for the daily Temporal workflow.++ `lazy_build=False` turns this into a pure cache read: on a miss it returns `None`+ instead of building. Untrusted read callers (a session-authenticated GET, or a+ `signal_scout:read` PAK without the internal scope) pass this so the read can't trigger+ the expensive inventory rebuild + row write — DRF exempts safe methods from CSRF, so a+ build on cache miss would otherwise be CSRF-reachable. The headless scout (internal+ token) and the Temporal workflow keep the default build-on-miss path. `force_refresh`+ always builds, regardless of `lazy_build`.++ `SignalProjectProfile` is a `TeamScopedRootMixin` model, so `RootTeamMixin.save()`+ stores every row under the *canonical* (root) team. Resolve the requested `team_id`+ to its canonical id up front so the cache read keys on the same id the write used —+ without this, a request scoped to an environment (child) team would never match its+ own cached row and would recompute the full inventory on every call.++ Cache hit is the steady-state path, so the full `Team` fetch is deferred to the miss+ branch — a hit completes with the cheap canonical-id resolution plus one indexed query+ against `signal_project_profile`, rather than fetching the whole `Team` row.++ `force_refresh=True` skips the cache lookup and goes straight to a rebuild, for+ callers that know the underlying data just changed (e.g. a dev seeded events into+ the project and wants the agent's view to reflect them on the next run, instead of+ waiting up to `PROFILE_TTL` for natural expiry). The compute path still takes the+ advisory lock, so concurrent force-refreshes collapse into one build with the+ losers returning the winner's freshly persisted row.+ """+ team_id = resolve_effective_team_id(team_id)+ if not force_refresh:+ cached = _latest_fresh_profile(team_id=team_id)+ if cached is not None:+ return _to_dataclass(cached)+ if not lazy_build:+ # Pure cache read: a miss returns None rather than triggering an inline build,+ # so an untrusted (CSRF-reachable) GET stays side-effect-free.+ return None+ team = Team.objects.get(id=team_id)+ return compute_project_profile(team=team, force=force_refresh)+++def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfile:+ """Build a new profile from authoritative sources and persist it.++ Currently writes the inventory layer only. The row is the cache for the next+ `PROFILE_TTL` (until `expires_at`); `get_project_profile` reads the newest+ non-expired row before paying the build cost again.++ Concurrent cache misses (Temporal coordinator + lazy MCP call hitting the same team+ at once) take a Postgres advisory lock keyed on team_id and re-check the cache after+ acquiring it. Without this, a thundering herd would each run `build_inventory` and+ insert a separate row; the lock collapses them into a single build with the losers+ returning the winner's freshly persisted row. After persisting, prune so only the+ last `PROFILE_KEEP_N` rows survive — the table would otherwise grow unbounded+ (one row per cache miss, ~once per `PROFILE_TTL` per team, forever).++ `force=True` skips the post-lock re-check so a caller that explicitly asked for a+ rebuild (via `get_project_profile(force_refresh=True)`) actually gets one even when+ a fresh row exists. The lock still serializes concurrent forced rebuilds, so the+ cost is at most one duplicate `build_inventory` per simultaneous force request —+ bounded and only paid by callers who knowingly opted into it.+ """+ # Canonicalize: `RootTeamMixin.save()` stores the row under the root team, so the+ # advisory lock, post-lock cache re-check, and prune must all key on the canonical+ # id too. `get_project_profile` already passes a canonical team; this guards the+ # direct / Phase-7 call path where an environment (child) team could be passed in.+ parent_team = team.parent_team+ if parent_team is not None:+ team = parent_team+ with transaction.atomic():+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [_PROFILE_LOCK_NAMESPACE, team.id])+ if not force:+ # Re-check after the lock — another worker may have just persisted a fresh row.+ existing = _latest_fresh_profile(team_id=team.id)+ if existing is not None:+ return _to_dataclass(existing)+ payload: dict[str, Any] = {"inventory": build_inventory(team).model_dump(mode="json")}+ now = timezone.now()+ # `.unscoped()` to match the reads above — off-request builds have no ambient team.+ row = SignalProjectProfile.objects.unscoped().create(+ team=team,+ expires_at=now + PROFILE_TTL,+ source_version=INVENTORY_SOURCE_VERSION,+ payload=payload,+ )+ _prune_stale_profiles(team_id=team.id)+ return _to_dataclass(row)+++def _prune_stale_profiles(*, team_id: int) -> int:+ """Delete all but the `PROFILE_KEEP_N` most recent profiles for a team.++ Bounds row growth on the time-series profile table. Called from inside the+ `compute_project_profile` transaction so prune happens under the same advisory+ lock as the insert — no risk of two workers racing to delete each other's rows.+ Returns the deleted-row count for logging/tests.++ `team_id` is the canonical id (callers resolve it before getting here), so query+ `.unscoped()` and filter on it explicitly rather than leaning on ambient team+ context — keeps the prune correct off the request path (Phase-7 Temporal) too.+ """+ keep_ids = list(+ SignalProjectProfile.objects.unscoped()+ .filter(team_id=team_id)+ .order_by("-computed_at")+ .values_list("id", flat=True)[:PROFILE_KEEP_N]+ )+ deleted, _ = SignalProjectProfile.objects.unscoped().filter(team_id=team_id).exclude(id__in=keep_ids).delete()+ return deleted+++def _latest_fresh_profile(*, team_id: int) -> SignalProjectProfile | None:+ """Newest profile for the team that's still within its TTL and on the current schema.++ Both checks matter: an expired row should be recomputed even if its schema matches,+ and a row on an older `source_version` is treated as a miss so a schema bump silently+ invalidates stale shapes without a manual backfill.++ `team_id` is the canonical id (callers resolve it before getting here), so query+ `.unscoped()` and filter on it explicitly. Going through the fail-closed manager+ would also apply the ambient `get_current_team_id()` filter, which for an environment+ (child) team request is the canonical parent id — combined with an explicit raw+ child-id filter that would never match the parent-scoped row, the cache would silently+ never hit. Filtering on the resolved canonical id directly keeps read symmetric with+ `RootTeamMixin.save()`'s canonicalized write.+ """+ now = timezone.now()+ return (+ SignalProjectProfile.objects.unscoped()+ .filter(+ team_id=team_id,+ expires_at__gt=now,+ source_version=INVENTORY_SOURCE_VERSION,+ )+ .order_by("-computed_at")+ .first()+ )+++def _to_dataclass(row: SignalProjectProfile) -> ProjectProfile:+ return ProjectProfile(+ profile_id=str(row.id),+ computed_at=row.computed_at.isoformat(),+ expires_at=row.expires_at.isoformat(),+ source_version=row.source_version,+ payload=dict(row.payload or {}),+ )diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex e616b61518d2..9e2dfe401ef5 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -2,9 +2,9 @@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.+tools — `runs-list`, `runs-retrieve`, `runs-findings-create`, `memory-list`,+`memory-create`, `memory-delete`, and `project-profile-get` — over the standard+PostHog MCP plumbing.Auth uses two dedicated scope objects: `signal_scout:read` is user-grantablevia the personal-API-key picker (so a team can introspect runs/scratchpad from@@ -39,13 +39,15 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.permissions import APIScopePermission-from products.signals.backend.models import SignalScoutRun+from products.signals.backend.models import SignalProjectProfile, SignalScoutRunfrom products.signals.backend.scout_harness.serializers import (EmitFindingRequestSerializer,EmitFindingResponseSerializer,EvidenceEntrySerializer,ForgetRequestSerializer,ForgetResponseSerializer,+ ProjectProfileQuerySerializer,+ ProjectProfileSerializer,RememberRequestSerializer,ScratchpadEntrySerializer,SearchMemoryQuerySerializer,@@ -54,6 +56,7 @@ from products.signals.backend.scout_harness.serializers import (SignalScoutRunSummarySerializer,)from products.signals.backend.scout_harness.tools.emit import EvidenceEntry, InvalidEmitError, emit_finding_sync+from products.signals.backend.scout_harness.tools.profile import get_project_profilefrom products.signals.backend.scout_harness.tools.runs import get_run, search_recent_runsfrom products.signals.backend.scout_harness.tools.scratchpad import (InvalidScratchpadError,@@ -63,6 +66,31 @@ from products.signals.backend.scout_harness.tools.scratchpad import ()+def _caller_carries_scout_internal_scope(request: Request) -> bool:+ """True only when the request authenticates with the sandbox-internal scout scope.++ The profile build — whether a `force_refresh` rebuild or the lazy build on cache miss —+ runs per-section table scans plus the ClickHouse top-events aggregation and writes a+ row. Honoring either for any `signal_scout:read` PAK would let an attacker spam+ expensive recomputes, and honoring either on a session-authenticated GET makes the+ rebuild CSRF-triggerable (DRF exempts safe methods from CSRF). The headless scout's+ sandbox OAuth token is the only caller that legitimately builds inline, and it's minted+ with `signal_scout_internal:write` via `SCOUT_INTERNAL_SCOPES` — so gate the build on+ that scope. Session and other non-token auth carry no API scopes and never pass, which+ closes the CSRF path; untrusted read callers get the cached profile or a 404. `*`+ (full-access consent) deliberately does not match: internal scopes are not reachable+ via user-consented tokens.+ """+ authenticator = request.successful_authenticator+ if isinstance(authenticator, PersonalAPIKeyAuthentication):+ scopes = authenticator.personal_api_key.scopes or []+ elif isinstance(authenticator, OAuthAccessTokenAuthentication):+ scopes = (authenticator.access_token.scope or "").split()+ else:+ return False+ return "signal_scout_internal:write" in scopes++def _parse_run_id_or_404(kwargs: dict) -> uuid.UUID:"""Parse the `id` URL kwarg as a UUID; raise 404 on missing or malformed.@@ -361,3 +389,96 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):data = request.validated_dataremoved = forget(team_id=_canonical_team_id(self), key=data["key"])return Response(ForgetResponseSerializer({"deleted": removed}).data)+++class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Project profile — deterministic snapshot of \"what's true about this project\".++ Singleton per team — there's no list, retrieve, or write surface. The agent calls+ `current` right after reading its skill to orient on this team's product mix,+ integrations, signal coverage, and existing inbox surface in one tool call instead of+ burning 4-5 discovery calls. Lazy-recomputes on cache miss / TTL expiry / source-version+ bump; the response is always either the latest cached profile or a freshly-built one.++ Exposed as a `@action(detail=False, url_path="current")` rather than `list()` so the+ OpenAPI spec — and every generated client downstream of it (`api.ts`, MCP tool+ response shape, etc.) — types the response as a single `ProjectProfileApi` instead+ of `ProjectProfileApi[]`. drf-spectacular and Orval treat the bare `list` action as+ a paginated collection by URL convention even when `responses=ProjectProfileSerializer`+ is set; routing through a named action breaks that convention without changing the+ semantics.+ """++ serializer_class = ProjectProfileSerializer+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission]+ scope_object = "signal_scout"+ # `.unscoped()` — see `SignalScoutRunViewSet` for the same module-load reasoning.+ # The `current` action filters by team_id explicitly via `get_project_profile`.+ queryset = SignalProjectProfile.objects.unscoped()+ pagination_class = None++ # The DRF default `list` operation_id would be `signals_scout_project_profile_list`,+ # which renders as `signals-scout-project-profile-list` in the MCP. The agent-facing+ # tool is semantically a "get the current profile" (singleton), not a "list" — override+ # the id so it matches the tool name in tools.yaml and the scout's bootstrap step.+ @validated_request(+ operation_id="signals_scout_project_profile_get",+ query_serializer=ProjectProfileQuerySerializer,+ responses={+ 200: OpenApiResponse(+ response=ProjectProfileSerializer,+ description="The team's current project profile (cached, or freshly built for the internal scout token).",+ ),+ 404: OpenApiResponse(+ description=(+ "No profile has been built for this team yet, and the caller is not the internal scout "+ "token (which builds on cache miss). Public read callers never trigger a build."+ ),+ ),+ },+ summary="Get the current project profile",+ description=(+ "Return the team's deterministic project profile. For the internal scout token the response "+ "reflects the newest non-expired cached row or a freshly-built one (lazy compute on cache miss); "+ "`force_refresh=true` skips the cache and rebuilds from authoritative sources. Public read callers "+ "(session auth or a `signal_scout:read` PAK) get the newest cached profile, or 404 if none has been "+ "built yet — they never trigger a rebuild. Read this at the start of a run to orient on the team's "+ "product mix, integrations, warehouse sources, signal coverage, and existing inbox surface."+ ),+ )+ @action(+ detail=False,+ methods=["get"],+ url_path="current",+ url_name="current",+ pagination_class=None,+ # Without explicit `required_scopes`, `APIScopePermission` falls into the+ # "no scopes declared" branch in `posthog/permissions.py:490` and rejects+ # the request — the rejection message even reads "does not support+ # personal API key access" regardless of whether the request was+ # authenticated via PAK or OAuth, because that branch fires for both.+ # `signal_scout:read` is the public, user-grantable read scope already+ # used by `runs-list`, `runs-retrieve`, and `memory-list` on this surface.+ required_scopes=["signal_scout:read"],+ )+ def current(self, request: Request, *args, **kwargs) -> Response:+ validated = getattr(request, "validated_query_data", {}) or {}+ caller_is_internal_scout = _caller_carries_scout_internal_scope(request)+ # Both `force_refresh` and the lazy build-on-miss run the full inventory rebuild+ # (per-section table scans + the ClickHouse top-events aggregation) and write a row,+ # so both are gated to the internal scout token. A session-authenticated GET bypasses+ # CSRF (safe method), so letting it build would make the rebuild CSRF-triggerable; a+ # `signal_scout:read` PAK could likewise spam recomputes. Untrusted read callers get+ # the newest cached profile, or a 404 if none exists — they never trigger a build. The+ # scout's sandbox token carries `signal_scout_internal:write`, and the Phase-7 Temporal+ # workflow builds out-of-band, so the build path stays covered.+ force_refresh = bool(validated.get("force_refresh", False)) and caller_is_internal_scout+ profile = get_project_profile(+ team_id=_canonical_team_id(self),+ force_refresh=force_refresh,+ lazy_build=caller_is_internal_scout,+ )+ if profile is None:+ raise exceptions.NotFound("No project profile has been built for this team yet.")+ return Response(ProjectProfileSerializer(profile.as_dict()).data)diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 60c54d238cbe..f0123dc3fa15 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -151,6 +151,11 @@ class TestPromptBuilder(BaseTest):assert "llma-skill-file-get" in promptassert "watch for spikes" not in promptassert "refs/playbook.md" not in prompt+ # Second bootstrap step orients the agent on the project via the+ # project-profile harness tool, eliminating the discovery-burn the+ # scout would otherwise pay on a fresh team.+ assert "Then: orient on this project" in prompt+ assert "signals-scout-project-profile-get" in prompt# The base prompt teaches the agent to call the harness MCP tools by name.assert "signals-scout-emit-signal" in promptassert "signals-scout-scratchpad-search" in promptdiff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex eccde5b2bb86..1446bc67c208 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -18,7 +18,8 @@ from posthog.temporal.oauth import (create_oauth_access_token_for_user,)-from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad+from products.signals.backend.models import SignalProjectProfile, SignalScoutConfig, SignalScoutRun, SignalScratchpad+from products.signals.backend.scout_harness.tools.profile import compute_project_profilefrom products.tasks.backend.models import Task, TaskRun# Fresh RSA key so RS256 OAuth apps validate in tests (OIDC_RSA_PRIVATE_KEY is unset by@@ -354,3 +355,114 @@ class TestScoutHarnessScratchpadAPI(APIBaseTest):format="json",)assert response.status_code == status.HTTP_400_BAD_REQUEST+++@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _OIDC_RSA_KEY})+class TestAgentHarnessProjectProfileAPI(APIBaseTest):+ """The project profile is the scout's orientation surface — read once at run start.++ The build path (per-section table scans + a ClickHouse aggregation, plus a row write)+ is gated to the internal scout token: a session GET bypasses CSRF, so letting it build+ on cache miss would make the rebuild CSRF-triggerable. These tests cover the read-only+ contract for untrusted callers (cached-or-404, never a build) and the scout's lazy build.+ """++ def _list_url(self) -> str:+ # The viewset exposes the singleton via an explicit `@action(url_path="current")`+ # (not `list()`), so the route is /project_profile/current/. Generated TS clients+ # call /current/; tests must match or the requests 404 and never exercise the view.+ return f"/api/projects/{self.team.id}/signals/scout/project_profile/current/"++ def _seed_profile(self, *, team: Team | None = None) -> str:+ """Persist a real, schema-valid profile via the build path so a later read hits the+ cache, and return its profile_id. Building here is fine — the behavior under test is+ that the *read* doesn't build, not that nothing ever builds.+ """+ return compute_project_profile(team=team or self.team).profile_id++ # --- untrusted (session) callers: read-only, never build ---++ def test_session_read_returns_404_when_no_profile_exists(self) -> None:+ # A session GET bypasses CSRF, so it must not trigger an inline build. With no+ # cached row the read-only caller gets a 404 rather than a freshly-built profile.+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 0+ response = self.client.get(self._list_url())+ assert response.status_code == status.HTTP_404_NOT_FOUND+ # No row written as a side effect of the GET.+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 0++ def test_session_read_returns_cached_profile(self) -> None:+ seeded_id = self._seed_profile()+ response = self.client.get(self._list_url())+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["profile_id"] == seeded_id+ assert {"profile_id", "computed_at", "expires_at", "source_version"} <= set(body.keys())+ assert "inventory" in body["payload"]+ # Read-only: no new row written.+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 1++ def test_session_read_ignores_force_refresh(self) -> None:+ # `force_refresh` is honored only for the internal scout token. A session caller+ # passing it still gets the cached row — no rebuild, no second row.+ seeded_id = self._seed_profile()+ response = self.client.get(self._list_url(), {"force_refresh": "true"})+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["profile_id"] == seeded_id+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 1++ def test_session_read_does_not_leak_other_teams_profile(self) -> None:+ # Another team in the same org has a profile; ours does not. A session GET must+ # neither build ours nor surface theirs — it 404s.+ other = Team.objects.create(organization=self.organization, name="Other")+ self._seed_profile(team=other)+ response = self.client.get(self._list_url())+ assert response.status_code == status.HTTP_404_NOT_FOUND++ # --- internal scout token: lazy-builds on miss ---++ def test_scout_read_lazy_computes_a_profile_when_none_exists(self) -> None:+ _authenticate_as_scout(self)+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 0+ response = self.client.get(self._list_url())+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ # Response shape carries the cache metadata + the inventory payload.+ assert {"profile_id", "computed_at", "expires_at", "source_version"} <= set(body.keys())+ assert "inventory" in body["payload"]+ # And a row was persisted as a side effect of the scout's build.+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 1++ def test_scout_read_returns_cached_profile_on_repeat_call(self) -> None:+ _authenticate_as_scout(self)+ first = self.client.get(self._list_url()).json()+ second = self.client.get(self._list_url()).json()+ assert first["profile_id"] == second["profile_id"]+ # No second row written.+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 1++ def test_scout_read_inventory_payload_carries_expected_keys(self) -> None:+ _authenticate_as_scout(self)+ response = self.client.get(self._list_url())+ inventory = response.json()["payload"]["inventory"]+ assert set(inventory.keys()) == {+ "project_context",+ "products_in_use",+ "product_intents",+ "integrations",+ "external_data_sources",+ "signal_source_configs",+ "existing_inbox_reports",+ "recent_activity",+ "recent_dashboards",+ "recent_surveys",+ "recent_feature_flags",+ "recent_experiments",+ "recent_alerts",+ "recent_hog_functions",+ "recent_hog_flows",+ "recent_notebooks",+ "recent_cohorts",+ "recent_actions",+ "top_events",+ }diff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.pynew file mode 100644index 000000000000..8210d384fcaa--- /dev/null+++ b/products/signals/backend/test/test_scout_harness_profile.py@@ -0,0 +1,699 @@+"""Tests for the project profile tools and inventory aggregator.++Layered top-down: builder source-readers → `compute_project_profile` end-to-end →+`get_project_profile` cache-hit / cache-miss paths.+"""++from __future__ import annotations++from datetime import timedelta++from posthog.test.base import BaseTest++from django.utils import timezone++from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.cohort.cohort import Cohort+from posthog.models.integration import Integration+from posthog.models.product_intent.product_intent import ProductIntent+from posthog.models.user import User++from products.actions.backend.models.action import Action+from products.alerts.backend.models.alert import AlertConfiguration+from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.dashboards.backend.models.dashboard import Dashboard+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insight+from products.signals.backend.models import SignalProjectProfile, SignalReport, SignalSourceConfig+from products.signals.backend.scout_harness.profile import INVENTORY_SOURCE_VERSION, Inventory, build_inventory+from products.signals.backend.scout_harness.profile.builders import (+ RECENT_ACTIVITY_WINDOW_DAYS,+ _existing_inbox_reports,+ _external_data_sources,+ _integrations,+ _product_intents,+ _products_in_use,+ _project_context,+ _recent_actions,+ _recent_activity,+ _recent_alerts,+ _recent_cohorts,+ _recent_dashboards,+ _recent_experiments,+ _recent_feature_flags,+ _recent_hog_flows,+ _recent_hog_functions,+ _recent_notebooks,+ _recent_surveys,+ _signal_source_configs,+)+from products.signals.backend.scout_harness.tools.profile import (+ PROFILE_TTL,+ compute_project_profile,+ get_project_profile,+)+from products.surveys.backend.models import Survey+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+++class TestProjectContext(BaseTest):+ def test_returns_product_description_and_app_urls(self) -> None:+ self.team.app_urls = ["https://app.example.com", "https://docs.example.com"]+ self.team.save()+ self.team.project.product_description = "A demo SaaS for testing"+ self.team.project.save()+ result = _project_context(self.team)+ assert result == {+ "product_description": "A demo SaaS for testing",+ "app_urls": ["https://app.example.com", "https://docs.example.com"],+ }++ def test_null_product_description_when_unset(self) -> None:+ self.team.project.product_description = None+ self.team.project.save()+ self.team.app_urls = []+ self.team.save()+ result = _project_context(self.team)+ assert result == {"product_description": None, "app_urls": []}++ def test_strips_blank_product_description(self) -> None:+ # A blank-string description should surface as null so the agent doesn't read+ # an empty string as "I have a product description, it's just empty."+ self.team.project.product_description = " "+ self.team.project.save()+ result = _project_context(self.team)+ assert result["product_description"] is None++ def test_filters_empty_app_urls(self) -> None:+ self.team.app_urls = ["https://app.example.com", "", None]+ self.team.save()+ result = _project_context(self.team)+ assert result["app_urls"] == ["https://app.example.com"]+++class TestProductsInUse(BaseTest):+ def test_returns_keys_with_truthy_values_sorted(self) -> None:+ self.team.has_completed_onboarding_for = {"product_analytics": True, "session_replay": True, "surveys": False}+ self.team.save()+ assert _products_in_use(self.team) == ["product_analytics", "session_replay"]++ def test_empty_when_field_is_null(self) -> None:+ self.team.has_completed_onboarding_for = None+ self.team.save()+ assert _products_in_use(self.team) == []++ def test_handles_non_dict_field_gracefully(self) -> None:+ # Defensive: if the JSON field somehow holds a non-dict value, return [] rather than raise.+ self.team.has_completed_onboarding_for = ["product_analytics"]+ self.team.save()+ assert _products_in_use(self.team) == []+++class TestProductIntents(BaseTest):+ def test_returns_intents_for_team_only(self) -> None:+ ProductIntent.objects.create(team=self.team, product_type="error_tracking")+ # Other team's intent should not appear.+ other = self.organization.teams.create(name="other")+ ProductIntent.objects.create(team=other, product_type="data_warehouse")+ result = _product_intents(self.team)+ assert [r["product_type"] for r in result] == ["error_tracking"]++ def test_carries_activated_at_when_set(self) -> None:+ intent = ProductIntent.objects.create(team=self.team, product_type="experiments")+ when = timezone.now()+ ProductIntent.objects.filter(id=intent.id).update(activated_at=when)+ result = _product_intents(self.team)+ assert result[0]["activated_at"] is not None+++class TestIntegrations(BaseTest):+ def test_lists_integrations_by_kind(self) -> None:+ Integration.objects.create(team=self.team, kind="github", config={})+ Integration.objects.create(team=self.team, kind="slack", config={})+ result = _integrations(self.team)+ assert sorted(r["kind"] for r in result) == ["github", "slack"]++ def test_does_not_leak_config_or_sensitive_config(self) -> None:+ # Defensive: integration config/sensitive_config can hold tokens; only kind + created_at+ # should reach the agent.+ Integration.objects.create(+ team=self.team,+ kind="slack",+ config={"workspace_id": "T123"},+ sensitive_config={"access_token": "xoxb-secret"},+ )+ result = _integrations(self.team)+ assert "config" not in result[0]+ assert "sensitive_config" not in result[0]+++class TestExternalDataSources(BaseTest):+ def test_excludes_deleted_rows(self) -> None:+ ExternalDataSource.objects.create(team=self.team, source_type="Stripe", status="Running", prefix="stripe_")+ ExternalDataSource.objects.create(+ team=self.team, source_type="Hubspot", status="Running", prefix="hub_", deleted=True+ )+ result = _external_data_sources(self.team)+ assert [r["source_type"] for r in result] == ["Stripe"]++ def test_carries_status_and_prefix(self) -> None:+ ExternalDataSource.objects.create(team=self.team, source_type="Postgres", status="Failed", prefix="pg_")+ result = _external_data_sources(self.team)+ assert result[0]["status"] == "Failed"+ assert result[0]["prefix"] == "pg_"+++class TestSignalSourceConfigs(BaseTest):+ def test_splits_enabled_and_disabled(self) -> None:+ SignalSourceConfig.objects.create(+ team=self.team,+ source_product=SignalSourceConfig.SourceProduct.ERROR_TRACKING,+ source_type=SignalSourceConfig.SourceType.ISSUE,+ enabled=True,+ )+ SignalSourceConfig.objects.create(+ team=self.team,+ source_product=SignalSourceConfig.SourceProduct.LINEAR,+ source_type=SignalSourceConfig.SourceType.TICKET,+ enabled=False,+ )+ result = _signal_source_configs(self.team)+ assert len(result["enabled"]) == 1+ assert result["enabled"][0]["source_product"] == "error_tracking"+ assert len(result["disabled"]) == 1+ assert result["disabled"][0]["source_product"] == "linear"+++class TestExistingInboxReports(BaseTest):+ def test_groups_by_status_excluding_deleted_and_suppressed(self) -> None:+ SignalReport.objects.create(team=self.team, status=SignalReport.Status.POTENTIAL)+ SignalReport.objects.create(team=self.team, status=SignalReport.Status.POTENTIAL)+ SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY)+ SignalReport.objects.create(team=self.team, status=SignalReport.Status.DELETED)+ SignalReport.objects.create(team=self.team, status=SignalReport.Status.SUPPRESSED)+ result = _existing_inbox_reports(self.team)+ assert result["total"] == 3+ by_status = {row["status"]: row["count"] for row in result["by_status"]}+ assert by_status == {"potential": 2, "ready": 1}++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ SignalReport.objects.create(team=other, status=SignalReport.Status.READY)+ result = _existing_inbox_reports(self.team)+ assert result["total"] == 0+++class TestRecentDashboards(BaseTest):+ def test_orders_by_last_accessed_desc(self) -> None:+ old = Dashboard.objects.create(team=self.team, name="old")+ new = Dashboard.objects.create(team=self.team, name="new")+ Dashboard.objects.filter(id=old.id).update(last_accessed_at=timezone.now() - timedelta(hours=2))+ Dashboard.objects.filter(id=new.id).update(last_accessed_at=timezone.now())+ result = _recent_dashboards(self.team)+ assert [r["name"] for r in result] == ["new", "old"]++ def test_excludes_deleted(self) -> None:+ live = Dashboard.objects.create(team=self.team, name="live")+ gone = Dashboard.objects.create(team=self.team, name="gone", deleted=True)+ Dashboard.objects.filter(id=live.id).update(last_accessed_at=timezone.now())+ Dashboard.objects.filter(id=gone.id).update(last_accessed_at=timezone.now())+ result = _recent_dashboards(self.team)+ assert [r["name"] for r in result] == ["live"]++ def test_excludes_never_accessed(self) -> None:+ # last_accessed_at null = never opened — surfacing it as "recent" would lie.+ accessed = Dashboard.objects.create(team=self.team, name="accessed")+ Dashboard.objects.filter(id=accessed.id).update(last_accessed_at=timezone.now())+ Dashboard.objects.create(team=self.team, name="never") # last_accessed_at = null+ result = _recent_dashboards(self.team)+ assert [r["name"] for r in result] == ["accessed"]++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ d = Dashboard.objects.create(team=other, name="other-team")+ Dashboard.objects.filter(id=d.id).update(last_accessed_at=timezone.now())+ result = _recent_dashboards(self.team)+ assert result == []+++class TestRecentSurveys(BaseTest):+ def test_caps_at_recent_entity_limit_and_orders_by_updated_at(self) -> None:+ for i in range(7):+ Survey.objects.create(team=self.team, name=f"s{i}", type=Survey.SurveyType.POPOVER)+ result = _recent_surveys(self.team)+ assert result["total_count"] == 7+ assert len(result["recent"]) == 5 # RECENT_ENTITY_LIMIT++ def test_active_count_excludes_drafts_stopped_and_archived(self) -> None:+ # Only `running` should count as active. Draft = no start_date; stopped = end_date in past;+ # scheduled = start_date in the future.+ now = timezone.now()+ Survey.objects.create(team=self.team, name="running", type="popover", start_date=now - timedelta(days=1))+ Survey.objects.create(+ team=self.team,+ name="stopped",+ type="popover",+ start_date=now - timedelta(days=2),+ end_date=now - timedelta(hours=1),+ )+ Survey.objects.create(team=self.team, name="draft", type="popover")+ Survey.objects.create(team=self.team, name="archived", type="popover", start_date=now, archived=True)+ Survey.objects.create(team=self.team, name="scheduled", type="popover", start_date=now + timedelta(days=1))+ result = _recent_surveys(self.team)+ assert result["total_count"] == 5+ assert result["active_count"] == 1++ def test_status_field_derivation(self) -> None:+ now = timezone.now()+ Survey.objects.create(team=self.team, name="r", type="popover", start_date=now - timedelta(days=1))+ Survey.objects.create(team=self.team, name="d", type="popover")+ Survey.objects.create(+ team=self.team,+ name="s",+ type="popover",+ start_date=now - timedelta(days=2),+ end_date=now - timedelta(hours=1),+ )+ Survey.objects.create(team=self.team, name="a", type="popover", archived=True)+ result = _recent_surveys(self.team)+ statuses = {row["name"]: row["status"] for row in result["recent"]}+ assert statuses == {"r": "running", "d": "draft", "s": "stopped", "a": "archived"}++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ Survey.objects.create(team=other, name="x", type="popover")+ result = _recent_surveys(self.team)+ assert result == {"total_count": 0, "active_count": 0, "recent": []}+++class TestRecentFeatureFlags(BaseTest):+ def test_total_active_counts_and_recent_ordering(self) -> None:+ FeatureFlag.objects.create(team=self.team, key="a", name="A", active=True, created_by=self.user)+ FeatureFlag.objects.create(team=self.team, key="b", name="B", active=False, created_by=self.user)+ FeatureFlag.objects.create(team=self.team, key="c", name="C", active=True, deleted=True, created_by=self.user)+ result = _recent_feature_flags(self.team)+ # `c` is soft-deleted — excluded from total.+ assert result["total_count"] == 2+ assert result["active_count"] == 1+ keys = {row["key"] for row in result["recent"]}+ assert keys == {"a", "b"}++ def test_falls_back_to_key_when_name_blank(self) -> None:+ FeatureFlag.objects.create(team=self.team, key="my-flag", name="", active=True, created_by=self.user)+ result = _recent_feature_flags(self.team)+ assert result["recent"][0]["name"] == "my-flag"++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ FeatureFlag.objects.create(team=other, key="x", name="X", active=True, created_by=self.user)+ result = _recent_feature_flags(self.team)+ assert result["total_count"] == 0+++class TestRecentExperiments(BaseTest):+ def _flag(self, key: str) -> FeatureFlag:+ return FeatureFlag.objects.create(team=self.team, key=key, name=key, active=True, created_by=self.user)++ def test_running_count_only_counts_started_unfinished_unarchived(self) -> None:+ now = timezone.now()+ Experiment.objects.create(+ team=self.team, name="running", feature_flag=self._flag("ff-r"), start_date=now - timedelta(days=1)+ )+ Experiment.objects.create(team=self.team, name="draft", feature_flag=self._flag("ff-d"))+ Experiment.objects.create(+ team=self.team,+ name="stopped",+ feature_flag=self._flag("ff-s"),+ start_date=now - timedelta(days=10),+ end_date=now - timedelta(days=1),+ )+ Experiment.objects.create(+ team=self.team, name="archived", feature_flag=self._flag("ff-a"), start_date=now, archived=True+ )+ result = _recent_experiments(self.team)+ assert result["total_count"] == 4+ assert result["running_count"] == 1+ statuses = {row["name"]: row["status"] for row in result["recent"]}+ assert statuses == {+ "running": "running",+ "draft": "draft",+ "stopped": "stopped",+ "archived": "archived",+ }++ def test_carries_feature_flag_key_for_cross_reference(self) -> None:+ Experiment.objects.create(team=self.team, name="exp", feature_flag=self._flag("my-exp-flag"))+ result = _recent_experiments(self.team)+ assert result["recent"][0]["feature_flag_key"] == "my-exp-flag"++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ Experiment.objects.create(+ team=other, name="x", feature_flag=FeatureFlag.objects.create(team=other, key="o", created_by=self.user)+ )+ result = _recent_experiments(self.team)+ assert result["total_count"] == 0+++class TestRecentAlerts(BaseTest):+ def _insight(self, name: str = "i") -> Insight:+ return Insight.objects.create(team=self.team, name=name)++ def test_total_and_enabled_counts(self) -> None:+ AlertConfiguration.objects.create(team=self.team, insight=self._insight("a"), name="on", enabled=True)+ AlertConfiguration.objects.create(team=self.team, insight=self._insight("b"), name="off", enabled=False)+ result = _recent_alerts(self.team)+ assert result["total_count"] == 2+ assert result["enabled_count"] == 1++ def test_orders_by_created_at_desc(self) -> None:+ # AlertConfiguration has no `updated_at` (CreatedMetaFields only) — sort uses+ # created_at, which captures the high-signal "alert was newly configured" moment.+ first = AlertConfiguration.objects.create(team=self.team, insight=self._insight("a"), name="first")+ AlertConfiguration.objects.filter(id=first.id).update(created_at=timezone.now() - timedelta(days=2))+ AlertConfiguration.objects.create(team=self.team, insight=self._insight("b"), name="second")+ result = _recent_alerts(self.team)+ assert [r["name"] for r in result["recent"]] == ["second", "first"]++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ AlertConfiguration.objects.create(team=other, insight=Insight.objects.create(team=other, name="i"), name="x")+ result = _recent_alerts(self.team)+ assert result["total_count"] == 0+++class TestRecentHogFunctions(BaseTest):+ def test_total_enabled_counts_and_excludes_deleted(self) -> None:+ HogFunction.objects.create(team=self.team, name="a", enabled=True, type="destination", hog="")+ HogFunction.objects.create(team=self.team, name="b", enabled=False, type="transformation", hog="")+ HogFunction.objects.create(team=self.team, name="c", enabled=True, type="destination", deleted=True, hog="")+ result = _recent_hog_functions(self.team)+ assert result["total_count"] == 2+ assert result["enabled_count"] == 1++ def test_carries_type_and_kind_for_orientation(self) -> None:+ HogFunction.objects.create(+ team=self.team, name="dest", enabled=True, type="destination", kind="webhook", hog=""+ )+ result = _recent_hog_functions(self.team)+ row = result["recent"][0]+ assert row["type"] == "destination"+ assert row["kind"] == "webhook"++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ HogFunction.objects.create(team=other, name="x", enabled=True, type="destination", hog="")+ result = _recent_hog_functions(self.team)+ assert result["total_count"] == 0+++class TestRecentHogFlows(BaseTest):+ def test_total_active_counts_excludes_archived(self) -> None:+ HogFlow.objects.create(team=self.team, name="draft", status="draft")+ HogFlow.objects.create(team=self.team, name="active", status="active")+ HogFlow.objects.create(team=self.team, name="archived", status="archived")+ result = _recent_hog_flows(self.team)+ assert result["total_count"] == 3+ assert result["active_count"] == 2 # everything except archived++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ HogFlow.objects.create(team=other, name="x", status="active")+ result = _recent_hog_flows(self.team)+ assert result["total_count"] == 0+++class TestRecentNotebooks(BaseTest):+ def test_orders_by_last_modified_at_desc_and_caps_at_limit(self) -> None:+ for i in range(7):+ Notebook.objects.create(team=self.team, title=f"n{i}")+ result = _recent_notebooks(self.team)+ assert result["total_count"] == 7+ assert len(result["recent"]) == 5++ def test_excludes_deleted(self) -> None:+ Notebook.objects.create(team=self.team, title="live")+ Notebook.objects.create(team=self.team, title="gone", deleted=True)+ result = _recent_notebooks(self.team)+ assert result["total_count"] == 1+ assert result["recent"][0]["title"] == "live"++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ Notebook.objects.create(team=other, title="x")+ result = _recent_notebooks(self.team)+ assert result == {"total_count": 0, "recent": []}+++class TestRecentCohorts(BaseTest):+ def test_orders_by_created_at_desc(self) -> None:+ old = Cohort.objects.create(team=self.team, name="old", created_by=self.user)+ Cohort.objects.filter(id=old.id).update(created_at=timezone.now() - timedelta(days=3))+ Cohort.objects.create(team=self.team, name="new", created_by=self.user)+ result = _recent_cohorts(self.team)+ assert [r["name"] for r in result["recent"]] == ["new", "old"]++ def test_carries_is_static_and_count(self) -> None:+ Cohort.objects.create(team=self.team, name="static", is_static=True, count=42, created_by=self.user)+ result = _recent_cohorts(self.team)+ row = result["recent"][0]+ assert row["is_static"] is True+ assert row["count"] == 42++ def test_excludes_deleted_and_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ Cohort.objects.create(team=self.team, name="kept", created_by=self.user)+ Cohort.objects.create(team=self.team, name="gone", deleted=True, created_by=self.user)+ Cohort.objects.create(team=other, name="other-team", created_by=self.user)+ result = _recent_cohorts(self.team)+ assert result["total_count"] == 1+ assert result["recent"][0]["name"] == "kept"+++class TestRecentActions(BaseTest):+ def test_orders_by_updated_at_desc(self) -> None:+ a = Action.objects.create(team=self.team, name="a", created_by=self.user)+ Action.objects.filter(id=a.id).update(updated_at=timezone.now() - timedelta(days=1))+ Action.objects.create(team=self.team, name="b", created_by=self.user)+ result = _recent_actions(self.team)+ assert [r["name"] for r in result["recent"]] == ["b", "a"]++ def test_excludes_deleted(self) -> None:+ Action.objects.create(team=self.team, name="kept", created_by=self.user)+ Action.objects.create(team=self.team, name="gone", deleted=True, created_by=self.user)+ result = _recent_actions(self.team)+ assert result["total_count"] == 1+ assert result["recent"][0]["name"] == "kept"++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ Action.objects.create(team=other, name="x", created_by=self.user)+ result = _recent_actions(self.team)+ assert result["total_count"] == 0+++class TestRecentActivity(BaseTest):+ def _log(+ self,+ *,+ scope: str,+ team=None,+ user=None,+ created_at=None,+ was_impersonated: bool | None = False,+ is_system: bool | None = False,+ activity: str = "updated",+ ) -> ActivityLog:+ # Direct create with `created_at=...` works because the model uses+ # `default=timezone.now` rather than `auto_now_add` — lets us backdate rows+ # to test the windowing without a follow-up `.update()` dance.+ return ActivityLog.objects.create(+ team_id=(team or self.team).id,+ user=user,+ activity=activity,+ scope=scope,+ item_id="x",+ was_impersonated=was_impersonated,+ is_system=is_system,+ created_at=created_at or timezone.now(),+ )++ def test_groups_scopes_by_edit_count_descending(self) -> None:+ self._log(scope="FeatureFlag")+ self._log(scope="FeatureFlag")+ self._log(scope="FeatureFlag")+ self._log(scope="Survey")+ result = _recent_activity(self.team)+ assert result["window_days"] == RECENT_ACTIVITY_WINDOW_DAYS+ assert [row["scope"] for row in result["by_scope"]] == ["FeatureFlag", "Survey"]+ assert [row["edits"] for row in result["by_scope"]] == [3, 1]++ def test_distinct_user_count_and_last_edit_per_scope(self) -> None:+ u1 = self._make_user("[email protected]")+ u2 = self._make_user("[email protected]")+ # Two users, three edits — `users` should be 2, not 3.+ first = self._log(scope="Experiment", user=u1)+ ActivityLog.objects.filter(id=first.id).update(created_at=timezone.now() - timedelta(days=2))+ self._log(scope="Experiment", user=u2)+ last = self._log(scope="Experiment", user=u2)+ result = _recent_activity(self.team)+ row = next(r for r in result["by_scope"] if r["scope"] == "Experiment")+ assert row["edits"] == 3+ assert row["users"] == 2+ # `last_edit` reflects the most recent row in the window.+ assert row["last_edit"] is not None+ assert row["last_edit"] == last.created_at.isoformat()++ def test_excludes_impersonated_and_system_rows(self) -> None:+ # The partial index treats both flags as required-False; we mirror that.+ self._log(scope="Survey") # counted+ self._log(scope="Survey", was_impersonated=True)+ self._log(scope="Survey", is_system=True)+ self._log(scope="Survey", was_impersonated=None)+ self._log(scope="Survey", is_system=None)+ result = _recent_activity(self.team)+ survey = next(r for r in result["by_scope"] if r["scope"] == "Survey")+ assert survey["edits"] == 1++ def test_excludes_rows_outside_window(self) -> None:+ old = self._log(scope="Cohort")+ ActivityLog.objects.filter(id=old.id).update(+ created_at=timezone.now() - timedelta(days=RECENT_ACTIVITY_WINDOW_DAYS + 1),+ )+ recent = self._log(scope="Cohort")+ result = _recent_activity(self.team)+ cohort = next(r for r in result["by_scope"] if r["scope"] == "Cohort")+ assert cohort["edits"] == 1+ assert cohort["last_edit"] == recent.created_at.isoformat()++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ self._log(scope="FeatureFlag", team=other)+ result = _recent_activity(self.team)+ assert result == {"window_days": RECENT_ACTIVITY_WINDOW_DAYS, "by_scope": []}++ def test_empty_when_no_activity(self) -> None:+ # A quiet team should return the section with no rows — distinguishable from+ # an exception (which would propagate; profile build has no defensive wrapping+ # at this layer for indexed Postgres readers).+ result = _recent_activity(self.team)+ assert result == {"window_days": RECENT_ACTIVITY_WINDOW_DAYS, "by_scope": []}++ def _make_user(self, email: str) -> User:+ return User.objects.create(email=email, distinct_id=email)+++class TestBuildInventory(BaseTest):+ def test_returns_a_validated_inventory_with_all_sections(self) -> None:+ inventory = build_inventory(self.team)+ assert isinstance(inventory, Inventory)+ assert set(inventory.model_dump().keys()) == {+ "project_context",+ "products_in_use",+ "product_intents",+ "integrations",+ "external_data_sources",+ "signal_source_configs",+ "existing_inbox_reports",+ "recent_activity",+ "recent_dashboards",+ "recent_surveys",+ "recent_feature_flags",+ "recent_experiments",+ "recent_alerts",+ "recent_hog_functions",+ "recent_hog_flows",+ "recent_notebooks",+ "recent_cohorts",+ "recent_actions",+ "top_events",+ }++ def test_persisted_payload_revalidates_against_the_schema(self) -> None:+ # The stored jsonb is the dumped model; round-tripping it back through `Inventory`+ # is the contract the scout skills rely on, so guard that the dump stays valid.+ profile = compute_project_profile(team=self.team)+ Inventory.model_validate(profile.payload["inventory"])+++class TestComputeProjectProfile(BaseTest):+ def test_persists_a_new_row_with_inventory_payload(self) -> None:+ profile = compute_project_profile(team=self.team)+ assert profile.source_version == INVENTORY_SOURCE_VERSION+ assert "inventory" in profile.payload+ # Row exists in the DB and points back to this team.+ row = SignalProjectProfile.objects.get(id=profile.profile_id)+ assert row.team_id == self.team.id++ def test_expires_at_is_ttl_after_computed_at(self) -> None:+ profile = compute_project_profile(team=self.team)+ row = SignalProjectProfile.objects.get(id=profile.profile_id)+ delta = row.expires_at - row.computed_at+ # Allow small slack for the two `timezone.now()` calls in the build path.+ assert PROFILE_TTL - timedelta(seconds=2) < delta < PROFILE_TTL + timedelta(seconds=2)+++class TestGetProjectProfile(BaseTest):+ def test_returns_existing_fresh_profile_without_recomputing(self) -> None:+ first = compute_project_profile(team=self.team)+ # Second call hits the cache — we should get the same row id back.+ second = get_project_profile(team_id=self.team.id)+ assert second is not None and second.profile_id == first.profile_id+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 1++ def test_recomputes_when_cached_row_is_expired(self) -> None:+ stale = compute_project_profile(team=self.team)+ # Backdate the row's expires_at to force a cache miss.+ SignalProjectProfile.objects.filter(id=stale.profile_id).update(+ expires_at=timezone.now() - timedelta(minutes=1),+ )+ fresh = get_project_profile(team_id=self.team.id)+ assert fresh is not None and fresh.profile_id != stale.profile_id+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 2++ def test_recomputes_when_source_version_does_not_match(self) -> None:+ old = compute_project_profile(team=self.team)+ # Simulate a schema bump by retagging the row to a stale version.+ SignalProjectProfile.objects.filter(id=old.profile_id).update(source_version="v0_legacy")+ fresh = get_project_profile(team_id=self.team.id)+ assert fresh is not None and fresh.profile_id != old.profile_id+ assert fresh.source_version == INVENTORY_SOURCE_VERSION++ def test_team_isolated(self) -> None:+ other = self.organization.teams.create(name="other")+ compute_project_profile(team=other)+ # Calling for self.team shouldn't return the other team's profile — it should+ # build a fresh one for self.team.+ result = get_project_profile(team_id=self.team.id)+ assert result is not None+ row = SignalProjectProfile.objects.get(id=result.profile_id)+ assert row.team_id == self.team.id++ def test_force_refresh_rebuilds_even_when_cache_is_fresh(self) -> None:+ cached = compute_project_profile(team=self.team)+ # Default fetch hits the cache — same row.+ sanity = get_project_profile(team_id=self.team.id)+ assert sanity is not None and sanity.profile_id == cached.profile_id+ # `force_refresh=True` skips the cache and the post-lock re-check, persisting a+ # second row even though the first is still well within TTL.+ fresh = get_project_profile(team_id=self.team.id, force_refresh=True)+ assert fresh is not None and fresh.profile_id != cached.profile_id+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 2++ def test_lazy_build_false_returns_none_on_cache_miss_without_building(self) -> None:+ # Read-only callers (untrusted, CSRF-reachable GETs) pass `lazy_build=False` so a+ # miss returns None instead of running the inventory build + persisting a row.+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 0+ result = get_project_profile(team_id=self.team.id, lazy_build=False)+ assert result is None+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 0++ def test_lazy_build_false_returns_cached_row_when_fresh(self) -> None:+ cached = compute_project_profile(team=self.team)+ result = get_project_profile(team_id=self.team.id, lazy_build=False)+ assert result is not None and result.profile_id == cached.profile_id+ # No new row — the read-only path served the cache.+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 1diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex c7e18346adc9..c530fbfa4ab4 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -108,6 +108,555 @@ export interface PaginatedSignalReportListApi {results: SignalReportApi[]}+/**+ * `inventory.project_context` — free-form orientation about the project's product.+ */+export interface ProjectContextApi {+ /**+ * Human-set product description on the project (max 1000 chars). When present, the most direct "what does this team's product do" answer. `null` when unset.+ * @nullable+ */+ product_description: string | null+ /** Registered app URLs for this team (toolbar / replay). The team's actual product surface; complements `$pageview.$host` discovery via `read-data-schema`. */+ app_urls: string[]+}++/**+ * One row in `inventory.product_intents`.+ */+export interface ProductIntentEntryApi {+ /** Product key the team signaled intent to use. */+ product_type: string+ /**+ * ISO-8601 timestamp the team activated the product, or null if intent only.+ * @nullable+ */+ activated_at: string | null+ /**+ * ISO-8601 timestamp the intent was first recorded.+ * @nullable+ */+ created_at: string | null+}++/**+ * One row in `inventory.integrations`. Sensitive config is intentionally excluded.+ */+export interface IntegrationEntryApi {+ /** Integration kind (e.g. `slack`, `github`, `linear`). */+ kind: string+ /**+ * ISO-8601 timestamp the integration was connected.+ * @nullable+ */+ created_at: string | null+}++/**+ * One row in `inventory.external_data_sources`.+ */+export interface ExternalDataSourceEntryApi {+ /** Warehouse source type (e.g. `Stripe`, `Postgres`, `BigQuery`). */+ source_type: string+ /** Current sync status (`Running`, `Failed`, `Paused`, etc.). */+ status: string+ /** Schema prefix used by this source, if any. */+ prefix: string+ /**+ * ISO-8601 timestamp the source was connected.+ * @nullable+ */+ created_at: string | null+}++/**+ * One row in either bucket of `inventory.signal_source_configs`.+ */+export interface SignalSourceConfigEntryApi {+ /** Source product the config applies to. */+ source_product: string+ /** Source type within the product. */+ source_type: string+}++/**+ * `inventory.signal_source_configs` split into enabled and disabled buckets.+ */+export interface SignalSourceConfigsBucketsApi {+ /** Source configs the team has explicitly enabled. */+ enabled: SignalSourceConfigEntryApi[]+ /** Source configs the team has explicitly disabled (different from never wired up). */+ disabled: SignalSourceConfigEntryApi[]+}++/**+ * One bucket in `inventory.existing_inbox_reports.by_status`.+ */+export interface InboxReportStatusBucketApi {+ /** Report status (e.g. `potential`, `candidate`, `ready`). */+ status: string+ /** Number of reports in this status (excludes deleted/suppressed). */+ count: number+}++/**+ * `inventory.existing_inbox_reports` — what's already been surfaced to the inbox.+ */+export interface ExistingInboxReportsApi {+ /** Total non-deleted, non-suppressed reports for this team. */+ total: number+ /** Per-status breakdown of inbox reports. */+ by_status: InboxReportStatusBucketApi[]+}++/**+ * One row in `inventory.recent_activity.by_scope`.+ */+export interface ScopeActivityEntryApi {+ /** Activity-log scope (entity type), e.g. `FeatureFlag`, `Dashboard`, `Survey`. */+ scope: string+ /** Total activity-log entries for this scope in the window (write velocity). */+ edits: number+ /** Distinct users who edited this scope in the window. */+ users: number+ /**+ * ISO-8601 timestamp of the most recent edit in the window.+ * @nullable+ */+ last_edit: string | null+}++/**+ * `inventory.recent_activity` — per-scope counts off the activity log.+ */+export interface RecentActivityApi {+ /** Lookback window in days the per-scope counts cover. */+ window_days: number+ /** Per-scope activity rows, busiest scope first. Triage which entity type the team has worked in lately. */+ by_scope: ScopeActivityEntryApi[]+}++/**+ * One row in `inventory.recent_dashboards`.+ */+export interface RecentDashboardEntryApi {+ /** Dashboard ID — pass to `dashboard-get` to pull the full payload. */+ id: number+ /** Dashboard name (may be blank if unnamed). */+ name: string+ /**+ * ISO-8601 timestamp of the most recent view in the PostHog UI.+ * @nullable+ */+ last_accessed_at: string | null+ /**+ * ISO-8601 timestamp of the most recent data refresh. Distinct from access — a dashboard can be refreshed without anyone viewing it.+ * @nullable+ */+ last_refresh: string | null+ /**+ * ISO-8601 timestamp the dashboard was created.+ * @nullable+ */+ created_at: string | null+}++/**+ * One row in `inventory.recent_surveys.recent`.+ */+export interface RecentSurveyEntryApi {+ /** Survey UUID — pass to `survey-get` for full question shape. */+ id: string+ /** Survey name (may be blank if unnamed). */+ name: string+ /** Survey mode: `popover`, `widget`, `external_survey`, or `api`. */+ type: string+ /** Derived status: `draft`, `running`, `stopped`, or `archived`. */+ status: string+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null+}++/**+ * `inventory.recent_surveys` — total + active count, plus the 5 most recently modified.+ */+export interface RecentSurveysApi {+ /** Total surveys on the team. */+ total_count: number+ /** Surveys that are live (not archived, started, and not yet ended). */+ active_count: number+ /** The 5 most recently updated surveys. */+ recent: RecentSurveyEntryApi[]+}++/**+ * One row in `inventory.recent_feature_flags.recent`.+ */+export interface RecentFeatureFlagEntryApi {+ /** Feature flag ID. */+ id: number+ /** Flag key used in code (`posthog.isFeatureEnabled('<key>')`). */+ key: string+ /** Human-set description; falls back to the key when blank. */+ name: string+ /** Whether the flag is currently evaluating (a user could be hitting it). */+ active: boolean+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null+}++/**+ * `inventory.recent_feature_flags` — total + active count, plus the 5 most recently modified.+ */+export interface RecentFeatureFlagsApi {+ /** Total non-deleted feature flags on the team. */+ total_count: number+ /** Flags currently evaluating (`active=true`). */+ active_count: number+ /** The 5 most recently updated non-deleted flags. */+ recent: RecentFeatureFlagEntryApi[]+}++/**+ * One row in `inventory.recent_experiments.recent`.+ */+export interface RecentExperimentEntryApi {+ /** Experiment ID. */+ id: number+ /** Experiment name. */+ name: string+ /** Derived status: `draft`, `running`, `stopped`, or `archived`. */+ status: string+ /**+ * Key of the experiment's feature flag — cross-ref into `recent_feature_flags`. Null if unlinked.+ * @nullable+ */+ feature_flag_key: string | null+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null+}++/**+ * `inventory.recent_experiments` — total + currently-running count, plus the 5 most recently modified.+ */+export interface RecentExperimentsApi {+ /** Total experiments on the team. */+ total_count: number+ /** Experiments currently running (started, not ended, not archived). */+ running_count: number+ /** The 5 most recently updated experiments. */+ recent: RecentExperimentEntryApi[]+}++/**+ * One row in `inventory.recent_alerts.recent`.+ */+export interface RecentAlertEntryApi {+ /** Alert configuration UUID. */+ id: string+ /** Alert name. */+ name: string+ /** Whether the alert is currently armed. */+ enabled: boolean+ /** Alert state (e.g. `not_firing`, `firing`). */+ state: string+ /**+ * How often the alert is evaluated (e.g. `daily`, `hourly`); null if unset.+ * @nullable+ */+ calculation_interval: string | null+ /**+ * ID of the insight the alert watches; null if none.+ * @nullable+ */+ insight_id: number | null+ /**+ * ISO-8601 creation timestamp.+ * @nullable+ */+ created_at: string | null+}++/**+ * `inventory.recent_alerts` — total + currently-enabled count, plus the 5 most recently created.+ */+export interface RecentAlertsApi {+ /** Total insight alerts on the team. */+ total_count: number+ /** Alerts currently armed (`enabled=true`). */+ enabled_count: number+ /** The 5 most recently created alerts. */+ recent: RecentAlertEntryApi[]+}++/**+ * One row in `inventory.recent_hog_functions.recent`.+ */+export interface RecentHogFunctionEntryApi {+ /** Hog function UUID. */+ id: string+ /** Hog function name. */+ name: string+ /**+ * Function type: `destination`, `transformation`, `site_app`, etc. Null if unset.+ * @nullable+ */+ type: string | null+ /**+ * Function kind sub-classifier; null if unset.+ * @nullable+ */+ kind: string | null+ /** Whether the function is currently enabled. */+ enabled: boolean+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null+}++/**+ * `inventory.recent_hog_functions` — total + enabled count, plus the 5 most recently modified.+ */+export interface RecentHogFunctionsApi {+ /** Total non-deleted hog functions on the team. */+ total_count: number+ /** Hog functions currently enabled (`enabled=true`). */+ enabled_count: number+ /** The 5 most recently updated hog functions. */+ recent: RecentHogFunctionEntryApi[]+}++/**+ * One row in `inventory.recent_hog_flows.recent`.+ */+export interface RecentHogFlowEntryApi {+ /** Hog flow UUID. */+ id: string+ /** Hog flow name. */+ name: string+ /** Flow lifecycle state (e.g. `draft`, `active`, `archived`). */+ status: string+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null+}++/**+ * `inventory.recent_hog_flows` — total + non-archived count, plus the 5 most recently modified.+ */+export interface RecentHogFlowsApi {+ /** Total hog flows on the team. */+ total_count: number+ /** Hog flows that are not archived. */+ active_count: number+ /** The 5 most recently updated hog flows. */+ recent: RecentHogFlowEntryApi[]+}++/**+ * One row in `inventory.recent_notebooks.recent`.+ */+export interface RecentNotebookEntryApi {+ /** Notebook short ID — pass to the notebooks API to open it. */+ short_id: string+ /** Notebook title (may be blank if untitled). */+ title: string+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ last_modified_at: string | null+}++/**+ * `inventory.recent_notebooks` — total + the 5 most recently modified.+ */+export interface RecentNotebooksApi {+ /** Total non-deleted notebooks on the team. */+ total_count: number+ /** The 5 most recently modified notebooks. */+ recent: RecentNotebookEntryApi[]+}++/**+ * One row in `inventory.recent_cohorts.recent`.+ */+export interface RecentCohortEntryApi {+ /** Cohort ID. */+ id: number+ /** Cohort name. */+ name: string+ /** True for a one-shot snapshot cohort; false for a dynamic-filter cohort. */+ is_static: boolean+ /**+ * Membership size when last calculated; null if never calculated.+ * @nullable+ */+ count: number | null+ /**+ * ISO-8601 creation timestamp.+ * @nullable+ */+ created_at: string | null+}++/**+ * `inventory.recent_cohorts` — total + the 5 most recently created.+ */+export interface RecentCohortsApi {+ /** Total non-deleted cohorts on the team. */+ total_count: number+ /** The 5 most recently created cohorts. */+ recent: RecentCohortEntryApi[]+}++/**+ * One row in `inventory.recent_actions.recent`.+ */+export interface RecentActionEntryApi {+ /** Action ID. */+ id: number+ /** Action name. */+ name: string+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null+}++/**+ * `inventory.recent_actions` — total + the 5 most recently modified.+ */+export interface RecentActionsApi {+ /** Total non-deleted actions on the team. */+ total_count: number+ /** The 5 most recently updated actions. */+ recent: RecentActionEntryApi[]+}++/**+ * One row in `inventory.top_events`.+ */+export interface TopEventEntryApi {+ /** Event name as captured. */+ event: string+ /** Number of occurrences in the lookback window (last 7 days). */+ count: number+ /** `uniq(person_id)` over the window — reach. Distinguishes a high-count event firing on one power user from one firing on many users. */+ distinct_users: number+ /** Count in just the last 24 hours. Compare to `count / 7` to spot bursts: a ratio well above 1/7 means the event is concentrated in the last day. */+ recent_24h_count: number+ /** `uniq(person_id)` over just the last 24 hours. A burst across many users is qualitatively different from one user in a loop. */+ recent_24h_users: number+ /**+ * ISO-8601 timestamp of the earliest occurrence within the lookback window. Compare to the window start to spot new event types: `first_seen` close to `now` ⇒ likely new or recently bursting; close to the window edge ⇒ has been around at least that long (the window can't tell you when the event *truly* first appeared).+ * @nullable+ */+ first_seen: string | null+ /**+ * ISO-8601 timestamp of the most recent occurrence within the lookback window.+ * @nullable+ */+ last_seen: string | null+}++/**+ * The deterministic inventory layer of a project profile.++Read this to orient on the team's product mix, integrations, warehouse sources, signal+coverage, and existing inbox surface in one tool call. Distinct from `SignalScratchpad`:+profile is ground truth from authoritative tables; memory is agent inference.+ */+export interface ProjectProfileInventoryApi {+ /** Free-form orientation: human-set product description + registered app URLs. */+ project_context: ProjectContextApi+ /** Product keys this team has completed onboarding for, sorted alphabetically. */+ products_in_use: string[]+ /** Products the team signaled intent to use; useful for spotting stuck onboardings. */+ product_intents: ProductIntentEntryApi[]+ /** Connected integrations (kind + connection time only — config never surfaced). */+ integrations: IntegrationEntryApi[]+ /** Connected warehouse sources (excludes soft-deleted). */+ external_data_sources: ExternalDataSourceEntryApi[]+ /** Signal source configs split into enabled / disabled buckets. */+ signal_source_configs: SignalSourceConfigsBucketsApi+ /** Counts of reports already in the inbox, grouped by status. */+ existing_inbox_reports: ExistingInboxReportsApi+ /** Per-scope counts off the activity log over the recent-activity window — cross-cutting orientation across every entity type (surveys, feature flags, experiments, dashboards, insights, cohorts, notebooks, actions, etc.). Each scope reports `edits` (total log entries), `users` (distinct user count), and `last_edit` (ISO-8601). Use to triage which scope a team has been working in lately before drilling down via the per-entity readers or `activity-log-list`. */+ recent_activity: RecentActivityApi+ /** Up to 20 dashboards on this team sorted by `last_accessed_at` desc — what the team is currently looking at, not necessarily the most-trafficked. We don't have per-dashboard view counts in Postgres, only the timestamp of the most recent access. */+ recent_dashboards: RecentDashboardEntryApi[]+ /** Surveys orientation: total + active count, plus the 5 most recently updated surveys with id, name, type, status (draft / running / stopped / archived), and updated_at. */+ recent_surveys: RecentSurveysApi+ /** Feature flag orientation: total + active count, plus the 5 most recently updated non-deleted flags with id, key, name, active, and updated_at. */+ recent_feature_flags: RecentFeatureFlagsApi+ /** Experiment orientation: total + running count, plus the 5 most recently updated experiments. The feature_flag_key on each row lets the scout correlate experiments with the `recent_feature_flags` section. */+ recent_experiments: RecentExperimentsApi+ /** Alert orientation: total + enabled count, plus the 5 most recently created alerts with their state and threshold metadata. */+ recent_alerts: RecentAlertsApi+ /** Hog function orientation: total + enabled count, plus the 5 most recently updated destinations / transformations the team has wired up via the CDP pipelines. */+ recent_hog_functions: RecentHogFunctionsApi+ /** Hog flow orientation: total + non-archived count, plus the 5 most recently updated automation flows. */+ recent_hog_flows: RecentHogFlowsApi+ /** Notebook orientation: total + the 5 most recently modified notebooks — useful signal for what the team has been investigating. */+ recent_notebooks: RecentNotebooksApi+ /** Cohort orientation: total + the 5 most recently created cohorts on the team. */+ recent_cohorts: RecentCohortsApi+ /** Action orientation: total + the 5 most recently updated actions — useful to anchor agent reasoning about what the team treats as a meaningful interaction. */+ recent_actions: RecentActionsApi+ /**+ * Top ~50 events by count over the last 7 days, with first/last seen timestamps within the window. `null` if the underlying ClickHouse query failed or timed out (distinct from `[]`, which means the team has no captures in the window). Use the gap between `first_seen` and `now` to spot new event types or recent bursts.+ * @nullable+ */+ top_events: TopEventEntryApi[] | null+}++/**+ * Top-level `payload` shape on a `SignalProjectProfile` row.++v1 carries `inventory` only. Phase 7 will add `deltas`, `activity_notes`, and+`narrative` slots — they're absent (not null) in v1 responses.+ */+export interface ProjectProfilePayloadApi {+ /** Deterministic snapshot of what's true about the project. */+ inventory: ProjectProfileInventoryApi+}++/**+ * Wire shape for the project profile returned by `signals-scout-harness-project-profile-list`.++Read this once at the start of a run (after `skill-get`) to orient on the team. Cache+is per-team with a soft TTL (`PROFILE_TTL`); the response always reflects either the+latest cached profile or a freshly-built one if the cache was stale or the caller passed+`force_refresh=true`.+ */+export interface ProjectProfileApi {+ /** UUID of the `SignalProjectProfile` row. */+ profile_id: string+ /** ISO-8601 timestamp the profile was built. */+ computed_at: string+ /** ISO-8601 timestamp after which the profile is considered stale. */+ expires_at: string+ /** Schema version of the inventory builder. Bumps invalidate older cached rows. */+ source_version: string+ /** Structured profile content. v1 has `inventory` only. */+ payload: ProjectProfilePayloadApi+}+/*** Lightweight projection of a `SignalScoutRun` row used by `search-recent-runs`.@@ -521,6 +1070,13 @@ export type SignalsReportsListParams = {suggested_reviewers?: string}+export type SignalsScoutProjectProfileGetParams = {+ /**+ * When true, skip the cache and rebuild the profile from authoritative sources before responding. Use after seeding events, importing data, or any other change the caller knows just landed but hasn't surfaced through natural cache expiry yet. Honored only for the internal scout token — public read callers get the cached profile regardless. Concurrent forced rebuilds are serialized by the team-keyed advisory lock — at most one extra `build_inventory` per simultaneous request.+ */+ force_refresh?: boolean+}+export type SignalsScoutRunsListParams = {/*** ISO-8601 inclusive lower bound on `created_at`. Omit to skip the lower bound.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 063fc982e5dc..ccd9cbe5d084 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -19,6 +19,7 @@ import type {PatchedSignalSourceConfigApi,PauseResponseApi,PauseUntilRequestApi,+ ProjectProfileApi,RememberRequestApi,ScratchpadEntryApi,SignalReportApi,@@ -28,6 +29,7 @@ import type {SignalUserAutonomyConfigApi,SignalsProcessingListParams,SignalsReportsListParams,+ SignalsScoutProjectProfileGetParams,SignalsScoutRunsListParams,SignalsScoutScratchpadSearchParams,SignalsSourceConfigsListParams,@@ -159,6 +161,40 @@ export const signalsReportsRetrieve = async (})}+export const getSignalsScoutProjectProfileGetUrl = (+ projectId: string,+ params?: SignalsScoutProjectProfileGetParams+) => {+ 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/project_profile/current/?${stringifiedParams}`+ : `/api/projects/${projectId}/signals/scout/project_profile/current/`+}++/**+ * Return the team's deterministic project profile. For the internal scout token the response reflects the newest non-expired cached row or a freshly-built one (lazy compute on cache miss); `force_refresh=true` skips the cache and rebuilds from authoritative sources. Public read callers (session auth or a `signal_scout:read` PAK) get the newest cached profile, or 404 if none has been built yet — they never trigger a rebuild. Read this at the start of a run to orient on the team's product mix, integrations, warehouse sources, signal coverage, and existing inbox surface.+ * @summary Get the current project profile+ */+export const signalsScoutProjectProfileGet = async (+ projectId: string,+ params?: SignalsScoutProjectProfileGetParams,+ options?: RequestInit+): Promise<ProjectProfileApi> => {+ return apiMutator<ProjectProfileApi>(getSignalsScoutProjectProfileGetUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsScoutRunsListUrl = (projectId: string, params?: SignalsScoutRunsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex d07c2456a629..fc3aacb7b583 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -133,6 +133,25 @@ tools: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 withthe same `finding_id` emits a second signal, so emit each finding exactly once and never retry an emit.+ signals-scout-project-profile-get:+ operation: signals_scout_project_profile_get+ enabled: true+ scopes:+ - signal_scout:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get the project profile+ description: >+ Return a deterministic snapshot of "what's true about this project" — products in use, product intents+ (stuck onboardings), connected integrations, warehouse sources, signal source configs (split+ enabled/disabled), and existing inbox report counts. Singleton per team; the response reflects either the+ newest non-expired cached profile or a freshly-built one. Read this once at the start of a run (right after+ `llma-skill-get`) to orient on the team in one tool call instead of paginating through+ `inbox-source-configs-list` / `inbox-reports-list` / `read-data-schema` / `activity-log-list`. Distinct from+ `signals-scout-scratchpad-list`: profile is ground truth from authoritative tables; scratchpad is the+ scout's inferred learnings.signals-scout-runs-list:operation: signals_scout_runs_listenabled: true@@ -147,8 +166,9 @@ tools:description: >Return the most recent `SignalScoutRun` summaries for this project, newest first. Used by the headless scoutto 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.+ run's `summary` (the primary dedupe key for runs that didn't emit findings). Pass `date_from` / `date_to`+ (ISO-8601, inclusive lower / exclusive upper bound on `created_at`) to scope to a window. Results capped at+ 100.signals-scout-runs-retrieve:operation: signals_scout_runs_retrieveenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c09d012f40cd..a5608b7e929b 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4783,8 +4783,23 @@"readOnlyHint": false}},+ "signals-scout-project-profile-get": {+ "description": "Return a deterministic snapshot of \"what's true about this project\" — products in use, product intents (stuck onboardings), connected integrations, warehouse sources, signal source configs (split enabled/disabled), and existing inbox report counts. Singleton per team; the response reflects either the newest non-expired cached profile or a freshly-built one. Read this once at the start of a run (right after `llma-skill-get`) to orient on the team in one tool call instead of paginating through `inbox-source-configs-list` / `inbox-reports-list` / `read-data-schema` / `activity-log-list`. Distinct from `signals-scout-scratchpad-list`: profile is ground truth from authoritative tables; scratchpad is the scout's inferred learnings.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get the project profile",+ "title": "Get the project profile",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"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.",+ "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 `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `created_at`) to scope to a window. Results capped at 100.","category": "Signals","feature": "signals","summary": "List recent scout runs",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9277fa26ab8c..b4051f5fa4c3 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5250,8 +5250,23 @@"readOnlyHint": false}},+ "signals-scout-project-profile-get": {+ "description": "Return a deterministic snapshot of \"what's true about this project\" — products in use, product intents (stuck onboardings), connected integrations, warehouse sources, signal source configs (split enabled/disabled), and existing inbox report counts. Singleton per team; the response reflects either the newest non-expired cached profile or a freshly-built one. Read this once at the start of a run (right after `llma-skill-get`) to orient on the team in one tool call instead of paginating through `inbox-source-configs-list` / `inbox-reports-list` / `read-data-schema` / `activity-log-list`. Distinct from `signals-scout-scratchpad-list`: profile is ground truth from authoritative tables; scratchpad is the scout's inferred learnings.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Get the project profile",+ "title": "Get the project profile",+ "required_scopes": ["signal_scout:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"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.",+ "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 `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `created_at`) to scope to a window. Results capped at 100.","category": "Signals","feature": "signals","summary": "List recent scout runs",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3c9f284e0e08..cc75f2425cce 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16391,6 +16391,26 @@ export namespace Schemas {rows_returned: number;}+ /**+ * One bucket in `inventory.existing_inbox_reports.by_status`.+ */+ export interface InboxReportStatusBucket {+ /** Report status (e.g. `potential`, `candidate`, `ready`). */+ status: string;+ /** Number of reports in this status (excludes deleted/suppressed). */+ count: number;+ }++ /**+ * `inventory.existing_inbox_reports` — what's already been surfaced to the inbox.+ */+ export interface ExistingInboxReports {+ /** Total non-deleted, non-suppressed reports for this team. */+ total: number;+ /** Per-status breakdown of inbox reports. */+ by_status: InboxReportStatusBucket[];+ }+/*** * `exit_on_conversion` - Conversion* `exit_on_trigger_not_matched` - Trigger Not Matched@@ -17227,6 +17247,23 @@ export namespace Schemas {created_via?: CreatedViaEnum;}+ /**+ * One row in `inventory.external_data_sources`.+ */+ export interface ExternalDataSourceEntry {+ /** Warehouse source type (e.g. `Stripe`, `Postgres`, `BigQuery`). */+ source_type: string;+ /** Current sync status (`Running`, `Failed`, `Paused`, etc.). */+ status: string;+ /** Schema prefix used by this source, if any. */+ prefix: string;+ /**+ * ISO-8601 timestamp the source was connected.+ * @nullable+ */+ created_at: string | null;+ }+export interface ExternalDataSourceRevenueAnalyticsConfig {enabled?: boolean;include_invoiceless_charges?: boolean;@@ -20335,6 +20372,19 @@ export namespace Schemas {readonly display_name: string;}+ /**+ * One row in `inventory.integrations`. Sensitive config is intentionally excluded.+ */+ export interface IntegrationEntry {+ /** Integration kind (e.g. `slack`, `github`, `linear`). */+ kind: string;+ /**+ * ISO-8601 timestamp the integration was connected.+ * @nullable+ */+ created_at: string | null;+ }+export interface InterestingNote {text: string;line_refs: string;@@ -32724,6 +32774,24 @@ export namespace Schemas {primary_properties: PrimaryPropertiesResponsePrimaryProperties;}+ /**+ * One row in `inventory.product_intents`.+ */+ export interface ProductIntentEntry {+ /** Product key the team signaled intent to use. */+ product_type: string;+ /**+ * ISO-8601 timestamp the team activated the product, or null if intent only.+ * @nullable+ */+ activated_at: string | null;+ /**+ * ISO-8601 timestamp the intent was first recorded.+ * @nullable+ */+ created_at: string | null;+ }+/*** Serializer for creating and updating ProductTour.*/@@ -33547,6 +33615,487 @@ export namespace Schemas {readonly available_setup_task_ids: readonly AvailableSetupTaskIdsEnum[];}+ /**+ * `inventory.project_context` — free-form orientation about the project's product.+ */+ export interface ProjectContext {+ /**+ * Human-set product description on the project (max 1000 chars). When present, the most direct "what does this team's product do" answer. `null` when unset.+ * @nullable+ */+ product_description: string | null;+ /** Registered app URLs for this team (toolbar / replay). The team's actual product surface; complements `$pageview.$host` discovery via `read-data-schema`. */+ app_urls: string[];+ }++ /**+ * One row in either bucket of `inventory.signal_source_configs`.+ */+ export interface SignalSourceConfigEntry {+ /** Source product the config applies to. */+ source_product: string;+ /** Source type within the product. */+ source_type: string;+ }++ /**+ * `inventory.signal_source_configs` split into enabled and disabled buckets.+ */+ export interface SignalSourceConfigsBuckets {+ /** Source configs the team has explicitly enabled. */+ enabled: SignalSourceConfigEntry[];+ /** Source configs the team has explicitly disabled (different from never wired up). */+ disabled: SignalSourceConfigEntry[];+ }++ /**+ * One row in `inventory.recent_activity.by_scope`.+ */+ export interface ScopeActivityEntry {+ /** Activity-log scope (entity type), e.g. `FeatureFlag`, `Dashboard`, `Survey`. */+ scope: string;+ /** Total activity-log entries for this scope in the window (write velocity). */+ edits: number;+ /** Distinct users who edited this scope in the window. */+ users: number;+ /**+ * ISO-8601 timestamp of the most recent edit in the window.+ * @nullable+ */+ last_edit: string | null;+ }++ /**+ * `inventory.recent_activity` — per-scope counts off the activity log.+ */+ export interface RecentActivity {+ /** Lookback window in days the per-scope counts cover. */+ window_days: number;+ /** Per-scope activity rows, busiest scope first. Triage which entity type the team has worked in lately. */+ by_scope: ScopeActivityEntry[];+ }++ /**+ * One row in `inventory.recent_dashboards`.+ */+ export interface RecentDashboardEntry {+ /** Dashboard ID — pass to `dashboard-get` to pull the full payload. */+ id: number;+ /** Dashboard name (may be blank if unnamed). */+ name: string;+ /**+ * ISO-8601 timestamp of the most recent view in the PostHog UI.+ * @nullable+ */+ last_accessed_at: string | null;+ /**+ * ISO-8601 timestamp of the most recent data refresh. Distinct from access — a dashboard can be refreshed without anyone viewing it.+ * @nullable+ */+ last_refresh: string | null;+ /**+ * ISO-8601 timestamp the dashboard was created.+ * @nullable+ */+ created_at: string | null;+ }++ /**+ * One row in `inventory.recent_surveys.recent`.+ */+ export interface RecentSurveyEntry {+ /** Survey UUID — pass to `survey-get` for full question shape. */+ id: string;+ /** Survey name (may be blank if unnamed). */+ name: string;+ /** Survey mode: `popover`, `widget`, `external_survey`, or `api`. */+ type: string;+ /** Derived status: `draft`, `running`, `stopped`, or `archived`. */+ status: string;+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null;+ }++ /**+ * `inventory.recent_surveys` — total + active count, plus the 5 most recently modified.+ */+ export interface RecentSurveys {+ /** Total surveys on the team. */+ total_count: number;+ /** Surveys that are live (not archived, started, and not yet ended). */+ active_count: number;+ /** The 5 most recently updated surveys. */+ recent: RecentSurveyEntry[];+ }++ /**+ * One row in `inventory.recent_feature_flags.recent`.+ */+ export interface RecentFeatureFlagEntry {+ /** Feature flag ID. */+ id: number;+ /** Flag key used in code (`posthog.isFeatureEnabled('<key>')`). */+ key: string;+ /** Human-set description; falls back to the key when blank. */+ name: string;+ /** Whether the flag is currently evaluating (a user could be hitting it). */+ active: boolean;+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null;+ }++ /**+ * `inventory.recent_feature_flags` — total + active count, plus the 5 most recently modified.+ */+ export interface RecentFeatureFlags {+ /** Total non-deleted feature flags on the team. */+ total_count: number;+ /** Flags currently evaluating (`active=true`). */+ active_count: number;+ /** The 5 most recently updated non-deleted flags. */+ recent: RecentFeatureFlagEntry[];+ }++ /**+ * One row in `inventory.recent_experiments.recent`.+ */+ export interface RecentExperimentEntry {+ /** Experiment ID. */+ id: number;+ /** Experiment name. */+ name: string;+ /** Derived status: `draft`, `running`, `stopped`, or `archived`. */+ status: string;+ /**+ * Key of the experiment's feature flag — cross-ref into `recent_feature_flags`. Null if unlinked.+ * @nullable+ */+ feature_flag_key: string | null;+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null;+ }++ /**+ * `inventory.recent_experiments` — total + currently-running count, plus the 5 most recently modified.+ */+ export interface RecentExperiments {+ /** Total experiments on the team. */+ total_count: number;+ /** Experiments currently running (started, not ended, not archived). */+ running_count: number;+ /** The 5 most recently updated experiments. */+ recent: RecentExperimentEntry[];+ }++ /**+ * One row in `inventory.recent_alerts.recent`.+ */+ export interface RecentAlertEntry {+ /** Alert configuration UUID. */+ id: string;+ /** Alert name. */+ name: string;+ /** Whether the alert is currently armed. */+ enabled: boolean;+ /** Alert state (e.g. `not_firing`, `firing`). */+ state: string;+ /**+ * How often the alert is evaluated (e.g. `daily`, `hourly`); null if unset.+ * @nullable+ */+ calculation_interval: string | null;+ /**+ * ID of the insight the alert watches; null if none.+ * @nullable+ */+ insight_id: number | null;+ /**+ * ISO-8601 creation timestamp.+ * @nullable+ */+ created_at: string | null;+ }++ /**+ * `inventory.recent_alerts` — total + currently-enabled count, plus the 5 most recently created.+ */+ export interface RecentAlerts {+ /** Total insight alerts on the team. */+ total_count: number;+ /** Alerts currently armed (`enabled=true`). */+ enabled_count: number;+ /** The 5 most recently created alerts. */+ recent: RecentAlertEntry[];+ }++ /**+ * One row in `inventory.recent_hog_functions.recent`.+ */+ export interface RecentHogFunctionEntry {+ /** Hog function UUID. */+ id: string;+ /** Hog function name. */+ name: string;+ /**+ * Function type: `destination`, `transformation`, `site_app`, etc. Null if unset.+ * @nullable+ */+ type: string | null;+ /**+ * Function kind sub-classifier; null if unset.+ * @nullable+ */+ kind: string | null;+ /** Whether the function is currently enabled. */+ enabled: boolean;+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null;+ }++ /**+ * `inventory.recent_hog_functions` — total + enabled count, plus the 5 most recently modified.+ */+ export interface RecentHogFunctions {+ /** Total non-deleted hog functions on the team. */+ total_count: number;+ /** Hog functions currently enabled (`enabled=true`). */+ enabled_count: number;+ /** The 5 most recently updated hog functions. */+ recent: RecentHogFunctionEntry[];+ }++ /**+ * One row in `inventory.recent_hog_flows.recent`.+ */+ export interface RecentHogFlowEntry {+ /** Hog flow UUID. */+ id: string;+ /** Hog flow name. */+ name: string;+ /** Flow lifecycle state (e.g. `draft`, `active`, `archived`). */+ status: string;+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null;+ }++ /**+ * `inventory.recent_hog_flows` — total + non-archived count, plus the 5 most recently modified.+ */+ export interface RecentHogFlows {+ /** Total hog flows on the team. */+ total_count: number;+ /** Hog flows that are not archived. */+ active_count: number;+ /** The 5 most recently updated hog flows. */+ recent: RecentHogFlowEntry[];+ }++ /**+ * One row in `inventory.recent_notebooks.recent`.+ */+ export interface RecentNotebookEntry {+ /** Notebook short ID — pass to the notebooks API to open it. */+ short_id: string;+ /** Notebook title (may be blank if untitled). */+ title: string;+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ last_modified_at: string | null;+ }++ /**+ * `inventory.recent_notebooks` — total + the 5 most recently modified.+ */+ export interface RecentNotebooks {+ /** Total non-deleted notebooks on the team. */+ total_count: number;+ /** The 5 most recently modified notebooks. */+ recent: RecentNotebookEntry[];+ }++ /**+ * One row in `inventory.recent_cohorts.recent`.+ */+ export interface RecentCohortEntry {+ /** Cohort ID. */+ id: number;+ /** Cohort name. */+ name: string;+ /** True for a one-shot snapshot cohort; false for a dynamic-filter cohort. */+ is_static: boolean;+ /**+ * Membership size when last calculated; null if never calculated.+ * @nullable+ */+ count: number | null;+ /**+ * ISO-8601 creation timestamp.+ * @nullable+ */+ created_at: string | null;+ }++ /**+ * `inventory.recent_cohorts` — total + the 5 most recently created.+ */+ export interface RecentCohorts {+ /** Total non-deleted cohorts on the team. */+ total_count: number;+ /** The 5 most recently created cohorts. */+ recent: RecentCohortEntry[];+ }++ /**+ * One row in `inventory.recent_actions.recent`.+ */+ export interface RecentActionEntry {+ /** Action ID. */+ id: number;+ /** Action name. */+ name: string;+ /**+ * ISO-8601 last-modified timestamp.+ * @nullable+ */+ updated_at: string | null;+ }++ /**+ * `inventory.recent_actions` — total + the 5 most recently modified.+ */+ export interface RecentActions {+ /** Total non-deleted actions on the team. */+ total_count: number;+ /** The 5 most recently updated actions. */+ recent: RecentActionEntry[];+ }++ /**+ * One row in `inventory.top_events`.+ */+ export interface TopEventEntry {+ /** Event name as captured. */+ event: string;+ /** Number of occurrences in the lookback window (last 7 days). */+ count: number;+ /** `uniq(person_id)` over the window — reach. Distinguishes a high-count event firing on one power user from one firing on many users. */+ distinct_users: number;+ /** Count in just the last 24 hours. Compare to `count / 7` to spot bursts: a ratio well above 1/7 means the event is concentrated in the last day. */+ recent_24h_count: number;+ /** `uniq(person_id)` over just the last 24 hours. A burst across many users is qualitatively different from one user in a loop. */+ recent_24h_users: number;+ /**+ * ISO-8601 timestamp of the earliest occurrence within the lookback window. Compare to the window start to spot new event types: `first_seen` close to `now` ⇒ likely new or recently bursting; close to the window edge ⇒ has been around at least that long (the window can't tell you when the event *truly* first appeared).+ * @nullable+ */+ first_seen: string | null;+ /**+ * ISO-8601 timestamp of the most recent occurrence within the lookback window.+ * @nullable+ */+ last_seen: string | null;+ }++ /**+ * The deterministic inventory layer of a project profile.++ Read this to orient on the team's product mix, integrations, warehouse sources, signal+ coverage, and existing inbox surface in one tool call. Distinct from `SignalScratchpad`:+ profile is ground truth from authoritative tables; memory is agent inference.+ */+ export interface ProjectProfileInventory {+ /** Free-form orientation: human-set product description + registered app URLs. */+ project_context: ProjectContext;+ /** Product keys this team has completed onboarding for, sorted alphabetically. */+ products_in_use: string[];+ /** Products the team signaled intent to use; useful for spotting stuck onboardings. */+ product_intents: ProductIntentEntry[];+ /** Connected integrations (kind + connection time only — config never surfaced). */+ integrations: IntegrationEntry[];+ /** Connected warehouse sources (excludes soft-deleted). */+ external_data_sources: ExternalDataSourceEntry[];+ /** Signal source configs split into enabled / disabled buckets. */+ signal_source_configs: SignalSourceConfigsBuckets;+ /** Counts of reports already in the inbox, grouped by status. */+ existing_inbox_reports: ExistingInboxReports;+ /** Per-scope counts off the activity log over the recent-activity window — cross-cutting orientation across every entity type (surveys, feature flags, experiments, dashboards, insights, cohorts, notebooks, actions, etc.). Each scope reports `edits` (total log entries), `users` (distinct user count), and `last_edit` (ISO-8601). Use to triage which scope a team has been working in lately before drilling down via the per-entity readers or `activity-log-list`. */+ recent_activity: RecentActivity;+ /** Up to 20 dashboards on this team sorted by `last_accessed_at` desc — what the team is currently looking at, not necessarily the most-trafficked. We don't have per-dashboard view counts in Postgres, only the timestamp of the most recent access. */+ recent_dashboards: RecentDashboardEntry[];+ /** Surveys orientation: total + active count, plus the 5 most recently updated surveys with id, name, type, status (draft / running / stopped / archived), and updated_at. */+ recent_surveys: RecentSurveys;+ /** Feature flag orientation: total + active count, plus the 5 most recently updated non-deleted flags with id, key, name, active, and updated_at. */+ recent_feature_flags: RecentFeatureFlags;+ /** Experiment orientation: total + running count, plus the 5 most recently updated experiments. The feature_flag_key on each row lets the scout correlate experiments with the `recent_feature_flags` section. */+ recent_experiments: RecentExperiments;+ /** Alert orientation: total + enabled count, plus the 5 most recently created alerts with their state and threshold metadata. */+ recent_alerts: RecentAlerts;+ /** Hog function orientation: total + enabled count, plus the 5 most recently updated destinations / transformations the team has wired up via the CDP pipelines. */+ recent_hog_functions: RecentHogFunctions;+ /** Hog flow orientation: total + non-archived count, plus the 5 most recently updated automation flows. */+ recent_hog_flows: RecentHogFlows;+ /** Notebook orientation: total + the 5 most recently modified notebooks — useful signal for what the team has been investigating. */+ recent_notebooks: RecentNotebooks;+ /** Cohort orientation: total + the 5 most recently created cohorts on the team. */+ recent_cohorts: RecentCohorts;+ /** Action orientation: total + the 5 most recently updated actions — useful to anchor agent reasoning about what the team treats as a meaningful interaction. */+ recent_actions: RecentActions;+ /**+ * Top ~50 events by count over the last 7 days, with first/last seen timestamps within the window. `null` if the underlying ClickHouse query failed or timed out (distinct from `[]`, which means the team has no captures in the window). Use the gap between `first_seen` and `now` to spot new event types or recent bursts.+ * @nullable+ */+ top_events: TopEventEntry[] | null;+ }++ /**+ * Top-level `payload` shape on a `SignalProjectProfile` row.++ v1 carries `inventory` only. Phase 7 will add `deltas`, `activity_notes`, and+ `narrative` slots — they're absent (not null) in v1 responses.+ */+ export interface ProjectProfilePayload {+ /** Deterministic snapshot of what's true about the project. */+ inventory: ProjectProfileInventory;+ }++ /**+ * Wire shape for the project profile returned by `signals-scout-harness-project-profile-list`.++ Read this once at the start of a run (after `skill-get`) to orient on the team. Cache+ is per-team with a soft TTL (`PROFILE_TTL`); the response always reflects either the+ latest cached profile or a freshly-built one if the cache was stale or the caller passed+ `force_refresh=true`.+ */+ export interface ProjectProfile {+ /** UUID of the `SignalProjectProfile` row. */+ profile_id: string;+ /** ISO-8601 timestamp the profile was built. */+ computed_at: string;+ /** ISO-8601 timestamp after which the profile is considered stale. */+ expires_at: string;+ /** Schema version of the inventory builder. Bumps invalidate older cached rows. */+ source_version: string;+ /** Structured profile content. v1 has `inventory` only. */+ payload: ProjectProfilePayload;+ }+export interface Property {/**You can use a simplified version:@@ -47593,6 +48142,13 @@ export namespace Schemas {suggested_reviewers?: string;};+ export type SignalsScoutProjectProfileGetParams = {+ /**+ * When true, skip the cache and rebuild the profile from authoritative sources before responding. Use after seeding events, importing data, or any other change the caller knows just landed but hasn't surfaced through natural cache expiry yet. Honored only for the internal scout token — public read callers get the cached profile regardless. Concurrent forced rebuilds are serialized by the team-keyed advisory lock — at most one extra `build_inventory` per simultaneous request.+ */+ force_refresh?: boolean;+ };+export type SignalsScoutRunsListParams = {/*** ISO-8601 inclusive lower bound on `created_at`. Omit to skip the lower bound.diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 90345233f081..d6fe3edbc58b 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 10 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -55,6 +55,29 @@ export const SignalsReportsRetrieveParams = /* @__PURE__ */ zod.object({),})+/**+ * Return the team's deterministic project profile. For the internal scout token the response reflects the newest non-expired cached row or a freshly-built one (lazy compute on cache miss); `force_refresh=true` skips the cache and rebuilds from authoritative sources. Public read callers (session auth or a `signal_scout:read` PAK) get the newest cached profile, or 404 if none has been built yet — they never trigger a rebuild. Read this at the start of a run to orient on the team's product mix, integrations, warehouse sources, signal coverage, and existing inbox surface.+ * @summary Get the current project profile+ */+export const SignalsScoutProjectProfileGetParams = /* @__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 signalsScoutProjectProfileGetQueryForceRefreshDefault = false++export const SignalsScoutProjectProfileGetQueryParams = /* @__PURE__ */ zod.object({+ force_refresh: zod+ .boolean()+ .default(signalsScoutProjectProfileGetQueryForceRefreshDefault)+ .describe(+ "When true, skip the cache and rebuild the profile from authoritative sources before responding. Use after seeding events, importing data, or any other change the caller knows just landed but hasn't surfaced through natural cache expiry yet. Honored only for the internal scout token — public read callers get the cached profile regardless. Concurrent forced rebuilds are serialized by the team-keyed advisory lock — at most one extra `build_inventory` per simultaneous request."+ ),+})+/*** 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 runsdiff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex b2f4eeccc37c..7c57abc72643 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -7,6 +7,7 @@ import {SignalsReportsRetrieveParams,SignalsScoutEmitSignalBody,SignalsScoutEmitSignalParams,+ SignalsScoutProjectProfileGetQueryParams,SignalsScoutRunsListQueryParams,SignalsScoutRunsRetrieveParams,SignalsScoutScratchpadForgetBody,@@ -193,6 +194,27 @@ const signalsScoutEmitSignal = (): ToolBase<typeof SignalsScoutEmitSignalSchema,},})+const SignalsScoutProjectProfileGetSchema = SignalsScoutProjectProfileGetQueryParams++const signalsScoutProjectProfileGet = (): ToolBase<+ typeof SignalsScoutProjectProfileGetSchema,+ Schemas.ProjectProfile+> => ({+ name: 'signals-scout-project-profile-get',+ schema: SignalsScoutProjectProfileGetSchema,+ handler: async (context: Context, params: z.infer<typeof SignalsScoutProjectProfileGetSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ProjectProfile>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/project_profile/current/`,+ query: {+ force_refresh: params.force_refresh,+ },+ })+ return result+ },+})+const SignalsScoutRunsListSchema = SignalsScoutRunsListQueryParamsconst signalsScoutRunsList = (): ToolBase<@@ -312,6 +334,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'inbox-source-configs-list': inboxSourceConfigsList,'inbox-source-configs-retrieve': inboxSourceConfigsRetrieve,'signals-scout-emit-signal': signalsScoutEmitSignal,+ 'signals-scout-project-profile-get': signalsScoutProjectProfileGet,'signals-scout-runs-list': signalsScoutRunsList,'signals-scout-runs-retrieve': signalsScoutRunsRetrieve,'signals-scout-scratchpad-forget': signalsScoutScratchpadForget,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-project-profile-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-project-profile-get.jsonnew file mode 100644index 000000000000..697da7354e57--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/signals-scout-project-profile-get.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "force_refresh": {+ "default": false,+ "description": "When true, skip the cache and rebuild the profile from authoritative sources before responding. Use after seeding events, importing data, or any other change the caller knows just landed but hasn't surfaced through natural cache expiry yet. Honored only for the internal scout token — public read callers get the cached profile regardless. Concurrent forced rebuilds are serialized by the team-keyed advisory lock — at most one extra `build_inventory` per simultaneous request.",+ "type": "boolean"+ }+ },+ "type": "object"+}diff --git a/tach.toml b/tach.tomlindex aab36ba5d6b7..c5ad36fb7a18 100644--- a/tach.toml+++ b/tach.toml@@ -496,10 +496,21 @@ layer = "modules"path = "products.signals"depends_on = ["posthog",+ "products.actions","products.ai_observability",+ "products.alerts",+ "products.cdp",+ "products.dashboards","products.data_warehouse","products.error_tracking",- "products.tasks", "products.warehouse_sources",+ "products.experiments",+ "products.feature_flags",+ "products.notebooks",+ "products.product_analytics",+ "products.surveys",+ "products.tasks",+ "products.warehouse_sources",+ "products.workflows",]layer = "modules"