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): let research and scouts author report checks (#102406)

posthog[bot]97888f00fc0a
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 53d62d1434ab..be021f0c4db4 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -208,6 +208,7 @@ post_save:products.feature_flags.backend.local_evaluation.feature_flag_changed
post_save:products.feature_flags.backend.session_recording_links.relink_teams_on_key_change
post_save:products.managed_warehouse.backend.models._observe_duckgres_server_save
post_save:products.review_hog.backend.receivers.handle_task_run_saved
+post_save:products.signals.backend.receivers.arm_pending_checks_when_report_resolved
post_save:products.signals.backend.receivers.capture_status_change_analytics
post_save:products.signals.backend.receivers.close_pr_when_report_dismissed
post_save:products.signals.backend.receivers.emit_report_embedding_on_document_change
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index b48f001d4247..8afed8e2e9cd 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -503,7 +503,15 @@ A dispatch is not a verdict. The row stays `active` with `dispatched_at` stamped
Execution rides the scout coordinator tick (`run_due_signal_report_checks_activity`, gated behind a `workflow.patched` marker). Each tick expires what timed out, then advances the due rows by one step, capped per tick and per team. A pass on a recurring check re-arms it anchored on `now` so an outage cannot owe a burst of catch-up runs; a breach retires the check as `failed`; a run that cannot be measured retries and only retires after three consecutive errors. A check stops running while its report is suppressed or soft-deleted and runs again when the report comes back, but its horizon keeps advancing, so one that outlives `expires_at` while paused expires. A check that names a report metric stores a copy of that metric's query at creation, so a later edit to the metric does not change what the check measures. Both kinds are written through one funnel (`record_check_verdict`) that re-reads the row under a lock, so a check cancelled while its run was working records nothing.
-Checks are created and cancelled through `SignalReportCheckViewSet` (`/signals/reports/:id/checks/`, `task:write`, same attribution as artefact writes). There is no update: editing a threshold after a result would make the recorded verdict unreadable.
+A check written _before_ the fix exists has no date to carry. The research pipeline's verification turn is that case: it authors the check in the same pass that writes the report. Such a check is stored `pending` with a `soak_minutes` window, and the report's transition to `resolved` is what sets `next_run_at` — a merged pull request's webhook, a manual resolve in the inbox, and an MCP state write all end in the same `save`, so the resolve is the clock for every kind of fix, including the ones that never had a pull request. `receivers.arm_pending_checks_when_report_resolved` is the choke point. A pending check counts against the per-report cap, is never collected as due, and expires at the 90-day horizon if its report never resolves.
+
+A failed verdict on a resolved report is the one outcome nobody would otherwise read, because the inbox no longer lists the report. An `agent` check has a scout in the loop that can author a fresh one, so only the deterministic lane needs help: a `metric_threshold` breach on a `resolved` report emits a `source_product="signals_check"` signal carrying the verdict and the origin report id. The grouping stage then applies the rule it already applies to any signal landing on a resolved report — a fresh report, linked back by `related_to`. Nothing reopens the terminal one.
+
+Four best-effort events in `report_check_telemetry.py` follow a check: `signals_report_check_created` from the shared write, so every author is counted; `signals_report_check_dispatch` for each attempt to hand an `agent` check to a run, with the refusing gate as `reason` on a deferral; `signals_report_check_evaluated` for each verdict, where a `check_status` of `active` means the check looks again; and `signals_report_checks_expired`, one per project per sweep, whose `never_ran_count` is the checks that were written and never looked at.
+
+Checks are written in one place, `report_check_authoring.create_check`, which owns the per-report cap, the metric-query copy, and the attribution for every caller. Only two authors write a check: a scout run, and the research pipeline. `SignalReportCheckViewSet` (`/signals/reports/:id/checks/`) is read and cancel only, and the public MCP surface is `inbox-report-checks-list` / `-retrieve`. There is deliberately no caller-facing create: an `agent` check puts its author's prose in front of a privileged scout run, which `task:write` does not authorize, and every other surface that does so demands `llm_skill:write` plus skill-editor access. Scouts create and cancel through the scout tools `scout-report-check-create` / `-list` / `-cancel` (gated on the report-channel `allowed_tools` opt-in and the `signal_scout_report:write` scope, the two layers `scout-emit-report` already sits behind, because a check is a write on a report). Research writes its specs in `mark_report_ready_activity`. The scout tools also bind to the run the caller's sandbox token was minted for, so a run cannot write, list or cancel under a sibling's task, and a write goes through the same emit preflight as a signal or a report, so a dry-run scout writes no check. There is no update: editing a threshold after a result would make the recorded verdict unreadable.
+
+Research authors its checks in the verification turn (`FixVerificationOutput.checks`, a list of `CheckSpec`). The turn is offered the `metric_threshold` kind only while the report-metrics rollout is on, because such a check references one of the report's own metrics by `metric_id`, and the `agent` kind only while the team is enrolled in scouts, because nothing would ever run a check with no scout fleet behind it. The daily run budget is not part of that gate: a research check stays pending until its report resolves, and the dispatcher defers a throttled check by itself. With neither, the `checks` field never reaches the schema. The specs are persisted by `mark_report_ready_activity`, in the same transaction that writes the title, summary, charts and metrics, so a spec naming a metric that transition did not store is dropped there rather than kept pointing at nothing. Only a pass that settles writes its specs: a pass that loops back to `candidate` is about to be replaced, and its checks would be armed later against prose they were not written for. For the same reason a settled pass that returns specs cancels the report's earlier `pending` checks first, which only research writes. A pass that returns none leaves them alone, because the verification turn is best-effort. The plan and the check read as one thing in the timeline: the prose is the plan, and `to_note()` names the check it scheduled.
**Report metrics.** `SignalReport.metrics` is typed report content, not an artefact log or a materialized time series. Its dependency-light schema lives in `report_metrics.py` (`ReportMetric`). Each entry has a stable id, title, semantic kind, role, display format, a required bounded live query, and an optional cached snapshot. Legacy comparison data stays compatible in storage but is not exposed as a live comparison. A report accepts at most six metrics, at most one primary metric, and at most one `affected_users` metric.
diff --git a/products/signals/backend/contracts.py b/products/signals/backend/contracts.py
index a66767230967..f0cbeec04b06 100644
--- a/products/signals/backend/contracts.py
+++ b/products/signals/backend/contracts.py
@@ -345,6 +345,32 @@ class SignalsScoutSignalInput(SignalInputBase):
extra: SignalsScoutSignalExtra
+# ── Report checks ──────────────────────────────────────────────────────────────
+
+
+class CheckFailedSignalExtra(SignalExtraBase):
+ check_id: str
+ report_id: str
+ check_title: str
+ explanation: str
+ observed_value: float | None = None
+ baseline_value: float | None = None
+ threshold: str | None = None
+
+
+class CheckFailedSignalInput(SignalInputBase):
+ """A deterministic check that breached after its report was resolved.
+
+ The inbox emitting to itself. An `agent` check has a scout that can author a fresh report; a
+ `metric_threshold` check has nobody, so the verdict becomes a signal and the pipeline treats the
+ relapse the way it treats any other recurrence on a resolved report.
+ """
+
+ source_type: Literal[SignalSourceType.CHECK_FAILED]
+ source_product: Literal[SignalSourceProduct.SIGNALS_CHECK]
+ extra: CheckFailedSignalExtra
+
+
# ── Logs ────────────────────────────────────────────────────────────────────────
@@ -1019,6 +1045,7 @@ SignalInput = Annotated[
| EndpointBreakdownLimitExceededSignalInput
| PgAnalyzeIssueSignalInput
| SignalsScoutSignalInput
+ | CheckFailedSignalInput
| LogsAlertStateChangeSignalInput
| AnalyticsAnomalyInvestigationSignalInput
| HealthCheckSignalInput
diff --git a/products/signals/backend/enums.py b/products/signals/backend/enums.py
index ffd11e7d4268..67cf2d161faf 100644
--- a/products/signals/backend/enums.py
+++ b/products/signals/backend/enums.py
@@ -30,6 +30,9 @@ class SignalSourceProduct(StrEnum):
ENDPOINTS = "endpoints"
PGANALYZE = "pganalyze"
SIGNALS_SCOUT = "signals_scout"
+ # A report check that failed after its report was resolved. Not a source a team connects:
+ # the inbox emits it to itself so a fix that stopped holding starts a fresh report.
+ SIGNALS_CHECK = "signals_check"
LOGS = "logs"
HEALTH_CHECKS = "health_checks"
REPLAY_VISION = "replay_vision"
@@ -100,6 +103,7 @@ class SignalSourceType(StrEnum):
CI_BROKEN_DEFAULT_BRANCH = "ci_broken_default_branch"
CI_DURATION_REGRESSION = "ci_duration_regression"
SEARCH_OPPORTUNITY = "search_opportunity"
+ CHECK_FAILED = "check_failed"
# Plain value lists for ENUM_NAME_OVERRIDES in web.py — drf-spectacular hashes ChoiceField
@@ -120,6 +124,7 @@ SIGNAL_SOURCE_PRODUCT_LABELS: dict[SignalSourceProduct, str] = {
SignalSourceProduct.ERROR_TRACKING: "Error tracking",
SignalSourceProduct.PGANALYZE: "pganalyze",
SignalSourceProduct.SIGNALS_SCOUT: "Signals scout",
+ SignalSourceProduct.SIGNALS_CHECK: "Report check",
SignalSourceProduct.LOGS: "Logs",
SignalSourceProduct.HEALTH_CHECKS: "Health checks",
SignalSourceProduct.ENDPOINTS: "Endpoints",
diff --git a/products/signals/backend/migrations/0140_signalreportcheck_soak_minutes_and_more.py b/products/signals/backend/migrations/0140_signalreportcheck_soak_minutes_and_more.py
new file mode 100644
index 000000000000..c6dd643040e1
--- /dev/null
+++ b/products/signals/backend/migrations/0140_signalreportcheck_soak_minutes_and_more.py
@@ -0,0 +1,34 @@
+# Generated by Django 5.2.17 on 2026-09-17 14:06
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0139_implementation_dispatch"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreportcheck",
+ name="soak_minutes",
+ field=models.PositiveIntegerField(blank=True, null=True),
+ ),
+ migrations.AlterField(
+ model_name="signalreportcheck",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("active", "Active"),
+ ("passed", "Passed"),
+ ("failed", "Failed"),
+ ("errored", "Errored"),
+ ("expired", "Expired"),
+ ("cancelled", "Cancelled"),
+ ],
+ default="active",
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index a3a0c6050106..1d49112c1473 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0139_implementation_dispatch
+0140_signalreportcheck_soak_minutes_and_more
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 37ef01187d9d..fb065aa72dbc 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1727,6 +1727,10 @@ class SignalReportCheck(UUIDModel):
days, and the check carries its own `next_run_at` rather than deriving one from a merged pull
request — plenty of fixes land with no pull request to date the window from.
+ A check written before the fix exists has no date to carry, so it is stored PENDING with a
+ `soak_minutes` window and the report's transition to RESOLVED sets its `next_run_at`. That makes
+ the resolve the clock for every kind of fix, including the ones that never had a pull request.
+
Terminal statuses are final. A check that passed, failed, errored out, expired, or was cancelled
is never rescheduled; the author writes a new check instead, so a result artefact always refers
to a row whose state explains it.
@@ -1741,6 +1745,10 @@ class SignalReportCheck(UUIDModel):
AGENT = "agent"
class Status(models.TextChoices):
+ # Written before the fix it checks exists, so it carries a soak rather than a date and
+ # waits for its report to resolve. Not due, not expired, and not terminal: the resolve
+ # transition arms it into ACTIVE (`report_check_authoring.arm_pending_checks`).
+ PENDING = "pending"
ACTIVE = "active"
PASSED = "passed"
FAILED = "failed"
@@ -1748,6 +1756,10 @@ class SignalReportCheck(UUIDModel):
EXPIRED = "expired"
CANCELLED = "cancelled"
+ # The two statuses a check can still produce a verdict from. Both count against the per-report
+ # cap, because a pending check is one the report has already committed to running.
+ OPEN_STATUSES = (Status.PENDING, Status.ACTIVE)
+
class Outcome(models.TextChoices):
PASSED = "passed"
FAILED = "failed"
@@ -1773,6 +1785,10 @@ class SignalReportCheck(UUIDModel):
config = models.JSONField(default=dict, db_default={})
next_run_at = models.DateTimeField()
+ # How long after the report resolves a PENDING check waits before its first run. Null on a check
+ # created ACTIVE, which named its own `next_run_at` instead. Kept after the check is armed, so a
+ # reader can see what window the verdict was measured over.
+ soak_minutes = models.PositiveIntegerField(null=True, blank=True)
# Null means one-shot. A recurring check re-arms at this interval until it runs out of runs or
# reaches its expiry.
run_interval_minutes = models.PositiveIntegerField(null=True, blank=True)
@@ -1821,7 +1837,7 @@ class SignalReportCheck(UUIDModel):
@property
def is_terminal(self) -> bool:
- return self.status != self.Status.ACTIVE
+ return self.status not in self.OPEN_STATUSES
# ── Signals scout (headless cross-source explorer) ──────────────────────────────
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index f968c70c9768..cdc11f8f72e6 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -376,6 +376,50 @@ def close_pr_when_report_dismissed(
)
+@receiver(post_save, sender=SignalReport)
+def arm_pending_checks_when_report_resolved(
+ sender: type[SignalReport],
+ instance: SignalReport,
+ created: bool,
+ update_fields: set[str] | None = None,
+ **kwargs: Any,
+) -> None:
+ """Start the soak clock on the report's pending checks the moment it resolves.
+
+ A check written during research predates any fix, so it carries a soak duration rather than a
+ date. The resolve is what it waits for, and hooking the model rather than each caller makes
+ every resolve path the same clock: a merged pull request's webhook, a manual resolve in the
+ inbox, and an MCP state write all finish in a ``save``. Plenty of fixes never have a pull
+ request to date a window from, which is why the report's own transition is the event.
+ """
+ if instance.status != SignalReport.Status.RESOLVED:
+ return
+ if not _status_changed_on_this_save(
+ instance, created=created, update_fields=update_fields, prior_status=getattr(instance, "_prior_status", None)
+ ):
+ return
+ team_id = instance.team_id
+ report_id = str(instance.id)
+ resolved_at = timezone.now()
+ # After commit, so a rolled-back resolve never arms a check, and best-effort: a report that
+ # resolved is the outcome that matters, and a failure here leaves the checks pending rather
+ # than losing them.
+ transaction.on_commit(
+ partial(_arm_pending_checks_safely, team_id=team_id, report_id=report_id, resolved_at=resolved_at)
+ )
+
+
+def _arm_pending_checks_safely(*, team_id: int, report_id: str, resolved_at: datetime) -> None:
+ # Function-local: the authoring module reaches the execution module and from there the alerts
+ # facade, which the startup-import-budget test keeps off django.setup().
+ from products.signals.backend.report_check_authoring import arm_pending_checks # noqa: PLC0415
+
+ try:
+ arm_pending_checks(team_id=team_id, report_id=report_id, resolved_at=resolved_at)
+ except Exception:
+ logger.exception("signals.report_check.arm_on_resolve_failed", report_id=report_id, team_id=team_id)
+
+
@receiver(post_save, sender=SignalReport)
def emit_report_embedding_on_document_change(
sender: type[SignalReport],
diff --git a/products/signals/backend/report_check_agent.py b/products/signals/backend/report_check_agent.py
index 34f31c2c0b1d..ba74d7b4f9e0 100644
--- a/products/signals/backend/report_check_agent.py
+++ b/products/signals/backend/report_check_agent.py
@@ -28,6 +28,7 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportCheck, SignalScoutConfig
+from products.signals.backend.report_check_telemetry import capture_report_check_dispatch
from products.signals.backend.report_checks import AgentCheckConfig, parse_check_config
from products.signals.backend.scout_harness.run_gates import check_fleet_gates, check_run_in_flight, check_spend_gates
from products.signals.backend.scout_harness.team_limits import withheld_skills_for_team
@@ -288,6 +289,9 @@ def run_agent_check(check: SignalReportCheck, *, now: datetime | None = None) ->
# spending an error on a flag read or a row lookup that failed.
logger.exception("signals.report_check.agent_gates_failed", check_id=str(check.id), team_id=check.team_id)
_defer(check, now)
+ capture_report_check_dispatch(
+ check.team, check, outcome="deferred", skill_name=skill_name, reason="gates_failed"
+ )
return "deferred"
if refusal is not None:
logger.info(
@@ -300,6 +304,9 @@ def run_agent_check(check: SignalReportCheck, *, now: datetime | None = None) ->
)
if refusal.retryable:
_defer(check, now)
+ capture_report_check_dispatch(
+ check.team, check, outcome="deferred", skill_name=skill_name, reason=refusal.reason
+ )
return "deferred"
record_check_verdict(
check, CheckVerdict(outcome="errored", explanation=f"{check.title}: {refusal.detail}"), now=now
@@ -322,10 +329,16 @@ def run_agent_check(check: SignalReportCheck, *, now: datetime | None = None) ->
# Another check on the same lane is still being answered. Theirs finishes, ours goes next
# window; nothing is wrong with either check.
_release_dispatch_claim(check, now)
+ capture_report_check_dispatch(
+ check.team, check, outcome="deferred", skill_name=skill_name, reason="workflow_already_started"
+ )
return "deferred"
except Exception:
logger.exception("signals.report_check.agent_dispatch_failed", check_id=str(check.id), team_id=check.team_id)
_release_dispatch_claim(check, now)
+ capture_report_check_dispatch(
+ check.team, check, outcome="deferred", skill_name=skill_name, reason="dispatch_failed"
+ )
return "deferred"
logger.info(
@@ -335,4 +348,5 @@ def run_agent_check(check: SignalReportCheck, *, now: datetime | None = None) ->
skill_name=skill_name,
workflow_id=workflow_id,
)
+ capture_report_check_dispatch(check.team, check, outcome="dispatched", skill_name=skill_name)
return "dispatched"
diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.py
new file mode 100644
index 000000000000..531f1f59c6db
--- /dev/null
+++ b/products/signals/backend/report_check_authoring.py
@@ -0,0 +1,229 @@
+"""The one place a `SignalReportCheck` row is written, and the one place a pending check is armed.
+
+Three callers author checks — the REST endpoint, the scout tool, and the research pipeline — and
+they must agree on what a check row means, so the cap, the metric-query copy, and the attribution
+live here rather than three times over. `report_checks.py` still owns the shapes and the bounds;
+this module owns the write.
+
+A check written after the fix shipped names the date to look on. A check written *before* it cannot:
+the research turn authors its check in the same pass that writes the report, and many fixes never
+get a merged pull request to date a soak window from. Such a check is stored `pending` with a soak
+duration and armed by the report's transition to `resolved`, whatever caused it. That makes the
+resolve the clock for every kind of fix.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timedelta
+from functools import partial
+
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.models import SignalReport, SignalReportCheck
+from products.signals.backend.report_check_execution import resolve_check_query
+from products.signals.backend.report_check_telemetry import capture_report_check_created
+from products.signals.backend.report_checks import (
+ DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
+ MAX_ACTIVE_CHECKS_PER_REPORT,
+ MAX_CHECK_HORIZON,
+ CheckConfigValidationError,
+ CheckSpec,
+ MetricThresholdConfig,
+ parse_check_config,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+class CheckCreationError(ValueError):
+ """A check that cannot be written: a bad config, an unresolvable metric, or a full report."""
+
+
+def create_check(
+ *,
+ report: SignalReport,
+ title: str,
+ rationale: str = "",
+ kind: str,
+ config: dict,
+ attribution: ArtefactAttribution,
+ next_run_at: datetime | None = None,
+ soak_minutes: int | None = None,
+ run_interval_minutes: int | None = None,
+ runs_remaining: int = 1,
+ expires_at: datetime | None = None,
+) -> SignalReportCheck:
+ """Write one check on a report, armed or pending.
+
+ Pass `next_run_at` and `expires_at` for a check that already knows when to look. Pass
+ `soak_minutes` instead for one that waits on the report resolving; the row is stored `pending`
+ and its dates are provisional until `arm_pending_checks` rewrites them.
+
+ The report row is locked for the same reason the REST path locks it: the per-report cap is a
+ count followed by an insert, which only holds if concurrent creates serialize.
+ """
+ if (next_run_at is None) == (soak_minutes is None):
+ raise CheckCreationError("a check names either a next_run_at or a soak_minutes, not both and not neither")
+
+ try:
+ parsed = parse_check_config(kind, config)
+ except CheckConfigValidationError as error:
+ raise CheckCreationError(str(error)) from None
+
+ stored_config = dict(config)
+ if isinstance(parsed, MetricThresholdConfig) and parsed.metric_id is not None:
+ if parsed.query is not None:
+ raise CheckCreationError(
+ "provide either metric_id or query, not both. The metric's query is copied onto the check."
+ )
+ # Resolved now and stored, rather than at each run: an unresolvable reference would
+ # otherwise sit idle for the whole soak window before retiring, and one resolved late would
+ # measure whatever the metric had become.
+ try:
+ stored_config["query"] = resolve_check_query(parsed, report)
+ except ValueError as error:
+ raise CheckCreationError(f"This check cannot run: {error}.") from None
+
+ now = timezone.now()
+ if soak_minutes is not None:
+ status = SignalReportCheck.Status.PENDING
+ # Provisional, and rewritten at arm time. The horizon is real though: a report that never
+ # resolves retires its pending checks rather than holding them forever.
+ next_run_at = now + timedelta(minutes=soak_minutes)
+ expires_at = now + MAX_CHECK_HORIZON
+ else:
+ status = SignalReportCheck.Status.ACTIVE
+ assert next_run_at is not None
+ if expires_at is None:
+ expires_at = min(
+ _last_run_at(next_run_at, run_interval_minutes, runs_remaining) + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
+ now + MAX_CHECK_HORIZON,
+ )
+
+ with transaction.atomic():
+ locked_report = SignalReport.objects.select_for_update().filter(id=report.id, team_id=report.team_id).first()
+ if locked_report is None:
+ raise CheckCreationError("The report this check belongs to is gone.")
+ open_checks = SignalReportCheck.objects.for_team(locked_report.team_id).filter(
+ report_id=locked_report.id, status__in=SignalReportCheck.OPEN_STATUSES
+ )
+ if open_checks.count() >= MAX_ACTIVE_CHECKS_PER_REPORT:
+ raise CheckCreationError(f"A report may carry at most {MAX_ACTIVE_CHECKS_PER_REPORT} active checks.")
+ check = SignalReportCheck.objects.for_team(locked_report.team_id).create(
+ # The report's own environment team, never a canonicalized one: the report's reads and
+ # its artefact log filter by it.
+ team_id=locked_report.team_id,
+ report_id=locked_report.id,
+ title=title,
+ rationale=rationale,
+ kind=kind,
+ config=stored_config,
+ status=status,
+ next_run_at=next_run_at,
+ soak_minutes=soak_minutes,
+ run_interval_minutes=run_interval_minutes,
+ runs_remaining=runs_remaining,
+ expires_at=expires_at,
+ actor_kind=attribution.kind,
+ actor_agent=attribution.agent_name,
+ created_by_id=attribution.user_id,
+ task_id=attribution.task_id,
+ )
+ # Reported from the shared write so every author is counted: the REST endpoint, the scout
+ # tool and the research pipeline. Post-commit, so a check the cap or a rollback rejected is
+ # never counted as written.
+ transaction.on_commit(partial(capture_report_check_created, report.team, check))
+ return check
+
+
+def create_checks_from_specs(
+ *,
+ report: SignalReport,
+ specs: list[CheckSpec],
+ attribution: ArtefactAttribution,
+) -> list[SignalReportCheck]:
+ """Write a research run's check specs on the report it just finished.
+
+ The specs replace the report's pending checks rather than joining them. Only research writes a
+ pending check, so every pending row came from an earlier pass over an older version of this
+ report. Left in place, those rows would fill the per-report cap, and the resolve would arm them
+ against prose they were not written for. A pass that returns no specs leaves them alone, because
+ the verification turn is best-effort and an empty result can be a failed turn.
+
+ A spec the report cannot carry is dropped with a log rather than failing the run, the way an
+ unvalidatable chart is: the prose is the report's point, and a check that names a metric the
+ presentation turn did not keep is the model over-reaching, not a broken pipeline.
+ """
+ if not specs:
+ return []
+ SignalReportCheck.objects.for_team(report.team_id).filter(
+ report_id=report.id, status=SignalReportCheck.Status.PENDING
+ ).update(status=SignalReportCheck.Status.CANCELLED, updated_at=timezone.now())
+ written: list[SignalReportCheck] = []
+ for spec in specs:
+ try:
+ written.append(
+ create_check(
+ report=report,
+ title=spec.title,
+ rationale=spec.rationale,
+ kind=spec.kind,
+ config=spec.config,
+ attribution=attribution,
+ soak_minutes=spec.soak_hours * 60,
+ )
+ )
+ except CheckCreationError as error:
+ logger.warning(
+ "signals.report_check.research_spec_dropped",
+ report_id=str(report.id),
+ team_id=report.team_id,
+ kind=spec.kind,
+ reason=str(error),
+ )
+ return written
+
+
+def arm_pending_checks(*, team_id: int, report_id: str | uuid.UUID, resolved_at: datetime) -> int:
+ """Start the clock on a resolved report's pending checks. Returns how many were armed.
+
+ Called from the report's `post_save` receiver, so every resolve path reaches it: the pull
+ request merge webhook, a manual resolve in the inbox, and an MCP state write alike.
+
+ Each row is armed individually rather than in one UPDATE, because `next_run_at` and `expires_at`
+ are derived from the row's own soak and schedule.
+ """
+ pending = list(
+ SignalReportCheck.objects.for_team(team_id).filter(report_id=report_id, status=SignalReportCheck.Status.PENDING)
+ )
+ horizon = resolved_at + MAX_CHECK_HORIZON
+ armed = 0
+ for check in pending:
+ next_run_at = resolved_at + timedelta(minutes=check.soak_minutes or 0)
+ expires_at = min(
+ _last_run_at(next_run_at, check.run_interval_minutes, check.runs_remaining)
+ + DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
+ horizon,
+ )
+ armed += (
+ SignalReportCheck.objects.for_team(team_id)
+ .filter(id=check.id, status=SignalReportCheck.Status.PENDING)
+ .update(
+ status=SignalReportCheck.Status.ACTIVE,
+ next_run_at=next_run_at,
+ expires_at=expires_at,
+ updated_at=resolved_at,
+ )
+ )
+ return armed
+
+
+def _last_run_at(next_run_at: datetime, run_interval_minutes: int | None, runs_remaining: int) -> datetime:
+ if not run_interval_minutes:
+ return next_run_at
+ return next_run_at + timedelta(minutes=run_interval_minutes * max(0, runs_remaining - 1))
diff --git a/products/signals/backend/report_check_execution.py b/products/signals/backend/report_check_execution.py
index a8eed179a0d6..5ee00d272faf 100644
--- a/products/signals/backend/report_check_execution.py
+++ b/products/signals/backend/report_check_execution.py
@@ -16,6 +16,7 @@ a breach the same way and there is one place where "is this value out of bounds?
from __future__ import annotations
import time
+import uuid
from datetime import datetime, timedelta
from functools import partial
@@ -36,6 +37,7 @@ from posthog.schema import (
from posthog.clickhouse.query_tagging import tag_queries
from posthog.dataclasses import frozen
+from posthog.models import Team
from products.alerts.backend.facade.evaluation import (
ComparableSeries,
@@ -45,8 +47,12 @@ from products.alerts.backend.facade.evaluation import (
)
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import CheckResult
+from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportCheck
-from products.signals.backend.report_check_telemetry import capture_report_check_resolved
+from products.signals.backend.report_check_telemetry import (
+ capture_report_check_evaluated,
+ capture_report_checks_expired,
+)
from products.signals.backend.report_checks import (
MAX_CONSECUTIVE_CHECK_ERRORS,
CheckComparison,
@@ -73,6 +79,9 @@ MAX_CHECK_EXPIRIES_PER_TICK = 500
CHECK_ERROR_RETRY_AFTER = timedelta(hours=6)
# Same bound the scout runner puts on a stored failure reason.
MAX_CHECK_ERROR_REASON_LENGTH = 300
+# Weight of the signal a failed check on a resolved report emits. High enough to promote on its own:
+# a fix that stopped holding is a finding somebody already decided was worth fixing once.
+CHECK_FAILURE_SIGNAL_WEIGHT = 1.0
# A check stops running while its report is soft-deleted or suppressed, and runs again when the report
# comes back. Its horizon keeps advancing meanwhile: a check that outlives `expires_at` while paused
@@ -327,27 +336,131 @@ def record_check_verdict(
),
attribution=attribution or ArtefactAttribution.system(),
)
+ if _should_resurface(current, verdict):
+ baseline = config.baseline_value if config is not None else None
+ threshold = _describe_comparison(config.comparison) if config is not None else None
+ transaction.on_commit(lambda: resurface_failed_check(current, verdict, baseline, threshold))
# Post-commit, so a rolled-back verdict is never counted as one, and after the artefact so
# the event describes a result a reader can already see on the report. The team comes off
# the caller's row, where both call paths already select it with its organization; the
# locked row selects neither, and widening the lock to reach them would take `FOR UPDATE`
# on `Team`.
- transaction.on_commit(partial(capture_report_check_resolved, check.team, current, run_id=run_id))
+ transaction.on_commit(partial(capture_report_check_evaluated, check.team, current, run_id=run_id))
+
+
+def _should_resurface(check: SignalReportCheck, verdict: CheckVerdict) -> bool:
+ """Whether this verdict has to become a fresh report, because nothing else will carry it.
+
+ An `agent` check has a scout in the loop that can author one. A `metric_threshold` check has
+ nobody, so a breach on a report the inbox no longer lists is an artefact on a closed item that
+ no reader will open. Only a resolved report qualifies: a breach on a report still being worked
+ lands where the person working it already looks.
+ """
+ return (
+ verdict.outcome == "failed"
+ and check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD
+ and check.report.status == SignalReport.Status.RESOLVED
+ )
+
+
+def resurface_failed_check(
+ check: SignalReportCheck,
+ verdict: CheckVerdict,
+ baseline_value: float | None,
+ threshold: str | None,
+) -> None:
+ """Emit the breach as a signal, so the pipeline authors a fresh report for the relapse.
+
+ This is the same rule the grouping stage already applies to a resolved report: a signal that
+ would have joined it starts a new report linked by `related_to` rather than reopening a
+ terminal one. Best-effort — the verdict is already on the report's log, and losing the
+ re-surface must not fail the tick that recorded it.
+ """
+ from asgiref.sync import async_to_sync # noqa: PLC0415
+
+ from products.signals.backend.facade.api import emit_signal # noqa: PLC0415
+
+ report = check.report
+ description = "\n".join(
+ [
+ f"A follow-up check on a resolved report failed: {check.title}",
+ "",
+ f"Resolved report: {report.title or 'Untitled'} ({report.id})",
+ f"What the check measured: {verdict.explanation}",
+ *([f"Baseline when the check was written: {baseline_value}"] if baseline_value is not None else []),
+ *([f"Expected: {threshold}"] if threshold else []),
+ ]
+ )
+ try:
+ async_to_sync(emit_signal)(
+ team=report.team,
+ source_product=SignalSourceProduct.SIGNALS_CHECK,
+ source_type=SignalSourceType.CHECK_FAILED,
+ source_id=f"check:{check.id}",
+ description=description,
+ weight=CHECK_FAILURE_SIGNAL_WEIGHT,
+ extra={
+ "check_id": str(check.id),
+ "report_id": str(report.id),
+ "check_title": check.title,
+ "explanation": verdict.explanation,
+ "observed_value": verdict.observed_value,
+ "baseline_value": baseline_value,
+ "threshold": threshold,
+ },
+ idempotency_key=str(check.id),
+ )
+ except Exception:
+ logger.exception("signals.report_check.resurface_failed", check_id=str(check.id), team_id=check.team_id)
def expire_overdue_checks(now: datetime) -> int:
- """Retire active checks whose horizon passed without a run. Returns how many were retired."""
+ """Retire open checks whose horizon passed without a run. Returns how many were retired.
+
+ Pending rows are swept too, so a check waiting on a report that never resolves retires at the
+ horizon instead of waiting forever for a clock that will not start.
+ """
overdue = list(
- SignalReportCheck.all_teams.filter(status=SignalReportCheck.Status.ACTIVE, expires_at__lte=now).values_list(
- "id", flat=True
+ SignalReportCheck.all_teams.filter(status__in=SignalReportCheck.OPEN_STATUSES, expires_at__lte=now).values_list(
+ "id", "team_id", "last_run_at"
)[:MAX_CHECK_EXPIRIES_PER_TICK]
)
if not overdue:
return 0
- return SignalReportCheck.all_teams.filter(id__in=overdue, status=SignalReportCheck.Status.ACTIVE).update(
- status=SignalReportCheck.Status.EXPIRED, updated_at=now
- )
+ # The horizon is re-checked in the write. A report can resolve between the read and the write,
+ # which arms its pending checks and moves `expires_at` forward, and an update filtered on id and
+ # status alone would retire a check that has just been given a clock.
+ expired = SignalReportCheck.all_teams.filter(
+ id__in=[check_id for check_id, _, _ in overdue],
+ status__in=SignalReportCheck.OPEN_STATUSES,
+ expires_at__lte=now,
+ ).update(status=SignalReportCheck.Status.EXPIRED, updated_at=now)
+ if expired:
+ _report_expired_checks(overdue)
+ return expired
+
+
+def _report_expired_checks(overdue: list[tuple[uuid.UUID, int, datetime | None]]) -> None:
+ """Emit one expiry event per project for the rows a sweep selected.
+
+ Counted from the selection rather than the write, so a row armed in between is over-counted by
+ one. That is acceptable for telemetry and saves a second read of every retired row.
+ """
+ per_team: dict[int, list[datetime | None]] = {}
+ for _, team_id, last_run_at in overdue:
+ per_team.setdefault(team_id, []).append(last_run_at)
+ try:
+ teams = Team.objects.filter(id__in=per_team.keys()).select_related("organization")
+ for team in teams:
+ last_runs = per_team[team.id]
+ capture_report_checks_expired(
+ team,
+ expired_count=len(last_runs),
+ never_ran_count=sum(1 for last_run_at in last_runs if last_run_at is None),
+ )
+ except Exception:
+ logger.exception("signals.report_check.expired_report_failed")
def collect_due_checks(now: datetime, *, limit: int = MAX_CHECK_RUNS_PER_TICK) -> list[SignalReportCheck]:
diff --git a/products/signals/backend/report_check_telemetry.py b/products/signals/backend/report_check_telemetry.py
index 1cfc388a56e3..15935168182a 100644
--- a/products/signals/backend/report_check_telemetry.py
+++ b/products/signals/backend/report_check_telemetry.py
@@ -1,17 +1,15 @@
"""Adoption telemetry for the forward-looking checks attached to signal reports.
-Two events, one per end of a check's life: `signals_report_check_created` when an author schedules
-a re-measurement, and `signals_report_check_resolved` when a run records the verdict. Together they
-answer the only questions that say whether the follow-up loop is working — how many reports get a
-check at all, which kind their authors reach for, how long the soak window really is, and how often
-a claim stops holding.
-
-Both are best-effort: telemetry must never fail the write it describes, so every call swallows its
+Four events follow a check through its life. `signals_report_check_created` fires when an author
+writes one. `signals_report_check_dispatch` fires each time the coordinator tries to hand an `agent`
+check to a scout run, whether the run started or the attempt was deferred. `signals_report_check_evaluated`
+fires for each verdict a run records. `signals_report_checks_expired` fires when checks retire at
+their horizon without a verdict. Together they say how many reports get a check, which kind their
+authors reach for, how long the soak window really is, how often a claim stops holding, and where a
+check that never reported got stuck.
+
+All are best-effort: telemetry must never fail the write it describes, so every call swallows its
own errors.
-
-A check that retires unrun reports nothing here. `expire_overdue_checks` retires a batch in one
-bounded UPDATE and holds no team, so counting those would cost a query per tick for an outcome that
-is already the gap between the two events.
"""
from __future__ import annotations
@@ -62,8 +60,9 @@ def capture_report_check_created(team: Team, check: SignalReportCheck) -> None:
`hours_to_first_run` and `hours_to_expiry` are the soak window the author chose, which is the
number that says whether checks are being written for a real deploy-and-soak gap or for the
- default. A null `run_interval_minutes` is a one-shot check. Requires `team.organization` to be
- loaded.
+ default. A `pending` check has no clock yet, because it waits on its report resolving: its two
+ hour values are provisional, and `soak_minutes` is the window its author chose. A null
+ `run_interval_minutes` is a one-shot check.
"""
try:
now = timezone.now()
@@ -74,6 +73,8 @@ def capture_report_check_created(team: Team, check: SignalReportCheck) -> None:
**_identity(team, check),
"actor_kind": check.actor_kind,
"actor_agent": check.actor_agent,
+ "check_status": check.status,
+ "soak_minutes": check.soak_minutes,
"runs_remaining": check.runs_remaining,
"run_interval_minutes": check.run_interval_minutes,
"hours_to_first_run": (check.next_run_at - now).total_seconds() / 3600,
@@ -85,8 +86,8 @@ def capture_report_check_created(team: Team, check: SignalReportCheck) -> None:
logger.exception("signals.report_check.created_capture_failed", check_id=str(check.id), team_id=check.team_id)
-def capture_report_check_resolved(team: Team, check: SignalReportCheck, *, run_id: str | None = None) -> None:
- """`signals_report_check_resolved`: a run recorded a verdict on a check.
+def capture_report_check_evaluated(team: Team, check: SignalReportCheck, *, run_id: str | None = None) -> None:
+ """`signals_report_check_evaluated`: a run recorded a verdict on a check.
Emitted per verdict rather than per check, so a recurring check that keeps holding reports one
event each time it is measured. `check_status` says what the row became, so "answered, and that
@@ -98,7 +99,7 @@ def capture_report_check_resolved(team: Team, check: SignalReportCheck, *, run_i
"""
try:
posthoganalytics.capture(
- event="signals_report_check_resolved",
+ event="signals_report_check_evaluated",
distinct_id=str(team.uuid),
properties={
**_identity(team, check),
@@ -112,4 +113,54 @@ def capture_report_check_resolved(team: Team, check: SignalReportCheck, *, run_i
groups=groups(team.organization, team),
)
except Exception:
- logger.exception("signals.report_check.resolved_capture_failed", check_id=str(check.id), team_id=check.team_id)
+ logger.exception("signals.report_check.evaluated_capture_failed", check_id=str(check.id), team_id=check.team_id)
+
+
+def capture_report_check_dispatch(
+ team: Team, check: SignalReportCheck, *, outcome: str, skill_name: str | None = None, reason: str | None = None
+) -> None:
+ """`signals_report_check_dispatch`: the coordinator tried to hand an `agent` check to a scout run.
+
+ `outcome` is `dispatched` or `deferred`. A deferral carries the `reason` the fleet refused the
+ run, so a check that expires unanswered can be traced to the gate that held it. A refusal that
+ cannot clear by itself is recorded as an errored verdict instead, and reports through
+ `signals_report_check_evaluated`.
+ """
+ try:
+ posthoganalytics.capture(
+ event="signals_report_check_dispatch",
+ distinct_id=str(team.uuid),
+ properties={
+ **_identity(team, check),
+ "outcome": outcome,
+ "skill_name": skill_name,
+ "reason": reason,
+ "hours_since_created": (timezone.now() - check.created_at).total_seconds() / 3600,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.exception("signals.report_check.dispatch_capture_failed", check_id=str(check.id), team_id=check.team_id)
+
+
+def capture_report_checks_expired(team: Team, *, expired_count: int, never_ran_count: int) -> None:
+ """`signals_report_checks_expired`: checks on one project retired at their horizon.
+
+ One event per project per sweep rather than one per check, because the sweep retires rows in
+ bulk. `never_ran_count` is the part that matters: a check that expires with no run behind it
+ was written and then never looked at.
+ """
+ try:
+ posthoganalytics.capture(
+ event="signals_report_checks_expired",
+ distinct_id=str(team.uuid),
+ properties={
+ "team_id": team.id,
+ "organization_id": str(team.organization_id),
+ "expired_count": expired_count,
+ "never_ran_count": never_ran_count,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.exception("signals.report_check.expired_capture_failed", team_id=team.id)
diff --git a/products/signals/backend/report_checks.py b/products/signals/backend/report_checks.py
index e5d8385f74f1..134dcdda818f 100644
--- a/products/signals/backend/report_checks.py
+++ b/products/signals/backend/report_checks.py
@@ -9,6 +9,12 @@ The soak window is the check's own clock. A fix does not always arrive as a merg
plenty land in the skills store with nothing to date the window from — so the author says when the
check runs rather than the system reading it off a merge.
+An author who writes the check *before* the fix exists has no date to name at all. The research
+turn is the case: it writes its check while the report is still being authored. Such a check names
+a soak duration instead and is stored `pending`, and the report's own transition to `resolved`
+starts its clock — whatever caused the transition, a merged pull request, a manual resolve, or an
+MCP state write. See ``CheckSpec`` and ``report_check_authoring.arm_pending_checks``.
+
This module stays Django-free and schema-free for the same reason as ``report_metrics``: model and
Temporal payload modules import it during process setup.
"""
@@ -45,6 +51,13 @@ MAX_CHECK_INTERVAL_MINUTES = int(MAX_CHECK_HORIZON.total_seconds() // 60)
# A soak needs the fix to have been live a while. A week is the default first look; an author who
# knows the window says so.
DEFAULT_FIRST_RUN_AFTER = timedelta(days=7)
+# The soak a resolve-armed check waits out before its first run. A day is long enough for a merged
+# fix to be deployed and for a day's traffic to accumulate behind it, which is what the comparison
+# needs; an author who knows the fix is slower to reach users (a mobile release, a cached client
+# bundle) says so.
+DEFAULT_CHECK_SOAK_HOURS = 24
+MIN_CHECK_SOAK_HOURS = 1
+MAX_CHECK_SOAK_HOURS = 30 * 24
DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN = timedelta(days=30)
# A check whose query keeps failing is misconfigured, not unlucky. Three errored runs retire it so a
# broken lane stops costing a query per tick.
@@ -260,3 +273,50 @@ def parse_check_config(kind: str, config: object) -> BaseModel:
return schema.model_validate(config)
except ValidationError as error:
raise CheckConfigValidationError(str(error)) from error
+
+
+class CheckSpec(BaseModel):
+ """A check whose clock starts when its report resolves, written before any fix exists.
+
+ The research turn's shape. It authors the check in the same pass that writes the report, so
+ there is nothing to date a soak window from yet: the spec names how long to wait after the
+ report is resolved rather than a date to look on. Everything else is the REST body's own
+ vocabulary, and the config goes through the same `parse_check_config` boundary, so a spec
+ cannot express a check the endpoint would refuse.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ title: str = Field(
+ max_length=MAX_CHECK_TITLE_LENGTH,
+ description="Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.",
+ )
+ rationale: str = Field(
+ default="",
+ max_length=MAX_CHECK_RATIONALE_LENGTH,
+ description="Why the check is worth running.",
+ )
+ kind: Literal["metric_threshold", "agent"] = Field(description="How the check is evaluated.")
+ config: dict[str, Any] = Field(description="What the check measures and what the result must satisfy.")
+ soak_hours: int = Field(
+ default=DEFAULT_CHECK_SOAK_HOURS,
+ ge=MIN_CHECK_SOAK_HOURS,
+ le=MAX_CHECK_SOAK_HOURS,
+ description=(
+ "How long after the report is resolved to wait before measuring. The fix has to have "
+ f"been live a while for the result to mean anything. Defaults to {DEFAULT_CHECK_SOAK_HOURS} hours."
+ ),
+ )
+
+ @field_validator("title")
+ @classmethod
+ def title_must_say_something(cls, value: str) -> str:
+ stripped = value.strip()
+ if not stripped:
+ raise ValueError("must not be empty or whitespace-only")
+ return stripped
+
+ @model_validator(mode="after")
+ def config_must_match_its_kind(self) -> CheckSpec:
+ parse_check_config(self.kind, self.config)
+ return self
diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.py
index 5bf7265b5e65..0af600177ca3 100644
--- a/products/signals/backend/report_generation/research.py
+++ b/products/signals/backend/report_generation/research.py
@@ -26,6 +26,7 @@ from products.signals.backend.artefact_schemas import (
from products.signals.backend.pipeline_identity import AI_STAGE_RESEARCH
from products.signals.backend.report_actionability import ACTIONABILITY_CRITERIA
from products.signals.backend.report_charts import MAX_REPORT_CHARTS, WHEN_TO_CHART, ReportChart
+from products.signals.backend.report_checks import DEFAULT_CHECK_SOAK_HOURS, MAX_ACTIVE_CHECKS_PER_REPORT, CheckSpec
from products.signals.backend.report_metrics import (
DEFAULT_LIVE_METRIC_DATE_FROM,
MAX_LIVE_METRIC_QUERY_POINTS,
@@ -167,6 +168,41 @@ Hard rules:
return v
+CHECKS_GUIDANCE = """
+## Scheduling the check
+
+A verification plan nobody runs is a note. When part of the `outcome` section can be settled later
+with no person involved, also return that part as a `checks` entry, so the coordinator settles it
+after the fix has soaked instead of a person remembering to. The prose stays the plan; the check is
+its executable part.
+
+Return a check only when it meets the bar stated for its kind below, and none otherwise. A replay to
+watch, a test to run, a diff to read, or a step to perform by hand stays prose only.
+
+`soak_hours` is how long after the report is resolved to wait before checking. Default
+{default_soak} hours, which covers a deploy plus a day of traffic. Say longer when the fix only
+reaches users slowly — a mobile release, a cached client bundle, a weekly batch.
+"""
+
+_METRIC_CHECK_GUIDANCE = """- Use `kind: "metric_threshold"` when the `outcome` section comes down to one number a query can
+ measure: a rate that should drop, a count that should stay under a bound, a latency that should
+ come back down. All three of these must hold. The `outcome` section names one metric, one baseline
+ you actually measured this session, and one comparison that decides the question. The comparison
+ is a bound a number either satisfies or does not: at most X, at least X, or between X and Y. The
+ measurement is a query. Do not invent a baseline or a threshold: if the session did not establish
+ one, return no metric check. The `config` is
+ `{{"metric_id": "<one of this report's metrics>", "comparison": {{"operator": "lte", "value": 10}},
+ "baseline_value": <what you measured now>}}`. The `metric_id` must name a metric you returned in
+ the presentation turn, so the check rides a query this report already shows. A spec naming
+ anything else is dropped."""
+
+_AGENT_CHECK_GUIDANCE = """- Use `kind: "agent"` when no single number settles the claim but a later run can establish it by
+ reading the project's data, such as re-reading an error issue's recent events. It needs no metric,
+ baseline, or comparison. The `config` is
+ `{{"instructions": "<what a later run must establish>", "probe_hints": ["<issue id>", "<service>"]}}`.
+ Say in `instructions` what result means the fix held and what result means it did not."""
+
+
class FixVerificationOutput(BaseModel):
"""Session output for the final, actionable-only fix verification turn."""
@@ -182,6 +218,15 @@ class FixVerificationOutput(BaseModel):
"collect, the result that supports a conclusion, and the result that is inconclusive."
),
)
+ checks: list[CheckSpec] = Field(
+ default_factory=list,
+ max_length=MAX_ACTIVE_CHECKS_PER_REPORT,
+ description=(
+ "The executable part of the outcome plan, scheduled rather than written down. Empty whenever the "
+ "plan's method is a replay, a test, a code review, or a manual step, and whenever the session "
+ "established no baseline and no threshold."
+ ),
+ )
@field_validator("current_state", "outcome")
@classmethod
@@ -191,12 +236,39 @@ class FixVerificationOutput(BaseModel):
raise ValueError("Verification plan sections must not be empty")
return section
+ @field_validator("checks", mode="before")
+ @classmethod
+ def drop_checks_that_do_not_validate(cls, v: object) -> object:
+ # Same trade as the presentation turn's charts: the plan is this turn's point, so one
+ # malformed spec costs that spec rather than the whole verification note. The rejected
+ # content is never logged, only the failing fields and rules.
+ if not isinstance(v, list):
+ return v
+ kept: list[CheckSpec] = []
+ for index, entry in enumerate(v):
+ try:
+ kept.append(CheckSpec.model_validate(entry))
+ except Exception as e:
+ logger.warning(
+ "fix_verification: dropped check at index %d that did not validate (%s)",
+ index,
+ _rejection_reason(e),
+ )
+ return kept
+
def to_note(self) -> NoteArtefact:
+ # The check is named in the note on purpose: the plan and the check are one thing in the
+ # report's timeline, and a reader who sees only the prose would go and re-measure by hand.
+ scheduled = "".join(
+ f"\n\n_Scheduled as a follow-up check: **{check.title}**, measured "
+ f"{check.soak_hours} hours after this report is resolved._"
+ for check in self.checks
+ )
return NoteArtefact(
note=(
f"## Verification plan\n\n"
f"### Confirm the current state\n\n{self.current_state}\n\n"
- f"### Confirm the outcome\n\n{self.outcome}"
+ f"### Confirm the outcome\n\n{self.outcome}{scheduled}"
)
)
@@ -233,6 +305,14 @@ class ReportResearchOutput(BaseModel):
"Present only when the report is actionable."
),
)
+ checks: list[CheckSpec] = Field(
+ default_factory=list,
+ description=(
+ "The executable part of the verification plan, written as `SignalReportCheck` rows alongside the "
+ "title, summary, charts and metrics. Each is stored `pending` and armed when the report resolves, "
+ "because the plan predates the fix it checks."
+ ),
+ )
# The run's findings and assessments split by whether they changed: `old_artefacts` were
# confirmed unchanged (already persisted — a re-research reusing them writes nothing) and
# `new_artefacts` were produced or changed this run (persisted unconditionally). The report's
@@ -872,9 +952,37 @@ Respond with a JSON object matching this schema:
</jsonschema>"""
-def build_fix_verification_prompt() -> str:
- """Build the final follow-up for actionable reports after all research and presentation work."""
- schema = json.dumps(FixVerificationOutput.model_json_schema(), indent=2)
+def build_fix_verification_prompt(*, metric_checks_enabled: bool = False, agent_checks_enabled: bool = False) -> str:
+ """Build the final follow-up for actionable reports after all research and presentation work.
+
+ The two flags decide whether this turn may schedule its plan as well as write it, and are
+ resolved per team: `metric_threshold` needs the report metrics rollout, because the check rides a
+ metric this report already shows, and `agent` needs the team enrolled in scouts, because nothing
+ would ever run a check with no fleet behind it. With neither, the turn writes prose only and the
+ `checks` field never reaches the schema, so the model is not offered a channel it cannot use.
+ """
+ schema_dict = FixVerificationOutput.model_json_schema()
+ kinds = [
+ guidance
+ for guidance, enabled in (
+ (_METRIC_CHECK_GUIDANCE, metric_checks_enabled),
+ (_AGENT_CHECK_GUIDANCE, agent_checks_enabled),
+ )
+ if enabled
+ ]
+ if not kinds:
+ schema_dict.get("properties", {}).pop("checks", None)
+ for definition in ("CheckSpec", "MetricThresholdConfig", "AgentCheckConfig"):
+ schema_dict.get("$defs", {}).pop(definition, None)
+ checks_section = (
+ "\n\n"
+ + CHECKS_GUIDANCE.format(default_soak=DEFAULT_CHECK_SOAK_HOURS).strip()
+ + "\n\n"
+ + "\n".join(kind.format() for kind in kinds)
+ if kinds
+ else ""
+ )
+ schema = json.dumps(schema_dict, indent=2)
return f"""As the final step, write the **verification plan** for this actionable report.
Base the plan only on the evidence and successful checks from this research session. Do not do more research in this turn. Do not prescribe a resolution or claim that one exists.
@@ -896,7 +1004,7 @@ State the observed baseline and comparison criterion when the research establish
- Do not invent tool arguments, IDs, events, baselines, or numerical thresholds. If a required input or success criterion is unknown, name it and say what must be established before drawing a conclusion.
-Do not include implementation instructions.
+Do not include implementation instructions.{checks_section}
Respond with a JSON object matching this schema. The pipeline will format it as a note with the heading `Verification plan`:
@@ -976,6 +1084,7 @@ async def run_multi_turn_research(
resolved_report_title: str | None = None,
resolved_report_summary: str | None = None,
metrics_enabled: bool = False,
+ agent_checks_enabled: bool = False,
steering_section: str = "",
implementation_context: ImplementationResearchContext = NO_IMPLEMENTATION_CONTEXT,
) -> ReportResearchOutput:
@@ -1156,10 +1265,16 @@ async def run_multi_turn_research(
output_fn(f"Report title: {presentation_result.title}")
verification_note: NoteArtefact | None = None
+ checks: list[CheckSpec] = []
if actionability_result.actionability != ActionabilityChoice.NOT_ACTIONABLE:
if output_fn:
output_fn("Generating fix verification steps...")
- verification_prompt = build_fix_verification_prompt()
+ verification_prompt = build_fix_verification_prompt(
+ # A `metric_threshold` check references one of the report's own metrics, so the
+ # metrics rollout is what makes that kind available at all.
+ metric_checks_enabled=metrics_enabled,
+ agent_checks_enabled=agent_checks_enabled,
+ )
try:
verification_result = await session.send_followup(
verification_prompt,
@@ -1167,6 +1282,7 @@ async def run_multi_turn_research(
label="fix_verification",
)
verification_note = verification_result.to_note()
+ checks = list(verification_result.checks)
except Exception:
logger.exception(
"multi_turn_research: failed to generate fix verification note",
@@ -1240,6 +1356,7 @@ async def run_multi_turn_research(
metrics=presentation_result.metrics if metrics_enabled else [],
research_task_id=str(session.task.id),
verification_note=verification_note,
+ checks=checks,
old_artefacts=old_artefacts,
new_artefacts=new_artefacts,
)
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index ac720101d900..896f2d8ecc7d 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -54,6 +54,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
- `notes.py` — `list_notes` / `leave_note` / `delete_note` backed by the `SignalScoutNote` model: steering notes humans (or other agents) leave for the fleet over the public MCP surface (`scout-notes-*` tools), the inbound counterpart to the scratchpad. A note targets one scout by `skill_name` or the whole fleet (blank), optionally expiring via `expires_at`; the run prompt's _Notes left for you_ section directs every scout to `scout-notes-list` its own notes in step 1 and treat them as advisory steering. A third audience is a stage of the report pipeline, addressed through the reserved `pipeline:*` family (`PIPELINE_AUDIENCES`, holding `pipeline:report-research` today): a pseudo-target riding the same `skill_name` column, allowlisted at write time so an unrecognized one is rejected instead of silently steering no one, and skipping the scout-skill lookup because a stage has no `LLMSkill` row. `list_notes` matches `skill_name` exactly, so no scout ever sees a pipeline note; the research loader in `../report_steering.py` reads `pipeline:report-research` alongside the report's scout target and the fleet-wide blanks. `validate_note_target`, the shared write-time rule, and the audience constants live in `../note_targets.py`, an import-light module, because the Django admin form calls the rule at registry load and importing anything under `tools/` runs that package's `__init__`, which pulls in every harness tool. Unlike the scratchpad there is no sandbox-only write gate, but writes still demand skill-authoring-level authorization (keys need `llm_skill:write` on top of `signal_scout:write`, and every writer must clear the `llm_skill` RBAC editor bar) — so a note-writer could already steer the fleet by editing its skills, and notes add no new steering power. Four more writers derive rows from inbox activity. `../dismissal_notes.py`: judging an inbox report with a note (dismiss, snooze, or restore) also leaves it here as an `origin=report_dismissal` note, targeted at the scout that authored the report, so a reviewer's verdict reaches the scout without it having to re-find the report. Resolving does not, since that says the report did its job rather than that filing it was wrong. `../discussion_notes.py`: opening a discussion on a report (the inbox "Discuss" action, which kicks off a Q&A task) also leaves the user's question here as an `origin=report_discussion` note, targeted at the authoring scout — framed as context to weigh or ignore, not a verdict, so the scout can fold a durable preference/correction into its scratchpad or dismiss it as noise. `../feedback_notes.py`: the thumbs rating at the end of a report body ("Was this report useful?") carries its optional note here as an `origin=report_feedback` note, targeted at the authoring scout. Unlike a dismissal it never falls back to a fleet-wide note — feedback is a verdict on one scout's own report, so with no resolvable authoring scout nothing is forwarded and the call is a no-op — and it never changes the report's state; the analytics event the client fires stays the durable record of the rating. `../reviewer_correction_notes.py`: a user-attributed reviewer edit that changes the set (adding or removing a suggested reviewer) also leaves an `origin=report_reviewer_correction` note, and it is the only derived origin addressed to more than one scout — every live scout that emitted or edited the report (`resolve_touching_scout_skills`, since an editing scout may be the one that put the reviewers there) plus every scout whose `reviewer:` memory names a removed login (`_memory_holders`, one exact-term search under the `reviewer:` key prefix), ordered emitting scout first and capped at `MAX_NOTE_TARGETS`, so a scout still routing on a stale login hears about the correction. A report no live scout touched falls back to the fleet-wide blank dismissals use, but only when no holder resolved, since a run reads the fleet-wide notes alongside its own and a holder would hear the same edit twice. An impersonated edit forwards nothing, matching the reviewer-corrections project profile, which excludes impersonated activity rows for the same reason. Logins are shape-checked against GitHub's login rule before rendering and capped per edit (`MAX_CORRECTION_LOGINS`), because both write paths into the reviewers artefact accept any string of any length and the value lands in a backtick span every scout reads. Repeated edits coalesce: a login already sent to a target in the same direction inside `SUPPRESSION_WINDOW` is left out of the next note, keyed on direction so a removal still corrects an addition made hours earlier. Like a dismissal it may fall back fleet-wide, and unlike discuss/feedback it does not demand the `signal_scout:write` / `llm_skill:write` key scopes, because the logins already reach scouts through the report's reviewers artefact and the project profile. All four paths re-check the same steering gate (token `scoped_teams`, canonical-project access, and the `llm_skill` editor bar) since the dismiss, discuss, feedback, and reviewer-edit actions need only `task:write`, and all forward only on the canonical team. The discuss and feedback paths additionally demand the `signal_scout:write` / `llm_skill:write` key scopes: a dismissal's text reaches runs anyway through the reports API, whereas the note is the only path a discussion question or feedback note takes to a scout, so a `task:write` credential must not open it alone. The discuss path is triggered from the tasks viewset (which holds the request the gate reads) through `facade/api.py:forward_report_discussion_note`, never from the tasks facade. On the read side, every derived origin quotes report content (report id, title, the note text), so `SignalScoutNoteViewSet.list` withholds them from any caller failing the reports read gate (`_may_read_reports`); both that gate and `../report_steering.py` read the list off `SignalScoutNote.derived_origins()` rather than naming the kinds, so a newly added origin is withheld from the moment it exists. The derived rows are context with a TTL; the `dismissal` artefact / discussion task / feedback analytics event / reviewer `suggested_reviewers` artefact + `suggested_reviewers_changed` activity-log row stays the record of truth. Notes reach two surfaces outside the fleet, both through `../report_steering.py`. `load_report_steering` renders the `HUMAN`-origin ones into the description of the self-driving implementation task, so steering that used to stop at the scout also reaches the run that writes the code; the derived origins are withheld there for the reason the read gate withholds them — they quote report content, which is built from raw product data, and that run can open a PR. `load_research_steering` renders every origin into the pipeline's report-research prompt, because the derived ones are feedback on exactly the judgment that stage is about to make; that run is read-only, already holds the report's raw signals, and writes back only to the report on the same team.
- `structured_output.py` — `record_structured_output` (+ `_sync`): the structured-output channel, next to signals and reports. Opt-in via `SignalScoutConfig.structured_output_schema` (a JSON Schema describing ONE record, validated at config-write time by `validate_structured_output_schema` — which also rejects non-local `$ref`/`$dynamicRef`, and every validator here uses a no-retrieval registry, so a user-controlled schema can never make the worker fetch a URL; null = channel off, and the record endpoint fails closed). Setting the schema is skill-authoring-level steering (schema `description` fields are free prose rendered verbatim into a privileged prompt), so the config viewset gates it behind `llm_skill:write` + the `llm_skill` editor bar, like scout notes; clearing it stays on the base config scope. Records validate against the dispatch-time schema snapshot the runner stamps on the run row (`metadata["structured_output_schema"]`), so a mid-run schema edit can't reject records matching what the run was shown — while clearing the config schema mid-run still fails the channel closed (re-checked inside the capacity-reservation transaction with the config row locked, so a clear racing a submit serializes cleanly). Each submitted record is validated against the schema (all-or-nothing per call — an invalid record fails the batch with nothing written) and written into the team's own project as a `$scout_structured_output` event via one `capture_batch_internal` call (person processing off, deterministic uuid over `(run, batch index, subject, payload)` so a resubmitted batch collapses at ingestion while in-batch duplicates stay distinct). The events ARE the record — there is no Postgres row store, so past records are read like any events (insights, HogQL) and retention follows event retention — which is also why a delivery failure fails the call (`StructuredOutputDeliveryError` → 503) with an instruction to retry — the events carry a stable timestamp (the run's `created_at`) alongside the deterministic uuid, so the dedupe sorting key (`toDate(timestamp)` is part of it) stays identical across retries even past UTC midnight — and why the channel fails loudly for a dry-run `emit=False` scout, an org without AI-processing consent (mirroring `emit._preflight_emit_gates`), or a disabled `signals_scout` source instead of suppressing quietly (the runner also withholds the prompt section and schema snapshot when `emit` is off). Cardinality is the scout's call — the schema describes one record; a run may submit one, one per judged entity, or a batch (caps: `MAX_RECORDS_PER_CALL` per call, `MAX_RECORDS_PER_RUN` per run via the `structured_output_count` counter on `run.metadata`, reserved under the run-row lock before the forward — it counts accepted batches, so failed or retried forwards still spend cap). The prompt renders the exact configured schema in a per-run `# Structured output` section only when the channel is live, so the prompt and the validator can never describe two different contracts.
- `checks.py` — `record_check_result`: the only way a scout run closes the report check it was dispatched to answer (`agent`-kind `SignalReportCheck`, dispatched by `../report_check_agent.py` with `triggered_by="check"`). The verdict goes through the check executor's own funnel (`../report_check_execution.record_check_verdict`), so an agent result advances or retires its check by the same rules a measured one does, and lands on the report as a `check_result` artefact attributed to the run's task. Binding is what keeps the tool narrow: it admits only a check whose resolved lane is this run's own skill and that is still waiting on a dispatch (`dispatched_at` set), so the widest thing a run can do is answer the question it was asked. Deliberately NOT gated on `allowed_tools` like the report channel — the dispatch binding is the gate, so the fallback lane needs no frontmatter change to answer a check. A run that never calls it leaves the check stamped, and the coordinator records an errored result once the result window passes.
+ The same module holds the authoring tools — `create_report_check` / `list_report_checks` / `cancel_report_check`, exposed as `scout-report-check-create` / `-list` / `-cancel` — which are the other direction: a run that surfaces something whose fix will show in data writes the re-measurement down instead of leaving a note for a future run to find. They write through `../report_check_authoring.create_check`, the one place a check row is written, so a scout-written check obeys the same per-report cap, the same metric-query copy, and the same bounds as one written through the REST endpoint, and is attributed to the run's task like every other scout write. Unlike `record_check_result` these ARE gated on the report channel (`signal_scout_report:write` plus the `edit_report` `allowed_tools` opt-in, through `_resolve_in_progress_run`), because a check is a write on a report rather than an answer to a question the coordinator already asked. Their actions resolve the run through `_resolve_own_in_progress_run`, which also refuses a sandbox token minted for a different run, and create and cancel pass `_preflight_emit_gates` first, so a dry-run scout writes no check.
- `profile.py` — `project_profile_*` tools that read the deterministic `SignalProjectProfile` snapshot.
- `runs.py` — `runs_*` tools that read past `SignalScoutRun` rows for dedupe and cross-skill awareness.
- `profile/`
@@ -75,7 +76,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
`seed_config_layers_for_team()` lets the on-demand `sync` endpoint seed the same launch posture.
- `derived_metadata.py`
Computes the `metadata["derived"]` region on the run row at finalize: booleans the harness reads back off the run's own settled output (`has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, `has_self_validation`). Deliberately server-derived rather than scout-reported, so a flag can't be omitted or contradicted by the model, and computed in one place at finalize rather than stamped incrementally at each emit/edit site.
- `has_self_improvement` classifies authored report titles through `tools/report.is_self_improvement_title`, the same predicate the lifecycle events use, so the run row and the event stream can never disagree. `has_self_validation` reads the run window against the skill-namespaced `followup:` scratchpad keys, since working that queue means writing to it.
+ `has_self_improvement` classifies authored report titles through `tools/report.is_self_improvement_title`, the same predicate the lifecycle events use, so the run row and the event stream can never disagree. `has_self_validation` reads both follow-up mechanisms: a report check the run's task created or recorded a verdict on, or the run window against the skill-namespaced `followup:` scratchpad keys, since working that queue means writing to it. Creating a check counts where creating a queue entry does not, because a check is the validation being scheduled rather than a note asking a future run to do it. The field name stays put while scouts move from the queue onto checks, so dashboards built on it keep meaning "a run that checked whether a past fix held".
- `run_costs.py`
What a run spent on model calls, for the staff-only cost readout in the roster's run tooltips.
A scout run is a Tasks run, so its `$ai_generation` events land in the internal AI observability project stamped with `task_origin_product = 'signals_scout'` and the run's `task_run_id`; the sum per run comes from `tasks.facade.billing.get_local_task_run_token_costs`, which is keyed on the origin product rather than on `ai_product` — scout runs report `ai_product = 'signals_scout'`, so the desktop read's `posthog_code` filter priced every one of them at zero, and a report's pipeline stages report a different value per stage again.
diff --git a/products/signals/backend/scout_harness/derived_metadata.py b/products/signals/backend/scout_harness/derived_metadata.py
index 5bcfbdfaac70..330360462af5 100644
--- a/products/signals/backend/scout_harness/derived_metadata.py
+++ b/products/signals/backend/scout_harness/derived_metadata.py
@@ -24,7 +24,13 @@ from typing import Any
from django.db import transaction
-from products.signals.backend.models import SignalReport, SignalScoutRun, SignalScratchpad
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportCheck,
+ SignalScoutRun,
+ SignalScratchpad,
+)
from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIX
from products.signals.backend.scout_harness.tools.report import is_self_improvement_title
from products.signals.backend.scout_harness.tools.structured_output import STRUCTURED_OUTPUT_COUNT_KEY
@@ -69,7 +75,7 @@ def build_derived_flags(*, run: SignalScoutRun, team_id: int) -> dict[str, bool]
# counted, which needs run-attributed chart provenance rather than a wider query here.
"has_self_improvement": any(is_self_improvement_title(title) for title in authored_titles),
"has_chart": any(charts for charts in authored_charts),
- "has_self_validation": _touched_followup_queue(run=run, team_id=team_id),
+ "has_self_validation": _closed_a_loop(run=run, team_id=team_id),
# The record endpoint bumps this counter on the run row under lock, so it's a
# server-side observation, not a scout self-report. It counts accepted batches —
# a batch whose event delivery then failed still registers here, which the
@@ -92,6 +98,37 @@ def _authored_report_facts(*, team_id: int, report_ids: list[str]) -> tuple[list
return titles, charts
+def _closed_a_loop(*, run: SignalScoutRun, team_id: int) -> bool:
+ """Whether this run did follow-up work: report checks, or the scratchpad queue that predates them.
+
+ Two mechanisms answer the same question, so the flag reads both and the field name stays put:
+ dashboards built on `has_self_validation` keep meaning "a run that checked whether a past fix
+ held" while scouts move from the scratchpad queue onto checks. Creating a check counts, unlike
+ creating a queue entry, because a check is the validation being scheduled rather than a note
+ asking a future run to do it.
+ """
+ return _wrote_a_check(run=run, team_id=team_id) or _touched_followup_queue(run=run, team_id=team_id)
+
+
+def _wrote_a_check(*, run: SignalScoutRun, team_id: int) -> bool:
+ """Whether the run created a report check or recorded a verdict on one.
+
+ Both are attributed to the run's task, the way every other artefact a scout writes is, so the
+ task is what identifies the run's check work. The lookups are unscoped by team on purpose: a
+ check and its result sit on the report's own environment team, while `team_id` here is the
+ canonical project the run was resolved on, and the task id is already this run's own.
+ """
+ task_id = run.task_run.task_id if run.task_run_id else None
+ if task_id is None:
+ return False
+ return (
+ SignalReportCheck.all_teams.filter(task_id=task_id).exists()
+ or SignalReportArtefact.objects.filter(
+ type=SignalReportArtefact.ArtefactType.CHECK_RESULT, task_id=task_id
+ ).exists()
+ )
+
+
def _touched_followup_queue(*, run: SignalScoutRun, team_id: int) -> bool:
"""Whether this run wrote to its own self-validation follow-up queue.
diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.py
index 94e3ebba7fc5..16e47c75ff89 100644
--- a/products/signals/backend/scout_harness/prompt.py
+++ b/products/signals/backend/scout_harness/prompt.py
@@ -287,7 +287,7 @@ If the `scout_fleet` roster shows `signals-scout-inbox-validation` running here
# about scope like the re-surface clause: it is about having a report to hang a check on. A
# signal-channel scout holds a finding id and no report, so it keeps the scratchpad queue as its
# whole loop.
-_FOLLOWUP_CHECK_ON_REPORT = """- **A follow-up that hangs on a report belongs on the report.** A scratchpad entry is yours alone, so a run that never comes back to it leaves the loop open and nobody else can see that it is open. When the expectation sits on a report — one you authored, or one that covers your finding — write it onto the report with `inbox-report-checks-create` and let the coordinator do the re-measuring. A check carries the same expectation, probe, and validate-after date the entry above holds. Choose `metric_threshold` when one number settles the claim, and the coordinator measures it with no run at all. Choose `agent` when the claim needs investigating, and a run is dispatched to answer it later. Either way the verdict lands on the report where a person reads it. Read `inbox-report-checks-list` before you add one, since a report carries at most 5 active checks and a sibling may already watch your claim. Keep a scratchpad entry for what no report covers, and name the check id in the entry when you write both, so you never re-measure what the coordinator already measured.
+_FOLLOWUP_CHECK_ON_REPORT = """- **A follow-up that hangs on a report belongs on the report.** A scratchpad entry is yours alone, so a run that never comes back to it leaves the loop open and nobody else can see that it is open. When the expectation sits on a report — one you authored, or one that covers your finding — write it onto the report with `scout-report-check-create` and let the coordinator do the re-measuring. A check carries the same expectation, probe, and validate-after date the entry above holds. Choose `metric_threshold` when one number settles the claim, and the coordinator measures it with no run at all. Choose `agent` when the claim needs investigating, and a run is dispatched to answer it later. Either way the verdict lands on the report where a person reads it. Read `scout-report-check-list` before you add one, since a report carries at most 5 open checks and a sibling may already watch your claim. Keep a scratchpad entry for what no report covers, and name the check id in the entry when you write both, so you never re-measure what the coordinator already measured.
"""
_FOLLOWUP_RESURFACE_SIGNAL = (
@@ -322,8 +322,8 @@ _FOLLOWUP_RESURFACE_EDIT_ONLY = (
def _self_validation_followups_section(*, report_channel: bool, can_emit_report: bool, can_edit_report: bool) -> str:
"""Compose the self-validation follow-ups section with the clauses matched to the tools the scout
actually holds — an emit-only scout is never pointed at `scout-edit-report` and vice versa, and
- only a report-channel scout is pointed at a report check, mirroring the fail-closed gating of the
- channel sections."""
+ only a scout holding `edit_report` is pointed at a report check, because the check endpoints fail
+ closed on that tool, mirroring the fail-closed gating of the channel sections."""
if not report_channel:
clause = _FOLLOWUP_RESURFACE_SIGNAL
elif can_emit_report and can_edit_report:
@@ -334,7 +334,7 @@ def _self_validation_followups_section(*, report_channel: bool, can_emit_report:
clause = _FOLLOWUP_RESURFACE_EDIT_ONLY
return _SELF_VALIDATION_FOLLOWUPS_TEMPLATE.format(
resurface_clause=clause,
- check_clause=_FOLLOWUP_CHECK_ON_REPORT if report_channel else "",
+ check_clause=_FOLLOWUP_CHECK_ON_REPORT if report_channel and can_edit_report else "",
)
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 71c0d326df16..a5212eb46e32 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -83,7 +83,11 @@ from products.signals.backend.scout_harness.tools.structured_output import (
StructuredOutputSchemaError,
validate_structured_output_schema,
)
-from products.signals.backend.serializers import ReportChartSerializer, ReportMetricWriteSerializer
+from products.signals.backend.serializers import (
+ ReportChartSerializer,
+ ReportMetricWriteSerializer,
+ SignalReportCheckWriteSerializer,
+)
from products.skills.backend.api.skill_serializers import (
MAX_SKILL_FILE_COUNT,
SPEC_DESCRIPTION_MAX_LENGTH,
@@ -735,6 +739,47 @@ class RecordCheckResultResponseSerializer(serializers.Serializer):
runs_remaining = serializers.IntegerField(help_text="Evaluations the check still owes after this one.")
+class CreateReportCheckRequestSerializer(SignalReportCheckWriteSerializer):
+ """Request body for `scout-report-check-create`: one forward-looking check on a report.
+
+ The REST body plus the report it attaches to. Subclassed rather than restated so the schedule
+ bounds a scout writes under are the ones the endpoint enforces, with no second copy to drift.
+ """
+
+ report_id = serializers.UUIDField(help_text="The report the check attaches to.")
+
+
+class CancelReportCheckRequestSerializer(serializers.Serializer):
+ """Request body for `scout-report-check-cancel`."""
+
+ check_id = serializers.UUIDField(help_text="The check to stop. Its recorded results stay on the report.")
+
+
+class ListReportChecksQuerySerializer(serializers.Serializer):
+ """Query for `scout-report-check-list`."""
+
+ report_id = serializers.UUIDField(help_text="The report whose checks to list.")
+
+
+class ScoutCheckSummarySerializer(serializers.Serializer):
+ """One check as a scout run reads it back."""
+
+ check_id = serializers.UUIDField(help_text="The check.")
+ report_id = serializers.UUIDField(help_text="The report it is attached to.")
+ title = serializers.CharField(help_text="The expectation the check states.")
+ kind = serializers.CharField(help_text="`metric_threshold` (the coordinator measures it) or `agent` (a run does).")
+ status = serializers.CharField(
+ help_text=(
+ "`pending` while the check waits for the report to resolve, `active` while it still runs; "
+ "every other value is terminal."
+ )
+ )
+ next_run_at = serializers.DateTimeField(help_text="When the check next runs. Provisional while it is `pending`.")
+ last_outcome = serializers.CharField(
+ allow_null=True, help_text="Verdict of the most recent run; null before the first."
+ )
+
+
class FleetFindingsSummarySerializer(serializers.Serializer):
"""Fleet-wide tally of recent scout output — legacy `emit_signal` findings plus reports
authored/edited via the report channel. Backs the "Scout findings" callout so it renders
diff --git a/products/signals/backend/scout_harness/tools/__init__.py b/products/signals/backend/scout_harness/tools/__init__.py
index 92fb9f07397a..33c574d1c72f 100644
--- a/products/signals/backend/scout_harness/tools/__init__.py
+++ b/products/signals/backend/scout_harness/tools/__init__.py
@@ -7,8 +7,14 @@ sandbox. Each tool is team-scoped and Postgres-backed.
from products.signals.backend.scout_harness.tools.checks import (
MAX_CHECK_EXPLANATION_LENGTH,
+ MAX_CHECKS_LISTED,
InvalidCheckResultError,
+ InvalidCheckWriteError,
RecordCheckResultResult,
+ ScoutCheckSummary,
+ cancel_report_check,
+ create_report_check,
+ list_report_checks,
record_check_result,
)
from products.signals.backend.scout_harness.tools.emit import (
@@ -149,6 +155,12 @@ __all__ = [
"list_notes",
"normalize_tags",
"record_check_result",
+ "MAX_CHECKS_LISTED",
+ "InvalidCheckWriteError",
+ "ScoutCheckSummary",
+ "cancel_report_check",
+ "create_report_check",
+ "list_report_checks",
"record_structured_output",
"record_structured_output_sync",
"remember",
diff --git a/products/signals/backend/scout_harness/tools/checks.py b/products/signals/backend/scout_harness/tools/checks.py
index 7b1fe89c8dff..a55ecffa0260 100644
--- a/products/signals/backend/scout_harness/tools/checks.py
+++ b/products/signals/backend/scout_harness/tools/checks.py
@@ -1,5 +1,6 @@
-"""`scout-check-record-result`: the one way a scout run closes the report check it was sent to answer.
+"""The report-check tools a scout run holds: author one, read a report's, cancel one, close one.
+`scout-check-record-result` is the one way a run closes the check it was dispatched to answer.
An `agent` check is dispatched as a scout run and stays open until this tool is called. Nothing
else closes it: the coordinator does not read the run's summary, and an agent that investigates and
then says nothing leaves a check its report can see is unanswered. That is deliberate. A verdict is
@@ -8,29 +9,47 @@ a claim recorded on the report, so it has to be a claim the run made on purpose.
The binding is what keeps the tool narrow. A run may only close a check that its own lane was
dispatched for and that is still waiting on a dispatch, so the broadest thing a compromised or
confused run can do is answer the question it was actually asked.
+
+The authoring tools are the other direction: a run that surfaces something whose fix will show in
+data writes the re-measurement down instead of leaving a note for a future run to find. They write
+through `report_check_authoring`, so a scout-written check is the same row the REST endpoint writes
+and obeys the same cap, the same metric-query copy, and the same bounds. Both are gated on the
+report channel, because a check is a write on a report.
"""
from __future__ import annotations
import uuid
+from datetime import datetime
+
+from django.db.models.functions import Coalesce
+from django.utils import timezone
from posthog.dataclasses import frozen
from posthog.models import Team
from products.signals.backend.artefact_attribution import ArtefactAttribution
-from products.signals.backend.models import SignalReportCheck, SignalScoutRun
+from products.signals.backend.models import SignalReport, SignalReportCheck, SignalScoutRun
from products.signals.backend.report_check_agent import resolve_check_skill_name
+from products.signals.backend.report_check_authoring import CheckCreationError, create_check
from products.signals.backend.report_check_execution import CheckVerdict, record_check_verdict
from products.signals.backend.report_checks import AgentCheckConfig, parse_check_config
-from products.signals.backend.scout_harness.tools.emit import _resolve_task_id
+from products.signals.backend.scout_harness.tools.emit import _preflight_emit_gates, _resolve_task_id
MAX_CHECK_EXPLANATION_LENGTH = 1_000
+# Rows one `scout-report-check-list` call returns. A report carries at most five open checks, so
+# this only bounds the terminal ones a long-lived report accumulates.
+MAX_CHECKS_LISTED = 50
class InvalidCheckResultError(ValueError):
"""A result a run may not record: an unknown check, someone else's, or one nothing is waiting on."""
+class InvalidCheckWriteError(ValueError):
+ """A check a run may not write, read, or cancel: an unknown report, or one outside its project."""
+
+
@frozen
class RecordCheckResultResult:
check_id: str
@@ -118,3 +137,141 @@ def record_check_result(
check_status=check.status,
runs_remaining=check.runs_remaining,
)
+
+
+@frozen
+class ScoutCheckSummary:
+ """One check, as a scout run reads it back."""
+
+ check_id: str
+ report_id: str
+ title: str
+ kind: str
+ status: str
+ next_run_at: datetime
+ last_outcome: str | None
+
+
+def _summarize(check: SignalReportCheck) -> ScoutCheckSummary:
+ return ScoutCheckSummary(
+ check_id=str(check.id),
+ report_id=str(check.report_id),
+ title=check.title,
+ kind=check.kind,
+ status=check.status,
+ # Provisional on a pending check, whose clock the report's resolve starts.
+ next_run_at=check.next_run_at,
+ last_outcome=check.last_outcome,
+ )
+
+
+def _assert_run_may_write_checks(team: Team, run: SignalScoutRun) -> None:
+ """Refuse a check write from a run whose other write channels are closed.
+
+ A check is durable and later runs a query or starts a scout, so it follows the rule signals,
+ reports and structured output follow: a dry-run scout previews what it would do and changes
+ nothing, and a project without AI-processing consent gets no agent output.
+ """
+ skipped_reason = _preflight_emit_gates(team, run)
+ if skipped_reason is not None:
+ raise InvalidCheckWriteError(f"this run cannot write checks: {skipped_reason}")
+
+
+def _resolve_report(team: Team, report_id: str) -> SignalReport:
+ """The report a run may attach a check to, scoped the way `_resolve_dispatched_check` scopes a check.
+
+ A report sits on its own environment team while the run is resolved on the canonical project, so
+ the read matches canonical teams in the query: a report on a child environment of
+ the run's project is reachable, and nothing outside it is.
+ """
+ try:
+ uuid.UUID(str(report_id))
+ except (ValueError, TypeError):
+ raise InvalidCheckWriteError(f"report {report_id} not found")
+ report = (
+ SignalReport.objects.select_related("team")
+ .alias(effective_project_id=Coalesce("team__parent_team_id", "team_id"))
+ .filter(id=report_id, effective_project_id=team.parent_team_id or team.id)
+ .exclude(status=SignalReport.Status.DELETED)
+ .first()
+ )
+ if report is None:
+ raise InvalidCheckWriteError(f"report {report_id} not found")
+ return report
+
+
+def create_report_check(
+ *,
+ team: Team,
+ run: SignalScoutRun,
+ report_id: str,
+ title: str,
+ kind: str,
+ config: dict,
+ rationale: str = "",
+ next_run_at: datetime,
+ expires_at: datetime,
+ run_interval_minutes: int | None = None,
+ runs_remaining: int = 1,
+) -> ScoutCheckSummary:
+ """Write one forward-looking check on a report this run can reach.
+
+ Attributed to the run's task, like every other scout write, so the report's log names the run
+ that decided the fix was worth re-measuring rather than the coordinator that will measure it.
+ """
+ _assert_run_may_write_checks(team, run)
+ report = _resolve_report(team, report_id)
+ task_id = _resolve_task_id(run)
+ try:
+ check = create_check(
+ report=report,
+ title=title,
+ rationale=rationale,
+ kind=kind,
+ config=config,
+ attribution=ArtefactAttribution.from_task(task_id) if task_id else ArtefactAttribution.system(),
+ next_run_at=next_run_at,
+ expires_at=expires_at,
+ run_interval_minutes=run_interval_minutes,
+ runs_remaining=runs_remaining,
+ )
+ except CheckCreationError as error:
+ raise InvalidCheckWriteError(str(error)) from None
+ return _summarize(check)
+
+
+def list_report_checks(*, team: Team, report_id: str) -> list[ScoutCheckSummary]:
+ """Every check on one report, newest first. Read it before writing: a report already carrying a
+ check for the claim needs no second one, and the cap is five."""
+ report = _resolve_report(team, report_id)
+ checks = SignalReportCheck.objects.for_team(report.team_id).filter(report_id=report.id).order_by("-created_at")
+ return [_summarize(check) for check in checks[:MAX_CHECKS_LISTED]]
+
+
+def cancel_report_check(*, team: Team, run: SignalScoutRun, check_id: str) -> ScoutCheckSummary:
+ """Stop a check that is no longer worth running. Its recorded results stay on the report.
+
+ One conditional update rather than a read and then a write, as the REST path does: a verdict
+ that lands in between leaves a result artefact, and an unconditional write would overwrite the
+ status that artefact explains.
+ """
+ _assert_run_may_write_checks(team, run)
+ try:
+ uuid.UUID(str(check_id))
+ except (ValueError, TypeError):
+ raise InvalidCheckWriteError(f"check {check_id} not found")
+ check = SignalReportCheck.all_teams.select_related("team").filter(id=check_id).first()
+ if check is None:
+ raise InvalidCheckWriteError(f"check {check_id} not found")
+ canonical_team_id = team.parent_team_id or team.id
+ if (check.team.parent_team_id or check.team_id) != canonical_team_id:
+ raise InvalidCheckWriteError(f"check {check_id} not found")
+ cancelled = (
+ SignalReportCheck.objects.for_team(check.team_id)
+ .filter(id=check.id, status__in=SignalReportCheck.OPEN_STATUSES)
+ .update(status=SignalReportCheck.Status.CANCELLED, updated_at=timezone.now())
+ )
+ check.refresh_from_db()
+ if not cancelled:
+ raise InvalidCheckWriteError(f"check {check_id} already finished as `{check.status}` and cannot be cancelled")
+ return _summarize(check)
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 71288a968332..ea9379978095 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -91,6 +91,8 @@ from products.signals.backend.scout_harness.scout_costs import SCOUT_COST_WINDOW
from products.signals.backend.scout_harness.scout_naming import SLUG_ALLOCATION_ATTEMPTS, allocate_scout_slug
from products.signals.backend.scout_harness.serializers import (
REPOSITORIES_REACHABILITY_CHECKED_CONTEXT_KEY,
+ CancelReportCheckRequestSerializer,
+ CreateReportCheckRequestSerializer,
EditReportRequestSerializer,
EditReportResponseSerializer,
EmitFindingRequestSerializer,
@@ -104,6 +106,7 @@ from products.signals.backend.scout_harness.serializers import (
ForgetResponseSerializer,
LighthouseAuditRequestSerializer,
LighthouseAuditResponseSerializer,
+ ListReportChecksQuerySerializer,
ProjectProfileQuerySerializer,
ProjectProfileSerializer,
RecentEmissionsQuerySerializer,
@@ -113,6 +116,7 @@ from products.signals.backend.scout_harness.serializers import (
RecordStructuredOutputRequestSerializer,
RecordStructuredOutputResponseSerializer,
RememberRequestSerializer,
+ ScoutCheckSummarySerializer,
ScoutCostsQuerySerializer,
ScoutCostsSerializer,
ScoutEmissionReportLinkSerializer,
@@ -150,7 +154,14 @@ from products.signals.backend.scout_harness.skill_loader import (
)
from products.signals.backend.scout_harness.suggestions import find_suggestion, mark_suggestion_created
from products.signals.backend.scout_harness.team_limits import resolve_team_metadata, withheld_skills_for_team
-from products.signals.backend.scout_harness.tools.checks import InvalidCheckResultError, record_check_result
+from products.signals.backend.scout_harness.tools.checks import (
+ InvalidCheckResultError,
+ InvalidCheckWriteError,
+ cancel_report_check,
+ create_report_check,
+ list_report_checks,
+ record_check_result,
+)
from products.signals.backend.scout_harness.tools.emit import EvidenceEntry, InvalidEmitError, emit_finding_sync
from products.signals.backend.scout_harness.tools.lighthouse import (
MAX_AUDITS_PER_RUN,
@@ -1129,6 +1140,20 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
self._assert_report_tool_opted_in(run, required_tool)
return run
+ def _resolve_own_in_progress_run(self, request: Request, kwargs: dict, *, required_tool: str) -> SignalScoutRun:
+ """`_resolve_in_progress_run`, narrowed to the run the caller's sandbox token was minted for.
+
+ Team scoping alone lets a run name a sibling's id and write, list or cancel checks under
+ that sibling's task. Answered as 404 like another team's run, so a caller learns nothing
+ about a run it may not touch. A caller with no bound task is unaffected, the internal scope
+ being server-mint-only.
+ """
+ run = self._resolve_in_progress_run(kwargs, required_tool=required_tool)
+ bound_task_id = _sandbox_bound_task_id(request)
+ if bound_task_id is not None and bound_task_id != run.task_run.task_id:
+ raise exceptions.NotFound()
+ return run
+
def _assert_report_tool_opted_in(self, run: SignalScoutRun, required_tool: str) -> None:
"""Fail closed unless the run's skill opted into `required_tool` via `allowed_tools`. Loads the
exact skill version the run snapshotted so the gate matches what actually ran; a missing/unloadable
@@ -1532,6 +1557,127 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
on every path, a scout can tell "you asked for the wrong thing" from "you are out"."""
return audits_remaining_for_run(run.metadata or {})
+ @validated_request(
+ request_serializer=CreateReportCheckRequestSerializer,
+ parameters=[_RUN_ID_PATH_PARAMETER],
+ responses={
+ 200: OpenApiResponse(response=ScoutCheckSummarySerializer, description="Check written on the report."),
+ 400: OpenApiResponse(
+ description=(
+ "The report does not exist for this project, the config does not match the kind, the "
+ "named metric is not on the report, or the report is already at its check limit."
+ )
+ ),
+ 404: OpenApiResponse(description="Run not found for this project."),
+ },
+ summary="Write a follow-up check on a report",
+ description=(
+ "Schedule a re-measurement of a report's claim, so whether the fix held becomes a stored fact "
+ "instead of something a future run has to remember to look for. A `metric_threshold` check runs "
+ "one bounded Trends query and compares the result. An `agent` check runs a scout instead, for a "
+ "claim no single number settles."
+ ),
+ operation_id="signals_scout_report_check_create",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="report-check-create",
+ required_scopes=["signal_scout_report:write"],
+ pagination_class=None,
+ )
+ def report_check_create(self, request: Request, **kwargs) -> Response:
+ run = self._resolve_own_in_progress_run(request, kwargs, required_tool="edit_report")
+ data = request.validated_data
+ try:
+ check = create_report_check(
+ # `run.team` is the canonical team the run was resolved on, as in `emit_report`.
+ team=run.team,
+ run=run,
+ report_id=str(data["report_id"]),
+ title=data["title"],
+ rationale=data.get("rationale", ""),
+ kind=data["kind"],
+ config=data["config"],
+ next_run_at=data["next_run_at"],
+ expires_at=data["expires_at"],
+ run_interval_minutes=data.get("run_interval_minutes"),
+ runs_remaining=data["runs_remaining"],
+ )
+ except InvalidCheckWriteError as exc:
+ raise exceptions.ValidationError({"detail": str(exc)})
+ return Response(ScoutCheckSummarySerializer(dataclasses.asdict(check)).data, status=status.HTTP_200_OK)
+
+ @validated_request(
+ query_serializer=ListReportChecksQuerySerializer,
+ parameters=[_RUN_ID_PATH_PARAMETER],
+ responses={
+ 200: OpenApiResponse(
+ response=ScoutCheckSummarySerializer(many=True), description="The report's checks, newest first."
+ ),
+ 400: OpenApiResponse(description="The report does not exist for this project."),
+ 404: OpenApiResponse(description="Run not found for this project."),
+ },
+ summary="List a report's follow-up checks",
+ description=(
+ "Every check on one report, newest first. Read this before writing one: a report already "
+ "carrying a check for the same claim needs no second one, and a report holds at most five open "
+ "checks at a time."
+ ),
+ operation_id="signals_scout_report_checks_list",
+ )
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="report-checks",
+ required_scopes=["signal_scout_report:write"],
+ pagination_class=None,
+ )
+ def report_checks(self, request: Request, **kwargs) -> Response:
+ run = self._resolve_own_in_progress_run(request, kwargs, required_tool="edit_report")
+ validated = getattr(request, "validated_query_data", {}) or {}
+ try:
+ checks = list_report_checks(team=run.team, report_id=str(validated["report_id"]))
+ except InvalidCheckWriteError as exc:
+ raise exceptions.ValidationError({"detail": str(exc)})
+ return Response(
+ ScoutCheckSummarySerializer([dataclasses.asdict(check) for check in checks], many=True).data,
+ status=status.HTTP_200_OK,
+ )
+
+ @validated_request(
+ request_serializer=CancelReportCheckRequestSerializer,
+ parameters=[_RUN_ID_PATH_PARAMETER],
+ responses={
+ 200: OpenApiResponse(response=ScoutCheckSummarySerializer, description="Check cancelled."),
+ 400: OpenApiResponse(
+ description="The check does not exist for this project, or already finished and cannot be cancelled."
+ ),
+ 404: OpenApiResponse(description="Run not found for this project."),
+ },
+ summary="Cancel a follow-up check",
+ description=(
+ "Stop a check that is no longer worth running — the claim it re-measures has changed, or a "
+ "better check replaces it. Results it already recorded stay on the report. A check that has "
+ "already finished cannot be cancelled."
+ ),
+ operation_id="signals_scout_report_check_cancel",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="report-check-cancel",
+ required_scopes=["signal_scout_report:write"],
+ pagination_class=None,
+ )
+ def report_check_cancel(self, request: Request, **kwargs) -> Response:
+ run = self._resolve_own_in_progress_run(request, kwargs, required_tool="edit_report")
+ try:
+ check = cancel_report_check(team=run.team, run=run, check_id=str(request.validated_data["check_id"]))
+ except InvalidCheckWriteError as exc:
+ raise exceptions.ValidationError({"detail": str(exc)})
+ return Response(ScoutCheckSummarySerializer(dataclasses.asdict(check)).data, status=status.HTTP_200_OK)
+
@validated_request(
request_serializer=RecordCheckResultRequestSerializer,
parameters=[_RUN_ID_PATH_PARAMETER],
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 3fe36bfcd844..69bc9a4e614d 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -1640,6 +1640,7 @@ class SignalReportCheckSerializer(serializers.ModelSerializer):
"status",
"config",
"next_run_at",
+ "soak_minutes",
"run_interval_minutes",
"runs_remaining",
"expires_at",
@@ -1654,8 +1655,24 @@ class SignalReportCheckSerializer(serializers.ModelSerializer):
"title": {"help_text": "Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`."},
"rationale": {"help_text": "Why the author set the check."},
"kind": {"help_text": "How the check is evaluated."},
- "status": {"help_text": "`active` while the check still runs; every other value is terminal."},
- "next_run_at": {"help_text": "When the coordinator next evaluates the check."},
+ "status": {
+ "help_text": (
+ "`pending` while the check waits for the report to resolve, `active` while it still runs; "
+ "every other value is terminal."
+ )
+ },
+ "next_run_at": {
+ "help_text": (
+ "When the coordinator next evaluates the check. Provisional while the check is `pending`: "
+ "the report resolving is what sets it."
+ )
+ },
+ "soak_minutes": {
+ "help_text": (
+ "How long after the report resolves a `pending` check waits before its first run. "
+ "Null on a check that named its own `next_run_at`."
+ )
+ },
"run_interval_minutes": {"help_text": "Gap between runs for a recurring check; null for a one-shot."},
"runs_remaining": {"help_text": "Evaluations still owed before the check retires as passed."},
"expires_at": {"help_text": "Horizon after which the check retires without running again."},
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 6178f580a65a..286c4faf8d3b 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -90,6 +90,13 @@ class RunAgenticReportOutput:
# Resolved impact-metric payload, with the same replay-safe replace/clear/preserve semantics as
# charts. The transition activity writes it with the matching title and summary.
metrics: list[dict[str, Any]] | None = None
+ # Check specs the verification turn authored, written as rows by the transition activity that
+ # writes the metrics they reference — a check naming a metric the report never got is dropped
+ # there rather than stored pointing at nothing. `None` predates the field and writes none.
+ checks: list[dict[str, Any]] | None = None
+ # The research sandbox task the check rows are attributed to, so the report's log names what
+ # decided the fix was worth re-measuring. `None` for saved fixtures and pre-existing outputs.
+ research_task_id: str | None = None
# Whether the rollout let this run author charts at all. Carried so telemetry can tell a run
# that chose not to chart apart from one that was never allowed to, which would otherwise read
# as the agent's charting rate moving on every rollout step. `None` predates the field.
@@ -579,6 +586,29 @@ async def _persist_agentic_report_artefacts(
# `maybe_autostart_implementation_activity` in temporal/summary.py.
+def _team_runs_scouts(team_id: int) -> bool:
+ """Whether this team's scout fleet could take an `agent` check dispatched at it.
+
+ The enrollment half of the gate the check dispatcher applies, read at authoring time so the
+ research turn is never offered a kind whose lane does not exist. A project at its daily run
+ budget still counts as running scouts: a research check stays pending until its report resolves
+ and its soak passes, so today's budget says nothing about that day, and the dispatcher defers a
+ throttled check by itself. Fails closed to False: a flag-service hiccup costs the run the agent
+ kind, never the report.
+ """
+ from products.signals.backend.scout_harness.run_gates import ( # noqa: PLC0415
+ ScoutRunRejectionKind,
+ check_fleet_gates,
+ )
+
+ try:
+ rejection = check_fleet_gates(team_id)
+ return rejection is None or rejection.kind == ScoutRunRejectionKind.THROTTLED
+ except Exception:
+ logger.warning("scout fleet availability check failed", team_id=team_id, exc_info=True)
+ return False
+
+
def _team_has_business_knowledge(team_id: int) -> bool:
"""Flag + ready-sources check, evaluated fresh per run so a flag flip takes
effect immediately. Fail open to False — research must not die on a flag-service
@@ -670,6 +700,11 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
metrics_enabled = await database_sync_to_async(team_report_metrics_enabled, thread_sensitive=False)(
input.team_id
)
+ # An `agent` check needs a scout fleet to dispatch it. A team with none degrades to
+ # deterministic checks rather than storing a check that could never run.
+ agent_checks_enabled = await database_sync_to_async(_team_runs_scouts, thread_sensitive=False)(
+ input.team_id
+ )
# 2. Load previous research if this is a re-promoted report
previous_research = await _load_previous_research(input.team_id, input.report_id)
# 2b. Load the resolved report this one recurred from, if any, as extra research context
@@ -702,6 +737,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
resolved_report_title=resolved_report_title,
resolved_report_summary=resolved_report_summary,
metrics_enabled=metrics_enabled,
+ agent_checks_enabled=agent_checks_enabled,
steering_section=steering.section,
)
# 4. Persist artefacts, avoid partial data from failed runs
@@ -738,6 +774,8 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
repository=repository,
charts=charts_payload,
metrics=metrics_payload,
+ checks=[check.model_dump(mode="json") for check in result.checks],
+ research_task_id=result.research_task_id,
charts_enabled=True,
)
except Exception as error:
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index 14a775c20cb3..accd7489b761 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -27,6 +27,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
+from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.auto_start import maybe_autostart_from_report_artefacts
from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate
from products.signals.backend.models import SIGNALS_AT_RUN_INCREMENT, SignalReport, SignalTeamConfig
@@ -143,6 +144,10 @@ class ReportDecision:
charts: list[dict[str, Any]] | None = None
# Resolved metric payload with the same preserve/replace/clear semantics as charts.
metrics: list[dict[str, Any]] | None = None
+ # Check specs the research run's verification turn authored, and the research task they are
+ # attributed to. Empty for the no-repo branch, which does no research.
+ checks: list[dict[str, Any]] = field(default_factory=list)
+ research_task_id: str | None = None
# The chart rollout state the research run saw (see `RunAgenticReportOutput.charts_enabled`).
# `None` for the no-repo branch, which does no research and so never asks.
charts_enabled: bool | None = None
@@ -448,6 +453,8 @@ class SignalReportSummaryWorkflow:
explanation=agentic_result.explanation,
charts=agentic_result.charts,
metrics=agentic_result.metrics,
+ checks=agentic_result.checks or [],
+ research_task_id=agentic_result.research_task_id,
charts_enabled=agentic_result.charts_enabled,
pending_reason="agent_requested",
)
@@ -509,6 +516,8 @@ class SignalReportSummaryWorkflow:
source_products=source_products,
charts=decision.charts,
metrics=decision.metrics,
+ checks=decision.checks,
+ checks_task_id=decision.research_task_id,
suggested_prompts=decision.suggested_prompts,
charts_enabled=decision.charts_enabled,
),
@@ -809,6 +818,12 @@ class MarkReportReadyInput:
charts: list[dict[str, Any]] | None = None
# Typed impact metrics written atomically with the prose and chart set.
metrics: list[dict[str, Any]] | None = None
+ # Check specs the research run's verification turn authored, written as rows in the same
+ # transaction as the metrics they reference. Empty or `None` writes none, which is also what an
+ # older workflow history that predates the field replays as.
+ checks: list[dict[str, Any]] | None = None
+ # Task the check rows are attributed to: the research sandbox that authored the specs.
+ checks_task_id: str | None = None
# Suggested prompts to write alongside title/summary, same three states and same replay-safe
# default. The research pipeline passes `[]`: it doesn't author prompts yet, and the ones a
# scout wrote were written against the summary this transition is replacing.
@@ -817,6 +832,37 @@ class MarkReportReadyInput:
charts_enabled: bool | None = None
+def _write_research_checks(report: SignalReport, input: MarkReportReadyInput) -> None:
+ """Persist the research run's check specs on the report it just made ready.
+
+ Best-effort as a whole: the report's prose is what this transition exists to write, so a spec
+ the pipeline cannot store is dropped with a log rather than failing the transition and leaving
+ the report stuck in progress.
+ """
+ if not input.checks:
+ return
+ # Function-local: the authoring module reaches the alerts facade through the check executor,
+ # which has no business on this module's import path.
+ from products.signals.backend.report_check_authoring import create_checks_from_specs # noqa: PLC0415
+ from products.signals.backend.report_checks import CheckSpec # noqa: PLC0415
+
+ specs: list[CheckSpec] = []
+ for raw in input.checks:
+ try:
+ specs.append(CheckSpec.model_validate(raw))
+ except Exception:
+ logger.warning("signals report check spec did not validate", report_id=str(report.id))
+ create_checks_from_specs(
+ report=report,
+ specs=specs,
+ attribution=(
+ ArtefactAttribution.from_task(input.checks_task_id)
+ if input.checks_task_id
+ else ArtefactAttribution.system()
+ ),
+ )
+
+
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
@@ -862,6 +908,14 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:
# re-promote it back to candidate and loop to also process new signals
candidate_fields = report.transition_to(SignalReport.Status.CANDIDATE)
report.save(update_fields=candidate_fields)
+ else:
+ # Only a pass that settles writes its checks. A pass about to be re-researched is
+ # an intermediate one, and its checks would describe prose the next pass replaces.
+ # After the metrics write and inside the same transaction, because a
+ # `metric_threshold` check resolves the query off the metric set this transition
+ # just stored: written earlier it would name a metric the report does not have yet,
+ # and written later it could survive a rollback that took the metric with it.
+ _write_research_checks(report, input)
return _ReportTransition(
run_count=report.run_count,
chart_count=len(report.charts or []),
diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.py
index d294f7bd97f0..5dc53ca127ec 100644
--- a/products/signals/backend/test/test_report_checks.py
+++ b/products/signals/backend/test/test_report_checks.py
@@ -1,12 +1,14 @@
+import time
from datetime import timedelta
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
+from pydantic import ValidationError as PydanticValidationError
from rest_framework import status
from temporalio.exceptions import WorkflowAlreadyStartedError
@@ -17,6 +19,7 @@ from products.access_control.backend.facade.contracts import PropertyAccessLevel
from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import Dismissal
+from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
from products.signals.backend.models import (
SignalReport,
SignalReportArtefact,
@@ -31,18 +34,21 @@ from products.signals.backend.report_check_agent import (
build_check_run_note,
resolve_check_skill_name,
)
+from products.signals.backend.report_check_authoring import CheckCreationError, create_check, create_checks_from_specs
from products.signals.backend.report_check_execution import (
CHECK_ERROR_RETRY_AFTER,
CheckVerdict,
collect_due_checks,
evaluate_check_value,
expire_overdue_checks,
+ measure_check,
record_check_verdict,
resolve_check_query,
run_due_report_checks,
)
from products.signals.backend.report_checks import (
DEFAULT_CHECK_EXPIRY_AFTER_LAST_RUN,
+ DEFAULT_CHECK_SOAK_HOURS,
MAX_ACTIVE_CHECKS_PER_REPORT,
MAX_CHECK_HORIZON,
MAX_CHECK_INSTRUCTIONS_LENGTH,
@@ -55,11 +61,19 @@ from products.signals.backend.report_checks import (
AgentCheckConfig,
CheckComparison,
CheckConfigValidationError,
+ CheckSpec,
MetricThresholdConfig,
parse_check_config,
)
from products.signals.backend.report_metric_refresh import MetricMeasurement
-from products.signals.backend.scout_harness.tools.checks import InvalidCheckResultError, record_check_result
+from products.signals.backend.scout_harness.tools.checks import (
+ InvalidCheckResultError,
+ InvalidCheckWriteError,
+ cancel_report_check,
+ create_report_check,
+ list_report_checks,
+ record_check_result,
+)
from products.signals.backend.serializers import CHECK_RESULT_HIDDEN_EXPLANATION, SignalReportCheckWriteSerializer
from products.signals.backend.test.report_metric_test_fixtures import trends_metric_query
from products.signals.backend.views import SignalReportCheckViewSet
@@ -72,6 +86,7 @@ _DISPATCH = "products.signals.backend.temporal.agentic.scout_scheduler.start_che
_CONNECT = "posthog.temporal.common.client.sync_connect"
_FLAG_PAYLOAD = "products.signals.backend.scout_harness.run_gates._read_flag_payload"
_OTHER_SKILL = "signals-scout-error-tracking"
+_EMIT_SIGNAL = "products.signals.backend.facade.api.emit_signal"
_PAGEVIEWS = trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}])
@@ -334,7 +349,7 @@ class TestReportCheckExecution(APIBaseTest):
assert capture.call_count == 1
properties = capture.call_args.kwargs["properties"]
- assert capture.call_args.kwargs["event"] == "signals_report_check_resolved"
+ assert capture.call_args.kwargs["event"] == "signals_report_check_evaluated"
assert properties["outcome"] == "failed"
assert properties["check_status"] == SignalReportCheck.Status.FAILED
assert properties["kind"] == SignalReportCheck.Kind.METRIC_THRESHOLD
@@ -468,10 +483,13 @@ class TestReportCheckExecution(APIBaseTest):
check = self._check(
next_run_at=timezone.now() + timedelta(days=1), expires_at=timezone.now() - timedelta(days=1)
)
- assert expire_overdue_checks(timezone.now()) == 1
+ with patch(_CAPTURE) as capture:
+ assert expire_overdue_checks(timezone.now()) == 1
check.refresh_from_db()
assert check.status == SignalReportCheck.Status.EXPIRED
assert self._results() == []
+ assert capture.call_args.kwargs["event"] == "signals_report_checks_expired"
+ assert capture.call_args.kwargs["properties"]["never_ran_count"] == 1
def test_a_check_past_its_horizon_is_not_due_even_when_the_sweep_has_not_reached_it(self) -> None:
now = timezone.now()
@@ -559,14 +577,28 @@ class TestReportCheckAPI(APIBaseTest):
self.report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.RESOLVED, title="Fix")
self.url = f"/api/projects/{self.team.id}/signals/reports/{self.report.id}/checks/"
- def test_create_then_list_then_cancel(self) -> None:
+ def _create(self, *, report: SignalReport | None = None, **overrides) -> SignalReportCheck:
+ spec: dict = {
+ "title": "Checkout errors stay low",
+ "kind": SignalReportCheck.Kind.METRIC_THRESHOLD,
+ "config": _threshold_config(),
+ "next_run_at": timezone.now() + timedelta(days=7),
+ }
+ spec.update(overrides)
+ return create_check(report=report or self.report, attribution=ArtefactAttribution.system(), **spec)
+
+ def test_the_endpoint_does_not_create_checks(self) -> None:
response = self.client.post(
self.url,
- {"title": "Checkout errors stay low", "kind": "metric_threshold", "config": _threshold_config()},
+ {"title": "Checkout errors stay low", "kind": "agent", "config": {"instructions": "Look at anything."}},
format="json",
)
- assert response.status_code == status.HTTP_201_CREATED, response.json()
- check_id = response.json()["id"]
+
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+ assert not SignalReportCheck.objects.for_team(self.team.id).exists()
+
+ def test_list_then_cancel(self) -> None:
+ check_id = str(self._create().id)
listed = self.client.get(self.url)
assert [row["id"] for row in listed.json()["results"]] == [check_id]
@@ -582,35 +614,19 @@ class TestReportCheckAPI(APIBaseTest):
def test_a_created_check_is_reported_for_adoption(self) -> None:
with patch(_CAPTURE) as capture:
with self.captureOnCommitCallbacks(execute=True):
- response = self.client.post(
- self.url,
- {
- "title": "Checkout errors stay low",
- "kind": "metric_threshold",
- "config": _threshold_config(),
- "run_interval_minutes": MIN_CHECK_INTERVAL_MINUTES,
- "runs_remaining": 2,
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_201_CREATED, response.json()
+ check = self._create(run_interval_minutes=MIN_CHECK_INTERVAL_MINUTES, runs_remaining=2)
+
assert capture.call_count == 1
properties = capture.call_args.kwargs["properties"]
assert capture.call_args.kwargs["event"] == "signals_report_check_created"
- assert properties["check_id"] == response.json()["id"]
+ assert properties["check_id"] == str(check.id)
assert properties["kind"] == SignalReportCheck.Kind.METRIC_THRESHOLD
assert properties["metric_source"] == "query"
assert properties["run_interval_minutes"] == MIN_CHECK_INTERVAL_MINUTES
assert properties["runs_remaining"] == 2
def test_cancelling_does_not_overwrite_a_verdict_that_landed_first(self) -> None:
- created = self.client.post(
- self.url,
- {"title": "Checkout errors stay low", "kind": "metric_threshold", "config": _threshold_config()},
- format="json",
- )
- check_id = created.json()["id"]
+ check_id = str(self._create().id)
# The row the request read before a run committed its verdict.
stale = SignalReportCheck.objects.for_team(self.team.id).get(id=check_id)
SignalReportCheck.objects.for_team(self.team.id).filter(id=check_id).update(
@@ -626,24 +642,17 @@ class TestReportCheckAPI(APIBaseTest):
)
def test_a_metric_reference_is_resolved_and_copied_when_the_check_is_created(self) -> None:
- payload = {
- "title": "Checkout errors stay low",
- "kind": "metric_threshold",
- "config": {"metric_id": "checkout-errors", "comparison": {"operator": "lte", "value": 10}},
- }
+ config = {"metric_id": "checkout-errors", "comparison": {"operator": "lte", "value": 10}}
- refused = self.client.post(self.url, payload, format="json")
-
- assert refused.status_code == status.HTTP_400_BAD_REQUEST
+ with self.assertRaises(CheckCreationError):
+ self._create(config=config)
assert not SignalReportCheck.objects.for_team(self.team.id).filter(report_id=self.report.id).exists()
self.report.metrics = [
{"metric_id": "checkout-errors", "title": "Checkout errors", "kind": "occurrences", "query": _PAGEVIEWS}
]
self.report.save(update_fields=["metrics"])
- created = self.client.post(self.url, payload, format="json")
- assert created.status_code == status.HTTP_201_CREATED, created.json()
- stored = SignalReportCheck.objects.for_team(self.team.id).get(id=created.json()["id"])
+ stored = self._create(config=config)
assert stored.config["metric_id"] == "checkout-errors"
assert stored.config["query"] == _PAGEVIEWS
@@ -665,11 +674,7 @@ class TestReportCheckAPI(APIBaseTest):
report = SignalReport.objects.create(team=child, status=SignalReport.Status.RESOLVED, title="Fix")
url = f"/api/projects/{child.id}/signals/reports/{report.id}/checks/"
- created = self.client.post(
- url, {"title": "Errors stay low", "kind": "metric_threshold", "config": _threshold_config()}, format="json"
- )
- assert created.status_code == status.HTTP_201_CREATED, created.json()
- check_id = created.json()["id"]
+ check_id = str(self._create(report=report).id)
assert [row["id"] for row in self.client.get(url).json()["results"]] == [check_id]
assert SignalReportCheck.all_teams.get(id=check_id).team_id == child.id
@@ -692,17 +697,12 @@ class TestReportCheckAPI(APIBaseTest):
}
]
)
- created = self.client.post(
- self.url,
- {
- "title": "Enterprise pageviews stay low",
- "kind": "metric_threshold",
- "config": _threshold_config(query=secret_pageviews, baseline_value=3),
- },
- format="json",
+ check_id = str(
+ self._create(
+ title="Enterprise pageviews stay low",
+ config=_threshold_config(query=secret_pageviews, baseline_value=3),
+ ).id
)
- assert created.status_code == status.HTTP_201_CREATED, created.json()
- check_id = created.json()["id"]
SignalReportCheck.objects.for_team(self.team.id).filter(id=check_id).update(
next_run_at=timezone.now() - timedelta(minutes=1)
)
@@ -746,17 +746,11 @@ class TestReportCheckAPI(APIBaseTest):
def test_an_agent_checks_verdict_is_readable_because_a_run_wrote_it(self) -> None:
# The metric-access policy judges a stored query, which an agent check does not carry, so
# gating its verdict on that policy would hide every agent result from every reader.
- created = self.client.post(
- self.url,
- {
- "title": "Checkout 500s stay gone",
- "kind": "agent",
- "config": {"instructions": "Re-read the issue and say whether it still fires."},
- },
- format="json",
+ check = self._create(
+ title="Checkout 500s stay gone",
+ kind=SignalReportCheck.Kind.AGENT,
+ config={"instructions": "Re-read the issue and say whether it still fires."},
)
- assert created.status_code == status.HTTP_201_CREATED, created.json()
- check = SignalReportCheck.objects.for_team(self.team.id).get(id=created.json()["id"])
record_check_verdict(check, CheckVerdict(outcome="failed", explanation="The issue fired 30 times yesterday."))
artefacts_url = f"/api/projects/{self.team.id}/signals/reports/{self.report.id}/artefacts/"
@@ -765,21 +759,12 @@ class TestReportCheckAPI(APIBaseTest):
)
assert result["explanation"] == "The issue fired 30 times yesterday."
- def test_an_invalid_config_is_rejected_by_the_endpoint(self) -> None:
- response = self.client.post(
- self.url,
- {"title": "Nonsense", "kind": "metric_threshold", "config": {"comparison": {"operator": "lte"}}},
- format="json",
- )
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
def test_a_report_carries_a_bounded_number_of_active_checks(self) -> None:
- payload = {"title": "Errors stay low", "kind": "metric_threshold", "config": _threshold_config()}
for _ in range(MAX_ACTIVE_CHECKS_PER_REPORT):
- assert self.client.post(self.url, payload, format="json").status_code == status.HTTP_201_CREATED
+ self._create()
- refused = self.client.post(self.url, payload, format="json")
- assert refused.status_code == status.HTTP_400_BAD_REQUEST
+ with self.assertRaises(CheckCreationError):
+ self._create()
def test_another_teams_report_is_not_reachable(self) -> None:
other_team = self.organization.teams.create(name="Other")
@@ -948,11 +933,14 @@ class TestAgentCheckDispatch(APIBaseTest):
)
check = self._check()
- with patch(_CONNECT), patch(_DISPATCH) as dispatch:
+ with patch(_CONNECT), patch(_DISPATCH) as dispatch, patch(_CAPTURE) as capture:
summary = run_due_report_checks()
assert summary.deferred == 1
dispatch.assert_not_called()
+ assert capture.call_args.kwargs["event"] == "signals_report_check_dispatch"
+ assert capture.call_args.kwargs["properties"]["outcome"] == "deferred"
+ assert capture.call_args.kwargs["properties"]["reason"] == "run_in_flight"
assert self._results() == []
check.refresh_from_db()
assert check.status == SignalReportCheck.Status.ACTIVE
@@ -1098,3 +1086,351 @@ class TestCheckResultTool(APIBaseTest):
with self.assertRaises(InvalidCheckResultError):
self._record(check, **overrides)
+
+
+class TestPendingChecks(APIBaseTest):
+ """A check written before the fix exists: it waits for the report to resolve, then soaks."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="Fix")
+
+ def _pending(self, **overrides) -> SignalReportCheck:
+ return create_check(
+ report=self.report,
+ title="Checkout errors stay low",
+ kind=SignalReportCheck.Kind.METRIC_THRESHOLD,
+ config=_threshold_config(),
+ attribution=ArtefactAttribution.system(),
+ soak_minutes=DEFAULT_CHECK_SOAK_HOURS * 60,
+ **overrides,
+ )
+
+ def _resolve(self) -> None:
+ with self.captureOnCommitCallbacks(execute=True):
+ self.report.status = SignalReport.Status.RESOLVED
+ self.report.save(update_fields=["status"])
+
+ def test_a_pending_check_is_never_due_while_its_report_is_unresolved(self) -> None:
+ self._pending()
+
+ # Well past the soak, but the clock has not started: the report is still open.
+ assert collect_due_checks(timezone.now() + timedelta(days=7)) == []
+
+ def test_resolving_the_report_arms_the_check_for_resolve_plus_soak(self) -> None:
+ check = self._pending()
+ before = timezone.now()
+
+ self._resolve()
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ soak = timedelta(hours=DEFAULT_CHECK_SOAK_HOURS)
+ assert before + soak <= check.next_run_at <= timezone.now() + soak
+ assert collect_due_checks(check.next_run_at + timedelta(minutes=1)) == [check]
+
+ @parameterized.expand(
+ [
+ # Every resolve path ends in the same save, which is why the arming hangs off the model
+ # rather off each caller: a merged pull request, a person in the inbox, and an MCP state
+ # write all have to start the same clock.
+ ("merged_pull_request", {"_status_from_pr_state": True}),
+ ("resolved_by_a_caller", {"_close_pr_on_resolve": True}),
+ ("resolved_with_no_marker", {}),
+ ]
+ )
+ def test_every_resolve_path_starts_the_clock(self, _name: str, markers: dict) -> None:
+ check = self._pending()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ for marker, value in markers.items():
+ setattr(self.report, marker, value)
+ self.report.status = SignalReport.Status.RESOLVED
+ self.report.save(update_fields=["status"])
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+
+ def test_an_edit_after_the_resolve_does_not_re_arm_an_answered_check(self) -> None:
+ check = self._pending()
+ self._resolve()
+ check.refresh_from_db()
+ armed_at = check.next_run_at
+
+ with self.captureOnCommitCallbacks(execute=True):
+ self.report.title = "Fix, retitled"
+ self.report.save(update_fields=["title"])
+
+ check.refresh_from_db()
+ assert check.next_run_at == armed_at
+
+ def test_a_pending_check_retires_when_its_report_never_resolves(self) -> None:
+ check = self._pending()
+
+ assert expire_overdue_checks(timezone.now() + MAX_CHECK_HORIZON + timedelta(minutes=1)) == 1
+
+ check.refresh_from_db()
+ assert check.status == SignalReportCheck.Status.EXPIRED
+
+ def test_pending_checks_count_against_the_reports_limit(self) -> None:
+ for _ in range(MAX_ACTIVE_CHECKS_PER_REPORT):
+ self._pending()
+
+ with self.assertRaises(CheckCreationError):
+ self._pending()
+
+ def test_a_check_naming_a_metric_the_report_does_not_have_is_refused(self) -> None:
+ with self.assertRaises(CheckCreationError):
+ create_check(
+ report=self.report,
+ title="Checkout errors stay low",
+ kind=SignalReportCheck.Kind.METRIC_THRESHOLD,
+ config={"metric_id": "checkout-errors", "comparison": {"operator": "lte", "value": 10}},
+ attribution=ArtefactAttribution.system(),
+ soak_minutes=60,
+ )
+
+
+class TestFailedCheckResurfaces(APIBaseTest):
+ """What happens when a deterministic check breaches on a report nobody is looking at any more."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.RESOLVED, title="Checkout 500s"
+ )
+
+ def _check(self, **overrides) -> SignalReportCheck:
+ now = timezone.now()
+ fields: dict = {
+ "team": self.team,
+ "report": self.report,
+ "title": "Checkout errors stay low",
+ "kind": SignalReportCheck.Kind.METRIC_THRESHOLD,
+ "config": _threshold_config(baseline_value=40.0),
+ "next_run_at": now - timedelta(minutes=1),
+ "expires_at": now + timedelta(days=30),
+ }
+ fields.update(overrides)
+ return SignalReportCheck.objects.for_team(self.team.id).create(**fields)
+
+ def _run_and_capture(self, check: SignalReportCheck, *, value: float):
+ with patch(_EMIT_SIGNAL, new=AsyncMock(return_value=None)) as emit:
+ with self.captureOnCommitCallbacks(execute=True):
+ with patch(
+ _MEASURE, return_value=MetricMeasurement(value=value, measured_at=timezone.now(), series=None)
+ ):
+ record_check_verdict(check, measure_check(check, deadline=time.monotonic() + 30))
+ return emit
+
+ def test_a_breach_on_a_resolved_report_emits_one_signal_naming_the_origin(self) -> None:
+ check = self._check()
+
+ emit = self._run_and_capture(check, value=42.0)
+
+ assert emit.call_count == 1
+ sent = emit.call_args.kwargs
+ assert sent["source_product"] == SignalSourceProduct.SIGNALS_CHECK
+ assert sent["source_type"] == SignalSourceType.CHECK_FAILED
+ assert sent["extra"]["report_id"] == str(self.report.id)
+ assert sent["extra"]["check_id"] == str(check.id)
+ assert sent["extra"]["baseline_value"] == 40.0
+ assert str(self.report.id) in sent["description"]
+
+ def test_a_breach_on_a_report_still_being_worked_emits_nothing(self) -> None:
+ SignalReport.objects.filter(id=self.report.id).update(status=SignalReport.Status.READY)
+ check = self._check()
+ check.refresh_from_db()
+
+ emit = self._run_and_capture(check, value=42.0)
+
+ assert emit.call_count == 0
+
+ def test_a_pass_on_a_resolved_report_emits_nothing(self) -> None:
+ check = self._check()
+
+ emit = self._run_and_capture(check, value=1.0)
+
+ assert emit.call_count == 0
+
+ def test_an_agent_check_breach_emits_nothing_because_its_scout_can_file(self) -> None:
+ check = self._check(
+ kind=SignalReportCheck.Kind.AGENT,
+ config={"instructions": "Re-read the issue."},
+ dispatched_at=timezone.now(),
+ )
+
+ with patch(_EMIT_SIGNAL, new=AsyncMock(return_value=None)) as emit:
+ with self.captureOnCommitCallbacks(execute=True):
+ record_check_verdict(check, CheckVerdict(outcome="failed", explanation="Still firing."))
+
+ assert emit.call_count == 0
+
+
+class TestScoutCheckTools(APIBaseTest):
+ """`scout-report-check-create` / `-list` / `-cancel`: what a run may write, read, and stop."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="Checkout 500s"
+ )
+ self.scout_config = SignalScoutConfig.objects.create(
+ team=self.team,
+ skill_name=FALLBACK_CHECK_SKILL_NAME,
+ status=SignalScoutConfig.Status.ACTIVE,
+ enabled=True,
+ )
+ self.task = Task.objects.create(team=self.team, title="t", description="d")
+ task_run = TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ self.scout_run = SignalScoutRun.objects.create(
+ task_run=task_run,
+ team=self.team,
+ scout_config=self.scout_config,
+ skill_name=FALLBACK_CHECK_SKILL_NAME,
+ skill_version=1,
+ )
+
+ def _create(self, **overrides):
+ now = timezone.now()
+ payload: dict = {
+ "report_id": str(self.report.id),
+ "title": "Checkout errors stay low",
+ "kind": SignalReportCheck.Kind.METRIC_THRESHOLD,
+ "config": _threshold_config(baseline_value=40.0),
+ "next_run_at": now + timedelta(days=3),
+ "expires_at": now + timedelta(days=30),
+ }
+ payload.update(overrides)
+ return create_report_check(team=self.team, run=self.scout_run, **payload)
+
+ def test_a_written_check_is_attributed_to_the_runs_task(self) -> None:
+ summary = self._create()
+
+ check = SignalReportCheck.objects.for_team(self.team.id).get(id=summary.check_id)
+ assert check.task_id == self.task.id
+ assert check.status == SignalReportCheck.Status.ACTIVE
+ assert check.report_id == self.report.id
+
+ def test_a_run_reads_back_the_checks_it_would_otherwise_duplicate(self) -> None:
+ written = self._create()
+
+ listed = list_report_checks(team=self.team, report_id=str(self.report.id))
+
+ assert [summary.check_id for summary in listed] == [written.check_id]
+
+ def test_cancelling_stops_the_check_and_refuses_a_second_cancel(self) -> None:
+ written = self._create()
+
+ cancelled = cancel_report_check(team=self.team, run=self.scout_run, check_id=written.check_id)
+
+ assert cancelled.status == SignalReportCheck.Status.CANCELLED
+ with self.assertRaises(InvalidCheckWriteError):
+ cancel_report_check(team=self.team, run=self.scout_run, check_id=written.check_id)
+
+ def test_a_dry_run_scout_neither_writes_nor_cancels_a_check(self) -> None:
+ written = self._create()
+ self.scout_config.emit = False
+ self.scout_config.save(update_fields=["emit"])
+
+ with self.assertRaises(InvalidCheckWriteError):
+ self._create(title="Written by a preview run")
+ with self.assertRaises(InvalidCheckWriteError):
+ cancel_report_check(team=self.team, run=self.scout_run, check_id=written.check_id)
+
+ check = SignalReportCheck.objects.for_team(self.team.id).get()
+ assert check.status == SignalReportCheck.Status.ACTIVE
+
+ def test_another_projects_report_is_not_reachable(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ other_report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.READY, title="theirs")
+
+ with self.assertRaises(InvalidCheckWriteError):
+ self._create(report_id=str(other_report.id))
+
+
+class TestResearchAuthoredChecks(APIBaseTest):
+ """The verification turn's specs, written alongside the metrics they measure."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="Checkout 500s",
+ metrics=[{"metric_id": "checkout-errors", "title": "Checkout errors", "query": _PAGEVIEWS}],
+ )
+
+ def _spec(self, **overrides) -> CheckSpec:
+ payload: dict = {
+ "title": "Checkout errors stay under 10 a day",
+ "kind": "metric_threshold",
+ "config": {
+ "metric_id": "checkout-errors",
+ "comparison": {"operator": "lte", "value": 10},
+ "baseline_value": 40.0,
+ },
+ }
+ payload.update(overrides)
+ return CheckSpec.model_validate(payload)
+
+ def test_a_spec_becomes_a_pending_check_carrying_the_metrics_query(self) -> None:
+ with patch(_CAPTURE) as capture, self.captureOnCommitCallbacks(execute=True):
+ written = create_checks_from_specs(
+ report=self.report, specs=[self._spec()], attribution=ArtefactAttribution.system()
+ )
+
+ assert len(written) == 1
+ check = written[0]
+ assert check.status == SignalReportCheck.Status.PENDING
+ assert check.soak_minutes == DEFAULT_CHECK_SOAK_HOURS * 60
+ assert check.config["query"] == _PAGEVIEWS
+ assert capture.call_args.kwargs["event"] == "signals_report_check_created"
+ assert capture.call_args.kwargs["properties"]["check_status"] == SignalReportCheck.Status.PENDING
+
+ def test_a_newer_research_pass_replaces_the_pending_checks_of_an_older_one(self) -> None:
+ older = create_checks_from_specs(
+ report=self.report, specs=[self._spec()], attribution=ArtefactAttribution.system()
+ )
+ newer = create_checks_from_specs(
+ report=self.report,
+ specs=[self._spec(title="Checkout errors stay under 5 a day")],
+ attribution=ArtefactAttribution.system(),
+ )
+ create_checks_from_specs(report=self.report, specs=[], attribution=ArtefactAttribution.system())
+
+ older[0].refresh_from_db()
+ newer[0].refresh_from_db()
+ assert older[0].status == SignalReportCheck.Status.CANCELLED
+ assert newer[0].status == SignalReportCheck.Status.PENDING
+
+ def test_a_spec_naming_a_metric_the_report_does_not_have_is_dropped(self) -> None:
+ written = create_checks_from_specs(
+ report=self.report,
+ specs=[self._spec(config={"metric_id": "invented", "comparison": {"operator": "lte", "value": 10}})],
+ attribution=ArtefactAttribution.system(),
+ )
+
+ assert written == []
+ assert not SignalReportCheck.objects.for_team(self.team.id).filter(report=self.report).exists()
+
+ def test_a_longer_soak_is_honoured_for_a_fix_that_reaches_users_slowly(self) -> None:
+ written = create_checks_from_specs(
+ report=self.report, specs=[self._spec(soak_hours=72)], attribution=ArtefactAttribution.system()
+ )
+
+ assert written[0].soak_minutes == 72 * 60
+
+ @parameterized.expand(
+ [
+ ("no_baseline_is_still_a_check", {"comparison": {"operator": "lte", "value": 10}}, True),
+ ("a_config_that_does_not_match_the_kind", {"instructions": "look at it"}, False),
+ ]
+ )
+ def test_a_spec_must_carry_a_config_its_kind_accepts(self, _name: str, config: dict, valid: bool) -> None:
+ payload = {"title": "t", "kind": "metric_threshold", "config": {"metric_id": "checkout-errors", **config}}
+ if valid:
+ assert CheckSpec.model_validate(payload).kind == "metric_threshold"
+ else:
+ with self.assertRaises(PydanticValidationError):
+ CheckSpec.model_validate(payload)
diff --git a/products/signals/backend/test/test_report_telemetry.py b/products/signals/backend/test/test_report_telemetry.py
index d34c484474c7..6ad6595ab5a4 100644
--- a/products/signals/backend/test/test_report_telemetry.py
+++ b/products/signals/backend/test/test_report_telemetry.py
@@ -3,7 +3,7 @@ from unittest.mock import patch
from posthog.sync import database_sync_to_async
-from products.signals.backend.models import SignalReport
+from products.signals.backend.models import SignalReport, SignalReportCheck
from products.signals.backend.temporal.summary import (
MarkReportFailedInput,
MarkReportInProgressInput,
@@ -367,10 +367,23 @@ async def test_ready_loops_only_when_the_run_reached_the_next_bucket(
summary="summary",
processed_signal_count=processed_signal_count,
source_products=["zendesk"],
+ checks=[
+ {
+ "title": "The exception stays gone",
+ "kind": "agent",
+ "config": {"instructions": "Confirm the checkout exception has no events since the fix."},
+ }
+ ],
)
)
assert has_new_signals is expected_loop
+ # Only the pass that settles writes its checks. A looping pass is about to be replaced, and its
+ # checks would be armed later against prose they were not written for.
+ check_count = await database_sync_to_async(
+ SignalReportCheck.objects.for_team(ateam.id).filter(report_id=report_id).count
+ )()
+ assert check_count == (0 if expected_loop else 1)
refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report_id)
expected_status = SignalReport.Status.CANDIDATE if expected_loop else SignalReport.Status.READY
assert refreshed.status == expected_status
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 2349114dfb97..6842dd3223f6 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -1321,13 +1321,12 @@ class TestPromptBuilder(BaseTest):
assert "signals-scout-inbox-validation" in prompt
section = prompt[prompt.index("Follow up on your own past work") :]
assert resurface_tool in section.split("# ")[0]
- # Same fail-closed rule for the durable half of the loop: a report check hangs on a report,
- # which only a report-channel scout holds. Naming it to a signal-channel run would point it
- # at a report it never has.
- if allowed_tools:
- assert "inbox-report-checks-create" in section.split("# ")[0]
+ # Same fail-closed rule for the durable half of the loop: the check endpoints refuse a run
+ # whose skill does not list `edit_report`, so only such a scout is pointed at them.
+ if "edit_report" in allowed_tools:
+ assert "scout-report-check-create" in section.split("# ")[0]
else:
- assert "inbox-report-checks" not in prompt
+ assert "scout-report-check" not in prompt
# Orchestration tests run as plain pytest functions because the async runner uses
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 85ee9e745910..5a94dce90ddb 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -38,6 +38,8 @@ from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import (
SignalProjectProfile,
SignalReport,
+ SignalReportArtefact,
+ SignalReportCheck,
SignalScoutConfig,
SignalScoutEmission,
SignalScoutNote,
@@ -4515,6 +4517,52 @@ class TestScoutRunDerivedMetadata(APIBaseTest):
SignalScratchpad.all_teams.filter(pk=entry.pk).update(created_at=run.created_at - timedelta(hours=2))
assert self._stamp(run)["has_self_validation"] is False
+ def test_self_validation_counts_a_run_that_wrote_a_report_check(self) -> None:
+ # Writing a check *is* the validation being scheduled, unlike writing a queue entry, which
+ # only asks a future run to do it. Keeping the same field name is deliberate: the flag means
+ # "this run closed a loop", and scouts are moving from the queue onto checks.
+ run = _make_run(self.team)
+ report = SignalReport.objects.create(team=self.team, title="Checkout 500s")
+ SignalReportCheck.objects.for_team(self.team.id).create(
+ team=self.team,
+ report=report,
+ title="Checkout errors stay low",
+ kind=SignalReportCheck.Kind.AGENT,
+ config={"instructions": "Re-read the issue."},
+ next_run_at=timezone.now() + timedelta(days=3),
+ expires_at=timezone.now() + timedelta(days=30),
+ task_id=run.task_run.task_id,
+ )
+ assert self._stamp(run)["has_self_validation"] is True
+
+ def test_self_validation_counts_a_run_that_recorded_a_verdict(self) -> None:
+ run = _make_run(self.team)
+ report = SignalReport.objects.create(team=self.team, title="Checkout 500s")
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.CHECK_RESULT,
+ content="{}",
+ task_id=run.task_run.task_id,
+ )
+ assert self._stamp(run)["has_self_validation"] is True
+
+ def test_another_runs_check_does_not_count(self) -> None:
+ run = _make_run(self.team)
+ other_run = _make_run(self.team)
+ report = SignalReport.objects.create(team=self.team, title="Checkout 500s")
+ SignalReportCheck.objects.for_team(self.team.id).create(
+ team=self.team,
+ report=report,
+ title="Checkout errors stay low",
+ kind=SignalReportCheck.Kind.AGENT,
+ config={"instructions": "Re-read the issue."},
+ next_run_at=timezone.now() + timedelta(days=3),
+ expires_at=timezone.now() + timedelta(days=30),
+ task_id=other_run.task_run.task_id,
+ )
+ assert self._stamp(run)["has_self_validation"] is False
+
def test_derived_map_round_trips_as_an_object_not_a_string(self) -> None:
# Guards the serializer field: a `DictField(child=CharField())` coerces the nested map to
# its Python repr, which turns a queryable object into unparseable prose.
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 9f064b8d106b..f85907bde39a 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -1,4 +1,5 @@
import json
+from datetime import timedelta
from typing import Any
from uuid import uuid4
@@ -25,6 +26,7 @@ from products.signals.backend.models import (
ArtefactAttribution,
SignalReport,
SignalReportArtefact,
+ SignalReportCheck,
SignalSourceConfig,
)
from products.signals.backend.report_generation.resolve_reviewers import ReviewerIdentitySet
@@ -2549,3 +2551,111 @@ class TestReportClassificationProps(SimpleTestCase):
assert props["is_self_improvement_report"] is is_self_improvement
expected_kind = REPORT_KIND_SELF_IMPROVEMENT if is_self_improvement else REPORT_KIND_FINDING
assert props["report_kind"] == expected_kind
+
+
+class TestScoutReportCheckAPI(APIBaseTest):
+ """The report-check tools' gate: only a run whose skill opted into the report channel may write one."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="Checkout")
+ self.scout_run = _make_run(self.team)
+ _authenticate_as_scout(self, scopes="signals_scout_reports")
+
+ def _opt_in(self, allowed_tools: list[str]) -> None:
+ LLMSkill.objects.create(
+ team=self.team,
+ name=self.scout_run.skill_name,
+ description="scout",
+ body="# scout",
+ allowed_tools=allowed_tools,
+ )
+
+ def _create_url(self) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/runs/{self.scout_run.id}/report-check-create/"
+
+ def _payload(self) -> dict:
+ return {
+ "report_id": str(self.report.id),
+ "title": "Checkout errors stay low",
+ "kind": "metric_threshold",
+ "config": {
+ "query": trends_metric_query(series=[{"kind": "EventsNode", "event": "$pageview"}]),
+ "comparison": {"operator": "lte", "value": 10},
+ },
+ "next_run_at": (timezone.now() + timedelta(days=3)).isoformat(),
+ }
+
+ def test_an_opted_in_run_writes_a_check_attributed_to_its_task(self) -> None:
+ self._opt_in(REPORT_TOOLS)
+
+ response = self.client.post(self._create_url(), self._payload(), format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ check = SignalReportCheck.objects.for_team(self.team.id).get(id=response.json()["check_id"])
+ assert check.task_id == self.scout_run.task_run.task_id
+ assert check.report_id == self.report.id
+
+ def test_a_run_without_the_report_channel_opt_in_is_refused(self) -> None:
+ self._opt_in([])
+
+ response = self.client.post(self._create_url(), self._payload(), format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert not SignalReportCheck.objects.for_team(self.team.id).exists()
+
+ def test_a_token_minted_for_another_run_cannot_write_through_this_one(self) -> None:
+ self._opt_in(REPORT_TOOLS)
+ sibling = _make_run(self.team)
+ _authenticate_as_scout(self, scopes="signals_scout_reports", sandbox_task_id=sibling.task_run.task_id)
+
+ response = self.client.post(self._create_url(), self._payload(), format="json")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.content
+ assert not SignalReportCheck.objects.for_team(self.team.id).exists()
+
+ def test_a_check_can_target_a_report_in_a_child_environment(self) -> None:
+ self._opt_in(REPORT_TOOLS)
+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child")
+ report = SignalReport.objects.create(team=child, status=SignalReport.Status.READY, title="Checkout")
+
+ response = self.client.post(self._create_url(), {**self._payload(), "report_id": str(report.id)}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ check = SignalReportCheck.objects.for_team(child.id).get(id=response.json()["check_id"])
+ assert check.report_id == report.id
+
+ def test_a_check_cannot_target_a_report_outside_the_canonical_team(self) -> None:
+ self._opt_in(REPORT_TOOLS)
+ other_team = Team.objects.create(organization=self.organization, project=self.team.project, name="Other")
+ report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.READY, title="Checkout")
+
+ response = self.client.post(self._create_url(), {**self._payload(), "report_id": str(report.id)}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert not SignalReportCheck.objects.for_team(other_team.id).exists()
+
+ def test_listing_a_reports_checks_returns_what_the_run_wrote(self) -> None:
+ self._opt_in(REPORT_TOOLS)
+ created = self.client.post(self._create_url(), self._payload(), format="json").json()
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/signals/scout/runs/{self.scout_run.id}/report-checks/",
+ {"report_id": str(self.report.id)},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert [row["check_id"] for row in response.json()] == [created["check_id"]]
+
+ def test_cancelling_stops_the_check(self) -> None:
+ self._opt_in(REPORT_TOOLS)
+ created = self.client.post(self._create_url(), self._payload(), format="json").json()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/signals/scout/runs/{self.scout_run.id}/report-check-cancel/",
+ {"check_id": created["check_id"]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["status"] == "cancelled"
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 153c0eaf920b..ee4881f87e59 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -123,13 +123,6 @@ from products.signals.backend.pull_requests import import_report_pull_requests
from products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate
from products.signals.backend.repo_corrections import sanitized_repository
from products.signals.backend.report_assignments import InvalidPullRequestUrl, ReportClaimConflict, claim_report
-from products.signals.backend.report_check_execution import resolve_check_query
-from products.signals.backend.report_check_telemetry import capture_report_check_created
-from products.signals.backend.report_checks import (
- MAX_ACTIVE_CHECKS_PER_REPORT,
- MetricThresholdConfig,
- parse_check_config,
-)
from products.signals.backend.report_claims import (
actor_owns_claim,
get_active_claim,
@@ -171,7 +164,6 @@ from products.signals.backend.serializers import (
SignalReportArtefactWriteResponseSerializer,
SignalReportArtefactWriteSerializer,
SignalReportCheckSerializer,
- SignalReportCheckWriteSerializer,
SignalReportClaimSerializer,
SignalReportListSerializer,
SignalReportMetricRefreshRequestSerializer,
@@ -4294,22 +4286,12 @@ def _record_reviewer_edit(
responses={200: SignalReportCheckSerializer},
operation_id="signals_report_checks_retrieve",
),
- create=extend_schema(
- summary="Create a check on a report",
- description=(
- "Schedule a re-measurement of the report's claim. A `metric_threshold` check runs one "
- "bounded Trends query and compares the result, so it needs no agent run. An `agent` check "
- "runs a scout instead, for a claim no single number settles; it runs on the scout its "
- "config names, or on the fleet's follow-up scout when it names none."
- ),
- parameters=[_REPORT_ID_PARAMETER],
- request=SignalReportCheckWriteSerializer,
- responses={201: SignalReportCheckSerializer},
- operation_id="signals_report_checks_create",
- ),
destroy=extend_schema(
summary="Cancel a check",
- description="Stop an active check. Its recorded results stay on the report.",
+ description=(
+ "Stop a check that is still open — active, or pending its report resolving. Its recorded "
+ "results stay on the report."
+ ),
parameters=[_REPORT_ID_PARAMETER],
responses={200: SignalReportCheckSerializer},
operation_id="signals_report_checks_destroy",
@@ -4319,17 +4301,19 @@ class SignalReportCheckViewSet(
TeamAndOrgViewSetMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
- mixins.CreateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
- """Checks attached to a signal report: read, create, and cancel.
+ """Checks attached to a signal report: read and cancel.
- There is no update: a check is a claim about the future, and editing its threshold after a
- result would make the recorded verdict unreadable. Cancel it and write a new one.
+ There is no create here. A check is authored by a scout run or by the research pipeline, both
+ through `report_check_authoring.create_check`. An `agent` check puts its author's prose in front
+ of a privileged scout run, and `task:write` does not authorize that, so no caller-facing
+ endpoint accepts one. Anyone who can read the report can read its checks, and a person can
+ still stop one.
- Writes are attributed the same way artefact writes are — to the task named by the
- `X-PostHog-Task-Id` header when present, else to the requesting user.
+ There is no update: a check is a claim about the future, and editing its threshold after a
+ result would make the recorded verdict unreadable. Cancel it and let its author write a new one.
"""
serializer_class = SignalReportCheckSerializer
@@ -4337,7 +4321,7 @@ class SignalReportCheckViewSet(
permission_classes = [IsAuthenticated, APIScopePermission]
scope_object = "task"
queryset = SignalReportCheck.objects.unscoped().order_by("-created_at")
- http_method_names = ["get", "post", "delete", "head", "options"]
+ http_method_names = ["get", "delete", "head", "options"]
def _validated_report(self) -> SignalReport:
report_id = self.parents_query_dict["report_id"]
@@ -4357,69 +4341,6 @@ class SignalReportCheckViewSet(
def safely_get_queryset(self, queryset):
return queryset.filter(report_id=self._validated_report().id, team=self.team)
- def create(self, request: Request, *args, **kwargs) -> Response:
- report = self._validated_report()
- write_serializer = SignalReportCheckWriteSerializer(data=request.data)
- write_serializer.is_valid(raise_exception=True)
- spec = write_serializer.validated_data
-
- # Resolve a metric reference now and store the query it points at, rather than at each run.
- # An unresolvable reference would otherwise sit idle for the whole soak window before
- # retiring, and a reference resolved late would measure whatever the metric had become.
- stored_config = spec["config"]
- config = parse_check_config(spec["kind"], stored_config)
- if isinstance(config, MetricThresholdConfig) and config.metric_id is not None:
- try:
- stored_config = {**stored_config, "query": resolve_check_query(config, report)}
- except ValueError as error:
- return Response(
- {"error": f"This check cannot run: {error}."},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- # Resolved before the locked transaction — a bad X-PostHog-Task-Id header must 400 before
- # anything mutates, and its task lookup has no business inside the lock.
- attribution = resolve_request_attribution(request, self.team.id)
-
- with transaction.atomic():
- # The cap is a count and then an insert, so it only holds if concurrent creates
- # serialize. Row-lock the report first, the lock `enforce_report_task_cap` takes to cap
- # a report's tasks the same way.
- locked_report = SignalReport.objects.select_for_update().filter(id=report.id, team_id=self.team.id).first()
- if locked_report is None:
- raise NotFound()
-
- active_checks = SignalReportCheck.objects.for_team(self.team.id).filter(
- report_id=locked_report.id, status=SignalReportCheck.Status.ACTIVE
- )
- if active_checks.count() >= MAX_ACTIVE_CHECKS_PER_REPORT:
- return Response(
- {"error": f"A report may carry at most {MAX_ACTIVE_CHECKS_PER_REPORT} active checks."},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- check = SignalReportCheck.objects.for_team(locked_report.team_id).create(
- # The report's own environment team, never a canonicalized one: the report's reads
- # and its artefact log filter by it.
- team_id=locked_report.team_id,
- report_id=locked_report.id,
- title=spec["title"],
- rationale=spec.get("rationale", ""),
- kind=spec["kind"],
- config=stored_config,
- next_run_at=spec["next_run_at"],
- run_interval_minutes=spec.get("run_interval_minutes"),
- runs_remaining=spec["runs_remaining"],
- expires_at=spec["expires_at"],
- actor_kind=attribution.kind,
- actor_agent=attribution.agent_name,
- created_by_id=attribution.user_id,
- task_id=attribution.task_id,
- )
- # Post-commit, so a check the cap or a rollback rejected is never counted as written.
- transaction.on_commit(partial(capture_report_check_created, self.team, check))
- return Response(self.get_serializer(check).data, status=status.HTTP_201_CREATED)
-
def destroy(self, request: Request, *args, **kwargs) -> Response:
check = cast(SignalReportCheck, self.get_object())
# One conditional update rather than a read and then a write. A run that commits its verdict
@@ -4427,7 +4348,7 @@ class SignalReportCheckViewSet(
# overwrite the status that artefact explains.
cancelled = (
SignalReportCheck.objects.for_team(self.team.id)
- .filter(id=check.id, status=SignalReportCheck.Status.ACTIVE)
+ .filter(id=check.id, status__in=SignalReportCheck.OPEN_STATUSES)
.update(status=SignalReportCheck.Status.CANCELLED, updated_at=timezone.now())
)
check.refresh_from_db()
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 4446d91ba2a7..6c91f83f5b09 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -1105,6 +1105,7 @@ export interface SignalReportRefundResponseApi {
* * `endpoints` - endpoints
* * `pganalyze` - pganalyze
* * `signals_scout` - signals_scout
+ * * `signals_check` - signals_check
* * `logs` - logs
* * `health_checks` - health_checks
* * `replay_vision` - replay_vision
@@ -1158,6 +1159,7 @@ export const SignalSourceProductApi = {
Endpoints: 'endpoints',
Pganalyze: 'pganalyze',
SignalsScout: 'signals_scout',
+ SignalsCheck: 'signals_check',
Logs: 'logs',
HealthChecks: 'health_checks',
ReplayVision: 'replay_vision',
@@ -1221,6 +1223,7 @@ export const SignalSourceProductApi = {
* * `ci_broken_default_branch` - ci_broken_default_branch
* * `ci_duration_regression` - ci_duration_regression
* * `search_opportunity` - search_opportunity
+ * * `check_failed` - check_failed
*/
export type SignalSourceTypeApi = (typeof SignalSourceTypeApi)[keyof typeof SignalSourceTypeApi]
@@ -1247,6 +1250,7 @@ export const SignalSourceTypeApi = {
CiBrokenDefaultBranch: 'ci_broken_default_branch',
CiDurationRegression: 'ci_duration_regression',
SearchOpportunity: 'search_opportunity',
+ CheckFailed: 'check_failed',
} as const
export type ProblemTypeEnumApi = (typeof ProblemTypeEnumApi)[keyof typeof ProblemTypeEnumApi]
@@ -1435,6 +1439,16 @@ export interface SignalsScoutSignalExtraApi {
mcp_trace_id?: string | null
}
+export interface CheckFailedSignalExtraApi {
+ check_id: string
+ report_id: string
+ check_title: string
+ explanation: string
+ observed_value?: number | null
+ baseline_value?: number | null
+ threshold?: string | null
+}
+
export type LogsAlertStateChangeSignalExtraActionEnumApi =
(typeof LogsAlertStateChangeSignalExtraActionEnumApi)[keyof typeof LogsAlertStateChangeSignalExtraActionEnumApi]
@@ -1840,6 +1854,7 @@ export type SignalExtraApi =
| EndpointExecutionFailedSignalExtraApi
| EndpointBreakdownLimitExceededSignalExtraApi
| SignalsScoutSignalExtraApi
+ | CheckFailedSignalExtraApi
| LogsAlertStateChangeSignalExtraApi
| ReplayVisionScannerFindingSignalExtraApi
| AnalyticsAnomalyInvestigationSignalExtraApi
@@ -1930,6 +1945,7 @@ export interface SignalNodeApi {
* * `endpoints` - endpoints
* * `pganalyze` - pganalyze
* * `signals_scout` - signals_scout
+ * * `signals_check` - signals_check
* * `logs` - logs
* * `health_checks` - health_checks
* * `replay_vision` - replay_vision
@@ -1992,7 +2008,8 @@ export interface SignalNodeApi {
* * `ci_flaky_check` - ci_flaky_check
* * `ci_broken_default_branch` - ci_broken_default_branch
* * `ci_duration_regression` - ci_duration_regression
- * * `search_opportunity` - search_opportunity */
+ * * `search_opportunity` - search_opportunity
+ * * `check_failed` - check_failed */
source_type: SignalSourceTypeApi
/** Emitter-scoped id of the underlying object (issue, ticket, ...). */
source_id: string
@@ -2275,6 +2292,7 @@ export const SignalReportCheckKindEnumApi = {
} as const
/**
+ * * `pending` - Pending
* * `active` - Active
* * `passed` - Passed
* * `failed` - Failed
@@ -2286,6 +2304,7 @@ export type SignalReportCheckStatusEnumApi =
(typeof SignalReportCheckStatusEnumApi)[keyof typeof SignalReportCheckStatusEnumApi]
export const SignalReportCheckStatusEnumApi = {
+ Pending: 'pending',
Active: 'active',
Passed: 'passed',
Failed: 'failed',
@@ -2412,8 +2431,9 @@ export interface SignalReportCheckApi {
* * `metric_threshold` - Metric Threshold
* * `agent` - Agent */
readonly kind: SignalReportCheckKindEnumApi
- /** `active` while the check still runs; every other value is terminal.
+ /** `pending` while the check waits for the report to resolve, `active` while it still runs; every other value is terminal.
*
+ * * `pending` - Pending
* * `active` - Active
* * `passed` - Passed
* * `failed` - Failed
@@ -2423,8 +2443,13 @@ export interface SignalReportCheckApi {
readonly status: SignalReportCheckStatusEnumApi
/** What the check measures and what the result must satisfy; the shape depends on `kind`. `query` and `baseline_value` are null when you cannot read the data they describe. */
config: SignalReportCheckConfigApi
- /** When the coordinator next evaluates the check. */
+ /** When the coordinator next evaluates the check. Provisional while the check is `pending`: the report resolving is what sets it. */
readonly next_run_at: string
+ /**
+ * How long after the report resolves a `pending` check waits before its first run. Null on a check that named its own `next_run_at`.
+ * @nullable
+ */
+ readonly soak_minutes: number | null
/**
* Gap between runs for a recurring check; null for a one-shot.
* @nullable
@@ -2460,49 +2485,6 @@ export interface PaginatedSignalReportCheckListApi {
results: SignalReportCheckApi[]
}
-/**
- * Request body for creating a check on a report.
- *
- * The schedule is the check's own: `next_run_at` says when to look, rather than the system
- * deriving a soak window from a merged pull request that many fixes never have.
- */
-export interface SignalReportCheckWriteApi {
- /**
- * Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.
- * @maxLength 200
- */
- title: string
- /**
- * Why the check is worth running.
- * @maxLength 2000
- */
- rationale?: string
- /** How the check is evaluated.
- *
- * * `metric_threshold` - Metric Threshold
- * * `agent` - Agent */
- kind: SignalReportCheckKindEnumApi
- /** What the check measures and what the result must satisfy; the shape depends on `kind`. */
- config: SignalReportCheckConfigApi
- /** When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now. */
- next_run_at?: string
- /**
- * Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.
- * @minimum 360
- * @maximum 129600
- * @nullable
- */
- run_interval_minutes?: number | null
- /**
- * How many times to evaluate the check, at most 10. Defaults to 1.
- * @minimum 1
- * @maximum 10
- */
- runs_remaining?: number
- /** Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first. */
- expires_at?: string
-}
-
export interface SignalReportBulkStateRequestApi {
/** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, 'potential' to snooze/reopen it for later review, or 'resolved' when the work this report asked for has been done. Resolving is only allowed from a researched status (ready or pending_input) or a suppressed report; other statuses return 409 (skipped in bulk). Dismissing or resolving closes the report's open implementation PR, if it has one.
*
@@ -5052,6 +5034,82 @@ export interface RecordStructuredOutputResponseApi {
record_ids: string[]
}
+/**
+ * Request body for `scout-report-check-cancel`.
+ */
+export interface CancelReportCheckRequestApi {
+ /** The check to stop. Its recorded results stay on the report. */
+ check_id: string
+}
+
+/**
+ * One check as a scout run reads it back.
+ */
+export interface ScoutCheckSummaryApi {
+ /** The check. */
+ check_id: string
+ /** The report it is attached to. */
+ report_id: string
+ /** The expectation the check states. */
+ title: string
+ /** `metric_threshold` (the coordinator measures it) or `agent` (a run does). */
+ kind: string
+ /** `pending` while the check waits for the report to resolve, `active` while it still runs; every other value is terminal. */
+ status: string
+ /** When the check next runs. Provisional while it is `pending`. */
+ next_run_at: string
+ /**
+ * Verdict of the most recent run; null before the first.
+ * @nullable
+ */
+ last_outcome: string | null
+}
+
+/**
+ * Request body for `scout-report-check-create`: one forward-looking check on a report.
+ *
+ * The REST body plus the report it attaches to. Subclassed rather than restated so the schedule
+ * bounds a scout writes under are the ones the endpoint enforces, with no second copy to drift.
+ */
+export interface CreateReportCheckRequestApi {
+ /**
+ * Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.
+ * @maxLength 200
+ */
+ title: string
+ /**
+ * Why the check is worth running.
+ * @maxLength 2000
+ */
+ rationale?: string
+ /** How the check is evaluated.
+ *
+ * * `metric_threshold` - Metric Threshold
+ * * `agent` - Agent */
+ kind: SignalReportCheckKindEnumApi
+ /** What the check measures and what the result must satisfy; the shape depends on `kind`. */
+ config: SignalReportCheckConfigApi
+ /** When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now. */
+ next_run_at?: string
+ /**
+ * Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.
+ * @minimum 360
+ * @maximum 129600
+ * @nullable
+ */
+ run_interval_minutes?: number | null
+ /**
+ * How many times to evaluate the check, at most 10. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ runs_remaining?: number
+ /** Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first. */
+ expires_at?: string
+ /** The report the check attaches to. */
+ report_id: string
+}
+
/**
* What one scout spent in the window, and what it produced for that spend.
*/
@@ -5332,6 +5390,7 @@ export interface ScoutSuggestionRefreshApi {
* * `error_tracking` - Error tracking
* * `pganalyze` - pganalyze
* * `signals_scout` - Signals scout
+ * * `signals_check` - Report check
* * `logs` - Logs
* * `health_checks` - Health checks
* * `endpoints` - Endpoints
@@ -5385,6 +5444,7 @@ export const SignalSourceProductEnumApi = {
ErrorTracking: 'error_tracking',
Pganalyze: 'pganalyze',
SignalsScout: 'signals_scout',
+ SignalsCheck: 'signals_check',
Logs: 'logs',
HealthChecks: 'health_checks',
Endpoints: 'endpoints',
@@ -5914,6 +5974,13 @@ export type SignalsScoutRunsListParams = {
text?: string
}
+export type SignalsScoutReportChecksListParams = {
+ /**
+ * The report whose checks to list.
+ */
+ report_id: string
+}
+
export type SignalsScoutRunsCostsParams = {
/**
* Window in days over runs' `created_at` (default 7). Only 7 is accepted today — it matches the window the roster's fleet headline spans, so every number on the page describes one span.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 2fdae056f7a7..ba318bc97d74 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -9,7 +9,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ CancelReportCheckRequestApi,
CommitDiffResponseApi,
+ CreateReportCheckRequestApi,
EditReportRequestApi,
EditReportResponseApi,
EmitFindingRequestApi,
@@ -49,6 +51,7 @@ import type {
ReportSignalsResponseApi,
ScoutChatTaskApi,
ScoutChatTaskCreateApi,
+ ScoutCheckSummaryApi,
ScoutCostsApi,
ScoutEmissionReportLinkApi,
ScoutMemberApi,
@@ -68,7 +71,6 @@ import type {
SignalReportBulkStateRequestApi,
SignalReportBulkStateResponseApi,
SignalReportCheckApi,
- SignalReportCheckWriteApi,
SignalReportClaimApi,
SignalReportFeedbackRequestApi,
SignalReportFeedbackResponseApi,
@@ -107,6 +109,7 @@ import type {
SignalsScoutMembersListParams,
SignalsScoutNotesListParams,
SignalsScoutProjectProfileGetParams,
+ SignalsScoutReportChecksListParams,
SignalsScoutRunsCostsParams,
SignalsScoutRunsFindingsSummaryParams,
SignalsScoutRunsListParams,
@@ -866,40 +869,21 @@ export const signalsReportChecksList = async (
})
}
-export const getSignalsReportChecksCreateUrl = (projectId: string, reportId: string) => {
- return `/api/projects/${projectId}/signals/reports/${reportId}/checks/`
-}
-
-/**
- * Schedule a re-measurement of the report's claim. A `metric_threshold` check runs one bounded Trends query and compares the result, so it needs no agent run. An `agent` check runs a scout instead, for a claim no single number settles; it runs on the scout its config names, or on the fleet's follow-up scout when it names none.
- * @summary Create a check on a report
- */
-export const signalsReportChecksCreate = async (
- projectId: string,
- reportId: string,
- signalReportCheckWriteApi: SignalReportCheckWriteApi,
- options?: RequestInit
-): Promise<SignalReportCheckApi> => {
- return apiMutator<SignalReportCheckApi>(getSignalsReportChecksCreateUrl(projectId, reportId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(signalReportCheckWriteApi),
- })
-}
-
export const getSignalsReportChecksRetrieveUrl = (projectId: string, reportId: string, id: string) => {
return `/api/projects/${projectId}/signals/reports/${reportId}/checks/${id}/`
}
/**
- * Checks attached to a signal report: read, create, and cancel.
+ * Checks attached to a signal report: read and cancel.
*
- * There is no update: a check is a claim about the future, and editing its threshold after a
- * result would make the recorded verdict unreadable. Cancel it and write a new one.
+ * There is no create here. A check is authored by a scout run or by the research pipeline, both
+ * through `report_check_authoring.create_check`. An `agent` check puts its author's prose in front
+ * of a privileged scout run, and `task:write` does not authorize that, so no caller-facing
+ * endpoint accepts one. Anyone who can read the report can read its checks, and a person can
+ * still stop one.
*
- * Writes are attributed the same way artefact writes are — to the task named by the
- * `X-PostHog-Task-Id` header when present, else to the requesting user.
+ * There is no update: a check is a claim about the future, and editing its threshold after a
+ * result would make the recorded verdict unreadable. Cancel it and let its author write a new one.
* @summary Get a single check
*/
export const signalsReportChecksRetrieve = async (
@@ -919,7 +903,7 @@ export const getSignalsReportChecksDestroyUrl = (projectId: string, reportId: st
}
/**
- * Stop an active check. Its recorded results stay on the report.
+ * Stop a check that is still open — active, or pending its report resolving. Its recorded results stay on the report.
* @summary Cancel a check
*/
export const signalsReportChecksDestroy = async (
@@ -1585,6 +1569,86 @@ export const signalsScoutRecordOutput = async (
})
}
+export const getSignalsScoutReportCheckCancelUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/signals/scout/runs/${runId}/report-check-cancel/`
+}
+
+/**
+ * Stop a check that is no longer worth running — the claim it re-measures has changed, or a better check replaces it. Results it already recorded stay on the report. A check that has already finished cannot be cancelled.
+ * @summary Cancel a follow-up check
+ */
+export const signalsScoutReportCheckCancel = async (
+ projectId: string,
+ runId: string,
+ cancelReportCheckRequestApi: CancelReportCheckRequestApi,
+ options?: RequestInit
+): Promise<ScoutCheckSummaryApi> => {
+ return apiMutator<ScoutCheckSummaryApi>(getSignalsScoutReportCheckCancelUrl(projectId, runId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(cancelReportCheckRequestApi),
+ })
+}
+
+export const getSignalsScoutReportCheckCreateUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/signals/scout/runs/${runId}/report-check-create/`
+}
+
+/**
+ * Schedule a re-measurement of a report's claim, so whether the fix held becomes a stored fact instead of something a future run has to remember to look for. A `metric_threshold` check runs one bounded Trends query and compares the result. An `agent` check runs a scout instead, for a claim no single number settles.
+ * @summary Write a follow-up check on a report
+ */
+export const signalsScoutReportCheckCreate = async (
+ projectId: string,
+ runId: string,
+ createReportCheckRequestApi: CreateReportCheckRequestApi,
+ options?: RequestInit
+): Promise<ScoutCheckSummaryApi> => {
+ return apiMutator<ScoutCheckSummaryApi>(getSignalsScoutReportCheckCreateUrl(projectId, runId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createReportCheckRequestApi),
+ })
+}
+
+export const getSignalsScoutReportChecksListUrl = (
+ projectId: string,
+ runId: string,
+ params: SignalsScoutReportChecksListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/scout/runs/${runId}/report-checks/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/scout/runs/${runId}/report-checks/`
+}
+
+/**
+ * Every check on one report, newest first. Read this before writing one: a report already carrying a check for the same claim needs no second one, and a report holds at most five open checks at a time.
+ * @summary List a report's follow-up checks
+ */
+export const signalsScoutReportChecksList = async (
+ projectId: string,
+ runId: string,
+ params: SignalsScoutReportChecksListParams,
+ options?: RequestInit
+): Promise<ScoutCheckSummaryApi[]> => {
+ return apiMutator<ScoutCheckSummaryApi[]>(getSignalsScoutReportChecksListUrl(projectId, runId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsScoutRunsCostsUrl = (projectId: string, params?: SignalsScoutRunsCostsParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 843058ba1388..40caf0a82dd8 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -313,144 +313,6 @@ export const SignalsReportArtefactsPartialUpdateBody = /* @__PURE__ */ zod
"Body for replacing the content of an existing artefact (addressed by id).\n\nPer-type schema validation happens in the view, which knows the artefact's type."
)
-/**
- * Schedule a re-measurement of the report's claim. A `metric_threshold` check runs one bounded Trends query and compares the result, so it needs no agent run. An `agent` check runs a scout instead, for a claim no single number settles; it runs on the scout its config names, or on the fleet's follow-up scout when it names none.
- * @summary Create a check on a report
- */
-export const signalsReportChecksCreateBodyTitleMax = 200
-
-export const signalsReportChecksCreateBodyRationaleMax = 2000
-
-export const signalsReportChecksCreateBodyConfigOneTwoInstructionsMax = 2000
-
-export const signalsReportChecksCreateBodyConfigOneTwoSkillNameOneMax = 200
-
-export const signalsReportChecksCreateBodyConfigOneTwoProbeHintsMax = 5
-
-export const signalsReportChecksCreateBodyRunIntervalMinutesMin = 360
-export const signalsReportChecksCreateBodyRunIntervalMinutesMax = 129600
-
-export const signalsReportChecksCreateBodyRunsRemainingMax = 10
-
-export const SignalsReportChecksCreateBody = /* @__PURE__ */ zod
- .object({
- title: zod
- .string()
- .max(signalsReportChecksCreateBodyTitleMax)
- .describe('Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.'),
- rationale: zod
- .string()
- .max(signalsReportChecksCreateBodyRationaleMax)
- .optional()
- .describe('Why the check is worth running.'),
- kind: zod
- .enum(['metric_threshold', 'agent'])
- .describe('\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent')
- .describe('How the check is evaluated.\n\n\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent'),
- config: zod
- .union([
- zod
- .object({
- metric_id: zod
- .union([zod.string(), zod.null()])
- .optional()
- .describe(
- "Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created."
- ),
- query: zod
- .union([zod.record(zod.string(), zod.unknown()), zod.null()])
- .optional()
- .describe(
- 'Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.'
- ),
- comparison: zod
- .object({
- operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),
- value: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe('The bound for `lte` and `gte`; unused by `between`.'),
- bounds: zod
- .union([
- zod.object({
- lower: zod.number(),
- upper: zod.number(),
- }),
- zod.null(),
- ])
- .optional()
- .describe('The inclusive range for `between`; unused by `lte` and `gte`.'),
- })
- .describe('What the measured value must satisfy to pass.'),
- baseline_value: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe(
- 'The value observed when the check was written, recorded on each result for context.'
- ),
- })
- .describe(
- "A deterministic check: measure one number, compare it, record the verdict.\n\nThe number comes either from a metric the report already shows (``metric_id``) or from a query\nthe author supplies. Both end up in the same runner, so a supplied query must satisfy the live\nmetric contract — the node allowlist, the bounded window, and the single-output-series rule.\n\nA caller names one source. When it names a metric, the create path copies that metric's query\ninto ``query`` before the row is stored, so the check keeps measuring what its author saw even if\nthe report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.\n\nUnknown keys are refused rather than ignored, so a misspelled field name is reported instead of\nbeing dropped in silence and stored as it arrived."
- ),
- zod
- .object({
- instructions: zod
- .string()
- .max(signalsReportChecksCreateBodyConfigOneTwoInstructionsMax)
- .describe("What the run must establish, in the author's own words."),
- skill_name: zod
- .union([
- zod.string().max(signalsReportChecksCreateBodyConfigOneTwoSkillNameOneMax),
- zod.null(),
- ])
- .optional()
- .describe(
- "Scout skill that runs the check. Omit it to run on the fleet's follow-up scout, which is the right lane for a report no scout authored."
- ),
- probe_hints: zod
- .array(zod.string())
- .max(signalsReportChecksCreateBodyConfigOneTwoProbeHintsMax)
- .optional()
- .describe(
- 'Concrete places to look, such as an issue id, a service name, or a query to repeat.'
- ),
- })
- .describe(
- 'A check a scout run answers: re-probe the report\'s claim and record one verdict.\n\nThe kind for a claim no single number settles. A resolved error-tracking report is the usual\ncase: \"did the exception stop?\" needs the issue looked up, its recent events read, and the\nstack compared against what the fix changed, which is a run rather than a comparison.\n\nEverything here is prompt material a scout reads, so it is untrusted by construction: it renders\nin the run block the agent is told to weigh, never in the instructions it is told to follow. The\nverdict still comes back through `scout-check-record-result`, so instructions cannot widen what\na check run may write.\n\n``skill_name`` names the lane. Most reports are pipeline-authored and have no scout behind them,\nso it is optional: a check that names none runs on the fleet\'s follow-up scout\n(see ``report_check_agent.FALLBACK_CHECK_SKILL_NAME``).'
- ),
- ])
- .describe('What the check measures and what the result must satisfy; the shape depends on `kind`.'),
- next_run_at: zod.iso
- .datetime({ offset: true })
- .optional()
- .describe(
- 'When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now.'
- ),
- run_interval_minutes: zod
- .number()
- .min(signalsReportChecksCreateBodyRunIntervalMinutesMin)
- .max(signalsReportChecksCreateBodyRunIntervalMinutesMax)
- .nullish()
- .describe(
- 'Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.'
- ),
- runs_remaining: zod
- .number()
- .min(1)
- .max(signalsReportChecksCreateBodyRunsRemainingMax)
- .optional()
- .describe('How many times to evaluate the check, at most 10. Defaults to 1.'),
- expires_at: zod.iso
- .datetime({ offset: true })
- .optional()
- .describe(
- 'Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first.'
- ),
- })
- .describe(
- "Request body for creating a check on a report.\n\nThe schedule is the check's own: `next_run_at` says when to look, rather than the system\nderiving a soak window from a merged pull request that many fixes never have."
- )
-
/**
* Transition many reports to a new state in one call.
*
@@ -2050,6 +1912,155 @@ export const SignalsScoutRecordOutputBody = /* @__PURE__ */ zod
})
.describe('Request body for `scout-record-output`: a batch of schema-validated records.')
+/**
+ * Stop a check that is no longer worth running — the claim it re-measures has changed, or a better check replaces it. Results it already recorded stay on the report. A check that has already finished cannot be cancelled.
+ * @summary Cancel a follow-up check
+ */
+export const SignalsScoutReportCheckCancelBody = /* @__PURE__ */ zod
+ .object({
+ check_id: zod.uuid().describe('The check to stop. Its recorded results stay on the report.'),
+ })
+ .describe('Request body for `scout-report-check-cancel`.')
+
+/**
+ * Schedule a re-measurement of a report's claim, so whether the fix held becomes a stored fact instead of something a future run has to remember to look for. A `metric_threshold` check runs one bounded Trends query and compares the result. An `agent` check runs a scout instead, for a claim no single number settles.
+ * @summary Write a follow-up check on a report
+ */
+export const signalsScoutReportCheckCreateBodyTitleMax = 200
+
+export const signalsScoutReportCheckCreateBodyRationaleMax = 2000
+
+export const signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax = 2000
+
+export const signalsScoutReportCheckCreateBodyConfigOneTwoSkillNameOneMax = 200
+
+export const signalsScoutReportCheckCreateBodyConfigOneTwoProbeHintsMax = 5
+
+export const signalsScoutReportCheckCreateBodyRunIntervalMinutesMin = 360
+export const signalsScoutReportCheckCreateBodyRunIntervalMinutesMax = 129600
+
+export const signalsScoutReportCheckCreateBodyRunsRemainingMax = 10
+
+export const SignalsScoutReportCheckCreateBody = /* @__PURE__ */ zod
+ .object({
+ title: zod
+ .string()
+ .max(signalsScoutReportCheckCreateBodyTitleMax)
+ .describe('Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.'),
+ rationale: zod
+ .string()
+ .max(signalsScoutReportCheckCreateBodyRationaleMax)
+ .optional()
+ .describe('Why the check is worth running.'),
+ kind: zod
+ .enum(['metric_threshold', 'agent'])
+ .describe('\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent')
+ .describe('How the check is evaluated.\n\n\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent'),
+ config: zod
+ .union([
+ zod
+ .object({
+ metric_id: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ "Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created."
+ ),
+ query: zod
+ .union([zod.record(zod.string(), zod.unknown()), zod.null()])
+ .optional()
+ .describe(
+ 'Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.'
+ ),
+ comparison: zod
+ .object({
+ operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),
+ value: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('The bound for `lte` and `gte`; unused by `between`.'),
+ bounds: zod
+ .union([
+ zod.object({
+ lower: zod.number(),
+ upper: zod.number(),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('The inclusive range for `between`; unused by `lte` and `gte`.'),
+ })
+ .describe('What the measured value must satisfy to pass.'),
+ baseline_value: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe(
+ 'The value observed when the check was written, recorded on each result for context.'
+ ),
+ })
+ .describe(
+ "A deterministic check: measure one number, compare it, record the verdict.\n\nThe number comes either from a metric the report already shows (``metric_id``) or from a query\nthe author supplies. Both end up in the same runner, so a supplied query must satisfy the live\nmetric contract — the node allowlist, the bounded window, and the single-output-series rule.\n\nA caller names one source. When it names a metric, the create path copies that metric's query\ninto ``query`` before the row is stored, so the check keeps measuring what its author saw even if\nthe report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.\n\nUnknown keys are refused rather than ignored, so a misspelled field name is reported instead of\nbeing dropped in silence and stored as it arrived."
+ ),
+ zod
+ .object({
+ instructions: zod
+ .string()
+ .max(signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax)
+ .describe("What the run must establish, in the author's own words."),
+ skill_name: zod
+ .union([
+ zod.string().max(signalsScoutReportCheckCreateBodyConfigOneTwoSkillNameOneMax),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Scout skill that runs the check. Omit it to run on the fleet's follow-up scout, which is the right lane for a report no scout authored."
+ ),
+ probe_hints: zod
+ .array(zod.string())
+ .max(signalsScoutReportCheckCreateBodyConfigOneTwoProbeHintsMax)
+ .optional()
+ .describe(
+ 'Concrete places to look, such as an issue id, a service name, or a query to repeat.'
+ ),
+ })
+ .describe(
+ 'A check a scout run answers: re-probe the report\'s claim and record one verdict.\n\nThe kind for a claim no single number settles. A resolved error-tracking report is the usual\ncase: \"did the exception stop?\" needs the issue looked up, its recent events read, and the\nstack compared against what the fix changed, which is a run rather than a comparison.\n\nEverything here is prompt material a scout reads, so it is untrusted by construction: it renders\nin the run block the agent is told to weigh, never in the instructions it is told to follow. The\nverdict still comes back through `scout-check-record-result`, so instructions cannot widen what\na check run may write.\n\n``skill_name`` names the lane. Most reports are pipeline-authored and have no scout behind them,\nso it is optional: a check that names none runs on the fleet\'s follow-up scout\n(see ``report_check_agent.FALLBACK_CHECK_SKILL_NAME``).'
+ ),
+ ])
+ .describe('What the check measures and what the result must satisfy; the shape depends on `kind`.'),
+ next_run_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now.'
+ ),
+ run_interval_minutes: zod
+ .number()
+ .min(signalsScoutReportCheckCreateBodyRunIntervalMinutesMin)
+ .max(signalsScoutReportCheckCreateBodyRunIntervalMinutesMax)
+ .nullish()
+ .describe(
+ 'Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.'
+ ),
+ runs_remaining: zod
+ .number()
+ .min(1)
+ .max(signalsScoutReportCheckCreateBodyRunsRemainingMax)
+ .optional()
+ .describe('How many times to evaluate the check, at most 10. Defaults to 1.'),
+ expires_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first.'
+ ),
+ report_id: zod.uuid().describe('The report the check attaches to.'),
+ })
+ .describe(
+ 'Request body for `scout-report-check-create`: one forward-looking check on a report.\n\nThe REST body plus the report it attaches to. Subclassed rather than restated so the schedule\nbounds a scout writes under are the ones the endpoint enforces, with no second copy to drift.'
+ )
+
/**
* Batched form of the per-run emissions endpoint: return the findings every requested `SignalScoutRun` emitted, flattened newest-first, in a single request. Each row carries its `run_id`, so the caller can regroup by run. The findings UI uses this to load the whole recent window in one round-trip instead of one request per run. Strictly team-scoped — run ids belonging to another team contribute no rows (no per-run 404; one stale id never fails the batch).
* @summary List emitted findings for many runs at once
@@ -2167,6 +2178,7 @@ export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({
'error_tracking',
'pganalyze',
'signals_scout',
+ 'signals_check',
'logs',
'health_checks',
'endpoints',
@@ -2208,7 +2220,7 @@ export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({
'google_search_console',
])
.describe(
- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `signals_check` - Report check\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
),
source_type: zod
.enum([
@@ -2258,6 +2270,7 @@ export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({
'error_tracking',
'pganalyze',
'signals_scout',
+ 'signals_check',
'logs',
'health_checks',
'endpoints',
@@ -2299,7 +2312,7 @@ export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({
'google_search_console',
])
.describe(
- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `signals_check` - Report check\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
),
source_type: zod
.enum([
@@ -2349,6 +2362,7 @@ export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object(
'error_tracking',
'pganalyze',
'signals_scout',
+ 'signals_check',
'logs',
'health_checks',
'endpoints',
@@ -2391,7 +2405,7 @@ export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object(
])
.optional()
.describe(
- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `signals_check` - Report check\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
),
source_type: zod
.enum([
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index aad397bf1fcd..6be06a141303 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -112,55 +112,6 @@ tools:
Replace the `content` of an existing artefact, addressed by its id, when new information supersedes it. The
new content is validated against the artefact type's schema. Editing the latest row of a status type changes
the report's canonical status; to re-assess while keeping history, append a new artefact instead.
- inbox-report-checks-create:
- operation: signals_report_checks_create
- enabled: true
- scopes:
- - task:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: false
- enrich_url: '{params.report_id}'
- title: Schedule a follow-up check on a report
- description: >
- Schedule a re-measurement of what a report claimed, so "did the fix hold?" becomes a verdict stored on the
- report instead of something a person re-derives weeks later. A check carries one expectation, one time to
- look, and how many times to look. The coordinator runs it when it comes due and appends the verdict to the
- report as a `check_result` entry people read in the inbox. Write one whenever the outcome is measurable;
- skip one for an observation with no "fixed" state to measure.
-
- Choose the `kind` by what settles the claim. A `metric_threshold` check measures one number and compares it,
- so it costs one query and no agent run. Its config takes a `comparison` (`lte`, `gte`, or `between`) plus
- either a `metric_id` the report already shows or your own `query` — never both. A supplied query is a
- bounded live InsightVizNode/TrendsQuery with one output series, the same shape a report metric carries. A
- named metric's query is copied onto the check as you create it, so the check keeps measuring what you saw.
- Pass the value you measured today as `baseline_value` to give the verdict context. An `agent` check runs a
- scout instead, for a claim no single number settles: "did the exception stop?" needs the issue looked up and
- its recent events read. Its config takes `instructions` saying what the run must establish, optional
- `probe_hints` naming where to look (an issue id, a service name, a query to repeat), and an optional
- `skill_name` for the scout that runs it — omit the name and the fleet's follow-up scout takes it.
-
- Allow for deploy and soak time, because unchanged numbers prove nothing before the fix is live.
- `next_run_at` defaults to a week out, and a recurring check may not re-measure more often than every 6
- hours; anything faster is an alert and belongs in the alerts product. Leave `run_interval_minutes` out for a
- one-shot check. A report carries at most 5 active checks, so list them first and extend what is already
- watching the claim rather than adding a duplicate.
- inbox-report-checks-delete:
- operation: signals_report_checks_destroy
- enabled: true
- scopes:
- - task:write
- annotations:
- readOnly: false
- destructive: true
- idempotent: true
- title: Cancel a check
- description: >
- Stop one active check by its id, freeing a slot against the report's limit of 5. Verdicts it already
- recorded stay on the report. There is no update: a check is a claim about the future, and moving its
- threshold after a result would make the recorded verdict unreadable, so cancel the check and write a new
- one. A check that already finished cannot be cancelled.
inbox-report-checks-list:
operation: signals_report_checks_list
enabled: true
@@ -175,8 +126,9 @@ tools:
description: >
List the follow-up checks on one report, newest first. Each row carries the expectation and why it was
written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status`
- (`active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. Read this
- before you write a check, so you extend or replace what already watches the claim. `query` and
+ (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A
+ `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs
+ and by the research pipeline, so this surface reads them and does not create them. `query` and
`baseline_value` read as null when you cannot read the data they describe.
inbox-report-checks-retrieve:
operation: signals_report_checks_retrieve
@@ -903,6 +855,57 @@ tools:
whole call with nothing written — fix and resubmit the batch. Each accepted record lands in the project's
event stream as a `$scout_structured_output` event, queryable like any event. Idempotent — event ids are
deterministic, so retrying a call that failed with a delivery error (503) cannot double-count.
+ scout-report-check-cancel:
+ operation: signals_scout_report_check_cancel
+ enabled: true
+ scopes:
+ - signal_scout_report:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Cancel a follow-up check
+ description: >
+ Stop a check that is no longer worth running — the claim it re-measures has changed, or a better check
+ replaces it. Results it already recorded stay on the report. A check that already finished cannot be
+ cancelled, and the call says so.
+ scout-report-check-create:
+ operation: signals_scout_report_check_create
+ enabled: true
+ scopes:
+ - signal_scout_report:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Write a follow-up check on a report
+ description: >
+ Schedule a re-measurement of a report's claim, so "did the fix hold?" becomes a stored fact instead of
+ something a future run has to remember to look for. Write one when this run surfaces something whose fix
+ would show up in data later. Use `metric_threshold` when a bounded query and a baseline exist: pass a
+ `config` with a `metric_id` naming one of the report's own metrics (or your own bounded Trends `query`), a
+ `comparison` (`lte` / `gte` / `between`) saying what the value must satisfy, and the `baseline_value` you
+ measured now. Use `agent` for a claim no single number settles: pass `instructions` saying what a later run
+ must establish and `probe_hints` naming the issue ids, services, or queries to look at; it runs on the scout
+ you name in `skill_name`, or on the fleet's follow-up scout when you name none. `next_run_at` is when to
+ first look, so allow deploy and soak time. The verdict lands on the report as a `check_result` entry people
+ read in the inbox. Check `scout-report-check-list` first: a report holds at most five open checks, and a
+ second check for the same claim is noise.
+ scout-report-check-list:
+ operation: signals_scout_report_checks_list
+ enabled: true
+ scopes:
+ - signal_scout_report:write
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List a report's follow-up checks
+ description: >
+ Every follow-up check on one report, newest first, with its kind, status, next run and last verdict. Read
+ this before writing a check: a report already carrying one for the same claim needs no second, and a report
+ holds at most five open checks at a time. A `pending` check is waiting for the report to resolve before its
+ clock starts; every status other than `pending` and `active` is terminal.
scout-run-now:
operation: signals_scout_config_run
enabled: true
@@ -1095,6 +1098,9 @@ tools:
signals-report-artefacts-diff:
operation: signals_report_artefacts_diff
enabled: false
+ signals-report-checks-destroy:
+ operation: signals_report_checks_destroy
+ enabled: false
signals-report-pr-checks:
operation: signals_report_pr_checks
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ce3ba1f923ba..5c20bf5f5c8c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6018,36 +6018,8 @@
"readOnlyHint": false
}
},
- "inbox-report-checks-create": {
- "description": "Schedule a re-measurement of what a report claimed, so \"did the fix hold?\" becomes a verdict stored on the report instead of something a person re-derives weeks later. A check carries one expectation, one time to look, and how many times to look. The coordinator runs it when it comes due and appends the verdict to the report as a `check_result` entry people read in the inbox. Write one whenever the outcome is measurable; skip one for an observation with no \"fixed\" state to measure.\nChoose the `kind` by what settles the claim. A `metric_threshold` check measures one number and compares it, so it costs one query and no agent run. Its config takes a `comparison` (`lte`, `gte`, or `between`) plus either a `metric_id` the report already shows or your own `query` — never both. A supplied query is a bounded live InsightVizNode/TrendsQuery with one output series, the same shape a report metric carries. A named metric's query is copied onto the check as you create it, so the check keeps measuring what you saw. Pass the value you measured today as `baseline_value` to give the verdict context. An `agent` check runs a scout instead, for a claim no single number settles: \"did the exception stop?\" needs the issue looked up and its recent events read. Its config takes `instructions` saying what the run must establish, optional `probe_hints` naming where to look (an issue id, a service name, a query to repeat), and an optional `skill_name` for the scout that runs it — omit the name and the fleet's follow-up scout takes it.\nAllow for deploy and soak time, because unchanged numbers prove nothing before the fix is live. `next_run_at` defaults to a week out, and a recurring check may not re-measure more often than every 6 hours; anything faster is an alert and belongs in the alerts product. Leave `run_interval_minutes` out for a one-shot check. A report carries at most 5 active checks, so list them first and extend what is already watching the claim rather than adding a duplicate.",
- "category": "Signals",
- "feature": "signals",
- "summary": "Schedule a follow-up check on a report",
- "title": "Schedule a follow-up check on a report",
- "required_scopes": ["task:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- }
- },
- "inbox-report-checks-delete": {
- "description": "Stop one active check by its id, freeing a slot against the report's limit of 5. Verdicts it already recorded stay on the report. There is no update: a check is a claim about the future, and moving its threshold after a result would make the recorded verdict unreadable, so cancel the check and write a new one. A check that already finished cannot be cancelled.",
- "category": "Signals",
- "feature": "signals",
- "summary": "Cancel a check",
- "title": "Cancel a check",
- "required_scopes": ["task:write"],
- "annotations": {
- "destructiveHint": true,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- }
- },
"inbox-report-checks-list": {
- "description": "List the follow-up checks on one report, newest first. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. Read this before you write a check, so you extend or replace what already watches the claim. `query` and `baseline_value` read as null when you cannot read the data they describe.",
+ "description": "List the follow-up checks on one report, newest first. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs and by the research pipeline, so this surface reads them and does not create them. `query` and `baseline_value` read as null when you cannot read the data they describe.",
"category": "Signals",
"feature": "signals",
"summary": "List a report's checks",
@@ -10148,6 +10120,48 @@
"readOnlyHint": false
}
},
+ "scout-report-check-cancel": {
+ "description": "Stop a check that is no longer worth running — the claim it re-measures has changed, or a better check replaces it. Results it already recorded stay on the report. A check that already finished cannot be cancelled, and the call says so.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Cancel a follow-up check",
+ "title": "Cancel a follow-up check",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "scout-report-check-create": {
+ "description": "Schedule a re-measurement of a report's claim, so \"did the fix hold?\" becomes a stored fact instead of something a future run has to remember to look for. Write one when this run surfaces something whose fix would show up in data later. Use `metric_threshold` when a bounded query and a baseline exist: pass a `config` with a `metric_id` naming one of the report's own metrics (or your own bounded Trends `query`), a `comparison` (`lte` / `gte` / `between`) saying what the value must satisfy, and the `baseline_value` you measured now. Use `agent` for a claim no single number settles: pass `instructions` saying what a later run must establish and `probe_hints` naming the issue ids, services, or queries to look at; it runs on the scout you name in `skill_name`, or on the fleet's follow-up scout when you name none. `next_run_at` is when to first look, so allow deploy and soak time. The verdict lands on the report as a `check_result` entry people read in the inbox. Check `scout-report-check-list` first: a report holds at most five open checks, and a second check for the same claim is noise.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Write a follow-up check on a report",
+ "title": "Write a follow-up check on a report",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "scout-report-check-list": {
+ "description": "Every follow-up check on one report, newest first, with its kind, status, next run and last verdict. Read this before writing a check: a report already carrying one for the same claim needs no second, and a report holds at most five open checks at a time. A `pending` check is waiting for the report to resolve before its clock starts; every status other than `pending` and `active` is terminal.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "List a report's follow-up checks",
+ "title": "List a report's follow-up checks",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"scout-run-now": {
"description": "Dispatch one on-demand run of a scout by its config `id`, regardless of its schedule — useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously and inherits the scheduled path's guards: it returns 429 if the project is over its Signals credits quota or its daily scout-run budget, and 409 if a run for this scout is already in progress. A manual run counts against the same daily run budget the scheduled runs draw from, so avoid triggering repeated runs of the same scout in a short window — each one consumes the project's scout-run allowance for the day. A manual run does not change the scout's schedule, and a disabled scout can still be run this way (to test before enabling). Pass an optional `note` to steer this run alone (\"focus on the checkout regression\"): the agent reads it next to the scout's durable notes and weighs it the same way, and it is never read by another run — use it instead of `scout-notes-create`, which would also steer every later scheduled run. A run carrying a note needs `llm_skill:write` as well, since the agent reads the note verbatim while holding privileged tools. Returns the workflow id immediately — poll `scout-runs-list` for the resulting run and its findings.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index f82c24a87549..cf63b3bdbe78 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6215,36 +6215,8 @@
"readOnlyHint": false
}
},
- "inbox-report-checks-create": {
- "description": "Schedule a re-measurement of what a report claimed, so \"did the fix hold?\" becomes a verdict stored on the report instead of something a person re-derives weeks later. A check carries one expectation, one time to look, and how many times to look. The coordinator runs it when it comes due and appends the verdict to the report as a `check_result` entry people read in the inbox. Write one whenever the outcome is measurable; skip one for an observation with no \"fixed\" state to measure.\nChoose the `kind` by what settles the claim. A `metric_threshold` check measures one number and compares it, so it costs one query and no agent run. Its config takes a `comparison` (`lte`, `gte`, or `between`) plus either a `metric_id` the report already shows or your own `query` — never both. A supplied query is a bounded live InsightVizNode/TrendsQuery with one output series, the same shape a report metric carries. A named metric's query is copied onto the check as you create it, so the check keeps measuring what you saw. Pass the value you measured today as `baseline_value` to give the verdict context. An `agent` check runs a scout instead, for a claim no single number settles: \"did the exception stop?\" needs the issue looked up and its recent events read. Its config takes `instructions` saying what the run must establish, optional `probe_hints` naming where to look (an issue id, a service name, a query to repeat), and an optional `skill_name` for the scout that runs it — omit the name and the fleet's follow-up scout takes it.\nAllow for deploy and soak time, because unchanged numbers prove nothing before the fix is live. `next_run_at` defaults to a week out, and a recurring check may not re-measure more often than every 6 hours; anything faster is an alert and belongs in the alerts product. Leave `run_interval_minutes` out for a one-shot check. A report carries at most 5 active checks, so list them first and extend what is already watching the claim rather than adding a duplicate.",
- "category": "Signals",
- "feature": "signals",
- "summary": "Schedule a follow-up check on a report",
- "title": "Schedule a follow-up check on a report",
- "required_scopes": ["task:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- }
- },
- "inbox-report-checks-delete": {
- "description": "Stop one active check by its id, freeing a slot against the report's limit of 5. Verdicts it already recorded stay on the report. There is no update: a check is a claim about the future, and moving its threshold after a result would make the recorded verdict unreadable, so cancel the check and write a new one. A check that already finished cannot be cancelled.",
- "category": "Signals",
- "feature": "signals",
- "summary": "Cancel a check",
- "title": "Cancel a check",
- "required_scopes": ["task:write"],
- "annotations": {
- "destructiveHint": true,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- }
- },
"inbox-report-checks-list": {
- "description": "List the follow-up checks on one report, newest first. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. Read this before you write a check, so you extend or replace what already watches the claim. `query` and `baseline_value` read as null when you cannot read the data they describe.",
+ "description": "List the follow-up checks on one report, newest first. Each row carries the expectation and why it was written, its schedule (`next_run_at`, `run_interval_minutes`, `runs_remaining`, `expires_at`), its `status` (`pending`, `active`, `passed`, `failed`, `errored`, `expired`, or `cancelled`) and its `last_outcome`. A `pending` check waits for its report to resolve before its clock starts. Checks are written by scout runs and by the research pipeline, so this surface reads them and does not create them. `query` and `baseline_value` read as null when you cannot read the data they describe.",
"category": "Signals",
"feature": "signals",
"summary": "List a report's checks",
@@ -10720,6 +10692,48 @@
"readOnlyHint": false
}
},
+ "scout-report-check-cancel": {
+ "description": "Stop a check that is no longer worth running — the claim it re-measures has changed, or a better check replaces it. Results it already recorded stay on the report. A check that already finished cannot be cancelled, and the call says so.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Cancel a follow-up check",
+ "title": "Cancel a follow-up check",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "scout-report-check-create": {
+ "description": "Schedule a re-measurement of a report's claim, so \"did the fix hold?\" becomes a stored fact instead of something a future run has to remember to look for. Write one when this run surfaces something whose fix would show up in data later. Use `metric_threshold` when a bounded query and a baseline exist: pass a `config` with a `metric_id` naming one of the report's own metrics (or your own bounded Trends `query`), a `comparison` (`lte` / `gte` / `between`) saying what the value must satisfy, and the `baseline_value` you measured now. Use `agent` for a claim no single number settles: pass `instructions` saying what a later run must establish and `probe_hints` naming the issue ids, services, or queries to look at; it runs on the scout you name in `skill_name`, or on the fleet's follow-up scout when you name none. `next_run_at` is when to first look, so allow deploy and soak time. The verdict lands on the report as a `check_result` entry people read in the inbox. Check `scout-report-check-list` first: a report holds at most five open checks, and a second check for the same claim is noise.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Write a follow-up check on a report",
+ "title": "Write a follow-up check on a report",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "scout-report-check-list": {
+ "description": "Every follow-up check on one report, newest first, with its kind, status, next run and last verdict. Read this before writing a check: a report already carrying one for the same claim needs no second, and a report holds at most five open checks at a time. A `pending` check is waiting for the report to resolve before its clock starts; every status other than `pending` and `active` is terminal.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "List a report's follow-up checks",
+ "title": "List a report's follow-up checks",
+ "required_scopes": ["signal_scout_report:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"scout-run-now": {
"description": "Dispatch one on-demand run of a scout by its config `id`, regardless of its schedule — useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously and inherits the scheduled path's guards: it returns 429 if the project is over its Signals credits quota or its daily scout-run budget, and 409 if a run for this scout is already in progress. A manual run counts against the same daily run budget the scheduled runs draw from, so avoid triggering repeated runs of the same scout in a short window — each one consumes the project's scout-run allowance for the day. A manual run does not change the scout's schedule, and a disabled scout can still be run this way (to test before enabling). Pass an optional `note` to steer this run alone (\"focus on the checkout regression\"): the agent reads it next to the scout's durable notes and weighs it the same way, and it is never read by another run — use it instead of `scout-notes-create`, which would also steer every later scheduled run. A run carrying a note needs `llm_skill:write` as well, since the agent reads the note verbatim while holding privileged tools. Returns the workflow id immediately — poll `scout-runs-list` for the resulting run and its findings.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ff31e5346555..f7c80a0fb315 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16495,6 +16495,14 @@ export namespace Schemas {
event_count_30d: number;
}
+ /**
+ * Request body for `scout-report-check-cancel`.
+ */
+ export interface CancelReportCheckRequest {
+ /** The check to stop. Its recorded results stay on the report. */
+ check_id: string;
+ }
+
export interface CandidateEvent {
/** Name of the candidate event */
event_name: string;
@@ -18700,6 +18708,16 @@ export namespace Schemas {
available: boolean;
}
+ export interface CheckFailedSignalExtra {
+ check_id: string;
+ report_id: string;
+ check_title: string;
+ explanation: string;
+ observed_value?: number | null;
+ baseline_value?: number | null;
+ threshold?: string | null;
+ }
+
/**
* Body of the `check_incremental` action: a query and an optional config to check it against.
*/
@@ -21620,6 +21638,95 @@ export namespace Schemas {
repo_external_id?: number | null;
}
+ /**
+ * * `metric_threshold` - Metric Threshold
+ * * `agent` - Agent
+ */
+ export type SignalReportCheckKindEnum = typeof SignalReportCheckKindEnum[keyof typeof SignalReportCheckKindEnum];
+
+
+ export const SignalReportCheckKindEnum = {
+ MetricThreshold: 'metric_threshold',
+ Agent: 'agent',
+ } as const;
+
+ /**
+ * Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.
+ */
+ export type MetricThresholdConfigQuery = { [key: string]: unknown } | null;
+
+ /**
+ * A deterministic check: measure one number, compare it, record the verdict.
+ *
+ * The number comes either from a metric the report already shows (``metric_id``) or from a query
+ * the author supplies. Both end up in the same runner, so a supplied query must satisfy the live
+ * metric contract — the node allowlist, the bounded window, and the single-output-series rule.
+ *
+ * A caller names one source. When it names a metric, the create path copies that metric's query
+ * into ``query`` before the row is stored, so the check keeps measuring what its author saw even if
+ * the report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.
+ *
+ * Unknown keys are refused rather than ignored, so a misspelled field name is reported instead of
+ * being dropped in silence and stored as it arrived.
+ */
+ export interface MetricThresholdConfig {
+ /** Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created. */
+ metric_id?: string | null;
+ /** Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. */
+ query?: MetricThresholdConfigQuery;
+ /** What the measured value must satisfy to pass. */
+ comparison: CheckComparison;
+ /** The value observed when the check was written, recorded on each result for context. */
+ baseline_value?: number | null;
+ }
+
+ export type SignalReportCheckConfig = MetricThresholdConfig | AgentCheckConfig;
+
+ /**
+ * Request body for `scout-report-check-create`: one forward-looking check on a report.
+ *
+ * The REST body plus the report it attaches to. Subclassed rather than restated so the schedule
+ * bounds a scout writes under are the ones the endpoint enforces, with no second copy to drift.
+ */
+ export interface CreateReportCheckRequest {
+ /**
+ * Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.
+ * @maxLength 200
+ */
+ title: string;
+ /**
+ * Why the check is worth running.
+ * @maxLength 2000
+ */
+ rationale?: string;
+ /** How the check is evaluated.
+ *
+ * * `metric_threshold` - Metric Threshold
+ * * `agent` - Agent */
+ kind: SignalReportCheckKindEnum;
+ /** What the check measures and what the result must satisfy; the shape depends on `kind`. */
+ config: SignalReportCheckConfig;
+ /** When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now. */
+ next_run_at?: string;
+ /**
+ * Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.
+ * @minimum 360
+ * @maximum 129600
+ * @nullable
+ */
+ run_interval_minutes?: number | null;
+ /**
+ * How many times to evaluate the check, at most 10. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ runs_remaining?: number;
+ /** Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first. */
+ expires_at?: string;
+ /** The report the check attaches to. */
+ report_id: string;
+ }
+
export type CreateRunInputBaselineHashes = {[key: string]: string};
export type CreateRunInputMetadata = { [key: string]: unknown };
@@ -56146,36 +56253,6 @@ export namespace Schemas {
Week: 'week',
} as const;
- /**
- * Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.
- */
- export type MetricThresholdConfigQuery = { [key: string]: unknown } | null;
-
- /**
- * A deterministic check: measure one number, compare it, record the verdict.
- *
- * The number comes either from a metric the report already shows (``metric_id``) or from a query
- * the author supplies. Both end up in the same runner, so a supplied query must satisfy the live
- * metric contract — the node allowlist, the bounded window, and the single-output-series rule.
- *
- * A caller names one source. When it names a metric, the create path copies that metric's query
- * into ``query`` before the row is stored, so the check keeps measuring what its author saw even if
- * the report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.
- *
- * Unknown keys are refused rather than ignored, so a misspelled field name is reported instead of
- * being dropped in silence and stored as it arrived.
- */
- export interface MetricThresholdConfig {
- /** Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created. */
- metric_id?: string | null;
- /** Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. */
- query?: MetricThresholdConfigQuery;
- /** What the measured value must satisfy to pass. */
- comparison: CheckComparison;
- /** The value observed when the check was written, recorded on each result for context. */
- baseline_value?: number | null;
- }
-
/**
* * `funnel` - funnel
* * `mean_count` - mean_count
@@ -61593,18 +61670,7 @@ export namespace Schemas {
}
/**
- * * `metric_threshold` - Metric Threshold
- * * `agent` - Agent
- */
- export type SignalReportCheckKindEnum = typeof SignalReportCheckKindEnum[keyof typeof SignalReportCheckKindEnum];
-
-
- export const SignalReportCheckKindEnum = {
- MetricThreshold: 'metric_threshold',
- Agent: 'agent',
- } as const;
-
- /**
+ * * `pending` - Pending
* * `active` - Active
* * `passed` - Passed
* * `failed` - Failed
@@ -61616,6 +61682,7 @@ export namespace Schemas {
export const SignalReportCheckStatusEnum = {
+ Pending: 'pending',
Active: 'active',
Passed: 'passed',
Failed: 'failed',
@@ -61624,8 +61691,6 @@ export namespace Schemas {
Cancelled: 'cancelled',
} as const;
- export type SignalReportCheckConfig = MetricThresholdConfig | AgentCheckConfig;
-
/**
* * `passed` - Passed
* * `failed` - Failed
@@ -61651,8 +61716,9 @@ export namespace Schemas {
* * `metric_threshold` - Metric Threshold
* * `agent` - Agent */
readonly kind: SignalReportCheckKindEnum;
- /** `active` while the check still runs; every other value is terminal.
+ /** `pending` while the check waits for the report to resolve, `active` while it still runs; every other value is terminal.
*
+ * * `pending` - Pending
* * `active` - Active
* * `passed` - Passed
* * `failed` - Failed
@@ -61662,8 +61728,13 @@ export namespace Schemas {
readonly status: SignalReportCheckStatusEnum;
/** What the check measures and what the result must satisfy; the shape depends on `kind`. `query` and `baseline_value` are null when you cannot read the data they describe. */
config: SignalReportCheckConfig;
- /** When the coordinator next evaluates the check. */
+ /** When the coordinator next evaluates the check. Provisional while the check is `pending`: the report resolving is what sets it. */
readonly next_run_at: string;
+ /**
+ * How long after the report resolves a `pending` check waits before its first run. Null on a check that named its own `next_run_at`.
+ * @nullable
+ */
+ readonly soak_minutes: number | null;
/**
* Gap between runs for a recurring check; null for a one-shot.
* @nullable
@@ -62099,6 +62170,7 @@ export namespace Schemas {
* * `error_tracking` - Error tracking
* * `pganalyze` - pganalyze
* * `signals_scout` - Signals scout
+ * * `signals_check` - Report check
* * `logs` - Logs
* * `health_checks` - Health checks
* * `endpoints` - Endpoints
@@ -62153,6 +62225,7 @@ export namespace Schemas {
ErrorTracking: 'error_tracking',
Pganalyze: 'pganalyze',
SignalsScout: 'signals_scout',
+ SignalsCheck: 'signals_check',
Logs: 'logs',
HealthChecks: 'health_checks',
Endpoints: 'endpoints',
@@ -80839,6 +80912,7 @@ export namespace Schemas {
* * `endpoints` - endpoints
* * `pganalyze` - pganalyze
* * `signals_scout` - signals_scout
+ * * `signals_check` - signals_check
* * `logs` - logs
* * `health_checks` - health_checks
* * `replay_vision` - replay_vision
@@ -80893,6 +80967,7 @@ export namespace Schemas {
Endpoints: 'endpoints',
Pganalyze: 'pganalyze',
SignalsScout: 'signals_scout',
+ SignalsCheck: 'signals_check',
Logs: 'logs',
HealthChecks: 'health_checks',
ReplayVision: 'replay_vision',
@@ -80956,6 +81031,7 @@ export namespace Schemas {
* * `ci_broken_default_branch` - ci_broken_default_branch
* * `ci_duration_regression` - ci_duration_regression
* * `search_opportunity` - search_opportunity
+ * * `check_failed` - check_failed
*/
export type SignalSourceType = typeof SignalSourceType[keyof typeof SignalSourceType];
@@ -80983,6 +81059,7 @@ export namespace Schemas {
CiBrokenDefaultBranch: 'ci_broken_default_branch',
CiDurationRegression: 'ci_duration_regression',
SearchOpportunity: 'search_opportunity',
+ CheckFailed: 'check_failed',
} as const;
export interface SessionProblemEventEntry {
@@ -81107,7 +81184,7 @@ export namespace Schemas {
createdDate: string | null;
}
- export type SignalExtra = SessionProblemSignalExtra | LlmEvalSignalExtra | LlmEvalReportSignalExtra | ZendeskTicketSignalExtra | GithubIssueSignalExtra | LinearIssueSignalExtra | JiraIssueSignalExtra | ConversationsTicketSignalExtra | ErrorTrackingSignalExtra | PgAnalyzeIssueSignalExtra | EndpointExecutionFailedSignalExtra | EndpointBreakdownLimitExceededSignalExtra | SignalsScoutSignalExtra | LogsAlertStateChangeSignalExtra | ReplayVisionScannerFindingSignalExtra | AnalyticsAnomalyInvestigationSignalExtra | HealthCheckSignalExtra | EngineeringAnalyticsCIFlakyCheckSignalExtra | EngineeringAnalyticsCIBrokenDefaultBranchSignalExtra | EngineeringAnalyticsCIDurationRegressionSignalExtra | FreshdeskTicketSignalExtra | FreshserviceTicketSignalExtra | FrontConversationSignalExtra | GorgiasTicketSignalExtra | KustomerConversationSignalExtra | DixaConversationSignalExtra | PlainThreadSignalExtra | GitlabIssueSignalExtra | GiteaIssueSignalExtra | ShortcutStorySignalExtra | SentryIssueSignalExtra | RollbarItemSignalExtra | BugsnagErrorSignalExtra | HoneybadgerFaultSignalExtra | RaygunErrorGroupSignalExtra | SnykScannerFindingSignalExtra | SonarqubeScannerFindingSignalExtra | SemgrepScannerFindingSignalExtra | Rapid7InsightvmScannerFindingSignalExtra | FeaturebaseFeedbackSignalExtra | FrillFeedbackSignalExtra | AhaFeedbackSignalExtra | UservoiceFeedbackSignalExtra | ProductboardFeedbackSignalExtra | CannyFeedbackSignalExtra | AsknicelyFeedbackSignalExtra | RetentlyFeedbackSignalExtra | AppfiguresReviewSignalExtra | AppfollowReviewSignalExtra | JudgemeReviewsReviewSignalExtra | IntercomTicketSignalExtra | HubspotTicketSignalExtra | GoogleSearchConsoleSearchOpportunitySignalExtra;
+ export type SignalExtra = SessionProblemSignalExtra | LlmEvalSignalExtra | LlmEvalReportSignalExtra | ZendeskTicketSignalExtra | GithubIssueSignalExtra | LinearIssueSignalExtra | JiraIssueSignalExtra | ConversationsTicketSignalExtra | ErrorTrackingSignalExtra | PgAnalyzeIssueSignalExtra | EndpointExecutionFailedSignalExtra | EndpointBreakdownLimitExceededSignalExtra | SignalsScoutSignalExtra | CheckFailedSignalExtra | LogsAlertStateChangeSignalExtra | ReplayVisionScannerFindingSignalExtra | AnalyticsAnomalyInvestigationSignalExtra | HealthCheckSignalExtra | EngineeringAnalyticsCIFlakyCheckSignalExtra | EngineeringAnalyticsCIBrokenDefaultBranchSignalExtra | EngineeringAnalyticsCIDurationRegressionSignalExtra | FreshdeskTicketSignalExtra | FreshserviceTicketSignalExtra | FrontConversationSignalExtra | GorgiasTicketSignalExtra | KustomerConversationSignalExtra | DixaConversationSignalExtra | PlainThreadSignalExtra | GitlabIssueSignalExtra | GiteaIssueSignalExtra | ShortcutStorySignalExtra | SentryIssueSignalExtra | RollbarItemSignalExtra | BugsnagErrorSignalExtra | HoneybadgerFaultSignalExtra | RaygunErrorGroupSignalExtra | SnykScannerFindingSignalExtra | SonarqubeScannerFindingSignalExtra | SemgrepScannerFindingSignalExtra | Rapid7InsightvmScannerFindingSignalExtra | FeaturebaseFeedbackSignalExtra | FrillFeedbackSignalExtra | AhaFeedbackSignalExtra | UservoiceFeedbackSignalExtra | ProductboardFeedbackSignalExtra | CannyFeedbackSignalExtra | AsknicelyFeedbackSignalExtra | RetentlyFeedbackSignalExtra | AppfiguresReviewSignalExtra | AppfollowReviewSignalExtra | JudgemeReviewsReviewSignalExtra | IntercomTicketSignalExtra | HubspotTicketSignalExtra | GoogleSearchConsoleSearchOpportunitySignalExtra;
export type SignalMatchMetadata = MatchedMetadata | NoMatchMetadata;
@@ -81129,6 +81206,7 @@ export namespace Schemas {
* * `endpoints` - endpoints
* * `pganalyze` - pganalyze
* * `signals_scout` - signals_scout
+ * * `signals_check` - signals_check
* * `logs` - logs
* * `health_checks` - health_checks
* * `replay_vision` - replay_vision
@@ -81191,7 +81269,8 @@ export namespace Schemas {
* * `ci_flaky_check` - ci_flaky_check
* * `ci_broken_default_branch` - ci_broken_default_branch
* * `ci_duration_regression` - ci_duration_regression
- * * `search_opportunity` - search_opportunity */
+ * * `search_opportunity` - search_opportunity
+ * * `check_failed` - check_failed */
source_type: SignalSourceType;
/** Emitter-scoped id of the underlying object (issue, ticket, ...). */
source_id: string;
@@ -83284,6 +83363,29 @@ export namespace Schemas {
suggestion_id?: string;
}
+ /**
+ * One check as a scout run reads it back.
+ */
+ export interface ScoutCheckSummary {
+ /** The check. */
+ check_id: string;
+ /** The report it is attached to. */
+ report_id: string;
+ /** The expectation the check states. */
+ title: string;
+ /** `metric_threshold` (the coordinator measures it) or `agent` (a run does). */
+ kind: string;
+ /** `pending` while the check waits for the report to resolve, `active` while it still runs; every other value is terminal. */
+ status: string;
+ /** When the check next runs. Provisional while it is `pending`. */
+ next_run_at: string;
+ /**
+ * Verdict of the most recent run; null before the first.
+ * @nullable
+ */
+ last_outcome: string | null;
+ }
+
/**
* What one scout spent in the window, and what it produced for that spend.
*/
@@ -84169,49 +84271,6 @@ export namespace Schemas {
not_found_count: number;
}
- /**
- * Request body for creating a check on a report.
- *
- * The schedule is the check's own: `next_run_at` says when to look, rather than the system
- * deriving a soak window from a merged pull request that many fixes never have.
- */
- export interface SignalReportCheckWrite {
- /**
- * Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.
- * @maxLength 200
- */
- title: string;
- /**
- * Why the check is worth running.
- * @maxLength 2000
- */
- rationale?: string;
- /** How the check is evaluated.
- *
- * * `metric_threshold` - Metric Threshold
- * * `agent` - Agent */
- kind: SignalReportCheckKindEnum;
- /** What the check measures and what the result must satisfy; the shape depends on `kind`. */
- config: SignalReportCheckConfig;
- /** When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now. */
- next_run_at?: string;
- /**
- * Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.
- * @minimum 360
- * @maximum 129600
- * @nullable
- */
- run_interval_minutes?: number | null;
- /**
- * How many times to evaluate the check, at most 10. Defaults to 1.
- * @minimum 1
- * @maximum 10
- */
- runs_remaining?: number;
- /** Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first. */
- expires_at?: string;
- }
-
export interface SignalReportClaim {
/** Active claim ID returned by an earlier call. Stale claims are rejected. */
claim_id?: string;
@@ -108117,6 +108176,13 @@ export namespace Schemas {
text?: string;
};
+ export type SignalsScoutReportChecksListParams = {
+ /**
+ * The report whose checks to list.
+ */
+ report_id: string;
+ };
+
export type SignalsScoutRunsCostsParams = {
/**
* Window in days over runs' `created_at` (default 7). Only 7 is accepted today — it matches the window the roster's fleet headline spans, so every number on the page describes one span.
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 5ac2c417e103..36d4481eec1b 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 47 enabled ops
+ * PostHog API - MCP 48 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -475,164 +475,16 @@ export const SignalsReportChecksListQueryParams = () => zod.object({
})
/**
- * Schedule a re-measurement of the report's claim. A `metric_threshold` check runs one bounded Trends query and compares the result, so it needs no agent run. An `agent` check runs a scout instead, for a claim no single number settles; it runs on the scout its config names, or on the fleet's follow-up scout when it names none.
- * @summary Create a check on a report
- */
-export const SignalsReportChecksCreateParams = () => zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
- report_id: zod
- .string()
- .describe(
- "UUID of the report whose artefacts you're addressing. This must be a report id (the report's own UUID), not a signal id such as `sig_praise` — a non-report id returns 404."
- ),
-})
-
-export const signalsReportChecksCreateBodyTitleMax = 200
-
-export const signalsReportChecksCreateBodyRationaleMax = 2000
-
-export const signalsReportChecksCreateBodyConfigOneTwoInstructionsMax = 2000
-
-export const signalsReportChecksCreateBodyConfigOneTwoSkillNameOneMax = 200
-
-export const signalsReportChecksCreateBodyConfigOneTwoProbeHintsMax = 5
-
-export const signalsReportChecksCreateBodyRunIntervalMinutesMin = 360
-export const signalsReportChecksCreateBodyRunIntervalMinutesMax = 129600
-
-export const signalsReportChecksCreateBodyRunsRemainingMax = 10
-
-export const SignalsReportChecksCreateBody = () => zod
- .object({
- title: zod
- .string()
- .max(signalsReportChecksCreateBodyTitleMax)
- .describe('Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.'),
- rationale: zod
- .string()
- .max(signalsReportChecksCreateBodyRationaleMax)
- .optional()
- .describe('Why the check is worth running.'),
- kind: zod
- .enum(['metric_threshold', 'agent'])
- .describe('\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent')
- .describe('How the check is evaluated.\n\n\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent'),
- config: zod
- .union([
- zod
- .object({
- metric_id: zod
- .union([zod.string(), zod.null()])
- .optional()
- .describe(
- "Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created."
- ),
- query: zod
- .union([zod.record(zod.string(), zod.unknown()), zod.null()])
- .optional()
- .describe(
- 'Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.'
- ),
- comparison: zod
- .object({
- operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),
- value: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe('The bound for `lte` and `gte`; unused by `between`.'),
- bounds: zod
- .union([
- zod.object({
- lower: zod.number(),
- upper: zod.number(),
- }),
- zod.null(),
- ])
- .optional()
- .describe('The inclusive range for `between`; unused by `lte` and `gte`.'),
- })
- .describe('What the measured value must satisfy to pass.'),
- baseline_value: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe(
- 'The value observed when the check was written, recorded on each result for context.'
- ),
- })
- .describe(
- "A deterministic check: measure one number, compare it, record the verdict.\n\nThe number comes either from a metric the report already shows (``metric_id``) or from a query\nthe author supplies. Both end up in the same runner, so a supplied query must satisfy the live\nmetric contract — the node allowlist, the bounded window, and the single-output-series rule.\n\nA caller names one source. When it names a metric, the create path copies that metric's query\ninto ``query`` before the row is stored, so the check keeps measuring what its author saw even if\nthe report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.\n\nUnknown keys are refused rather than ignored, so a misspelled field name is reported instead of\nbeing dropped in silence and stored as it arrived."
- ),
- zod
- .object({
- instructions: zod
- .string()
- .max(signalsReportChecksCreateBodyConfigOneTwoInstructionsMax)
- .describe("What the run must establish, in the author's own words."),
- skill_name: zod
- .union([
- zod.string().max(signalsReportChecksCreateBodyConfigOneTwoSkillNameOneMax),
- zod.null(),
- ])
- .optional()
- .describe(
- "Scout skill that runs the check. Omit it to run on the fleet's follow-up scout, which is the right lane for a report no scout authored."
- ),
- probe_hints: zod
- .array(zod.string())
- .max(signalsReportChecksCreateBodyConfigOneTwoProbeHintsMax)
- .optional()
- .describe(
- 'Concrete places to look, such as an issue id, a service name, or a query to repeat.'
- ),
- })
- .describe(
- 'A check a scout run answers: re-probe the report\'s claim and record one verdict.\n\nThe kind for a claim no single number settles. A resolved error-tracking report is the usual\ncase: \"did the exception stop?\" needs the issue looked up, its recent events read, and the\nstack compared against what the fix changed, which is a run rather than a comparison.\n\nEverything here is prompt material a scout reads, so it is untrusted by construction: it renders\nin the run block the agent is told to weigh, never in the instructions it is told to follow. The\nverdict still comes back through `scout-check-record-result`, so instructions cannot widen what\na check run may write.\n\n``skill_name`` names the lane. Most reports are pipeline-authored and have no scout behind them,\nso it is optional: a check that names none runs on the fleet\'s follow-up scout\n(see ``report_check_agent.FALLBACK_CHECK_SKILL_NAME``).'
- ),
- ])
- .describe('What the check measures and what the result must satisfy; the shape depends on `kind`.'),
- next_run_at: zod.iso
- .datetime({ offset: true })
- .optional()
- .describe(
- 'When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now.'
- ),
- run_interval_minutes: zod
- .number()
- .min(signalsReportChecksCreateBodyRunIntervalMinutesMin)
- .max(signalsReportChecksCreateBodyRunIntervalMinutesMax)
- .nullish()
- .describe(
- 'Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.'
- ),
- runs_remaining: zod
- .number()
- .min(1)
- .max(signalsReportChecksCreateBodyRunsRemainingMax)
- .optional()
- .describe('How many times to evaluate the check, at most 10. Defaults to 1.'),
- expires_at: zod.iso
- .datetime({ offset: true })
- .optional()
- .describe(
- 'Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first.'
- ),
- })
- .describe(
- "Request body for creating a check on a report.\n\nThe schedule is the check's own: `next_run_at` says when to look, rather than the system\nderiving a soak window from a merged pull request that many fixes never have."
- )
-
-/**
- * Checks attached to a signal report: read, create, and cancel.
+ * Checks attached to a signal report: read and cancel.
*
- * There is no update: a check is a claim about the future, and editing its threshold after a
- * result would make the recorded verdict unreadable. Cancel it and write a new one.
+ * There is no create here. A check is authored by a scout run or by the research pipeline, both
+ * through `report_check_authoring.create_check`. An `agent` check puts its author's prose in front
+ * of a privileged scout run, and `task:write` does not authorize that, so no caller-facing
+ * endpoint accepts one. Anyone who can read the report can read its checks, and a person can
+ * still stop one.
*
- * Writes are attributed the same way artefact writes are — to the task named by the
- * `X-PostHog-Task-Id` header when present, else to the requesting user.
+ * There is no update: a check is a claim about the future, and editing its threshold after a
+ * result would make the recorded verdict unreadable. Cancel it and let its author write a new one.
* @summary Get a single check
*/
export const SignalsReportChecksRetrieveParams = () => zod.object({
@@ -649,24 +501,6 @@ export const SignalsReportChecksRetrieveParams = () => zod.object({
),
})
-/**
- * Stop an active check. Its recorded results stay on the report.
- * @summary Cancel a check
- */
-export const SignalsReportChecksDestroyParams = () => zod.object({
- id: zod.string().describe('A UUID string identifying this Signal report check.'),
- 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\/."
- ),
- report_id: zod
- .string()
- .describe(
- "UUID of the report whose artefacts you're addressing. This must be a report id (the report's own UUID), not a signal id such as `sig_praise` — a non-report id returns 404."
- ),
-})
-
/**
* Transition many reports to a new state in one call.
*
@@ -2617,6 +2451,190 @@ export const SignalsScoutRecordOutputBody = () => zod
})
.describe('Request body for `scout-record-output`: a batch of schema-validated records.')
+/**
+ * Stop a check that is no longer worth running — the claim it re-measures has changed, or a better check replaces it. Results it already recorded stay on the report. A check that has already finished cannot be cancelled.
+ * @summary Cancel a follow-up check
+ */
+export const SignalsScoutReportCheckCancelParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+ run_id: zod.string().describe('UUID of the `SignalScoutRun` bridge row.'),
+})
+
+export const SignalsScoutReportCheckCancelBody = () => zod
+ .object({
+ check_id: zod.string().describe('The check to stop. Its recorded results stay on the report.'),
+ })
+ .describe('Request body for `scout-report-check-cancel`.')
+
+/**
+ * Schedule a re-measurement of a report's claim, so whether the fix held becomes a stored fact instead of something a future run has to remember to look for. A `metric_threshold` check runs one bounded Trends query and compares the result. An `agent` check runs a scout instead, for a claim no single number settles.
+ * @summary Write a follow-up check on a report
+ */
+export const SignalsScoutReportCheckCreateParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+ run_id: zod.string().describe('UUID of the `SignalScoutRun` bridge row.'),
+})
+
+export const signalsScoutReportCheckCreateBodyTitleMax = 200
+
+export const signalsScoutReportCheckCreateBodyRationaleMax = 2000
+
+export const signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax = 2000
+
+export const signalsScoutReportCheckCreateBodyConfigOneTwoSkillNameOneMax = 200
+
+export const signalsScoutReportCheckCreateBodyConfigOneTwoProbeHintsMax = 5
+
+export const signalsScoutReportCheckCreateBodyRunIntervalMinutesMin = 360
+export const signalsScoutReportCheckCreateBodyRunIntervalMinutesMax = 129600
+
+export const signalsScoutReportCheckCreateBodyRunsRemainingMax = 10
+
+export const SignalsScoutReportCheckCreateBody = () => zod
+ .object({
+ title: zod
+ .string()
+ .max(signalsScoutReportCheckCreateBodyTitleMax)
+ .describe('Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.'),
+ rationale: zod
+ .string()
+ .max(signalsScoutReportCheckCreateBodyRationaleMax)
+ .optional()
+ .describe('Why the check is worth running.'),
+ kind: zod
+ .enum(['metric_threshold', 'agent'])
+ .describe('\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent')
+ .describe('How the check is evaluated.\n\n\* `metric_threshold` - Metric Threshold\n\* `agent` - Agent'),
+ config: zod
+ .union([
+ zod
+ .object({
+ metric_id: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ "Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created."
+ ),
+ query: zod
+ .union([zod.record(zod.string(), zod.unknown()), zod.null()])
+ .optional()
+ .describe(
+ 'Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created.'
+ ),
+ comparison: zod
+ .object({
+ operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),
+ value: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('The bound for `lte` and `gte`; unused by `between`.'),
+ bounds: zod
+ .union([
+ zod.object({
+ lower: zod.number(),
+ upper: zod.number(),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('The inclusive range for `between`; unused by `lte` and `gte`.'),
+ })
+ .describe('What the measured value must satisfy to pass.'),
+ baseline_value: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe(
+ 'The value observed when the check was written, recorded on each result for context.'
+ ),
+ })
+ .describe(
+ "A deterministic check: measure one number, compare it, record the verdict.\n\nThe number comes either from a metric the report already shows (``metric_id``) or from a query\nthe author supplies. Both end up in the same runner, so a supplied query must satisfy the live\nmetric contract — the node allowlist, the bounded window, and the single-output-series rule.\n\nA caller names one source. When it names a metric, the create path copies that metric's query\ninto ``query`` before the row is stored, so the check keeps measuring what its author saw even if\nthe report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.\n\nUnknown keys are refused rather than ignored, so a misspelled field name is reported instead of\nbeing dropped in silence and stored as it arrived."
+ ),
+ zod
+ .object({
+ instructions: zod
+ .string()
+ .max(signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax)
+ .describe("What the run must establish, in the author's own words."),
+ skill_name: zod
+ .union([
+ zod.string().max(signalsScoutReportCheckCreateBodyConfigOneTwoSkillNameOneMax),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Scout skill that runs the check. Omit it to run on the fleet's follow-up scout, which is the right lane for a report no scout authored."
+ ),
+ probe_hints: zod
+ .array(zod.string())
+ .max(signalsScoutReportCheckCreateBodyConfigOneTwoProbeHintsMax)
+ .optional()
+ .describe(
+ 'Concrete places to look, such as an issue id, a service name, or a query to repeat.'
+ ),
+ })
+ .describe(
+ 'A check a scout run answers: re-probe the report\'s claim and record one verdict.\n\nThe kind for a claim no single number settles. A resolved error-tracking report is the usual\ncase: \"did the exception stop?\" needs the issue looked up, its recent events read, and the\nstack compared against what the fix changed, which is a run rather than a comparison.\n\nEverything here is prompt material a scout reads, so it is untrusted by construction: it renders\nin the run block the agent is told to weigh, never in the instructions it is told to follow. The\nverdict still comes back through `scout-check-record-result`, so instructions cannot widen what\na check run may write.\n\n``skill_name`` names the lane. Most reports are pipeline-authored and have no scout behind them,\nso it is optional: a check that names none runs on the fleet\'s follow-up scout\n(see ``report_check_agent.FALLBACK_CHECK_SKILL_NAME``).'
+ ),
+ ])
+ .describe('What the check measures and what the result must satisfy; the shape depends on `kind`.'),
+ next_run_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now.'
+ ),
+ run_interval_minutes: zod
+ .number()
+ .min(signalsScoutReportCheckCreateBodyRunIntervalMinutesMin)
+ .max(signalsScoutReportCheckCreateBodyRunIntervalMinutesMax)
+ .nullish()
+ .describe(
+ 'Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check.'
+ ),
+ runs_remaining: zod
+ .number()
+ .min(1)
+ .max(signalsScoutReportCheckCreateBodyRunsRemainingMax)
+ .optional()
+ .describe('How many times to evaluate the check, at most 10. Defaults to 1.'),
+ expires_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first.'
+ ),
+ report_id: zod.string().describe('The report the check attaches to.'),
+ })
+ .describe(
+ 'Request body for `scout-report-check-create`: one forward-looking check on a report.\n\nThe REST body plus the report it attaches to. Subclassed rather than restated so the schedule\nbounds a scout writes under are the ones the endpoint enforces, with no second copy to drift.'
+ )
+
+/**
+ * Every check on one report, newest first. Read this before writing one: a report already carrying a check for the same claim needs no second one, and a report holds at most five open checks at a time.
+ * @summary List a report's follow-up checks
+ */
+export const SignalsScoutReportChecksListParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+ run_id: zod.string().describe('UUID of the `SignalScoutRun` bridge row.'),
+})
+
+export const SignalsScoutReportChecksListQueryParams = () => zod.object({
+ report_id: zod.string().describe('The report whose checks to list.'),
+})
+
/**
* Return the team's recently emitted scout findings across *every* run, newest first — the cross-run counterpart to the per-run `emissions` action. Each row carries its `run_id`, so you can regroup by run without first listing runs and fanning out one `emissions` call each. Pass `skill_name` to scope to a single scout, and `date_from` / `date_to` (a half-open window on `emitted_at`) to bound or paginate — set `date_to` to the oldest emission's `emitted_at` to walk back past the limit. Pure Postgres, no ClickHouse round-trip. Capped at 200 rows (default 50).
* @summary List recent emitted findings across all runs
@@ -2820,6 +2838,7 @@ export const SignalsSourceConfigsCreateBody = () => zod.object({
'error_tracking',
'pganalyze',
'signals_scout',
+ 'signals_check',
'logs',
'health_checks',
'endpoints',
@@ -2861,7 +2880,7 @@ export const SignalsSourceConfigsCreateBody = () => zod.object({
'google_search_console',
])
.describe(
- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `signals_check` - Report check\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
),
source_type: zod
.enum([
@@ -2929,6 +2948,7 @@ export const SignalsSourceConfigsUpdateBody = () => zod.object({
'error_tracking',
'pganalyze',
'signals_scout',
+ 'signals_check',
'logs',
'health_checks',
'endpoints',
@@ -2970,7 +2990,7 @@ export const SignalsSourceConfigsUpdateBody = () => zod.object({
'google_search_console',
])
.describe(
- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `signals_check` - Report check\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
),
source_type: zod
.enum([
@@ -3029,6 +3049,7 @@ export const SignalsSourceConfigsPartialUpdateBody = () => zod.object({
'error_tracking',
'pganalyze',
'signals_scout',
+ 'signals_check',
'logs',
'health_checks',
'endpoints',
@@ -3071,7 +3092,7 @@ export const SignalsSourceConfigsPartialUpdateBody = () => zod.object({
])
.optional()
.describe(
- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `jira` - Jira\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `signals_check` - Report check\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints\n\* `replay_vision` - Replay Vision\n\* `analytics` - Product analytics\n\* `freshdesk` - Freshdesk\n\* `freshservice` - Freshservice\n\* `front` - Front\n\* `gorgias` - Gorgias\n\* `kustomer` - Kustomer\n\* `dixa` - Dixa\n\* `plain` - Plain\n\* `gitlab` - GitLab\n\* `gitea` - Gitea\n\* `shortcut` - Shortcut\n\* `sentry` - Sentry\n\* `rollbar` - Rollbar\n\* `bugsnag` - Bugsnag\n\* `honeybadger` - Honeybadger\n\* `raygun` - Raygun\n\* `snyk` - Snyk\n\* `sonarqube` - SonarQube\n\* `semgrep` - Semgrep\n\* `rapid7_insightvm` - Rapid7 InsightVM\n\* `featurebase` - Featurebase\n\* `frill` - Frill\n\* `aha` - Aha\n\* `uservoice` - UserVoice\n\* `productboard` - Productboard\n\* `canny` - Canny\n\* `asknicely` - AskNicely\n\* `retently` - Retently\n\* `appfigures` - Appfigures\n\* `appfollow` - AppFollow\n\* `judgeme_reviews` - Judge.me\n\* `intercom` - Intercom\n\* `hubspot` - HubSpot\n\* `engineering_analytics` - Engineering analytics\n\* `google_search_console` - Google Search Console'
),
source_type: zod
.enum([
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 72f6aae7c65f..3c0a4e7f88ea 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -147,75 +147,6 @@ const inboxReportArtefactsUpdate = (): ToolBase<
},
})
-const InboxReportChecksCreateSchema = () => {
- const SignalsReportChecksCreateBody = orvalSchemas.SignalsReportChecksCreateBody()
- const SignalsReportChecksCreateParams = orvalSchemas.SignalsReportChecksCreateParams()
- return SignalsReportChecksCreateParams.omit({ project_id: true }).extend(SignalsReportChecksCreateBody.shape)
-}
-
-const inboxReportChecksCreate = (): ToolBase<
- ReturnType<typeof InboxReportChecksCreateSchema>,
- WithPostHogUrl<Schemas.SignalReportCheck>
-> => ({
- name: 'inbox-report-checks-create',
- schema: InboxReportChecksCreateSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof InboxReportChecksCreateSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.title !== undefined) {
- body['title'] = params.title
- }
- if (params.rationale !== undefined) {
- body['rationale'] = params.rationale
- }
- if (params.kind !== undefined) {
- body['kind'] = params.kind
- }
- if (params.config !== undefined) {
- body['config'] = params.config
- }
- if (params.next_run_at !== undefined) {
- body['next_run_at'] = params.next_run_at
- }
- if (params.run_interval_minutes !== undefined) {
- body['run_interval_minutes'] = params.run_interval_minutes
- }
- if (params.runs_remaining !== undefined) {
- body['runs_remaining'] = params.runs_remaining
- }
- if (params.expires_at !== undefined) {
- body['expires_at'] = params.expires_at
- }
- const result = await context.api.request<Schemas.SignalReportCheck>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/checks/`,
- body,
- })
- return await withPostHogUrl(context, result, `/inbox/${params.report_id}`)
- },
-})
-
-const InboxReportChecksDeleteSchema = () => {
- const SignalsReportChecksDestroyParams = orvalSchemas.SignalsReportChecksDestroyParams()
- return SignalsReportChecksDestroyParams.omit({ project_id: true })
-}
-
-const inboxReportChecksDelete = (): ToolBase<
- ReturnType<typeof InboxReportChecksDeleteSchema>,
- Schemas.SignalReportCheck
-> => ({
- name: 'inbox-report-checks-delete',
- schema: InboxReportChecksDeleteSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof InboxReportChecksDeleteSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.SignalReportCheck>({
- method: 'DELETE',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/reports/${encodeURIComponent(String(params.report_id))}/checks/${encodeURIComponent(String(params.id))}/`,
- })
- return result
- },
-})
-
const InboxReportChecksListSchema = () => {
const SignalsReportChecksListParams = orvalSchemas.SignalsReportChecksListParams()
const SignalsReportChecksListQueryParams = orvalSchemas.SignalsReportChecksListQueryParams()
@@ -1351,6 +1282,115 @@ const scoutRecordOutput = (): ToolBase<
},
})
+const ScoutReportCheckCancelSchema = () => {
+ const SignalsScoutReportCheckCancelBody = orvalSchemas.SignalsScoutReportCheckCancelBody()
+ const SignalsScoutReportCheckCancelParams = orvalSchemas.SignalsScoutReportCheckCancelParams()
+ return SignalsScoutReportCheckCancelParams.omit({ project_id: true }).extend(
+ SignalsScoutReportCheckCancelBody.shape
+ )
+}
+
+const scoutReportCheckCancel = (): ToolBase<
+ ReturnType<typeof ScoutReportCheckCancelSchema>,
+ Schemas.ScoutCheckSummary
+> => ({
+ name: 'scout-report-check-cancel',
+ schema: ScoutReportCheckCancelSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ScoutReportCheckCancelSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.check_id !== undefined) {
+ body['check_id'] = params.check_id
+ }
+ const result = await context.api.request<Schemas.ScoutCheckSummary>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/report-check-cancel/`,
+ body,
+ })
+ return result
+ },
+})
+
+const ScoutReportCheckCreateSchema = () => {
+ const SignalsScoutReportCheckCreateBody = orvalSchemas.SignalsScoutReportCheckCreateBody()
+ const SignalsScoutReportCheckCreateParams = orvalSchemas.SignalsScoutReportCheckCreateParams()
+ return SignalsScoutReportCheckCreateParams.omit({ project_id: true }).extend(
+ SignalsScoutReportCheckCreateBody.shape
+ )
+}
+
+const scoutReportCheckCreate = (): ToolBase<
+ ReturnType<typeof ScoutReportCheckCreateSchema>,
+ Schemas.ScoutCheckSummary
+> => ({
+ name: 'scout-report-check-create',
+ schema: ScoutReportCheckCreateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ScoutReportCheckCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.title !== undefined) {
+ body['title'] = params.title
+ }
+ if (params.rationale !== undefined) {
+ body['rationale'] = params.rationale
+ }
+ if (params.kind !== undefined) {
+ body['kind'] = params.kind
+ }
+ if (params.config !== undefined) {
+ body['config'] = params.config
+ }
+ if (params.next_run_at !== undefined) {
+ body['next_run_at'] = params.next_run_at
+ }
+ if (params.run_interval_minutes !== undefined) {
+ body['run_interval_minutes'] = params.run_interval_minutes
+ }
+ if (params.runs_remaining !== undefined) {
+ body['runs_remaining'] = params.runs_remaining
+ }
+ if (params.expires_at !== undefined) {
+ body['expires_at'] = params.expires_at
+ }
+ if (params.report_id !== undefined) {
+ body['report_id'] = params.report_id
+ }
+ const result = await context.api.request<Schemas.ScoutCheckSummary>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/report-check-create/`,
+ body,
+ })
+ return result
+ },
+})
+
+const ScoutReportCheckListSchema = () => {
+ const SignalsScoutReportChecksListParams = orvalSchemas.SignalsScoutReportChecksListParams()
+ const SignalsScoutReportChecksListQueryParams = orvalSchemas.SignalsScoutReportChecksListQueryParams()
+ return SignalsScoutReportChecksListParams.omit({ project_id: true }).extend(
+ SignalsScoutReportChecksListQueryParams.shape
+ )
+}
+
+const scoutReportCheckList = (): ToolBase<
+ ReturnType<typeof ScoutReportCheckListSchema>,
+ Schemas.ScoutCheckSummary[]
+> => ({
+ name: 'scout-report-check-list',
+ schema: ScoutReportCheckListSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ScoutReportCheckListSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ScoutCheckSummary[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/report-checks/`,
+ query: {
+ report_id: params.report_id,
+ },
+ })
+ return result
+ },
+})
+
const ScoutRunNowSchema = () => {
const SignalsScoutConfigRunBody = orvalSchemas.SignalsScoutConfigRunBody()
const SignalsScoutConfigRunParams = orvalSchemas.SignalsScoutConfigRunParams()
@@ -2253,8 +2293,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'inbox-report-artefacts-list': inboxReportArtefactsList,
'inbox-report-artefacts-retrieve': inboxReportArtefactsRetrieve,
'inbox-report-artefacts-update': inboxReportArtefactsUpdate,
- 'inbox-report-checks-create': inboxReportChecksCreate,
- 'inbox-report-checks-delete': inboxReportChecksDelete,
'inbox-report-checks-list': inboxReportChecksList,
'inbox-report-checks-retrieve': inboxReportChecksRetrieve,
'inbox-reports-bulk-set-state': inboxReportsBulkSetState,
@@ -2286,6 +2324,9 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'scout-notes-list': scoutNotesList,
'scout-project-profile-get': scoutProjectProfileGet,
'scout-record-output': scoutRecordOutput,
+ 'scout-report-check-cancel': scoutReportCheckCancel,
+ 'scout-report-check-create': scoutReportCheckCreate,
+ 'scout-report-check-list': scoutReportCheckList,
'scout-run-now': scoutRunNow,
'scout-runs-emission-reports': scoutRunsEmissionReports,
'scout-runs-emissions-list': scoutRunsEmissionsList,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-create.json
deleted file mode 100644
index 2b4e18dfa6d8..000000000000
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-create.json
+++ /dev/null
@@ -1,181 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "properties": {
- "config": {
- "anyOf": [
- {
- "description": "A deterministic check: measure one number, compare it, record the verdict.\n\nThe number comes either from a metric the report already shows (``metric_id``) or from a query\nthe author supplies. Both end up in the same runner, so a supplied query must satisfy the live\nmetric contract — the node allowlist, the bounded window, and the single-output-series rule.\n\nA caller names one source. When it names a metric, the create path copies that metric's query\ninto ``query`` before the row is stored, so the check keeps measuring what its author saw even if\nthe report's metric is later rewritten under the same id; ``metric_id`` stays as provenance.\n\nUnknown keys are refused rather than ignored, so a misspelled field name is reported instead of\nbeing dropped in silence and stored as it arrived.",
- "properties": {
- "baseline_value": {
- "anyOf": [
- {
- "type": "number"
- },
- {
- "type": "null"
- }
- ],
- "description": "The value observed when the check was written, recorded on each result for context."
- },
- "comparison": {
- "description": "What the measured value must satisfy to pass.",
- "properties": {
- "bounds": {
- "anyOf": [
- {
- "properties": {
- "lower": {
- "type": "number"
- },
- "upper": {
- "type": "number"
- }
- },
- "required": ["lower", "upper"],
- "type": "object"
- },
- {
- "type": "null"
- }
- ],
- "description": "The inclusive range for `between`; unused by `lte` and `gte`."
- },
- "operator": {
- "description": "`lte`, `gte`, or `between`.",
- "enum": ["lte", "gte", "between"],
- "type": "string"
- },
- "value": {
- "anyOf": [
- {
- "type": "number"
- },
- {
- "type": "null"
- }
- ],
- "description": "The bound for `lte` and `gte`; unused by `between`."
- }
- },
- "required": ["operator"],
- "type": "object"
- },
- "metric_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "Identifier of a metric on the report whose query this check measures. The metric's query is copied into `query` when the check is created."
- },
- "query": {
- "anyOf": [
- {
- "additionalProperties": {},
- "propertyNames": {
- "type": "string"
- },
- "type": "object"
- },
- {
- "type": "null"
- }
- ],
- "description": "Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created."
- }
- },
- "required": ["comparison"],
- "type": "object"
- },
- {
- "description": "A check a scout run answers: re-probe the report's claim and record one verdict.\n\nThe kind for a claim no single number settles. A resolved error-tracking report is the usual\ncase: \"did the exception stop?\" needs the issue looked up, its recent events read, and the\nstack compared against what the fix changed, which is a run rather than a comparison.\n\nEverything here is prompt material a scout reads, so it is untrusted by construction: it renders\nin the run block the agent is told to weigh, never in the instructions it is told to follow. The\nverdict still comes back through `scout-check-record-result`, so instructions cannot widen what\na check run may write.\n\n``skill_name`` names the lane. Most reports are pipeline-authored and have no scout behind them,\nso it is optional: a check that names none runs on the fleet's follow-up scout\n(see ``report_check_agent.FALLBACK_CHECK_SKILL_NAME``).",
- "properties": {
- "instructions": {
- "description": "What the run must establish, in the author's own words.",
- "maxLength": 2000,
- "type": "string"
- },
- "probe_hints": {
- "description": "Concrete places to look, such as an issue id, a service name, or a query to repeat.",
- "items": {
- "type": "string"
- },
- "maxItems": 5,
- "type": "array"
- },
- "skill_name": {
- "anyOf": [
- {
- "maxLength": 200,
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "Scout skill that runs the check. Omit it to run on the fleet's follow-up scout, which is the right lane for a report no scout authored."
- }
- },
- "required": ["instructions"],
- "type": "object"
- }
- ],
- "description": "What the check measures and what the result must satisfy; the shape depends on `kind`."
- },
- "expires_at": {
- "description": "Horizon after which the check retires unrun. Defaults to 30 days after the last scheduled run, or the 90-day horizon if that comes first.",
- "format": "date-time",
- "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
- "type": "string"
- },
- "kind": {
- "description": "How the check is evaluated.\n\n* `metric_threshold` - Metric Threshold\n* `agent` - Agent",
- "enum": ["metric_threshold", "agent"],
- "type": "string"
- },
- "next_run_at": {
- "description": "When to first evaluate the check. Must be in the future and within 90 days. Defaults to 7 days from now.",
- "format": "date-time",
- "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
- "type": "string"
- },
- "rationale": {
- "description": "Why the check is worth running.",
- "maxLength": 2000,
- "type": "string"
- },
- "report_id": {
- "description": "UUID of the report whose artefacts you're addressing. This must be a report id (the report's own UUID), not a signal id such as `sig_praise` — a non-report id returns 404.",
- "type": "string"
- },
- "run_interval_minutes": {
- "anyOf": [
- {
- "maximum": 129600,
- "minimum": 360,
- "type": "number"
- },
- {
- "type": "null"
- }
- ],
- "description": "Gap between runs for a recurring check, between 360 and 129600 minutes. Omit for a one-shot check."
- },
- "runs_remaining": {
- "description": "How many times to evaluate the check, at most 10. Defaults to 1.",
- "maximum": 10,
- "minimum": 1,
- "type": "number"
- },
- "title": {
- "description": "Short label for the expectation, e.g. `Checkout 500s stay below 10 a day`.",
- "maxLength": 200,
- "type": "string"
- }
- },
- "required": ["report_id", "title", "kind", "config"],
- "type": "object"
-}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-delete.json
deleted file mode 100644
index 26d7110e857e..000000000000
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-delete.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "properties": {
- "id": {
- "description": "A UUID string identifying this Signal report check.",
- "type": "string"
- },
- "report_id": {
- "description": "UUID of the report whose artefacts you're addressing. This must be a report id (the report's own UUID), not a signal id such as `sig_praise` — a non-report id returns 404.",
- "type": "string"
- }
- },
- "required": ["id", "report_id"],
- "type": "object"
-}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json
index 963923406ff9..225eb9501a19 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json
@@ -13,7 +13,7 @@
"type": "boolean"
},
"source_product": {
- "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `jira` - Jira\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints\n* `replay_vision` - Replay Vision\n* `analytics` - Product analytics\n* `freshdesk` - Freshdesk\n* `freshservice` - Freshservice\n* `front` - Front\n* `gorgias` - Gorgias\n* `kustomer` - Kustomer\n* `dixa` - Dixa\n* `plain` - Plain\n* `gitlab` - GitLab\n* `gitea` - Gitea\n* `shortcut` - Shortcut\n* `sentry` - Sentry\n* `rollbar` - Rollbar\n* `bugsnag` - Bugsnag\n* `honeybadger` - Honeybadger\n* `raygun` - Raygun\n* `snyk` - Snyk\n* `sonarqube` - SonarQube\n* `semgrep` - Semgrep\n* `rapid7_insightvm` - Rapid7 InsightVM\n* `featurebase` - Featurebase\n* `frill` - Frill\n* `aha` - Aha\n* `uservoice` - UserVoice\n* `productboard` - Productboard\n* `canny` - Canny\n* `asknicely` - AskNicely\n* `retently` - Retently\n* `appfigures` - Appfigures\n* `appfollow` - AppFollow\n* `judgeme_reviews` - Judge.me\n* `intercom` - Intercom\n* `hubspot` - HubSpot\n* `engineering_analytics` - Engineering analytics\n* `google_search_console` - Google Search Console",
+ "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `jira` - Jira\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `signals_check` - Report check\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints\n* `replay_vision` - Replay Vision\n* `analytics` - Product analytics\n* `freshdesk` - Freshdesk\n* `freshservice` - Freshservice\n* `front` - Front\n* `gorgias` - Gorgias\n* `kustomer` - Kustomer\n* `dixa` - Dixa\n* `plain` - Plain\n* `gitlab` - GitLab\n* `gitea` - Gitea\n* `shortcut` - Shortcut\n* `sentry` - Sentry\n* `rollbar` - Rollbar\n* `bugsnag` - Bugsnag\n* `honeybadger` - Honeybadger\n* `raygun` - Raygun\n* `snyk` - Snyk\n* `sonarqube` - SonarQube\n* `semgrep` - Semgrep\n* `rapid7_insightvm` - Rapid7 InsightVM\n* `featurebase` - Featurebase\n* `frill` - Frill\n* `aha` - Aha\n* `uservoice` - UserVoice\n* `productboard` - Productboard\n* `canny` - Canny\n* `asknicely` - AskNicely\n* `retently` - Retently\n* `appfigures` - Appfigures\n* `appfollow` - AppFollow\n* `judgeme_reviews` - Judge.me\n* `intercom` - Intercom\n* `hubspot` - HubSpot\n* `engineering_analytics` - Engineering analytics\n* `google_search_console` - Google Search Console",
"enum": [
"session_replay",
"llm_analytics",
@@ -25,6 +25,7 @@
"error_tracking",
"pganalyze",
"signals_scout",
+ "signals_check",
"logs",
"health_checks",
"endpoints",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json
index 66061a941ab4..cd7671654fb6 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json
@@ -17,7 +17,7 @@
"type": "string"
},
"source_product": {
- "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `jira` - Jira\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints\n* `replay_vision` - Replay Vision\n* `analytics` - Product analytics\n* `freshdesk` - Freshdesk\n* `freshservice` - Freshservice\n* `front` - Front\n* `gorgias` - Gorgias\n* `kustomer` - Kustomer\n* `dixa` - Dixa\n* `plain` - Plain\n* `gitlab` - GitLab\n* `gitea` - Gitea\n* `shortcut` - Shortcut\n* `sentry` - Sentry\n* `rollbar` - Rollbar\n* `bugsnag` - Bugsnag\n* `honeybadger` - Honeybadger\n* `raygun` - Raygun\n* `snyk` - Snyk\n* `sonarqube` - SonarQube\n* `semgrep` - Semgrep\n* `rapid7_insightvm` - Rapid7 InsightVM\n* `featurebase` - Featurebase\n* `frill` - Frill\n* `aha` - Aha\n* `uservoice` - UserVoice\n* `productboard` - Productboard\n* `canny` - Canny\n* `asknicely` - AskNicely\n* `retently` - Retently\n* `appfigures` - Appfigures\n* `appfollow` - AppFollow\n* `judgeme_reviews` - Judge.me\n* `intercom` - Intercom\n* `hubspot` - HubSpot\n* `engineering_analytics` - Engineering analytics\n* `google_search_console` - Google Search Console",
+ "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `jira` - Jira\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `signals_check` - Report check\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints\n* `replay_vision` - Replay Vision\n* `analytics` - Product analytics\n* `freshdesk` - Freshdesk\n* `freshservice` - Freshservice\n* `front` - Front\n* `gorgias` - Gorgias\n* `kustomer` - Kustomer\n* `dixa` - Dixa\n* `plain` - Plain\n* `gitlab` - GitLab\n* `gitea` - Gitea\n* `shortcut` - Shortcut\n* `sentry` - Sentry\n* `rollbar` - Rollbar\n* `bugsnag` - Bugsnag\n* `honeybadger` - Honeybadger\n* `raygun` - Raygun\n* `snyk` - Snyk\n* `sonarqube` - SonarQube\n* `semgrep` - Semgrep\n* `rapid7_insightvm` - Rapid7 InsightVM\n* `featurebase` - Featurebase\n* `frill` - Frill\n* `aha` - Aha\n* `uservoice` - UserVoice\n* `productboard` - Productboard\n* `canny` - Canny\n* `asknicely` - AskNicely\n* `retently` - Retently\n* `appfigures` - Appfigures\n* `appfollow` - AppFollow\n* `judgeme_reviews` - Judge.me\n* `intercom` - Intercom\n* `hubspot` - HubSpot\n* `engineering_analytics` - Engineering analytics\n* `google_search_console` - Google Search Console",
"enum": [
"session_replay",
"llm_analytics",
@@ -29,6 +29,7 @@
"error_tracking",
"pganalyze",
"signals_scout",
+ "signals_check",
"logs",
"health_checks",
"endpoints",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json
index 59cc54ce49cc..d5cbe79fb12e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json
@@ -17,7 +17,7 @@
"type": "string"
},
"source_product": {
- "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `jira` - Jira\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints\n* `replay_vision` - Replay Vision\n* `analytics` - Product analytics\n* `freshdesk` - Freshdesk\n* `freshservice` - Freshservice\n* `front` - Front\n* `gorgias` - Gorgias\n* `kustomer` - Kustomer\n* `dixa` - Dixa\n* `plain` - Plain\n* `gitlab` - GitLab\n* `gitea` - Gitea\n* `shortcut` - Shortcut\n* `sentry` - Sentry\n* `rollbar` - Rollbar\n* `bugsnag` - Bugsnag\n* `honeybadger` - Honeybadger\n* `raygun` - Raygun\n* `snyk` - Snyk\n* `sonarqube` - SonarQube\n* `semgrep` - Semgrep\n* `rapid7_insightvm` - Rapid7 InsightVM\n* `featurebase` - Featurebase\n* `frill` - Frill\n* `aha` - Aha\n* `uservoice` - UserVoice\n* `productboard` - Productboard\n* `canny` - Canny\n* `asknicely` - AskNicely\n* `retently` - Retently\n* `appfigures` - Appfigures\n* `appfollow` - AppFollow\n* `judgeme_reviews` - Judge.me\n* `intercom` - Intercom\n* `hubspot` - HubSpot\n* `engineering_analytics` - Engineering analytics\n* `google_search_console` - Google Search Console",
+ "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `jira` - Jira\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `signals_check` - Report check\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints\n* `replay_vision` - Replay Vision\n* `analytics` - Product analytics\n* `freshdesk` - Freshdesk\n* `freshservice` - Freshservice\n* `front` - Front\n* `gorgias` - Gorgias\n* `kustomer` - Kustomer\n* `dixa` - Dixa\n* `plain` - Plain\n* `gitlab` - GitLab\n* `gitea` - Gitea\n* `shortcut` - Shortcut\n* `sentry` - Sentry\n* `rollbar` - Rollbar\n* `bugsnag` - Bugsnag\n* `honeybadger` - Honeybadger\n* `raygun` - Raygun\n* `snyk` - Snyk\n* `sonarqube` - SonarQube\n* `semgrep` - Semgrep\n* `rapid7_insightvm` - Rapid7 InsightVM\n* `featurebase` - Featurebase\n* `frill` - Frill\n* `aha` - Aha\n* `uservoice` - UserVoice\n* `productboard` - Productboard\n* `canny` - Canny\n* `asknicely` - AskNicely\n* `retently` - Retently\n* `appfigures` - Appfigures\n* `appfollow` - AppFollow\n* `judgeme_reviews` - Judge.me\n* `intercom` - Intercom\n* `hubspot` - HubSpot\n* `engineering_analytics` - Engineering analytics\n* `google_search_console` - Google Search Console",
"enum": [
"session_replay",
"llm_analytics",
@@ -29,6 +29,7 @@
"error_tracking",
"pganalyze",
"signals_scout",
+ "signals_check",
"logs",
"health_checks",
"endpoints",