: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
fix(signals): serve stale project profiles to read callers (#117884)
posthog[bot]79ac2b85a438
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 4a2e28ccb6aa..00564baf811d 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -3492,9 +3492,8 @@ class SignalScoutNote(TeamScopedRootMixin, UUIDModel):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.+ One row per (team, computed_at). The payload holds the inventory layer only. The last+ few rows per team are kept for debugging.Profile is the *deterministic ground truth* about a project (computed from authoritativetables). Distinct from `SignalScratchpad`, which is the *agent's inferred learnings* (possibly@@ -3511,16 +3510,14 @@ class SignalProjectProfile(TeamScopedRootMixin, UUIDModel):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+ # Soft TTL (`PROFILE_TTL`) — `get_project_profile` treats rows past expiry as cache misses+ # and recomputes for the scout. Read-only callers still get an expired row, marked 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+ # Structured payload: `{inventory: {...}}`. 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 (seediff --git a/products/signals/backend/scout_harness/profile/__init__.py b/products/signals/backend/scout_harness/profile/__init__.pyindex 346732542abd..3267a1c1bf8f 100644--- a/products/signals/backend/scout_harness/profile/__init__.py+++ b/products/signals/backend/scout_harness/profile/__init__.py@@ -1,8 +1,8 @@"""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.+grows with each new inventory section. 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_inventorydiff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex dcf0a42317b8..a739c1799dd1 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -2711,8 +2711,7 @@ class ProjectProfileInventorySerializer(serializers.Serializer):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.+ Carries `inventory` only."""inventory = ProjectProfileInventorySerializer(help_text="Deterministic snapshot of what's true about the project.")@@ -2790,9 +2789,9 @@ 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`.+ is per-team with a soft TTL (`PROFILE_TTL`). The internal scout token gets a fresh+ profile, built on a stale cache or `force_refresh=true`. Other callers get the newest+ stored profile, with `stale=true` when it is past `expires_at`.`summary` leads the response and `payload` trails it: the inventory runs to tens ofkilobytes, so a client that truncates a long tool result would otherwise cut off the emit@@ -2808,6 +2807,12 @@ class ProjectProfileSerializer(serializers.Serializer):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.")+ stale = serializers.BooleanField(+ help_text=(+ "True when the profile is past `expires_at`. Only read-only callers get a stale profile. "+ "Read `computed_at` to see how old it is, and verify a detail live when its age matters."+ ),+ )source_version = serializers.CharField(help_text="Schema version of the inventory builder. Bumps invalidate older cached rows.",)diff --git a/products/signals/backend/scout_harness/tools/profile.py b/products/signals/backend/scout_harness/tools/profile.pyindex 64e029a65605..c23a0bc5afb0 100644--- a/products/signals/backend/scout_harness/tools/profile.py+++ b/products/signals/backend/scout_harness/tools/profile.py@@ -5,8 +5,9 @@ so a fresh scout doesn't burn 4-5 orientation tool calls on `inbox-source-config`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.+team, or builds a fresh one on cache miss. A read-only caller gets the newest row of any age+instead, marked `stale` when it is past `expires_at`. `compute_project_profile` is the explicit+build path. The cache-miss branch and the `build_signal_project_profile` Celery task call it.Profile is *deterministic ground truth* (computed from authoritative tables). Distinctfrom `SignalScratchpad`, which is the *scout's inferred learnings* (TTL'd, possibly wrong).@@ -29,8 +30,8 @@ from products.signals.backend.models import SignalProjectProfilefrom 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+# A scout run reads the profile at start, so a team whose scouts run more often than this+# sees ground truth at most one TTL 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.@@ -39,9 +40,8 @@ from products.signals.backend.scout_harness.profile import INVENTORY_SOURCE_VERSPROFILE_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.+# pruning a single active team accumulates indefinitely. N=10 keeps some history for+# debugging without unbounded growth.PROFILE_KEEP_N = 10# Advisory-lock namespace key for `pg_advisory_xact_lock(ns, team_id)`. Picked@@ -63,10 +63,10 @@ SUMMARY_SECTIONS = ("emit_eligibility", "existing_inbox_reports")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+ `payload` is the structured snapshot: `{inventory: {...}}`. `stale` is true when the+ row is past `expires_at`, which only a read-only caller can get. `payload` is 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 thestored jsonb is schema-backed rather than free-form."""@@ -74,6 +74,7 @@ class ProjectProfile:computed_at: strexpires_at: strsource_version: str+ stale: bool = Falsepayload: dict[str, Any] = field(default_factory=dict)def summary(self) -> dict[str, Any]:@@ -94,15 +95,15 @@ def get_project_profile(*, team_id: int, force_refresh: bool = False, lazy_build"""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`+ and persists. The lazy compute path keeps brand-new teams (no profile yet) usable.++ `lazy_build=False` turns this into a pure read: it returns the newest row on the+ current `source_version` whatever its age, with `stale=True` when it is past+ `expires_at`, and `None` only when the team has no such row. 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) keeps the default build-on-miss path. `force_refresh`always builds, regardless of `lazy_build`.`SignalProjectProfile` is a `TeamScopedRootMixin` model, so `RootTeamMixin.save()`@@ -124,12 +125,12 @@ def get_project_profile(*, team_id: int, force_refresh: bool = False, lazy_build"""team_id = resolve_effective_team_id(team_id)if not force_refresh:- cached = _latest_fresh_profile(team_id=team_id)+ # A read-only caller gets an expired row rather than nothing, because it cannot+ # build a fresh one, and an old snapshot still orients better than a 404.+ cached = _latest_profile(team_id=team_id, include_expired=not lazy_build)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 Noneteam = Team.objects.get(id=team_id)return compute_project_profile(team=team, force=force_refresh)@@ -142,11 +143,11 @@ def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfil`PROFILE_TTL` (until `expires_at`); `get_project_profile` reads the newestnon-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+ Concurrent cache misses (several scout runs, or a scout run and the+ `build_signal_project_profile` task, 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 thelast `PROFILE_KEEP_N` rows survive — the table would otherwise grow unbounded(one row per cache miss, ~once per `PROFILE_TTL` per team, forever).@@ -158,8 +159,8 @@ def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfil"""# 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.+ # id too. `get_project_profile` already passes a canonical team; this guards a+ # direct call where an environment (child) team could be passed in.parent_team = team.parent_teamif parent_team is not None:team = parent_team@@ -168,7 +169,7 @@ def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfilcursor.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)+ existing = _latest_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")}@@ -194,7 +195,7 @@ def _prune_stale_profiles(*, team_id: int) -> int:`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.+ context — keeps the prune correct off the request path (the Celery build) too."""keep_ids = list(SignalProjectProfile.objects.unscoped()@@ -206,12 +207,13 @@ def _prune_stale_profiles(*, team_id: int) -> int: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.+def _latest_profile(*, team_id: int, include_expired: bool = False) -> SignalProjectProfile | None:+ """Newest profile for the team on the current schema, within its TTL unless `include_expired`.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.+ invalidates stale shapes without a manual backfill. `include_expired` drops only the+ TTL check, for read-only callers that cannot rebuild.`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@@ -221,17 +223,10 @@ def _latest_fresh_profile(*, team_id: int) -> SignalProjectProfile | None: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()- )+ rows = SignalProjectProfile.objects.unscoped().filter(team_id=team_id, source_version=INVENTORY_SOURCE_VERSION)+ if not include_expired:+ rows = rows.filter(expires_at__gt=timezone.now())+ return rows.order_by("-computed_at").first()def _to_dataclass(row: SignalProjectProfile) -> ProjectProfile:@@ -240,5 +235,6 @@ def _to_dataclass(row: SignalProjectProfile) -> ProjectProfile:computed_at=row.computed_at.isoformat(),expires_at=row.expires_at.isoformat(),source_version=row.source_version,+ stale=row.expires_at <= timezone.now(),payload=dict(row.payload or {}),)diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 062e0306e4ca..29ea7567a31b 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -263,6 +263,7 @@ from products.signals.backend.scout_harness.trial_access import ()from products.signals.backend.scout_harness.trial_views import ScoutTrialConfigMixinfrom products.signals.backend.scout_report import InvalidScoutReportError+from products.signals.backend.tasks import enqueue_project_profile_buildfrom products.skills.backend.api.skill_services import (LLMSkillDuplicateNameConflictError,create_skill,@@ -2379,12 +2380,15 @@ class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSeresponses={200: OpenApiResponse(response=ProjectProfileSerializer,- description="The team's current project profile (cached, or freshly built for the internal scout token).",+ description=(+ "The team's current project profile: freshly built for the internal scout token, or the "+ "newest stored profile for other callers, with `stale=true` when it is past `expires_at`."+ ),),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."+ "The team has no project profile yet, and the caller is not the internal scout token "+ "(which builds on cache miss). A background build starts, so retry in a minute."),),},@@ -2396,9 +2400,11 @@ class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe"the gate. Pass `summary_only=true` to omit `payload` entirely. 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."+ "callers (session auth or a `signal_scout:read` PAK) get the newest stored profile whatever its age, "+ "with `stale=true` when it is past `expires_at`. They never build inline: when the team has no "+ "profile, the call starts a background build and returns 404, so retry in a minute. 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(@@ -2424,9 +2430,8 @@ class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe# 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.+ # the newest stored profile of any age. When the team has none, they queue one deduped+ # background build per team, which bounds what a forged GET can cost.force_refresh = bool(validated.get("force_refresh", False)) and caller_is_internal_scoutteam_id = _canonical_team_id(self)profile = get_project_profile(@@ -2435,7 +2440,10 @@ class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSelazy_build=caller_is_internal_scout,)if profile is None:- raise exceptions.NotFound("No project profile has been built for this team yet.")+ enqueue_project_profile_build(team_id)+ raise exceptions.NotFound(+ "No project profile has been built for this team yet. A build has started, so retry in a minute."+ )body = profile.as_dict()_overlay_effective_emit_eligibility(body,diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex dc44ba36e96e..04f3dd64f62c 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -1019,6 +1019,35 @@ def rebuild_signal_repository_activity(team_id: int, repository: str, force: boocache.delete(lock_key)+# Long enough to collapse a burst of reads into one queued build, short enough that a failed+# build is retried by the next read a few minutes later.+_PROFILE_BUILD_DEDUPE_SECONDS = 5 * 60+++def enqueue_project_profile_build(team_id: int) -> None:+ """Queue one `build_signal_project_profile` per team per dedupe window."""+ if cache.add(f"signals_project_profile_build/{team_id}", "1", timeout=_PROFILE_BUILD_DEDUPE_SECONDS):+ build_signal_project_profile.delay(team_id)+++@shared_task(+ name="products.signals.backend.tasks.build_signal_project_profile",+ ignore_result=True,+ max_retries=0,+)+@with_team_scope()+def build_signal_project_profile(team_id: int) -> None:+ """Build the team's project profile off the request path, for a read caller that found none.++ `get_project_profile` returns a fresh row if one landed since the enqueue, and its advisory+ lock collapses this build with a concurrent scout build.+ """+ # The `tools` package imports this module through `slack_delivery_queue`.+ from products.signals.backend.scout_harness.tools.profile import get_project_profile # noqa: PLC0415++ get_project_profile(team_id=team_id)++@shared_task(name="products.signals.backend.tasks.refresh_signal_scout_background_bands",ignore_result=True,diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 6a25eb3e0099..8dac03b2c6e0 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -2865,25 +2865,36 @@ class TestAgentHarnessProjectProfileAPI(APIBaseTest):# --- untrusted (session) callers: read-only, never build ---- def test_session_read_returns_404_when_no_profile_exists(self) -> None:+ @patch("products.signals.backend.tasks.build_signal_project_profile.delay")+ def test_session_read_returns_404_and_queues_one_build_when_no_profile_exists(self, mock_delay: MagicMock) -> 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.+ # cached row the read-only caller gets a 404 and a deduped background build.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+ first = self.client.get(self._list_url())+ second = self.client.get(self._list_url())+ assert first.status_code == second.status_code == status.HTTP_404_NOT_FOUND+ assert "retry" in first.json()["detail"]+ mock_delay.assert_called_once_with(self.team.id)# 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:+ @parameterized.expand([("fresh", timedelta(minutes=30), False), ("a_day_old", -timedelta(days=1), True)])+ @patch("products.signals.backend.tasks.build_signal_project_profile.delay")+ def test_session_read_returns_stored_profile(+ self, _name: str, expires_in: timedelta, stale: bool, mock_delay: MagicMock+ ) -> None:seeded_id = self._seed_profile()+ SignalProjectProfile.objects.filter(id=seeded_id).update(expires_at=timezone.now() + expires_in)response = self.client.get(self._list_url())assert response.status_code == status.HTTP_200_OKbody = response.json()assert body["profile_id"] == seeded_id+ assert body["stale"] is staleassert {"summary", "profile_id", "computed_at", "expires_at", "source_version"} <= set(body.keys())assert "inventory" in body["payload"]- # Read-only: no new row written.+ # Read-only: no new row written, no build queued.assert SignalProjectProfile.objects.filter(team=self.team).count() == 1+ mock_delay.assert_not_called()def test_session_read_ignores_force_refresh(self) -> None:# `force_refresh` is honored only for the internal scout token. A session callerdiff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.pyindex c02433ffdea8..e5315405d298 100644--- a/products/signals/backend/test/test_scout_harness_profile.py+++ b/products/signals/backend/test/test_scout_harness_profile.py@@ -82,6 +82,7 @@ from products.signals.backend.scout_harness.tools.profile import (compute_project_profile,get_project_profile,)+from products.signals.backend.tasks import build_signal_project_profilefrom products.skills.backend.models.skills import LLMSkillfrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource@@ -1182,17 +1183,34 @@ class TestGetProjectProfile(BaseTest):assert fresh is not None and fresh.profile_id != cached.profile_idassert SignalProjectProfile.objects.filter(team=self.team).count() == 2- def test_lazy_build_false_returns_none_on_cache_miss_without_building(self) -> None:+ @parameterized.expand([("no_row", False), ("row_on_an_older_schema", True)])+ def test_lazy_build_false_returns_none_on_cache_miss_without_building(+ self, _name: str, seed_old_schema_row: bool+ ) -> 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+ if seed_old_schema_row:+ old = compute_project_profile(team=self.team)+ SignalProjectProfile.objects.filter(id=old.profile_id).update(source_version="v0_legacy")+ rows_before = SignalProjectProfile.objects.filter(team=self.team).count()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+ assert SignalProjectProfile.objects.filter(team=self.team).count() == rows_before++ def test_background_build_lets_a_read_only_caller_find_a_profile(self) -> None:+ assert get_project_profile(team_id=self.team.id, lazy_build=False) is None+ build_signal_project_profile(self.team.id)+ result = get_project_profile(team_id=self.team.id, lazy_build=False)+ assert result is not None and result.stale is False- def test_lazy_build_false_returns_cached_row_when_fresh(self) -> None:+ @parameterized.expand([("fresh", timedelta(minutes=30), False), ("expired", -timedelta(days=1), True)])+ def test_lazy_build_false_returns_newest_row_whatever_its_age(+ self, _name: str, expires_in: timedelta, stale: bool+ ) -> None:cached = compute_project_profile(team=self.team)+ SignalProjectProfile.objects.filter(id=cached.profile_id).update(expires_at=timezone.now() + expires_in)result = get_project_profile(team_id=self.team.id, lazy_build=False)assert result is not None and result.profile_id == cached.profile_id+ assert result.stale is stale# 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 d6b3b77594f5..74f561355235 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -5859,8 +5859,7 @@ export interface ProjectProfileInventoryApi {/*** 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.+ * Carries `inventory` only.*/export interface ProjectProfilePayloadApi {/** Deterministic snapshot of what's true about the project. */@@ -5871,9 +5870,9 @@ export interface ProjectProfilePayloadApi {* 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`.+ * is per-team with a soft TTL (`PROFILE_TTL`). The internal scout token gets a fresh+ * profile, built on a stale cache or `force_refresh=true`. Other callers get the newest+ * stored profile, with `stale=true` when it is past `expires_at`.** `summary` leads the response and `payload` trails it: the inventory runs to tens of* kilobytes, so a client that truncates a long tool result would otherwise cut off the emit@@ -5888,6 +5887,8 @@ export interface ProjectProfileApi {computed_at: string/** ISO-8601 timestamp after which the profile is considered stale. */expires_at: string+ /** True when the profile is past `expires_at`. Only read-only callers get a stale profile. Read `computed_at` to see how old it is, and verify a detail live when its age matters. */+ stale: boolean/** Schema version of the inventory builder. Bumps invalidate older cached rows. */source_version: string/** Structured profile content. v1 has `inventory` only. Omitted when `summary_only=true`. */diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex a2981c15c40e..f3d47dd51980 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -2076,7 +2076,7 @@ export const getSignalsScoutProjectProfileGetUrl = (}/**- * Return the team's deterministic project profile. The response opens with a compact `summary` envelope carrying the emit gate and the inbox report counts, then the full `payload`. The inventory runs to tens of kilobytes, so a client that truncates a long tool result still keeps the gate. Pass `summary_only=true` to omit `payload` entirely. 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.+ * Return the team's deterministic project profile. The response opens with a compact `summary` envelope carrying the emit gate and the inbox report counts, then the full `payload`. The inventory runs to tens of kilobytes, so a client that truncates a long tool result still keeps the gate. Pass `summary_only=true` to omit `payload` entirely. 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 stored profile whatever its age, with `stale=true` when it is past `expires_at`. They never build inline: when the team has no profile, the call starts a background build and returns 404, so retry in a minute. 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 (diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 27f38ca4c95e..4b552ef3d6bf 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -90654,8 +90654,7 @@ export namespace Schemas {/*** 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.+ * Carries `inventory` only.*/export interface ProjectProfilePayload {/** Deterministic snapshot of what's true about the project. */@@ -90666,9 +90665,9 @@ export namespace Schemas {* 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`.+ * is per-team with a soft TTL (`PROFILE_TTL`). The internal scout token gets a fresh+ * profile, built on a stale cache or `force_refresh=true`. Other callers get the newest+ * stored profile, with `stale=true` when it is past `expires_at`.** `summary` leads the response and `payload` trails it: the inventory runs to tens of* kilobytes, so a client that truncates a long tool result would otherwise cut off the emit@@ -90683,6 +90682,8 @@ export namespace Schemas {computed_at: string;/** ISO-8601 timestamp after which the profile is considered stale. */expires_at: string;+ /** True when the profile is past `expires_at`. Only read-only callers get a stale profile. Read `computed_at` to see how old it is, and verify a detail live when its age matters. */+ stale: boolean;/** Schema version of the inventory builder. Bumps invalidate older cached rows. */source_version: string;/** Structured profile content. v1 has `inventory` only. Omitted when `summary_only=true`. */diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 8be3e4b5b9f6..8aedcf93cda8 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -2151,7 +2151,7 @@ export const SignalsScoutNotesDestroyParams = () => zod.object({})/**- * Return the team's deterministic project profile. The response opens with a compact `summary` envelope carrying the emit gate and the inbox report counts, then the full `payload`. The inventory runs to tens of kilobytes, so a client that truncates a long tool result still keeps the gate. Pass `summary_only=true` to omit `payload` entirely. 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.+ * Return the team's deterministic project profile. The response opens with a compact `summary` envelope carrying the emit gate and the inbox report counts, then the full `payload`. The inventory runs to tens of kilobytes, so a client that truncates a long tool result still keeps the gate. Pass `summary_only=true` to omit `payload` entirely. 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 stored profile whatever its age, with `stale=true` when it is past `expires_at`. They never build inline: when the team has no profile, the call starts a background build and returns 404, so retry in a minute. 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 = () => zod.object({