: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): pre-compute suggested scouts per project (#85963)
Andrew Maguire0b6f7426416e
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex aa32471c088b..07c6da18e385 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -323,6 +323,7 @@ rules:|SignalScoutEmission|SignalScoutNote|SignalScoutStructuredOutput+ |SignalScoutSuggestionSet|SignalScratchpad|SignalProjectProfile|SingleSessionSummary@@ -700,6 +701,7 @@ rules:|SignalScoutEmission|SignalScoutNote|SignalScoutStructuredOutput+ |SignalScoutSuggestionSet|SignalScratchpad|SignalProjectProfile|SingleSessionSummarydiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex f10a0319d173..7ce69e866cfe 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -580,6 +580,8 @@ SPECTACULAR_SETTINGS = {"ScoutConfigStatusEnum": "products.signals.backend.models.SignalScoutConfig.Status","ScoutConfigPauseReasonEnum": "products.signals.backend.models.SignalScoutConfig.PauseReason","ScoutConfigNetworkAccessEnum": "products.signals.backend.models.SignalScoutConfig.NetworkAccess",+ # Shared by growth's identity-matching `tier` and the scout suggestion `confidence` fields.+ "ConfidenceTierEnum": ["low", "medium", "high"],# `source_product` names the same choice set on several signals components, so pin one name."SignalSourceProductEnum": "products.signals.backend.enums.signal_source_product_choices","EngineeringAnalyticsPRStateEnum": "products.engineering_analytics.backend.facade.contracts.PRState",diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 536e6fcebe73..064d25964147 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -116,7 +116,10 @@ from products.replay_vision.backend.temporal.reconciler import create_replay_visfrom products.replay_vision.backend.temporal.vision_alerts.schedule import create_vision_alert_check_schedulefrom products.review_hog.backend.temporal.outcomes_schedule import create_review_hog_finding_outcomes_schedulefrom products.signals.backend.emission.conversations_schedule import create_conversations_signals_coordinator_schedule-from products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedule+from products.signals.backend.temporal.agentic.schedule import (+ create_scout_suggestions_coordinator_schedule,+ create_signals_scout_coordinator_schedule,+)from products.web_analytics.backend.temporal.digest_notification.types import WADigestNotificationInputfrom products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInput@@ -924,6 +927,7 @@ schedules = [create_run_investigation_safety_net_schedule,create_cleanup_alert_checks_schedule,create_signals_scout_coordinator_schedule,+ create_scout_suggestions_coordinator_schedule,create_support_reply_coordinator_schedule,create_channel_summary_coordinator_schedule,create_account_track_rule_coordinator_schedule,diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 133708363fa5..c1e6057fd35d 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -101,6 +101,8 @@ class TestSignalsProductModuleIntegrity:"EmitEvalSignalWorkflow","RunSignalsScoutWorkflow","SignalsScoutCoordinatorWorkflow",+ "RunScoutSuggestionsWorkflow",+ "ScoutSuggestionsCoordinatorWorkflow","CustomSignalAgentWorkflow","SignalReportInboxNotificationWorkflow",]@@ -166,6 +168,9 @@ class TestSignalsProductModuleIntegrity:"fetch_enabled_signals_scout_runs_activity","stamp_dispatched_signals_scout_runs_activity","run_signals_scout_activity",+ "plan_scout_suggestion_runs_activity",+ "run_scout_suggestions_activity",+ "stamp_requested_scout_suggestions_activity","run_custom_signal_agent_activity",]actual_activity_names = [a.__name__ for a in SIGNALS_PRODUCT_ACTIVITIES]diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex ab831e86f0f7..796c84832977 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -95,6 +95,7 @@ post_delete:products.feature_flags.backend.local_evaluation.evaluation_context_cpost_delete:products.feature_flags.backend.local_evaluation.experiment_changedpost_delete:products.feature_flags.backend.local_evaluation.feature_flag_changedpost_delete:products.managed_warehouse.backend.models._observe_duckgres_server_delete+post_delete:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_changepost_delete:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_deletedpost_delete:products.signals.backend.receivers.tombstone_report_embedding_on_hard_deletepost_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change@@ -202,6 +203,7 @@ post_save:products.review_hog.backend.receivers.handle_task_run_savedpost_save:products.signals.backend.receivers.capture_status_change_analyticspost_save:products.signals.backend.receivers.close_pr_when_report_dismissedpost_save:products.signals.backend.receivers.emit_report_embedding_on_document_change+post_save:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_changepost_save:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_savedpost_save:products.signals.backend.receivers.tombstone_report_embedding_on_deletepost_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_changediff --git a/products/desktop/packages/agent/src/utils/gateway-routing-cases.json b/products/desktop/packages/agent/src/utils/gateway-routing-cases.jsonindex dca5519cc097..be142a162797 100644--- a/products/desktop/packages/agent/src/utils/gateway-routing-cases.json+++ b/products/desktop/packages/agent/src/utils/gateway-routing-cases.json@@ -7,6 +7,12 @@"internal": false,"expected": "signals_scout"},+ {+ "origin_product": "scout_suggestions",+ "ai_stage": "scout_suggestions",+ "internal": true,+ "expected": "signals"+ },{"origin_product": "signals_scout","ai_stage": "scout:web-analytics",diff --git a/products/desktop/packages/agent/src/utils/gateway.test.ts b/products/desktop/packages/agent/src/utils/gateway.test.tsindex 334204e0e8cc..6172b2df0794 100644--- a/products/desktop/packages/agent/src/utils/gateway.test.ts+++ b/products/desktop/packages/agent/src/utils/gateway.test.ts@@ -47,6 +47,11 @@ describe("resolveGatewayProduct", () => {originProduct: "signals_chat",expected: "signals",},+ {+ isInternal: true,+ originProduct: "scout_suggestions",+ expected: "signals",+ },{isInternal: false,originProduct: "posthog_ai",diff --git a/products/desktop/packages/agent/src/utils/gateway.ts b/products/desktop/packages/agent/src/utils/gateway.tsindex 898749c766e3..16db9d60e55f 100644--- a/products/desktop/packages/agent/src/utils/gateway.ts+++ b/products/desktop/packages/agent/src/utils/gateway.ts@@ -23,6 +23,7 @@ export function resolveGatewayProduct({loop: "posthog_code",onboarding: "onboarding",posthog_ai: "posthog_ai",+ scout_suggestions: "signals",signal_report: "signals",signals_chat: "signals",signals_scout: "signals",diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.tsindex a90ae8420ab8..388734951c53 100644--- a/products/growth/frontend/generated/api.schemas.ts+++ b/products/growth/frontend/generated/api.schemas.ts@@ -193,10 +193,9 @@ export interface ProductPushCampaignApi {* * `medium` - medium* * `low` - low*/-export type IdentityMatchingLinkTierEnumApi =- (typeof IdentityMatchingLinkTierEnumApi)[keyof typeof IdentityMatchingLinkTierEnumApi]+export type ConfidenceTierEnumApi = (typeof ConfidenceTierEnumApi)[keyof typeof ConfidenceTierEnumApi]-export const IdentityMatchingLinkTierEnumApi = {+export const ConfidenceTierEnumApi = {High: 'high',Medium: 'medium',Low: 'low',@@ -304,7 +303,7 @@ export interface IdentityMatchingLinkApi {* * `high` - high* * `medium` - medium* * `low` - low */- tier: IdentityMatchingLinkTierEnumApi+ tier: ConfidenceTierEnumApi/** When the link was computed (UTC). */computed_at: string/** Distinct (IP, day) combinations both sides were seen on. */diff --git a/products/mcp_store/backend/agents.py b/products/mcp_store/backend/agents.pyindex b79339b9a634..42420efa75ca 100644--- a/products/mcp_store/backend/agents.py+++ b/products/mcp_store/backend/agents.py@@ -55,6 +55,9 @@ _SPEC_BY_HANDLE = {spec.handle: spec for spec in BUILT_IN_AGENTS}_TASK_ORIGIN_TO_AGENT: dict[str, BuiltInAgentKey] = {"support_reply": "support","signals_scout": "scout",+ # The headless suggestion scan runs as the Scout agent with an empty server allowlist, so it+ # mounts nothing from the Store rather than the team's shared connectors.+ "scout_suggestions": "scout",}# Signal report tasks may be created through the public Tasks API, so they# remain member-scoped instead of inheriting Scout's MCP grants.diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex dc9c560f4bb4..9d96e1948fe3 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -319,9 +319,10 @@ def get_installations_for_sandbox(URL as a shared one, only the personal one is returned — the user acts asthemselves rather than through the shared credential.- ``allowed_gateway_server_ids`` narrows the agent mounts to the listed- gateway servers regardless of grant scope (a scout's per-scout selection);- see ``_mounts_for_agent_run``. It only applies on the agent path.+ ``allowed_gateway_server_ids`` narrows the mounts to the listed gateway+ servers regardless of grant scope (a scout's per-scout selection); see+ ``_mounts_for_agent_run``. It binds on both paths: passing ``[]`` mounts no+ MCP Store servers at all, and passing ``None`` leaves the mounts unnarrowed."""try:base_queryset = MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True).select_related(@@ -367,6 +368,11 @@ def get_installations_for_sandbox(shared_queryset = shared_queryset.filter(Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True))+ if allowed_gateway_server_ids is not None:+ # An explicit allowlist binds here too, so a caller that narrowed its mounts does+ # not silently get every shared installation while the team waits for the+ # `mcp-gateway` rollout. An empty list means the run wants no MCP Store servers.+ shared_queryset = shared_queryset.filter(gateway_server_id__in=allowed_gateway_server_ids)if user_id is not None:shared_queryset = shared_queryset.exclude(gateway_server__member_revocations__user_id=user_id)# list() evaluates the lazy querysets here so DB errors hit this handler.diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex 1aaadfe58840..c7194a7290df 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -314,6 +314,21 @@ class TestGetInstallationsForSandbox(BaseTest):assert {result.id for result in results} == {str(shared.id), str(personal.id)}assert all(result.proxy_token is None for result in results)+ def test_empty_allowlist_mounts_nothing_before_the_gateway_flag_rollout(self) -> None:+ # The rollout gate sends a mapped origin down the legacy path. An autonomous run that asked+ # for no MCP Store servers must not pick up every shared installation on the way.+ self.enforcement_enabled_mock.return_value = False+ self._create_installation(scope="shared", display_name="Shared")++ results = get_installations_for_sandbox(+ self.team.id,+ user_id=self.user.id,+ task_origin="scout_suggestions",+ allowed_gateway_server_ids=[],+ )++ assert results == []+def test_built_in_agent_only_gets_its_explicitly_delegated_credential(self) -> None:account = self._support_agent()granted_server = self._create_gateway_server(diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 69fbd231c4f8..bd7c78b66ee0 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2211,6 +2211,10 @@ export interface ScannerScoutCreateApi {config?: SignalScoutConfigOptionsApi}+/**+ * * `canonical` - canonical+ * * `custom` - custom+ */export type ScoutOriginEnumApi = (typeof ScoutOriginEnumApi)[keyof typeof ScoutOriginEnumApi]export const ScoutOriginEnumApi = {diff --git a/products/signals/backend/agent_runtime.py b/products/signals/backend/agent_runtime.pyindex 58405b5763d2..b8b41929168f 100644--- a/products/signals/backend/agent_runtime.py+++ b/products/signals/backend/agent_runtime.py@@ -60,6 +60,7 @@ WILDCARD = "*"# vocabulary they see in LLM analytics. Scout generations tag `scout:<skill>` for per-scout# cost attribution; the step key here stays the bare stage.STEP_SCOUT = "scout"+STEP_SCOUT_SUGGESTIONS = "scout_suggestions"STEP_RESEARCH = "research"STEP_REPO_SELECTION = "repo_selection"STEP_IMPLEMENTATION = "implementation"diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.mdindex 51edeb7f18c5..8324039c2a7e 100644--- a/products/signals/backend/management/AGENTS.md+++ b/products/signals/backend/management/AGENTS.md@@ -142,6 +142,21 @@ python manage.py sync_signals_scout_skills --all-enabled --dry-runOutput buckets per team: `created`, `updated`, `diverged` (team-edited or hand-authored rows left alone), `tombstoned` (rows the team already soft-deleted — left alone, never resurrected), `pruned` (live rows whose canonical skill was removed from disk — soft-deleted so the coordinator stops dispatching them). Same function the coordinator and runner call lazily — this command is just the impatient path.+### Pre-computed scout suggestions++`run_scout_suggestions` drives the headless "Suggested for this project" scan (`../scout_harness/suggestions.py`) without waiting for its Temporal coordinator. `--team-id` runs the scan inline for one team (bypassing the planner and its cap; the org still needs AI data processing approved) and prints the stored batch; `--show` prints the stored batch without running; `--plan` prints what the coordinator would dispatch on the next tick under the current `signals-scout-suggestions` flag payload.++```bash+# Generate (or regenerate) the batch for one team now, then print it+python manage.py run_scout_suggestions --team-id 1++# Just print what is stored+python manage.py run_scout_suggestions --team-id 1 --show++# What would the next coordinator tick dispatch?+python manage.py run_scout_suggestions --plan+```+## Backfilling task_run artefactsOne-off data migration: turn legacy `SignalReportTask` rows (those carrying the old `relationship` label) into `task_run` log artefacts so the research / implementation / repo-selection runs tied to a report show up in its artefact timeline. `SignalReportTask` lives on as the unlabelled task↔report association; rows without a legacy label are skipped — their `task_run` artefact is written at creation time.diff --git a/products/signals/backend/management/commands/run_scout_suggestions.py b/products/signals/backend/management/commands/run_scout_suggestions.pynew file mode 100644index 000000000000..6637dd423ced--- /dev/null+++ b/products/signals/backend/management/commands/run_scout_suggestions.py@@ -0,0 +1,82 @@+"""Hand-trigger the pre-computed scout suggestion scan for one team, or print the plan.++`--team-id` runs the headless scan inline (bypassing the planner and its cap) and prints the+stored batch. `--plan` prints what the coordinator would dispatch on the next tick under the+current `signals-scout-suggestions` flag payload, without dispatching anything.+"""++from __future__ import annotations++import json++from django.core.management.base import BaseCommand, CommandError++from asgiref.sync import async_to_sync++from posthog.models.scoping.manager import resolve_effective_team_id++from products.signals.backend.models import SignalScoutSuggestionSet+from products.signals.backend.scout_harness.suggestions import (+ enabled_skill_names,+ plan_suggestion_runs,+ read_suggestion_settings,+ reserved_scout_names,+ stamp_requested,+ visible_items,+)+from products.signals.backend.scout_harness.suggestions_runner import arun_scout_suggestions+++class Command(BaseCommand):+ help = "Generate the suggested-scouts batch for one team now, or print the coordinator's plan."++ def add_arguments(self, parser):+ parser.add_argument("--team-id", type=int, default=None)+ parser.add_argument("--plan", action="store_true", help="Print the next tick's plan; dispatch nothing.")+ parser.add_argument("--show", action="store_true", help="Print the stored batch for --team-id; run nothing.")++ def handle(self, *args, **options):+ settings = read_suggestion_settings()+ if options["plan"]:+ planned = plan_suggestion_runs(settings)+ self.stdout.write(f"settings: {settings}")+ self.stdout.write(f"planned {len(planned)} team(s):")+ for run in planned:+ self.stdout.write(f" team {run.team_id} (tier {run.tier})")+ return++ if options["team_id"] is None:+ raise CommandError("--team-id is required unless --plan is given")+ # The row and the planner state live on the canonical project, so a child-environment+ # id must resolve before the stamp or it strands a per-environment row.+ team_id = resolve_effective_team_id(options["team_id"])++ if not options["show"]:+ # Planner state, as a dispatched child would leave it: the coordinator does not redo+ # this team on its next tick.+ stamp_requested([team_id])+ result = async_to_sync(arun_scout_suggestions)(team_id, settings=settings, triggered_by="manual")+ self.stdout.write(+ self.style.SUCCESS(+ f"team {team_id}: {result.status} in {result.runtime_s:.1f}s "+ f"({result.suggestion_count} suggestions, task_run={result.task_run_id}, skip={result.skip_reason})"+ )+ )++ row = SignalScoutSuggestionSet.objects.for_team(team_id).first()+ if row is None:+ self.stdout.write("no stored batch")+ return+ self.stdout.write(f"status={row.status} generated_at={row.generated_at} fleet={row.fleet_snapshot}")+ for record in visible_items(+ row, enabled_skill_names=enabled_skill_names(team_id), reserved_names=reserved_scout_names(team_id)+ ):+ self.stdout.write(+ f"- [{record['kind']}/{record['confidence']}] {record['skill_name']}: {record['title']}"+ f"{' (gap)' if record.get('gap') else ''}"+ )+ self.stdout.write(f" {record['why_here']}")+ if record.get("draft_body"):+ self.stdout.write(+ f" draft: {len(record['draft_body'])} chars; config={json.dumps(record['proposed_config'])}"+ )diff --git a/products/signals/backend/migrations/0109_signal_scout_suggestion_set.py b/products/signals/backend/migrations/0109_signal_scout_suggestion_set.pynew file mode 100644index 000000000000..1da13034fa18--- /dev/null+++ b/products/signals/backend/migrations/0109_signal_scout_suggestion_set.py@@ -0,0 +1,78 @@+# Generated by Django 5.2.17 on 2026-08-19 17:59++import django.db.models.manager+import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1309_integration_kind_ext_idx"),+ ("signals", "0108_signalscratchpad_created_by_identity"),+ ]++ operations = [+ migrations.CreateModel(+ name="SignalScoutSuggestionSet",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("items", models.JSONField(blank=True, default=list)),+ (+ "status",+ models.CharField(+ choices=[+ ("fresh", "Fresh"),+ ("stale", "Stale"),+ ("failed", "Failed"),+ ("empty", "Empty"),+ ],+ db_default="empty",+ default="empty",+ max_length=16,+ ),+ ),+ ("generated_at", models.DateTimeField(blank=True, null=True)),+ ("task_run_id", models.UUIDField(blank=True, null=True)),+ (+ "model",+ models.CharField(blank=True, db_default="", default="", max_length=200),+ ),+ ("fleet_snapshot", models.JSONField(blank=True, default=list)),+ ("last_requested_at", models.DateTimeField(blank=True, null=True)),+ ("last_completed_at", models.DateTimeField(blank=True, null=True)),+ (+ "consecutive_failures",+ models.PositiveIntegerField(db_default=0, default=0),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "verbose_name": "Signal scout suggestion set",+ "verbose_name_plural": "Signal scout suggestion sets",+ "default_manager_name": "all_teams",+ },+ 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 5d97ea62debf..7c5a5e89b744 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0108_signalscratchpad_created_by_identity+0109_signal_scout_suggestion_setdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 835a8ad178b3..d2c6b556325f 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -2174,3 +2174,66 @@ class SignalRepositoryAreaActivity(TeamScopedRootMixin, UUIDModel):constraints = [models.UniqueConstraint(fields=["team", "repository", "area"], name="signal_repo_area_activity_uniq"),]+++class SignalScoutSuggestionSet(TeamScopedRootMixin, UUIDModel):+ """The pre-computed "Suggested for this project" scout batch, one row per team.++ The push-side complement to the "Suggest a scout" chat button: a headless task scans the+ project ahead of time (`scout_harness/suggestions.py`, dispatched by the+ `SuggestScoutsCoordinatorWorkflow`) and writes 3-5 suggestions here, so the scouts tab can+ offer them with zero wait. The row doubles as the planner's per-team state: `last_requested_at`+ is what "overdue" is measured from, `consecutive_failures` feeds the per-team breaker, and a+ team with no row has never been generated for.++ Items live in one JSON column rather than a child table because the only reads are "the+ whole batch for this team" and per-item writes are two flags (`dismissed_at`,+ `created_config_id`). Cross-team analysis rides the product events the surface emits, not+ SQL over the JSON. Exploding into rows is a mechanical upgrade if per-item history across+ refreshes is ever wanted.+ """++ class Status(models.TextChoices):+ # A batch exists and describes the fleet as it is now. Age is `generated_at`; the+ # scheduled refresh, not the status, is what bounds it.+ FRESH = "fresh", "Fresh"+ # A batch exists but the fleet changed since it was generated.+ STALE = "stale", "Stale"+ # The last generation attempt did not produce a batch; the prior items (if any) remain.+ FAILED = "failed", "Failed"+ # The last generation completed and found nothing worth suggesting.+ EMPTY = "empty", "Empty"++ # See SignalScoutConfig.all_teams for rationale.+ all_teams = models.Manager() # noqa: DJ012++ # db_constraint=False: creating an FK constraint locks the hot posthog_team table and has+ # blocked deploys (same as SignalScoutNote); app-level enforcement only.+ team = models.OneToOneField(+ "posthog.Team",+ on_delete=models.CASCADE,+ db_constraint=False,+ related_name="+",+ )+ # The suggestion records (`ScoutSuggestionItem` shape plus per-item `dismissed_at`,+ # `dismissed_by_id`, `created_config_id`). Empty until the first successful generation.+ items = models.JSONField(default=list, blank=True)+ status = models.CharField(max_length=16, choices=Status, default=Status.EMPTY, db_default=Status.EMPTY)+ # Batch provenance. `fleet_snapshot` is the enabled skill names at generation time so a later+ # reader can tell a suggestion went stale because the fleet changed, not because time passed.+ generated_at = models.DateTimeField(null=True, blank=True)+ task_run_id = models.UUIDField(null=True, blank=True)+ model = models.CharField(max_length=200, blank=True, default="", db_default="")+ fleet_snapshot = models.JSONField(default=list, blank=True)+ # Planner state. `last_requested_at` advances when a child workflow is dispatched (not when it+ # finishes) so a stuck or failed child does not get re-dispatched every tick.+ last_requested_at = models.DateTimeField(null=True, blank=True)+ last_completed_at = models.DateTimeField(null=True, blank=True)+ consecutive_failures = models.PositiveIntegerField(default=0, db_default=0)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ verbose_name = "Signal scout suggestion set"+ verbose_name_plural = "Signal scout suggestion sets"+ default_manager_name = "all_teams"diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex a63b78c288b3..c0b88c157fb3 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -26,6 +26,7 @@ from products.signals.backend.report_embeddings import (emit_report_tombstone,render_report_document,)+from products.signals.backend.scout_harness.suggestions import mark_stale_if_fleet_changedfrom products.signals.backend.tasks import close_dismissed_report_prlogger = structlog.get_logger(__name__)@@ -614,3 +615,19 @@ def _classification_snapshot(value = Nonesnapshot[prop] = value if isinstance(value, str) else Nonereturn snapshot+++@receiver(post_save, sender="signals.SignalScoutConfig")+@receiver(post_delete, sender="signals.SignalScoutConfig")+def mark_scout_suggestions_stale_on_fleet_change(sender: Any, instance: Any, **kwargs: Any) -> None:+ """A suggestion batch describes gaps in the fleet it was generated against, so a scout being+ enabled, disabled, or removed flips a `fresh` batch to `stale`; regeneration waits for the+ normal refresh. Saves that cannot change the enabled set (`update_fields` without `enabled`)+ skip the read entirely, and nothing here may fail the config write."""+ update_fields = kwargs.get("update_fields")+ if update_fields is not None and "enabled" not in update_fields:+ return+ try:+ mark_stale_if_fleet_changed(instance.team_id)+ except Exception:+ logger.warning("scout_suggestions: failed to mark batch stale", team_id=instance.team_id, exc_info=True)diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.pyindex 728768f302b2..589b4f1729dc 100644--- a/products/signals/backend/routes.py+++ b/products/signals/backend/routes.py@@ -12,6 +12,7 @@ from products.signals.backend.scout_harness.views import (SignalScoutViewSet,SignalScratchpadViewSet,)+from products.signals.backend.scout_suggestions_api import SignalScoutSuggestionViewSetfrom products.signals.backend.views import SignalViewSet@@ -77,4 +78,12 @@ def register_routes(routers: RouterRegistry) -> None:"project_signals_scout_chat_tasks",["team_id"],)+ # Pre-computed "Suggested for this project" scout batch (read / dismiss / refresh); the scouts+ # tab reads it with zero wait, the chat_tasks path above stays the interactive alternative.+ routers.projects.register(+ r"signals/scout/suggestions",+ SignalScoutSuggestionViewSet,+ "project_signals_scout_suggestions",+ ["team_id"],+ )routers.projects.register(r"signals/scout", SignalScoutViewSet, "project_signals_scout", ["team_id"])diff --git a/products/signals/backend/scout_chat.py b/products/signals/backend/scout_chat.pyindex de2f9af49598..7540478c98dc 100644--- a/products/signals/backend/scout_chat.py+++ b/products/signals/backend/scout_chat.py@@ -25,14 +25,15 @@ from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthenticfrom posthog.permissions import APIScopePermissionfrom products.signals.backend.models import SignalScoutConfig+from products.signals.backend.scout_harness.prompt import SCOUT_PROJECT_SCAN_GUIDANCEfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.access import usage_limit_response-SCOUT_AUTHOR_PROMPT = """I'd like to make a new scout for this PostHog project.+SCOUT_AUTHOR_PROMPT = f"""I'd like to make a new scout for this PostHog project.Use the authoring-scouts skill from the PostHog MCP to guide creating a new signals scout.-First, take a quick scan of this PostHog project to ground your suggestions: skim its events, insights, dashboards, recently emitted signals, and the existing scout fleet so you understand what this product is and where automated monitoring would add value.+First, {SCOUT_PROJECT_SCAN_GUIDANCE}Then ask me what sort of scout I'd like to make, and offer a few concrete suggestions tailored to what you found (for example specific funnels, error or latency spikes, churn or activation signals, or revenue metrics worth watching) – and call out gaps the current fleet doesn't already cover. Once I pick a direction, walk me through authoring the scout end to end.@@ -68,6 +69,27 @@ SCOUT_CHAT_TEMPLATES: dict[str, tuple[str, str]] = {SCOUT_CHAT_DAILY_ATTEMPT_CAP = 15+def consume_daily_attempt(key_prefix: str, scope_id: int | str, cap: int) -> bool:+ """Fixed UTC-day counter in the cache: True while `scope_id` is within `cap` attempts today."""+ window = int(time.time()) // 86400+ key = f"{key_prefix}:{scope_id}:{window}"+ cache.add(key, 0, timeout=86400)+ try:+ attempts = cache.incr(key)+ except ValueError:+ attempts = 1+ return attempts <= cap+++def refund_daily_attempt(key_prefix: str, scope_id: int | str) -> None:+ """Give back one attempt consumed this UTC day, for a request that did no work."""+ window = int(time.time()) // 86400+ try:+ cache.decr(f"{key_prefix}:{scope_id}:{window}")+ except ValueError:+ pass++class ScoutChatBurstRateThrottle(UserRateThrottle):scope = "signals_scout_chat_burst"rate = "2/hour"@@ -135,14 +157,7 @@ class SignalScoutChatTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetif limit_response := usage_limit_response(request.user, self.team_id):return limit_response- window = int(time.time()) // 86400- key = f"signals_scout_chat_attempts:{request.user.id}:{window}"- cache.add(key, 0, timeout=86400)- try:- attempts = cache.incr(key)- except ValueError:- attempts = 1- if attempts > SCOUT_CHAT_DAILY_ATTEMPT_CAP:+ if not consume_daily_attempt("signals_scout_chat_attempts", request.user.id, SCOUT_CHAT_DAILY_ATTEMPT_CAP):raise exceptions.Throttled(detail="You've reached today's limit for scout chats. Try again tomorrow.")title, prompt = SCOUT_CHAT_TEMPLATES[request.validated_data["chat_type"]]diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 73a6ecad483e..2e9dbcbbfd52 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -25,6 +25,8 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eIt also carries the mass-prune tripwire. A reap that takes more than half the canonical fleet, and at least `MASS_PRUNE_FLOOR` scouts, is not a retirement — it means the sync read a fleet the deploy did not ship — so it stamps `unexpected_prune` on the event and captures `UnexpectedScoutFleetPrune` into error tracking. A detector, not a guard: by the time the count exists the rows are tombstoned.- `config_registry.py``register_missing_configs(team_id)` — auto-creates an enabled, default-schedule `SignalScoutConfig` for any `signals-scout-*` skill lacking one ("author a skill, get a scout"). Called by the coordinator tick; the HTTP surface registers explicitly via the write-scoped config `create` endpoint instead (reads stay side-effect free). A canonical scout's `scout-tags` frontmatter (read through `lazy_seed.canonical_config_tags_for`) is stamped on the row it creates, which is how a product surface claims its scouts by tag instead of by hardcoded skill name — AI observability's self-driving tab lists the `ai-observability`-tagged configs. Forward-only like the rest of the seed posture: adding the key to an already-seeded scout leaves that team's existing config untagged until someone tags it through the config API.+- `suggestions.py` / `suggestions_runner.py`+ Pre-computed scout suggestions: the push-side twin of the "Suggest a scout" chat button. `suggestions.py` (temporalio-free, cheap to import) holds the structured-output contract the headless run returns (`ScoutSuggestionBatch`: 3-5 items, each a `canonical` "turn this on" pick or a `custom` draft with a ready-to-create `draft_body`), the `signals-scout-suggestions` flag-payload settings (`enabled`, `eligibility_tier` 0-4 (0 = allowlist only), `refresh_days`, `max_children_per_tick`, allow/blocklist, failure breaker), the planner (`plan_suggestion_runs`: recomputes the priority queue from Postgres every tick; tier, then never-generated, then most overdue, then most recently engaged; engagement is a report view or rating, a scout a person turned on or off (`status_changed_by`), or a scout a person created (`created_by`), never a plain edit or a system touch; nothing is stored as a queue; engagement is read only for the teams already in the tier map, since `SignalReportAction.last_at` is deliberately unindexed and an unbounded filter on it scans the whole action history; a team past the failure breaker doubles its refresh interval per further failure, because the cooldown is shorter than the refresh window and so could never hold a scheduled retry back), draft validation (`validate_suggestion_items` drops anything the one-click Create could not apply as-is), and persistence on `SignalScoutSuggestionSet` (one row per team, items as JSON, every write under a row lock since each is a read-modify-write of the column; dismissals carry forward by `skill_name` and survive as hidden tombstones when a batch omits the name, compacted to the dismissal fields so a dropped draft body does not sit in the row forever; a batch persisted after the fleet moved is stored `stale`, and a batch that merely aged past `refresh_days`, whether it held items or concluded there was nothing to suggest, reads as `stale` through `effective_status`, since nothing writes that status on expiry; a failed generation anywhere after the gates keeps the prior items and counts toward the breaker; `mark_stale_if_fleet_changed` is wired to `SignalScoutConfig` saves in `../receivers.py`). Reads hide dismissed, created, and already-enabled items, plus custom drafts whose name a stored skill or config has since taken; the manual refresh endpoint honors the same kill switch and blocklist as the planner, runs the scan as its authenticated caller rather than the resolved team member, and a manual dispatch stamps `last_requested_at` so the coordinator does not double up. `suggestions_runner.py` is the one piece that needs the tasks agent facade: `arun_scout_suggestions` gates (AI-processing consent, signals quota, an acting user), mints a `read_only` headless task with the reserved `SIGNALS_SCOUT_SUGGESTIONS` origin, no GitHub token and no MCP Store servers, because the scan reads project text any member can write, parses the batch with no prose salvage (an unparseable close-out is a failed generation), validates, persists, and emits `$scout_suggestions_generated`. Driven by `temporal/agentic/scout_suggestions.py` (coordinator + child, same shape as the scout coordinator, own schedule) and exposed read/dismiss/refresh at `signals/scout/suggestions/` (`../scout_suggestions_api.py`), where membership, token scope, and resource-level RBAC all anchor to the canonical parent team. The prompt shares `SCOUT_PROJECT_SCAN_GUIDANCE` (in `prompt.py`) with the chat template so the two voices never drift.- `slack_delivery.py` / `slack_delivery_queue.py` / `slack_charts.py`Best-effort direct Slack delivery for configured scout outputs. Finding emissions and surfaced report emits/edits snapshot the run config's destination after their database write commits, then enqueue the shared retrying Celery worker. The destination targets a single channel or up to `MAX_SCOUT_SLACK_DM_TARGETS` members who each get an individual DM (one Celery task per recipient, so retries and permanent failures stay independent; a group DM would need the `mpim:write` scope the Slack app doesn't request). Integrations are project-scoped, so a workspace connected from any environment in the project can receive the canonical parent team's scout output.A report message renders its `charts` through the exports facade (`render_png_export`, attributed to the run's acting user, so the insight access check applies; a system render that expires with its delivery url, so it stays out of the user's export quota and does not outlive its only reference) and appends them as `image` blocks pointing at a signed delivery url; chart links in the prose still reduce to their label. A threaded report carries its charts on the lead message, since the replies only hold the summary's tail. Only `InsightVizNode` / `SavedInsightNode` charts render, capped per report and by a render-time budget (a render only starts if it can finish inside the budget), with rendered assets remembered per delivery so a Slack retry does not re-render, and every failure is skipped rather than failing the delivery — the whole chart build is best effort, not only the render. The Slack integration row is resolved again after the build, since a workspace reconnected during the render window replaces the token on the same row.@@ -145,8 +147,8 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e- **Scout fleet** — the `signals-scout-*` skills live at`../../skills/signals-scout-*/` (generalist + 7 specialists). See`../../skills/AGENTS.md` for the fleet convention.-- **Local commands** — `run_signals_scout` (one-shot run) and- `sync_signals_scout_skills` (force a canonical-skill sync). Both documented in `../management/AGENTS.md`.+- **Local commands** — `run_signals_scout` (one-shot run), `run_scout_suggestions` (one-shot suggestion scan / print the plan), and+ `sync_signals_scout_skills` (force a canonical-skill sync). All documented in `../management/AGENTS.md`.## When editing this flowdiff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex 27a60c7c9eaf..cb394332bb70 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -9,7 +9,10 @@ goes through the write-scoped config `create` endpoint.from __future__ import annotations+from datetime import UTC, datetime+import structlog+from croniter import CroniterError, croniterfrom products.signals.backend.models import SignalScoutConfigfrom products.signals.backend.scout_harness.lazy_seed import (@@ -31,6 +34,40 @@ logger = structlog.get_logger(__name__)MIN_RUN_INTERVAL_MINUTES = 30MAX_RUN_INTERVAL_MINUTES = 43200+# Matches the `run_interval_minutes` floor: one scout may not occupy the coordinator more+# than once per 30 minutes, however the schedule is expressed.+CRON_MIN_GAP_SECONDS = MIN_RUN_INTERVAL_MINUTES * 60+# The column and the config API field cap; every writer applies it so a stored schedule fits.+CRON_SCHEDULE_MAX_LENGTH = 100+# Occurrences sampled by the min-gap check. Enough to expose sub-30-minute patterns+# (a `*/15` fires 96×/day) while staying trivially cheap for sparse schedules.+_CRON_SAMPLE_OCCURRENCES = 100+++def cron_schedule_error(value: str) -> str | None:+ """Why `value` is not an acceptable scout cron schedule, or None when it is.++ The one rule every writer applies (the config API serializers and the suggestion producer), so a+ schedule stored anywhere can be run everywhere: croniter also accepts 6/7-field (seconds/years)+ forms and @-aliases, so the shape is restricted to plain five fields, and occurrences must keep+ the same 30-minute floor as `run_interval_minutes`.+ """+ expr = value.strip()+ if len(expr) > CRON_SCHEDULE_MAX_LENGTH:+ return f"Cron expressions must be at most {CRON_SCHEDULE_MAX_LENGTH} characters."+ if len(expr.split()) != 5 or not croniter.is_valid(expr):+ return "Not a valid five-field cron expression, e.g. '30 9 * * *' or '0 9 * * 1-5'."+ iterator = croniter(expr, datetime(2026, 1, 1, tzinfo=UTC))+ try:+ occurrences = [iterator.get_next(datetime) for _ in range(_CRON_SAMPLE_OCCURRENCES)]+ except CroniterError:+ # `is_valid` accepts syntactically valid calendars that never occur, like '0 0 31 2 *'.+ return "This schedule never matches a real date. Check the day and month fields."+ min_gap = min((later - earlier).total_seconds() for earlier, later in zip(occurrences, occurrences[1:]))+ if min_gap < CRON_MIN_GAP_SECONDS:+ return "Scheduled runs must be at least 30 minutes apart (the same floor as run_interval_minutes)."+ return None+def ensure_scout_category(team_id: int, skill_name: str | None = None) -> None:"""Stamp `LLMSkill.category="scout"` on the team's scout skill rows.diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex c46bb83f8708..5d5250636838 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -13,6 +13,10 @@ from products.signals.backend.report_charts import MAX_REPORT_CHARTSfrom products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPT_LENGTH, MAX_SUGGESTED_PROMPTSfrom products.signals.backend.scout_harness.skill_loader import LoadedSkill, SkillAuthor, skill_uses_report_channel+# The project-scan step shared by the interactive "Suggest a scout" chat (`scout_chat.py`) and the+# headless pre-computed suggestion run (`suggestions.py`), so the two voices never drift.+SCOUT_PROJECT_SCAN_GUIDANCE = "take a quick scan of this PostHog project to ground your suggestions: skim its events, insights, dashboards, recently emitted signals, and the existing scout fleet so you understand what this product is and where automated monitoring would add value."+if TYPE_CHECKING:from collections.abc import Sequencediff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex b3d39b449683..3faf8d41922c 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -10,7 +10,7 @@ shape and Python shape stay in lockstep.from __future__ import annotationsimport re-from datetime import UTC, datetime+from datetime import datetimefrom typing import Anyfrom uuid import UUID@@ -18,7 +18,6 @@ from django.utils import timezoneimport structlogimport posthoganalytics-from croniter import croniterfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializers@@ -35,6 +34,7 @@ from products.signals.backend.artefact_schemas import ActionabilityChoice, Priorfrom products.signals.backend.models import SignalScoutConfig, SignalScoutEmissionfrom products.signals.backend.report_charts import MAX_REPORT_CHARTSfrom products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPT_LENGTH, MAX_SUGGESTED_PROMPTS+from products.signals.backend.scout_harness.config_registry import CRON_SCHEDULE_MAX_LENGTH, cron_schedule_errorfrom products.signals.backend.scout_harness.derived_metadata import DERIVED_FLAG_KEYS, DERIVED_METADATA_KEYfrom products.signals.backend.scout_harness.fleet_sync import SYNC_SURFACESfrom products.signals.backend.scout_harness.model_selection import scout_model_config_enabled, scout_model_pin_catalog@@ -2592,28 +2592,10 @@ class SignalScoutConfigSerializer(serializers.ModelSerializer):read_only_fields = ["id", "created_at"]-# Matches the `run_interval_minutes` floor: one scout may not occupy the coordinator more-# than once per 30 minutes, however the schedule is expressed.-_CRON_MIN_GAP_SECONDS = 30 * 60-# Occurrences sampled by the min-gap check. Enough to expose sub-30-minute patterns-# (a `*/15` fires 96×/day) while staying trivially cheap for sparse schedules.-_CRON_SAMPLE_OCCURRENCES = 100--def _validate_run_cron_schedule(value: str) -> str:expr = value.strip()- fields = expr.split()- # croniter also accepts 6/7-field (seconds/years) forms and @-aliases; restrict the API to- # the plain five-field shape so the stored expressions stay predictable across consumers.- if len(fields) != 5 or not croniter.is_valid(expr):- raise serializers.ValidationError("Not a valid five-field cron expression, e.g. '30 9 * * *' or '0 9 * * 1-5'.")- iterator = croniter(expr, datetime(2026, 1, 1, tzinfo=UTC))- occurrences = [iterator.get_next(datetime) for _ in range(_CRON_SAMPLE_OCCURRENCES)]- min_gap = min((later - earlier).total_seconds() for earlier, later in zip(occurrences, occurrences[1:]))- if min_gap < _CRON_MIN_GAP_SECONDS:- raise serializers.ValidationError(- "Scheduled runs must be at least 30 minutes apart (the same floor as run_interval_minutes)."- )+ if error := cron_schedule_error(expr):+ raise serializers.ValidationError(error)return expr@@ -2681,7 +2663,7 @@ class SignalScoutConfigUpdateSerializer(serializers.ModelSerializer):run_cron_schedule = serializers.CharField(required=False,allow_null=True,- max_length=100,+ max_length=CRON_SCHEDULE_MAX_LENGTH,help_text=("Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' ""(twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. "@@ -2868,7 +2850,7 @@ class SignalScoutConfigOptionsSerializer(serializers.Serializer):run_cron_schedule = serializers.CharField(required=False,allow_null=True,- max_length=100,+ max_length=CRON_SCHEDULE_MAX_LENGTH,help_text=("Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' ""(twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. "diff --git a/products/signals/backend/scout_harness/suggestions.py b/products/signals/backend/scout_harness/suggestions.pynew file mode 100644index 000000000000..035b29247abd--- /dev/null+++ b/products/signals/backend/scout_harness/suggestions.py@@ -0,0 +1,768 @@+"""Pre-computed scout suggestions: the push-side twin of the "Suggest a scout" chat.++The chat button mints a `SIGNALS_CHAT` task the user then waits on while the agent scans the+project. This module runs the same scan ahead of time, headless, for every eligible project and+stores 3-5 structured suggestions on `SignalScoutSuggestionSet`, so the scouts tab can offer them+with zero wait. Three pieces live here, all temporalio-free and cheap to import:++- the structured-output contract the headless run returns (`ScoutSuggestionBatch`)+- the planner: which teams to refresh this tick, in priority order (`plan_suggestion_runs`)+- persistence: write a batch, carry dismissals forward, dismiss / mark created++The runner that mints the headless task for one team lives in `suggestions_runner.py`, because it+pulls in the tasks agent facade (heavy by import) and the HTTP surface and receivers only need the+pieces here.++Everything that tunes the fleet-wide behavior reads from the `signals-scout-suggestions` flag+payload, so widening eligibility, capping spend, or switching the producer off is a flag edit+rather than a deploy or a per-team write.+"""++from __future__ import annotations++import json+from collections.abc import Collection, Iterable+from datetime import datetime, timedelta+from typing import Any, Literal+from uuid import UUID++from django.db import transaction+from django.db.models import F, Max, Q+from django.utils import timezone++import structlog+from pydantic import BaseModel, Field++from posthog.dataclasses import frozen+from posthog.models.scoping.manager import resolve_effective_team_id+from posthog.models.team.team import Team+from posthog.models.utils import uuid7++from products.signals.backend.models import (+ SignalReportAction,+ SignalScoutConfig,+ SignalScoutSuggestionSet,+ SignalSourceConfig,+)+from products.signals.backend.scout_harness.lazy_seed import CanonicalSkillParseError, discover_canonical_skills+from products.signals.backend.scout_harness.prompt import SCOUT_PROJECT_SCAN_GUIDANCE+from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX+from products.signals.backend.scout_harness.team_limits import read_flag_payload, withheld_skills_for_team+from products.skills.backend.models.skills import LLMSkill++logger = structlog.get_logger(__name__)++SIGNALS_SCOUT_SUGGESTIONS_FLAG = "signals-scout-suggestions"++# A scan plus 3-5 suggestions is a fraction of a scout run; the ceiling exists so a wedged+# sandbox cannot hold a worker slot for a scout-length run.+SUGGESTIONS_MAX_RUNTIME_S = 10 * 60+SUGGESTIONS_ACTIVITY_SLACK_S = 60++MAX_SUGGESTIONS_PER_BATCH = 5+MIN_SUGGESTIONS_PER_BATCH = 3+MAX_DRAFT_BODY_CHARS = 20_000+# Mirrors `SignalScoutCreateSerializer.description`: a longer one stores fine but fails the+# create it is supposed to be ready for.+MAX_DESCRIPTION_CHARS = 4_096++# Tags every $ai_generation a suggestion run makes, so its spend is splittable out of the+# `ai_product='signals'` bucket next to `scout:<skill>` (see `runner._ai_stage`).+SUGGESTIONS_AI_STAGE = "scout_suggestions"++SuggestionKind = Literal["canonical", "custom"]+SuggestionConfidence = Literal["low", "medium", "high"]+++# ---------------------------------------------------------------------------+# Structured-output contract+# ---------------------------------------------------------------------------+++class ScoutSuggestionProposedConfig(BaseModel):+ """Schedule and posture for the suggested scout. Mirrors the fields of the scout create API."""++ run_cron_schedule: str | None = Field(+ default=None,+ description=(+ "Optional five-field cron expression in the project timezone, e.g. '30 9 * * 1-5'. "+ "Takes precedence over run_interval_minutes."+ ),+ )+ run_interval_minutes: int | None = Field(+ default=None,+ description="Minutes between runs when no cron is given (30-43200). Omit for the daily default.",+ )+ emit: bool = Field(default=True, description="False for a dry run that logs but writes nothing to the inbox.")+++class ScoutSuggestionItem(BaseModel):+ """One suggestion: either turn on a canonical scout, or create a custom draft."""++ kind: SuggestionKind = Field(+ description=(+ "'canonical' to enable one of the PostHog-authored scouts listed in the prompt; "+ "'custom' for a new project-specific scout you drafted."+ )+ )+ skill_name: str = Field(+ description=(+ "canonical: the exact listed name. custom: a new slug starting with 'signals-scout-' "+ "(lowercase letters, digits, hyphens), not already in the fleet."+ )+ )+ title: str = Field(max_length=80, description="Sentence case, <= 80 chars: what the scout watches.")+ why_here: str = Field(+ description=(+ "2-4 sentences of project-specific evidence: the named events, funnels, insights, dashboards "+ "or recent reports that make this scout worth running on THIS project."+ )+ )+ description: str = Field(+ default="",+ description="custom only: one or two sentences describing the signal or behavior the scout investigates.",+ )+ draft_body: str = Field(+ default="",+ description=(+ "custom only: the complete markdown body the scout runs on every run, written per the "+ "authoring-scouts skill (what to check, thresholds, what counts as a finding, what to ignore)."+ ),+ )+ proposed_config: ScoutSuggestionProposedConfig = Field(default_factory=ScoutSuggestionProposedConfig)+ gap: bool = Field(default=False, description="True when nothing in the current fleet covers this.")+ confidence: SuggestionConfidence = Field(default="medium")+++class ScoutSuggestionBatch(BaseModel):+ """The JSON object the headless run ends its turn with."""++ suggestions: list[ScoutSuggestionItem] = Field(+ description=f"{MIN_SUGGESTIONS_PER_BATCH}-{MAX_SUGGESTIONS_PER_BATCH} suggestions, best first."+ )+ notes: str = Field(+ default="",+ description="Optional: why the batch is short or empty (e.g. the project has almost no data yet).",+ )+++# ---------------------------------------------------------------------------+# Flag payload -> settings+# ---------------------------------------------------------------------------+++@frozen+class SuggestionSettings:+ """The fleet-wide knobs, read from the `signals-scout-suggestions` flag payload every tick."""++ enabled: bool = False+ # The planner includes every tier <= this (see `_candidate_teams_by_tier`). 0 = the+ # `team_allowlist` only; 1 = engaged self-driving projects; 4 = every AI-approved team.+ eligibility_tier: int = 1+ engagement_window_days: int = 30+ refresh_days: int = 7+ max_children_per_tick: int = 10+ team_allowlist: frozenset[int] = frozenset()+ team_blocklist: frozenset[int] = frozenset()+ failure_breaker_threshold: int = 3+ failure_cooldown_hours: int = 24+ max_runtime_s: int = SUGGESTIONS_MAX_RUNTIME_S+++def _int_in(payload: dict[str, Any], key: str, default: int, *, low: int, high: int) -> int:+ value = payload.get(key, default)+ if isinstance(value, bool) or not isinstance(value, int):+ return default+ return min(max(value, low), high)+++def _team_id_set(payload: dict[str, Any], key: str) -> frozenset[int]:+ raw = payload.get(key)+ if not isinstance(raw, list):+ return frozenset()+ return frozenset(item for item in raw if isinstance(item, int) and not isinstance(item, bool))+++def parse_suggestion_settings(payload: dict[str, Any] | None) -> SuggestionSettings:+ """Parse the flag payload defensively: an absent or malformed payload means "off"."""+ if not payload:+ return SuggestionSettings()+ return SuggestionSettings(+ enabled=payload.get("enabled") is True,+ eligibility_tier=_int_in(payload, "eligibility_tier", 1, low=0, high=4),+ engagement_window_days=_int_in(payload, "engagement_window_days", 30, low=1, high=365),+ refresh_days=_int_in(payload, "refresh_days", 7, low=1, high=90),+ max_children_per_tick=_int_in(payload, "max_children_per_tick", 10, low=0, high=500),+ team_allowlist=_team_id_set(payload, "team_allowlist"),+ team_blocklist=_team_id_set(payload, "team_blocklist"),+ failure_breaker_threshold=_int_in(payload, "failure_breaker_threshold", 3, low=1, high=100),+ failure_cooldown_hours=_int_in(payload, "failure_cooldown_hours", 24, low=1, high=24 * 30),+ max_runtime_s=_int_in(payload, "max_runtime_s", SUGGESTIONS_MAX_RUNTIME_S, low=60, high=30 * 60),+ )+++def read_suggestion_settings() -> SuggestionSettings:+ """Blocking (flag SDK read); async callers wrap this in `asyncio.to_thread`."""+ return parse_suggestion_settings(read_flag_payload(SIGNALS_SCOUT_SUGGESTIONS_FLAG))+++# ---------------------------------------------------------------------------+# Planner+# ---------------------------------------------------------------------------+++@frozen+class PlannedSuggestionRun:+ team_id: int+ tier: int+++@frozen(order=True)+class _SortKey:+ # Tier first, never-generated before generated, most overdue first, then the project someone+ # looked at most recently, so when the cap bites the teams who will see the strip get+ # refreshed first. Field order is the sort order.+ tier: int+ generated: int+ overdue_negative_s: float+ engagement_recency_s: float+++@frozen+class _Candidate:+ team_id: int+ tier: int+ never_generated: bool+ overdue_s: float+ engagement_recency_s: float++ @property+ def sort_key(self) -> _SortKey:+ return _SortKey(+ tier=self.tier,+ generated=0 if self.never_generated else 1,+ overdue_negative_s=-self.overdue_s,+ engagement_recency_s=self.engagement_recency_s,+ )+++def _root_team_q() -> Q:+ # `TeamScopedRootMixin` rows canonicalize to the parent project, so child environments are+ # never planned; their parent's batch is what their inbox reads.+ return Q(parent_team_id__isnull=True) | Q(parent_team_id=F("id"))+++def _engagement_by_team(cutoff: datetime, team_ids: Collection[int]) -> dict[int, datetime]:+ """Most recent inbox engagement per team inside the window: report views/ratings, a scout+ someone turned on or off, or a scout someone created. Aggregated in Postgres so the transfer+ is one row per team.++ The config row attributes only those two acts: `status_changed_by` is cleared by system+ transitions and enabled-only writes, and `created_by` is unset on coordinator-registered rows,+ so neither can mistake a system touch for a person. A plain edit carries no actor.++ Restricted to the teams the planner is already considering, so this rides the `team_id` index.+ `SignalReportAction.last_at` is deliberately unindexed, to keep the hot repeat-view UPDATE+ eligible for HOT, which makes an unbounded filter on it a scan of the whole action history.+ """+ if not team_ids:+ return {}+ latest: dict[int, datetime] = {}+ for queryset in (+ SignalReportAction.all_teams.filter(team_id__in=team_ids, last_at__gte=cutoff)+ .values("team_id")+ .annotate(latest=Max("last_at")),+ SignalScoutConfig.all_teams.filter(team_id__in=team_ids)+ .filter(+ Q(updated_at__gte=cutoff, status_changed_by__isnull=False)+ | Q(created_at__gte=cutoff, created_by__isnull=False)+ )+ .values("team_id")+ .annotate(latest=Max("updated_at")),+ ):+ for row in queryset:+ team_id, engaged_at = row["team_id"], row["latest"]+ if team_id not in latest or engaged_at > latest[team_id]:+ latest[team_id] = engaged_at+ return latest+++def _candidate_teams_by_tier(settings: SuggestionSettings, now: datetime) -> tuple[dict[int, int], dict[int, datetime]]:+ """Map team_id -> tier for every team in a tier <= `settings.eligibility_tier`, plus the+ engagement map used as the sort tie-break. The tier predicates run as subqueries so only the+ matching ids cross the wire, never the whole approved-team set."""+ if settings.eligibility_tier < 1:+ # Allowlist-only mode: the caller injects the allowlist at tier 0, so there is+ # nothing to compute here.+ return {}, {}+ cutoff = now - timedelta(days=settings.engagement_window_days)++ approved_root_teams = Team.objects.filter(_root_team_q(), organization__is_ai_data_processing_approved=True)+ # Source configs are environment-scoped, so a project whose Signals setup lives in a child+ # environment counts through that child's parent; scout configs already canonicalize.+ source_teams = SignalSourceConfig.objects.filter(enabled=True).values("team_id")+ set_up = (+ Q(id__in=source_teams)+ | Q(id__in=Team.objects.filter(id__in=source_teams, parent_team_id__isnull=False).values("parent_team_id"))+ | Q(id__in=SignalScoutConfig.all_teams.filter(enabled=True).values("team_id"))+ )++ tiers: dict[int, int] = {}+ set_up_team_ids = list(approved_root_teams.filter(set_up).values_list("id", flat=True))+ if settings.eligibility_tier >= 3:+ active_member_teams = (+ approved_root_teams.exclude(set_up)+ .filter(organization__membership__user__last_login__gte=cutoff)+ .values_list("id", flat=True)+ .distinct()+ )+ for team_id in active_member_teams:+ tiers[team_id] = 3+ if settings.eligibility_tier >= 4:+ for team_id in approved_root_teams.exclude(set_up).values_list("id", flat=True):+ tiers.setdefault(team_id, 4)+ # Engagement last, over the candidates we actually have: it splits tier 1 from tier 2 and+ # breaks ties in the sort, so it never needs a team the planner would not consider anyway.+ engagement = _engagement_by_team(cutoff, set(set_up_team_ids) | set(tiers))+ for team_id in set_up_team_ids:+ tiers[team_id] = 1 if team_id in engagement else 2+ tiers = {team_id: tier for team_id, tier in tiers.items() if tier <= settings.eligibility_tier}+ return tiers, engagement+++def canonical_team_ids(team_ids: Iterable[int]) -> set[int]:+ """Resolve operator-supplied ids to canonical project ids, so a child environment listed in+ the flag payload lands on the same row the planner and the API read. Unknown ids drop out."""+ ids = set(team_ids)+ if not ids:+ return set()+ return {+ parent_id or team_id+ for team_id, parent_id in Team.objects.filter(id__in=ids).values_list("id", "parent_team_id")+ }+++def suggestions_allowed_for_team(settings: SuggestionSettings, team_id: int) -> bool:+ """The kill switch and blocklist the planner honors, for the manual refresh path."""+ return settings.enabled and team_id not in canonical_team_ids(settings.team_blocklist)+++# How far the failure backoff can double the refresh interval. At the defaults (threshold 3,+# refresh 7 days) a project that keeps failing waits 14 days, then 28, then 56, then 112.+MAX_BREAKER_DOUBLINGS = 4+++def _wait_s(consecutive_failures: int, settings: SuggestionSettings, *, refresh_s: float) -> float:+ """How long a team must sit since its last request before it is due again.++ A tripped breaker doubles the refresh interval per failure past the threshold. The cooldown+ alone cannot suppress a scheduled retry, because it is shorter than the refresh window it+ would have to outlast, so a permanently failing project used to spend a scan every refresh+ period no matter how many times it had failed.+ """+ if consecutive_failures < settings.failure_breaker_threshold:+ return refresh_s+ doublings = min(consecutive_failures - settings.failure_breaker_threshold + 1, MAX_BREAKER_DOUBLINGS)+ return refresh_s * (2**doublings)+++def plan_suggestion_runs(settings: SuggestionSettings, now: datetime | None = None) -> list[PlannedSuggestionRun]:+ """The teams to refresh this tick, best first, capped at `max_children_per_tick`.++ The queue is recomputed from DB state every tick (no stored queue), so changing eligibility is a+ payload edit, never a migration of queued work. Allowlisted teams are always candidates+ (dogfood / support), blocklisted teams never are, and a team past the failure breaker backs off+ geometrically so a broken project cannot hold a slot every refresh period.+ """+ now = now or timezone.now()+ if not settings.enabled or settings.max_children_per_tick == 0:+ return []+ tiers, engagement = _candidate_teams_by_tier(settings, now)+ for team_id in canonical_team_ids(settings.team_allowlist):+ tiers.setdefault(team_id, 0)+ for team_id in canonical_team_ids(settings.team_blocklist):+ tiers.pop(team_id, None)+ if not tiers:+ return []++ # One row per ever-planned team, so loading the table beats an IN list the size of the fleet.+ state_by_team = {+ row.team_id: row+ for row in SignalScoutSuggestionSet.all_teams.only(+ "team_id", "last_requested_at", "consecutive_failures", "last_completed_at"+ )+ }+ refresh_s = settings.refresh_days * 86400+ cooldown = timedelta(hours=settings.failure_cooldown_hours)+ candidates: list[_Candidate] = []+ for team_id, tier in tiers.items():+ state = state_by_team.get(team_id)+ if state is None or state.last_requested_at is None:+ never_generated, overdue_s = True, float("inf")+ else:+ never_generated = False+ overdue_s = (now - state.last_requested_at).total_seconds() - _wait_s(+ state.consecutive_failures, settings, refresh_s=refresh_s+ )+ if overdue_s < 0:+ continue+ # The cooldown runs from the last attempt, not `updated_at`: a dismissal on the prior+ # batch touches the row too and must not push recovery out. It floors the wait; the+ # backoff above is what actually holds a repeatedly failing project back, since the+ # cooldown is shorter than the refresh window it would have to outlast.+ if (+ state is not None+ and state.consecutive_failures >= settings.failure_breaker_threshold+ and state.last_completed_at is not None+ and state.last_completed_at >= now - cooldown+ ):+ continue+ engaged_at = engagement.get(team_id)+ recency = (now - engaged_at).total_seconds() if engaged_at else float("inf")+ candidates.append(+ _Candidate(+ team_id=team_id,+ tier=tier,+ never_generated=never_generated,+ overdue_s=overdue_s,+ engagement_recency_s=recency,+ )+ )+ candidates.sort(key=lambda candidate: candidate.sort_key)+ return [+ PlannedSuggestionRun(team_id=candidate.team_id, tier=candidate.tier)+ for candidate in candidates[: settings.max_children_per_tick]+ ]+++def stamp_requested(team_ids: list[int], now: datetime | None = None) -> None:+ """Advance `last_requested_at` for the teams a child was dispatched for. Split from planning+ so a fan-out failure re-plans the team next tick instead of silently skipping a refresh."""+ if not team_ids:+ return+ now = now or timezone.now()+ # `bulk_create` skips `save()`, which is fine here: the planner only hands over canonical root+ # team ids, so there is nothing for `TeamScopedRootMixin` to rewrite.+ SignalScoutSuggestionSet.all_teams.bulk_create(+ [SignalScoutSuggestionSet(team_id=team_id) for team_id in team_ids], ignore_conflicts=True+ )+ SignalScoutSuggestionSet.all_teams.filter(team_id__in=team_ids).update(last_requested_at=now)+++# ---------------------------------------------------------------------------+# Prompt+# ---------------------------------------------------------------------------+++@frozen+class FleetContext:+ enabled_skill_names: tuple[str, ...]+ available_canonical: tuple[tuple[str, str], ...] # (name, description) not yet enabled+ # Names a custom draft may not take: every scout config on the project (enabled or not) and+ # every `signals-scout-*` skill already stored, since create returns 409 when a name's stored+ # definition differs from the draft.+ reserved_names: frozenset[str] = frozenset()+++def enabled_skill_names(team_id: int) -> list[str]:+ """The project's enabled scout skill names, sorted, as `fleet_snapshot` stores them."""+ return sorted(SignalScoutConfig.objects.for_team(team_id).filter(enabled=True).values_list("skill_name", flat=True))+++def reserved_scout_names(team_id: int) -> frozenset[str]:+ """Names a custom draft may not take: every scout config on the project (enabled or not) and+ every stored `signals-scout-*` skill, since create answers a differing definition with 409."""+ reserved = set(SignalScoutConfig.objects.for_team(team_id).values_list("skill_name", flat=True))+ reserved.update(+ LLMSkill.objects.filter(+ team_id=resolve_effective_team_id(team_id),+ is_latest=True,+ deleted=False,+ name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,+ ).values_list("name", flat=True)+ )+ return frozenset(reserved)+++def fleet_context(team_id: int) -> FleetContext:+ enabled = tuple(enabled_skill_names(team_id))+ try:+ canonical = discover_canonical_skills()+ except CanonicalSkillParseError:+ canonical = ()+ enabled_set = set(enabled)+ # A held-back canonical scout is not seeded by the sync path and the config API refuses to+ # enable it, so offering it would surface an unreleased scout behind a Create that must fail.+ withheld = withheld_skills_for_team(resolve_effective_team_id(team_id))+ available = tuple(+ (skill.name, skill.description)+ for skill in canonical+ if skill.name not in enabled_set and skill.name not in withheld+ )+ return FleetContext(+ enabled_skill_names=enabled, available_canonical=available, reserved_names=reserved_scout_names(team_id)+ )+++def build_suggestions_prompt(fleet: FleetContext) -> str:+ schema = json.dumps(ScoutSuggestionBatch.model_json_schema(), indent=2)+ enabled_lines = "\n".join(f"- {name}" for name in fleet.enabled_skill_names) or "- (none yet)"+ canonical_lines = (+ "\n".join(f"- `{name}`: {description}" for name, description in fleet.available_canonical) or "- (none)"+ )+ return f"""You are preparing the "Suggested for this project" list for the PostHog scouts tab. Nobody is in the chat with you: work headlessly and end your turn with the JSON object described at the bottom.++First, {SCOUT_PROJECT_SCAN_GUIDANCE} Use the read-data, insight, dashboard, and signals-scout MCP tools (config list for the fleet, recent runs and reports for what the scouts already surface). Read the authoring-scouts skill from the PostHog MCP (`skill-get`) before drafting any custom scout; if it is unavailable, write the draft in the same shape as the canonical scout bodies.++Scouts currently enabled on this project:+{enabled_lines}++PostHog-authored scouts available to turn on (suggest these by exact name with kind "canonical"):+{canonical_lines}++Produce {MIN_SUGGESTIONS_PER_BATCH}-{MAX_SUGGESTIONS_PER_BATCH} suggestions, best first:+- Mix "canonical" picks (cheap, high-confidence "turn this on") with at least one or two "custom" drafts tailored to what you found (a specific funnel, a custom event, an error or latency spike, a churn, activation, or revenue signal), so the set is project-specific rather than a template list.+- Every `why_here` must cite concrete evidence you actually saw: event names, insight or dashboard names, report titles, volumes. Never suggest something the project has no data for.+- Do not suggest a scout that is already enabled, and set `gap` only when nothing in the fleet covers the same ground.+- A custom draft needs a `skill_name` starting with `signals-scout-`, a one-line `description`, and a complete `draft_body` following the authoring-scouts skill: what to check, thresholds, what counts as a finding, what to ignore, how to dedupe against prior runs. Keep the `description` under {MAX_DESCRIPTION_CHARS} characters and the body under {MAX_DRAFT_BODY_CHARS}.+- Leave Slack delivery out of `proposed_config`; the person choosing the suggestion picks the destination.+- If the project genuinely has too little data to suggest anything, return an empty list and say why in `notes`.++End your turn with ONLY a JSON object matching this schema (no prose before or after it):++{schema}+"""+++# ---------------------------------------------------------------------------+# Persistence+# ---------------------------------------------------------------------------+++def _item_record(item: ScoutSuggestionItem, *, prior: dict[str, Any] | None) -> dict[str, Any]:+ prior = prior or {}+ record = item.model_dump()+ record["id"] = prior.get("id") or str(uuid7())+ # A dismissed suggestion must not resurrect on the next refresh; carry the flag by skill_name.+ record["dismissed_at"] = prior.get("dismissed_at")+ record["dismissed_by_id"] = prior.get("dismissed_by_id")+ record["created_config_id"] = prior.get("created_config_id")+ return record+++def _is_tombstone(record: dict[str, Any]) -> bool:+ """A record `_tombstone` compacted: dismissal bookkeeping with none of the item fields left."""+ return "kind" not in record+++def _tombstone(record: dict[str, Any]) -> dict[str, Any]:+ """A dismissed suggestion the new batch dropped, reduced to what a later batch needs to know.+ Carrying the whole record would keep a 20,000-character draft body in the row forever, and+ every read, dismissal and refresh pays to load and rewrite it under the row lock."""+ return {+ "id": record.get("id"),+ "skill_name": record.get("skill_name"),+ "dismissed_at": record.get("dismissed_at"),+ "dismissed_by_id": record.get("dismissed_by_id"),+ "created_config_id": record.get("created_config_id"),+ }+++def _lock_row(team_id: int, *, create: bool) -> SignalScoutSuggestionSet | None:+ """The team's row, locked for the enclosing transaction. Every write to `items` is a+ read-modify-write of one JSON column, so a dismissal racing a refresh (or two dismissals)+ serializes here instead of the later save dropping the earlier change."""+ team_id = resolve_effective_team_id(team_id)+ if create:+ SignalScoutSuggestionSet.all_teams.get_or_create(team_id=team_id)+ return SignalScoutSuggestionSet.objects.for_team(team_id, canonical=True).select_for_update().first()+++def persist_suggestion_batch(+ team_id: int,+ items: list[ScoutSuggestionItem],+ *,+ task_run_id: str | None,+ model: str | None,+ fleet_snapshot: list[str],+ now: datetime | None = None,+) -> SignalScoutSuggestionSet:+ """Replace the team's batch with `items`, carrying forward per-item dismissal and created+ state for any suggestion that survives by `skill_name`. Dismissed suggestions the new batch+ does not repeat stay as hidden tombstones, so a skill dismissed two refreshes ago does not+ resurface the next time the model proposes it."""+ now = now or timezone.now()+ with transaction.atomic():+ row = _lock_row(team_id, create=True)+ assert row is not None+ prior_by_name = {record.get("skill_name"): record for record in (row.items or []) if isinstance(record, dict)}+ records = [_item_record(item, prior=prior_by_name.get(item.skill_name)) for item in items]+ suggested = {item.skill_name for item in items}+ records.extend(+ _tombstone(record)+ for name, record in prior_by_name.items()+ if record.get("dismissed_at") and name not in suggested+ )+ row.items = records+ row.fleet_snapshot = sorted(fleet_snapshot)+ # The fleet can move while the scan runs; a batch generated against the old fleet is+ # stored, but reported as stale, the same as the config receiver would flag it later.+ # Fleet first: "nothing to suggest" reached against a fleet that has since moved is as+ # stale as any other conclusion, and nothing would revisit it before the next refresh.+ if enabled_skill_names(row.team_id) != row.fleet_snapshot:+ row.status = SignalScoutSuggestionSet.Status.STALE+ elif not items:+ row.status = SignalScoutSuggestionSet.Status.EMPTY+ else:+ row.status = SignalScoutSuggestionSet.Status.FRESH+ row.generated_at = now+ row.last_completed_at = now+ row.task_run_id = UUID(task_run_id) if task_run_id else None+ row.model = model or ""+ row.consecutive_failures = 0+ row.save(+ update_fields=[+ "items",+ "status",+ "generated_at",+ "last_completed_at",+ "task_run_id",+ "model",+ "fleet_snapshot",+ "consecutive_failures",+ "updated_at",+ ]+ )+ return row+++def mark_generation_failed(team_id: int, *, task_run_id: str | None) -> SignalScoutSuggestionSet:+ """A failed generation keeps the prior items readable and counts toward the breaker."""+ with transaction.atomic():+ row = _lock_row(team_id, create=True)+ assert row is not None+ row.status = SignalScoutSuggestionSet.Status.FAILED+ row.consecutive_failures += 1+ row.last_completed_at = timezone.now()+ if task_run_id:+ row.task_run_id = UUID(task_run_id)+ row.save(update_fields=["status", "consecutive_failures", "last_completed_at", "task_run_id", "updated_at"])+ return row+++# A generated conclusion, with or without items; `failed` and `stale` already say what they are.+_EXPIRING_STATUSES = (SignalScoutSuggestionSet.Status.FRESH, SignalScoutSuggestionSet.Status.EMPTY)+++def effective_status(row: SignalScoutSuggestionSet, *, refresh_days: int) -> str:+ """The row's status with expiry applied. Only the fleet-change receiver writes `STALE`, so a+ batch that simply aged past its refresh window would otherwise keep reporting `fresh` (or a+ "nothing to suggest" conclusion `empty`) for as long as the planner does not reach it, which+ is forever while scheduling is off."""+ if row.status not in _EXPIRING_STATUSES or row.generated_at is None:+ return row.status+ if timezone.now() - row.generated_at >= timedelta(days=refresh_days):+ return SignalScoutSuggestionSet.Status.STALE+ return row.status+++def visible_items(+ row: SignalScoutSuggestionSet,+ *,+ enabled_skill_names: Collection[str] = (),+ reserved_names: Collection[str] = (),+) -> list[dict[str, Any]]:+ """The batch minus dismissed, already-created, and already-enabled items, in stored+ (best-first) order. Pass the project's enabled names so a scout someone turned on through the+ normal config API disappears without waiting for `mark_suggestion_created`, and its reserved+ names so a custom draft whose name was since taken (a stored skill or a disabled config, which+ Create answers with 409) is hidden too. Canonical items ignore `reserved_names` — a disabled+ canonical scout is exactly what those items offer to enable."""+ enabled = set(enabled_skill_names)+ reserved = set(reserved_names)+ return [+ record+ for record in (row.items or [])+ if isinstance(record, dict)+ and not record.get("dismissed_at")+ and not record.get("created_config_id")+ and record.get("skill_name") not in enabled+ and not (record.get("kind") == "custom" and record.get("skill_name") in reserved)+ ]+++def _update_item(team_id: int, suggestion_id: str, changes: dict[str, Any]) -> dict[str, Any] | None:+ with transaction.atomic():+ row = _lock_row(team_id, create=False)+ if row is None:+ return None+ updated: dict[str, Any] | None = None+ items = []+ for record in row.items or []:+ # A compacted tombstone keeps its id but is no longer a suggestion, so a duplicate+ # dismiss of one reads as gone rather than returning a record with no item fields.+ if isinstance(record, dict) and record.get("id") == suggestion_id and not _is_tombstone(record):+ record = {**record, **changes}+ updated = record+ items.append(record)+ if updated is None:+ return None+ row.items = items+ row.save(update_fields=["items", "updated_at"])+ return updated+++def dismiss_suggestion(team_id: int, suggestion_id: str, *, user_id: int | None) -> dict[str, Any] | None:+ return _update_item(+ team_id,+ suggestion_id,+ {"dismissed_at": timezone.now().isoformat(), "dismissed_by_id": user_id},+ )+++def mark_suggestion_created(team_id: int, suggestion_id: str, *, config_id: str) -> dict[str, Any] | None:+ return _update_item(team_id, suggestion_id, {"created_config_id": config_id})+++def mark_stale_if_fleet_changed(team_id: int) -> None:+ """Called when a scout is created or deleted: a batch generated against a different fleet is+ marked stale so the UI can say so; regeneration waits for the normal refresh."""+ with transaction.atomic():+ row = _lock_row(team_id, create=False)+ if row is None or row.status not in (+ SignalScoutSuggestionSet.Status.FRESH,+ SignalScoutSuggestionSet.Status.EMPTY,+ ):+ return+ if enabled_skill_names(team_id) != list(row.fleet_snapshot or []):+ row.status = SignalScoutSuggestionSet.Status.STALE+ row.save(update_fields=["status", "updated_at"])+++__all__ = [+ "MAX_SUGGESTIONS_PER_BATCH",+ "SIGNALS_SCOUT_SUGGESTIONS_FLAG",+ "SUGGESTIONS_ACTIVITY_SLACK_S",+ "SUGGESTIONS_AI_STAGE",+ "SUGGESTIONS_MAX_RUNTIME_S",+ "PlannedSuggestionRun",+ "ScoutSuggestionBatch",+ "ScoutSuggestionItem",+ "SuggestionSettings",+ "build_suggestions_prompt",+ "canonical_team_ids",+ "dismiss_suggestion",+ "enabled_skill_names",+ "fleet_context",+ "mark_generation_failed",+ "mark_stale_if_fleet_changed",+ "mark_suggestion_created",+ "parse_suggestion_settings",+ "persist_suggestion_batch",+ "plan_suggestion_runs",+ "read_suggestion_settings",+ "reserved_scout_names",+ "stamp_requested",+ "suggestions_allowed_for_team",+ "visible_items",+]diff --git a/products/signals/backend/scout_harness/suggestions_runner.py b/products/signals/backend/scout_harness/suggestions_runner.pynew file mode 100644index 000000000000..39c5dcc25d42--- /dev/null+++ b/products/signals/backend/scout_harness/suggestions_runner.py@@ -0,0 +1,311 @@+"""The headless run behind pre-computed scout suggestions: one team, one task, one batch.++Split from `suggestions.py` because this is the only piece that needs the tasks agent facade+(`MultiTurnSession`), which is heavy by import; the planner, contract, and persistence stay light+for the HTTP surface and the config receivers.+"""++from __future__ import annotations++import time+import asyncio+from collections.abc import Collection+from typing import Literal++import structlog+import posthoganalytics+from rest_framework import serializers++from posthog.dataclasses import frozen+from posthog.event_usage import groups+from posthog.models.team.team import Team+from posthog.sync import database_sync_to_async++from products.signals.backend.agent_runtime import STEP_SCOUT_SUGGESTIONS, resolve_agent_runtime+from products.signals.backend.quota import is_team_signals_quota_limited+from products.signals.backend.scout_harness.config_registry import (+ MAX_RUN_INTERVAL_MINUTES,+ MIN_RUN_INTERVAL_MINUTES,+ cron_schedule_error,+)+from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX+from products.signals.backend.scout_harness.suggestions import (+ MAX_DESCRIPTION_CHARS,+ MAX_DRAFT_BODY_CHARS,+ MAX_SUGGESTIONS_PER_BATCH,+ SUGGESTIONS_AI_STAGE,+ ScoutSuggestionBatch,+ ScoutSuggestionItem,+ SuggestionSettings,+ build_suggestions_prompt,+ fleet_context,+ mark_generation_failed,+ persist_suggestion_batch,+)+from products.signals.backend.temporal.agentic import (+ SIGNALS_REPORT_RESEARCH_ENV_NAME,+ get_or_create_signals_sandbox_env,+ resolve_acting_user_id_for_team,+)+from products.skills.backend.api.skill_serializers import validate_skill_name_value+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession++logger = structlog.get_logger(__name__)+++def _valid_cron(expression: str) -> bool:+ # The same rule the scout create API applies, so a stored schedule can never fail on create.+ return cron_schedule_error(expression) is None+++def _valid_custom_name(name: str) -> bool:+ if not name.startswith(SIGNALS_SCOUT_SKILL_PREFIX):+ return False+ try:+ validate_skill_name_value(name)+ except serializers.ValidationError:+ return False+ return True+++def validate_suggestion_items(+ items: list[ScoutSuggestionItem],+ *,+ enabled_skill_names: set[str],+ canonical_names: set[str],+ reserved_names: Collection[str] = (),+) -> list[ScoutSuggestionItem]:+ """Drop any item the Create action could not apply as-is: unknown canonical names, custom+ drafts with a bad slug, empty body, or a name the project already holds (a disabled config or+ a stored skill, which create answers with 409), invalid schedules, duplicates, already-enabled+ scouts. The one-click Create must never fail on a stored suggestion, so invalid ones are not+ shown."""+ seen: set[str] = set()+ kept: list[ScoutSuggestionItem] = []+ for item in items:+ name = item.skill_name.strip()+ if not name or name in seen or name in enabled_skill_names:+ continue+ if item.kind == "canonical":+ if name not in canonical_names:+ continue+ else:+ if name in canonical_names or name in reserved_names or not _valid_custom_name(name):+ continue+ if (+ not item.draft_body.strip()+ or len(item.draft_body) > MAX_DRAFT_BODY_CHARS+ or not item.description.strip()+ or len(item.description) > MAX_DESCRIPTION_CHARS+ ):+ continue+ config = item.proposed_config+ # The create serializers accept a null cron but not a blank one, so a blank normalizes.+ cron = (config.run_cron_schedule or "").strip() or None+ if cron is not None and not _valid_cron(cron):+ continue+ if config.run_interval_minutes is not None and not (+ MIN_RUN_INTERVAL_MINUTES <= config.run_interval_minutes <= MAX_RUN_INTERVAL_MINUTES+ ):+ continue+ if not item.title.strip() or not item.why_here.strip():+ continue+ seen.add(name)+ kept.append(+ item.model_copy(+ update={"skill_name": name, "proposed_config": config.model_copy(update={"run_cron_schedule": cron})}+ )+ )+ if len(kept) == MAX_SUGGESTIONS_PER_BATCH:+ break+ return kept+++@frozen+class SuggestionRunResult:+ team_id: int+ status: Literal["completed", "failed", "skipped"]+ task_run_id: str | None+ suggestion_count: int+ runtime_s: float+ skip_reason: str | None = None+++def _gate_skip_reason(team: Team) -> str | None:+ if team.organization.is_ai_data_processing_approved is not True:+ return "ai_data_processing_not_approved"+ if is_team_signals_quota_limited(team.api_token):+ return "quota_limited"+ return None+++def _capture_generated(+ team: Team, *, result: SuggestionRunResult, tier: int | None, model: str | None, triggered_by: str+) -> None:+ try:+ posthoganalytics.capture(+ event="$scout_suggestions_generated",+ distinct_id=str(team.uuid),+ properties={+ "team_id": team.id,+ "status": result.status,+ "skip_reason": result.skip_reason,+ "suggestion_count": result.suggestion_count,+ "runtime_s": round(result.runtime_s, 1),+ "task_run_id": result.task_run_id,+ "tier": tier,+ "model": model,+ "triggered_by": triggered_by,+ },+ groups=groups(team.organization, team),+ )+ except Exception:+ logger.warning("scout_suggestions: failed to capture generated event", team_id=team.id)+++async def arun_scout_suggestions(+ team_id: int,+ *,+ settings: SuggestionSettings | None = None,+ tier: int | None = None,+ triggered_by: str = "schedule",+ acting_user_id: int | None = None,+) -> SuggestionRunResult:+ """Generate one team's suggestion batch: gate, mint the headless task, validate, persist.++ Never raises for a failed generation: anything after the gates (fleet discovery, sandbox and+ runtime resolution, the run, validation, persistence) marks the row failed, feeding the+ breaker, and the result says so. This mirrors the scout runner's fail-safe posture so one+ bad project cannot take a coordinator tick down with it, and so a failure before the run+ still counts: the coordinator has already stamped the team for a full refresh window.+ """+ started = time.monotonic()+ settings = settings or SuggestionSettings()+ team = await database_sync_to_async(+ lambda: Team.objects.select_related("organization").get(id=team_id), thread_sensitive=False+ )()+ model: str | None = None++ def _finish(+ status: Literal["completed", "failed", "skipped"],+ *,+ task_run_id: str | None = None,+ suggestion_count: int = 0,+ skip_reason: str | None = None,+ ) -> SuggestionRunResult:+ result = SuggestionRunResult(+ team_id=team_id,+ status=status,+ task_run_id=task_run_id,+ suggestion_count=suggestion_count,+ runtime_s=time.monotonic() - started,+ skip_reason=skip_reason,+ )+ _capture_generated(team, result=result, tier=tier, model=model, triggered_by=triggered_by)+ return result++ skip_reason = await database_sync_to_async(_gate_skip_reason, thread_sensitive=False)(team)+ if skip_reason is not None:+ return _finish("skipped", skip_reason=skip_reason)+ # A manual refresh runs as its authenticated caller, so the batch is minted under that+ # caller's own access rather than a possibly more privileged resolved member.+ user_id = acting_user_id+ if user_id is None:+ user_id = await database_sync_to_async(resolve_acting_user_id_for_team, thread_sensitive=False)(team.id)+ if user_id is None:+ return _finish("skipped", skip_reason="no_active_user")++ task_run_id: str | None = None+ session: MultiTurnSession | None = None+ try:+ fleet = await database_sync_to_async(fleet_context, thread_sensitive=False)(team.id)+ sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(+ team.id, SIGNALS_REPORT_RESEARCH_ENV_NAME, tasks_facade.SandboxNetworkAccessLevel.TRUSTED+ )+ runtime = await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(+ team.id, STEP_SCOUT_SUGGESTIONS+ )+ model = runtime.model+ context = CustomPromptSandboxContext(+ team_id=team.id,+ user_id=user_id,+ repository=None,+ sandbox_environment_id=sandbox_env_id,+ # Reads only: the scan never writes, and `read_only` still carries `llm_skill:read` for+ # the authoring-scouts skill and `signal_scout:read` for the fleet and recent runs.+ posthog_mcp_scopes="read_only",+ # No GitHub at all: `Task._build_task` leaves this origin's `github_integration`+ # unset, so no token is minted. The scan grounds itself in project data a member can+ # write, and a repository token would let planted text pull private source into a+ # suggestion field the API hands back.+ github_read_access=False,+ model=runtime.model,+ runtime_adapter=runtime.runtime_adapter,+ reasoning_effort=runtime.reasoning_effort,+ )+ session, batch = await MultiTurnSession.start(+ prompt=build_suggestions_prompt(fleet),+ context=context,+ model=ScoutSuggestionBatch,+ step_name="scout_suggestions",+ origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT_SUGGESTIONS,+ # Not a user's task: hidden from the task tracker and never mounts personal MCP grants.+ internal=True,+ # Runs as the Scout agent with an empty server allowlist, so nothing from the MCP Store+ # is mounted; the scan needs only the PostHog MCP.+ mcp_builtin_agent_key="scout",+ mcp_gateway_server_ids=[],+ ai_stage=SUGGESTIONS_AI_STAGE,+ max_poll_seconds=settings.max_runtime_s,+ # No prose salvage: an unparseable close-out is a failed generation, since no human is+ # there to repair it and the Create action needs the structured draft.+ fallback_from_text=None,+ )+ task_run_id = str(session.task_run.id)++ canonical_names = {name for name, _ in fleet.available_canonical} | set(fleet.enabled_skill_names)+ items = validate_suggestion_items(+ batch.suggestions,+ enabled_skill_names=set(fleet.enabled_skill_names),+ canonical_names=canonical_names,+ reserved_names=fleet.reserved_names,+ )+ if batch.suggestions and not items:+ # The model produced only unusable output. Persisting that as an empty success would+ # reset the breaker and buy it a whole refresh window on the strength of nothing.+ raise ValueError(f"every suggestion in a batch of {len(batch.suggestions)} failed validation")+ await database_sync_to_async(persist_suggestion_batch, thread_sensitive=False)(+ team.id,+ items,+ task_run_id=task_run_id,+ model=runtime.model,+ fleet_snapshot=list(fleet.enabled_skill_names),+ )+ # The TaskRun closes as completed only once the batch is stored: its terminal status is+ # what run metrics and triage read, and a scan whose output never landed did fail.+ await session.end()+ except asyncio.CancelledError:+ # The activity deadline cancels the coroutine with a BaseException, which the handler+ # below would not see. The coordinator has already stamped `last_requested_at`, so an+ # unrecorded cancellation would suppress the project for a whole refresh window.+ logger.warning("scout_suggestions: generation cancelled", team_id=team.id, exc_info=True)+ await _end_failed(session, "cancelled")+ await database_sync_to_async(mark_generation_failed, thread_sensitive=False)(team.id, task_run_id=task_run_id)+ raise+ except Exception as error:+ logger.warning("scout_suggestions: generation failed", team_id=team.id, error=str(error), exc_info=True)+ await _end_failed(session, str(error))+ await database_sync_to_async(mark_generation_failed, thread_sensitive=False)(team.id, task_run_id=task_run_id)+ return _finish("failed", task_run_id=task_run_id)+ return _finish("completed", task_run_id=task_run_id, suggestion_count=len(items))+++async def _end_failed(session: MultiTurnSession | None, error: str) -> None:+ if session is None:+ return+ # Shielded so the failure status still lands when a cancel re-fires mid-signal.+ await asyncio.shield(session.end(status="failed", error=error))+++__all__ = ["SuggestionRunResult", "arun_scout_suggestions", "validate_suggestion_items"]diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.pyindex bd1e91aa8766..225588febdc6 100644--- a/products/signals/backend/scout_harness/team_limits.py+++ b/products/signals/backend/scout_harness/team_limits.py@@ -116,6 +116,22 @@ def _fallback_team_ids() -> list[int]:return list(DEFAULT_ENROLLED_TEAM_IDS) if (is_cloud() or settings.DEBUG) else []+def read_flag_payload(flag_key: str, distinct_id: str = SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID) -> dict | None:+ """Read + parse one flag's JSON payload for the synthetic discovery distinct id.++ Returns the parsed dict, or `None` when the payload is absent / not an object / unreadable; a+ read error never breaks the caller, which applies its own fallback to `None`.+ """+ try:+ payload = posthoganalytics.get_feature_flag_payload(flag_key, distinct_id, match_value=True)+ if isinstance(payload, str):+ payload = json.loads(payload)+ return payload if isinstance(payload, dict) else None+ except Exception as error:+ capture_exception(error)+ return None++def _read_flag_payload() -> dict | None:"""Read + parse the `signals-scout` flag's JSON payload once.@@ -126,16 +142,7 @@ def _read_flag_payload() -> dict | None:Enrollment and per-team configs both derive from a single call to this so they always seethe same snapshot. Mirrors `posthog/temporal/ai_observability/team_discovery.py`."""- try:- payload = posthoganalytics.get_feature_flag_payload(- SIGNALS_SCOUT_DOGFOOD_FLAG, SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID, match_value=True- )- if isinstance(payload, str):- payload = json.loads(payload)- return payload if isinstance(payload, dict) else None- except Exception as error:- capture_exception(error)- return None+ return read_flag_payload(SIGNALS_SCOUT_DOGFOOD_FLAG)# Sentinel inside `guaranteed_team_ids` that enrolls EVERY team which already has scout configs,diff --git a/products/signals/backend/scout_suggestions_api.py b/products/signals/backend/scout_suggestions_api.pynew file mode 100644index 000000000000..93515d1944e8--- /dev/null+++ b/products/signals/backend/scout_suggestions_api.py@@ -0,0 +1,267 @@+"""HTTP surface for pre-computed scout suggestions.++Read the team's "Suggested for this project" batch, dismiss one, or ask for a refresh. The batch is+produced headlessly by `scout_harness/suggestions.py` (see that module's docstring); this viewset+only reads and flags the stored JSON, so the scouts tab can render the strip without a task.+"""++from __future__ import annotations++from functools import cached_property+from typing import Any, cast++import structlog+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_serializer+from rest_framework import exceptions, serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.exceptions import Conflict+from posthog.models.user import User+from posthog.permissions import APIScopePermission+from posthog.temporal.common.client import sync_connect++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.signals.backend.models import SignalScoutSuggestionSet+from products.signals.backend.quota import is_team_signals_quota_limited+from products.signals.backend.scout_chat import consume_daily_attempt, refund_daily_attempt+from products.signals.backend.scout_harness.suggestions import (+ dismiss_suggestion,+ effective_status,+ enabled_skill_names,+ read_suggestion_settings,+ reserved_scout_names,+ suggestions_allowed_for_team,+ visible_items,+)+from products.signals.backend.scout_harness.views import ScoutCanonicalTeamAccessPermission, _canonical_team_id++logger = structlog.get_logger(__name__)++# Refreshes a team may request per day through the API. The headless scan costs real model spend,+# so the pull path is capped well below the chat button's daily budget; the scheduled producer is+# the normal refresh.+SUGGESTIONS_REFRESH_DAILY_CAP = 3+++class ScoutSuggestionProposedConfigSerializer(serializers.Serializer):+ run_cron_schedule = serializers.CharField(+ allow_null=True,+ required=False,+ help_text="Suggested five-field cron schedule in the project timezone, or null for an interval.",+ )+ run_interval_minutes = serializers.IntegerField(+ allow_null=True,+ required=False,+ help_text="Suggested minutes between runs when no cron is given; null means the daily default.",+ )+ emit = serializers.BooleanField(+ help_text="Whether the suggested scout should write to the inbox (false = dry run)."+ )+++class ScoutSuggestionItemSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="Stable id of this suggestion within the batch; use it to dismiss.")+ kind = serializers.ChoiceField(+ choices=["canonical", "custom"],+ help_text="`canonical`: enable a PostHog-authored scout that exists but is off. `custom`: create a drafted scout.",+ )+ skill_name = serializers.CharField(+ help_text="The scout's `signals-scout-*` skill name (existing for canonical, proposed for custom)."+ )+ title = serializers.CharField(help_text="Short sentence-case title: what the scout watches.")+ why_here = serializers.CharField(help_text="Project-specific evidence for this suggestion, in prose.")+ description = serializers.CharField(+ allow_blank=True, help_text="Custom only: the one-line description the scout would be created with."+ )+ draft_body = serializers.CharField(+ allow_blank=True, help_text="Custom only: the complete skill body the scout would be created with."+ )+ proposed_config = ScoutSuggestionProposedConfigSerializer(help_text="Suggested schedule and emit posture.")+ gap = serializers.BooleanField(help_text="True when nothing in the current fleet covers this.")+ confidence = serializers.ChoiceField(choices=["low", "medium", "high"], help_text="The producer's confidence.")+++# The read is the viewset's `list` action but returns one object; without this drf-spectacular+# infers a list response and the generated client types it as an array.+@extend_schema_serializer(many=False)+class ScoutSuggestionSetSerializer(serializers.Serializer):+ status = serializers.ChoiceField(+ choices=SignalScoutSuggestionSet.Status.choices,+ help_text=(+ "`fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past "+ "the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). "+ "`empty`: nothing to suggest yet."+ ),+ )+ generated_at = serializers.DateTimeField(+ allow_null=True, help_text="When the current batch was generated; null before the first run."+ )+ model = serializers.CharField(allow_blank=True, help_text="The model that produced the batch, when pinned.")+ fleet_snapshot = serializers.ListField(+ child=serializers.CharField(),+ help_text="Skill names that were enabled when the batch was generated.",+ )+ items = ScoutSuggestionItemSerializer(+ many=True, help_text="Suggestions not yet dismissed or created, best first. Up to 5."+ )+++class ScoutSuggestionRefreshSerializer(serializers.Serializer):+ workflow_id = serializers.CharField(help_text="The dispatched refresh workflow id.")+++def _set_payload(row: SignalScoutSuggestionSet | None, *, team_id: int) -> dict[str, Any]:+ if row is None:+ return {+ "status": SignalScoutSuggestionSet.Status.EMPTY,+ "generated_at": None,+ "model": "",+ "fleet_snapshot": [],+ "items": [],+ }+ return {+ "status": effective_status(row, refresh_days=read_suggestion_settings().refresh_days),+ "generated_at": row.generated_at,+ "model": row.model,+ "fleet_snapshot": list(row.fleet_snapshot or []),+ "items": visible_items(+ row,+ enabled_skill_names=enabled_skill_names(team_id),+ reserved_names=reserved_scout_names(team_id),+ ),+ }+++class SignalScoutSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """The pre-computed "Suggested for this project" scout batch: read, dismiss, refresh."""++ serializer_class = ScoutSuggestionSetSerializer+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission, ScoutCanonicalTeamAccessPermission]+ scope_object = "signal_scout"+ # An aggregate surface: suggestions are not `signal_scout` objects, so an object-specific+ # grant on one scout must not open the whole project's batch (or its paid refresh) to a+ # member whose project-level access is "none".+ requires_resource_level_access = True+ pagination_class = None+ lookup_field = "id"+ # A single row per team; `list` is the read and the row is resolved by team, never by pk.+ queryset = SignalScoutSuggestionSet.all_teams.all()++ def dangerously_get_required_scopes(self, request: Request, view) -> list[str] | None:+ if getattr(view, "action", None) in ("dismiss", "refresh"):+ return ["signal_scout:write"]+ return None++ @cached_property+ def user_access_control(self) -> UserAccessControl:+ # `AccessControlPermission` reads its resource-level check from here. Anchor it to the+ # canonical team like the membership and token-scope legs: the batch belongs to the parent+ # project, so a child environment's own `signal_scout` grant must not read it or pay for+ # its refresh when the parent grants `none`.+ team = self.team.parent_team or self.team+ return UserAccessControl(user=cast(User, self.request.user), team=team, organization_id=self.organization_id)++ @extend_schema(+ responses={200: OpenApiResponse(response=ScoutSuggestionSetSerializer, description="The current batch.")},+ summary="Get suggested scouts for this project",+ description=(+ "Return the pre-computed scout suggestions for this project: up to five picks, best first, "+ "each either a PostHog-authored scout to turn on or a drafted custom scout. Dismissed and "+ "already-created suggestions are omitted. An empty `items` with status `empty` means no "+ "batch has been generated yet; the interactive `scout-chat-tasks` path still works."+ ),+ operation_id="signals_scout_suggestions_list",+ )+ def list(self, request: Request, *args, **kwargs) -> Response:+ team_id = _canonical_team_id(self)+ row = SignalScoutSuggestionSet.objects.for_team(team_id, canonical=True).first()+ return Response(ScoutSuggestionSetSerializer(_set_payload(row, team_id=team_id)).data)++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(response=ScoutSuggestionItemSerializer, description="The dismissed suggestion."),+ 404: OpenApiResponse(description="No suggestion with that id in this project's batch."),+ },+ summary="Dismiss a suggested scout",+ description=(+ "Hide one suggestion from this project's batch. Dismissal is remembered across refreshes by "+ "skill name, so the same suggestion is not shown again."+ ),+ operation_id="signals_scout_suggestions_dismiss",+ )+ @action(detail=True, methods=["post"], url_path="dismiss")+ def dismiss(self, request: Request, id: str, *args, **kwargs) -> Response:+ record = dismiss_suggestion(_canonical_team_id(self), id, user_id=request.user.pk)+ if record is None:+ raise exceptions.NotFound()+ return Response(ScoutSuggestionItemSerializer(record).data)++ @extend_schema(+ request=None,+ responses={+ 202: OpenApiResponse(response=ScoutSuggestionRefreshSerializer, description="Refresh dispatched."),+ 403: OpenApiResponse(+ description="Organization has not approved AI data processing, or suggestions are off for this project."+ ),+ 409: OpenApiResponse(description="A refresh is already running for this project."),+ 429: OpenApiResponse(description="Daily refresh cap reached, or the project is over its Signals quota."),+ },+ summary="Refresh suggested scouts",+ description=(+ "Re-run the suggestion scan for this project now instead of waiting for the scheduled "+ "refresh. Runs headlessly; poll the list endpoint for the new batch (`generated_at` "+ "advances). Capped per project per day."+ ),+ operation_id="signals_scout_suggestions_refresh",+ )+ @action(detail=False, methods=["post"], url_path="refresh")+ def refresh(self, request: Request, *args, **kwargs) -> Response:+ team = self.team.parent_team or self.team+ if team.organization.is_ai_data_processing_approved is not True:+ raise exceptions.PermissionDenied(+ "Enable AI data processing for this organization to get scout suggestions."+ )+ if is_team_signals_quota_limited(team.api_token):+ raise exceptions.Throttled(detail="This project is over its Signals credits quota. Try again later.")+ # The same kill switch and blocklist the scheduled planner honors, so a caller with+ # `signal_scout:write` cannot pull a paid scan on a project an operator has turned off.+ if not suggestions_allowed_for_team(read_suggestion_settings(), team.id):+ raise exceptions.PermissionDenied("Scout suggestions are not enabled for this project.")++ if not consume_daily_attempt("signals_scout_suggestions_refresh", team.id, SUGGESTIONS_REFRESH_DAILY_CAP):+ raise exceptions.Throttled(+ detail="You've reached today's limit for suggestion refreshes. Try again tomorrow."+ )++ try:+ # Deferred for the same reason as the scout manual-run endpoint: keep the Signals+ # Temporal graph off the route-load path. Inside the try so an import error refunds+ # the attempt rather than spending one of the day's three on nothing.+ from products.signals.backend.temporal.agentic.scout_suggestions import ( # noqa: PLC0415+ start_manual_scout_suggestions_run,+ )++ workflow_id = start_manual_scout_suggestions_run(+ sync_connect(), team_id=team.id, acting_user_id=request.user.pk+ )+ except WorkflowAlreadyStartedError:+ # Nothing was dispatched, so the attempt goes back: retries against a running scan+ # must not spend the day's budget.+ refund_daily_attempt("signals_scout_suggestions_refresh", team.id)+ raise Conflict("A suggestion refresh is already running for this project.")+ except Exception:+ refund_daily_attempt("signals_scout_suggestions_refresh", team.id)+ raise+ logger.info("scout_suggestions: manual refresh dispatched", team_id=team.id, workflow_id=workflow_id)+ return Response(+ ScoutSuggestionRefreshSerializer({"workflow_id": workflow_id}).data,+ status=status.HTTP_202_ACCEPTED,+ )diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.pyindex 834d5e1c9172..5e0a062c14b9 100644--- a/products/signals/backend/temporal/__init__.py+++ b/products/signals/backend/temporal/__init__.py@@ -8,6 +8,13 @@ from products.signals.backend.temporal.agentic.scout_scheduler import (RunSignalsScoutWorkflow,run_signals_scout_activity,)+from products.signals.backend.temporal.agentic.scout_suggestions import (+ RunScoutSuggestionsWorkflow,+ ScoutSuggestionsCoordinatorWorkflow,+ plan_scout_suggestion_runs_activity,+ run_scout_suggestions_activity,+ stamp_requested_scout_suggestions_activity,+)from products.signals.backend.temporal.agentic.select_repository import select_repository_activityfrom products.signals.backend.temporal.backfill_error_tracking import (BackfillErrorTrackingWorkflow,@@ -92,6 +99,8 @@ WORKFLOWS = [CustomSignalAgentWorkflow,RunSignalsScoutWorkflow,SignalsScoutCoordinatorWorkflow,+ RunScoutSuggestionsWorkflow,+ ScoutSuggestionsCoordinatorWorkflow,SignalReportInboxNotificationWorkflow,]@@ -140,6 +149,9 @@ ACTIVITIES = [run_custom_signal_agent_activity,run_signal_semantic_search_activity,run_signals_scout_activity,+ plan_scout_suggestion_runs_activity,+ run_scout_suggestions_activity,+ stamp_requested_scout_suggestions_activity,report_safety_judge_activity,safety_filter_activity,select_repository_activity,diff --git a/products/signals/backend/temporal/agentic/schedule.py b/products/signals/backend/temporal/agentic/schedule.pyindex a651fc72cdaa..a9d68ad35693 100644--- a/products/signals/backend/temporal/agentic/schedule.py+++ b/products/signals/backend/temporal/agentic/schedule.py@@ -23,6 +23,12 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (COORDINATOR_INTERVAL_MINUTES,CoordinatorWorkflowInput,)+from products.signals.backend.temporal.agentic.scout_suggestions import (+ SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES,+ SUGGESTIONS_COORDINATOR_SCHEDULE_ID,+ SUGGESTIONS_COORDINATOR_WORKFLOW_NAME,+ SuggestionsCoordinatorInput,+)SIGNALS_SCOUT_COORDINATOR_SCHEDULE_ID = "signals-scout-coordinator-schedule"SIGNALS_SCOUT_COORDINATOR_WORKFLOW_NAME = "run-signals-scout-coordinator"@@ -60,3 +66,32 @@ async def create_signals_scout_coordinator_schedule(client: Client) -> None:schedule,trigger_immediately=False,)+++async def create_scout_suggestions_coordinator_schedule(client: Client) -> None:+ """Create or update the schedule driving the pre-computed scout suggestions coordinator.++ Its own schedule (not a branch of the scout coordinator) so it can be paused independently;+ the `signals-scout-suggestions` flag payload is the softer switch (`enabled: false` plans+ nothing). Same task queue and overlap posture as the scout coordinator.+ """+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ SUGGESTIONS_COORDINATOR_WORKFLOW_NAME,+ asdict(SuggestionsCoordinatorInput()),+ id=SUGGESTIONS_COORDINATOR_SCHEDULE_ID,+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ # One whole interval, like the scout coordinator: `SKIP` means an execution that never+ # ends would silently starve every later tick.+ execution_timeout=timedelta(minutes=SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES),+ ),+ spec=ScheduleSpec(+ intervals=[ScheduleIntervalSpec(every=timedelta(minutes=SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES))]+ ),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, SUGGESTIONS_COORDINATOR_SCHEDULE_ID):+ await a_update_schedule(client, SUGGESTIONS_COORDINATOR_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, SUGGESTIONS_COORDINATOR_SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/products/signals/backend/temporal/agentic/scout_suggestions.py b/products/signals/backend/temporal/agentic/scout_suggestions.pynew file mode 100644index 000000000000..ffa69a9164fb--- /dev/null+++ b/products/signals/backend/temporal/agentic/scout_suggestions.py@@ -0,0 +1,338 @@+"""Temporal producer for pre-computed scout suggestions.++Mirrors the scout coordinator pair (`scout_coordinator.py` / `scout_scheduler.py`): a+schedule-driven coordinator plans the most-overdue eligible projects, fans out one fire-and-forget+child per project with deterministic ids, and stamps `last_requested_at` only for the children it+actually dispatched; each child runs one headless suggestion scan for one team. The planning,+gating, and persistence logic lives in `scout_harness/suggestions.py` (temporalio-free); this+module is the wiring.+"""++from __future__ import annotations++import json+import asyncio+from dataclasses import asdict, dataclass+from datetime import timedelta++from django.conf import settings as django_settings+from django.db import InterfaceError, OperationalError++import structlog+from asgiref.sync import async_to_sync+from temporalio import activity, workflow+from temporalio.client import Client+from temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.sync import database_sync_to_async+from posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.utils import close_db_connections++from products.signals.backend.scout_harness.suggestions import (+ SUGGESTIONS_ACTIVITY_SLACK_S,+ SuggestionSettings,+ mark_generation_failed,+ parse_suggestion_settings,+ plan_suggestion_runs,+ read_suggestion_settings,+ stamp_requested,+)++logger = structlog.get_logger(__name__)++# Same grid as the scout coordinator so the two tick together and the per-tick cap is the only+# spend knob; the suggestion schedule is registered separately so it can be paused on its own.+SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES = 30+# How long a per-team scan may sit unclaimed on the task queue before the run is given up.+SUGGESTIONS_ACTIVITY_QUEUE_WAIT = timedelta(minutes=SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES)+SUGGESTIONS_COORDINATOR_WORKFLOW_NAME = "run-signals-scout-suggestions-coordinator"+SUGGESTIONS_COORDINATOR_SCHEDULE_ID = "signals-scout-suggestions-coordinator-schedule"+++@dataclass(frozen=True)+class PlannedSuggestion:+ team_id: int+ tier: int+++@dataclass(frozen=True)+class PlanSuggestionsInput:+ pass+++@dataclass(frozen=True)+class PlanSuggestionsOutput:+ planned: list[PlannedSuggestion]+ # The settings snapshot the plan was made under, passed to every child so one tick uses one+ # max-runtime / model posture even if the flag changes mid-fan-out.+ settings_json: str+++@dataclass(frozen=True)+class StampRequestedInput:+ team_ids: list[int]+++@dataclass(frozen=True)+class SuggestionsCoordinatorInput:+ pass+++@dataclass(frozen=True)+class SuggestionsCoordinatorOutput:+ planned_count: int+ started_count: int+ skipped_count: int+++@dataclass(frozen=True)+class RunScoutSuggestionsInput:+ team_id: int+ tier: int | None = None+ settings_json: str | None = None+ # "schedule" (coordinator) or "manual" (management command / internal endpoint).+ triggered_by: str = "schedule"+ # The authenticated user behind a manual refresh. The scan acts as this user so an+ # RBAC-restricted caller cannot pull a batch minted under a more privileged member;+ # None (scheduled and command runs) falls back to the team's resolved acting user.+ acting_user_id: int | None = None+++@dataclass(frozen=True)+class RunScoutSuggestionsOutput:+ team_id: int+ status: str+ task_run_id: str | None+ suggestion_count: int+ runtime_s: float+ skip_reason: str | None = None+++def _settings_to_json(settings: SuggestionSettings) -> str:+ data = asdict(settings)+ data["team_allowlist"] = sorted(settings.team_allowlist)+ data["team_blocklist"] = sorted(settings.team_blocklist)+ return json.dumps(data)+++def _settings_from_json(raw: str | None) -> SuggestionSettings:+ if not raw:+ return SuggestionSettings()+ return parse_suggestion_settings(json.loads(raw))+++async def plan_scout_suggestion_runs_activity(_input: PlanSuggestionsInput) -> PlanSuggestionsOutput:+ """Select the teams to refresh this tick, best first, capped by the flag payload."""+ async with Heartbeater():+ # Flag read off the DB thread pool, like the scout coordinator: the SDK call can block on+ # a cold cache and the DB pool is sized for DB-bound work.+ settings = await asyncio.to_thread(read_suggestion_settings)+ planned = await database_sync_to_async(plan_suggestion_runs, thread_sensitive=False)(settings)+ logger.info("scout_suggestions coordinator: planned", count=len(planned), enabled=settings.enabled)+ return PlanSuggestionsOutput(+ planned=[PlannedSuggestion(team_id=run.team_id, tier=run.tier) for run in planned],+ settings_json=_settings_to_json(settings),+ )+++async def stamp_requested_scout_suggestions_activity(stamp_input: StampRequestedInput) -> None:+ """Advance `last_requested_at` for the dispatched teams, so a fan-out failure re-plans them+ next tick rather than silently skipping a refresh window."""+ async with Heartbeater():+ await database_sync_to_async(stamp_requested, thread_sensitive=False)(stamp_input.team_ids)+++@close_db_connections+async def run_scout_suggestions_activity(input: RunScoutSuggestionsInput) -> RunScoutSuggestionsOutput:+ """One headless suggestion scan for one team. Never raises for a failed generation; the row+ records the failure and the result carries `status='failed'`."""+ # Deferred like the scout scheduler's runner import: the runner reaches back into this+ # package for the sandbox helpers, and `temporal/__init__.py` imports this module.+ from products.signals.backend.scout_harness.suggestions_runner import arun_scout_suggestions # noqa: PLC0415++ settings = _settings_from_json(input.settings_json)+ try:+ async with Heartbeater():+ result = await arun_scout_suggestions(+ input.team_id,+ settings=settings,+ tier=input.tier,+ triggered_by=input.triggered_by,+ acting_user_id=input.acting_user_id,+ )+ except (OperationalError, InterfaceError):+ # Transient pooled-connection drop (pgbouncer recycle / failover / deploy). The coordinator+ # has already stamped `last_requested_at`, so this has to be recorded as a failure or the+ # team is simply suppressed until its next refresh with nothing to show for the attempt.+ logger.warning("scout_suggestions activity: transient DB failure", team_id=input.team_id, exc_info=True)+ try:+ await database_sync_to_async(mark_generation_failed, thread_sensitive=False)(+ input.team_id, task_run_id=None+ )+ except Exception:+ # The connection may still be down, in which case the breaker misses this attempt.+ logger.warning(+ "scout_suggestions activity: could not record transient DB failure",+ team_id=input.team_id,+ exc_info=True,+ )+ return RunScoutSuggestionsOutput(+ team_id=input.team_id, status="failed", task_run_id=None, suggestion_count=0, runtime_s=0.0+ )+ logger.info(+ "scout_suggestions activity finished",+ team_id=input.team_id,+ status=result.status,+ suggestion_count=result.suggestion_count,+ runtime_s=result.runtime_s,+ skip_reason=result.skip_reason,+ )+ return RunScoutSuggestionsOutput(+ team_id=result.team_id,+ status=result.status,+ task_run_id=result.task_run_id,+ suggestion_count=result.suggestion_count,+ runtime_s=result.runtime_s,+ skip_reason=result.skip_reason,+ )++[email protected](name="run-scout-suggestions")+class RunScoutSuggestionsWorkflow:+ """One team's suggestion scan. The activity owns the row lifecycle; the workflow only sets the+ timeout and retry posture."""++ @workflow.run+ async def run(self, input: RunScoutSuggestionsInput) -> RunScoutSuggestionsOutput:+ settings = _settings_from_json(input.settings_json)+ run_budget = timedelta(seconds=settings.max_runtime_s + SUGGESTIONS_ACTIVITY_SLACK_S)+ return await workflow.execute_activity(+ run_scout_suggestions_activity,+ input,+ start_to_close_timeout=run_budget,+ # Bounds the queue wait too: `start_to_close` only starts once a worker picks the+ # activity up, so without this a run-now's stable id would answer 409 for as long as+ # no compatible worker exists, and scheduled runs would stack under fresh tick ids.+ schedule_to_close_timeout=run_budget + SUGGESTIONS_ACTIVITY_QUEUE_WAIT,+ heartbeat_timeout=timedelta(minutes=2),+ # No retries: a failed generation is recorded on the row and re-planned by the+ # coordinator after the breaker cooldown; a retry loop here would spend blindly.+ retry_policy=RetryPolicy(maximum_attempts=1),+ )++[email protected](name=SUGGESTIONS_COORDINATOR_WORKFLOW_NAME)+class ScoutSuggestionsCoordinatorWorkflow:+ """Plan the overdue eligible teams, fan out one abandoned child per team, stamp after dispatch.++ Child ids are deterministic per `(team, tick, idx)` with `REJECT_DUPLICATE`, so a coordinator+ retry within a tick skips instead of double-launching. `ParentClosePolicy.ABANDON` keeps the+ coordinator's lifetime to seconds regardless of fan-out size.+ """++ @staticmethod+ def parse_inputs(inputs: list[str]) -> SuggestionsCoordinatorInput:+ return SuggestionsCoordinatorInput()++ @workflow.run+ async def run(self, _input: SuggestionsCoordinatorInput) -> SuggestionsCoordinatorOutput:+ plan = await workflow.execute_activity(+ plan_scout_suggestion_runs_activity,+ PlanSuggestionsInput(),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if not plan.planned:+ return SuggestionsCoordinatorOutput(0, 0, 0)++ # `workflow_id` is per tick (the schedule appends the scheduled time) and stable across a+ # retry of the same tick, which is what makes the child ids below dedupe correctly.+ tick_id = workflow.info().workflow_id+ started = 0+ skipped = 0+ dispatched: list[int] = []+ for idx, planned in enumerate(plan.planned):+ child_id = f"scout-suggestions-run-{planned.team_id}-{tick_id}-{idx}"+ try:+ await workflow.start_child_workflow(+ RunScoutSuggestionsWorkflow.run,+ RunScoutSuggestionsInput(+ team_id=planned.team_id, tier=planned.tier, settings_json=plan.settings_json+ ),+ id=child_id,+ id_reuse_policy=WorkflowIDReusePolicy.REJECT_DUPLICATE,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ )+ started += 1+ except WorkflowAlreadyStartedError:+ skipped += 1+ dispatched.append(planned.team_id)++ await workflow.execute_activity(+ stamp_requested_scout_suggestions_activity,+ StampRequestedInput(team_ids=dispatched),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=5),+ )+ return SuggestionsCoordinatorOutput(+ planned_count=len(plan.planned), started_count=started, skipped_count=skipped+ )+++def manual_suggestions_workflow_id(team_id: int) -> str:+ """Stable per-team id for a run-now, so a second trigger while one is in flight is rejected."""+ return f"scout-suggestions-manual-run-{team_id}"+++@async_to_sync+async def start_manual_scout_suggestions_run(client: Client, *, team_id: int, acting_user_id: int | None = None) -> str:+ """Dispatch one on-demand suggestion scan for a team, bypassing the planner and its cap.++ Single-flight at the Temporal server: `ALLOW_DUPLICATE` lets the stable id be reused once the+ prior run closed, `FAIL` rejects a second trigger while one is still running (raises+ `WorkflowAlreadyStartedError` for the caller to map to a 409). A started run also stamps the+ planner state, so the coordinator treats it as this window's refresh instead of dispatching a+ second scan for the same team on its next tick.+ """+ workflow_id = manual_suggestions_workflow_id(team_id)+ settings = read_suggestion_settings()+ await client.start_workflow(+ RunScoutSuggestionsWorkflow.run,+ RunScoutSuggestionsInput(+ team_id=team_id,+ settings_json=_settings_to_json(settings),+ triggered_by="manual",+ acting_user_id=acting_user_id,+ ),+ id=workflow_id,+ task_queue=django_settings.VIDEO_EXPORT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ id_conflict_policy=WorkflowIDConflictPolicy.FAIL,+ )+ try:+ await database_sync_to_async(stamp_requested, thread_sensitive=False)([team_id])+ except Exception:+ # The scan is already running; a lost stamp costs at worst one extra scheduled scan,+ # which is cheaper than reporting a dispatched run as a failure.+ logger.warning("scout_suggestions: manual dispatch stamp failed", team_id=team_id, exc_info=True)+ return workflow_id+++__all__ = [+ "SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES",+ "SUGGESTIONS_COORDINATOR_SCHEDULE_ID",+ "SUGGESTIONS_COORDINATOR_WORKFLOW_NAME",+ "RunScoutSuggestionsInput",+ "RunScoutSuggestionsOutput",+ "RunScoutSuggestionsWorkflow",+ "ScoutSuggestionsCoordinatorWorkflow",+ "SuggestionsCoordinatorInput",+ "plan_scout_suggestion_runs_activity",+ "run_scout_suggestions_activity",+ "stamp_requested_scout_suggestions_activity",+ "start_manual_scout_suggestions_run",+]diff --git a/products/signals/backend/test/test_scout_suggestions.py b/products/signals/backend/test/test_scout_suggestions.pynew file mode 100644index 000000000000..0453a9a2a41a--- /dev/null+++ b/products/signals/backend/test/test_scout_suggestions.py@@ -0,0 +1,752 @@+import random+import asyncio+from datetime import timedelta++import pytest+from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from django.test import SimpleTestCase+from django.utils import timezone++import pytest_asyncio+from asgiref.sync import sync_to_async+from parameterized import parameterized+from rest_framework import status+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, Team, User+from posthog.models.integration import Integration+from posthog.models.scoping import team_scope+from posthog.sync import database_sync_to_async++from products.access_control.backend.models.access_control import AccessControl+from products.signals.backend.models import SignalScoutConfig, SignalScoutSuggestionSet, SignalSourceConfig+from products.signals.backend.scout_harness.suggestions import (+ ScoutSuggestionBatch,+ ScoutSuggestionItem,+ SuggestionSettings,+ dismiss_suggestion,+ mark_generation_failed,+ mark_suggestion_created,+ parse_suggestion_settings,+ persist_suggestion_batch,+ plan_suggestion_runs,+ visible_items,+)+from products.signals.backend.scout_harness.suggestions_runner import arun_scout_suggestions, validate_suggestion_items+from products.tasks.backend.models import Task++CANONICAL = {"signals-scout-general", "signals-scout-error-tracking"}+++def _item(**overrides) -> ScoutSuggestionItem:+ base = {+ "kind": "canonical",+ "skill_name": "signals-scout-error-tracking",+ "title": "Watch new error spikes",+ "why_here": "The project ingests $exception events at volume.",+ }+ return ScoutSuggestionItem(**{**base, **overrides})+++def _custom(**overrides) -> ScoutSuggestionItem:+ base = {+ "kind": "custom",+ "skill_name": "signals-scout-checkout-drop",+ "description": "Watches the checkout funnel.",+ "draft_body": "# Checkout drop\n\nCheck the checkout funnel daily.",+ }+ return _item(**{**base, **overrides})+++class TestSuggestionSettings(SimpleTestCase):+ @parameterized.expand(+ [+ ("absent", None, False, 1, 10),+ ("enabled_string_is_off", {"enabled": "true", "eligibility_tier": 3}, False, 3, 10),+ ("tier_clamped", {"enabled": True, "eligibility_tier": 99, "max_children_per_tick": -5}, True, 4, 0),+ ("tier_zero_is_allowlist_only", {"enabled": True, "eligibility_tier": 0}, True, 0, 10),+ ("tier_below_zero_clamps_to_zero", {"enabled": True, "eligibility_tier": -3}, True, 0, 10),+ ("bool_is_not_int", {"enabled": True, "max_children_per_tick": True}, True, 1, 10),+ ]+ )+ def test_malformed_payload_degrades_to_safe_defaults(self, _name, payload, enabled, tier, cap):+ settings = parse_suggestion_settings(payload)+ self.assertEqual(+ (settings.enabled, settings.eligibility_tier, settings.max_children_per_tick), (enabled, tier, cap)+ )++ def test_allowlist_ignores_non_int_entries(self):+ settings = parse_suggestion_settings({"enabled": True, "team_allowlist": [2, "3", True, 4]})+ self.assertEqual(settings.team_allowlist, frozenset({2, 4}))+++class TestValidateSuggestionItems(SimpleTestCase):+ @parameterized.expand(+ [+ ("unknown_canonical", _item(skill_name="signals-scout-nope")),+ ("already_enabled", _item(skill_name="signals-scout-general")),+ ("custom_shadows_canonical", _custom(skill_name="signals-scout-error-tracking")),+ ("custom_bad_slug", _custom(skill_name="scout-checkout")),+ ("custom_uppercase_slug", _custom(skill_name="signals-scout-Checkout")),+ ("custom_double_hyphen", _custom(skill_name="signals-scout--checkout")),+ ("six_field_cron", _item(proposed_config={"run_cron_schedule": "0 30 9 * * *"})),+ ("cron_under_30_min_gap", _item(proposed_config={"run_cron_schedule": "*/15 * * * *"})),+ ("custom_empty_body", _custom(draft_body=" ")),+ ("custom_no_description", _custom(description="")),+ ("custom_description_over_create_limit", _custom(description="x" * 4097)),+ ("bad_cron", _item(proposed_config={"run_cron_schedule": "every tuesday"})),+ # Syntactically valid but never occurs; croniter only raises on enumeration, which+ # must drop the item rather than fail the whole batch.+ ("impossible_calendar_cron", _item(proposed_config={"run_cron_schedule": "0 0 31 2 *"})),+ # Valid, hourly, and longer than the config API's column: Create would reject it.+ (+ "cron_over_create_length_limit",+ _item(+ proposed_config={+ "run_cron_schedule": f"0 {','.join(map(str, range(24)))} {','.join(map(str, range(1, 32)))} * *"+ }+ ),+ ),+ ("interval_below_floor", _item(proposed_config={"run_interval_minutes": 5})),+ ("blank_title", _item(title=" ")),+ ("custom_reuses_a_stored_skill_name", _custom(skill_name="signals-scout-disabled-custom")),+ ]+ )+ def test_drops_items_create_could_not_apply(self, _name, item):+ kept = validate_suggestion_items(+ [item],+ enabled_skill_names={"signals-scout-general"},+ canonical_names=CANONICAL,+ reserved_names={"signals-scout-disabled-custom"},+ )+ self.assertEqual(kept, [])++ def test_blank_cron_normalizes_to_none(self):+ kept = validate_suggestion_items(+ [_item(proposed_config={"run_cron_schedule": " "})], enabled_skill_names=set(), canonical_names=CANONICAL+ )+ self.assertIsNone(kept[0].proposed_config.run_cron_schedule)++ def test_keeps_valid_items_dedupes_and_caps_at_five(self):+ items = [_item(), _item(), _custom()] + [_custom(skill_name=f"signals-scout-extra-{i}") for i in range(5)]+ kept = validate_suggestion_items(items, enabled_skill_names=set(), canonical_names=CANONICAL)+ self.assertEqual(len(kept), 5)+ self.assertEqual(kept[0].skill_name, "signals-scout-error-tracking")+ self.assertEqual(kept[1].skill_name, "signals-scout-checkout-drop")+ self.assertEqual(len({item.skill_name for item in kept}), 5)+++class TestSuggestionPersistence(BaseTest):+ def test_dismissal_survives_refresh_and_created_items_are_hidden(self):+ row = persist_suggestion_batch(+ self.team.id, [_item(), _custom()], task_run_id=None, model="m", fleet_snapshot=["signals-scout-general"]+ )+ first_id, custom_id = (record["id"] for record in row.items)+ self.assertIsNotNone(dismiss_suggestion(self.team.id, first_id, user_id=self.user.id))+ self.assertIsNotNone(mark_suggestion_created(self.team.id, custom_id, config_id="cfg-1"))+ row.refresh_from_db()+ self.assertEqual(visible_items(row), [])++ row = persist_suggestion_batch(+ self.team.id, [_item(), _custom(title="Renamed")], task_run_id=None, model="m", fleet_snapshot=[]+ )+ by_name = {record["skill_name"]: record for record in row.items}+ self.assertIsNotNone(by_name["signals-scout-error-tracking"]["dismissed_at"])+ self.assertEqual(by_name["signals-scout-error-tracking"]["id"], first_id)+ self.assertEqual(by_name["signals-scout-checkout-drop"]["created_config_id"], "cfg-1")+ self.assertEqual(row.status, SignalScoutSuggestionSet.Status.FRESH)+ self.assertEqual(row.consecutive_failures, 0)++ def test_dismissal_tombstone_survives_a_batch_that_omits_it(self):+ row = persist_suggestion_batch(+ self.team.id, [_item(), _custom()], task_run_id=None, model=None, fleet_snapshot=[]+ )+ dismiss_suggestion(self.team.id, row.items[0]["id"], user_id=self.user.id)+ persist_suggestion_batch(self.team.id, [_custom()], task_run_id=None, model=None, fleet_snapshot=[])+ row = persist_suggestion_batch(+ self.team.id, [_item(), _custom()], task_run_id=None, model=None, fleet_snapshot=[]+ )+ self.assertEqual([record["skill_name"] for record in visible_items(row)], ["signals-scout-checkout-drop"])++ def test_dismissing_a_compacted_tombstone_again_is_not_found(self):+ row = persist_suggestion_batch(self.team.id, [_custom()], task_run_id=None, model=None, fleet_snapshot=[])+ suggestion_id = row.items[0]["id"]+ dismiss_suggestion(self.team.id, suggestion_id, user_id=self.user.id)+ persist_suggestion_batch(self.team.id, [_item()], task_run_id=None, model=None, fleet_snapshot=[])+ # The tombstone keeps the id but has no item fields left to serialize.+ self.assertIsNone(dismiss_suggestion(self.team.id, suggestion_id, user_id=self.user.id))++ def test_omitted_tombstone_drops_the_draft_body_it_no_longer_needs(self):+ row = persist_suggestion_batch(+ self.team.id, [_custom(draft_body="b" * 5_000)], task_run_id=None, model=None, fleet_snapshot=[]+ )+ dismiss_suggestion(self.team.id, row.items[0]["id"], user_id=self.user.id)+ row = persist_suggestion_batch(self.team.id, [_item()], task_run_id=None, model=None, fleet_snapshot=[])+ tombstone = next(record for record in row.items if record["skill_name"] == "signals-scout-checkout-drop")+ self.assertIsNotNone(tombstone["dismissed_at"])+ self.assertNotIn("draft_body", tombstone)++ def test_batch_generated_against_a_moved_fleet_is_stored_stale(self):+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-general", enabled=True)+ row = persist_suggestion_batch(self.team.id, [_item()], task_run_id=None, model=None, fleet_snapshot=[])+ self.assertEqual(row.status, SignalScoutSuggestionSet.Status.STALE)++ def test_empty_batch_generated_against_a_moved_fleet_is_stale(self):+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-general", enabled=True)+ row = persist_suggestion_batch(self.team.id, [], task_run_id=None, model=None, fleet_snapshot=[])+ self.assertEqual(row.status, SignalScoutSuggestionSet.Status.STALE)++ def test_visible_items_hides_scouts_enabled_since_generation(self):+ row = persist_suggestion_batch(+ self.team.id, [_item(), _custom()], task_run_id=None, model=None, fleet_snapshot=[]+ )+ visible = visible_items(row, enabled_skill_names={"signals-scout-error-tracking"})+ self.assertEqual([record["skill_name"] for record in visible], ["signals-scout-checkout-drop"])++ def test_failed_generation_keeps_prior_items_and_counts_toward_breaker(self):+ persist_suggestion_batch(self.team.id, [_item()], task_run_id=None, model=None, fleet_snapshot=[])+ row = mark_generation_failed(self.team.id, task_run_id=None)+ row = mark_generation_failed(self.team.id, task_run_id=None)+ self.assertEqual(row.status, SignalScoutSuggestionSet.Status.FAILED)+ self.assertEqual(row.consecutive_failures, 2)+ self.assertEqual(len(visible_items(row)), 1)++ def test_dismissing_unknown_id_is_a_noop(self):+ persist_suggestion_batch(self.team.id, [_item()], task_run_id=None, model=None, fleet_snapshot=[])+ self.assertIsNone(dismiss_suggestion(self.team.id, "nope", user_id=None))++ def test_enabling_a_scout_marks_a_fresh_batch_stale(self):+ persist_suggestion_batch(self.team.id, [_item()], task_run_id=None, model=None, fleet_snapshot=[])+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-general", enabled=True)+ row = SignalScoutSuggestionSet.all_teams.get(team=self.team)+ self.assertEqual(row.status, SignalScoutSuggestionSet.Status.STALE)+++class TestPlanSuggestionRuns(BaseTest):+ def setUp(self):+ super().setUp()+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ self.now = timezone.now()++ def _team(self, name: str, *, approved: bool = True) -> Team:+ organization = Organization.objects.create(name=name, is_ai_data_processing_approved=approved)+ return Team.objects.create(organization=organization, name=name)++ def _enable_scout(self, team: Team, *, engaged: bool) -> None:+ config = SignalScoutConfig.objects.create(team=team, skill_name="signals-scout-general", enabled=True)+ if engaged:+ config.status_changed_by = self.user+ config.save()+ else:+ # Push the touch outside the engagement window without a human attached to it.+ SignalScoutConfig.all_teams.filter(pk=config.pk).update(updated_at=self.now - timedelta(days=90))++ def test_disabled_payload_plans_nothing(self):+ self._enable_scout(self.team, engaged=True)+ self.assertEqual(plan_suggestion_runs(SuggestionSettings(enabled=False), self.now), [])++ def test_tier_one_then_never_generated_then_most_overdue(self):+ engaged_fresh = self.team+ self._enable_scout(engaged_fresh, engaged=True)+ engaged_overdue = self._team("overdue")+ self._enable_scout(engaged_overdue, engaged=True)+ quiet = self._team("quiet")+ self._enable_scout(quiet, engaged=False)+ unapproved = self._team("unapproved", approved=False)+ self._enable_scout(unapproved, engaged=True)+ self._team("no-signals-setup")++ SignalScoutSuggestionSet.all_teams.create(team=engaged_fresh, last_requested_at=self.now - timedelta(days=1))+ SignalScoutSuggestionSet.all_teams.create(team=engaged_overdue, last_requested_at=self.now - timedelta(days=30))++ planned = plan_suggestion_runs(SuggestionSettings(enabled=True, eligibility_tier=2), self.now)+ self.assertEqual([(run.team_id, run.tier) for run in planned], [(engaged_overdue.id, 1), (quiet.id, 2)])++ tier_one_only = plan_suggestion_runs(SuggestionSettings(enabled=True, eligibility_tier=1), self.now)+ self.assertEqual([run.team_id for run in tier_one_only], [engaged_overdue.id])++ def test_a_scout_a_person_created_counts_as_engagement(self):+ # Creation stamps `created_by` but no status transition, so `status_changed_by` stays+ # null; the project is still being actively managed and must not fall to tier 2.+ SignalScoutConfig.objects.create(+ team=self.team, skill_name="signals-scout-general", enabled=True, created_by=self.user+ )+ registered = self._team("coordinator-registered")+ SignalScoutConfig.objects.create(team=registered, skill_name="signals-scout-general", enabled=True)++ planned = plan_suggestion_runs(SuggestionSettings(enabled=True, eligibility_tier=2), self.now)+ self.assertEqual([(run.team_id, run.tier) for run in planned], [(self.team.id, 1), (registered.id, 2)])++ def test_cap_allowlist_blocklist_and_breaker(self):+ self._enable_scout(self.team, engaged=True)+ second = self._team("second")+ self._enable_scout(second, engaged=True)+ second_env = Team.objects.create(organization=second.organization, name="second-env", parent_team=second)+ broken = self._team("broken")+ self._enable_scout(broken, engaged=True)+ SignalScoutSuggestionSet.all_teams.create(+ team=broken,+ last_requested_at=self.now - timedelta(days=30),+ consecutive_failures=3,+ last_completed_at=self.now - timedelta(hours=1),+ )+ # Past the cooldown even though a dismissal just touched the row: the clock is the last attempt.+ recovered = self._team("recovered")+ self._enable_scout(recovered, engaged=True)+ SignalScoutSuggestionSet.all_teams.create(+ team=recovered,+ last_requested_at=self.now - timedelta(days=30),+ consecutive_failures=3,+ last_completed_at=self.now - timedelta(hours=25),+ )+ outsider = self._team("outsider")+ outsider_env = Team.objects.create(+ organization=outsider.organization, name="outsider-env", parent_team=outsider+ )++ # Flag lists name child environments; the plan lands on their canonical projects.+ planned = plan_suggestion_runs(+ SuggestionSettings(+ enabled=True,+ max_children_per_tick=3,+ team_allowlist=frozenset({outsider_env.id}),+ team_blocklist=frozenset({second_env.id}),+ ),+ self.now,+ )+ self.assertEqual([run.team_id for run in planned], [outsider.id, self.team.id, recovered.id])++ # Tier 0 drops every fleet tier: only the allowlist is planned.+ allowlist_only = plan_suggestion_runs(+ SuggestionSettings(+ enabled=True,+ eligibility_tier=0,+ max_children_per_tick=3,+ team_allowlist=frozenset({outsider_env.id}),+ ),+ self.now,+ )+ self.assertEqual([(run.team_id, run.tier) for run in allowlist_only], [(outsider.id, 0)])++ def test_breaker_backs_a_failing_project_off_past_its_refresh_window(self):+ # Both are long past the 24h cooldown and past a plain 7-day refresh, so only the+ # doubling breaker separates them.+ healthy = self._team("healthy")+ self._enable_scout(healthy, engaged=True)+ SignalScoutSuggestionSet.all_teams.create(+ team=healthy, last_requested_at=self.now - timedelta(days=8), last_completed_at=self.now - timedelta(days=8)+ )+ failing = self._team("failing")+ self._enable_scout(failing, engaged=True)+ SignalScoutSuggestionSet.all_teams.create(+ team=failing,+ last_requested_at=self.now - timedelta(days=8),+ last_completed_at=self.now - timedelta(days=8),+ consecutive_failures=3,+ )++ settings = SuggestionSettings(enabled=True)+ self.assertEqual([run.team_id for run in plan_suggestion_runs(settings, self.now)], [healthy.id])+ # Once it is overdue against the doubled window it comes back, so the breaker slows the+ # spend rather than parking the project forever.+ self.assertIn(failing.id, [run.team_id for run in plan_suggestion_runs(settings, self.now + timedelta(days=7))])++ def test_root_source_config_does_not_hide_wider_tiers(self):+ SignalSourceConfig.objects.create(team=self.team, source_product="error_tracking", source_type="issue_created")+ plain = self._team("plain")+ OrganizationMembership.objects.create(organization=plain.organization, user=self.user)+ self.user.last_login = self.now+ self.user.save()++ planned = plan_suggestion_runs(SuggestionSettings(enabled=True, eligibility_tier=3), self.now)+ self.assertIn((plain.id, 3), [(run.team_id, run.tier) for run in planned])++ def test_source_config_in_a_child_environment_makes_the_project_eligible(self):+ project = self._team("project")+ env = Team.objects.create(organization=project.organization, name="env", parent_team=project)+ SignalSourceConfig.objects.create(team=env, source_product="error_tracking", source_type="issue_created")++ planned = plan_suggestion_runs(SuggestionSettings(enabled=True, eligibility_tier=2), self.now)+ self.assertEqual([(run.team_id, run.tier) for run in planned], [(project.id, 2)])+++class TestManualSuggestionsDispatch(BaseTest):+ def test_manual_dispatch_stamps_planner_state(self):+ from products.signals.backend.temporal.agentic.scout_suggestions import start_manual_scout_suggestions_run++ client = MagicMock()+ client.start_workflow = AsyncMock()+ with patch(+ "products.signals.backend.temporal.agentic.scout_suggestions.read_suggestion_settings",+ return_value=SuggestionSettings(enabled=True),+ ):+ start_manual_scout_suggestions_run(client, team_id=self.team.id)++ client.start_workflow.assert_awaited_once()+ row = SignalScoutSuggestionSet.all_teams.get(team=self.team)+ self.assertIsNotNone(row.last_requested_at)+ settings = SuggestionSettings(enabled=True, team_allowlist=frozenset({self.team.id}))+ self.assertEqual(plan_suggestion_runs(settings, timezone.now()), [])++ def test_manual_dispatch_survives_a_failed_stamp(self):+ from products.signals.backend.temporal.agentic.scout_suggestions import start_manual_scout_suggestions_run++ client = MagicMock()+ client.start_workflow = AsyncMock()+ with (+ patch(+ "products.signals.backend.temporal.agentic.scout_suggestions.read_suggestion_settings",+ return_value=SuggestionSettings(enabled=True),+ ),+ patch(+ "products.signals.backend.temporal.agentic.scout_suggestions.stamp_requested",+ side_effect=RuntimeError("db down"),+ ),+ ):+ workflow_id = start_manual_scout_suggestions_run(client, team_id=self.team.id)+ self.assertEqual(workflow_id, f"scout-suggestions-manual-run-{self.team.id}")+++@pytest_asyncio.fixture+async def asuggestion_team():+ organization = await sync_to_async(Organization.objects.create)(+ name=f"ScoutSuggestionsOrg-{random.randint(1, 99999)}", is_ai_data_processing_approved=True+ )+ team = await sync_to_async(Team.objects.create)(+ organization=organization, name=f"ScoutSuggestionsTeam-{random.randint(1, 99999)}"+ )+ with team_scope(team.id, canonical=True):+ yield team+ await sync_to_async(team.delete)()+ await sync_to_async(organization.delete)()+++def _fake_session() -> MagicMock:+ session = MagicMock()+ session.task_run.id = "11111111-1111-1111-1111-111111111111"+ session.end = AsyncMock()+ return session+++_RUNNER = "products.signals.backend.scout_harness.suggestions_runner"+++async def test_runner_persists_validated_batch(asuggestion_team):+ batch = ScoutSuggestionBatch(suggestions=[_custom(), _item(skill_name="signals-scout-not-canonical")])+ session = _fake_session()+ with (+ patch(f"{_RUNNER}.MultiTurnSession.start", new_callable=AsyncMock, return_value=(session, batch)) as start,+ patch(f"{_RUNNER}.get_or_create_signals_sandbox_env", return_value="env"),+ patch(f"{_RUNNER}.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.scout_harness.suggestions.discover_canonical_skills", return_value=()),+ ):+ result = await arun_scout_suggestions(asuggestion_team.id, acting_user_id=7)++ assert (result.status, result.suggestion_count) == ("completed", 1)+ row = await database_sync_to_async(SignalScoutSuggestionSet.all_teams.get)(team=asuggestion_team)+ assert [record["skill_name"] for record in visible_items(row)] == ["signals-scout-checkout-drop"]+ assert str(row.task_run_id) == "11111111-1111-1111-1111-111111111111"+ assert start.call_args.kwargs["context"].posthog_mcp_scopes == "read_only"+ # The manual caller's identity wins over the resolved team member (patched to 42 above).+ assert start.call_args.kwargs["context"].user_id == 7+ assert start.call_args.kwargs["fallback_from_text"] is None+ session.end.assert_awaited_once_with()++[email protected]("failing_stage", ["unparseable_close_out", "sandbox_setup"])+async def test_runner_records_a_failure_anywhere_after_the_gates(asuggestion_team, failing_stage):+ session_error = ValueError("no json") if failing_stage == "unparseable_close_out" else None+ sandbox_error = RuntimeError("no sandbox") if failing_stage == "sandbox_setup" else None+ with (+ patch(f"{_RUNNER}.MultiTurnSession.start", new_callable=AsyncMock, side_effect=session_error),+ patch(f"{_RUNNER}.get_or_create_signals_sandbox_env", return_value="env", side_effect=sandbox_error),+ patch(f"{_RUNNER}.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.scout_harness.suggestions.discover_canonical_skills", return_value=()),+ ):+ result = await arun_scout_suggestions(asuggestion_team.id)++ assert result.status == "failed"+ row = await database_sync_to_async(SignalScoutSuggestionSet.all_teams.get)(team=asuggestion_team)+ assert (row.status, row.consecutive_failures) == (SignalScoutSuggestionSet.Status.FAILED, 1)+++async def test_runner_fails_a_batch_that_validates_down_to_nothing(asuggestion_team):+ # Every suggestion names an unknown canonical scout, so validation drops the lot. Storing that+ # as an empty success would reset the breaker and buy a whole refresh window.+ batch = ScoutSuggestionBatch(suggestions=[_item(skill_name="signals-scout-not-canonical")])+ session = _fake_session()+ with (+ patch(f"{_RUNNER}.MultiTurnSession.start", new_callable=AsyncMock, return_value=(session, batch)),+ patch(f"{_RUNNER}.get_or_create_signals_sandbox_env", return_value="env"),+ patch(f"{_RUNNER}.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.scout_harness.suggestions.discover_canonical_skills", return_value=()),+ ):+ result = await arun_scout_suggestions(asuggestion_team.id)++ assert result.status == "failed"+ row = await database_sync_to_async(SignalScoutSuggestionSet.all_teams.get)(team=asuggestion_team)+ assert (row.status, row.consecutive_failures) == (SignalScoutSuggestionSet.Status.FAILED, 1)+ # The TaskRun must not read as completed when nothing was stored: triage reads its status.+ session.end.assert_awaited_once()+ assert session.end.await_args.kwargs["status"] == "failed"+++async def test_runner_records_a_cancelled_scan_as_a_failure(asuggestion_team):+ # The activity deadline cancels with a BaseException, which the runner's `except Exception`+ # would miss; the coordinator has already stamped the request either way.+ with (+ patch(f"{_RUNNER}.MultiTurnSession.start", new_callable=AsyncMock, side_effect=asyncio.CancelledError()),+ patch(f"{_RUNNER}.get_or_create_signals_sandbox_env", return_value="env"),+ patch(f"{_RUNNER}.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.scout_harness.suggestions.discover_canonical_skills", return_value=()),+ pytest.raises(asyncio.CancelledError),+ ):+ await arun_scout_suggestions(asuggestion_team.id)++ row = await database_sync_to_async(SignalScoutSuggestionSet.all_teams.get)(team=asuggestion_team)+ assert (row.status, row.consecutive_failures) == (SignalScoutSuggestionSet.Status.FAILED, 1)+++async def test_runner_skips_unapproved_org_before_any_spend(asuggestion_team):+ organization = asuggestion_team.organization+ organization.is_ai_data_processing_approved = False+ await sync_to_async(organization.save)()+ with patch(f"{_RUNNER}.MultiTurnSession.start", new_callable=AsyncMock) as start:+ result = await arun_scout_suggestions(asuggestion_team.id)++ assert (result.status, result.skip_reason) == ("skipped", "ai_data_processing_not_approved")+ start.assert_not_called()+ assert not await database_sync_to_async(SignalScoutSuggestionSet.all_teams.filter(team=asuggestion_team).exists)()+++class TestScoutSuggestionsAPI(APIBaseTest):+ def test_list_before_first_generation_is_empty(self):+ response = self.client.get(f"/api/projects/{self.team.id}/signals/scout/suggestions/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ response.json(), {"status": "empty", "generated_at": None, "model": "", "fleet_snapshot": [], "items": []}+ )++ @parameterized.expand(+ [+ ("with_items", [_item()], SignalScoutSuggestionSet.Status.FRESH),+ ("nothing_to_suggest", [], SignalScoutSuggestionSet.Status.EMPTY),+ ]+ )+ def test_list_reports_an_aged_batch_as_stale(self, _name, items, stored_status):+ row = persist_suggestion_batch(self.team.id, items, task_run_id=None, model="m", fleet_snapshot=[])+ self.assertEqual(row.status, stored_status)+ SignalScoutSuggestionSet.all_teams.filter(pk=row.pk).update(generated_at=timezone.now() - timedelta(days=8))++ response = self.client.get(f"/api/projects/{self.team.id}/signals/scout/suggestions/")+ # Nothing writes STALE when a batch merely ages, so a fresh read has to derive it.+ self.assertEqual(response.json()["status"], "stale")++ def test_list_and_dismiss_round_trip(self):+ row = persist_suggestion_batch(+ self.team.id, [_item(), _custom()], task_run_id=None, model="m", fleet_snapshot=[]+ )+ suggestion_id = row.items[0]["id"]++ response = self.client.post(f"/api/projects/{self.team.id}/signals/scout/suggestions/{suggestion_id}/dismiss/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["skill_name"], "signals-scout-error-tracking")++ response = self.client.get(f"/api/projects/{self.team.id}/signals/scout/suggestions/")+ body = response.json()+ self.assertEqual(body["status"], "fresh")+ self.assertEqual([item["skill_name"] for item in body["items"]], ["signals-scout-checkout-drop"])+ self.assertEqual(+ body["items"][0]["proposed_config"], {"run_cron_schedule": None, "run_interval_minutes": None, "emit": True}+ )++ response = self.client.post(f"/api/projects/{self.team.id}/signals/scout/suggestions/nope/dismiss/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ @patch("products.signals.backend.temporal.agentic.scout_suggestions.start_manual_scout_suggestions_run")+ def test_refresh_requires_ai_consent(self, mock_start):+ self.organization.is_ai_data_processing_approved = None+ self.organization.save()+ response = self.client.post(f"/api/projects/{self.team.id}/signals/scout/suggestions/refresh/")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_start.assert_not_called()++ def test_list_hides_a_suggestion_whose_scout_is_now_enabled(self):+ persist_suggestion_batch(self.team.id, [_item(), _custom()], task_run_id=None, model="m", fleet_snapshot=[])+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-error-tracking", enabled=True)++ body = self.client.get(f"/api/projects/{self.team.id}/signals/scout/suggestions/").json()+ self.assertEqual(body["status"], "stale")+ self.assertEqual([item["skill_name"] for item in body["items"]], ["signals-scout-checkout-drop"])++ def test_list_hides_a_custom_draft_whose_name_was_since_taken(self):+ persist_suggestion_batch(self.team.id, [_item(), _custom()], task_run_id=None, model="m", fleet_snapshot=[])+ # A disabled config now holds the draft's name, so Create would answer 409. The canonical+ # item keeps its disabled config visible — enabling it is exactly what that item offers.+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-checkout-drop", enabled=False)+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-error-tracking", enabled=False)++ body = self.client.get(f"/api/projects/{self.team.id}/signals/scout/suggestions/").json()+ self.assertEqual([item["skill_name"] for item in body["items"]], ["signals-scout-error-tracking"])++ @patch("products.signals.backend.scout_suggestions_api.sync_connect", return_value=MagicMock())+ @patch(+ "products.signals.backend.temporal.agentic.scout_suggestions.start_manual_scout_suggestions_run",+ return_value="wf-1",+ )+ @patch(+ "products.signals.backend.scout_suggestions_api.read_suggestion_settings",+ return_value=SuggestionSettings(enabled=True),+ )+ def test_refresh_dispatches_once_approved(self, _settings, mock_start, _connect):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ response = self.client.post(f"/api/projects/{self.team.id}/signals/scout/suggestions/refresh/")+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)+ self.assertEqual(response.json(), {"workflow_id": "wf-1"})+ mock_start.assert_called_once()+ # The scan must act as the caller, not a resolved (possibly more privileged) member.+ self.assertEqual(mock_start.call_args.kwargs["acting_user_id"], self.user.pk)++ @patch("products.signals.backend.scout_suggestions_api.sync_connect", return_value=MagicMock())+ @patch("products.signals.backend.temporal.agentic.scout_suggestions.start_manual_scout_suggestions_run")+ @patch(+ "products.signals.backend.scout_suggestions_api.read_suggestion_settings",+ return_value=SuggestionSettings(enabled=True),+ )+ def test_refresh_conflicts_do_not_spend_the_daily_cap(self, _settings, mock_start, _connect):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ mock_start.side_effect = [WorkflowAlreadyStartedError("wf", "run-scout-suggestions")] * 3 + ["wf-1"]+ url = f"/api/projects/{self.team.id}/signals/scout/suggestions/refresh/"+ for _ in range(3):+ self.assertEqual(self.client.post(url).status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(self.client.post(url).status_code, status.HTTP_202_ACCEPTED)++ @parameterized.expand(+ [+ ("flag_off", lambda team_id: SuggestionSettings(enabled=False)),+ ("blocklisted", lambda team_id: SuggestionSettings(enabled=True, team_blocklist=frozenset({team_id}))),+ ]+ )+ @patch("products.signals.backend.temporal.agentic.scout_suggestions.start_manual_scout_suggestions_run")+ def test_refresh_honors_the_kill_switch_and_blocklist(self, _name, settings_for, mock_start):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ with patch(+ "products.signals.backend.scout_suggestions_api.read_suggestion_settings",+ return_value=settings_for(self.team.id),+ ):+ response = self.client.post(f"/api/projects/{self.team.id}/signals/scout/suggestions/refresh/")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_start.assert_not_called()+++class TestScoutSuggestionsResourceLevelAccess(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ persist_suggestion_batch(self.team.id, [_item()], task_run_id=None, model="m", fleet_snapshot=[])+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-general", enabled=False)+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="signal_scout",+ access_level="none",+ organization_member=membership,+ )+ # Editor on one scout clears has_any_specific_access_for_resource at both levels, so every+ # action below is turned away by requires_resource_level_access, not for a lesser reason.+ AccessControl.objects.create(+ team=self.team,+ resource="signal_scout",+ resource_id=str(config.id),+ access_level="editor",+ organization_member=membership,+ )+ self.client.force_login(member)++ @parameterized.expand([("list", "get", ""), ("dismiss", "post", "x/dismiss/"), ("refresh", "post", "refresh/")])+ def test_a_grant_on_one_scout_does_not_open_the_project_batch(self, _name, method, suffix):+ url = f"/api/projects/{self.team.id}/signals/scout/suggestions/{suffix}"+ response = self.client.get(url) if method == "get" else self.client.post(url)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)++ @parameterized.expand([("list", "get", ""), ("dismiss", "post", "x/dismiss/"), ("refresh", "post", "refresh/")])+ def test_a_child_environment_grant_does_not_open_the_parent_batch(self, _name, method, suffix):+ # The batch is the parent project's row, so RBAC on the child environment's URL must+ # answer for the parent, where this member's `signal_scout` access is `none`.+ environment = Team.objects.create(+ organization=self.organization, project=self.team.project, parent_team=self.team, name="env"+ )+ membership = OrganizationMembership.objects.get(user__email="[email protected]")+ AccessControl.objects.create(+ team=environment, resource="signal_scout", access_level="editor", organization_member=membership+ )++ url = f"/api/projects/{environment.id}/signals/scout/suggestions/{suffix}"+ response = self.client.get(url) if method == "get" else self.client.post(url)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)+++class TestSuggestionScanGitHubPosture(BaseTest):+ @parameterized.expand(+ [+ ("suggestion_scan", Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, None),+ ("scout_run", Task.OriginProduct.SIGNALS_SCOUT, "posthog/posthog"),+ ]+ )+ def test_only_a_repo_less_suggestion_scan_gets_no_github_integration(self, _name, origin_product, expected_repo):+ # `github_read_access=False` downscopes nothing on its own: it selects the read-only branch+ # in credential refresh, so leaving the integration attached hands the scan the ordinary+ # write-capable token. The scan must carry no integration at all.+ Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})++ task = Task.create_without_run(+ team=self.team,+ title="t",+ description="d",+ origin_product=origin_product,+ user_id=self.user.id,+ repository=expected_repo,+ )++ self.assertEqual(task.github_integration_id is None, expected_repo is None)++ def test_a_repo_less_suggestion_scan_never_resolves_a_personal_integration(self):+ # With no team integration, bot authorship falls back to the creator's personal GitHub+ # integration, and a repository-less lookup accepts any of them - so the resolution+ # itself must be bypassed, or the sandbox still gets a full personal token.+ with patch(+ "products.tasks.backend.temporal.process_task.utils.resolve_user_github_integration_for_task"+ ) as resolve:+ task = Task.create_without_run(+ team=self.team,+ title="t",+ description="d",+ origin_product=Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,+ user_id=self.user.id,+ repository=None,+ )++ resolve.assert_not_called()+ self.assertIsNone(task.github_user_integration_id)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 22c9d1febadf..37acf87199f5 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1979,6 +1979,10 @@ export interface SignalScoutSkillSummaryApi {readonly allowed_tools: readonly string[]}+/**+ * * `canonical` - canonical+ * * `custom` - custom+ */export type ScoutOriginEnumApi = (typeof ScoutOriginEnumApi)[keyof typeof ScoutOriginEnumApi]export const ScoutOriginEnumApi = {@@ -3885,6 +3889,106 @@ export interface ForgetResponseApi {deleted: boolean}+/**+ * * `fresh` - Fresh+ * * `stale` - Stale+ * * `failed` - Failed+ * * `empty` - Empty+ */+export type ScoutSuggestionSetStatusEnumApi =+ (typeof ScoutSuggestionSetStatusEnumApi)[keyof typeof ScoutSuggestionSetStatusEnumApi]++export const ScoutSuggestionSetStatusEnumApi = {+ Fresh: 'fresh',+ Stale: 'stale',+ Failed: 'failed',+ Empty: 'empty',+} as const++export interface ScoutSuggestionProposedConfigApi {+ /**+ * Suggested five-field cron schedule in the project timezone, or null for an interval.+ * @nullable+ */+ run_cron_schedule?: string | null+ /**+ * Suggested minutes between runs when no cron is given; null means the daily default.+ * @nullable+ */+ run_interval_minutes?: number | null+ /** Whether the suggested scout should write to the inbox (false = dry run). */+ emit: boolean+}++/**+ * * `high` - high+ * * `medium` - medium+ * * `low` - low+ */+export type ConfidenceTierEnumApi = (typeof ConfidenceTierEnumApi)[keyof typeof ConfidenceTierEnumApi]++export const ConfidenceTierEnumApi = {+ High: 'high',+ Medium: 'medium',+ Low: 'low',+} as const++export interface ScoutSuggestionItemApi {+ /** Stable id of this suggestion within the batch; use it to dismiss. */+ id: string+ /** `canonical`: enable a PostHog-authored scout that exists but is off. `custom`: create a drafted scout.+ *+ * * `canonical` - canonical+ * * `custom` - custom */+ kind: ScoutOriginEnumApi+ /** The scout's `signals-scout-*` skill name (existing for canonical, proposed for custom). */+ skill_name: string+ /** Short sentence-case title: what the scout watches. */+ title: string+ /** Project-specific evidence for this suggestion, in prose. */+ why_here: string+ /** Custom only: the one-line description the scout would be created with. */+ description: string+ /** Custom only: the complete skill body the scout would be created with. */+ draft_body: string+ /** Suggested schedule and emit posture. */+ proposed_config: ScoutSuggestionProposedConfigApi+ /** True when nothing in the current fleet covers this. */+ gap: boolean+ /** The producer's confidence.+ *+ * * `low` - low+ * * `medium` - medium+ * * `high` - high */+ confidence: ConfidenceTierEnumApi+}++export interface ScoutSuggestionSetApi {+ /** `fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). `empty`: nothing to suggest yet.+ *+ * * `fresh` - Fresh+ * * `stale` - Stale+ * * `failed` - Failed+ * * `empty` - Empty */+ status: ScoutSuggestionSetStatusEnumApi+ /**+ * When the current batch was generated; null before the first run.+ * @nullable+ */+ generated_at: string | null+ /** The model that produced the batch, when pinned. */+ model: string+ /** Skill names that were enabled when the batch was generated. */+ fleet_snapshot: string[]+ /** Suggestions not yet dismissed or created, best first. Up to 5. */+ items: ScoutSuggestionItemApi[]+}++export interface ScoutSuggestionRefreshApi {+ /** The dispatched refresh workflow id. */+ workflow_id: string+}+/*** * `session_replay` - Session replay* * `llm_analytics` - LLM analyticsdiff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 398f5753f6a9..2e019aa182cd 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -49,6 +49,9 @@ import type {ScoutNoteApi,ScoutNoteCreateRequestApi,ScoutRunIdsBatchRequestApi,+ ScoutSuggestionItemApi,+ ScoutSuggestionRefreshApi,+ ScoutSuggestionSetApi,ScratchpadEntryApi,SignalReportApi,SignalReportArtefactApi,@@ -1426,6 +1429,61 @@ export const signalsScoutScratchpadForget = async (})}+export const getSignalsScoutSuggestionsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/suggestions/`+}++/**+ * Return the pre-computed scout suggestions for this project: up to five picks, best first, each either a PostHog-authored scout to turn on or a drafted custom scout. Dismissed and already-created suggestions are omitted. An empty `items` with status `empty` means no batch has been generated yet; the interactive `scout-chat-tasks` path still works.+ * @summary Get suggested scouts for this project+ */+export const signalsScoutSuggestionsList = async (+ projectId: string,+ options?: RequestInit+): Promise<ScoutSuggestionSetApi> => {+ return apiMutator<ScoutSuggestionSetApi>(getSignalsScoutSuggestionsListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getSignalsScoutSuggestionsDismissUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/scout/suggestions/${id}/dismiss/`+}++/**+ * Hide one suggestion from this project's batch. Dismissal is remembered across refreshes by skill name, so the same suggestion is not shown again.+ * @summary Dismiss a suggested scout+ */+export const signalsScoutSuggestionsDismiss = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ScoutSuggestionItemApi> => {+ return apiMutator<ScoutSuggestionItemApi>(getSignalsScoutSuggestionsDismissUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getSignalsScoutSuggestionsRefreshUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/suggestions/refresh/`+}++/**+ * Re-run the suggestion scan for this project now instead of waiting for the scheduled refresh. Runs headlessly; poll the list endpoint for the new batch (`generated_at` advances). Capped per project per day.+ * @summary Refresh suggested scouts+ */+export const signalsScoutSuggestionsRefresh = async (+ projectId: string,+ options?: RequestInit+): Promise<ScoutSuggestionRefreshApi> => {+ return apiMutator<ScoutSuggestionRefreshApi>(getSignalsScoutSuggestionsRefreshUrl(projectId), {+ ...options,+ method: 'POST',+ })+}+export const getSignalsSourceConfigsListUrl = (projectId: string, params?: SignalsSourceConfigsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex d54cf3658b35..678eeea5dc87 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -1161,6 +1161,15 @@ tools:description:'DEPRECATED: renamed to scout-scratchpad-search. This alias forwards to the same endpoint and will beremoved. Call scout-scratchpad-search directly with the same arguments.'+ signals-scout-suggestions-dismiss:+ operation: signals_scout_suggestions_dismiss+ enabled: false+ signals-scout-suggestions-list:+ operation: signals_scout_suggestions_list+ enabled: false+ signals-scout-suggestions-refresh:+ operation: signals_scout_suggestions_refresh+ enabled: falseusers-signal-autonomy-create:operation: users_signal_autonomy_createenabled: falsediff --git a/products/signals/skills/signals-scout-tasks/SKILL.md b/products/signals/skills/signals-scout-tasks/SKILL.mdindex d0e7b2b999b5..9d35e584cad1 100644--- a/products/signals/skills/signals-scout-tasks/SKILL.md+++ b/products/signals/skills/signals-scout-tasks/SKILL.md@@ -75,8 +75,8 @@ It encodes the exclusions below.## The exclusion that matters most-**Always exclude `origin_product = 'signals_scout'`.**-Those rows are the scout fleet's own run containers, not project work: they carry no repository and a single creator, and on an active project they can be the _largest_ origin by volume.+**Always exclude `origin_product` in (`signals_scout`, `scout_suggestions`).**+Those rows are the scout fleet's own run containers, the second being the scans that pre-compute a project's suggested scouts, not project work: they carry no repository and a single creator, and on an active project they can be the _largest_ origin by volume.They are not filtered out for you — the `internal` flag does not cover them.A run that forgets this exclusion is mostly measuring the scout fleet, and the demand lens would be reading the inbox's own output back as if it were user demand.@@ -84,7 +84,7 @@ A run that forgets this exclusion is mostly measuring the scout fleet, and the dClose out on **runs, not task creation**.A project that creates no new tasks can still be running old ones daily, and those runs are exactly what lens A exists to watch — closing out on a task-creation count would skip today's failures entirely.-So: if a 14-day count of non-`signals_scout` _runs_ is ~0, this project isn't using Tasks.+So: if a 14-day count of _runs_ outside those two origins is ~0, this project isn't using Tasks.Write one scratchpad entry and stop:- key `not-in-use:tasks` — _"checked {timestamp}, no non-scout task runs in 14d"_@@ -113,14 +113,14 @@ Both read the same tables and ask different questions.| Lens | Cadence | Origins | Unit | Question || ----------------------- | ---------------------------------------------- | ------------------------------------------------------------ | -------- | ------------------------------- |-| **A — delivery health** | every run | non-internal, all except `signals_scout` | the run | does agent work actually land? |+| **A — delivery health** | every run | non-internal, all except the fleet's own origins | the run | does agent work actually land? || **B — demand** | when `pattern:tasks:last-demand-pass` > 7d old | human only: `user_created`, `slack`, `posthog_ai`, `hogdesk` | the task | what do people keep asking for? |`onboarding` is deliberately absent: those tasks are generated server-side with a fixed title and a templated prompt, and only _attributed_ to the user who onboarded.Several of them clear the distinct-creator repetition test on their own and would manufacture a demand theme out of product-generated work.Lens B's origin filter is load-bearing, not tidiness.-Machine origins (`signal_report`, `review_hog`, `loops`, `automation`, and the excluded `signals_scout`) are work the platform generated for itself.+Machine origins (`signal_report`, `review_hog`, `loops`, `automation`, and the excluded `signals_scout` and `scout_suggestions`) are work the platform generated for itself.Counting them as demand manufactures a trend out of the inbox's own throughput.Read them in lens A, where "did it land" is exactly the right question for them, and never in lens B.@@ -228,7 +228,7 @@ Author / edit / remember / skip, against the four-states classifier:## Disqualifiers (skip these)-- **The scout fleet's own rows** — `origin_product = 'signals_scout'`, always excluded, both lenses.+- **The scout fleet's own rows** — `origin_product` in (`signals_scout`, `scout_suggestions`), always excluded, both lenses.- **Low absolute volume** — below this project's floor, a rate is noise.A handful of runs failing proves nothing.- **Retry storms read as systemic** — always compute runs ÷ distinct tasks before believing a big number.diff --git a/products/signals/skills/signals-scout-tasks/references/queries.md b/products/signals/skills/signals-scout-tasks/references/queries.mdindex 0d5ac4354adb..673afdb2351d 100644--- a/products/signals/skills/signals-scout-tasks/references/queries.md+++ b/products/signals/skills/signals-scout-tasks/references/queries.md@@ -3,7 +3,7 @@All queries run via `execute-sql` over the `system.tasks` and `system.task_runs` Postgres system tables.Conventions used throughout:-- **Always exclude the scout fleet's own rows**: `t.origin_product != 'signals_scout'`.+- **Always exclude the scout fleet's own rows**: `t.origin_product NOT IN ('signals_scout', 'scout_suggestions')` (scout runs, and the scans that pre-compute suggested scouts).Those are the harness's run containers, not project work — no repository, one creator, and on an active project they can outnumber every real origin combined.The `internal` flag does **not** exclude them.- **Join on `r.task_id = t.id`.**@@ -55,7 +55,7 @@ SELECTFROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.idWHERE r.created_at > now() - interval 14 day- AND t.origin_product != 'signals_scout'+ AND t.origin_product NOT IN ('signals_scout', 'scout_suggestions')GROUP BY originORDER BY runs DESC```@@ -77,7 +77,7 @@ SELECTFROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.idWHERE r.created_at > now() - interval 14 day- AND t.origin_product != 'signals_scout'+ AND t.origin_product NOT IN ('signals_scout', 'scout_suggestions')GROUP BY originORDER BY runs DESC```@@ -107,7 +107,7 @@ SELECTFROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.idWHERE r.created_at > now() - interval 14 day- AND t.origin_product != 'signals_scout'+ AND t.origin_product NOT IN ('signals_scout', 'scout_suggestions')-- Repo-less tasks are unrelated work that would group into one synthetic "repository";-- that cluster can trip the total-failure exception with no shared repo behind it.-- Query 3 owns cross-task failure classes that have no repository.@@ -156,7 +156,7 @@ SELECTFROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.idWHERE r.created_at > now() - interval 14 day- AND t.origin_product != 'signals_scout'+ AND t.origin_product NOT IN ('signals_scout', 'scout_suggestions')AND r.status = 'failed'AND isNotNull(r.error_message)-- Project-wide by default. When query 2 named a candidate repository, re-run this@@ -198,7 +198,7 @@ SELECTFROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.idWHERE r.created_at > now() - interval 14 day- AND t.origin_product != 'signals_scout'+ AND t.origin_product NOT IN ('signals_scout', 'scout_suggestions')AND r.status = 'failed'AND isNotNull(r.error_message)-- Substitute the integer from query 3's err_fingerprint column (digits only):@@ -226,7 +226,7 @@ SELECTFROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.idWHERE r.created_at > now() - interval 14 day- AND t.origin_product != 'signals_scout'+ AND t.origin_product NOT IN ('signals_scout', 'scout_suggestions')GROUP BY repoHAVING runs > 20-- Rate first: the guard above already handles volume, and a busy healthy repo would@@ -254,7 +254,7 @@ FROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.idWHERE r.status IN ('not_started', 'queued', 'in_progress')AND r.created_at < now() - interval 1 day- AND t.origin_product != 'signals_scout'+ AND t.origin_product NOT IN ('signals_scout', 'scout_suggestions')-- `Task.soft_delete()` does not transition its runs, so without this a deleted task's-- stuck run stays "backlog" forever. This scan is unbounded, so that false finding never ages out.AND t.deleted = 0@@ -353,7 +353,7 @@ SELECTr.created_at AS run_created_atFROM system.task_runs AS rJOIN system.tasks AS t ON r.task_id = t.id-WHERE t.origin_product != 'signals_scout'+WHERE t.origin_product NOT IN ('signals_scout', 'scout_suggestions')AND t.deleted = 0-- Failure clusters: keep both lines as written.-- Backlog clusters (query 5b): swap the status list fordiff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 8090f734c629..05606b740cc2 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -93,8 +93,9 @@ SELF_DRIVING_ORIGIN_PRODUCTS: frozenset[str] = frozenset({# Signals report research + repo selection"signal_report",- # Headless Signals scouts+ # Headless Signals scouts, and the headless scan that pre-computes scout suggestions"signals_scout",+ "scout_suggestions",# ReviewHog's per-chunk review, blind-spot, and validation sandboxes"review_hog",}diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex fc84baa8ed44..167b7e4a2561 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -68,6 +68,7 @@ TASK_OWNERSHIP_VERSION_STATE_KEY = "task_ownership_version"MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN: dict[str, MCPBuiltInAgentKey] = {"support_reply": "support","signals_scout": "scout",+ "scout_suggestions": "scout",}@@ -302,6 +303,10 @@ class Task(DeletedMetaFields, models.Model):SIGNAL_REPORT = "signal_report", "Signal Report"# Headless Signals scout — proactively explores a project and emits signals.SIGNALS_SCOUT = "signals_scout", "Signals Scout"+ # Headless scan that pre-computes the "Suggested for this project" scout batch+ # (products/signals/backend/scout_harness/suggestions.py). Reserved: the origin is what+ # routes the run to the Signals OAuth app and its read-only posture.+ SIGNALS_SCOUT_SUGGESTIONS = "scout_suggestions", "Signals Scout Suggestions"# Conversations support reply pipeline — autonomous grounded draft replies.SUPPORT_REPLY = "support_reply", "Support Reply"# HogDesk — the internal support desk client. Tasks it creates from a@@ -848,8 +853,16 @@ class Task(DeletedMetaFields, models.Model):user_github_integration_is_usable,)+ # A repo-less signals task must carry no GitHub credential at all — team or personal.+ # Provisioning injects whatever integration is attached, and these runs read text any+ # member can write, so an attached token turns planted text into repository access.+ github_resolution_allowed = bool(repository) or origin_product not in (+ Task.OriginProduct.SIGNALS_CHAT,+ Task.OriginProduct.SIGNAL_REPORT,+ Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,+ )github_integration = None- if repository or origin_product not in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):+ if github_resolution_allowed:github_integration = (Integration.objects.filter(team=team, kind="github").exclude(errors=ERROR_TOKEN_REFRESH_FAILED)@@ -872,7 +885,9 @@ class Task(DeletedMetaFields, models.Model):if origin_product == Task.OriginProduct.SIGNAL_REPORTelse None,)- if authorship_mode == PrAuthorshipMode.USER:+ if not github_resolution_allowed:+ pass+ elif authorship_mode == PrAuthorshipMode.USER:user_github_integration = resolve_user_github_integration_for_task(task_stub,repository=repository,diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 401175cac569..01e3cb8f245d 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -814,6 +814,7 @@ class TaskWriteSerializer(serializers.Serializer):tasks_facade.TaskOriginProduct.IMAGE_BUILDER,tasks_facade.TaskOriginProduct.EXPERIMENTS,tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,+ tasks_facade.TaskOriginProduct.SIGNALS_SCOUT_SUGGESTIONS,tasks_facade.TaskOriginProduct.SUPPORT_REPLY,# Routes the run's LLM traffic to the unbilled `onboarding` gateway product, so a# forged origin would be free model access. Only create_wizard_cloud_run sets it,diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex 927d33e506de..43ac00b9f558 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -414,6 +414,9 @@ def _resolve_mcp_scopes(task_run: TaskRun) -> PosthogMcpScopes:if task_run.task.origin_product == Task.OriginProduct.SIGNALS_SCOUT:return "signals_scout_reports"+ # The suggestion scan only reads; a reconciled run must not inherit the generic full posture.+ if task_run.task.origin_product == Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS:+ return "read_only"# Loop-fired runs persist their real scopes in pending_dispatch; a row missing it must# degrade to read_only, never escalate to the full write surface the generic fallbackdiff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex f45dd7d5ec1b..e0518b27c632 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -54,6 +54,7 @@ SIGNALS_ORIGIN_PRODUCTS = frozenset({Task.OriginProduct.SIGNAL_REPORT,Task.OriginProduct.SIGNALS_SCOUT,+ Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,Task.OriginProduct.SIGNALS_CHAT,})@@ -150,6 +151,7 @@ def create_oauth_access_token(}if task.origin_product in {Task.OriginProduct.SIGNALS_SCOUT,+ Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,Task.OriginProduct.SUPPORT_REPLY,} and is_builtin_agent_enforcement_enabled(task.team_id):# This scope only removes access to the human MCP Store surface. Add itdiff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex 1cdc5a541f91..677769f8ea64 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -33,6 +33,7 @@ _ORIGIN_TO_GATEWAY_PRODUCT: dict[str, str] = {"loop": "posthog_code","onboarding": "onboarding","posthog_ai": "posthog_ai",+ "scout_suggestions": "signals","signal_report": "signals","signals_scout": "signals","slack": "slack_app",diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.pyindex 4b33e0717ed4..a66234e501be 100644--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py@@ -22,6 +22,7 @@ class TestResolveSandboxAiProduct:[("signals_scout", "scout", "signals_scout"),("signals_scout", "scout:web-analytics", "signals_scout"),+ ("scout_suggestions", "scout_suggestions", "signals"),("signal_report", "research", "signals_research"),("signal_report", "implementation", "signals_implementation"),("signal_report", "repo_selection", "signals_repo_selection"),diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 7f78a6b3edee..c5a30d264fa0 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1760,6 +1760,7 @@ export interface PaginatedTaskDetailDTOListApi {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -1784,6 +1785,7 @@ export const OriginProductEnumApi = {Experiments: 'experiments',SignalReport: 'signal_report',SignalsScout: 'signals_scout',+ ScoutSuggestions: 'scout_suggestions',SupportReply: 'support_reply',Hogdesk: 'hogdesk',ReviewHog: 'review_hog',@@ -1847,6 +1849,7 @@ export interface TaskCreateApi {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -2002,6 +2005,7 @@ export interface TaskWriteApi {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -2140,6 +2144,7 @@ export interface PatchedTaskWriteApi {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -4950,6 +4955,7 @@ export type TasksListParams = {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -5082,6 +5088,7 @@ export const TasksListExcludeOriginProduct = {Experiments: 'experiments',SignalReport: 'signal_report',SignalsScout: 'signals_scout',+ ScoutSuggestions: 'scout_suggestions',SupportReply: 'support_reply',Hogdesk: 'hogdesk',ReviewHog: 'review_hog',diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 4373fa67d822..26cd9a0e3e26 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1168,6 +1168,7 @@ export const TasksCreateBody = /* @__PURE__ */ zod'experiments','signal_report','signals_scout',+ 'scout_suggestions','support_reply','hogdesk','review_hog',@@ -1179,11 +1180,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod'workflow',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'),repository: zod.string()@@ -1349,6 +1350,7 @@ export const TasksUpdateBody = /* @__PURE__ */ zod'experiments','signal_report','signals_scout',+ 'scout_suggestions','support_reply','hogdesk','review_hog',@@ -1360,11 +1362,11 @@ export const TasksUpdateBody = /* @__PURE__ */ zod'workflow',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'),repository: zod.string()@@ -1509,6 +1511,7 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod'experiments','signal_report','signals_scout',+ 'scout_suggestions','support_reply','hogdesk','review_hog',@@ -1520,11 +1523,11 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod'workflow',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'),repository: zod.string()diff --git a/pyproject.toml b/pyproject.tomlindex 43de9d5c9d22..9ec3690f9f0b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -762,6 +762,7 @@ ignore_imports = ["products.signals.backend.routes -> products.signals.backend.views","products.signals.backend.routes -> products.signals.backend.scout_chat","products.signals.backend.routes -> products.signals.backend.scout_harness.views",+ "products.signals.backend.routes -> products.signals.backend.scout_suggestions_api","products.skills.backend.routes -> products.skills.backend.api.community_skills","products.skills.backend.routes -> products.skills.backend.api.marketplace_views","products.skills.backend.routes -> products.skills.backend.api.skills",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7034fc3d1f31..487ac433be8e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18676,6 +18676,20 @@ export namespace Schemas {Inferred: 'inferred',} as const;+ /**+ * * `high` - high+ * * `medium` - medium+ * * `low` - low+ */+ export type ConfidenceTierEnum = typeof ConfidenceTierEnum[keyof typeof ConfidenceTierEnum];+++ export const ConfidenceTierEnum = {+ High: 'high',+ Medium: 'medium',+ Low: 'low',+ } as const;+/*** * `boolean` - boolean* * `number` - number@@ -45600,20 +45614,6 @@ export namespace Schemas {detail: string;}- /**- * * `high` - high- * * `medium` - medium- * * `low` - low- */- export type IdentityMatchingLinkTierEnum = typeof IdentityMatchingLinkTierEnum[keyof typeof IdentityMatchingLinkTierEnum];--- export const IdentityMatchingLinkTierEnum = {- High: 'high',- Medium: 'medium',- Low: 'low',- } as const;-/*** The resolved person behind one side of a link, with a curated set of properties that mirror* the match signals (geo, device, campaign) so a reviewer can judge whether the link is plausible.@@ -45716,7 +45716,7 @@ export namespace Schemas {* * `high` - high* * `medium` - medium* * `low` - low */- tier: IdentityMatchingLinkTierEnum;+ tier: ConfidenceTierEnum;/** When the link was computed (UTC). */computed_at: string;/** Distinct (IP, day) combinations both sides were seen on. */@@ -53263,6 +53263,7 @@ export namespace Schemas {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -53288,6 +53289,7 @@ export namespace Schemas {Experiments: 'experiments',SignalReport: 'signal_report',SignalsScout: 'signals_scout',+ ScoutSuggestions: 'scout_suggestions',SupportReply: 'support_reply',Hogdesk: 'hogdesk',ReviewHog: 'review_hog',@@ -67078,6 +67080,7 @@ export namespace Schemas {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -76054,6 +76057,10 @@ export namespace Schemas {config?: SignalScoutConfigOptions;}+ /**+ * * `canonical` - canonical+ * * `custom` - custom+ */export type ScoutOriginEnum = typeof ScoutOriginEnum[keyof typeof ScoutOriginEnum];@@ -76453,6 +76460,93 @@ export namespace Schemas {run_ids: string[];}+ export interface ScoutSuggestionProposedConfig {+ /**+ * Suggested five-field cron schedule in the project timezone, or null for an interval.+ * @nullable+ */+ run_cron_schedule?: string | null;+ /**+ * Suggested minutes between runs when no cron is given; null means the daily default.+ * @nullable+ */+ run_interval_minutes?: number | null;+ /** Whether the suggested scout should write to the inbox (false = dry run). */+ emit: boolean;+ }++ export interface ScoutSuggestionItem {+ /** Stable id of this suggestion within the batch; use it to dismiss. */+ id: string;+ /** `canonical`: enable a PostHog-authored scout that exists but is off. `custom`: create a drafted scout.+ *+ * * `canonical` - canonical+ * * `custom` - custom */+ kind: ScoutOriginEnum;+ /** The scout's `signals-scout-*` skill name (existing for canonical, proposed for custom). */+ skill_name: string;+ /** Short sentence-case title: what the scout watches. */+ title: string;+ /** Project-specific evidence for this suggestion, in prose. */+ why_here: string;+ /** Custom only: the one-line description the scout would be created with. */+ description: string;+ /** Custom only: the complete skill body the scout would be created with. */+ draft_body: string;+ /** Suggested schedule and emit posture. */+ proposed_config: ScoutSuggestionProposedConfig;+ /** True when nothing in the current fleet covers this. */+ gap: boolean;+ /** The producer's confidence.+ *+ * * `low` - low+ * * `medium` - medium+ * * `high` - high */+ confidence: ConfidenceTierEnum;+ }++ export interface ScoutSuggestionRefresh {+ /** The dispatched refresh workflow id. */+ workflow_id: string;+ }++ /**+ * * `fresh` - Fresh+ * * `stale` - Stale+ * * `failed` - Failed+ * * `empty` - Empty+ */+ export type ScoutSuggestionSetStatusEnum = typeof ScoutSuggestionSetStatusEnum[keyof typeof ScoutSuggestionSetStatusEnum];+++ export const ScoutSuggestionSetStatusEnum = {+ Fresh: 'fresh',+ Stale: 'stale',+ Failed: 'failed',+ Empty: 'empty',+ } as const;++ export interface ScoutSuggestionSet {+ /** `fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). `empty`: nothing to suggest yet.+ *+ * * `fresh` - Fresh+ * * `stale` - Stale+ * * `failed` - Failed+ * * `empty` - Empty */+ status: ScoutSuggestionSetStatusEnum;+ /**+ * When the current batch was generated; null before the first run.+ * @nullable+ */+ generated_at: string | null;+ /** The model that produced the batch, when pinned. */+ model: string;+ /** Skill names that were enabled when the batch was generated. */+ fleet_snapshot: string[];+ /** Suggestions not yet dismissed or created, best first. Up to 5. */+ items: ScoutSuggestionItem[];+ }+/*** `SignalScratchpad` projection used by `search-memory` and `remember`.*/@@ -83548,6 +83642,7 @@ export namespace Schemas {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -84947,6 +85042,7 @@ export namespace Schemas {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -98952,6 +99048,7 @@ export namespace Schemas {* * `experiments` - Experiments* * `signal_report` - Signal Report* * `signals_scout` - Signals Scout+ * * `scout_suggestions` - Signals Scout Suggestions* * `support_reply` - Support Reply* * `hogdesk` - HogDesk* * `review_hog` - ReviewHog@@ -99086,6 +99183,7 @@ export namespace Schemas {Experiments: 'experiments',SignalReport: 'signal_report',SignalsScout: 'signals_scout',+ ScoutSuggestions: 'scout_suggestions',SupportReply: 'support_reply',Hogdesk: 'hogdesk',ReviewHog: 'review_hog',diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex bfc488c17420..198da33e0a31 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -901,6 +901,7 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({'experiments','signal_report','signals_scout',+ 'scout_suggestions','support_reply','hogdesk','review_hog',@@ -913,7 +914,7 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({]).optional().describe(- 'Exclude tasks with this origin product from the results\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ 'Exclude tasks with this origin product from the results\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'),hog_flow_id: zod.string()@@ -1021,6 +1022,7 @@ export const TasksCreateBody = /* @__PURE__ */ zod'experiments','signal_report','signals_scout',+ 'scout_suggestions','support_reply','hogdesk','review_hog',@@ -1032,11 +1034,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod'workflow',]).describe(- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow').optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'),repository: zod.string()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.jsonindex ca49672fb278..713046bb92f5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json@@ -29,7 +29,7 @@"type": "number"},"exclude_origin_product": {- "description": "Exclude tasks with this origin product from the results\n\n* `onboarding` - Onboarding\n* `error_tracking` - Error Tracking\n* `eval_clusters` - Eval Clusters\n* `user_created` - User Created\n* `slack` - Slack\n* `support_queue` - Support Queue\n* `session_summaries` - Session Summaries\n* `posthog_ai` - PostHog AI\n* `experiments` - Experiments\n* `signal_report` - Signal Report\n* `signals_scout` - Signals Scout\n* `support_reply` - Support Reply\n* `hogdesk` - HogDesk\n* `review_hog` - ReviewHog\n* `image_builder` - Image Builder\n* `loop` - Loop\n* `mcp_analytics` - MCP Analytics\n* `signals_chat` - Signals Chat\n* `task_analysis` - Task Analysis\n* `workflow` - Workflow",+ "description": "Exclude tasks with this origin product from the results\n\n* `onboarding` - Onboarding\n* `error_tracking` - Error Tracking\n* `eval_clusters` - Eval Clusters\n* `user_created` - User Created\n* `slack` - Slack\n* `support_queue` - Support Queue\n* `session_summaries` - Session Summaries\n* `posthog_ai` - PostHog AI\n* `experiments` - Experiments\n* `signal_report` - Signal Report\n* `signals_scout` - Signals Scout\n* `scout_suggestions` - Signals Scout Suggestions\n* `support_reply` - Support Reply\n* `hogdesk` - HogDesk\n* `review_hog` - ReviewHog\n* `image_builder` - Image Builder\n* `loop` - Loop\n* `mcp_analytics` - MCP Analytics\n* `signals_chat` - Signals Chat\n* `task_analysis` - Task Analysis\n* `workflow` - Workflow","enum": ["onboarding","error_tracking",@@ -42,6 +42,7 @@"experiments","signal_report","signals_scout",+ "scout_suggestions","support_reply","hogdesk","review_hog",