:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): define monitoring metric checks (#118139)
Mikayla Thompson52916492bbfc
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex 130667888817..823005497fc0 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -55,6 +55,16 @@ Custom HogQL aggregations are parsed before a metric or check is authored. InvalProtected research runs require analytics access before a person can resume or warm a successor. The successor’s bound sandbox can read the verified source history through authenticated log routes, but cannot modify the source run.+## Monitoring metric definitions++With `signals-report-monitoring` enabled, a metric check can include an optional `config.monitoring` definition. It records the target's `reference_period_minutes`, an explicit `threshold_scaling` policy, and `baseline_period_minutes` when a baseline is supplied. These periods are independent of the soak, run interval, expiry, and any future Monitoring deadline. No existing check receives an inferred definition.++The definition describes a measurement from Monitoring start through the observation time. A `linear` target scales by elapsed minutes divided by reference minutes and requires a single additive event count or property sum without a formula. Session-level sums are excluded because a session can contribute to more than one chart bucket. A `fixed` target keeps its bound as the observation period grows, including for percentages, averages, distinct counts, or explicitly fixed custom targets. Display format alone never selects the policy. The baseline retains its own measured period and is not presented as an observation from Monitoring.++Expected impact keeps the activity chart visible and collapses the target period, scaling policy, baseline, and minimum wait under measurement details. Dynamic chart boundaries refresh at minute intervals so repeated views can reuse cached results. Bucket granularity follows the full displayed range and stays within the 1,000-point budget. The chart preserves date-range filters and spans one reference period on each side of Monitoring start, or now before Monitoring starts, extending through now if necessary. Start and now markers separate the surrounding activity from future dates, whose values remain empty. Compatible charts show target reference lines: additive linear targets scale to a full chart bucket, and fixed rates or property averages/quantiles retain their level. Fixed totals, distinct counts, unknown aggregations, linear calendar intervals longer than a day, and linear day buckets with unequal daylight-saving durations receive no reference line. These references do not impose per-bucket pass/fail rules. This read-time chart does not evaluate the Monitoring target or save a check result. The stored bounded query and whole-window comparison retain their existing Resolved execution meaning. Monitoring execution, scaled comparisons, saved interim observations, and final outcomes remain separate work.++The server refuses new Monitoring definitions when the flag is disabled or unavailable and omits the definition from check responses. Stored definitions remain intact. Research carries its definition-visibility decision into reconciliation, so flag recovery during a run does not replace an unchanged check or reset its approval and schedule. Existing definitions, charts, check schedules, and Resolved outcomes otherwise follow their current behavior.+## Inbox value summaryThe `signals-inbox-value-summary` flag shows project-wide counts above the webdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 71ddfc294305..fc29aadaa0c6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11202,6 +11202,26 @@ snapshots:hash: v1.k794b7964.edd5299beb69a84a93bbf0f52027dbe6f13a5b9d9585a2c29baa188cb6ed7a42.kXjmkRCQpYM5AA02sRPqTPT0YaWs-WY_CmDsG0GdQLAscenes-app-inbox-detail-expected-impact--metric-check--light:hash: v1.k794b7964.310dcf4af274f3011c148d9890a4a72507418b43a800535b192d91f4cb709791.HBW72C9W6XXe-cgONBY3vJ9VA4q_26sThTLfFgQv0X0+ scenes-app-inbox-detail-expected-impact--monitoring-definition--dark:+ hash: v1.k794b7964.f482d5e856f4a091907c17df4d10f7177ad0b869651f7f12db7bc4068c63af5a.Zuqxv1SHytVPlbUuSBT_BmnXRlo4gG_RWBbqfOvB2EI+ scenes-app-inbox-detail-expected-impact--monitoring-definition--light:+ hash: v1.k794b7964.1c48e4db15ed08eccbea00bcbf4ac171f5464150f4fd38b9d8b6a3059568da37.45trlRpmF2xF5WVaJuk4TKp8U2ij2xQyvfCozBCtcFU+ scenes-app-inbox-detail-expected-impact--monitoring-definition-flag-off--dark:+ hash: v1.k794b7964.2159fc93ebc60413cf0baf9a6c23baf5f9002555a57d494983bcb253cc87b72a.Bnyv9obRcLTsAv-h4FIC7THgEui8LoOsj1H2qjW-lj0+ scenes-app-inbox-detail-expected-impact--monitoring-definition-flag-off--light:+ hash: v1.k794b7964.6a75f114a3b82e271240e13ebd0ba8d8d21f5a11da64fdf4e1c3fab06920adaa.NgM0xTjXuMDY9mDs2T1TozhdgCmL15Bp9TyklOe3htg+ scenes-app-inbox-detail-expected-impact--monitoring-definition-narrow--dark:+ hash: v1.k794b7964.4dfeb114cad317e4cba7ae3f2c67de70c49c7dfa1af1d00f00d38e3f915f6270.FspNXRPH4N3s8bwmSoDqySs6ICe1u3p3br7URhC7UyM+ scenes-app-inbox-detail-expected-impact--monitoring-definition-narrow--light:+ hash: v1.k794b7964.b7e63fb3ad4441f3e869541223241b21b9650ee2e6316d8e1c4ccbc30d3c436c._UG4NkF_E-VdiJp_pOQEekrk6pKQXoV2wSK8VFdsxtM+ scenes-app-inbox-detail-expected-impact--monitoring-fixed-target--dark:+ hash: v1.k794b7964.91d98ef087648fdc073dc47b0156423532f35e1f16b5fb29008e5691c33a2660.QEHsmnLcRiZVgpjCkv_1Tgf67tQ8eIzb4ZrQVQky83M+ scenes-app-inbox-detail-expected-impact--monitoring-fixed-target--light:+ hash: v1.k794b7964.c8474a99c310a6d27e85bff16feecf375ea787c0d2b6dfcb5278ae4327ee0de8.c9c4hHQBYcUX5xP4GOa_xgFxCjdihqVP9iEyo2tP9qo+ scenes-app-inbox-detail-expected-impact--monitoring-rate-target--dark:+ hash: v1.k794b7964.70cfc07fc2521c97d58224900b8a04bbbf71ab17ad9676ce3d6daee7de293ba3.6Y5k-TjzULfY4BBUpE_tMvk-phrEVF9OSNdOFg806f4+ scenes-app-inbox-detail-expected-impact--monitoring-rate-target--light:+ hash: v1.k794b7964.2c04b68013375c5f011d1ab8a07b869fef0f40840c163711debb09b40a65bb78.WoFy4o2ilcUHQQWtfoJUJPX_WBl1q1dhwdcnNuBuB-8scenes-app-inbox-detail-expected-impact--narrow--dark:hash: v1.k794b7964.a2aea8677171f649ba45a21aa7103003773b36dcf0efe8093a2b4184897ac105.FESJsY6WQhEi2AtXx4RHoVDnx-pVcqRVizXrGQbSus0scenes-app-inbox-detail-expected-impact--narrow--light:diff --git a/products/signals/backend/report_check_authoring.py b/products/signals/backend/report_check_authoring.pyindex 343b7924cf17..164e66ac2c62 100644--- a/products/signals/backend/report_check_authoring.py+++ b/products/signals/backend/report_check_authoring.py@@ -48,6 +48,7 @@ from products.signals.backend.report_checks import (soak_minutes_from_gap,validate_metric_check_for_write,)+from products.signals.backend.report_content_gates import team_report_monitoring_enabledfrom products.signals.backend.report_lifecycle import effective_report_statusfrom products.signals.backend.report_metric_access import ReportMetricAccessPolicy@@ -228,6 +229,12 @@ def _stored_config(report: SignalReport, kind: str, config: dict) -> dict:except CheckConfigValidationError as error:raise CheckCreationError(str(error)) from None+ if (+ isinstance(parsed, MetricThresholdConfig)+ and parsed.monitoring is not None+ and not team_report_monitoring_enabled(report.team_id)+ ):+ raise CheckCreationError("Monitoring metric definitions are not enabled for this organization.")stored_config = dict(config)if isinstance(parsed, MetricThresholdConfig) and parsed.metric_id is not None:if parsed.query is not None:@@ -280,13 +287,25 @@ def _with_metric_display(report: SignalReport, config: dict, metric_id: str | Noreturn filled-def _check_configs_match(report: SignalReport, check: SignalReportCheck, desired: dict) -> bool:+def _check_configs_match(+ report: SignalReport, check: SignalReportCheck, desired: dict, *, monitoring_definitions_visible: bool | None+) -> bool:try:stored = parse_check_config(check.kind, _with_metric_display(report, check.config, check.config.get("metric_id")))except CheckConfigValidationError:return False+ if (+ isinstance(stored, MetricThresholdConfig)+ and stored.monitoring is not None+ and not (+ team_report_monitoring_enabled(report.team_id)+ if monitoring_definitions_visible is None+ else monitoring_definitions_visible+ )+ ):+ stored = stored.model_copy(update={"monitoring": None})return stored == parse_check_config(check.kind, desired)@@ -302,6 +321,7 @@ def create_checks_from_specs(specs: list[CheckSpec],attribution: ArtefactAttribution,checks_snapshot: dict[str, str] | None = None,+ monitoring_definitions_visible: bool | None = None,reconcile: bool = True,) -> CheckReconciliation:"""Reconcile a successful verification turn with the report's open checks.@@ -361,7 +381,9 @@ def create_checks_from_specs("soak_hours" not in spec.model_fields_setor max(1, round((check.soak_minutes or 60) / 60)) == spec.soak_hours)- and _check_configs_match(report, check, config)+ and _check_configs_match(+ report, check, config, monitoring_definitions_visible=monitoring_definitions_visible+ )),None,)diff --git a/products/signals/backend/report_checks.py b/products/signals/backend/report_checks.pyindex c5614d2ba256..3731ffdd82ae 100644--- a/products/signals/backend/report_checks.py+++ b/products/signals/backend/report_checks.py@@ -32,6 +32,7 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validafrom products.signals.backend.report_charts import _unstorable_textfrom products.signals.backend.report_metrics import (+ MAX_LIVE_METRIC_WINDOW_DAYS,MAX_METRIC_UNIT_LENGTH,ReportMetric,ReportMetricKind,@@ -150,6 +151,32 @@ class CheckComparison(BaseModel):return self+class MonitoringMetricConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")++ reference_period_minutes: int = Field(+ strict=True,+ gt=0,+ le=MAX_LIVE_METRIC_WINDOW_DAYS * 24 * 60,+ description="The period the comparison target describes, in minutes. Independent of the soak and run schedule.",+ )+ threshold_scaling: Literal["linear", "fixed"] = Field(+ description=(+ "How the target applies to a measurement from Monitoring start to the observation time. "+ "`linear` multiplies the target by elapsed minutes / reference_period_minutes and requires an additive "+ "event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. "+ "This definition does not enable Monitoring execution."+ ),+ )+ baseline_period_minutes: int | None = Field(+ default=None,+ strict=True,+ gt=0,+ le=MAX_LIVE_METRIC_WINDOW_DAYS * 24 * 60,+ description="The actual period measured by baseline_value, in minutes. Required when a baseline is supplied.",+ )++class MetricThresholdConfig(BaseModel):"""A deterministic check: measure one number, compare it, record the verdict.@@ -186,6 +213,13 @@ class MetricThresholdConfig(BaseModel):"you unless `metricSummary` is `latest`, which keeps compare mode off already."),)+ monitoring: MonitoringMetricConfig | None = Field(+ default=None,+ description=(+ "Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. "+ "Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks."+ ),+ )comparison: CheckComparison = Field(description="What the measured value must satisfy to pass.")baseline_value: float | None = Field(default=None,@@ -338,6 +372,27 @@ def parse_check_config(kind: str, config: object) -> BaseModel:def validate_metric_check_for_write(config: MetricThresholdConfig) -> None:if config.query is None:raise CheckConfigValidationError("The metric query must be resolved before writing a check.")+ if config.monitoring is not None:+ if config.baseline_value is not None and config.monitoring.baseline_period_minutes is None:+ raise CheckConfigValidationError("A Monitoring baseline needs its measured baseline_period_minutes.")+ if config.monitoring.threshold_scaling == "linear":+ source = config.query["source"]+ series = source["series"]+ if (+ len(series) != 1+ or any((source.get("trendsFilter") or {}).get(key) for key in ("formula", "formulas", "formulaNodes"))+ or series[0].get("math") not in {None, "total", "sum"}+ or (+ series[0].get("math") == "sum"+ and (+ series[0].get("math_property") == "$session_duration"+ or series[0].get("math_property_type") == "session_properties"+ )+ )+ ):+ raise CheckConfigValidationError(+ "Linear Monitoring targets require one additive event count or property sum, without a formula."+ )kind = config.metric_kind or "custom"value_format = config.value_format or "number"try:diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.mdindex dc28f52ad199..2049d8cd0cce 100644--- a/products/signals/backend/report_generation/AGENTS.md+++ b/products/signals/backend/report_generation/AGENTS.md@@ -82,6 +82,8 @@ In production, the `update` path is triggered automatically when a `ready` reporThis module is intentionally prompt-orchestration only.Production persistence is handled outside `run_multi_turn_research()`, in the caller activity, so this module stays isolated from report DB writes.+Monitoring metric definitions are offered only with `signals-report-monitoring` enabled. The shared writer validates the reference period, scaling policy, and baseline period. Disabled research contexts omit stored Monitoring definitions. Read [Monitoring metric definitions](../../../../docs/internal/signals-pr-lifecycle.md#monitoring-metric-definitions) when changing this contract; execution and final outcomes ship separately.+Fix verification is best-effort. Generation failures do not fail completed research, but cancellation still does.Presentation receives the current follow-up checks as untrusted evidence. When verification proposes metric checks, it can return a separate `checks_summary` with Expected impact prose aligned with those goals and baselines, preserving other sections and chart markers. The transition applies that summary only if the matching check reconciliation succeeds. Omitted waits inherit the referenced check’s wait before generating the verification note. Invalid optional check specs leave the presentation summary and existing checks intact.diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.pyindex 4f473fb41e9e..08ee8c206b25 100644--- a/products/signals/backend/report_generation/research.py+++ b/products/signals/backend/report_generation/research.py@@ -360,6 +360,19 @@ _METRIC_CHECK_GUIDANCE = """- Use `kind: "metric_threshold"` when the `outcome`Do not use a per-interval goal: the executor compares the whole query window. A spec naminganything else is dropped."""+_MONITORING_METRIC_CHECK_GUIDANCE = """- This organization can define Monitoring metric checks. When the evidence establishes the periods and+ scaling policy, include `config.monitoring` with `reference_period_minutes`, `threshold_scaling`, and+ `baseline_period_minutes`. The reference period is the period the comparison target describes; the+ baseline period is the actual period you measured. Both are positive whole minutes, at most 366 days.+ They are independent of soak_hours and the run schedule. Monitoring observations will cover Monitoring+ start through the observation time. Choose `linear` only for one additive event count or property sum+ without a formula: the target scales by elapsed minutes / reference_period_minutes. Choose `fixed`+ explicitly for rates, averages, distinct counts, or other targets that keep the same bound. Never infer+ scaling from the number's display format. Supply the baseline period whenever baseline_value is present.+ If these facts are unknown, omit monitoring rather than invent them. Preserve the bounded relative query+ and whole-window comparison for existing Resolved behavior. This only defines the measurement; it does+ not enable interim execution or decide a final outcome."""+_AGENT_CHECK_GUIDANCE = """- Use `kind: "agent"` when no single number settles the claim but a later run can establish it byreading the project's data, such as re-reading an error issue's recent events. It needs no metric,baseline, or comparison. The `config` is@@ -1323,6 +1336,7 @@ Respond with a JSON object matching this schema:def build_fix_verification_prompt(*,metric_checks_enabled: bool = False,+ monitoring_enabled: bool = False,agent_checks_enabled: bool = False,previous_checks: list[dict] | None = None,) -> str:@@ -1339,6 +1353,7 @@ def build_fix_verification_prompt(guidancefor guidance, enabled in ((_METRIC_CHECK_GUIDANCE, metric_checks_enabled),+ (_MONITORING_METRIC_CHECK_GUIDANCE, metric_checks_enabled and monitoring_enabled),(_AGENT_CHECK_GUIDANCE, agent_checks_enabled),(_METRIC_ONLY_CHECK_GUIDANCE, metric_checks_enabled and not agent_checks_enabled),)@@ -1478,6 +1493,7 @@ async def run_multi_turn_research(resolved_report_summary: str | None = None,linked_reports: list[LinkedReportContext] | None = None,metrics_enabled: bool = False,+ monitoring_enabled: bool = False,reviewer_selection_enabled: bool = False,agent_checks_enabled: bool = False,steering_section: str = "",@@ -1685,6 +1701,7 @@ async def run_multi_turn_research(# 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,+ monitoring_enabled=monitoring_enabled,agent_checks_enabled=agent_checks_enabled,previous_checks=previous_checks,)diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex b38c2eac2b35..c9c54c913660 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -2213,6 +2213,14 @@ class SignalReportCheckSerializer(serializers.ModelSerializer):config = representation.get("config")if isinstance(config, Mapping):config = dict(config)+ if "monitoring" in config:+ enabled_by_team = cast(+ dict[int, bool], self.context.setdefault("report_monitoring_enabled_by_team", {})+ )+ if instance.team_id not in enabled_by_team:+ enabled_by_team[instance.team_id] = team_report_monitoring_enabled(instance.team_id)+ if not enabled_by_team[instance.team_id]:+ config.pop("monitoring")if instance.kind == SignalReportCheck.Kind.METRIC_THRESHOLD:metric = next((diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.pyindex 2672b7bc1a1e..7c212bcbdd7e 100644--- a/products/signals/backend/temporal/agentic/report.py+++ b/products/signals/backend/temporal/agentic/report.py@@ -46,6 +46,7 @@ from products.signals.backend.report_charts import ReportChart, chart_batch_errofrom products.signals.backend.report_check_research import check_versionsfrom products.signals.backend.report_content_gates import (team_report_metrics_enabled,+ team_report_monitoring_enabled,team_research_reviewer_selection_enabled,)from products.signals.backend.report_generation.ownership_reviewers import suggest_repository_owners@@ -130,6 +131,8 @@ class RunAgenticReportOutput:# there rather than stored pointing at nothing. `None` predates the field and writes none.checks: list[dict[str, Any]] | None = Nonechecks_snapshot: dict[str, str] | None = None+ # Reconciliation must use the definition visibility research saw if the rollout changes mid-run.+ checks_monitoring_enabled: bool = False# Old activity results wrote an empty list when no checks were authored. The transition may# reconcile existing rows only when this marker came from a new verification turn.@@ -267,7 +270,7 @@ def _parse_stored_metrics(raw: object, report_id: str) -> list[ReportMetric]:return parsed-def _load_previous_checks(team_id: int, report_id: str) -> list[dict]:+def _load_previous_checks(team_id: int, report_id: str, *, monitoring_enabled: bool = False) -> list[dict]:checks = SignalReportCheck.objects.for_team(team_id).filter(report_id=report_id, status__in=SignalReportCheck.OPEN_STATUSES)@@ -282,6 +285,7 @@ def _load_previous_checks(team_id: int, report_id: str) -> list[dict]:for key, value in check.config.items()if (key != "query" or not check.config.get("metric_id"))and (key != "baseline_value" or check.config.get("query") is not None)+ and (key != "monitoring" or monitoring_enabled)},"stored_query": check.config.get("query")if check.kind == SignalReportCheck.Kind.METRIC_THRESHOLD@@ -1087,6 +1091,9 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgentimetrics_enabled = await database_sync_to_async(team_report_metrics_enabled, thread_sensitive=False)(input.team_id)+ monitoring_enabled = await database_sync_to_async(team_report_monitoring_enabled, thread_sensitive=False)(+ input.team_id+ )reviewer_selection_enabled = await database_sync_to_async(team_research_reviewer_selection_enabled, thread_sensitive=False)(input.team_id)@@ -1114,7 +1121,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti)previous_research = await _load_previous_research(input.team_id, input.report_id)previous_checks = await database_sync_to_async(_load_previous_checks, thread_sensitive=False)(- input.team_id, input.report_id+ input.team_id, input.report_id, monitoring_enabled=monitoring_enabled)# 2b. Load the resolved report this one recurred from, if any, as extra research contextresolved_report_title, resolved_report_summary = await _load_resolved_report_context(@@ -1151,6 +1158,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgentiresolved_report_summary=resolved_report_summary,linked_reports=linked_reports,metrics_enabled=metrics_enabled,+ monitoring_enabled=monitoring_enabled,reviewer_selection_enabled=reviewer_selection_enabled,agent_checks_enabled=agent_checks_enabled,steering_section=steering.section,@@ -1200,6 +1208,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgentireconcile_checks=result.checks is not None,checks_summary=result.checks_summary,checks_snapshot=checks_snapshot,+ checks_monitoring_enabled=monitoring_enabled,layers=[layer.model_dump(mode="json") for layer in result.layers],research_task_id=result.research_task_id,charts_enabled=True,diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex b00edd296997..ce3340de2183 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -168,6 +168,7 @@ class ReportDecision:reconcile_checks: bool = Falsechecks_summary: str | None = Nonechecks_snapshot: dict[str, str] | None = None+ checks_monitoring_enabled: bool = Falselayers: 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`).@@ -503,6 +504,7 @@ class SignalReportSummaryWorkflow:reconcile_checks=agentic_result.reconcile_checks,checks_summary=agentic_result.checks_summary,checks_snapshot=agentic_result.checks_snapshot,+ checks_monitoring_enabled=agentic_result.checks_monitoring_enabled,layers=agentic_result.layers or [],research_task_id=agentic_result.research_task_id,charts_enabled=agentic_result.charts_enabled,@@ -546,6 +548,7 @@ class SignalReportSummaryWorkflow:metrics=decision.metrics,checks=decision.checks,checks_snapshot=decision.checks_snapshot,+ checks_monitoring_enabled=decision.checks_monitoring_enabled,reconcile_checks=decision.reconcile_checks,checks_summary=decision.checks_summary,checks_task_id=decision.research_task_id,@@ -575,6 +578,7 @@ class SignalReportSummaryWorkflow:metrics=decision.metrics,checks=decision.checks,checks_snapshot=decision.checks_snapshot,+ checks_monitoring_enabled=decision.checks_monitoring_enabled,reconcile_checks=decision.reconcile_checks,checks_summary=decision.checks_summary,checks_task_id=decision.research_task_id,@@ -896,6 +900,7 @@ class MarkReportReadyInput:# that meant "write none", so only a new result marked for reconciliation can clear rows.checks: list[dict[str, Any]] | None = Nonechecks_snapshot: dict[str, str] | None = None+ checks_monitoring_enabled: bool = Falsereconcile_checks: bool = Falsechecks_summary: str | None = None@@ -954,6 +959,7 @@ def _write_research_checks(report: SignalReport, input: "MarkReportReadyInput |reconcile=input.reconcile_checks,specs=specs,checks_snapshot=input.checks_snapshot,+ monitoring_definitions_visible=input.checks_monitoring_enabled,attribution=(ArtefactAttribution.from_task(input.checks_task_id)if input.checks_task_id@@ -1255,6 +1261,7 @@ class MarkReportPendingInput:# See MarkReportReadyInput.checks: same transaction, same replay-safe defaults.checks: list[dict[str, Any]] | None = Nonechecks_snapshot: dict[str, str] | None = None+ checks_monitoring_enabled: bool = Falsereconcile_checks: bool = Falsechecks_summary: str | None = Nonechecks_task_id: str | None = Nonediff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.pyindex ae69c9b6fe00..0c337f5717d8 100644--- a/products/signals/backend/test/test_agentic_report_activity.py+++ b/products/signals/backend/test/test_agentic_report_activity.py@@ -1148,9 +1148,14 @@ async def test_run_agentic_report_activity_resolves_metrics_payload(@pytest.mark.django_db@pytest.mark.parametrize("has_previous_research", [False, True])@pytest.mark.parametrize("has_query", [False, True])[email protected]("monitoring_enabled", [False, True])async def test_run_agentic_report_activity_supplies_existing_checks_to_reresearch(- monkeypatch, ateam, has_previous_research, has_query+ monkeypatch, ateam, has_previous_research, has_query, monitoring_enabled):+ monkeypatch.setattr(+ "products.signals.backend.report_content_gates.feature_enabled_or_false",+ lambda flag, *args, **kwargs: monitoring_enabled if flag == "signals-report-monitoring" else False,+ )report = await database_sync_to_async(SignalReport.objects.create)(team=ateam, status=SignalReport.Status.IN_PROGRESS, signal_count=2, total_weight=1.3)@@ -1163,6 +1168,11 @@ async def test_run_agentic_report_activity_supplies_existing_checks_to_reresearc"query": _metric().query if has_query else None,"baseline_value": 40,"comparison": {"operator": "lte", "value": 0},+ "monitoring": {+ "reference_period_minutes": 10080,+ "threshold_scaling": "fixed",+ "baseline_period_minutes": 10080,+ },},status=SignalReportCheck.Status.PENDING,next_run_at=timezone.now() + timedelta(days=7),@@ -1186,6 +1196,9 @@ async def test_run_agentic_report_activity_supplies_existing_checks_to_reresearcassert previous_checks[0]["id"] == str(check.id)assert previous_checks[0]["approved"] is Trueassert ("baseline_value" in previous_checks[0]["config"]) is has_query+ assert ("monitoring" in previous_checks[0]["config"]) is monitoring_enabled+ assert research_kwargs["monitoring_enabled"] is monitoring_enabled+ assert result.checks_monitoring_enabled is monitoring_enabledassert result.checks_snapshot == {str(check.id): check.updated_at.isoformat()}diff --git a/products/signals/backend/test/test_report_checks.py b/products/signals/backend/test/test_report_checks.pyindex e76c4a01e3b7..3502a8e534dc 100644--- a/products/signals/backend/test/test_report_checks.py+++ b/products/signals/backend/test/test_report_checks.py@@ -167,6 +167,24 @@ class TestCheckComparison(SimpleTestCase):@parameterized.expand([+ ("missing_monitoring_period", _threshold_config(monitoring={"threshold_scaling": "linear"})),+ ("missing_scaling_policy", _threshold_config(monitoring={"reference_period_minutes": 10080})),+ (+ "zero_monitoring_period",+ _threshold_config(monitoring={"reference_period_minutes": 0, "threshold_scaling": "fixed"}),+ ),+ (+ "boolean_monitoring_period",+ _threshold_config(monitoring={"reference_period_minutes": True, "threshold_scaling": "fixed"}),+ ),+ (+ "unbounded_monitoring_period",+ _threshold_config(monitoring={"reference_period_minutes": 527041, "threshold_scaling": "fixed"}),+ ),+ (+ "unknown_scaling_policy",+ _threshold_config(monitoring={"reference_period_minutes": 10080, "threshold_scaling": "automatic"}),+ ),("null_unit", _threshold_config(unit="m\x00s")),("surrogate_unit", _threshold_config(unit="m\ud800s")),("neither_source", {"comparison": {"operator": "lte", "value": 1}}),@@ -202,6 +220,57 @@ class TestCheckComparison(SimpleTestCase):with self.assertRaises(CheckConfigValidationError):parse_check_config("metric_threshold", config)+ @parameterized.expand(+ [+ ("count", "total", "linear", None, True),+ ("null_count", None, "linear", None, True),+ ("sum", "sum", "linear", None, True),+ ("session_duration_sum", "sum", "linear", None, False, "$session_duration"),+ ("session_property_sum", "sum", "linear", None, False, "$pageview_count", "session_properties"),+ ("fixed_session_sum", "sum", "fixed", None, True, "$session_duration"),+ ("distinct", "dau", "linear", None, False),+ ("average", "avg", "linear", None, False),+ ("fixed_average", "avg", "fixed", None, True),+ ("fixed_distinct", "dau", "fixed", None, True),+ ("formula", "total", "linear", {"formulas": ["A * 2"]}, False),+ ("missing_baseline_period", "total", "fixed", None, False),+ ]+ )+ def test_monitoring_targets_require_explicit_supported_scaling(+ self,+ name: str,+ math: str | None,+ scaling: str,+ trends_filter: dict | None,+ valid: bool,+ math_property: str = "amount",+ math_property_type: str | None = None,+ ) -> None:+ query = trends_metric_query(+ series=[+ {+ "kind": "EventsNode",+ "event": "checkout_failed",+ "math": math,+ "math_property": math_property,+ "math_property_type": math_property_type,+ }+ ]+ )+ if trends_filter is not None:+ query["source"]["trendsFilter"] = trends_filter+ monitoring: dict[str, object] = {"reference_period_minutes": 10080, "threshold_scaling": scaling}+ if name != "missing_baseline_period":+ monitoring["baseline_period_minutes"] = 20160+ config = MetricThresholdConfig.model_validate(+ _threshold_config(query=query, baseline_value=80, monitoring=monitoring)+ )+ if valid:+ validate_metric_check_for_write(config)+ else:+ with self.assertRaises(CheckConfigValidationError):+ validate_metric_check_for_write(config)+def test_a_padded_metric_reference_is_normalized_so_it_can_still_match(self) -> None:config = parse_check_config("metric_threshold", {"metric_id": " checkout-errors ", "comparison": {"operator": "lte", "value": 1}}@@ -1023,6 +1092,59 @@ class TestReportCheckAPI(APIBaseTest):spec.update(overrides)return create_check(report=report or self.report, attribution=ArtefactAttribution.system(), **spec)+ @parameterized.expand(+ [+ ("enabled", True),+ ("disabled", False),+ ("unavailable", RuntimeError("flag unavailable")),+ ]+ )+ def test_monitoring_metric_definition_writes_and_reads_follow_the_organization_gate(+ self, _name: str, flag_result: bool | Exception+ ) -> None:+ monitoring = {+ "reference_period_minutes": 10080,+ "threshold_scaling": "linear",+ "baseline_period_minutes": 20160,+ }+ config = _threshold_config(baseline_value=80, monitoring=monitoring)+ with patch("products.signals.backend.report_content_gates.feature_enabled_or_false", return_value=True):+ check = self._create(config=config)+ with patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false",+ return_value=flag_result if isinstance(flag_result, bool) else False,+ side_effect=flag_result if isinstance(flag_result, Exception) else None,+ ):+ if flag_result is True:+ self._create(config=config)+ else:+ with self.assertRaisesMessage(CheckCreationError, "not enabled"):+ self._create(config=config)+ response = self.client.get(f"{self.url}{check.id}/")+ assert response.status_code == status.HTTP_200_OK+ returned_config = response.json()["config"]+ assert ("monitoring" in returned_config) is (flag_result is True)+ assert returned_config["query"] == _PAGEVIEWS+ assert returned_config["comparison"] == config["comparison"]+ check.refresh_from_db()+ assert check.config["monitoring"] == monitoring++ def test_monitoring_metric_definitions_do_not_cross_organization_rollouts(self) -> None:+ other_organization = Organization.objects.create(name="Other organization")+ other_team = Team.objects.create(organization=other_organization)+ other_report = SignalReport.objects.create(team=other_team, status=SignalReport.Status.READY, title="Other fix")+ config = _threshold_config(monitoring={"reference_period_minutes": 10080, "threshold_scaling": "fixed"})+ with patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false",+ side_effect=lambda flag, organization_id, **kwargs: organization_id == str(self.organization.id),+ ):+ check = self._create(config=config)+ with self.assertRaisesMessage(CheckCreationError, "not enabled"):+ self._create(report=other_report, config=config)+ response = self.client.get(f"{self.url}{check.id}/")+ assert response.json()["config"]["monitoring"] == config["monitoring"]+ assert not SignalReportCheck.objects.for_team(other_team.id).exists()+def test_the_endpoint_does_not_create_checks(self) -> None:response = self.client.post(self.url,@@ -2800,6 +2922,9 @@ class TestResearchAuthoredChecks(APIBaseTest):@parameterized.expand([("current_config", False, "unchanged"),+ ("hidden_monitoring_definition", False, "unchanged", "monitoring_disabled"),+ ("hidden_monitoring_after_flag_recovery", False, "unchanged", "monitoring_recovered"),+ ("visible_monitoring_removed", False, "revise", "monitoring_visible"),("config_written_before_display_fields", True, "unchanged"),("revise_approved", False, "revise"),("retire_approved", False, "retire"),@@ -2833,6 +2958,12 @@ class TestResearchAuthoredChecks(APIBaseTest):stored_config.update(probe_hints=[], skill_name=None)if variant == "invalid_stored":stored_config["retired_config_field"] = "obsolete"+ if variant in {"monitoring_disabled", "monitoring_recovered", "monitoring_visible"}:+ stored_config["monitoring"] = {+ "reference_period_minutes": 10080,+ "threshold_scaling": "fixed",+ "baseline_period_minutes": 10080,+ }if variant == "omitted_wait":SignalReportCheck.objects.for_team(self.team.id).filter(id=existing.id).update(soak_minutes=72 * 60)if variant == "recurring":@@ -2856,18 +2987,29 @@ class TestResearchAuthoredChecks(APIBaseTest):else [spec])+ if variant == "monitoring_visible":+ specs = [spec]if variant == "omitted_wait":specs[0] = self._spec(title=specs[0].title, existing_check_id=existing.id)if variant == "invalid_stored":specs = [self._spec(existing_check_id=existing.id)]elif variant == "longer_wait":specs[0] = specs[0].model_copy(update={"soak_hours": 72})- written = create_checks_from_specs(- report=self.report,- specs=specs,- attribution=ArtefactAttribution.system(),- checks_snapshot=check_versions([existing]),- ).created+ with patch(+ "products.signals.backend.report_content_gates.feature_enabled_or_false",+ return_value=variant in {"monitoring_recovered", "monitoring_visible"},+ ):+ written = create_checks_from_specs(+ report=self.report,+ specs=specs,+ attribution=ArtefactAttribution.system(),+ checks_snapshot=check_versions([existing]),+ monitoring_definitions_visible=(+ variant == "monitoring_visible"+ if variant in {"monitoring_recovered", "monitoring_visible"}+ else None+ ),+ ).createdexisting.refresh_from_db()assert existing.status == (@@ -2876,9 +3018,10 @@ class TestResearchAuthoredChecks(APIBaseTest):assert existing.approved_at == approved_atif action == "unchanged":assert (existing.next_run_at, existing.expires_at, existing.updated_at) == original_schedule+ assert existing.config == stored_configassert len(written) == (1 if action == "revise" else 0)if written:- assert written[0].title == (spec.title if variant == "invalid_stored" else "Revised goal")+ assert written[0].title == specs[0].titleassert written[0].approved_at is Noneassert written[0].soak_minutes == (72 * 60 if variant == "longer_wait" else existing.soak_minutes)assert written[0].run_interval_minutes == existing.run_interval_minutesdiff --git a/products/signals/backend/test/test_research_prompt.py b/products/signals/backend/test/test_research_prompt.pyindex 370c4fd5d22a..7df30cd58781 100644--- a/products/signals/backend/test/test_research_prompt.py+++ b/products/signals/backend/test/test_research_prompt.py@@ -278,6 +278,13 @@ class TestBuildInitialResearchPrompt:class TestBuildFixVerificationPrompt:+ @pytest.mark.parametrize("monitoring_enabled", [True, False])+ def test_monitoring_metric_authoring_is_offered_only_when_enabled(self, monitoring_enabled: bool) -> None:+ prompt = build_fix_verification_prompt(metric_checks_enabled=True, monitoring_enabled=monitoring_enabled)+ assert ("reference_period_minutes" in prompt) is monitoring_enabled+ assert ("threshold_scaling" in prompt) is monitoring_enabled+ assert ("baseline_period_minutes" in prompt) is monitoring_enabled+def test_reresearch_reviews_approved_checks_without_gating_them(self):prompt = build_fix_verification_prompt(metric_checks_enabled=True,diff --git a/products/signals/backend/test/test_summary_workflow.py b/products/signals/backend/test/test_summary_workflow.pyindex 1d5b4805c81f..83988d90eeb8 100644--- a/products/signals/backend/test/test_summary_workflow.py+++ b/products/signals/backend/test/test_summary_workflow.py@@ -191,6 +191,7 @@ class _Recorder:self.research_metrics = research_metricsself.checks_snapshot = checks_snapshotself.checks_summary: str | None = None+ self.checks_monitoring_enabled = Falseself.selected_repository = selected_repositoryself.gate_checks: list[str] = []self.fetches = 0@@ -237,6 +238,7 @@ def test_legacy_agentic_activity_payload_defaults_metrics_to_preserve() -> None:assert decoded.metrics is Noneassert decoded.charts is Noneassert decoded.checks_snapshot is None+ assert decoded.checks_monitoring_enabled is Falseasync def _run_summary_workflow(recorder: _Recorder) -> None:@@ -283,6 +285,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:repository="owner/repo",metrics=recorder.research_metrics,checks_snapshot=recorder.checks_snapshot,+ checks_monitoring_enabled=recorder.checks_monitoring_enabled,checks_summary=recorder.checks_summary,)@@ -402,6 +405,7 @@ async def test_metric_payload_reaches_the_report_transition(choice, target):snapshot = {"check-1": "2026-10-02T12:00:00+00:00"}recorder = _Recorder(research_choice=choice, research_metrics=metrics, checks_snapshot=snapshot)recorder.checks_summary = "Expected impact matches the reconciled checks."+ recorder.checks_monitoring_enabled = Trueawait _run_summary_workflow(recorder)@@ -409,6 +413,7 @@ async def test_metric_payload_reaches_the_report_transition(choice, target):assert len(inputs) == 1assert inputs[0].metrics == metricsassert inputs[0].checks_snapshot == snapshot+ assert inputs[0].checks_monitoring_enabled is Trueassert inputs[0].checks_summary == recorder.checks_summarydiff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 829b839498e9..6fb61bccdd91 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -2943,6 +2943,26 @@ export const SignalReportCheckStatusEnumApi = {Cancelled: 'cancelled',} as const+export type ThresholdScalingEnumApi = (typeof ThresholdScalingEnumApi)[keyof typeof ThresholdScalingEnumApi]++export const ThresholdScalingEnumApi = {+ Linear: 'linear',+ Fixed: 'fixed',+} as const++export interface MonitoringMetricConfigApi {+ /**+ * The period the comparison target describes, in minutes. Independent of the soak and run schedule.+ * @maximum 527040+ * @exclusiveMinimum 0+ */+ reference_period_minutes: number+ /** How the target applies to a measurement from Monitoring start to the observation time. `linear` multiplies the target by elapsed minutes / reference_period_minutes and requires an additive event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. This definition does not enable Monitoring execution. */+ threshold_scaling: ThresholdScalingEnumApi+ /** The actual period measured by baseline_value, in minutes. Required when a baseline is supplied. */+ baseline_period_minutes?: number | null+}+export type CheckComparisonOperatorEnumApi =(typeof CheckComparisonOperatorEnumApi)[keyof typeof CheckComparisonOperatorEnumApi]@@ -3031,6 +3051,8 @@ export interface MetricThresholdConfigApi {metric_id?: string | null/** Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already. */query?: MetricThresholdConfigApiQuery+ /** Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks. */+ monitoring?: MonitoringMetricConfigApi | null/** What the measured value must satisfy to pass. */comparison: CheckComparisonApi/** The value observed when the check was written, recorded on each result for context. */diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 359e05aadbe3..53ac3966ac48 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -533,6 +533,12 @@ export const signalsReportChecksReplaceCreateBodyTitleMax = 200export const signalsReportChecksReplaceCreateBodyRationaleMax = 2000+export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesExclusiveMin = 0+export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesMax = 527040++export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin = 0+export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneMax = 527040+export const signalsReportChecksReplaceCreateBodyConfigOneUnitOneMax = 40export const SignalsReportChecksReplaceCreateBody = /* @__PURE__ */ zod.object({@@ -556,6 +562,46 @@ export const SignalsReportChecksReplaceCreateBody = /* @__PURE__ */ zod.object({.describe('Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already.'),+ monitoring: zod+ .union([+ zod.object({+ reference_period_minutes: zod+ .number()+ .gt(+ signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesExclusiveMin+ )+ .max(signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesMax)+ .describe(+ 'The period the comparison target describes, in minutes. Independent of the soak and run schedule.'+ ),+ threshold_scaling: zod+ .enum(['linear', 'fixed'])+ .describe(+ 'How the target applies to a measurement from Monitoring start to the observation time. `linear` multiplies the target by elapsed minutes \/ reference_period_minutes and requires an additive event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. This definition does not enable Monitoring execution.'+ ),+ baseline_period_minutes: zod+ .union([+ zod+ .number()+ .gt(+ signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin+ )+ .max(+ signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneMax+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'The actual period measured by baseline_value, in minutes. Required when a baseline is supplied.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ "Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks."+ ),comparison: zod.object({operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),@@ -2715,6 +2761,12 @@ export const signalsScoutReportCheckCreateBodyTitleMax = 200export const signalsScoutReportCheckCreateBodyRationaleMax = 2000+export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesExclusiveMin = 0+export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesMax = 527040++export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin = 0+export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneMax = 527040+export const signalsScoutReportCheckCreateBodyConfigOneOneUnitOneMax = 40export const signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax = 2000@@ -2759,6 +2811,48 @@ export const SignalsScoutReportCheckCreateBody = /* @__PURE__ */ zod.describe('Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already.'),+ monitoring: zod+ .union([+ zod.object({+ reference_period_minutes: zod+ .number()+ .gt(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesExclusiveMin+ )+ .max(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesMax+ )+ .describe(+ 'The period the comparison target describes, in minutes. Independent of the soak and run schedule.'+ ),+ threshold_scaling: zod+ .enum(['linear', 'fixed'])+ .describe(+ 'How the target applies to a measurement from Monitoring start to the observation time. `linear` multiplies the target by elapsed minutes \/ reference_period_minutes and requires an additive event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. This definition does not enable Monitoring execution.'+ ),+ baseline_period_minutes: zod+ .union([+ zod+ .number()+ .gt(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin+ )+ .max(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneMax+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'The actual period measured by baseline_value, in minutes. Required when a baseline is supplied.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ "Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks."+ ),comparison: zod.object({operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),diff --git a/products/signals/frontend/inbox/__mocks__/reportMetricMocks.ts b/products/signals/frontend/inbox/__mocks__/reportMetricMocks.tsindex 3fbe1a10b615..9c4df1fa6911 100644--- a/products/signals/frontend/inbox/__mocks__/reportMetricMocks.ts+++ b/products/signals/frontend/inbox/__mocks__/reportMetricMocks.ts@@ -83,6 +83,11 @@ const conversionQuery: InsightVizNode<TrendsQuery> = {}const liveMetricResults: Record<string, { aggregatedValue: number; data: number[]; label: string; days?: string[] }> = {+ checkout_failed: {+ aggregatedValue: 280,+ data: [22, 26, 21, 24, 28, 23, 25, 21, 24, 22, 20, 6, 4, 3],+ label: 'Checkout errors',+ },$autocapture: {aggregatedValue: 1248,data: [88, 96, 104, 99, 121, 118, 132, 132, 184, 211, 196, 249, 238, 263],@@ -203,12 +208,30 @@ export async function reportMetricQueryHandler({ request }: { request: Request }query?: {series?: Array<{ custom_name?: string; event?: string; math?: string; name?: string }>trendsFilter?: { formula?: string }+ dateRange?: { date_from?: string; date_to?: string }}}const series = body.query?.series?.[0]const resultKey = body.query?.trendsFilter?.formula ? 'conversion' : series?.eventconst result = liveMetricResults[resultKey ?? ''] ?? liveMetricResults.$autocapture+ let resultDays = result.days ?? dates+ let resultData = result.data+ const range = body.query?.dateRange+ if (range?.date_from && range.date_to && !range.date_from.startsWith('-')) {+ const from = new Date(range.date_from)+ const to = new Date(range.date_to)+ const observed = new Map(resultDays.map((day, index) => [day, result.data[index]]))+ resultDays = []+ resultData = []+ for (const bucket = new Date(from); bucket <= to; bucket.setUTCDate(bucket.getUTCDate() + 1)) {+ bucket.setUTCHours(0, 0, 0, 0)+ const day = bucket.toISOString().slice(0, 10)+ resultDays.push(day)+ resultData.push(observed.get(day) ?? 0)+ }+ }+return [200,{@@ -225,9 +248,9 @@ export async function reportMetricQueryHandler({ request }: { request: Request }},label: result.label,count: result.data.at(-1) ?? 0,- data: result.data,- days: result.days ?? dates,- labels: result.days ?? dates,+ data: resultData,+ days: resultDays,+ labels: resultDays,aggregated_value: result.aggregatedValue,},],diff --git a/products/signals/frontend/inbox/components/detail/ReportChartMarkers.tsx b/products/signals/frontend/inbox/components/detail/ReportChartMarkers.tsxnew file mode 100644index 000000000000..92975304751a--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportChartMarkers.tsx@@ -0,0 +1,40 @@+/* eslint-disable react/forbid-dom-props -- chart scales determine label positions */+import { ReferenceLines, useChartLayout, type ReferenceLineProps } from '@posthog/quill-charts'++export function ReportChartMarkers({ markers }: { markers: ReferenceLineProps[] }): JSX.Element {+ const { scales, dimensions } = useChartLayout()++ return (+ <>+ <ReferenceLines+ lines={markers.map((marker) =>+ marker.labelPosition === 'start' ? { ...marker, label: undefined } : marker+ )}+ />+ {markers.map((marker) => {+ if (marker.labelPosition !== 'start' || typeof marker.value !== 'string' || !marker.label) {+ return null+ }+ const left = scales.x(marker.value)+ if (+ left == null ||+ !Number.isFinite(left) ||+ left < dimensions.plotLeft ||+ left > dimensions.plotLeft + dimensions.plotWidth+ ) {+ return null+ }+ return (+ <span+ key={marker.value}+ data-attr="report-chart-marker-label"+ className="absolute -translate-x-1/2 -translate-y-full whitespace-nowrap pb-1 text-xs text-secondary"+ style={{ left, top: dimensions.plotTop }}+ >+ {marker.label}+ </span>+ )+ })}+ </>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ReportCheckMetricChart.tsx b/products/signals/frontend/inbox/components/detail/ReportCheckMetricChart.tsxindex 09ecbff9e086..3e56dda24a0c 100644--- a/products/signals/frontend/inbox/components/detail/ReportCheckMetricChart.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportCheckMetricChart.tsx@@ -1,7 +1,10 @@import { useValues } from 'kea'+import { useState } from 'react'import { LemonSkeleton } from '@posthog/lemon-ui'+import { teamLogic } from 'scenes/teamLogic'+import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'@@ -14,6 +17,13 @@ import {reportMetricChartType,reportMetricSeriesPoints,} from '../../utils/reportMetrics'+import {+ monitoringChartMarkers,+ monitoringChartPoints,+ monitoringChartQuery,+ monitoringChartTargetLines,+ type ReportMonitoringChartWindow,+} from '../../utils/reportMonitoringChart'import { ReportObservationChart } from './ReportObservationChart'export function ReportCheckMetricChart({@@ -23,6 +33,7 @@ export function ReportCheckMetricChart({goalGrain,goalBounds,version,+ monitoring,}: {reportId: stringmetric: ReportMetricApi@@ -30,21 +41,27 @@ export function ReportCheckMetricChart({goalGrain: 'whole_window' | 'per_interval'goalBounds?: { lower: number; upper: number } | nullversion: string+ monitoring?: ReportMonitoringChartWindow}): JSX.Element {+ const { timezone } = useValues(teamLogic)+ const [observedAt] = useState(() => Date.now())+ const chartQuery = monitoring ? monitoringChartQuery(query, monitoring, observedAt) : queryconst props: DataNodeLogicProps = {key: `ReportMetricSeries.${reportId}.${metric.metric_id}.${version}`,- query,+ query: chartQuery,dataNodeCollectionId: `report-metrics-${reportId}`,autoLoad: true,}const { response, responseError, responseLoading } = useValues(dataNodeLogic(props))- const points = reportMetricSeriesPoints(response)+ const responsePoints = reportMetricSeriesPoints(response)+ const points =+ responsePoints && monitoring ? monitoringChartPoints(responsePoints, observedAt, timezone) : responsePointsconst aggregateQuery = asReportMetricAggregateQuery(metric.query)const aggregateProps: DataNodeLogicProps = {key: `FollowUpCheckTotal.${reportId}.${metric.metric_id}.${version}`,query: aggregateQuery?.source ?? query,dataNodeCollectionId: `report-metrics-${reportId}`,- autoLoad: goalGrain === 'whole_window' && aggregateQuery !== null,+ autoLoad: !monitoring && goalGrain === 'whole_window' && aggregateQuery !== null,}const {response: aggregateResponse,@@ -73,10 +90,25 @@ export function ReportCheckMetricChart({metric={metric}points={points}type={reportMetricChartType(metric)}- interval={query.interval}- goalValue={goalGrain === 'per_interval' ? (goal ?? undefined) : undefined}+ interval={chartQuery.interval}+ markers={+ monitoring ? monitoringChartMarkers(points.labels, monitoring, observedAt, timezone) : undefined+ }+ goalLines={+ monitoring+ ? monitoringChartTargetLines({+ metric,+ monitoring,+ interval: chartQuery.interval,+ labels: points.labels,+ timezone,+ bounds: goalBounds,+ })+ : undefined+ }+ goalValue={!monitoring && goalGrain === 'per_interval' ? (goal ?? undefined) : undefined}/>- {goalGrain === 'whole_window' && targets.length > 0 && (+ {!monitoring && goalGrain === 'whole_window' && targets.length > 0 && (<div className="text-xs text-secondary"><div className="mb-1 flex justify-between"><span>diff --git a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.stories.tsx b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.stories.tsxindex cff0c5fbc9b2..c0731af5bc0d 100644--- a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.stories.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.stories.tsx@@ -4,7 +4,11 @@ import { FEATURE_FLAGS } from 'lib/constants'import { mswDecorator } from '~/mocks/browser'-import type { SignalReportCheckApi } from 'products/signals/frontend/generated/api.schemas'+import type {+ MetricThresholdConfigApi,+ MonitoringMetricConfigApi,+ SignalReportCheckApi,+} from 'products/signals/frontend/generated/api.schemas'import { makeReport } from '../../__mocks__/inboxMocks'import { reportMetricQueryHandler, reportMetricsFixture } from '../../__mocks__/reportMetricMocks'@@ -42,13 +46,72 @@ const check: SignalReportCheckApi = {updated_at: '2026-08-29T00:00:00Z',}+const monitoringDefinition: MonitoringMetricConfigApi = {+ reference_period_minutes: 10080,+ threshold_scaling: 'linear',+ baseline_period_minutes: 20160,+}+const monitoringConfig: MetricThresholdConfigApi = {+ ...check.config,+ metric_kind: 'occurrences',+ value_format: 'count',+ unit: 'errors',+ comparison: { operator: 'lte', value: 70 },+ baseline_value: 280,+ query: {+ kind: 'InsightVizNode',+ source: {+ kind: 'TrendsQuery',+ dateRange: { date_from: '-7d', explicitDate: true },+ series: [{ kind: 'EventsNode', event: 'checkout_failed', math: 'total' }],+ },+ },+ monitoring: monitoringDefinition,+}+const monitoringCheck: SignalReportCheckApi = {+ ...check,+ title: 'Checkout errors stay low',+ config: monitoringConfig,+}+const flagOffCheck: SignalReportCheckApi = {+ ...monitoringCheck,+ config: { ...monitoringConfig, monitoring: undefined },+}+const fixedTargetCheck: SignalReportCheckApi = {+ ...monitoringCheck,+ config: { ...monitoringConfig, monitoring: { ...monitoringDefinition, threshold_scaling: 'fixed' } },+}+const rateTargetCheck: SignalReportCheckApi = {+ ...fixedTargetCheck,+ title: 'Checkout conversion recovers',+ config: {+ ...fixedTargetCheck.config,+ metric_kind: 'conversion_rate',+ value_format: 'percentage_scaled',+ unit: null,+ comparison: { operator: 'gte', value: 0.4 },+ baseline_value: 0.34,+ query: reportMetricsFixture[2].query as Record<string, unknown>,+ },+}+const failedCheck: SignalReportCheckApi = {+ ...check,+ status: 'failed',+ last_run_at: '2026-08-29T00:00:00Z',+ last_outcome: 'failed',+}+const rangeCheck: SignalReportCheckApi = {+ ...check,+ config: { ...check.config, comparison: { operator: 'between', bounds: { lower: 50, upper: 100 } } },+}+const meta: Meta<typeof ReportExpectedImpact> = {title: 'Scenes-App/Inbox/Detail/Expected impact',component: ReportExpectedImpact,parameters: {layout: 'centered',viewMode: 'story',- mockDate: '2026-08-29',+ mockDate: '2026-08-29T12:00:00Z',featureFlags: [FEATURE_FLAGS.SIGNALS_REPORT_CHECKS_REPLACE],},args: { report, reportUrl: 'https://example.com/report' },@@ -61,27 +124,7 @@ const meta: Meta<typeof ReportExpectedImpact> = {'/api/projects/:id/signals/reports/:reportId/checks/': context.parameters.loadFailure? [500, {}]: {- results: [- context.parameters.failed- ? {- ...check,- status: 'failed',- last_run_at: '2026-08-29T00:00:00Z',- last_outcome: 'failed',- }- : context.parameters.rangeGoal- ? {- ...check,- config: {- ...check.config,- comparison: {- operator: 'between',- bounds: { lower: 50, upper: 100 },- },- },- }- : check,- ],+ results: [context.parameters.check ?? check],},'/api/projects/:id/signals/reports/available_reviewers/': [],},@@ -107,12 +150,52 @@ const meta: Meta<typeof ReportExpectedImpact> = {export default metatype Story = StoryObj<typeof ReportExpectedImpact>+export const MonitoringDefinitionFlagOff: Story = {+ parameters: {+ check: flagOffCheck,+ featureFlags: { [FEATURE_FLAGS.SIGNALS_REPORT_CHECKS_REPLACE]: true, 'signals-report-monitoring': false },+ },+}++export const MonitoringDefinition: Story = {+ args: { report: { ...report, monitoring_started_at: '2026-08-27T12:00:00Z' } },+ parameters: {+ check: monitoringCheck,+ featureFlags: [FEATURE_FLAGS.SIGNALS_REPORT_CHECKS_REPLACE, 'signals-report-monitoring'],+ },+}++export const MonitoringDefinitionNarrow: Story = {+ args: MonitoringDefinition.args,+ parameters: {+ check: monitoringCheck,+ narrow: true,+ featureFlags: [FEATURE_FLAGS.SIGNALS_REPORT_CHECKS_REPLACE, 'signals-report-monitoring'],+ },+}++export const MonitoringFixedTarget: Story = {+ args: MonitoringDefinition.args,+ parameters: {+ check: fixedTargetCheck,+ featureFlags: [FEATURE_FLAGS.SIGNALS_REPORT_CHECKS_REPLACE, 'signals-report-monitoring'],+ },+}+export const MetricCheck: Story = {}-export const RangeGoal: Story = { parameters: { rangeGoal: true } }+export const RangeGoal: Story = { parameters: { check: rangeCheck } }export const Narrow: Story = { parameters: { narrow: true } }-export const Failed: Story = { parameters: { failed: true } }+export const Failed: Story = { parameters: { check: failedCheck } }export const LoadFailure: Story = { parameters: { loadFailure: true } }export const ReplacementUnavailable: Story = {parameters: { featureFlags: { [FEATURE_FLAGS.SIGNALS_REPORT_CHECKS_REPLACE]: false } },}++export const MonitoringRateTarget: Story = {+ args: MonitoringDefinition.args,+ parameters: {+ check: rateTargetCheck,+ featureFlags: [FEATURE_FLAGS.SIGNALS_REPORT_CHECKS_REPLACE, 'signals-report-monitoring'],+ },+}diff --git a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.test.tsx b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.test.tsxindex 66fe6560706c..11b370ccc4fc 100644--- a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.test.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.test.tsx@@ -118,6 +118,52 @@ describe('ReportExpectedImpact', () => {render(<ReportExpectedImpact report={report} reportUrl="https://example.com/report-1" />)}+ it.each(['linear', 'fixed'] as const)(+ 'keeps the chart and collapses the %s Monitoring definition',+ async (scaling) => {+ renderMeasurements([+ {+ ...check,+ config: {+ ...check.config,+ metric_kind: 'occurrences',+ value_format: 'count',+ unit: 'errors',+ query: {+ kind: 'InsightVizNode',+ source: {+ kind: 'TrendsQuery',+ dateRange: { date_from: '-7d', explicitDate: true },+ series: [{ kind: 'EventsNode', event: 'checkout_failed', math: 'total' }],+ },+ },+ monitoring: {+ reference_period_minutes: 10080,+ threshold_scaling: scaling,+ baseline_period_minutes: 20160,+ },+ },+ },+ ])+ expect(screen.getByText('Measurement window: since Monitoring starts.')).toBeInTheDocument()+ expect(screen.getByText('Target reference period: 7 days.')).toBeInTheDocument()+ expect(screen.getByText('· Measured over 14 days')).toBeInTheDocument()+ expect(+ screen.getByText(+ scaling === 'linear'+ ? 'The target scales in proportion to elapsed time.'+ : 'The target stays fixed as the measurement period grows.'+ )+ ).toBeInTheDocument()+ expect(screen.getByText('View measurement details').closest('details')).not.toHaveAttribute('open')+ expect(screen.getByText('Target reference period: 7 days.')).not.toBeVisible()+ expect(screen.getByText('Chart')).toBeInTheDocument()+ expect(screen.queryByText(/Goal for the full query window/)).not.toBeInTheDocument()+ await userEvent.setup().click(screen.getByText('View measurement details'))+ expect(screen.getByText('Target reference period: 7 days.')).toBeVisible()+ }+ )+it('uses check goals and excludes investigations and replaced checks', async () => {renderMeasurements([check,diff --git a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.tsx b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.tsxindex 6422defef943..7e1d123933c9 100644--- a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.tsx@@ -11,7 +11,8 @@ import { SignalReport } from '../../types'import { asReportMetricSeriesQuery, formatReportMetricValue } from '../../utils/reportMetrics'import { ReportCheckMetricChart } from './ReportCheckMetricChart'import { ReportCheckMetricSuggestionModal } from './ReportCheckMetricSuggestionModal'-import { buildReportCheckRows, latestCheckExplanations } from './reportCheckPresentation'+import { buildReportCheckRows, latestCheckExplanations, monitoringPeriodLabel } from './reportCheckPresentation'+import { ReportMonitoringDetails } from './ReportMonitoringDetails'const MAX_VISIBLE_MEASUREMENTS = 6@@ -78,7 +79,10 @@ export function ReportExpectedImpact({ report, reportUrl }: { report: SignalReporeturn (<div key={check.id} className="flex flex-col gap-2"><p className="m-0 font-semibold">- {metric.title}: {goal}+ <span>{`${metric.title}: ${goal}`}</span>+ {config.monitoring?.threshold_scaling === 'linear' && (+ <span>{` per ${monitoringPeriodLabel(config.monitoring.reference_period_minutes)}`}</span>+ )}</p><p className="m-0 text-secondary text-sm">{cancellable ? (@@ -86,7 +90,11 @@ export function ReportExpectedImpact({ report, reportUrl }: { report: SignalRepo) : (<LemonTag type={tag.type}>{tag.label}</LemonTag>)}- <span> · Goal for the full query window</span>+ <span>+ {config.monitoring+ ? ' · Monitoring definition'+ : ' · Goal for the full query window'}+ </span></p>{query ? (<ReportCheckMetricChart@@ -98,17 +106,40 @@ export function ReportExpectedImpact({ report, reportUrl }: { report: SignalRepoconfig.comparison.operator === 'between' ? config.comparison.bounds : null}version={check.id}+ monitoring={+ config.monitoring+ ? {+ referencePeriodMinutes: config.monitoring.reference_period_minutes,+ thresholdScaling: config.monitoring.threshold_scaling,+ startedAt: report.monitoring_started_at,+ }+ : undefined+ }/>) : (<p className="text-tertiary m-0">The query is not available to you.</p>)}- {config.baseline_value != null && (- <p className="m-0 text-secondary text-sm">- Baseline:{' '}- {formatReportMetricValue(metric, config.baseline_value) ?? config.baseline_value}- </p>+ {config.monitoring ? (+ <ReportMonitoringDetails+ config={config}+ monitoring={config.monitoring}+ metric={metric}+ waitDescription={+ cancellable && check.soak_minutes != null+ ? `Minimum wait after implementation: ${monitoringPeriodLabel(check.soak_minutes)}.`+ : cancellable+ ? 'The soak and run schedule are separate from this definition.'+ : detail+ }+ />+ ) : (+ <>+ {config.baseline_value != null && (+ <p className="m-0 text-secondary text-sm">{`Baseline: ${formatReportMetricValue(metric, config.baseline_value) ?? config.baseline_value}`}</p>+ )}+ <p className="m-0 text-secondary text-sm">{detail}</p>+ </>)}- <p className="m-0 text-secondary text-sm">{detail}</p>{config.query != null && (<details className="text-sm"><summary className="cursor-pointer">View measurement query</summary>diff --git a/products/signals/frontend/inbox/components/detail/ReportMonitoringDetails.tsx b/products/signals/frontend/inbox/components/detail/ReportMonitoringDetails.tsxnew file mode 100644index 000000000000..e82e002cb5de--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportMonitoringDetails.tsx@@ -0,0 +1,49 @@+import type {+ MetricThresholdConfigApi,+ MonitoringMetricConfigApi,+ ReportMetricApi,+} from 'products/signals/frontend/generated/api.schemas'++import { formatReportMetricValue } from '../../utils/reportMetrics'+import { monitoringPeriodLabel } from './reportCheckPresentation'++export function ReportMonitoringDetails({+ config,+ monitoring,+ metric,+ waitDescription,+}: {+ config: MetricThresholdConfigApi+ monitoring: MonitoringMetricConfigApi+ metric: ReportMetricApi+ waitDescription: string+}): JSX.Element {+ return (+ <details className="text-sm">+ <summary className="cursor-pointer">View measurement details</summary>+ <div className="mt-2 flex flex-col gap-1 text-secondary">+ <p className="m-0">Measurement window: since Monitoring starts.</p>+ <p className="m-0">{`Target reference period: ${monitoringPeriodLabel(monitoring.reference_period_minutes)}.`}</p>+ <p className="m-0">+ {monitoring.threshold_scaling === 'linear'+ ? 'The target scales in proportion to elapsed time.'+ : 'The target stays fixed as the measurement period grows.'}+ </p>+ <p className="m-0">The chart shows surrounding activity. Future dates have no measurements.</p>+ <p className="m-0">+ Target lines show a reference for a full chart interval. Individual buckets do not decide the+ outcome.+ </p>+ {config.baseline_value != null && (+ <p className="m-0">+ <span>{`Baseline: ${formatReportMetricValue(metric, config.baseline_value) ?? config.baseline_value}`}</span>+ {monitoring.baseline_period_minutes != null && (+ <span>{` · Measured over ${monitoringPeriodLabel(monitoring.baseline_period_minutes)}`}</span>+ )}+ </p>+ )}+ <p className="m-0">{waitDescription}</p>+ </div>+ </details>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsx b/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsxindex 07454af15449..961e7a2517da 100644--- a/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsx@@ -2,7 +2,13 @@ import { useValues } from 'kea'import { useMemo } from 'react'import { TimeSeriesBarChart, TimeSeriesLineChart } from '@posthog/quill-charts'-import type { Series, TimeSeriesBarChartConfig, TimeSeriesLineChartConfig } from '@posthog/quill-charts'+import type {+ GoalLineConfig,+ ReferenceLineProps,+ Series,+ TimeSeriesBarChartConfig,+ TimeSeriesLineChartConfig,+} from '@posthog/quill-charts'import { useChartConfig, useChartTheme } from 'lib/charts/hooks'import { teamLogic } from 'scenes/teamLogic'@@ -17,11 +23,13 @@ import {type ReportMetricChartType,type ReportMetricSeriesPoints,} from '../../utils/reportMetrics'+import { ReportChartMarkers } from './ReportChartMarkers'// Only the top is pinned: the sides keep the computed gutter so the first and last date labels fit.// The top gridline sits at the top of the plot, and its tick label is centered on it, so the plot// starts far enough down for the upper half of that label to stay inside the chart box.const BAR_MARGINS = { top: 9 }+const MARKER_MARGINS = { top: 26 }/** Height of the chart. A month of daily buckets needs this much room for the bar heights to* separate and for the date row to stay smaller than the plot. The skeleton that stands in while@@ -43,12 +51,16 @@ export function ReportObservationChart({type,interval,goalValue,+ goalLines,+ markers,}: {metric: ReportMetricApipoints: ReportMetricSeriesPointstype: ReportMetricChartTypeinterval: IntervalType | null | undefinedgoalValue?: number+ goalLines?: GoalLineConfig[]+ markers?: ReferenceLineProps[]}): JSX.Element {const theme = useChartTheme()const { timezone } = useValues(teamLogic)@@ -75,29 +87,30 @@ export function ReportObservationChart({const lineConfig = useChartConfig<TimeSeriesLineChartConfig>(() => ({xAxis,- goalLines: goalValue === undefined ? undefined : [{ value: goalValue, label: 'Goal' }],+ margins: markers?.length ? MARKER_MARGINS : undefined,+ goalLines: goalLines ?? (goalValue === undefined ? undefined : [{ value: goalValue, label: 'Goal' }]),// Rates and durations emphasize change, so the value axis floats to the observed range.yAxis: { startAtZero: false, tickFormatter: yAxisValueFormatter },...AXIS_CHROME,showCrosshair: true,tooltip: { pinnable: false, valueFormatter },}),- [xAxis, yAxisValueFormatter, valueFormatter, goalValue]+ [xAxis, yAxisValueFormatter, valueFormatter, goalValue, goalLines, markers?.length])const barConfig = useChartConfig<TimeSeriesBarChartConfig>(() => ({xAxis,- goalLines: goalValue === undefined ? undefined : [{ value: goalValue, label: 'Goal' }],+ goalLines: goalLines ?? (goalValue === undefined ? undefined : [{ value: goalValue, label: 'Goal' }]),yAxis: { tickFormatter: yAxisValueFormatter },...AXIS_CHROME,showCrosshair: false,barCornerRadius: 1,bandPadding: 0.25,minBarSize: 2,- margins: BAR_MARGINS,+ margins: markers?.length ? MARKER_MARGINS : BAR_MARGINS,tooltip: { pinnable: false, hitArea: 'band', valueFormatter },}),- [xAxis, yAxisValueFormatter, valueFormatter, goalValue]+ [xAxis, yAxisValueFormatter, valueFormatter, goalValue, goalLines, markers?.length])return (@@ -107,9 +120,13 @@ export function ReportObservationChart({data-chart-type={type}>{type === 'bar' ? (- <TimeSeriesBarChart series={series} labels={points.labels} theme={theme} config={barConfig} />+ <TimeSeriesBarChart series={series} labels={points.labels} theme={theme} config={barConfig}>+ {markers && <ReportChartMarkers markers={markers} />}+ </TimeSeriesBarChart>) : (- <TimeSeriesLineChart series={series} labels={points.labels} theme={theme} config={lineConfig} />+ <TimeSeriesLineChart series={series} labels={points.labels} theme={theme} config={lineConfig}>+ {markers && <ReportChartMarkers markers={markers} />}+ </TimeSeriesLineChart>)}</div>)diff --git a/products/signals/frontend/inbox/components/detail/reportCheckPresentation.test.ts b/products/signals/frontend/inbox/components/detail/reportCheckPresentation.test.tsindex 303fc7210a71..af99917b37f8 100644--- a/products/signals/frontend/inbox/components/detail/reportCheckPresentation.test.ts+++ b/products/signals/frontend/inbox/components/detail/reportCheckPresentation.test.ts@@ -9,6 +9,7 @@ import {checkExpiredEntry,checkScheduledEntry,latestCheckExplanations,+ monitoringPeriodLabel,reportChecksMeta,splitReportCheckRows,} from './reportCheckPresentation'@@ -49,6 +50,16 @@ function rowFor(}describe('reportCheckPresentation', () => {+ it.each([+ [0, '0 minutes'],+ [1, '1 minute'],+ [1441, '1 day 1 minute'],+ [1501, '1 day 1 hour 1 minute'],+ [20160, '14 days'],+ ])('preserves the full Monitoring period of %s minutes', (minutes, label) => {+ expect(monitoringPeriodLabel(Number(minutes))).toBe(label)+ })+describe('buildReportCheckRows', () => {// The section exists so a reader can tell a scheduled check from a waiting one from a check// that never ran. A wrong mapping here puts the wrong verdict word on the row.diff --git a/products/signals/frontend/inbox/components/detail/reportCheckPresentation.ts b/products/signals/frontend/inbox/components/detail/reportCheckPresentation.tsindex 4c8f5ba8fe9b..363b8922e009 100644--- a/products/signals/frontend/inbox/components/detail/reportCheckPresentation.ts+++ b/products/signals/frontend/inbox/components/detail/reportCheckPresentation.ts@@ -49,6 +49,20 @@ export function inconclusiveReasonLabel(reason: string | null | undefined): stri)}+export function monitoringPeriodLabel(minutes: number): string {+ if (minutes === 0) {+ return '0 minutes'+ }+ return [+ [Math.floor(minutes / 1440), 'day'],+ [Math.floor((minutes % 1440) / 60), 'hour'],+ [minutes % 60, 'minute'],+ ]+ .filter(([value]) => Number(value) > 0)+ .map(([value, unit]) => `${value} ${unit}${value === 1 ? '' : 's'}`)+ .join(' ')+}+/** A soak window in the words the copy needs: "7 days", "1 day 12 hours", "2 hours", "45 minutes". */function soakLabel(minutes: number): string {const plural = (n: number, unit: string): string => `${n} ${n === 1 ? unit : `${unit}s`}`diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex d44355df048c..1e4c15fd1027 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -1,6 +1,7 @@import type { UserBasicType } from '~/types'import {+ type SignalReportApi,type ReportChartApi,type ReportMetricApi,type ReportRankingApi,@@ -85,7 +86,7 @@ export const ACTIONABLE_ACTIONABILITY_VALUES: SignalReportActionability[] = ['requires_human_input',]-export interface SignalReport {+export interface SignalReport extends Pick<SignalReportApi, 'monitoring_started_at'> {pull_requests?: readonly SignalReportPullRequestApi[]assignee?: SignalReportAssigneeApi | nullid: stringdiff --git a/products/signals/frontend/inbox/utils/reportMonitoringChart.test.ts b/products/signals/frontend/inbox/utils/reportMonitoringChart.test.tsnew file mode 100644index 000000000000..fbbf229c3069--- /dev/null+++ b/products/signals/frontend/inbox/utils/reportMonitoringChart.test.ts@@ -0,0 +1,231 @@+import { NodeKind, type TrendsQuery } from '~/queries/schema/schema-general'++import { reportMetricsFixture } from '../__mocks__/reportMetricMocks'+import {+ monitoringChartMarkers,+ monitoringChartPoints,+ monitoringChartQuery,+ monitoringChartTargetLines,+} from './reportMonitoringChart'++const now = Date.parse('2026-08-29T12:00:00Z')+const query: TrendsQuery = {+ kind: NodeKind.TrendsQuery,+ dateRange: { date_from: '-7d' },+ series: [{ kind: NodeKind.EventsNode, event: 'checkout_failed', properties: [] }],+}++describe('Monitoring chart context', () => {+ it.each([+ [undefined, '2026-08-22T12:00:00.000Z', '2026-09-05T12:00:00.000Z'],+ ['2026-08-27T12:00:00Z', '2026-08-20T12:00:00.000Z', '2026-09-03T12:00:00.000Z'],+ ['2026-08-01T12:00:00Z', '2026-07-25T12:00:00.000Z', '2026-08-29T12:00:00.000Z'],+ ])('shows surrounding activity from %s through now or the future window', (startedAt, from, to) => {+ const result = monitoringChartQuery(query, { referencePeriodMinutes: 10080, startedAt }, now)+ expect(result.dateRange).toEqual({ date_from: from, date_to: to, explicitDate: true })+ expect(result.series).toEqual(query.series)+ expect(query.dateRange).toEqual({ date_from: '-7d' })+ })++ it.each([+ [30, 'minute'],+ [1440, 'hour'],+ [10080, 'day'],+ ] as const)('uses visible buckets for a %s minute reference period', (minutes, interval) => {+ expect(monitoringChartQuery(query, { referencePeriodMinutes: minutes }, now).interval).toBe(interval)+ })++ it('preserves weekday filtering when replacing the query boundaries', () => {+ const filtered: TrendsQuery = { ...query, dateRange: { ...query.dateRange, daysOfWeek: [1, 2, 3, 4, 5] } }+ const result = monitoringChartQuery(filtered, { referencePeriodMinutes: 10080 }, now)+ expect(result.dateRange).toEqual({+ date_from: '2026-08-22T12:00:00.000Z',+ date_to: '2026-09-05T12:00:00.000Z',+ daysOfWeek: [1, 2, 3, 4, 5],+ explicitDate: true,+ })+ expect(filtered.dateRange?.date_from).toBe('-7d')+ })++ it.each([undefined, '2026-08-01T12:00:00.123Z'])(+ 'reuses query boundaries within a refresh minute for a start of %s',+ (startedAt) => {+ const monitoring = { referencePeriodMinutes: 30, startedAt }+ const first = monitoringChartQuery(query, monitoring, now + 100)+ expect(monitoringChartQuery(query, monitoring, now + 59000)).toEqual(first)+ expect(monitoringChartQuery(query, monitoring, now + 60000).dateRange).not.toEqual(first.dateRange)+ if (startedAt) {+ expect(first.dateRange?.date_from).toBe('2026-08-01T11:30:00.123Z')+ }+ }+ )++ it.each([+ [30, '2026-07-30T12:00:00Z', 'day', 1440],+ [1440, '2026-08-20T12:00:00Z', 'day', 1440],+ [527040, undefined, 'day', 1440],+ [30, '2020-01-01T12:00:00Z', 'week', 10080],+ [30, '2000-01-01T12:00:00Z', 'month', 40320],+ ] as const)(+ 'bounds the full displayed range for a %s minute reference starting %s',+ (minutes, startedAt, interval, bucketMinutes) => {+ const result = monitoringChartQuery(query, { referencePeriodMinutes: minutes, startedAt }, now)+ expect(result.interval).toBe(interval)+ const from = Date.parse(result.dateRange!.date_from!)+ const to = Date.parse(result.dateRange!.date_to!)+ expect(Math.ceil((to - from) / (bucketMinutes * 60000)) + 2).toBeLessThanOrEqual(1000)+ }+ )++ it('keeps observed zeros and masks future buckets instead of implying success', () => {+ const points = { labels: ['2026-08-28', '2026-08-29', '2026-08-30'], values: [0, 3, 0] }+ expect(monitoringChartPoints(points, now, 'UTC')).toEqual({ labels: points.labels, values: [0, 3, NaN] })+ expect(points.values).toEqual([0, 3, 0])+ })++ it.each([+ ['America/Los_Angeles', ['2026-08-28', '2026-08-29'], '2026-08-29T06:30:00Z'],+ ['America/Los_Angeles', ['2026-08-28 23:00:00', '2026-08-29 00:00:00'], '2026-08-29T06:30:00Z'],+ ['Asia/Tokyo', ['2026-08-29', '2026-08-30'], '2026-08-29T14:30:00Z'],+ ['America/Los_Angeles', ['2026-08-29T06:00:00Z', '2026-08-29T07:00:00Z'], '2026-08-29T06:30:00Z'],+ ])('interprets buckets in %s when hiding future activity and marking now', (timezone, labels, observedAt) => {+ const at = Date.parse(observedAt)+ expect(monitoringChartPoints({ labels, values: [0, 0] }, at, timezone).values).toEqual([0, NaN])+ expect(monitoringChartMarkers(labels, { referencePeriodMinutes: 1440 }, at, timezone)[0].value).toBe(labels[0])+ })++ it.each([+ [undefined, ['Now']],+ ['2026-08-27T12:00:00Z', ['Monitoring start', 'Now']],+ ['2026-08-29T10:00:00Z', ['Monitoring start / now']],+ ])('marks the observation boundaries for %s', (startedAt, labels) => {+ const buckets = ['2026-08-27', '2026-08-28', '2026-08-29', '2026-08-30']+ const markers = monitoringChartMarkers(buckets, { referencePeriodMinutes: 10080, startedAt }, now, 'UTC')+ expect(markers.map((marker) => marker.label)).toEqual(labels)+ expect(markers.at(-1)?.value).toBe('2026-08-29')+ if (markers.length === 2) {+ expect(markers[0].value).toBe('2026-08-27')+ }+ })+ const targetMetric = {+ ...reportMetricsFixture[1],+ goal_value: 70,+ goal_direction: 'at_most' as const,+ query: {+ kind: NodeKind.InsightVizNode,+ source: { ...query, series: [{ kind: NodeKind.EventsNode, event: 'checkout_failed', math: 'total' }] },+ },+ }+ const targetOptions = {+ metric: targetMetric,+ monitoring: { referencePeriodMinutes: 10080, thresholdScaling: 'linear' as const },+ interval: 'day' as const,+ labels: ['2026-08-27', '2026-08-28', '2026-08-29'],+ timezone: 'UTC',+ }++ it.each([+ [10080, 'day', 70, 10, 'Goal: ≤10/day'],+ [1440, 'hour', 24, 1, 'Goal: ≤1/hour'],+ [60, 'minute', 30, 0.5, 'Goal: ≤0.5/minute'],+ ] as const)('normalizes a %s minute additive target to full %s buckets', (period, interval, goal, value, label) => {+ expect(+ monitoringChartTargetLines({+ ...targetOptions,+ metric: { ...targetMetric, goal_value: goal },+ monitoring: { ...targetOptions.monitoring, referencePeriodMinutes: period },+ interval,+ })+ ).toEqual([expect.objectContaining({ value, label })])+ })++ it('draws both inclusive bounds in the chart bucket units', () => {+ expect(monitoringChartTargetLines({ ...targetOptions, bounds: { lower: 70, upper: 140 } })).toEqual([+ expect.objectContaining({ value: 10, label: 'Goal: ≥10/day' }),+ expect.objectContaining({ value: 20, label: 'Goal: ≤20/day' }),+ ])+ })++ it.each([+ ['avg', 'fixed', true, 'amount', undefined],+ ['p95', 'fixed', true, 'amount', undefined],+ ['total', 'fixed', false, undefined, undefined],+ ['sum', 'fixed', false, 'amount', undefined],+ ['dau', 'fixed', false, undefined, undefined],+ ['hogql', 'fixed', false, undefined, undefined],+ ['avg', 'linear', false, 'amount', undefined],+ [null, 'linear', true, undefined, undefined],+ ['sum', 'linear', true, 'amount', undefined],+ ['sum', 'linear', false, '$session_duration', undefined],+ ['sum', 'linear', false, '$pageview_count', 'session_properties'],+ ] as const)(+ 'matches %s aggregation to a %s reference (visible=%s, property=%s, type=%s)',+ (math, thresholdScaling, visible, mathProperty, mathPropertyType) => {+ const result = monitoringChartTargetLines({+ ...targetOptions,+ monitoring: { ...targetOptions.monitoring, thresholdScaling },+ metric: {+ ...targetMetric,+ kind: 'custom',+ value_format: 'number',+ query: {+ kind: NodeKind.InsightVizNode,+ source: {+ ...query,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: 'checkout_failed',+ math,+ math_property: mathProperty,+ math_property_type: mathPropertyType,+ },+ ],+ },+ },+ },+ })+ expect(result).toHaveLength(visible ? 1 : 0)+ if (visible) {+ expect(result[0].value).toBe(thresholdScaling === 'linear' ? 10 : 70)+ }+ }+ )++ it('keeps a fixed percentage target on the rate scale without inferring it from formatting', () => {+ const metric = { ...reportMetricsFixture[2], goal_value: 0.4, goal_direction: 'at_least' as const }+ const options = {+ ...targetOptions,+ metric,+ monitoring: { ...targetOptions.monitoring, thresholdScaling: 'fixed' as const },+ }+ expect(monitoringChartTargetLines(options)).toEqual([+ expect.objectContaining({ value: 0.4, label: 'Target: ≥40%' }),+ ])+ expect(monitoringChartTargetLines({ ...options, metric: { ...metric, kind: 'custom' } })).toEqual([])+ })++ it('omits a horizontal count reference when daylight-saving days have unequal durations', () => {+ const options = { ...targetOptions, labels: ['2026-11-01', '2026-11-02'] }+ expect(monitoringChartTargetLines({ ...options, timezone: 'America/Los_Angeles' })).toEqual([])+ expect(monitoringChartTargetLines(options)[0].value).toBe(10)+ })++ it('does not present a formula count or a missing definition as a bucket target', () => {+ expect(monitoringChartTargetLines({ ...targetOptions, monitoring: { referencePeriodMinutes: 10080 } })).toEqual(+ []+ )+ expect(+ monitoringChartTargetLines({+ ...targetOptions,+ metric: {+ ...targetMetric,+ query: {+ kind: NodeKind.InsightVizNode,+ source: { ...query, trendsFilter: { formula: 'A * 2' } },+ },+ },+ })+ ).toEqual([])+ })+})diff --git a/products/signals/frontend/inbox/utils/reportMonitoringChart.ts b/products/signals/frontend/inbox/utils/reportMonitoringChart.tsnew file mode 100644index 000000000000..f3060074b643--- /dev/null+++ b/products/signals/frontend/inbox/utils/reportMonitoringChart.ts@@ -0,0 +1,263 @@+import type { GoalLineConfig, ReferenceLineProps } from '@posthog/quill-charts'++import { dayjs } from 'lib/dayjs'++import type { TrendsQuery } from '~/queries/schema/schema-general'+import { PropertyMathType } from '~/types'++import type { MonitoringMetricConfigApi, ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'++import { asReportMetricTrendsQuery, formatReportMetricParts, type ReportMetricSeriesPoints } from './reportMetrics'++export interface ReportMonitoringChartWindow {+ referencePeriodMinutes: number+ thresholdScaling?: MonitoringMetricConfigApi['threshold_scaling']+ startedAt?: string | null+}++const MINUTE_MS = 60_000+const MAX_CHART_POINTS = 1000++function monitoringChartDateRange(monitoring: ReportMonitoringChartWindow, now: number): { from: number; to: number } {+ const startedAt = monitoring.startedAt ? Date.parse(monitoring.startedAt) : NaN+ // Stable dynamic boundaries let repeated views share query-cache entries.+ const refreshedAt = Math.floor(now / MINUTE_MS) * MINUTE_MS+ const anchor = Number.isFinite(startedAt) ? startedAt : refreshedAt+ const windowMs = monitoring.referencePeriodMinutes * MINUTE_MS+ return { from: anchor - windowMs, to: Math.max(anchor + windowMs, refreshedAt) }+}++function monitoringChartInterval(from: number, to: number): NonNullable<TrendsQuery['interval']> {+ const minutes = (to - from) / MINUTE_MS+ if (minutes <= 120) {+ return 'minute'+ }+ if (minutes <= 2880) {+ return 'hour'+ }+ // Use the shortest calendar buckets, including DST, and allow for partial edge buckets.+ const intervals = [+ ['day', 23 * 60],+ ['week', (7 * 24 - 1) * 60],+ ['month', (28 * 24 - 1) * 60],+ ['year', (365 * 24 - 1) * 60],+ ] as const+ const interval = intervals.find(([, bucketMinutes]) => Math.ceil(minutes / bucketMinutes) + 2 <= MAX_CHART_POINTS)+ if (!interval) {+ throw new Error('The Monitoring chart window exceeds the chart point budget.')+ }+ return interval[0]+}++export function monitoringChartQuery(+ query: TrendsQuery,+ monitoring: ReportMonitoringChartWindow,+ now: number+): TrendsQuery {+ const { from, to } = monitoringChartDateRange(monitoring, now)+ return {+ ...query,+ dateRange: {+ ...query.dateRange,+ date_from: new Date(from).toISOString(),+ date_to: new Date(to).toISOString(),+ explicitDate: true,+ },+ compareFilter: undefined,+ interval: monitoringChartInterval(from, to),+ }+}++function bucketTimestamp(label: string, timezone: string): number {+ return /(?:Z|[+-]\d{2}:\d{2})$/i.test(label) ? dayjs(label).valueOf() : dayjs.tz(label, timezone).valueOf()+}++export function monitoringChartPoints(+ points: ReportMetricSeriesPoints,+ now: number,+ timezone: string+): ReportMetricSeriesPoints {+ return {+ labels: points.labels,+ // Trends fills future buckets with zero; they are unobserved rather than successful checks.+ values: points.values.map((value, index) =>+ bucketTimestamp(points.labels[index], timezone) > now ? NaN : value+ ),+ }+}++export function monitoringChartMarkers(+ labels: string[],+ monitoring: ReportMonitoringChartWindow,+ now: number,+ timezone: string+): ReferenceLineProps[] {+ const bucketFor = (at: number): string | undefined => {+ const dates = labels.map((label) => bucketTimestamp(label, timezone))+ if (!dates.length || at < dates[0]) {+ return undefined+ }+ return labels[dates.findLastIndex((date) => date <= at)]+ }+ const start = monitoring.startedAt ? bucketFor(Date.parse(monitoring.startedAt)) : undefined+ const current = bucketFor(now)+ if (start && start !== current) {+ return [+ {+ value: start,+ orientation: 'vertical',+ variant: 'marker',+ label: 'Monitoring start',+ labelPosition: 'start',+ style: { color: 'var(--text-secondary)' },+ },+ ...(current+ ? [+ {+ value: current,+ orientation: 'vertical' as const,+ variant: 'marker' as const,+ label: 'Now',+ style: { color: 'var(--text-secondary)', stroke: 'dashed' as const },+ },+ ]+ : []),+ ]+ }+ return current+ ? [+ {+ value: current,+ orientation: 'vertical',+ variant: 'marker',+ label: start ? 'Monitoring start / now' : 'Now',+ labelPosition: 'start',+ style: { color: 'var(--text-secondary)' },+ },+ ]+ : []+}++const LEVEL_MATHS: Set<string> = new Set([+ PropertyMathType.Average,+ PropertyMathType.Minimum,+ PropertyMathType.Maximum,+ PropertyMathType.Median,+ PropertyMathType.P75,+ PropertyMathType.P90,+ PropertyMathType.P95,+ PropertyMathType.P99,+])++function uniformBucketMinutes(labels: string[], interval: TrendsQuery['interval'], timezone: string): number | null {+ if (interval === 'minute') {+ return 1+ }+ if (interval === 'hour') {+ return 60+ }+ if (interval !== 'day' || !labels.length) {+ return null+ }+ const durations = labels.map((label) => {+ const start = dayjs(bucketTimestamp(label, timezone)).tz(timezone)+ const next = dayjs.tz(start.add(1, 'day').format('YYYY-MM-DD'), timezone)+ return (next.valueOf() - start.valueOf()) / 60_000+ })+ // One horizontal reference cannot represent unequal bucket durations around daylight-saving changes.+ return durations[0] > 0 && durations.every((minutes) => minutes === durations[0]) ? durations[0] : null+}++function singleMetricSeries(source: TrendsQuery): TrendsQuery['series'][number] | null {+ const filter = source.trendsFilter+ const hasFormula = !!(filter?.formula || filter?.formulas?.length || filter?.formulaNodes?.length)+ return source.series.length === 1 && !hasFormula ? source.series[0] : null+}++function isAdditiveMetricSeries(series: TrendsQuery['series'][number]): boolean {+ const math = 'math' in series ? series.math : null+ if (math == null || math === 'total') {+ return true+ }+ // A session can contribute once to each bucket, but only once to the full window.+ return (+ math === 'sum' &&+ !('math_property' in series && series.math_property === '$session_duration') &&+ !('math_property_type' in series && series.math_property_type === 'session_properties')+ )+}++function monitoringTargetFactor(+ metric: ReportMetricApi,+ monitoring: ReportMonitoringChartWindow,+ interval: TrendsQuery['interval'],+ labels: string[],+ timezone: string+): number | null {+ const source = asReportMetricTrendsQuery(metric.query)?.source+ if (!source || !monitoring.thresholdScaling) {+ return null+ }+ const onlySeries = singleMetricSeries(source)+ const math = onlySeries && 'math' in onlySeries ? onlySeries.math : null+ if (monitoring.thresholdScaling === 'fixed') {+ return metric.kind === 'conversion_rate' ||+ metric.kind === 'error_rate' ||+ (onlySeries && typeof math === 'string' && LEVEL_MATHS.has(math))+ ? 1+ : null+ }+ if (!onlySeries || !isAdditiveMetricSeries(onlySeries)) {+ return null+ }+ const minutes = uniformBucketMinutes(labels, interval, timezone)+ return minutes != null && monitoring.referencePeriodMinutes > 0 ? minutes / monitoring.referencePeriodMinutes : null+}++export function monitoringChartTargetLines({+ metric,+ monitoring,+ interval,+ labels,+ timezone,+ bounds,+}: {+ metric: ReportMetricApi+ monitoring: ReportMonitoringChartWindow+ interval: TrendsQuery['interval']+ labels: string[]+ timezone: string+ bounds?: { lower: number; upper: number } | null+}): GoalLineConfig[] {+ const factor = monitoringTargetFactor(metric, monitoring, interval, labels, timezone)+ if (factor == null) {+ return []+ }+ const linear = monitoring.thresholdScaling === 'linear'+ const targets = bounds+ ? [+ { value: bounds.lower, sign: '≥' },+ { value: bounds.upper, sign: '≤' },+ ]+ : metric.goal_value != null+ ? [{ value: metric.goal_value, sign: metric.goal_direction === 'at_most' ? '≤' : '≥' }]+ : []+ return targets.flatMap((target, index) => {+ const value = target.value * factor+ const formatted = formatReportMetricParts(+ { ...metric, value_format: metric.value_format === 'count' ? 'number' : metric.value_format },+ value+ )?.value+ if (!formatted) {+ return []+ }+ return [+ {+ value,+ label: `${linear ? 'Goal' : 'Target'}: ${target.sign}${formatted}${linear ? `/${interval}` : ''}`,+ labelPosition: bounds && index === 0 ? 'start' : 'end',+ showValueOnHover: false,+ },+ ]+ })+}diff --git a/products/signals/skills/authoring-scouts/references/report-checks.md b/products/signals/skills/authoring-scouts/references/report-checks.mdindex 052ee5c28c66..d55781830029 100644--- a/products/signals/skills/authoring-scouts/references/report-checks.md+++ b/products/signals/skills/authoring-scouts/references/report-checks.md@@ -23,6 +23,12 @@ A resolved report often arrives already covered, because the research stage atta## The two kinds+### Monitoring definitions++When the organization's `signals-report-monitoring` rollout is enabled, `config.monitoring` can describe a metric target for observations since Monitoring starts. Supply `reference_period_minutes` for the period the comparison describes and an explicit `threshold_scaling`: `linear` for one additive event count or property sum without a formula, or `fixed` for a target that retains the same bound. Include `baseline_period_minutes` for the actual period measured whenever you supply `baseline_value`. Periods are positive whole minutes, at most 366 days. Do not infer scaling from the display format or invent unknown periods. Omit `monitoring` if these facts are unknown or the rollout is unavailable; the server refuses it while disabled.++For example, a target of at most 70 errors per seven days uses `comparison: {"operator": "lte", "value": 70}` and `monitoring: {"reference_period_minutes": 10080, "threshold_scaling": "linear", "baseline_period_minutes": 20160}` when the supplied baseline measures fourteen days. A percentage target uses `fixed`; its numerical threshold does not shrink with elapsed time. Keep the bounded query and whole-window comparison valid for existing Resolved behavior. This definition adds no Monitoring execution or final decision. The periods do not set the soak, run cadence, expiry, or Monitoring duration.+### `metric_threshold`One bounded query, one comparison, no sandbox and no LLM.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a17756cf6f4c..45074409caa6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26313,6 +26313,27 @@ export namespace Schemas {Agent: 'agent',} as const;+ export type ThresholdScalingEnum = typeof ThresholdScalingEnum[keyof typeof ThresholdScalingEnum];+++ export const ThresholdScalingEnum = {+ Linear: 'linear',+ Fixed: 'fixed',+ } as const;++ export interface MonitoringMetricConfig {+ /**+ * The period the comparison target describes, in minutes. Independent of the soak and run schedule.+ * @maximum 527040+ * @exclusiveMinimum 0+ */+ reference_period_minutes: number;+ /** How the target applies to a measurement from Monitoring start to the observation time. `linear` multiplies the target by elapsed minutes / reference_period_minutes and requires an additive event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. This definition does not enable Monitoring execution. */+ threshold_scaling: ThresholdScalingEnum;+ /** The actual period measured by baseline_value, in minutes. Required when a baseline is supplied. */+ baseline_period_minutes?: number | null;+ }+/*** How to draw this measurement; copied from a referenced metric.*/@@ -26369,6 +26390,8 @@ export namespace Schemas {metric_id?: string | null;/** Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already. */query?: MetricThresholdConfigQuery;+ /** Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks. */+ monitoring?: MonitoringMetricConfig | null;/** What the measured value must satisfy to pass. */comparison: CheckComparison;/** The value observed when the check was written, recorded on each result for context. */diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex ab852d297c8a..03c47a0abe8c 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -752,6 +752,12 @@ export const signalsReportChecksReplaceCreateBodyTitleMax = 200export const signalsReportChecksReplaceCreateBodyRationaleMax = 2000+export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesExclusiveMin = 0+export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesMax = 527040++export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin = 0+export const signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneMax = 527040+export const signalsReportChecksReplaceCreateBodyConfigOneUnitOneMax = 40export const SignalsReportChecksReplaceCreateBody = () => zod.object({@@ -775,6 +781,46 @@ export const SignalsReportChecksReplaceCreateBody = () => zod.object({.describe('Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already.'),+ monitoring: zod+ .union([+ zod.object({+ reference_period_minutes: zod+ .number()+ .gt(+ signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesExclusiveMin+ )+ .max(signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneReferencePeriodMinutesMax)+ .describe(+ 'The period the comparison target describes, in minutes. Independent of the soak and run schedule.'+ ),+ threshold_scaling: zod+ .enum(['linear', 'fixed'])+ .describe(+ 'How the target applies to a measurement from Monitoring start to the observation time. `linear` multiplies the target by elapsed minutes \/ reference_period_minutes and requires an additive event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. This definition does not enable Monitoring execution.'+ ),+ baseline_period_minutes: zod+ .union([+ zod+ .number()+ .gt(+ signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin+ )+ .max(+ signalsReportChecksReplaceCreateBodyConfigOneMonitoringOneBaselinePeriodMinutesOneMax+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'The actual period measured by baseline_value, in minutes. Required when a baseline is supplied.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ "Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks."+ ),comparison: zod.object({operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),@@ -3418,6 +3464,12 @@ export const signalsScoutReportCheckCreateBodyTitleMax = 200export const signalsScoutReportCheckCreateBodyRationaleMax = 2000+export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesExclusiveMin = 0+export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesMax = 527040++export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin = 0+export const signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneMax = 527040+export const signalsScoutReportCheckCreateBodyConfigOneOneUnitOneMax = 40export const signalsScoutReportCheckCreateBodyConfigOneTwoInstructionsMax = 2000@@ -3462,6 +3514,48 @@ export const SignalsScoutReportCheckCreateBody = () => zod.describe('Live InsightVizNode wrapping one TrendsQuery: supplied by the caller, or copied from the named metric when the check is created. `dateRange.date_from` must be a relative window such as `-13d`, and `date_to` must be empty, so the check measures the days before each run rather than the days before it was written. The query must produce exactly one output series: use one event or action series, or combine up to ten of them with exactly one formula. Use no breakdown and no compare mode. A `trendsFilter.display` of `Metric` turns compare mode on, so `metricShowChange` is switched off for you unless `metricSummary` is `latest`, which keeps compare mode off already.'),+ monitoring: zod+ .union([+ zod.object({+ reference_period_minutes: zod+ .number()+ .gt(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesExclusiveMin+ )+ .max(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneReferencePeriodMinutesMax+ )+ .describe(+ 'The period the comparison target describes, in minutes. Independent of the soak and run schedule.'+ ),+ threshold_scaling: zod+ .enum(['linear', 'fixed'])+ .describe(+ 'How the target applies to a measurement from Monitoring start to the observation time. `linear` multiplies the target by elapsed minutes \/ reference_period_minutes and requires an additive event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. This definition does not enable Monitoring execution.'+ ),+ baseline_period_minutes: zod+ .union([+ zod+ .number()+ .gt(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneExclusiveMin+ )+ .max(+ signalsScoutReportCheckCreateBodyConfigOneOneMonitoringOneBaselinePeriodMinutesOneMax+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'The actual period measured by baseline_value, in minutes. Required when a baseline is supplied.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ "Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks."+ ),comparison: zod.object({operator: zod.enum(['lte', 'gte', 'between']).describe('`lte`, `gte`, or `between`.'),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-replace.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-replace.jsonindex 1d4435ede18a..49ae13f30948 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-replace.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-checks-replace.json@@ -90,6 +90,44 @@],"description": "How to draw this measurement; copied from a referenced metric."},+ "monitoring": {+ "anyOf": [+ {+ "properties": {+ "baseline_period_minutes": {+ "anyOf": [+ {+ "exclusiveMinimum": 0,+ "maximum": 527040,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "The actual period measured by baseline_value, in minutes. Required when a baseline is supplied."+ },+ "reference_period_minutes": {+ "description": "The period the comparison target describes, in minutes. Independent of the soak and run schedule.",+ "exclusiveMinimum": 0,+ "maximum": 527040,+ "type": "number"+ },+ "threshold_scaling": {+ "description": "How the target applies to a measurement from Monitoring start to the observation time. `linear` multiplies the target by elapsed minutes / reference_period_minutes and requires an additive event count or property sum. `fixed` keeps the target unchanged, including for rates and averages. This definition does not enable Monitoring execution.",+ "enum": ["linear", "fixed"],+ "type": "string"+ }+ },+ "required": ["reference_period_minutes", "threshold_scaling"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional Monitoring measurement definition, available only with the organization's Monitoring rollout. Measurements cover Monitoring start through the observation time. Omit for existing whole-window checks."+ },"query": {"anyOf": [{