Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): expose scout pre-check config and a dry-run test endpoint (#114364)

posthog[bot]ff49b7213dce
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index ef114896ebf1..e8de503abff1 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -1927,6 +1927,12 @@ export interface SignalScoutConfigOptionsApi {
* * `read_only` - Read only
* * `support_notes` - Support notes */
tool_preset?: ToolPresetEnumApi
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null
/** Whether this scout runs on its schedule. Defaults to true. */
enabled?: boolean
/** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
@@ -2190,6 +2196,11 @@ export interface SignalScoutConfigApi {
* @nullable
*/
readonly tool_preset: string | null
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @nullable
+ */
+ readonly precheck_query: string | null
/**
* When the coordinator last dispatched this scout. Null if it has never run.
* @nullable
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 0e52fa144b37..93d2937c28d5 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -947,6 +947,8 @@ export const visionScannersScoutsCreateBodyConfigOneRepositoriesMax = 10
export const visionScannersScoutsCreateBodyConfigOneWriteScopesMax = 10
+export const visionScannersScoutsCreateBodyConfigOnePrecheckQueryMax = 10000
+
export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMin = 30
export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMax = 43200
@@ -1045,6 +1047,13 @@ export const VisionScannersScoutsCreateBody = /* @__PURE__ */ zod
.describe(
'Expand this named preset into a saved tool list. Later preset changes do not alter the saved list. Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag.\n\n\* `read_only` - Read only\n\* `support_notes` - Support notes'
),
+ precheck_query: zod
+ .string()
+ .max(visionScannersScoutsCreateBodyConfigOnePrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
enabled: zod
.boolean()
.optional()
diff --git a/products/signals/backend/scout_harness/precheck.py b/products/signals/backend/scout_harness/precheck.py
index c449ccd4430c..a85c32def9bf 100644
--- a/products/signals/backend/scout_harness/precheck.py
+++ b/products/signals/backend/scout_harness/precheck.py
@@ -30,12 +30,14 @@ import posthoganalytics
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.clickhouse.workload import Workload
from posthog.dataclasses import frozen
+from posthog.errors import ExposedCHQueryError
from posthog.event_usage import groups
from posthog.models import Team
@@ -47,6 +49,7 @@ logger = structlog.get_logger(__name__)
PRECHECK_TIMEOUT_S = 10
PRECHECK_MAX_ROWS = 50
PRECHECK_MAX_TEXT_BYTES = 8 * 1024
+PRECHECK_MAX_QUERY_LENGTH = 10_000
PrecheckOutcome = Literal["run", "skip", "error"]
# `rows`: the query found rows. `no_rows`: it found none. `false_value`: it returned one false
@@ -77,6 +80,25 @@ class _PrecheckRows:
return len(self.rows) == 1 and len(self.rows[0]) == 1 and self.rows[0][0] in (None, False, 0, "")
+@frozen
+class PrecheckDryRunResult:
+ would_run: bool
+ reason: PrecheckReason
+ since: datetime
+ now: datetime
+ row_count: int = 0
+ columns: tuple[str, ...] = ()
+ rows_text: str = ""
+ # Set only for an error the person who wrote the query can act on, such as a syntax error.
+ error: str | None = None
+
+
+def parse_precheck_query(query: str) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Parse a pre-check query with its `{since}` and `{now}` placeholders bound. Raises on a bad query."""
+ placeholder = ast.Constant(value=timezone.now())
+ return parse_select(query, placeholders={"since": placeholder, "now": placeholder})
+
+
def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | None = None) -> PrecheckResult | None:
"""Evaluate the pre-check of one scout. Return None when the scout has no pre-check.
@@ -94,7 +116,7 @@ def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | None
return None
now = now or timezone.now()
- since = _last_real_run_at(team_id, skill_name) or config.created_at
+ since = precheck_since(config)
team = Team.objects.select_related("organization").get(pk=team_id)
started = time.monotonic()
error_type: str | None = None
@@ -124,15 +146,48 @@ def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | None
return result
-def _last_real_run_at(team_id: int, skill_name: str) -> datetime | None:
- return (
- SignalScoutRun.objects.for_team(team_id)
- .filter(skill_name=skill_name)
+def dry_run_scout_precheck(
+ team: Team, config: SignalScoutConfig, query: str, now: datetime | None = None
+) -> PrecheckDryRunResult:
+ """Run a pre-check query the way the next scheduled run would, and change nothing."""
+ now = now or timezone.now()
+ since = precheck_since(config)
+ try:
+ found = _run_query(team, query, since=since, now=now)
+ except Exception as error:
+ logger.info(
+ "signals_scout: pre-check dry run failed",
+ team_id=team.pk,
+ skill_name=config.skill_name,
+ error_type=type(error).__name__,
+ )
+ # Other errors can carry generated SQL, so only an exposed error reaches the caller as written.
+ exposed = isinstance(error, ExposedHogQLError | ExposedCHQueryError)
+ message = str(error) if exposed else "The query could not run."
+ return PrecheckDryRunResult(would_run=True, reason="query_error", since=since, now=now, error=message)
+ result = _result_from_rows(found)
+ return PrecheckDryRunResult(
+ would_run=result.should_run,
+ reason=result.reason,
+ since=since,
+ now=now,
+ row_count=len(found.rows),
+ columns=tuple(str(column) for column in found.columns),
+ rows_text=_render_rows(found),
+ )
+
+
+def precheck_since(config: SignalScoutConfig) -> datetime:
+ """The `{since}` bound: the last run that actually ran, or the config's creation."""
+ last_run_at = (
+ SignalScoutRun.objects.for_team(config.team_id)
+ .filter(skill_name=config.skill_name)
.exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
.order_by("-created_at")
.values_list("created_at", flat=True)
.first()
)
+ return last_run_at or config.created_at
def _result_from_rows(found: _PrecheckRows) -> PrecheckResult:
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 2f8bbb04e26f..396c3532f282 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -56,6 +56,12 @@ from products.signals.backend.scout_harness.lazy_seed import (
from products.signals.backend.scout_harness.limits import MAX_RUN_NOTE_CHARS
from products.signals.backend.scout_harness.model_selection import scout_model_config_enabled, scout_model_pin_catalog
from products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCES
+from products.signals.backend.scout_harness.precheck import (
+ PRECHECK_MAX_QUERY_LENGTH,
+ PRECHECK_MAX_ROWS,
+ PRECHECK_TIMEOUT_S,
+ parse_precheck_query,
+)
from products.signals.backend.scout_harness.scout_costs import SCOUT_COST_WINDOW_DAYS
from products.signals.backend.scout_harness.skill_loader import reserved_scout_name_error
from products.signals.backend.scout_harness.slack_delivery import MAX_SCOUT_SLACK_DM_TARGETS
@@ -3107,6 +3113,31 @@ _SCOUT_MODEL_HELP = (
)
+_PRECHECK_QUERY_HELP = (
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or "
+ "one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no "
+ "model call, and no run row. Any other result starts the run, and the scout reads the rows. A "
+ "query error also starts the run. Use `{since}` (the start of the last run that ran, or when the "
+ "scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events "
+ "WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet "
+ "it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate "
+ "it: a manual or workflow run always starts. "
+ f"The query stops after {PRECHECK_TIMEOUT_S} seconds and reads at most {PRECHECK_MAX_ROWS} rows. "
+ "Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+)
+
+
+def _validate_precheck_query(value: str | None) -> str | None:
+ if value is None or not value.strip():
+ return None
+ query = value.strip()
+ try:
+ parse_precheck_query(query)
+ except Exception as exc:
+ raise serializers.ValidationError(f"The pre-check query is not a valid HogQL SELECT: {exc}")
+ return query
+
+
def _validate_scout_model(value: str | None, context: dict, current: str | None = None) -> str | None:
"""Normalize a scout model pin, gate setting one on the `scouts-model-config` dogfood flag, and
hold it to the platform's model catalog.
@@ -3500,6 +3531,7 @@ class SignalScoutConfigSerializer(serializers.ModelSerializer):
allow_null=True,
help_text=_SCOUT_MODEL_HELP,
)
+ precheck_query = serializers.CharField(read_only=True, allow_null=True, help_text=_PRECHECK_QUERY_HELP)
last_run_at = serializers.DateTimeField(
read_only=True,
allow_null=True,
@@ -3648,6 +3680,7 @@ class SignalScoutConfigSerializer(serializers.ModelSerializer):
"write_scopes",
"allowed_mcp_tools",
"tool_preset",
+ "precheck_query",
"last_run_at",
"consecutive_failure_count",
"status_changed_at",
@@ -3739,6 +3772,14 @@ class _ScoutConfigCapabilityFieldsMixin(serializers.Serializer):
"Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag."
),
)
+ precheck_query = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ trim_whitespace=False,
+ max_length=PRECHECK_MAX_QUERY_LENGTH,
+ help_text=_PRECHECK_QUERY_HELP,
+ )
def validate_allowed_mcp_tools(self, value: list[str] | None) -> list[str] | None:
return validate_allowed_mcp_tools(value)
@@ -3781,6 +3822,9 @@ class _ScoutConfigCapabilityFieldsMixin(serializers.Serializer):
def validate_write_scopes(self, value: list[str]) -> list[str]:
return _validate_write_scopes(value)
+ def validate_precheck_query(self, value: str | None) -> str | None:
+ return _validate_precheck_query(value)
+
def _display_name_field() -> serializers.CharField:
"""The scout's label, as written. Separate from the skill name, which stays its identity."""
@@ -3972,6 +4016,7 @@ class SignalScoutConfigUpdateSerializer(_ScoutConfigCapabilityFieldsMixin, seria
"mcp_gateway_server_ids",
"repositories",
"write_scopes",
+ "precheck_query",
"suggestion_id",
"allowed_mcp_tools",
"tool_preset",
@@ -4069,6 +4114,68 @@ class SignalScoutConfigCreateSerializer(SignalScoutConfigOptionsSerializer):
return value
+class ScoutPrecheckReason(models.TextChoices):
+ ROWS = "rows"
+ NO_ROWS = "no_rows"
+ FALSE_VALUE = "false_value"
+ QUERY_ERROR = "query_error"
+
+
+class SignalScoutPrecheckTestRequestSerializer(serializers.Serializer):
+ precheck_query = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ trim_whitespace=False,
+ max_length=PRECHECK_MAX_QUERY_LENGTH,
+ help_text=(
+ "HogQL `SELECT` to try, with the same `{since}` and `{now}` placeholders a saved pre-check "
+ "gets. Omit it, or pass null or blank, to try the query saved on the scout."
+ ),
+ )
+
+ def validate_precheck_query(self, value: str | None) -> str | None:
+ return _validate_precheck_query(value)
+
+
+class SignalScoutPrecheckTestSerializer(serializers.Serializer):
+ would_run = serializers.BooleanField(
+ help_text="Whether a scheduled run that started now would run the scout. False means it would skip the run."
+ )
+ reason = serializers.ChoiceField(
+ choices=ScoutPrecheckReason.choices,
+ help_text=(
+ "Why: `rows` (the query found rows), `no_rows` (it found none, so the run is skipped), "
+ "`false_value` (it returned one false value, so the run is skipped), or `query_error` (the "
+ "query failed, so the run starts as if there were no pre-check)."
+ ),
+ )
+ since = serializers.DateTimeField(
+ help_text="The value bound to `{since}`: the start of the last run that ran, or when the scout was created."
+ )
+ now = serializers.DateTimeField(help_text="The value bound to `{now}`.")
+ row_count = serializers.IntegerField(
+ help_text=f"How many rows the query returned, at most {PRECHECK_MAX_ROWS}.",
+ )
+ columns = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="The column names of the result, in order.",
+ )
+ rows_text = serializers.CharField(
+ help_text=(
+ "The rows as the scout reads them: one JSON object per line, cut before the text passes "
+ "the size limit. Empty when the query returned no rows or failed."
+ ),
+ )
+ error = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Why the query failed, when it failed. A syntax or schema error is given as written; other "
+ "failures read as a general message. Null when the query ran."
+ ),
+ )
+
+
class SignalScoutCreateSerializer(serializers.Serializer):
"""Create a runnable custom scout and its config in one atomic request."""
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 4fd839c37889..139ec9cf2309 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -58,7 +58,12 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.permissions import AccessControlPermission, APIScopePermission, get_authenticator_scopes
-from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle
+from posthog.rate_limit import (
+ AIBurstRateThrottle,
+ AISustainedRateThrottle,
+ ClickHouseBurstRateThrottle,
+ ClickHouseSustainedRateThrottle,
+)
from posthog.temporal.common.client import sync_connect
from posthog.temporal.oauth import SCOUT_GRANTABLE_WRITE_SCOPES
from posthog.user_permissions import UserPermissions
@@ -88,6 +93,7 @@ from products.signals.backend.scout_harness.lazy_seed import (
is_operational_scout,
scout_skill_origin,
)
+from products.signals.backend.scout_harness.precheck import dry_run_scout_precheck
from products.signals.backend.scout_harness.run_costs import scout_run_token_costs
from products.signals.backend.scout_harness.run_gates import (
ScoutRunRejection,
@@ -152,6 +158,8 @@ from products.signals.backend.scout_harness.serializers import (
SignalScoutEmissionSerializer,
SignalScoutManualRunRequestSerializer,
SignalScoutManualRunSerializer,
+ SignalScoutPrecheckTestRequestSerializer,
+ SignalScoutPrecheckTestSerializer,
SignalScoutRunDetailSerializer,
SignalScoutRunSummarySerializer,
validate_scout_repositories,
@@ -3664,6 +3672,46 @@ class SignalScoutConfigViewSet(ScoutTrialConfigMixin, TeamAndOrgViewSetMixin, vi
status=status.HTTP_202_ACCEPTED,
)
+ @validated_request(
+ request_serializer=SignalScoutPrecheckTestRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=SignalScoutPrecheckTestSerializer,
+ description="What the pre-check returns now, and whether a scheduled run would start.",
+ ),
+ 400: OpenApiResponse(description="The scout has no saved pre-check and the request gives no query."),
+ 404: OpenApiResponse(description="Config not found for this project."),
+ },
+ summary="Test a scout pre-check",
+ description=(
+ "Run a scout's pre-check query once and return its rows, without starting a run and without "
+ "saving anything. The query gets the same `{since}` and `{now}` values the next scheduled run "
+ "would get, so the result says whether that run would start or skip. Pass `precheck_query` to "
+ "try a query before you save it, or omit it to try the saved one. A query error comes back in "
+ "the `error` field with a 200, because a scheduled run treats it as a reason to run."
+ ),
+ operation_id="signals_scout_config_precheck_test",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="precheck_test",
+ # The query reads project data and returns it, so the caller needs the query read scope too.
+ required_scopes=["signal_scout:read", "query:read"],
+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],
+ )
+ def precheck_test(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ team = _canonical_team(self)
+ config_id = _parse_run_id_or_404(kwargs)
+ config = SignalScoutConfig.objects.for_team(team.id).filter(id=config_id).first()
+ if config is None or config.skill_name in withheld_skills_for_team(team.id):
+ raise exceptions.NotFound()
+ query = request.validated_data.get("precheck_query") or config.precheck_query
+ if not query:
+ raise exceptions.ValidationError({"precheck_query": "This scout has no pre-check query. Give one to test."})
+ result = dry_run_scout_precheck(team, config, query)
+ return Response(SignalScoutPrecheckTestSerializer(dataclasses.asdict(result)).data)
+
@extend_schema(
request=None,
responses={
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 7185653551bf..d3f84b4c3079 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -2727,6 +2727,30 @@ class TestRunCronScheduleValidation(SimpleTestCase):
assert serializer.validated_data["run_cron_schedule"] is None
+_PRECHECK_QUERY = "SELECT 1 FROM events WHERE timestamp > {since} AND timestamp <= {now}"
+
+
+class TestPrecheckQueryValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("placeholders", _PRECHECK_QUERY, True, _PRECHECK_QUERY),
+ ("padded", " SELECT 1 ", True, "SELECT 1"),
+ ("blank_turns_it_off", " ", True, None),
+ ("syntax_error", "SELEC 1", False, None),
+ ("unknown_placeholder", "SELECT 1 WHERE {nope}", False, None),
+ ("not_a_select", "DELETE FROM events", False, None),
+ ]
+ )
+ def test_precheck_query_validation(self, _name: str, query: str, valid: bool, expected: str | None) -> None:
+ serializer = SignalScoutConfigUpdateSerializer(data={"precheck_query": query}, partial=True)
+
+ assert serializer.is_valid() is valid
+ if valid:
+ assert serializer.validated_data["precheck_query"] == expected
+ else:
+ assert "precheck_query" in serializer.errors
+
+
class TestScoutHarnessConfigAPI(APIBaseTest):
def _list_url(self) -> str:
return f"/api/projects/{self.team.id}/signals/scout/configs/"
diff --git a/products/signals/backend/test/test_scout_precheck.py b/products/signals/backend/test/test_scout_precheck.py
index 14ee9fcc506a..e3137764b650 100644
--- a/products/signals/backend/test/test_scout_precheck.py
+++ b/products/signals/backend/test/test_scout_precheck.py
@@ -1,12 +1,13 @@
from datetime import UTC, datetime, timedelta
import time_machine
-from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
from django.apps import apps
from parameterized import parameterized
+from rest_framework import status
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.scout_harness.precheck import PRECHECK_MAX_ROWS, evaluate_scout_precheck
@@ -133,3 +134,59 @@ class TestEvaluateScoutPrecheck(ClickhouseTestMixin, BaseTest):
assert result is None
capture.assert_not_called()
+
+
+@time_machine.travel(NOW, tick=False)
+class TestScoutPrecheckTestAPI(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.config = SignalScoutConfig.all_teams.create(team=self.team, skill_name=SKILL)
+ SignalScoutConfig.all_teams.filter(pk=self.config.pk).update(created_at=NOW - timedelta(days=7))
+ _create_event(team=self.team, event="boom", distinct_id="d1", timestamp=NOW - timedelta(hours=1))
+ flush_persons_and_events()
+
+ def _url(self, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/configs/{self.config.id}/{suffix}"
+
+ @parameterized.expand(
+ [
+ ("saved_query_finds_rows", NEW_EVENTS_QUERY, {}, True, "rows", 1, False),
+ (
+ "body_query_overrides_saved",
+ NEW_EVENTS_QUERY,
+ {"precheck_query": "SELECT 1 FROM events WHERE event = 'other' AND timestamp > {since}"},
+ False,
+ "no_rows",
+ 0,
+ False,
+ ),
+ (
+ "query_error_runs_the_scout",
+ None,
+ {"precheck_query": "SELECT nope FROM not_a_table"},
+ True,
+ "query_error",
+ 0,
+ True,
+ ),
+ ]
+ )
+ def test_precheck_test_runs_the_query_without_a_run(
+ self, _name, saved_query, body, would_run, reason, row_count, has_error
+ ) -> None:
+ self.client.patch(self._url(), {"precheck_query": saved_query}, format="json")
+
+ with patch("products.signals.backend.temporal.agentic.scout_scheduler.start_manual_signals_scout_run") as start:
+ response = self.client.post(self._url("precheck_test/"), body, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ data = response.json()
+ assert (data["would_run"], data["reason"], data["row_count"]) == (would_run, reason, row_count)
+ assert (data["error"] is not None) is has_error
+ start.assert_not_called()
+ assert not SignalScoutRun.all_teams.filter(team=self.team).exists()
+
+ def test_precheck_test_without_any_query_is_rejected(self) -> None:
+ response = self.client.post(self._url("precheck_test/"), {}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index b941d4d08744..27b0aca37801 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3419,6 +3419,12 @@ export interface SignalScoutConfigOptionsApi {
* * `read_only` - Read only
* * `support_notes` - Support notes */
tool_preset?: ToolPresetEnumApi
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null
/** Whether this scout runs on its schedule. Defaults to true. */
enabled?: boolean
/** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
@@ -3749,6 +3755,11 @@ export interface SignalScoutConfigApi {
* @nullable
*/
readonly tool_preset: string | null
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @nullable
+ */
+ readonly precheck_query: string | null
/**
* When the coordinator last dispatched this scout. Null if it has never run.
* @nullable
@@ -3881,6 +3892,12 @@ export interface SignalScoutConfigCreateApi {
* * `read_only` - Read only
* * `support_notes` - Support notes */
tool_preset?: ToolPresetEnumApi
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null
/** Whether this scout runs on its schedule. Defaults to true. */
enabled?: boolean
/** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
@@ -4022,6 +4039,12 @@ export interface PatchedSignalScoutConfigUpdateApi {
* @maxItems 10
*/
write_scopes?: string[]
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null
/**
* Optional id of the canonical scout suggestion this request turns on. It records that the scout came from that suggestion. An id this project's batch does not hold is ignored.
* @maxLength 64
@@ -4039,6 +4062,57 @@ export interface PatchedSignalScoutConfigUpdateApi {
tool_preset?: ToolPresetEnumApi
}
+export interface SignalScoutPrecheckTestRequestApi {
+ /**
+ * HogQL `SELECT` to try, with the same `{since}` and `{now}` placeholders a saved pre-check gets. Omit it, or pass null or blank, to try the query saved on the scout.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null
+}
+
+/**
+ * * `rows` - Rows
+ * * `no_rows` - No Rows
+ * * `false_value` - False Value
+ * * `query_error` - Query Error
+ */
+export type ScoutPrecheckReasonEnumApi = (typeof ScoutPrecheckReasonEnumApi)[keyof typeof ScoutPrecheckReasonEnumApi]
+
+export const ScoutPrecheckReasonEnumApi = {
+ Rows: 'rows',
+ NoRows: 'no_rows',
+ FalseValue: 'false_value',
+ QueryError: 'query_error',
+} as const
+
+export interface SignalScoutPrecheckTestApi {
+ /** Whether a scheduled run that started now would run the scout. False means it would skip the run. */
+ would_run: boolean
+ /** Why: `rows` (the query found rows), `no_rows` (it found none, so the run is skipped), `false_value` (it returned one false value, so the run is skipped), or `query_error` (the query failed, so the run starts as if there were no pre-check).
+ *
+ * * `rows` - Rows
+ * * `no_rows` - No Rows
+ * * `false_value` - False Value
+ * * `query_error` - Query Error */
+ reason: ScoutPrecheckReasonEnumApi
+ /** The value bound to `{since}`: the start of the last run that ran, or when the scout was created. */
+ since: string
+ /** The value bound to `{now}`. */
+ now: string
+ /** How many rows the query returned, at most 50. */
+ row_count: number
+ /** The column names of the result, in order. */
+ columns: string[]
+ /** The rows as the scout reads them: one JSON object per line, cut before the text passes the size limit. Empty when the query returned no rows or failed. */
+ rows_text: string
+ /**
+ * Why the query failed, when it failed. A syntax or schema error is given as written; other failures read as a general message. Null when the query ran.
+ * @nullable
+ */
+ error: string | null
+}
+
/**
* Request body for an on-demand (`run now`) scout dispatch.
*
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index cdb644f5ff6a..b93b8d511275 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -116,6 +116,8 @@ import type {
SignalScoutEmissionApi,
SignalScoutManualRunApi,
SignalScoutManualRunRequestApi,
+ SignalScoutPrecheckTestApi,
+ SignalScoutPrecheckTestRequestApi,
SignalScoutRunDetailApi,
SignalScoutRunSummaryApi,
SignalSourceConfigApi,
@@ -1503,6 +1505,28 @@ export const signalsScoutConfigDestroy = async (
})
}
+export const getSignalsScoutConfigPrecheckTestUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/scout/configs/${id}/precheck_test/`
+}
+
+/**
+ * Run a scout's pre-check query once and return its rows, without starting a run and without saving anything. The query gets the same `{since}` and `{now}` values the next scheduled run would get, so the result says whether that run would start or skip. Pass `precheck_query` to try a query before you save it, or omit it to try the saved one. A query error comes back in the `error` field with a 200, because a scheduled run treats it as a reason to run.
+ * @summary Test a scout pre-check
+ */
+export const signalsScoutConfigPrecheckTest = async (
+ projectId: string,
+ id: string,
+ signalScoutPrecheckTestRequestApi?: SignalScoutPrecheckTestRequestApi,
+ options?: RequestInit
+): Promise<SignalScoutPrecheckTestApi> => {
+ return apiMutator<SignalScoutPrecheckTestApi>(getSignalsScoutConfigPrecheckTestUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(signalScoutPrecheckTestRequestApi),
+ })
+}
+
export const getSignalsScoutConfigRunUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/signals/scout/configs/${id}/run/`
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index f24f126eb293..5098be4e7898 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -726,6 +726,8 @@ export const signalsScoutCreateBodyConfigOneRepositoriesMax = 10
export const signalsScoutCreateBodyConfigOneWriteScopesMax = 10
+export const signalsScoutCreateBodyConfigOnePrecheckQueryMax = 10000
+
export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMin = 30
export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200
@@ -843,6 +845,13 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod
.describe(
'Expand this named preset into a saved tool list. Later preset changes do not alter the saved list. Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag.\n\n\* `read_only` - Read only\n\* `support_notes` - Support notes'
),
+ precheck_query: zod
+ .string()
+ .max(signalsScoutCreateBodyConfigOnePrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
enabled: zod
.boolean()
.optional()
@@ -1012,6 +1021,8 @@ export const signalsScoutConfigCreateBodyRepositoriesMax = 10
export const signalsScoutConfigCreateBodyWriteScopesMax = 10
+export const signalsScoutConfigCreateBodyPrecheckQueryMax = 10000
+
export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30
export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
@@ -1087,6 +1098,13 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.describe(
'Expand this named preset into a saved tool list. Later preset changes do not alter the saved list. Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag.\n\n\* `read_only` - Read only\n\* `support_notes` - Support notes'
),
+ precheck_query: zod
+ .string()
+ .max(signalsScoutConfigCreateBodyPrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
enabled: zod.boolean().optional().describe('Whether this scout runs on its schedule. Defaults to true.'),
emit: zod
.boolean()
@@ -1232,6 +1250,8 @@ export const signalsScoutConfigUpdateBodyRepositoriesMax = 10
export const signalsScoutConfigUpdateBodyWriteScopesMax = 10
+export const signalsScoutConfigUpdateBodyPrecheckQueryMax = 10000
+
export const signalsScoutConfigUpdateBodySuggestionIdMax = 64
export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
@@ -1386,6 +1406,13 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
.describe(
"Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `customer_task:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."
),
+ precheck_query: zod
+ .string()
+ .max(signalsScoutConfigUpdateBodyPrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
suggestion_id: zod
.string()
.max(signalsScoutConfigUpdateBodySuggestionIdMax)
@@ -1409,6 +1436,22 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
})
.describe('Editable display name, schedule, enablement, and emit posture for one scout config.')
+/**
+ * Run a scout's pre-check query once and return its rows, without starting a run and without saving anything. The query gets the same `{since}` and `{now}` values the next scheduled run would get, so the result says whether that run would start or skip. Pass `precheck_query` to try a query before you save it, or omit it to try the saved one. A query error comes back in the `error` field with a 200, because a scheduled run treats it as a reason to run.
+ * @summary Test a scout pre-check
+ */
+export const signalsScoutConfigPrecheckTestBodyPrecheckQueryMax = 10000
+
+export const SignalsScoutConfigPrecheckTestBody = /* @__PURE__ */ zod.object({
+ precheck_query: zod
+ .string()
+ .max(signalsScoutConfigPrecheckTestBodyPrecheckQueryMax)
+ .nullish()
+ .describe(
+ 'HogQL `SELECT` to try, with the same `{since}` and `{now}` placeholders a saved pre-check gets. Omit it, or pass null or blank, to try the query saved on the scout.'
+ ),
+})
+
/**
* Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if self-driving is paused at the project's pull request limit, or the project is over its daily report limit or daily run budget (429), or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Pass an optional `note` to steer this one run without leaving a scout note that would steer every later run too. Returns immediately with the workflow id: poll the scout's runs for the result.
* @summary Run a scout now
diff --git a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts b/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts
index fc2bb97eee9b..bb7f656147b5 100644
--- a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts
+++ b/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts
@@ -47,6 +47,7 @@ function makeMockScout(overrides: MockScoutOverrides): SignalScoutConfigApi {
structured_output_schema: null,
network_access: 'trusted',
model: null,
+ precheck_query: null,
last_run_at: null,
consecutive_failure_count: 0,
status_changed_at: null,
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCadenceLabel.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCadenceLabel.test.tsx
index c406e853490c..ac658546d669 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCadenceLabel.test.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCadenceLabel.test.tsx
@@ -34,6 +34,7 @@ const config: SignalScoutConfigApi = {
auto_pause_exempt: false,
network_access: 'trusted',
model: null,
+ precheck_query: null,
tags: [],
source_product: null,
source_id: null,
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx
index b33d85b46ba9..4dd588f2e774 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx
@@ -40,6 +40,7 @@ const config: SignalScoutConfigApi = {
auto_pause_exempt: false,
network_access: 'trusted',
model: null,
+ precheck_query: null,
tags: [],
source_product: null,
source_id: null,
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNextRunLabel.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNextRunLabel.test.tsx
index 9034ef22a50e..463b42ee83eb 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutNextRunLabel.test.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNextRunLabel.test.tsx
@@ -36,6 +36,7 @@ const config: SignalScoutConfigApi = {
auto_pause_exempt: false,
network_access: 'trusted',
model: null,
+ precheck_query: null,
tags: [],
source_product: null,
source_id: null,
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsx
index f1091e3a648d..fb5f9859420c 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsx
@@ -35,6 +35,7 @@ const config: SignalScoutConfigApi = {
tool_preset: null,
network_access: 'trusted',
model: null,
+ precheck_query: null,
last_run_at: null,
consecutive_failure_count: 0,
status_changed_at: null,
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutWriteAccessSection.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutWriteAccessSection.test.tsx
index 43907988f239..eb21004af73d 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutWriteAccessSection.test.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutWriteAccessSection.test.tsx
@@ -36,6 +36,7 @@ const CONFIG: SignalScoutConfigApi = {
auto_pause_exempt: false,
network_access: 'trusted',
model: null,
+ precheck_query: null,
tags: [],
source_product: null,
source_id: null,
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts
index 41e1b0720da9..d10737b9025d 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts
@@ -30,6 +30,7 @@ export const trialFixtureConfig: SignalScoutConfigApi = {
structured_output_schema: null,
network_access: 'trusted',
model: 'gpt-5.6-terra',
+ precheck_query: null,
last_run_at: null,
consecutive_failure_count: 0,
status_changed_at: null,
diff --git a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts
index 0eafc6f3bca2..566c90e7b17a 100644
--- a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts
@@ -63,6 +63,7 @@ const CREATED_SCOUT: SignalScoutCreateResponseApi = {
auto_pause_exempt: false,
network_access: 'trusted',
model: null,
+ precheck_query: null,
source_product: null,
source_id: null,
created_at: '2026-07-24T00:00:00Z',
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
index 2d1fe5e20000..ce13c8b27664 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
@@ -90,6 +90,7 @@ const BASE_CONFIG: SignalScoutConfigApi = {
auto_pause_exempt: false,
network_access: 'trusted',
model: null,
+ precheck_query: null,
source_product: null,
source_id: null,
created_at: '2026-07-22T00:00:00Z',
diff --git a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts
index 654bb0301427..93262cf4569a 100644
--- a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts
@@ -119,6 +119,7 @@ const CONFIG: SignalScoutConfigApi = {
auto_pause_exempt: false,
network_access: 'trusted',
model: null,
+ precheck_query: null,
source_product: null,
source_id: null,
created_at: '2026-07-22T00:00:00Z',
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index eef5834b50a9..d13944bfb12f 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -626,6 +626,24 @@ tools:
tick. Use this to see which scouts run, how often, whether they emit findings to the inbox, and where those
findings are delivered. Pass `search` to narrow the list to the scouts matching a substring of either name.
Pair with `scout-config-update` to tune them.
+ scout-config-precheck-test:
+ operation: signals_scout_config_precheck_test
+ enabled: true
+ scopes:
+ - signal_scout:read
+ - query:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Test a scout pre-check
+ description: >
+ Run a scout's pre-check query once by its config `id` and return the rows, without starting a run and
+ without saving anything. Pass `precheck_query` to try a query before you save it with `scout-config-update`,
+ or omit it to try the saved one. The query gets the same `{since}` (the start of the last run that ran) and
+ `{now}` values the next scheduled run would get. `would_run` and `reason` say whether that run would start
+ (`rows`, `query_error`) or skip (`no_rows`, `false_value`). `rows_text` is the text the scout reads, one
+ JSON object per line. A query error comes back in `error`: fix the query and test again.
scout-config-sync:
operation: signals_scout_config_sync
enabled: true
@@ -661,7 +679,10 @@ tools:
minutes apart; set null to return to the rolling interval. You can also configure
`output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM
directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids
- with integrations-users-retrieve. `skill_name` is fixed. Enabling records who flipped it on and is
+ with integrations-users-retrieve. Set `precheck_query` to a HogQL `SELECT` so a scheduled run starts only
+ when the query returns something: no rows, or one false value such as a zero `count()`, skips the run;
+ `{since}` and `{now}` bind the last run that ran and the current time. Try the query with
+ `scout-config-precheck-test` first. `skill_name` is fixed. Enabling records who flipped it on and is
activity-logged, since running a scout drives spend.
scout-create:
operation: signals_scout_create
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 66f0ca1e5e69..411252f921e8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11230,6 +11230,20 @@
"readOnlyHint": true
}
},
+ "scout-config-precheck-test": {
+ "description": "Run a scout's pre-check query once by its config `id` and return the rows, without starting a run and without saving anything. Pass `precheck_query` to try a query before you save it with `scout-config-update`, or omit it to try the saved one. The query gets the same `{since}` (the start of the last run that ran) and `{now}` values the next scheduled run would get. `would_run` and `reason` say whether that run would start (`rows`, `query_error`) or skip (`no_rows`, `false_value`). `rows_text` is the text the scout reads, one JSON object per line. A query error comes back in `error`: fix the query and test again.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Test a scout pre-check",
+ "title": "Test a scout pre-check",
+ "required_scopes": ["signal_scout:read", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"scout-config-sync": {
"description": "Materialize the Signals scout fleet for this project (idempotent): seeds the canonical `signals-scout-*` skills and creates a default-schedule config for any scout lacking one, then returns all scout configs. The Temporal coordinator does the same on its next tick; call this when a setup flow needs a tunable fleet immediately instead of waiting for the tick. Pair with `scout-config-update` to tune the returned configs.",
"category": "Signals",
@@ -11245,7 +11259,7 @@
}
},
"scout-config-update": {
- "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids with integrations-users-retrieve. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids with integrations-users-retrieve. Set `precheck_query` to a HogQL `SELECT` so a scheduled run starts only when the query returns something: no rows, or one false value such as a zero `count()`, skips the run; `{since}` and `{now}` bind the last run that ran and the current time. Try the query with `scout-config-precheck-test` first. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Update a scout config",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c5e0f49af3ba..99ff9f7522d4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11835,6 +11835,20 @@
"readOnlyHint": true
}
},
+ "scout-config-precheck-test": {
+ "description": "Run a scout's pre-check query once by its config `id` and return the rows, without starting a run and without saving anything. Pass `precheck_query` to try a query before you save it with `scout-config-update`, or omit it to try the saved one. The query gets the same `{since}` (the start of the last run that ran) and `{now}` values the next scheduled run would get. `would_run` and `reason` say whether that run would start (`rows`, `query_error`) or skip (`no_rows`, `false_value`). `rows_text` is the text the scout reads, one JSON object per line. A query error comes back in `error`: fix the query and test again.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Test a scout pre-check",
+ "title": "Test a scout pre-check",
+ "required_scopes": ["signal_scout:read", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"scout-config-sync": {
"description": "Materialize the Signals scout fleet for this project (idempotent): seeds the canonical `signals-scout-*` skills and creates a default-schedule config for any scout lacking one, then returns all scout configs. The Temporal coordinator does the same on its next tick; call this when a setup flow needs a tunable fleet immediately instead of waiting for the tick. Pair with `scout-config-update` to tune the returned configs.",
"category": "Signals",
@@ -11850,7 +11864,7 @@
}
},
"scout-config-update": {
- "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids with integrations-users-retrieve. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids with integrations-users-retrieve. Set `precheck_query` to a HogQL `SELECT` so a scheduled run starts only when the query returns something: no rows, or one false value such as a zero `count()`, skips the run; `{since}` and `{now}` bind the last run that ran and the current time. Try the query with `scout-config-precheck-test` first. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Update a scout config",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c7bc94850b64..bafc6227e702 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -83623,6 +83623,12 @@ export namespace Schemas {
* @maxItems 10
*/
write_scopes?: string[];
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null;
/**
* Optional id of the canonical scout suggestion this request turns on. It records that the scout came from that suggestion. An id this project's batch does not hold is ignored.
* @maxLength 64
@@ -96961,6 +96967,12 @@ export namespace Schemas {
* * `read_only` - Read only
* * `support_notes` - Support notes */
tool_preset?: ToolPresetEnum;
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null;
/** Whether this scout runs on its schedule. Defaults to true. */
enabled?: boolean;
/** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
@@ -97226,6 +97238,11 @@ export namespace Schemas {
* @nullable
*/
readonly tool_preset: string | null;
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @nullable
+ */
+ readonly precheck_query: string | null;
/**
* When the coordinator last dispatched this scout. Null if it has never run.
* @nullable
@@ -97819,6 +97836,22 @@ export namespace Schemas {
expires_at?: string | null;
}
+ /**
+ * * `rows` - Rows
+ * * `no_rows` - No Rows
+ * * `false_value` - False Value
+ * * `query_error` - Query Error
+ */
+ export type ScoutPrecheckReasonEnum = typeof ScoutPrecheckReasonEnum[keyof typeof ScoutPrecheckReasonEnum];
+
+
+ export const ScoutPrecheckReasonEnum = {
+ Rows: 'rows',
+ NoRows: 'no_rows',
+ FalseValue: 'false_value',
+ QueryError: 'query_error',
+ } as const;
+
/**
* One report a scanner's scout filed. Enough to read it in Replay Vision; the inbox owns the
* full record (status, priority, reviewers, run trail).
@@ -100106,6 +100139,12 @@ export namespace Schemas {
* * `read_only` - Read only
* * `support_notes` - Support notes */
tool_preset?: ToolPresetEnum;
+ /**
+ * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null;
/** Whether this scout runs on its schedule. Defaults to true. */
enabled?: boolean;
/** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
@@ -100250,6 +100289,42 @@ export namespace Schemas {
note?: string;
}
+ export interface SignalScoutPrecheckTest {
+ /** Whether a scheduled run that started now would run the scout. False means it would skip the run. */
+ would_run: boolean;
+ /** Why: `rows` (the query found rows), `no_rows` (it found none, so the run is skipped), `false_value` (it returned one false value, so the run is skipped), or `query_error` (the query failed, so the run starts as if there were no pre-check).
+ *
+ * * `rows` - Rows
+ * * `no_rows` - No Rows
+ * * `false_value` - False Value
+ * * `query_error` - Query Error */
+ reason: ScoutPrecheckReasonEnum;
+ /** The value bound to `{since}`: the start of the last run that ran, or when the scout was created. */
+ since: string;
+ /** The value bound to `{now}`. */
+ now: string;
+ /** How many rows the query returned, at most 50. */
+ row_count: number;
+ /** The column names of the result, in order. */
+ columns: string[];
+ /** The rows as the scout reads them: one JSON object per line, cut before the text passes the size limit. Empty when the query returned no rows or failed. */
+ rows_text: string;
+ /**
+ * Why the query failed, when it failed. A syntax or schema error is given as written; other failures read as a general message. Null when the query ran.
+ * @nullable
+ */
+ error: string | null;
+ }
+
+ export interface SignalScoutPrecheckTestRequest {
+ /**
+ * HogQL `SELECT` to try, with the same `{since}` and `{now}` placeholders a saved pre-check gets. Omit it, or pass null or blank, to try the query saved on the scout.
+ * @maxLength 10000
+ * @nullable
+ */
+ precheck_query?: string | null;
+ }
+
export type SignalScoutRunDetailMetadataDerived = {
has_emit_report: boolean;
has_edit_report: boolean;
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index dfe55b09d3c5..a191105ef693 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -1663,6 +1663,8 @@ export const visionScannersScoutsCreateBodyConfigOneRepositoriesMax = 10
export const visionScannersScoutsCreateBodyConfigOneWriteScopesMax = 10
+export const visionScannersScoutsCreateBodyConfigOnePrecheckQueryMax = 10000
+
export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMin = 30
export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMax = 43200
@@ -1761,6 +1763,13 @@ export const VisionScannersScoutsCreateBody = () => zod
.describe(
'Expand this named preset into a saved tool list. Later preset changes do not alter the saved list. Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag.\n\n\* `read_only` - Read only\n\* `support_notes` - Support notes'
),
+ precheck_query: zod
+ .string()
+ .max(visionScannersScoutsCreateBodyConfigOnePrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
enabled: zod
.boolean()
.optional()
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 09d0f9ad3307..023c66c9d468 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 53 enabled ops
+ * PostHog API - MCP 54 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -776,6 +776,8 @@ export const signalsScoutCreateBodyConfigOneRepositoriesMax = 10
export const signalsScoutCreateBodyConfigOneWriteScopesMax = 10
+export const signalsScoutCreateBodyConfigOnePrecheckQueryMax = 10000
+
export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMin = 30
export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200
@@ -891,6 +893,13 @@ export const SignalsScoutCreateBody = () => zod
.describe(
'Expand this named preset into a saved tool list. Later preset changes do not alter the saved list. Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag.\n\n\* `read_only` - Read only\n\* `support_notes` - Support notes'
),
+ precheck_query: zod
+ .string()
+ .max(signalsScoutCreateBodyConfigOnePrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
enabled: zod
.boolean()
.optional()
@@ -1057,6 +1066,8 @@ export const signalsScoutConfigCreateBodyRepositoriesMax = 10
export const signalsScoutConfigCreateBodyWriteScopesMax = 10
+export const signalsScoutConfigCreateBodyPrecheckQueryMax = 10000
+
export const signalsScoutConfigCreateBodyRunIntervalMinutesMin = 30
export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
@@ -1132,6 +1143,13 @@ export const SignalsScoutConfigCreateBody = () => zod
.describe(
'Expand this named preset into a saved tool list. Later preset changes do not alter the saved list. Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag.\n\n\* `read_only` - Read only\n\* `support_notes` - Support notes'
),
+ precheck_query: zod
+ .string()
+ .max(signalsScoutConfigCreateBodyPrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
enabled: zod.boolean().optional().describe('Whether this scout runs on its schedule. Defaults to true.'),
emit: zod
.boolean()
@@ -1286,6 +1304,8 @@ export const signalsScoutConfigUpdateBodyRepositoriesMax = 10
export const signalsScoutConfigUpdateBodyWriteScopesMax = 10
+export const signalsScoutConfigUpdateBodyPrecheckQueryMax = 10000
+
export const signalsScoutConfigUpdateBodySuggestionIdMax = 64
export const SignalsScoutConfigUpdateBody = () => zod
@@ -1440,6 +1460,13 @@ export const SignalsScoutConfigUpdateBody = () => zod
.describe(
"Extra write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `customer_task:write`, `dashboard:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `replay_scanner:write`, `warehouse_table:write`, `warehouse_view:write`. Empty (the default) means the scout reads the project and writes only what every scout may write: notebooks, its findings, and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant. Applies from the scout's next run."
),
+ precheck_query: zod
+ .string()
+ .max(signalsScoutConfigUpdateBodyPrecheckQueryMax)
+ .nullish()
+ .describe(
+ "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ ),
suggestion_id: zod
.string()
.max(signalsScoutConfigUpdateBodySuggestionIdMax)
@@ -1476,6 +1503,31 @@ export const SignalsScoutConfigDestroyParams = () => zod.object({
),
})
+/**
+ * Run a scout's pre-check query once and return its rows, without starting a run and without saving anything. The query gets the same `{since}` and `{now}` values the next scheduled run would get, so the result says whether that run would start or skip. Pass `precheck_query` to try a query before you save it, or omit it to try the saved one. A query error comes back in the `error` field with a 200, because a scheduled run treats it as a reason to run.
+ * @summary Test a scout pre-check
+ */
+export const SignalsScoutConfigPrecheckTestParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this Signal scout config.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const signalsScoutConfigPrecheckTestBodyPrecheckQueryMax = 10000
+
+export const SignalsScoutConfigPrecheckTestBody = () => zod.object({
+ precheck_query: zod
+ .string()
+ .max(signalsScoutConfigPrecheckTestBodyPrecheckQueryMax)
+ .nullish()
+ .describe(
+ 'HogQL `SELECT` to try, with the same `{since}` and `{now}` placeholders a saved pre-check gets. Omit it, or pass null or blank, to try the query saved on the scout.'
+ ),
+})
+
/**
* Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if self-driving is paused at the project's pull request limit, or the project is over its daily report limit or daily run budget (429), or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Pass an optional `note` to steer this one run without leaving a scout note that would steer every later run too. Returns immediately with the workflow id: poll the scout's runs for the result.
* @summary Run a scout now
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 3422fe8228e3..f18daa28bcca 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -858,6 +858,9 @@ const scoutConfigCreate = (): ToolBase<ReturnType<typeof ScoutConfigCreateSchema
if (params.tool_preset !== undefined) {
body['tool_preset'] = params.tool_preset
}
+ if (params.precheck_query !== undefined) {
+ body['precheck_query'] = params.precheck_query
+ }
if (params.enabled !== undefined) {
body['enabled'] = params.enabled
}
@@ -937,6 +940,35 @@ const scoutConfigList = (): ToolBase<
},
})
+const ScoutConfigPrecheckTestSchema = () => {
+ const SignalsScoutConfigPrecheckTestBody = orvalSchemas.SignalsScoutConfigPrecheckTestBody()
+ const SignalsScoutConfigPrecheckTestParams = orvalSchemas.SignalsScoutConfigPrecheckTestParams()
+ return SignalsScoutConfigPrecheckTestParams.omit({ project_id: true }).extend(
+ SignalsScoutConfigPrecheckTestBody.shape
+ )
+}
+
+const scoutConfigPrecheckTest = (): ToolBase<
+ ReturnType<typeof ScoutConfigPrecheckTestSchema>,
+ Schemas.SignalScoutPrecheckTest
+> => ({
+ name: 'scout-config-precheck-test',
+ schema: ScoutConfigPrecheckTestSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ScoutConfigPrecheckTestSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.precheck_query !== undefined) {
+ body['precheck_query'] = params.precheck_query
+ }
+ const result = await context.api.request<Schemas.SignalScoutPrecheckTest>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/${encodeURIComponent(String(params.id))}/precheck_test/`,
+ body,
+ })
+ return result
+ },
+})
+
const ScoutConfigSyncSchema = () => {
const SignalsScoutConfigSyncQueryParams = orvalSchemas.SignalsScoutConfigSyncQueryParams()
return SignalsScoutConfigSyncQueryParams
@@ -1018,6 +1050,9 @@ const scoutConfigUpdate = (): ToolBase<
if (params.write_scopes !== undefined) {
body['write_scopes'] = params.write_scopes
}
+ if (params.precheck_query !== undefined) {
+ body['precheck_query'] = params.precheck_query
+ }
if (params.suggestion_id !== undefined) {
body['suggestion_id'] = params.suggestion_id
}
@@ -1934,6 +1969,9 @@ const signalsScoutConfigCreate = (): ToolBase<
if (params.tool_preset !== undefined) {
body['tool_preset'] = params.tool_preset
}
+ if (params.precheck_query !== undefined) {
+ body['precheck_query'] = params.precheck_query
+ }
if (params.enabled !== undefined) {
body['enabled'] = params.enabled
}
@@ -2094,6 +2132,9 @@ const signalsScoutConfigUpdate = (): ToolBase<
if (params.write_scopes !== undefined) {
body['write_scopes'] = params.write_scopes
}
+ if (params.precheck_query !== undefined) {
+ body['precheck_query'] = params.precheck_query
+ }
if (params.suggestion_id !== undefined) {
body['suggestion_id'] = params.suggestion_id
}
@@ -2626,6 +2667,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'scout-config-create': scoutConfigCreate,
'scout-config-delete': scoutConfigDelete,
'scout-config-list': scoutConfigList,
+ 'scout-config-precheck-test': scoutConfigPrecheckTest,
'scout-config-sync': scoutConfigSync,
'scout-config-update': scoutConfigUpdate,
'scout-create': scoutCreate,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
index b08dd13a54ba..ddd2f626fcaa 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
@@ -136,6 +136,18 @@
},
"type": "object"
},
+ "precheck_query": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ },
"repositories": {
"description": "GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-precheck-test.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-precheck-test.json
new file mode 100644
index 000000000000..3eb73aa09cc4
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-precheck-test.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this Signal scout config.",
+ "type": "string"
+ },
+ "precheck_query": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "HogQL `SELECT` to try, with the same `{since}` and `{now}` placeholders a saved pre-check gets. Omit it, or pass null or blank, to try the query saved on the scout."
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
index 2458ccd49c8a..0ab30043f25f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
@@ -138,6 +138,18 @@
},
"type": "object"
},
+ "precheck_query": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ },
"repositories": {
"description": "GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.json
index 5dfaeb72a4c9..652539a104cf 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create.json
@@ -138,6 +138,18 @@
},
"type": "object"
},
+ "precheck_query": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ },
"repositories": {
"description": "GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
index b08dd13a54ba..ddd2f626fcaa 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
@@ -136,6 +136,18 @@
},
"type": "object"
},
+ "precheck_query": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ },
"repositories": {
"description": "GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
index 2458ccd49c8a..0ab30043f25f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
@@ -138,6 +138,18 @@
},
"type": "object"
},
+ "precheck_query": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ },
"repositories": {
"description": "GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json
index d2d17039775a..96da2983c42a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json
@@ -137,6 +137,18 @@
},
"type": "object"
},
+ "precheck_query": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank turns the pre-check off."
+ },
"repositories": {
"description": "GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.",
"items": {