: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): propose expected impact goals behind two flags (#106264)
Mikayla Thompson391733e0d2c5
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex 8c5e2c96dce2..e898c4a90069 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -22,6 +22,10 @@ A `part_of` link written on a step that already closed runs the check as well, bIt continues up a plan of plans, and skips a plan that is waiting on a replacement.It also skips a plan that carries its own open, draft, or unknown PR, because that plan's own work decides its status.+## Proposed impact measurement++The organization authoring flag lets research propose up to six active `impact_measurement_plan` artefacts for measurable outcomes. Each bounded query, goal, aggregation grain, and decision rule lives in an artefact, not in the report's observation metrics. A minimum-data rule also needs an eligibility query for qualifying opportunities. A later research pass reviews the current plans against new evidence. It preserves unchanged plans, appends an unapproved version for a material revision, or appends a retired version when the outcome is no longer relevant or measurable. A plan changed by a person during research takes precedence over that pass. Earlier versions remain for review. The report's "Keep an eye on this for me" action activates current proposals when the display flag is on. Activation appends a new version and does not schedule a check or change the report state. The approval action currently accepts an authenticated person; the artefact schema does not require a person as its approver.+## Repository selectionThe shared repository selection prompt asks the agent to check the sources in the supplied context before choosing a repository.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex aea6c73fbb09..4cfc9d9d0509 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9396,6 +9396,10 @@ snapshots:hash: v1.k794b7964.0516b8985888b92018506cee3a0cf40c7f7499027455fb8f6957853a91440557.heUzrn_iZd5CtI3GTUAKNrrP2zEkv-NEUxo3FnmZKF0scenes-app-inbox-detail--report--light:hash: v1.k794b7964.f42eb359e62e037d7b75d0348f507dea76b69e442f80adc8b54736e0edcd8da5.42xwdpzwUuNAIMlWPnm3StGJdZdEOr-0lSd9-xtvvmc+ scenes-app-inbox-detail--report-expected-impact-pending--dark:+ hash: v1.k794b7964.7c5fdee00eb64783cbd3679b1a4666eb94d32ab3979fc31f6fb49321eb6adf3e.A4KxCJYBUMfJfCY2iDxX5TbLLgYsYJAvx0Aw98oQBPA+ scenes-app-inbox-detail--report-expected-impact-pending--light:+ hash: v1.k794b7964.d387c6c2df5673e7333383d6a5195da3b16c3c573bf12a3e772512813c99afb5.-7i8C-Nl6upJ-B-R5eYDZwNxykXyVHQ7gld3U2YkWKoscenes-app-inbox-detail--report-legacy--dark:hash: v1.k794b7964.92f20f83ec71e560c0bf6e0fb6c42d761f68f76052344957d1368cdd6e38f507.exzESVszbMhsdVWzJgqpeJRQPXbvSqM1KqXLAuApAcQscenes-app-inbox-detail--report-legacy--light:@@ -9408,6 +9412,10 @@ snapshots:hash: v1.k794b7964.0516b8985888b92018506cee3a0cf40c7f7499027455fb8f6957853a91440557.m5kKe7m4ITNuyQyusa72o9rk-dyF5d5QOps4_rNLuRMscenes-app-inbox-detail--report-ready-to-implement--light:hash: v1.k794b7964.f42eb359e62e037d7b75d0348f507dea76b69e442f80adc8b54736e0edcd8da5.CnKeyAMmz5IP5UQXp6G_6mWUR0C0BmaCm5qSIt7egqU+ scenes-app-inbox-detail--report-with-expected-impact--dark:+ hash: v1.k794b7964.0d6ee6cc04852c157327c5a054301e0bd3df9b54adb0fee3cb04d26cc38e7bea.GXTop6CLWbSUnfuVWpA4_mBnbKkyYaeH6W1ZvXUZZZw+ scenes-app-inbox-detail--report-with-expected-impact--light:+ hash: v1.k794b7964.e2937bb44ba3bd9e9091f9a8f82d76acbbd246c6c0824d309e6011fd9a52bb36.F5h6gDd-tFoqYPxcxO1b6R_xI5mCMMh0HTUlsQzt7bUscenes-app-inbox-detail--report-with-metrics--dark:hash: v1.k794b7964.39466f57a704406dd1b049bd496f4fba58090c01b5b7bfeeabebd785ad1585aa.b1spVq_6Mgzx2U5nmSNXeOtXL0X10JZo1wOrbhS35q0scenes-app-inbox-detail--report-with-metrics--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex ffe7555a73ea..56ac3975c933 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -5032,6 +5032,9 @@ const api = {): Promise<SignalReportArtefactResponse> {return await new ApiRequest().signalReport(id).withAction('artefacts').withQueryString(params).get()},+ async activateMeasurement(id: SignalReport['id'], artefactId: string): Promise<void> {+ await new ApiRequest().signalReport(id).withAction(`artefacts/${artefactId}/activate`).create()+ },async delete(id: SignalReport['id']): Promise<void> {await new ApiRequest().signalReport(id).delete()},diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 71de01d722ec..b3a0464b6e7d 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -237,6 +237,7 @@ export const FEATURE_FLAGS = {SETTINGS_SESSION_TABLE_VERSION: 'settings-session-table-version', // owner: #team-analytics-platformSETTINGS_SESSIONS_V2_JOIN: 'settings-sessions-v2-join', // owner: @robbie-c #team-web-analyticsSETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES: 'web-analytics-pre-aggregated-tables', // owner: @lricoy #team-web-analytics+ SIGNALS_EXPECTED_IMPACT_DISPLAY: 'signals-expected-impact', // owner: #team-self-driving, person-level display gate for proposed impact graphs and actionsSIGNALS_PR_REFUNDS: 'signals-pr-refunds', // owner: #team-self-driving, gates the inbox PR refund flow (also checked server-side)SIGNALS_REPORT_METRICS: 'signals-report-metrics', // owner: #team-self-driving, gates the live impact metrics on inbox report rows and the report detail, and the snapshot refresh calls they makeSTARTUP_PROGRAM_INTENT: 'startup-program-intent', // owner: @pawel-cebula #team-billingdiff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 9c77daa408c2..a96b4ae74226 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -1656,18 +1656,24 @@ class _EmptyArrowClient:class TestHogqlTableModifiers:@pytest.mark.parametrize(- "query,team_modifiers,expected_sql",+ "query,team_modifiers,expected_sql,expected_sql_new_events_schema",[- ("SELECT $is_bounce FROM sessions LIMIT 1", {"bounceRateDurationSeconds": 123}, "123"),+ ("SELECT $is_bounce FROM sessions LIMIT 1", {"bounceRateDurationSeconds": 123}, "123", "123"),("SELECT properties.plan FROM events LIMIT 1",{"propertyGroupsMode": "optimized"},"properties_group_custom",+ "events_json AS events",),],)async def test_compiles_the_view_with_the_team_default_modifiers(- self, ateam: Team, query: str, team_modifiers: dict[str, Any], expected_sql: str+ self,+ ateam: Team,+ query: str,+ team_modifiers: dict[str, Any],+ expected_sql: str,+ expected_sql_new_events_schema: str,) -> None:ateam.modifiers = team_modifiersawait database_sync_to_async(ateam.save)()@@ -1690,6 +1696,9 @@ class TestHogqlTableModifiers:):_ = [batch async for batch in hogql_table(query, ateam, LOGGER.bind())]+ expected_sql = (+ expected_sql_new_events_schema if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else expected_sql+ )assert captured_sql is not None and expected_sql in captured_sqlasync def test_compiles_account_dependencies_without_a_user(self, ateam: Team) -> None:diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.pyindex 5d5fd7a738f5..dcafb8c5359e 100644--- a/products/signals/backend/artefact_schemas.py+++ b/products/signals/backend/artefact_schemas.py@@ -1017,9 +1017,60 @@ class CheckCancelled(CheckLifecycleEntry):# ── Type mapping ─────────────────────────────────────────────────────────────────+# Content models that describe the report's current state (latest row of each type wins) vs# entries that record discrete work (accumulate). `SignalFinding` (keyed by signal_id) and# `Dismissal` (stacking) have their own semantics; `VideoSegment` is a legacy plain append.+class ImpactMeasurementPlan(BaseModel):+ """One version of a proposed impact measurement, keyed by metric_id within a report."""++ model_config = ConfigDict(extra="forbid")++ metric_id: str = Field(max_length=100)+ title: str = Field(max_length=200)+ kind: str+ query: dict[str, Any]+ value_format: str = "number"+ unit: str | None = None+ goal_value: float+ goal_direction: Literal["at_most", "at_least"]+ goal_grain: Literal["whole_window", "per_interval"] = "whole_window"+ decision_window_days: int | None = Field(default=None, ge=1, le=30)+ minimum_data_points: int | None = Field(default=None, ge=1, le=1000)+ eligibility_query: dict[str, Any] | None = None+ activated: bool = Field(default=False, strict=True)+ retired: bool = Field(default=False, strict=True)++ @field_validator("goal_value", "decision_window_days", "minimum_data_points", mode="before")+ @classmethod+ def reject_coerced_flags_and_counts(cls, value: object) -> object:+ if isinstance(value, bool):+ raise ValueError("provide a number, not a boolean")+ return value++ @model_validator(mode="after")+ def validate_measurement(self) -> ImpactMeasurementPlan:+ from products.signals.backend.report_metrics import ReportMetric++ validated_metric = ReportMetric.model_validate(+ self.model_dump(exclude={"activated", "retired", "goal_grain", "eligibility_query"})+ )+ self.metric_id = validated_metric.metric_id+ if self.minimum_data_points is not None and self.eligibility_query is None:+ raise ValueError("minimum_data_points requires an eligibility_query for qualifying opportunities")+ if self.eligibility_query is not None:+ ReportMetric.model_validate(+ {+ "metric_id": "eligible",+ "title": "Qualifying opportunities",+ "kind": "occurrences",+ "value_format": "count",+ "query": self.eligibility_query,+ }+ )+ return self++StatusArtefactContent = (SafetyJudgment| ActionabilityAssessment@@ -1051,6 +1102,7 @@ LogArtefactContent = (| CheckCancelled| ImplementationReplacement| ImplementationHandover+ | ImpactMeasurementPlan)ArtefactContent = StatusArtefactContent | LogArtefactContent | SignalFinding | Dismissal | VideoSegment@@ -1088,6 +1140,7 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {"implementation_dispatch": ImplementationDispatch,"implementation_replacement": ImplementationReplacement,"implementation_handover": ImplementationHandover,+ "impact_measurement_plan": ImpactMeasurementPlan,}_ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model in ARTEFACT_CONTENT_SCHEMAS.items()}diff --git a/products/signals/backend/impact_measurement_plans.py b/products/signals/backend/impact_measurement_plans.pynew file mode 100644index 000000000000..ff9b70a4d126--- /dev/null+++ b/products/signals/backend/impact_measurement_plans.py@@ -0,0 +1,128 @@+"""Versioned impact proposals. Execution and check results live outside this definition."""++from __future__ import annotations++from collections.abc import Mapping++import structlog++from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.artefact_schemas import ImpactMeasurementPlan+from products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.report_metrics import MAX_REPORT_METRICS, REPORT_METRIC_GOAL_FIELDS++logger = structlog.get_logger(__name__)+++def latest_measurement_plans(report: SignalReport) -> dict[str, tuple[SignalReportArtefact, ImpactMeasurementPlan]]:+ plans: dict[str, tuple[SignalReportArtefact, ImpactMeasurementPlan]] = {}+ rows = SignalReportArtefact.objects.filter(+ team_id=report.team_id,+ report_id=report.id,+ type=SignalReportArtefact.ArtefactType.IMPACT_MEASUREMENT_PLAN,+ ).order_by("-created_at", "-id")+ for row in rows:+ try:+ plan = ImpactMeasurementPlan.model_validate_json(row.content)+ except ValueError:+ continue+ plans.setdefault(plan.metric_id, (row, plan))+ return plans+++def can_append_measurement_plan(+ existing: Mapping[str, tuple[SignalReportArtefact, ImpactMeasurementPlan]], plan: ImpactMeasurementPlan+) -> bool:+ if plan.retired:+ return True+ current = existing.get(plan.metric_id)+ if current is not None and not current[1].retired:+ return True+ return sum(not current_plan.retired for _, current_plan in existing.values()) < MAX_REPORT_METRICS+++def persist_authored_measurement_plans(+ report: SignalReport,+ metrics: list[dict],+ attribution: ArtefactAttribution,+ *,+ revise_metric_ids: list[str] | None = None,+ retire_metric_ids: list[str] | None = None,+ previous_plan_ids: Mapping[str, str] | None = None,+) -> list[dict]:+ """Move authored goals into immutable plans, appending explicit revisions and retirements."""+ existing = latest_measurement_plans(report)+ revise_ids = set(revise_metric_ids or [])+ retire_ids = set(retire_metric_ids or [])+ ambiguous_ids = revise_ids & retire_ids+ if ambiguous_ids:+ logger.warning("ignoring conflicting impact measurement decisions", report_id=str(report.id))+ clean_metrics = []+ for metric in metrics:+ clean_metrics.append({key: value for key, value in metric.items() if key not in REPORT_METRIC_GOAL_FIELDS})+ if metric.get("goal_value") is None or metric.get("goal_direction") is None:+ continue+ metric_id = metric.get("metric_id")+ if not isinstance(metric_id, str):+ continue+ if metric_id in ambiguous_ids:+ continue+ current = existing.get(metric_id)+ if current is not None:+ if metric_id not in revise_ids:+ continue+ if previous_plan_ids is None or previous_plan_ids.get(metric_id) != str(current[0].id):+ logger.info("skipping stale impact measurement revision", report_id=str(report.id), metric_id=metric_id)+ continue+ try:+ plan = ImpactMeasurementPlan.model_validate(+ {+ **{+ key: metric[key]+ for key in (+ "metric_id",+ "title",+ "kind",+ "query",+ "value_format",+ "unit",+ "goal_value",+ "goal_direction",+ "goal_grain",+ "decision_window_days",+ "minimum_data_points",+ "eligibility_query",+ )+ if key in metric and (key not in {"goal_grain", "eligibility_query"} or metric[key] is not None)+ },+ "activated": False,+ }+ )+ except ValueError:+ logger.warning(+ "ignoring invalid proposed impact measurement", report_id=str(report.id), metric_id=metric_id+ )+ continue+ if current is not None and current[1].model_dump(exclude={"activated"}) == plan.model_dump(+ exclude={"activated"}+ ):+ continue+ if not can_append_measurement_plan(existing, plan):+ logger.warning("impact measurement limit reached", report_id=str(report.id), metric_id=metric_id)+ continue+ row = SignalReportArtefact.add_log(+ team_id=report.team_id, report_id=str(report.id), content=plan, attribution=attribution+ )+ existing[plan.metric_id] = (row, plan)+ for metric_id in retire_ids - ambiguous_ids:+ current = existing.get(metric_id)+ if current is None or current[1].retired:+ continue+ if previous_plan_ids is None or previous_plan_ids.get(metric_id) != str(current[0].id):+ logger.info("skipping stale impact measurement retirement", report_id=str(report.id), metric_id=metric_id)+ continue+ retired = current[1].model_copy(update={"activated": False, "retired": True})+ SignalReportArtefact.add_log(+ team_id=report.team_id, report_id=str(report.id), content=retired, attribution=attribution+ )+ return clean_metricsdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 67fc8865516c..cc00778ffd3f 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1243,6 +1243,7 @@ class SignalReportArtefact(UUIDModel):IMPLEMENTATION_REPLACEMENT = "implementation_replacement"IMPLEMENTATION_HANDOVER = "implementation_handover"RANKING_SCORE = "ranking_score"+ IMPACT_MEASUREMENT_PLAN = "impact_measurement_plan"# Every artefact is an append-only, point-in-time log entry — nothing is mutated in place by# the producers. The two sets below classify *what an entry means*, not how it is written:@@ -1302,6 +1303,7 @@ class SignalReportArtefact(UUIDModel):ArtefactType.CHECK_SCHEDULED,ArtefactType.CHECK_EXPIRED,ArtefactType.CHECK_CANCELLED,+ ArtefactType.IMPACT_MEASUREMENT_PLAN,})@@ -1847,6 +1849,8 @@ class SignalReportArtefact(UUIDModel):Editing the latest `suggested_reviewers` row changes the report's canonical reviewers,so it re-evaluates auto-start the same way appending a new reviewers row does."""+ if self.type == self.ArtefactType.IMPACT_MEASUREMENT_PLAN:+ raise ArtefactContentValidationError("Append a new measurement version instead of editing one.")parsed = parse_artefact_content(self.type, content)# The `task` FK is the association and is creation-time only; an edit must not let# content.task_id drift away from it.diff --git a/products/signals/backend/report_content_gates.py b/products/signals/backend/report_content_gates.pyindex a2c54aee0c4d..643c37e6b67f 100644--- a/products/signals/backend/report_content_gates.py+++ b/products/signals/backend/report_content_gates.py@@ -1,4 +1,4 @@-"""Organization-level rollout gates for report metrics.+"""Organization-level rollout gates for agent-authored report content.The checks live in their own module because they need `Team` and the flag client.Report models and Temporal payloads import `report_metrics.py` during process setup,@@ -20,6 +20,7 @@ from posthog.ph_client import feature_enabled_or_falselogger = structlog.get_logger(__name__)REPORT_METRICS_FLAG = "signals-report-metrics"+EXPECTED_IMPACT_AUTHORING_FLAG = "signals-expected-impact-authoring"def _organization_flag_enabled(flag: str, organization_id: UUID) -> bool:@@ -67,3 +68,7 @@ def organization_report_metrics_enabled(organization_id: UUID) -> bool:def team_report_metrics_enabled(team_id: int) -> bool:return _team_flag_enabled(REPORT_METRICS_FLAG, team_id)+++def team_expected_impact_authoring_enabled(team_id: int) -> bool:+ return _team_flag_enabled(EXPECTED_IMPACT_AUTHORING_FLAG, team_id)diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.mdindex 6fc58f7b9ef9..1b85af491478 100644--- a/products/signals/backend/report_generation/AGENTS.md+++ b/products/signals/backend/report_generation/AGENTS.md@@ -97,7 +97,7 @@ The presentation step can also author up to six typed `metrics` alongside the pr- **Affected people and sessions are distinct.** An `affected_users` metric uses exactly one event or action series with `math: "dau"`. An `affected_sessions` metric uses exactly one event or action series with `math: "unique_session"`. Neither kind uses formulas, group math, breakdowns, or compare mode. Never sum interval buckets.- **One bounded live measurement.** Every metric has a live query built only from event or action sources, rejects breakdown and compare mode, and must produce exactly one output series. Without a formula that means exactly one source. A conversion or rate may combine at most ten event/action sources through exactly one formula output. The longitudinal result is capped at 1,000 estimated interval points, including the current partial bucket.-- **A malformed metric costs the whole report.** `metrics` rides in the same `ReportPresentationOutput` as the title and summary, and `MultiTurnSession._parse_and_validate` calls `model_validate` with no retry, so one rejected item fails the research run with nothing persisted. `_resolve_report_metrics_payload` never sees it, because `metric_batch_error` only checks whole-set rules (count, total query characters, duplicate ids, one primary, one affected-users). This is the same tradeoff as a malformed chart, on a wider surface: `ReportMetric` carries about fifteen field validators plus a cross-field one, against four on `ReportChart`, so a metric has many more ways to fail late. Giving one metric its own degrade path needs a retry or a partial parse in the runner, which is shared with every other multi-turn caller. Until then the `signals-report-metrics` flag bounds who is exposed, and the authoring guidance keeps the surface small by telling the run to omit a metric it cannot measure honestly.+- **A malformed optional goal does not cost the whole report.** Before parsing the presentation, an invalid goal is stripped when the underlying observation metric is still valid; an invalid observation metric still fails the presentation. `_resolve_report_metrics_payload` checks whole-set rules (count, total query characters, duplicate ids, one primary, one affected-users). Research can propose goals only under the separate organization authoring flag. The ready or pending-input transition moves them to versioned `impact_measurement_plan` artefacts and stores goal-free observations in report metrics. On re-research, the agent reviews current plans and explicitly identifies material revisions or retirements; unchanged plans keep their version and approval. A revision appends an unapproved version, and a retirement appends a retired version. A concurrent manual edit takes precedence over the research decision. Activating a plan appends an approved version but does not schedule a check.- **Consumers own the display.** Authored Trends display is not the report presentation contract. Consumers derive `BoldNumber` for the first output series' whole-window `aggregated_value` and `ActionsBar` for longitudinal buckets. Every metric runs through both derived shapes and the normal query cache. The inbox does not maintain a separate time-series table.- **Snapshots are optional fallbacks.** `value` and `value_at` travel together, preserve zero as measured data, and never replace the live query. `value_at` is stored in UTC, whatever offset the author wrote; a measurement time still ahead of the server clock drops the snapshot and keeps the metric, so an unusable timestamp never costs the report. Opening the inbox list or a report refreshes the stale snapshots on screen through the query cache without changing report ordering; there is no background job. Snapshot-only or queryless rows are legacy or malformed and are always redacted.- **Independent opt-in.** Metrics use the organization-level `signals-report-metrics` flag (`report_content_gates.py`, on in DEBUG). Charts do not require a feature flag. When off, pipeline metric guidance and schema fields are removed and the caller preserves existing metrics. Every writer reads the flag, including the scout report channel, which drops a supplied set before the safety judge. Scout-authored metrics are safety-judged with the rest of the report.diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.pyindex 9a10bd48471a..89b931a7cd58 100644--- a/products/signals/backend/report_generation/research.py+++ b/products/signals/backend/report_generation/research.py@@ -16,6 +16,7 @@ from posthog.dataclasses import frozenfrom products.signals.backend.artefact_schemas import (ActionabilityAssessment,ActionabilityChoice,+ ImpactMeasurementPlan,ImplementationAssessment,ImplementationDecision,NoteArtefact,@@ -39,6 +40,7 @@ from products.signals.backend.report_metrics import (MAX_LIVE_METRIC_WINDOW_DAYS,MAX_METRIC_SERIES_POINTS,MAX_REPORT_METRICS,+ REPORT_METRIC_GOAL_FIELDS,ReportMetric,)from products.signals.backend.supersession import NO_IMPLEMENTATION_CONTEXT, ImplementationResearchContext@@ -172,6 +174,8 @@ Hard rules:"EventsNode or ActionsNode sources. Its value/value_at snapshot is an optional cached fallback."),)+ revise_measurement_plan_metric_ids: list[str] = Field(default_factory=list)+ retire_measurement_plan_metric_ids: list[str] = Field(default_factory=list)layers: list[ReportLayer] = Field(default_factory=list,description=(@@ -246,6 +250,44 @@ Hard rules:)return kept+ @field_validator("metrics", mode="before")+ @classmethod+ def clear_goals_that_do_not_validate(cls, v: object) -> object:+ # A goal is an optional proposal on a metric that is otherwise valid. Without this, a bad+ # threshold or a missing decision rule fails the whole presentation step, and the run ends+ # with no report. A metric that validates without its goal keeps its measurement. A metric+ # that fails for any other reason still fails the response.+ if not isinstance(v, list):+ return v+ kept: list[object] = []+ for index, entry in enumerate(v):+ if not isinstance(entry, dict) or all(entry.get(field) is None for field in REPORT_METRIC_GOAL_FIELDS):+ kept.append(entry)+ continue+ if entry.get("minimum_data_points") is not None and entry.get("eligibility_query") is None:+ # A saved plan rejects a minimum-data rule with no opportunities to count. Drop the rule+ # so that a decision window can still carry the goal into a plan.+ entry = {**entry, "minimum_data_points": None}+ logger.warning(+ "presentation: dropped minimum data points without an eligibility query at index %d", index+ )+ try:+ kept.append(ReportMetric.model_validate(entry))+ continue+ except Exception as e:+ reason = _rejection_reason(e)+ try:+ kept.append(+ ReportMetric.model_validate(+ {key: value for key, value in entry.items() if key not in REPORT_METRIC_GOAL_FIELDS}+ )+ )+ except Exception:+ kept.append(entry)+ continue+ logger.warning("presentation: cleared goal on metric at index %d that did not validate (%s)", index, reason)+ return kept+@field_validator("title", "summary")@classmethoddef fields_must_not_be_empty(cls, v: str) -> str:@@ -379,6 +421,8 @@ class ReportResearchOutput(BaseModel):"Every entry has a bounded live EventsNode/ActionsNode Trends query; its snapshot is optional."),)+ revise_measurement_plan_metric_ids: list[str] = Field(default_factory=list)+ retire_measurement_plan_metric_ids: list[str] = Field(default_factory=list)layers: list[ReportLayer] = Field(default_factory=list,description="The plan of dependent pull requests, when research split the work. Each layer becomes "@@ -773,12 +817,47 @@ Put reproducible report-level measurements under `metrics`. A metric tells the r- **At most {MAX_REPORT_METRICS} metrics per report.** Prefer the handful that changes a decision. `metrics` replaces the previous set with the new title and summary, so repeat any still-valid metric on re-research. Snapshot-only or queryless rows are legacy or malformed, are always redacted, and must not be re-sent."""+_EXPECTED_IMPACT_GUIDANCE = """## Proposed impact measurement-def _render_previous_metrics_context(previous_metrics: list[ReportMetric]) -> str:+When the solution has an Expected impact section and the research supports it, give one live metric that directly measures the intended change a `goal_value` and `goal_direction` (`at_most` or `at_least`). Suggest `decision_window_days` (1–30) based on observed traffic. Set `minimum_data_points` (1–1000) only when you can also supply a bounded `eligibility_query`. Count qualifying opportunities, not failures: a zero-failure goal cannot require failures to occur. Prefer a short useful window over waiting for certainty. State the baseline and intended outcome in the Expected impact prose. The goal is a proposal, not a scheduled check or a statistical confidence claim. If the metric cannot observe the intended outcome, or no credible threshold or traffic estimate exists, omit the goal rather than invent one. Keep an existing valid goal on re-research unless evidence changes it.+Choose `goal_grain=per_interval` only when the threshold applies to each chart bucket; otherwise use `whole_window`. The proposal is saved as an impact measurement artefact separate from the report's observation metrics. Do not call it statistically significant without a suitable test.+"""+++def _render_previous_measurement_plans_context(+ previous_plans: dict[str, tuple[str, ImpactMeasurementPlan]],+) -> str:+ if not previous_plans:+ return ""+ rendered = json.dumps(+ [+ {"artefact_id": artefact_id, **plan.model_dump(mode="json")}+ for _, (artefact_id, plan) in sorted(previous_plans.items())+ ],+ indent=2,+ )+ return (+ "## Existing impact measurement plans\n\n"+ "Review each attached plan against the new signals, current code and data, and the Expected impact prose. "+ "Keep a sound plan unchanged: do not list its metric ID in either decision field. "+ "If its measure, goal, or decision window needs a material change, include its metric ID in "+ "`revise_measurement_plan_metric_ids` and return the complete updated observation metric, including "+ "goal fields, in `metrics`. If the outcome is no longer relevant or measurable, include its metric ID "+ "in `retire_measurement_plan_metric_ids`. Do not use both decisions for one plan, and do not treat "+ "an omitted metric as a request to retire its plan. Revisions need fresh human approval. "+ "Keep the Expected impact prose consistent with the plans you keep, revise, or retire.\n\n"+ f"```json\n{rendered}\n```"+ )+++def _render_previous_metrics_context(previous_metrics: list[ReportMetric], *, include_goals: bool = True) -> str:if not previous_metrics:return ""+ excluded_fields = {"comparison"}+ if not include_goals:+ excluded_fields.update(REPORT_METRIC_GOAL_FIELDS)rendered = json.dumps(- [metric.model_dump(mode="json", exclude={"comparison"}) for metric in previous_metrics], indent=2+ [metric.model_dump(mode="json", exclude=excluded_fields) for metric in previous_metrics], indent=2)return ("## Impact metrics this report already shows\n\n"@@ -1108,20 +1187,35 @@ def build_report_presentation_prompt(previous_summary: str | None = None,previous_charts: list[ReportChart] | None = None,previous_metrics: list[ReportMetric] | None = None,+ previous_measurement_plans: dict[str, tuple[str, ImpactMeasurementPlan]] | None = None,metrics_enabled: bool = False,+ expected_impact_authoring_enabled: bool = False,) -> str:schema_dict = ReportPresentationOutput.model_json_schema()if not metrics_enabled:schema_dict.get("properties", {}).pop("metrics", None)schema_dict.get("$defs", {}).pop("ReportMetric", None)schema_dict.get("$defs", {}).pop("ReportMetricComparison", None)+ elif not expected_impact_authoring_enabled:+ metric_properties = schema_dict["$defs"]["ReportMetric"]["properties"]+ for field_name in REPORT_METRIC_GOAL_FIELDS:+ metric_properties.pop(field_name, None)+ if not (expected_impact_authoring_enabled and previous_measurement_plans):+ schema_dict["properties"].pop("revise_measurement_plan_metric_ids", None)+ schema_dict["properties"].pop("retire_measurement_plan_metric_ids", None)schema = json.dumps(schema_dict, indent=2)previous_presentation_context = _render_previous_presentation_context(previous_title, previous_summary)visual_sections: list[str] = []if metrics_enabled:visual_sections.append(_REPORT_METRICS_GUIDANCE)- previous_metrics_context = _render_previous_metrics_context(previous_metrics or [])+ if expected_impact_authoring_enabled:+ visual_sections.append(_EXPECTED_IMPACT_GUIDANCE)+ if previous_measurement_plans:+ visual_sections.append(_render_previous_measurement_plans_context(previous_measurement_plans))+ previous_metrics_context = _render_previous_metrics_context(+ previous_metrics or [], include_goals=expected_impact_authoring_enabled+ )if previous_metrics_context:visual_sections.append(previous_metrics_context)visual_sections.append(_REPORT_CHARTS_GUIDANCE)@@ -1268,6 +1362,7 @@ async def run_multi_turn_research(summary: str | None = None,previous_report_id: str | None = None,previous_report_research: ReportResearchOutput | None = None,+ previous_measurement_plans: dict[str, tuple[str, ImpactMeasurementPlan]] | None = None,branch: str | None = None,verbose: bool = False,output_fn: OutputFn = None,@@ -1277,6 +1372,7 @@ async def run_multi_turn_research(resolved_report_summary: str | None = None,linked_reports: list[LinkedReportContext] | None = None,metrics_enabled: bool = False,+ expected_impact_authoring_enabled: bool = False,agent_checks_enabled: bool = False,steering_section: str = "",implementation_context: ImplementationResearchContext = NO_IMPLEMENTATION_CONTEXT,@@ -1448,7 +1544,9 @@ async def run_multi_turn_research(previous_summary=summary or (previous_report_research.summary if previous_report_research else None),previous_charts=previous_report_research.charts if previous_report_research else None,previous_metrics=previous_report_research.metrics if previous_report_research else None,+ previous_measurement_plans=previous_measurement_plans,metrics_enabled=metrics_enabled,+ expected_impact_authoring_enabled=expected_impact_authoring_enabled,)presentation_result = await session.send_followup(presentation_prompt,@@ -1548,6 +1646,12 @@ async def run_multi_turn_research(summary=presentation_result.summary,charts=presentation_result.charts,metrics=presentation_result.metrics if metrics_enabled else [],+ revise_measurement_plan_metric_ids=(+ presentation_result.revise_measurement_plan_metric_ids if previous_measurement_plans else []+ ),+ retire_measurement_plan_metric_ids=(+ presentation_result.retire_measurement_plan_metric_ids if previous_measurement_plans else []+ ),layers=presentation_result.layers,research_task_id=str(session.task.id),verification_note=verification_note,diff --git a/products/signals/backend/report_metrics.py b/products/signals/backend/report_metrics.pyindex 03ca329bb2c2..35ff4ccd7ee6 100644--- a/products/signals/backend/report_metrics.py+++ b/products/signals/backend/report_metrics.py@@ -358,6 +358,16 @@ class ReportMetricComparison(BaseModel):return normalized+REPORT_METRIC_GOAL_FIELDS = (+ "goal_value",+ "goal_direction",+ "goal_grain",+ "decision_window_days",+ "minimum_data_points",+ "eligibility_query",+)++class ReportMetric(BaseModel):"""One impact measurement backed by a bounded live Trends query.@@ -430,6 +440,38 @@ class ReportMetric(BaseModel):default=None,description="Legacy authoring field, not exposed as a live comparison.",)+ goal_value: float | None = Field(+ default=None,+ description="Proposed threshold for this metric after a change ships; informational only, not a scheduled check.",+ )+ goal_direction: Literal["at_most", "at_least"] | None = Field(+ default=None,+ description="Whether success means reaching or going below/above goal_value.",+ )+ goal_grain: Literal["whole_window", "per_interval"] | None = Field(+ default=None,+ description="Whether the goal compares with the whole query window or each chart bucket.",+ )+ decision_window_days: int | None = Field(+ default=None,+ ge=1,+ le=30,+ description="Suggested number of days after release to assess the goal, not an automatic monitoring schedule.",+ )+ minimum_data_points: int | None = Field(+ default=None,+ ge=1,+ le=1000,+ description="Optional minimum qualifying observations for the suggested decision window.",+ )+ eligibility_query: dict[str, Any] | None = Field(+ default=None, description="Bounded live query counting opportunities eligible for a minimum-data rule."+ )++ @field_validator("eligibility_query")+ @classmethod+ def eligibility_query_must_be_bounded(cls, value: dict[str, Any] | None) -> dict[str, Any] | None:+ return validate_live_metric_query(value) if value is not None else None@field_validator("metric_id")@classmethod@@ -445,12 +487,11 @@ class ReportMetric(BaseModel):raise ValueError(f"must not exceed {MAX_METRIC_TITLE_LENGTH} characters")return value- @field_validator("value", mode="before")+ @field_validator("value", "goal_value", "decision_window_days", "minimum_data_points", mode="before")@classmethoddef value_must_not_be_a_boolean(cls, value: object) -> object:- # Pydantic's lax mode coerces a JSON boolean into a float (`true` becomes 1.0, `false`- # becomes 0.0), which would store a bogus snapshot that clears the finite, count, and rate- # guards below. A snapshot value is never a boolean, so reject it before that coercion runs.+ # Pydantic's lax mode coerces a JSON boolean into a number (`true` becomes 1, `false`+ # becomes 0), which would store a bogus measurement that clears the numeric guards below.if isinstance(value, bool):raise ValueError("must be a number, not a boolean")return value@@ -538,6 +579,19 @@ class ReportMetric(BaseModel):@model_validator(mode="after")def measurement_must_be_available_and_consistent(self) -> ReportMetric:+ if (self.goal_value is None) != (self.goal_direction is None):+ raise ValueError("goal_value and goal_direction must be provided together")+ if self.goal_value is not None and not math.isfinite(self.goal_value):+ raise ValueError("goal_value must be finite")+ if self.goal_value is not None and self.decision_window_days is None and self.minimum_data_points is None:+ raise ValueError("a goal requires a suggested decision window or minimum data points")+ if self.goal_value is not None and self.value_format == "count":+ if self.goal_value < 0 or not self.goal_value.is_integer():+ raise ValueError("a count goal must be a non-negative whole number")+ if self.goal_value is not None and self.kind in {"conversion_rate", "error_rate"}:+ upper_bound = 1 if self.value_format == "percentage_scaled" else 100+ if not 0 <= self.goal_value <= upper_bound:+ raise ValueError(f"a rate goal must be between 0 and {upper_bound}")if (self.value is None) != (self.value_at is None):raise ValueError("value and value_at must be provided together")self._drop_a_snapshot_measured_in_the_future()@@ -583,6 +637,8 @@ class ReportMetric(BaseModel):raise ValueError("a duration metric must use duration formatting")if self.unit not in {"ms", "s"}:raise ValueError("a duration metric must use `ms` or `s` as its unit")+ if self.goal_value is not None and self.goal_value < 0:+ raise ValueError("a duration goal must be non-negative")if self.value is not None and self.value < 0:raise ValueError("a duration snapshot must be non-negative")if self.comparison is not None and self.comparison.value < 0:diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 35651d5b9513..eac3e8e2137c 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -1048,6 +1048,41 @@ class ReportMetricSerializer(serializers.Serializer):"caveat on the data. Omit it rather than restate the title, unit, or window."),)+ goal_value = _MetricFloatField(+ allow_null=True,+ required=False,+ default=None,+ help_text="Proposed threshold after release. Informational only; does not schedule a check.",+ )+ goal_direction = serializers.ChoiceField(+ choices=("at_most", "at_least"),+ allow_null=True,+ required=False,+ default=None,+ help_text="Whether success means at most or at least goal_value.",+ )+ goal_grain = serializers.ChoiceField(+ choices=("whole_window", "per_interval"),+ required=False,+ default="whole_window",+ help_text="Whether the goal compares with the whole query window or each chart bucket.",+ )+ decision_window_days = serializers.IntegerField(+ min_value=1,+ max_value=30,+ allow_null=True,+ required=False,+ default=None,+ help_text="Suggested days after release before assessing impact, not a monitoring schedule.",+ )+ minimum_data_points = serializers.IntegerField(+ min_value=1,+ max_value=1000,+ allow_null=True,+ required=False,+ default=None,+ help_text="Optional number of qualifying observations before assessing impact.",+ )def to_representation(self, instance: Mapping[str, object]) -> dict[str, object]:representation = dict(super().to_representation(instance))@@ -1078,6 +1113,16 @@ class ReportMetricWriteSerializer(ReportMetricSerializer):help_text="Legacy optional comparison. New report metrics must omit it.",)+ def validate(self, attrs: dict[str, object]) -> dict[str, object]:+ if any(+ attrs.get(field) is not None+ for field in ("goal_value", "goal_direction", "decision_window_days", "minimum_data_points")+ ):+ raise serializers.ValidationError(+ "Write proposed goals as impact_measurement_plan artefacts, not report metrics."+ )+ return attrs+class ReportMetricListSerializer(ReportMetricSerializer):"""Snapshot-only metric shape for report lists.@@ -2040,6 +2085,19 @@ class SignalReportArtefactSerializer(serializers.ModelSerializer):if obj.type == SignalReportArtefact.ArtefactType.CHECK_RESULT and isinstance(parsed, dict):return self._redact_check_result(obj, parsed)+ if obj.type == SignalReportArtefact.ArtefactType.IMPACT_MEASUREMENT_PLAN and isinstance(parsed, dict):+ policy = report_metric_access_policy(self.context)+ if not policy.may_read_query(parsed) or (+ parsed.get("eligibility_query") is not None+ and not policy.may_read_query({"query": parsed["eligibility_query"]})+ ):+ return {+ "metric_id": parsed.get("metric_id"),+ "title": parsed.get("title"),+ "activated": parsed.get("activated", False),+ "retired": parsed.get("retired", False),+ }+return parseddef _redact_check_result(self, obj: SignalReportArtefact, content: dict) -> dict:diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.pyindex 0be96c70e9d4..4cd815e0dec6 100644--- a/products/signals/backend/temporal/agentic/report.py+++ b/products/signals/backend/temporal/agentic/report.py@@ -23,15 +23,25 @@ from posthog.temporal.oauth import McpScopePreset, grants_scratchpad_writefrom products.business_knowledge.backend.logic import is_available_for_teamfrom products.signals.backend.agent_runtime import STEP_RESEARCH, resolve_agent_runtime-from products.signals.backend.artefact_schemas import ArtefactContent, RelatedTo, ReportLink, SuggestedReviewers+from products.signals.backend.artefact_schemas import (+ ArtefactContent,+ ImpactMeasurementPlan,+ RelatedTo,+ ReportLink,+ SuggestedReviewers,+)from products.signals.backend.auto_start import ReviewerContentfrom products.signals.backend.enums import ReportLinkKind+from products.signals.backend.impact_measurement_plans import latest_measurement_plansfrom products.signals.backend.models import ArtefactAttribution, SignalActorKind, SignalReport, SignalReportArtefactfrom products.signals.backend.receivers import _is_safety_suppressedfrom products.signals.backend.recurrence import fixed_dismissal_atfrom products.signals.backend.repo_corrections import SCOUT_REPOSITORY_CONTENT_NEEDLE, WRONG_REPO_CONTENT_NEEDLEfrom products.signals.backend.report_charts import ReportChart, chart_batch_error-from products.signals.backend.report_content_gates import team_report_metrics_enabled+from products.signals.backend.report_content_gates import (+ team_expected_impact_authoring_enabled,+ team_report_metrics_enabled,+)from products.signals.backend.report_generation.ownership_reviewers import suggest_repository_ownersfrom products.signals.backend.report_generation.research import (ActionabilityAssessment,@@ -53,7 +63,7 @@ from products.signals.backend.report_generation.reviewer_telemetry import (capture_suggested_reviewers_unresolved,)from products.signals.backend.report_generation.select_repo import RepoSelectionResult-from products.signals.backend.report_metrics import ReportMetric, metric_batch_error+from products.signals.backend.report_metrics import REPORT_METRIC_GOAL_FIELDS, ReportMetric, metric_batch_errorfrom products.signals.backend.report_steering import ReportSteering, load_research_steeringfrom products.signals.backend.supersession import research_implementation_contextfrom products.signals.backend.temporal.agentic import (@@ -103,6 +113,9 @@ class RunAgenticReportOutput:# Resolved impact-metric payload, with the same replay-safe replace/clear/preserve semantics as# charts. The transition activity writes it with the matching title and summary.metrics: list[dict[str, Any]] | None = None+ revise_measurement_plan_metric_ids: list[str] | None = None+ retire_measurement_plan_metric_ids: list[str] | None = None+ previous_measurement_plan_ids: dict[str, str] | None = None# Check specs the verification turn authored, written as rows by the transition activity that# writes the metrics they reference — a check naming a metric the report never got is dropped# there rather than stored pointing at nothing. `None` predates the field and writes none.@@ -231,6 +244,17 @@ def _parse_stored_metrics(raw: object, report_id: str) -> list[ReportMetric]:return parsed+def _load_previous_measurement_plans(team_id: int, report_id: str) -> dict[str, tuple[str, ImpactMeasurementPlan]]:+ report = SignalReport.objects.filter(team_id=team_id, id=report_id).first()+ if report is None:+ return {}+ return {+ metric_id: (str(row.id), plan)+ for metric_id, (row, plan) in latest_measurement_plans(report).items()+ if not plan.retired+ }++async def _load_resolved_report_context(team_id: int, report_id: str) -> tuple[str | None, str | None]:"""Title/summary of the report claimed as fixed that this one recurred from, if any.@@ -642,7 +666,13 @@ def _resolve_report_charts_payload(def _resolve_report_metrics_payload(- metrics: list[ReportMetric], metrics_enabled: bool, *, report_id: str, team_id: int+ metrics: list[ReportMetric],+ metrics_enabled: bool,+ *,+ expected_impact_authoring_enabled: bool = False,+ previous_metrics: list[ReportMetric] | None = None,+ report_id: str,+ team_id: int,) -> list[dict[str, Any]] | None:"""Resolve authored metrics using their own rollout and replace/clear/preserve semantics."""if not metrics_enabled:@@ -659,6 +689,28 @@ def _resolve_report_metrics_payload(metric_count=len(metrics),)return []+ if not expected_impact_authoring_enabled:+ previous_by_id = {metric.metric_id: metric for metric in previous_metrics or []}+ sanitized_metrics = []+ for metric in metrics:+ previous = previous_by_id.get(metric.metric_id)+ same_measure = (+ previous is not None+ and previous.query == metric.query+ and previous.kind == metric.kind+ and previous.value_format == metric.value_format+ and previous.unit == metric.unit+ )+ retained_goal = previous if same_measure else None+ sanitized_metrics.append(+ metric.model_copy(+ update={+ field_name: getattr(retained_goal, field_name) if retained_goal else None+ for field_name in REPORT_METRIC_GOAL_FIELDS+ }+ )+ )+ metrics = sanitized_metricsreturn [metric.model_dump(mode="json") for metric in metrics]@@ -909,6 +961,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)+ expected_impact_authoring_enabled = metrics_enabled and await database_sync_to_async(+ team_expected_impact_authoring_enabled, thread_sensitive=False+ )(input.team_id)# An `agent` check needs a scout fleet to dispatch it. A team with none degrades to# deterministic checks rather than storing a check that could never run.agent_checks_enabled = await database_sync_to_async(_team_runs_scouts, thread_sensitive=False)(@@ -916,6 +971,13 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti)# 2. Load previous research if this is a re-promoted reportprevious_research = await _load_previous_research(input.team_id, input.report_id)+ previous_measurement_plans = (+ await database_sync_to_async(_load_previous_measurement_plans, thread_sensitive=False)(+ input.team_id, input.report_id+ )+ if previous_research and expected_impact_authoring_enabled+ else {}+ )# 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(input.team_id, input.report_id@@ -943,6 +1005,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenticontext,previous_report_id=input.report_id if previous_research else None,previous_report_research=previous_research,+ previous_measurement_plans=previous_measurement_plans,implementation_context=implementation_context,signal_report_id=input.report_id,has_business_knowledge=has_bk,@@ -950,6 +1013,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgentiresolved_report_summary=resolved_report_summary,linked_reports=linked_reports,metrics_enabled=metrics_enabled,+ expected_impact_authoring_enabled=expected_impact_authoring_enabled,agent_checks_enabled=agent_checks_enabled,steering_section=steering.section,)@@ -968,7 +1032,12 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti# not-actionable reset or a failed run, which don't write the new prose).charts_payload = _resolve_report_charts_payload(result.charts, report_id=input.report_id, team_id=input.team_id)metrics_payload = _resolve_report_metrics_payload(- result.metrics, metrics_enabled, report_id=input.report_id, team_id=input.team_id+ result.metrics,+ metrics_enabled,+ expected_impact_authoring_enabled=expected_impact_authoring_enabled,+ previous_metrics=previous_research.metrics if previous_research else None,+ report_id=input.report_id,+ team_id=input.team_id,)logger.info("signals agentic report completed",@@ -987,6 +1056,11 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgentirepository=repository,charts=charts_payload,metrics=metrics_payload,+ revise_measurement_plan_metric_ids=result.revise_measurement_plan_metric_ids,+ retire_measurement_plan_metric_ids=result.retire_measurement_plan_metric_ids,+ previous_measurement_plan_ids={+ metric_id: row_id for metric_id, (row_id, _) in previous_measurement_plans.items()+ },checks=[check.model_dump(mode="json") for check in result.checks],layers=[layer.model_dump(mode="json") for layer in result.layers],research_task_id=result.research_task_id,diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex fe9e2ae6b22e..f4a7402db512 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -34,6 +34,7 @@ from products.signals.backend.auto_start import (start_requested_implementation,)from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate+from products.signals.backend.impact_measurement_plans import persist_authored_measurement_plansfrom products.signals.backend.models import SIGNALS_AT_RUN_INCREMENT, SignalReport, SignalTeamConfigfrom products.signals.backend.quota import (capture_signal_report_quota_paused,@@ -149,6 +150,9 @@ class ReportDecision:charts: list[dict[str, Any]] | None = None# Resolved metric payload with the same preserve/replace/clear semantics as charts.metrics: list[dict[str, Any]] | None = None+ revise_measurement_plan_metric_ids: list[str] | None = None+ retire_measurement_plan_metric_ids: list[str] | None = None+ previous_measurement_plan_ids: dict[str, str] | None = None# Check specs the research run's verification turn authored, and the research task they are# attributed to. Empty for the no-repo branch, which does no research.checks: list[dict[str, Any]] = field(default_factory=list)@@ -459,6 +463,9 @@ class SignalReportSummaryWorkflow:explanation=agentic_result.explanation,charts=agentic_result.charts,metrics=agentic_result.metrics,+ revise_measurement_plan_metric_ids=agentic_result.revise_measurement_plan_metric_ids,+ retire_measurement_plan_metric_ids=agentic_result.retire_measurement_plan_metric_ids,+ previous_measurement_plan_ids=agentic_result.previous_measurement_plan_ids,checks=agentic_result.checks or [],layers=agentic_result.layers or [],research_task_id=agentic_result.research_task_id,@@ -501,6 +508,10 @@ class SignalReportSummaryWorkflow:source_products=source_products,charts=decision.charts,metrics=decision.metrics,+ revise_measurement_plan_metric_ids=decision.revise_measurement_plan_metric_ids,+ retire_measurement_plan_metric_ids=decision.retire_measurement_plan_metric_ids,+ previous_measurement_plan_ids=decision.previous_measurement_plan_ids,+ plans_task_id=decision.research_task_id,suggested_prompts=decision.suggested_prompts,charts_enabled=decision.charts_enabled,pending_reason=decision.pending_reason,@@ -523,6 +534,10 @@ class SignalReportSummaryWorkflow:source_products=source_products,charts=decision.charts,metrics=decision.metrics,+ revise_measurement_plan_metric_ids=decision.revise_measurement_plan_metric_ids,+ retire_measurement_plan_metric_ids=decision.retire_measurement_plan_metric_ids,+ previous_measurement_plan_ids=decision.previous_measurement_plan_ids,+ plans_task_id=decision.research_task_id,checks=decision.checks,checks_task_id=decision.research_task_id,layers=decision.layers,@@ -832,6 +847,10 @@ class MarkReportReadyInput:charts: list[dict[str, Any]] | None = None# Typed impact metrics written atomically with the prose and chart set.metrics: list[dict[str, Any]] | None = None+ plans_task_id: str | None = None+ revise_measurement_plan_metric_ids: list[str] | None = None+ retire_measurement_plan_metric_ids: list[str] | None = None+ previous_measurement_plan_ids: dict[str, str] | None = None# Check specs the research run's verification turn authored, written as rows in the same# transaction as the metrics they reference. Empty or `None` writes none, which is also what an# older workflow history that predates the field replays as.@@ -927,7 +946,16 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:report.charts = input.chartsupdated_fields = [*updated_fields, "charts"]if input.metrics is not None:- report.metrics = input.metrics+ report.metrics = persist_authored_measurement_plans(+ report,+ input.metrics,+ ArtefactAttribution.from_task(input.plans_task_id)+ if input.plans_task_id+ else ArtefactAttribution.system(),+ revise_metric_ids=input.revise_measurement_plan_metric_ids,+ retire_metric_ids=input.retire_measurement_plan_metric_ids,+ previous_plan_ids=input.previous_measurement_plan_ids,+ )updated_fields = [*updated_fields, "metrics"]if input.suggested_prompts is not None:report.suggested_prompts = input.suggested_prompts@@ -1161,6 +1189,10 @@ class MarkReportPendingInput:charts: list[dict[str, Any]] | None = None# See MarkReportReadyInput.metrics — same transaction and replay-safe default.metrics: list[dict[str, Any]] | None = None+ plans_task_id: str | None = None+ revise_measurement_plan_metric_ids: list[str] | None = None+ retire_measurement_plan_metric_ids: list[str] | None = None+ previous_measurement_plan_ids: dict[str, str] | None = None# See MarkReportReadyInput.suggested_prompts — same transaction, same three states.suggested_prompts: list[str] | None = None# See MarkReportReadyInput.charts_enabled — reported, never stored.@@ -1189,7 +1221,16 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> Nreport.charts = input.chartsupdated_fields = [*updated_fields, "charts"]if input.metrics is not None:- report.metrics = input.metrics+ report.metrics = persist_authored_measurement_plans(+ report,+ input.metrics,+ ArtefactAttribution.from_task(input.plans_task_id)+ if input.plans_task_id+ else ArtefactAttribution.system(),+ revise_metric_ids=input.revise_measurement_plan_metric_ids,+ retire_metric_ids=input.retire_measurement_plan_metric_ids,+ previous_plan_ids=input.previous_measurement_plan_ids,+ )updated_fields = [*updated_fields, "metrics"]if input.suggested_prompts is not None:report.suggested_prompts = input.suggested_promptsdiff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.pyindex 0cc243e5d759..02b233e32a49 100644--- a/products/signals/backend/test/test_agentic_report_activity.py+++ b/products/signals/backend/test/test_agentic_report_activity.py@@ -1,6 +1,7 @@import jsonimport randomimport asyncio+from collections.abc import Callablefrom datetime import UTC, datetime, timedeltafrom uuid import UUID@@ -25,6 +26,7 @@ from posthog.temporal.oauth import grants_scratchpad_writefrom products.signals.backend.artefact_schemas import (DISMISSAL_REASON_WRONG_REPO,Dismissal,+ ImpactMeasurementPlan,ImplementationAssessment,ImplementationTarget,NoteArtefact,@@ -32,6 +34,10 @@ from products.signals.backend.artefact_schemas import (ReportLink,)from products.signals.backend.enums import ReportLinkKind+from products.signals.backend.impact_measurement_plans import (+ latest_measurement_plans,+ persist_authored_measurement_plans,+)from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalScoutNotefrom products.signals.backend.repo_corrections import SCOUT_REPOSITORY_REASONfrom products.signals.backend.report_charts import ReportChart@@ -51,7 +57,7 @@ from products.signals.backend.report_generation.research import (run_multi_turn_research,)from products.signals.backend.report_generation.select_repo import RepoSelectionResult-from products.signals.backend.report_metrics import ReportMetric+from products.signals.backend.report_metrics import REPORT_METRIC_GOAL_FIELDS, ReportMetricfrom products.signals.backend.supersession import ImplementationResearchContextfrom products.signals.backend.temporal.agentic.report import (RESEARCH_MCP_SCOPES,@@ -62,6 +68,7 @@ from products.signals.backend.temporal.agentic.report import (_parse_artefact_content,_parse_stored_charts,_parse_stored_metrics,+ _resolve_report_metrics_payload,run_agentic_report_activity,)from products.signals.backend.temporal.agentic.select_repository import (@@ -207,8 +214,50 @@ _EXISTING_CHART = {_EXISTING_METRIC = _metric("existing-affected-users").model_dump(mode="json")+def test_automatic_metric_goal_requires_authoring_flag():+ metric = _metric().model_copy(+ update={"goal_value": 2, "goal_direction": "at_most", "decision_window_days": 7, "minimum_data_points": 30}+ )++ blocked = _resolve_report_metrics_payload([metric], True, report_id="report-1", team_id=2)+ allowed = _resolve_report_metrics_payload(+ [metric], True, expected_impact_authoring_enabled=True, report_id="report-1", team_id=2+ )++ assert blocked is not None and allowed is not None+ assert all(blocked[0][field_name] is None for field_name in REPORT_METRIC_GOAL_FIELDS)+ assert allowed[0]["goal_value"] == 2+++def test_disabled_authoring_preserves_existing_goal_only_for_the_same_measure():+ previous = _metric().model_copy(update={"goal_value": 5, "goal_direction": "at_most", "decision_window_days": 7})+ changed_goal = previous.model_copy(update={"goal_value": 0, "decision_window_days": 1})+ changed_query = json.loads(json.dumps(changed_goal.query))+ changed_query["source"]["series"][0]["event"] = "$pageview"+ changed_measure = changed_goal.model_copy(update={"query": changed_query})++ retained = _resolve_report_metrics_payload(+ [changed_goal], True, previous_metrics=[previous], report_id="report-1", team_id=2+ )+ removed = _resolve_report_metrics_payload(+ [changed_measure], True, previous_metrics=[previous], report_id="report-1", team_id=2+ )++ assert retained is not None and removed is not None+ assert retained[0]["goal_value"] == 5+ assert retained[0]["decision_window_days"] == 7+ assert removed[0]["goal_value"] is None++async def _run_activity_with_output(- monkeypatch, ateam, report, output, *, metrics_enabled=True, repo_selection_as_of=None+ monkeypatch,+ ateam,+ report,+ output,+ *,+ metrics_enabled=True,+ repo_selection_as_of=None,+ research_kwargs=None,):monkeypatch.setattr("products.signals.backend.temporal.agentic.report.resolve_user_id_for_team",@@ -220,6 +269,8 @@ async def _run_activity_with_output()async def fake_run_multi_turn_research(*args, **kwargs):+ if research_kwargs is not None:+ research_kwargs.update(kwargs)return outputmonkeypatch.setattr(@@ -1091,8 +1142,13 @@ async def test_run_agentic_report_activity_resolves_charts_payload(monkeypatch,],)async def test_run_agentic_report_activity_resolves_metrics_payload(- monkeypatch, ateam, name, metrics_enabled, output_factory, expected-):+ monkeypatch: pytest.MonkeyPatch,+ ateam: Team,+ name: str,+ metrics_enabled: bool,+ output_factory: Callable[[], ReportResearchOutput],+ expected: list[str] | None,+) -> None:report = await database_sync_to_async(SignalReport.objects.create)(team=ateam, status=SignalReport.Status.IN_PROGRESS, signal_count=2, total_weight=1.3)@@ -1111,6 +1167,48 @@ async def test_run_agentic_report_activity_resolves_metrics_payload(assert [metric["metric_id"] for metric in result.metrics or []] == expected+async def test_run_agentic_report_activity_supplies_existing_plans_to_reresearch(monkeypatch, ateam):+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam, status=SignalReport.Status.IN_PROGRESS, signal_count=2, total_weight=1.3+ )+ plan = ImpactMeasurementPlan(+ metric_id="affected-users",+ title="Affected users",+ kind="affected_users",+ query=_metric().query,+ value_format="count",+ unit="users",+ goal_value=0,+ goal_direction="at_most",+ decision_window_days=7,+ activated=True,+ )+ row = await database_sync_to_async(SignalReportArtefact.add_log)(+ team_id=ateam.id,+ report_id=str(report.id),+ content=plan,+ attribution=ArtefactAttribution.system(),+ )+ monkeypatch.setattr(+ "products.signals.backend.temporal.agentic.report._load_previous_research",+ AsyncMock(return_value=_build_research_output()),+ )+ monkeypatch.setattr(+ "products.signals.backend.temporal.agentic.report.team_expected_impact_authoring_enabled",+ lambda team_id: True,+ )+ research_kwargs: dict[str, object] = {}++ result = await _run_activity_with_output(+ monkeypatch, ateam, report, _build_research_output(), research_kwargs=research_kwargs+ )++ assert research_kwargs["previous_measurement_plans"] == {"affected-users": (str(row.id), plan)}+ assert result.previous_measurement_plan_ids == {"affected-users": str(row.id)}++@pytest.mark.asyncio@pytest.mark.django_db@pytest.mark.parametrize(@@ -1194,6 +1292,45 @@ async def test_mark_report_ready_activity_applies_metrics(ateam, name, metrics,assert stored == []+async def test_mark_report_ready_activity_revises_existing_measurement_plan(ateam):+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.IN_PROGRESS,+ signal_count=2,+ total_weight=1.3,+ )+ original_metric = (+ _metric()+ .model_copy(update={"goal_value": 0, "goal_direction": "at_most", "decision_window_days": 7})+ .model_dump(mode="json")+ )+ await database_sync_to_async(persist_authored_measurement_plans)(+ report, [original_metric], ArtefactAttribution.system()+ )+ previous_row, _ = await database_sync_to_async(lambda: latest_measurement_plans(report)["affected-users"])()+ revised_metric = {**original_metric, "goal_value": 7}++ await mark_report_ready_activity(+ MarkReportReadyInput(+ team_id=ateam.id,+ report_id=str(report.id),+ title="Updated title",+ summary="Updated expected impact",+ processed_signal_count=2,+ metrics=[revised_metric],+ revise_measurement_plan_metric_ids=["affected-users"],+ previous_measurement_plan_ids={"affected-users": str(previous_row.id)},+ )+ )++ updated_row, revised = await database_sync_to_async(lambda: latest_measurement_plans(report)["affected-users"])()+ assert updated_row.id != previous_row.id+ assert revised.goal_value == 7+ assert revised.activated is False++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_mark_report_pending_input_activity_applies_metrics_with_draft_prose(ateam):@@ -1224,6 +1361,57 @@ async def test_mark_report_pending_input_activity_applies_metrics_with_draft_proassert [metric["metric_id"] for metric in stored.metrics] == ["pending-affected-users"][email protected]("pending_input", [False, True])+async def test_report_transition_saves_goals_as_plans_and_keeps_observations_goal_free(+ ateam: Team, pending_input: bool+) -> None:+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.IN_PROGRESS,+ signal_count=2,+ total_weight=1.3,+ )+ metric = (+ _metric("measured-outcome")+ .model_copy(update={"goal_value": 0, "goal_direction": "at_most", "decision_window_days": 7})+ .model_dump(mode="json")+ )+ if pending_input:+ await mark_report_pending_input_activity(+ MarkReportPendingInput(+ team_id=ateam.id,+ report_id=str(report.id),+ title="Draft title",+ summary="Draft summary",+ reason="Needs input",+ metrics=[metric],+ )+ )+ else:+ await mark_report_ready_activity(+ MarkReportReadyInput(+ team_id=ateam.id,+ report_id=str(report.id),+ title="Title",+ summary="Summary",+ processed_signal_count=2,+ metrics=[metric],+ )+ )++ def stored_outcome() -> tuple[list[dict[str, object]], ImpactMeasurementPlan]:+ updated_report = SignalReport.objects.get(id=report.id)+ return updated_report.metrics, latest_measurement_plans(updated_report)["measured-outcome"][1]++ observations, plan = await database_sync_to_async(stored_outcome)()+ assert observations[0]["metric_id"] == plan.metric_id+ assert not any(field in observations[0] for field in REPORT_METRIC_GOAL_FIELDS)+ assert plan.goal_value == 0+ assert plan.activated is False++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_run_agentic_report_activity_does_not_persist_partial_artefacts(monkeypatch, ateam):diff --git a/products/signals/backend/test/test_artefact_schemas.py b/products/signals/backend/test/test_artefact_schemas.pyindex 6911fb8e9e97..07140f58a8bf 100644--- a/products/signals/backend/test/test_artefact_schemas.py+++ b/products/signals/backend/test/test_artefact_schemas.py@@ -11,6 +11,7 @@ from products.signals.backend.artefact_schemas import (ArtefactContentValidationError,CodeReference,Commit,+ ImpactMeasurementPlan,NoteArtefact,RelevantCommit,SuggestedReviewerEntry,@@ -24,6 +25,32 @@ from products.signals.backend.models import SignalReportArtefactclass TestArtefactSchemas(SimpleTestCase):+ def test_impact_plan_rejects_boolean_decision_rules(self) -> None:+ plan = {+ "metric_id": "errors",+ "title": "Errors",+ "kind": "occurrences",+ "value_format": "count",+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "TrendsQuery",+ "dateRange": {"date_from": "-7d"},+ "series": [{"kind": "EventsNode", "event": "$exception", "math": "total"}],+ "trendsFilter": {"display": "ActionsBar"},+ },+ },+ "goal_value": 0,+ "goal_direction": "at_most",+ "decision_window_days": 7,+ }+ ImpactMeasurementPlan.model_validate(plan)+ for field in ("goal_value", "decision_window_days", "minimum_data_points"):+ for boolean in (True, False):+ with self.assertRaises(ValidationError) as caught:+ ImpactMeasurementPlan.model_validate({**plan, field: boolean})+ self.assertIn(field, str(caught.exception))+def test_reviewer_reasons_are_bounded_on_write(self):with self.assertRaises(ValidationError):SuggestedReviewerEntry(github_login="reviewer", reason="x" * 501)diff --git a/products/signals/backend/test/test_report_metrics.py b/products/signals/backend/test/test_report_metrics.pyindex f38c21943021..853f6c74a869 100644--- a/products/signals/backend/test/test_report_metrics.py+++ b/products/signals/backend/test/test_report_metrics.py@@ -74,6 +74,58 @@ class TestReportMetric(SimpleTestCase):assert metric.value == 0+ def test_proposed_goal_is_informational_and_round_trips(self) -> None:+ content = _affected_users_metric().model_dump(mode="json")+ content.update(goal_value=0, goal_direction="at_most", decision_window_days=7, minimum_data_points=30)++ metric = ReportMetric.model_validate(content)++ assert metric.goal_value == 0+ assert ReportMetric.model_validate_json(metric.model_dump_json()) == metric++ def test_proposed_goal_requires_direction_and_decision_rule(self) -> None:+ content = _affected_users_metric().model_dump(mode="json")+ content.update(goal_value=10, goal_direction="at_most")++ with self.assertRaisesRegex(ValidationError, "suggested decision window"):+ ReportMetric.model_validate(content)++ content["decision_window_days"] = 7+ content["goal_direction"] = None+ with self.assertRaisesRegex(ValidationError, "goal_value and goal_direction"):+ ReportMetric.model_validate(content)++ def test_proposed_goal_rejects_boolean_values(self) -> None:+ for field_name in ("goal_value", "decision_window_days", "minimum_data_points"):+ for boolean in (True, False):+ content = _affected_users_metric().model_dump(mode="json")+ content.update(goal_value=10, goal_direction="at_most", decision_window_days=7)+ content[field_name] = boolean+ with self.subTest(field_name=field_name, value=boolean):+ with self.assertRaisesRegex(ValidationError, "must be a number, not a boolean"):+ ReportMetric.model_validate(content)++ def test_proposed_duration_goal_rejects_negative_values(self) -> None:+ content = _affected_users_metric().model_dump(mode="json")+ content.update(+ kind="duration",+ value_format="duration",+ unit="ms",+ goal_value=-1,+ goal_direction="at_most",+ decision_window_days=7,+ )++ with self.assertRaisesRegex(ValidationError, "duration goal must be non-negative"):+ ReportMetric.model_validate(content)++ def test_rejects_fractional_count_goal(self) -> None:+ content = _affected_users_metric().model_dump(mode="json")+ content.update(goal_value=1.5, goal_direction="at_most", decision_window_days=3)++ with self.assertRaisesRegex(ValidationError, "count goal"):+ ReportMetric.model_validate(content)+def test_rejects_fractional_or_negative_count_snapshots(self) -> None:for value in (-1, 1.5):content = _affected_users_metric().model_dump(mode="json")diff --git a/products/signals/backend/test/test_research_prompt.py b/products/signals/backend/test/test_research_prompt.pyindex e427d45641cd..90afad4ff08f 100644--- a/products/signals/backend/test/test_research_prompt.py+++ b/products/signals/backend/test/test_research_prompt.py@@ -5,6 +5,7 @@ from xml.etree import ElementTreeimport pytest+from products.signals.backend.artefact_schemas import ImpactMeasurementPlanfrom products.signals.backend.enums import ReportLinkKindfrom products.signals.backend.report_charts import ReportChartfrom products.signals.backend.report_generation.research import (@@ -315,6 +316,74 @@ def _make_chart() -> ReportChart:class TestBuildReportPresentationPrompt:+ def test_proposed_impact_guidance_only_appears_with_both_flags(self):+ off = build_report_presentation_prompt(2, metrics_enabled=True)+ no_metrics = build_report_presentation_prompt(2, expected_impact_authoring_enabled=True)+ on = build_report_presentation_prompt(2, metrics_enabled=True, expected_impact_authoring_enabled=True)++ assert "## Proposed impact measurement" not in off+ assert "## Proposed impact measurement" not in no_metrics+ assert "## Proposed impact measurement" in on+ assert '"goal_value"' not in off+ assert '"goal_value"' not in no_metrics+ assert '"goal_value"' in on+ assert "Count qualifying opportunities, not failures" in on++ def test_previous_goal_is_hidden_when_authoring_is_disabled(self):+ metric = ReportMetric.model_validate(+ {+ "metric_id": "affected-users",+ "title": "Affected users",+ "kind": "affected_users",+ "value_format": "count",+ "unit": "users",+ "query": trends_metric_query(series=[{"kind": "EventsNode", "event": "$exception", "math": "dau"}]),+ "goal_value": 5,+ "goal_direction": "at_most",+ "decision_window_days": 7,+ }+ )++ off = build_report_presentation_prompt(2, metrics_enabled=True, previous_metrics=[metric])+ on = build_report_presentation_prompt(+ 2, metrics_enabled=True, expected_impact_authoring_enabled=True, previous_metrics=[metric]+ )++ assert '"goal_value"' not in off+ assert '"goal_value"' in on++ def test_reresearch_reviews_existing_measurement_plans_when_authoring_is_enabled(self):+ plan = ImpactMeasurementPlan.model_validate(+ {+ "metric_id": "affected-users",+ "title": "Affected users",+ "kind": "affected_users",+ "value_format": "count",+ "unit": "users",+ "query": trends_metric_query(series=[{"kind": "EventsNode", "event": "$exception", "math": "dau"}]),+ "goal_value": 0,+ "goal_direction": "at_most",+ "decision_window_days": 7,+ "activated": True,+ }+ )+ previous_plans = {"affected-users": ("plan-version-1", plan)}++ enabled = build_report_presentation_prompt(+ 2,+ metrics_enabled=True,+ expected_impact_authoring_enabled=True,+ previous_measurement_plans=previous_plans,+ )+ disabled = build_report_presentation_prompt(2, metrics_enabled=True, previous_measurement_plans=previous_plans)++ assert "Review each attached plan" in enabled+ assert '"artefact_id": "plan-version-1"' in enabled+ assert "retire_measurement_plan_metric_ids" in enabled+ assert "revise_measurement_plan_metric_ids" in enabled+ assert "Existing impact measurement plans" not in disabled+ assert "retire_measurement_plan_metric_ids" not in disabled+def test_metric_guidance_and_schema_field_only_present_when_enabled(self):off = build_report_presentation_prompt(2, metrics_enabled=False)on = build_report_presentation_prompt(2, metrics_enabled=True)@@ -450,6 +519,47 @@ class TestReportPresentationOutputCharts:assert parsed.summary == "Signups fell 60% over the week."+_WINDOW_GOAL = {"goal_value": 0.01, "goal_direction": "at_most", "decision_window_days": 7}+++class TestReportPresentationOutputMetrics:+ @pytest.mark.parametrize(+ "goal, kept_goal",+ [+ (_WINDOW_GOAL, _WINDOW_GOAL),+ ({"goal_value": 0.01, "goal_direction": "at_most"}, {}),+ ({"goal_direction": "at_most", "decision_window_days": 7}, {}),+ ({"goal_value": 5, "goal_direction": "at_most", "minimum_data_points": 100}, {}),+ ({**_WINDOW_GOAL, "minimum_data_points": 30}, _WINDOW_GOAL),+ ({"goal_value": 0.01, "goal_direction": "at_most", "minimum_data_points": 30}, {}),+ ],+ )+ def test_an_invalid_goal_is_cleared_without_failing_the_response(self, goal, kept_goal):+ query = trends_metric_query(series=[{"kind": "EventsNode", "event": "checkout_failed"}])+ query["source"]["trendsFilter"] = {"aggregationAxisFormat": "percentage_scaled"}+ parsed = ReportPresentationOutput.model_validate(+ {+ "title": "fix(checkout): Handle the payment timeout",+ "summary": "Checkout errors rose over the week.",+ "metrics": [+ {+ "metric_id": "checkout-error-rate",+ "title": "Checkout attempts that fail",+ "kind": "error_rate",+ "role": "primary",+ "value_format": "percentage_scaled",+ "query": query,+ **goal,+ }+ ],+ }+ )++ assert parsed.title == "fix(checkout): Handle the payment timeout"+ assert [metric.metric_id for metric in parsed.metrics] == ["checkout-error-rate"]+ assert {field: getattr(parsed.metrics[0], field) for field in goal} == {**dict.fromkeys(goal), **kept_goal}++class TestOwnPullRequestCarveOut:_PR = "https://github.com/PostHog/posthog/pull/7"diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.pyindex 77cc7ebaecb5..79939fc597e8 100644--- a/products/signals/backend/test/test_signal_report_artefact_api.py+++ b/products/signals/backend/test/test_signal_report_artefact_api.py@@ -27,6 +27,10 @@ from products.signals.backend.artefact_schemas import (TaskRunArtefact,)from products.signals.backend.enums import ReportLinkKind+from products.signals.backend.impact_measurement_plans import (+ latest_measurement_plans,+ persist_authored_measurement_plans,+)from products.signals.backend.implementation_pr import ImplementationPrfrom products.signals.backend.models import (ArtefactAttribution,@@ -37,7 +41,9 @@ from products.signals.backend.models import (SignalReportPullRequest,SignalReportSuggestedReviewer,)+from products.signals.backend.report_metrics import MAX_REPORT_METRICSfrom products.signals.backend.reviewer_correction_notes import ForwardedCorrectionNotes+from products.signals.backend.test.report_metric_test_fixtures import trends_metric_query# Task ORM model needed to build cross-product fixtures; the tasks facade exposes DTOs only.from products.tasks.backend.models import Channel, Task@@ -53,6 +59,224 @@ def _attach_github_login(user: User, login: str, *, uid: str | None = None) -> Nclass TestSignalReportArtefactViewSet(APIBaseTest):+ def _impact_plan(self) -> dict:+ return {+ "metric_id": "affected-users",+ "title": "Affected users",+ "kind": "affected_users",+ "value_format": "count",+ "unit": "users",+ "query": trends_metric_query(+ series=[{"kind": "EventsNode", "event": "$exception", "math": "dau"}], date_from="-14d"+ ),+ "goal_value": 0,+ "goal_direction": "at_most",+ "decision_window_days": 7,+ }++ def test_impact_plan_approval_appends_a_version_and_rejects_stale_approval(self):+ report = self._create_report()+ url = self._list_url(str(report.id))+ response = self.client.post(+ url, {"artefact_type": "impact_measurement_plan", "content": self._impact_plan()}, format="json"+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ plan_id = response.json()["id"]+ approval_url = f"{self._detail_url(str(report.id), plan_id)}activate/"+ approved = self.client.post(approval_url)+ assert approved.status_code == status.HTTP_200_OK, approved.json()+ assert approved.json()["content"]["activated"] is True+ assert approved.json()["id"] != plan_id+ assert SignalReportArtefact.objects.filter(report=report, type="impact_measurement_plan").count() == 2+ assert self.client.post(approval_url).status_code == status.HTTP_409_CONFLICT++ def test_impact_plan_normalizes_metric_id_before_storing(self) -> None:+ report = self._create_report()+ plan = {**self._impact_plan(), "metric_id": " affected-users "}+ response = self.client.post(+ self._list_url(str(report.id)), {"artefact_type": "impact_measurement_plan", "content": plan}, format="json"+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["content"]["metric_id"] == "affected-users"+ assert list(latest_measurement_plans(report)) == ["affected-users"]++ persist_authored_measurement_plans(report, [self._impact_plan()], ArtefactAttribution.system())+ assert SignalReportArtefact.objects.filter(report=report, type="impact_measurement_plan").count() == 1++ def test_impact_plan_limits_active_outcomes_but_allows_revisions_and_replacements(self) -> None:+ report = self._create_report()+ url = self._list_url(str(report.id))++ def write(metric_id: str, *, retired: bool = False) -> int:+ content = {**self._impact_plan(), "metric_id": metric_id, "retired": retired}+ return self.client.post(+ url, {"artefact_type": "impact_measurement_plan", "content": content}, format="json"+ ).status_code++ for index in range(MAX_REPORT_METRICS):+ assert write(f"outcome-{index}") == status.HTTP_201_CREATED++ assert write("one-more") == status.HTTP_400_BAD_REQUEST+ assert write("outcome-0") == status.HTTP_201_CREATED+ assert write("outcome-0", retired=True) == status.HTTP_201_CREATED+ assert write("one-more") == status.HTTP_201_CREATED+ assert sum(not plan.retired for _, plan in latest_measurement_plans(report).values()) == MAX_REPORT_METRICS++ def test_revised_plan_needs_new_approval_without_changing_other_outcomes(self):+ report = self._create_report()+ url = self._list_url(str(report.id))+ original = self.client.post(+ url, {"artefact_type": "impact_measurement_plan", "content": self._impact_plan()}, format="json"+ )+ assert original.status_code == status.HTTP_201_CREATED, original.json()+ approved = self.client.post(f"{self._detail_url(str(report.id), original.json()['id'])}activate/")+ assert approved.status_code == status.HTTP_200_OK, approved.json()++ another_outcome = {**self._impact_plan(), "metric_id": "another-outcome", "title": "Another outcome"}+ assert (+ self.client.post(+ url, {"artefact_type": "impact_measurement_plan", "content": another_outcome}, format="json"+ ).status_code+ == status.HTTP_201_CREATED+ )++ revised = {**self._impact_plan(), "goal_value": 1}+ revision = self.client.post(+ url, {"artefact_type": "impact_measurement_plan", "content": revised}, format="json"+ )+ assert revision.status_code == status.HTTP_201_CREATED, revision.json()+ latest = latest_measurement_plans(report)+ assert str(latest["affected-users"][0].id) == revision.json()["id"]+ assert latest["affected-users"][1].activated is False+ assert latest["another-outcome"][1].goal_value == 0+ assert (+ self.client.post(f"{self._detail_url(str(report.id), approved.json()['id'])}activate/").status_code+ == status.HTTP_409_CONFLICT+ )++ def test_impact_plan_cannot_be_activated_by_generic_write_or_changed_in_place(self):+ report = self._create_report()+ plan = self._impact_plan()+ plan["activated"] = True+ response = self.client.post(+ self._list_url(str(report.id)), {"artefact_type": "impact_measurement_plan", "content": plan}, format="json"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ plan["activated"] = False+ response = self.client.post(+ self._list_url(str(report.id)), {"artefact_type": "impact_measurement_plan", "content": plan}, format="json"+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ detail_url = self._detail_url(str(report.id), response.json()["id"])+ assert (+ self.client.patch(detail_url, {"content": plan}, format="json").status_code == status.HTTP_400_BAD_REQUEST+ )+ assert self.client.delete(detail_url).status_code == status.HTTP_400_BAD_REQUEST++ def test_research_keeps_plans_unless_it_explicitly_revises_or_retires_them(self):+ report = self._create_report()+ metric = self._impact_plan()+ clean = persist_authored_measurement_plans(report, [metric], ArtefactAttribution.system())+ assert "goal_value" not in clean[0]+ assert clean[0]["query"] == metric["query"]+ first, proposal = latest_measurement_plans(report)["affected-users"]+ assert proposal.goal_value == 0+ assert proposal.activated is False+ changed = {**metric, "goal_value": 7}+ persist_authored_measurement_plans(report, [changed], ArtefactAttribution.system())+ latest, unchanged = latest_measurement_plans(report)["affected-users"]+ assert latest.id == first.id+ assert unchanged.goal_value == 0++ approved = SignalReportArtefact.add_log(+ team_id=report.team_id,+ report_id=str(report.id),+ content=unchanged.model_copy(update={"activated": True}),+ attribution=ArtefactAttribution.system(),+ )+ previous_plan_ids = {"affected-users": str(approved.id)}+ persist_authored_measurement_plans(+ report,+ [metric],+ ArtefactAttribution.system(),+ revise_metric_ids=["affected-users"],+ previous_plan_ids=previous_plan_ids,+ )+ assert latest_measurement_plans(report)["affected-users"][0].id == approved.id++ persist_authored_measurement_plans(+ report,+ [changed],+ ArtefactAttribution.system(),+ revise_metric_ids=["affected-users"],+ previous_plan_ids={"affected-users": str(first.id)},+ )+ assert latest_measurement_plans(report)["affected-users"][0].id == approved.id++ persist_authored_measurement_plans(+ report,+ [changed],+ ArtefactAttribution.system(),+ revise_metric_ids=["affected-users"],+ previous_plan_ids=previous_plan_ids,+ )+ revised_row, revised = latest_measurement_plans(report)["affected-users"]+ assert revised_row.id != approved.id+ assert revised.goal_value == 7+ assert revised.activated is False++ persist_authored_measurement_plans(+ report,+ [changed],+ ArtefactAttribution.system(),+ retire_metric_ids=["affected-users"],+ previous_plan_ids={"affected-users": str(revised_row.id)},+ )+ retired_row, retired = latest_measurement_plans(report)["affected-users"]+ assert retired_row.id != revised_row.id+ assert retired.retired is True+ assert retired.activated is False++ def test_research_respects_the_active_measurement_limit(self) -> None:+ report = self._create_report()+ for index in range(MAX_REPORT_METRICS):+ metric = {**self._impact_plan(), "metric_id": f"outcome-{index}"}+ persist_authored_measurement_plans(report, [metric], ArtefactAttribution.system())++ extra = {**self._impact_plan(), "metric_id": "one-more"}+ observations = persist_authored_measurement_plans(report, [extra], ArtefactAttribution.system())+ assert "goal_value" not in observations[0]+ assert "one-more" not in latest_measurement_plans(report)++ def test_minimum_sample_requires_a_query_for_eligible_opportunities(self):+ report = self._create_report()+ plan = {**self._impact_plan(), "minimum_data_points": 30}+ url = self._list_url(str(report.id))+ payload = {"artefact_type": "impact_measurement_plan", "content": plan}+ assert self.client.post(url, payload, format="json").status_code == status.HTTP_400_BAD_REQUEST++ eligible_query = json.loads(json.dumps(plan["query"]))+ eligible_query["source"]["series"][0]["math"] = "total"+ payload["content"] = {**plan, "eligibility_query": eligible_query}+ response = self.client.post(url, payload, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ def test_impact_plan_redacts_the_goal_if_query_access_is_denied(self):+ report = self._create_report()+ response = self.client.post(+ self._list_url(str(report.id)),+ {"artefact_type": "impact_measurement_plan", "content": self._impact_plan()},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED+ with patch(+ "products.signals.backend.report_metric_access.ReportMetricAccessPolicy.may_read_query", return_value=False+ ):+ listed = self.client.get(self._list_url(str(report.id)))+ content = listed.json()["results"][0]["content"]+ assert "query" not in content+ assert "goal_value" not in content+def _list_url(self, report_id: str) -> str:return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/"diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 2a5d1d857b91..530de171bf13 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -79,6 +79,7 @@ from products.signals.backend.artefact_schemas import (ArtefactContentValidationError,ChannelAssignment,Dismissal,+ ImpactMeasurementPlan,SuggestedReviewers,SummaryChange,TitleChange,@@ -100,6 +101,7 @@ from products.signals.backend.billing import (from products.signals.backend.dismissal_notes import forward_dismissal_notefrom products.signals.backend.facade.api import emit_signalfrom products.signals.backend.feedback_notes import forward_feedback_note+from products.signals.backend.impact_measurement_plans import can_append_measurement_plan, latest_measurement_plansfrom products.signals.backend.implementation_pr import (fetch_implementation_prs_for_reports,implementation_pr_report_filter,@@ -4869,10 +4871,21 @@ class SignalReportArtefactViewSet({"error": f"content does not match the '{artefact_type}' schema: {e}"},status=status.HTTP_400_BAD_REQUEST,)+ if isinstance(parsed_content, ImpactMeasurementPlan) and parsed_content.activated:+ return Response(+ {"error": "Activate a measurement with its approval action."}, status=status.HTTP_400_BAD_REQUEST+ )if isinstance(parsed_content, ChannelAssignment):self._validate_channel_assignment(parsed_content, request)with transaction.atomic():report = SignalReport.objects.select_for_update().get(team_id=self.team.id, id=report_id)+ if isinstance(parsed_content, ImpactMeasurementPlan) and not can_append_measurement_plan(+ latest_measurement_plans(report), parsed_content+ ):+ return Response(+ {"error": "This report already has the maximum number of active impact measurements."},+ status=status.HTTP_400_BAD_REQUEST,+ )import_report_pull_requests(report)claim_id = request.validated_data.get("claim_id")if claim_id:@@ -4975,6 +4988,11 @@ class SignalReportArtefactViewSet()def partial_update(self, request: ValidatedRequest, *args, **kwargs) -> Response:artefact = cast(SignalReportArtefact, self.get_object())+ if artefact.type == SignalReportArtefact.ArtefactType.IMPACT_MEASUREMENT_PLAN:+ return Response(+ {"error": "Append a new measurement version instead of editing one."},+ status=status.HTTP_400_BAD_REQUEST,+ )if artefact.type in NON_WRITABLE_ARTEFACT_TYPES:# Legacy read-only types (e.g. video_segment) can't be created via the API, so they# can't be edited through it either.@@ -4997,6 +5015,45 @@ class SignalReportArtefactViewSet(transaction.on_commit(partial(self._capture_canonical_reviewer_state, str(artefact.report_id)))return Response(self._write_response_data(artefact))+ @extend_schema(+ request=None,+ responses={200: SignalReportArtefactWriteResponseSerializer},+ summary="Activate a proposed impact measurement",+ )+ @action(detail=True, methods=["post"], url_path="activate")+ def activate(self, request: Request, *args, **kwargs) -> Response:+ attribution = resolve_request_attribution(request, self.team.id)+ if attribution.kind != "user" or not isinstance(request.successful_authenticator, SessionAuthentication):+ return Response({"error": "A person must approve this measurement."}, status=status.HTTP_403_FORBIDDEN)+ with transaction.atomic():+ artefact = cast(SignalReportArtefact, self.get_object())+ if artefact.type != SignalReportArtefact.ArtefactType.IMPACT_MEASUREMENT_PLAN:+ return Response({"error": "Not a measurement plan."}, status=status.HTTP_400_BAD_REQUEST)+ report = SignalReport.objects.select_for_update().get(id=artefact.report_id, team_id=self.team.id)+ plan = parse_artefact_content(artefact.type, artefact.content)+ assert isinstance(plan, ImpactMeasurementPlan)+ current = latest_measurement_plans(report).get(plan.metric_id)+ if current is None or current[0].id != artefact.id or plan.retired:+ return Response(+ {"error": "This proposal has changed. Review its latest version."}, status=status.HTTP_409_CONFLICT+ )+ policy = ReportMetricAccessPolicy(request=request, team=self.team)+ if not policy.may_read_query(plan.model_dump()) or (+ plan.eligibility_query is not None and not policy.may_read_query({"query": plan.eligibility_query})+ ):+ return Response(+ {"error": "The measurement query is not available to you."}, status=status.HTTP_403_FORBIDDEN+ )+ if plan.activated:+ return Response(self._write_response_data(artefact))+ approved = SignalReportArtefact.add_log(+ team_id=self.team.id,+ report_id=str(report.id),+ content=plan.model_copy(update={"activated": True}),+ attribution=attribution,+ )+ return Response(self._write_response_data(approved))+@extend_schema(responses={204: OpenApiResponse(description="Artefact deleted."),@@ -5019,6 +5076,7 @@ class SignalReportArtefactViewSet(artefact = cast(SignalReportArtefact, self.get_object())if artefact.type in {SignalReportArtefact.ArtefactType.TASK_RUN,+ SignalReportArtefact.ArtefactType.IMPACT_MEASUREMENT_PLAN,SignalReportArtefact.ArtefactType.WORK_CLAIM,SignalReportArtefact.ArtefactType.WORK_RELEASE,SignalReportArtefact.ArtefactType.PULL_REQUEST,diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 82723bf94a76..4e919ae47c7a 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -237,6 +237,28 @@ export const ValueFormatEnumApi = {Currency: 'currency',} as const+/**+ * * `at_most` - at_most+ * * `at_least` - at_least+ */+export type GoalDirectionEnumApi = (typeof GoalDirectionEnumApi)[keyof typeof GoalDirectionEnumApi]++export const GoalDirectionEnumApi = {+ AtMost: 'at_most',+ AtLeast: 'at_least',+} as const++/**+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval+ */+export type GoalGrainEnumApi = (typeof GoalGrainEnumApi)[keyof typeof GoalGrainEnumApi]++export const GoalGrainEnumApi = {+ WholeWindow: 'whole_window',+ PerInterval: 'per_interval',+} as const+/*** Snapshot-only metric shape for report lists.*@@ -306,6 +328,35 @@ export interface ReportMetricListApi {* @nullable*/caption?: string | null+ /**+ * Proposed threshold after release. Informational only; does not schedule a check.+ * @nullable+ */+ goal_value?: number | null+ /** Whether success means at most or at least goal_value.+ *+ * * `at_most` - at_most+ * * `at_least` - at_least */+ goal_direction?: GoalDirectionEnumApi | null+ /** Whether the goal compares with the whole query window or each chart bucket.+ *+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval */+ goal_grain?: GoalGrainEnumApi+ /**+ * Suggested days after release before assessing impact, not a monitoring schedule.+ * @minimum 1+ * @maximum 30+ * @nullable+ */+ decision_window_days?: number | null+ /**+ * Optional number of qualifying observations before assessing impact.+ * @minimum 1+ * @maximum 1000+ * @nullable+ */+ minimum_data_points?: number | null}export type SignalReportAssignmentPrStateEnumApi =@@ -735,6 +786,35 @@ export interface ReportMetricApi {* @nullable*/caption?: string | null+ /**+ * Proposed threshold after release. Informational only; does not schedule a check.+ * @nullable+ */+ goal_value?: number | null+ /** Whether success means at most or at least goal_value.+ *+ * * `at_most` - at_most+ * * `at_least` - at_least */+ goal_direction?: GoalDirectionEnumApi | null+ /** Whether the goal compares with the whole query window or each chart bucket.+ *+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval */+ goal_grain?: GoalGrainEnumApi+ /**+ * Suggested days after release before assessing impact, not a monitoring schedule.+ * @minimum 1+ * @maximum 30+ * @nullable+ */+ decision_window_days?: number | null+ /**+ * Optional number of qualifying observations before assessing impact.+ * @minimum 1+ * @maximum 1000+ * @nullable+ */+ minimum_data_points?: number | null}export interface SignalReportApi {@@ -2507,6 +2587,7 @@ export interface SignalReportStateRequestApi {* * `implementation_replacement` - Implementation Replacement* * `implementation_handover` - Implementation Handover* * `ranking_score` - Ranking Score+ * * `impact_measurement_plan` - Impact Measurement Plan*/export type SignalReportArtefactArtefactTypeEnumApi =(typeof SignalReportArtefactArtefactTypeEnumApi)[keyof typeof SignalReportArtefactArtefactTypeEnumApi]@@ -2543,6 +2624,7 @@ export const SignalReportArtefactArtefactTypeEnumApi = {ImplementationReplacement: 'implementation_replacement',ImplementationHandover: 'implementation_handover',RankingScore: 'ranking_score',+ ImpactMeasurementPlan: 'impact_measurement_plan',} as constexport type SignalReportArtefactApiContent = { [key: string]: unknown } | unknown[]@@ -2599,7 +2681,7 @@ export interface PaginatedSignalReportArtefactListApi {export interface SignalReportArtefactLogCreateApi {/** Active claim to attribute this work to. Must belong to the caller and report. */claim_id?: string- /** The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. */+ /** The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, impact_measurement_plan, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. */artefact_type: string/** The artefact payload as a JSON object or array; shape depends on artefact_type and is validated against its schema. */content: unknown@@ -4979,6 +5061,35 @@ export interface ReportMetricWriteApi {* @nullable*/caption?: string | null+ /**+ * Proposed threshold after release. Informational only; does not schedule a check.+ * @nullable+ */+ goal_value?: number | null+ /** Whether success means at most or at least goal_value.+ *+ * * `at_most` - at_most+ * * `at_least` - at_least */+ goal_direction?: GoalDirectionEnumApi | null+ /** Whether the goal compares with the whole query window or each chart bucket.+ *+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval */+ goal_grain?: GoalGrainEnumApi+ /**+ * Suggested days after release before assessing impact, not a monitoring schedule.+ * @minimum 1+ * @maximum 30+ * @nullable+ */+ decision_window_days?: number | null+ /**+ * Optional number of qualifying observations before assessing impact.+ * @minimum 1+ * @maximum 1000+ * @nullable+ */+ minimum_data_points?: number | null/** Legacy optional comparison. New report metrics must omit it. */comparison?: ReportMetricComparisonApi | null}diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 920ea3208136..40fd3f7140e7 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -948,6 +948,46 @@ export const signalsReportArtefactsDestroy = async (})}+export const getSignalsReportsArtefactsActivateCreateUrl = (projectId: string, reportId: string, id: string) => {+ return `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/${id}/activate/`+}++/**+ * Artefacts attached to a signal report.+ *+ * Two write surfaces, both gated by the `task:write` scope (already held by the agent tokens):+ *+ * - PUT edits a report's suggested reviewers: it appends a new `suggested_reviewers` status+ * artefact (latest-wins, so the new row becomes current) with bespoke reviewer enrichment,+ * merging commits/names forward from the current reviewers. Other types return 400.+ * - POST / PATCH / DELETE manage artefacts, except for the types the pipeline owns+ * (`NON_WRITABLE_ARTEFACT_TYPES`) and, for DELETE, the append-only `task_run` log; all of+ * those return 400 naming the type.+ * Log entries accumulate; status types (judgments, repo selection, suggested reviewers, channel assignments)+ * are latest-wins, so appending a new version supersedes the previous one as the report's+ * canonical status. Content is validated against the type's schema. Team scoping is+ * enforced by `safely_get_queryset`, so an artefact id from another team / a deleted+ * report 404s.+ *+ * Writes are attributed: to the task named by the `X-PostHog-Task-Id` header (set automatically+ * for sandbox agents) when present, else to the requesting user.+ * @summary Activate a proposed impact measurement+ */+export const signalsReportsArtefactsActivateCreate = async (+ projectId: string,+ reportId: string,+ id: string,+ options?: RequestInit+): Promise<SignalReportArtefactWriteResponseApi> => {+ return apiMutator<SignalReportArtefactWriteResponseApi>(+ getSignalsReportsArtefactsActivateCreateUrl(projectId, reportId, id),+ {+ ...options,+ method: 'POST',+ }+ )+}+export const getSignalsReportArtefactsDiffUrl = (projectId: string, reportId: string, id: string) => {return `/api/projects/${projectId}/signals/reports/${reportId}/artefacts/${id}/diff/`}diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 690d59ce2199..17be47fc53ab 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -456,7 +456,7 @@ export const SignalsReportArtefactsCreateBody = /* @__PURE__ */ zodartefact_type: zod.string().describe(- "The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status."+ "The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, impact_measurement_plan, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status."),content: zod.unknown()@@ -1353,6 +1353,11 @@ export const signalsScoutEditReportBodyMetricsItemUnitMax = 40export const signalsScoutEditReportBodyMetricsItemCaptionMax = 500+export const signalsScoutEditReportBodyMetricsItemGoalGrainDefault = `whole_window`+export const signalsScoutEditReportBodyMetricsItemDecisionWindowDaysMax = 30++export const signalsScoutEditReportBodyMetricsItemMinimumDataPointsMax = 1000+export const signalsScoutEditReportBodyMetricsItemComparisonOneLabelMax = 40export const signalsScoutEditReportBodyMetricsMax = 6@@ -1582,6 +1587,44 @@ export const SignalsScoutEditReportBody = /* @__PURE__ */ zod.describe('Optional context the tile cannot show, such as a filter that narrows the count or a caveat on the data. Omit it rather than restate the title, unit, or window.'),+ goal_value: zod+ .number()+ .nullish()+ .describe(+ 'Proposed threshold after release. Informational only; does not schedule a check.'+ ),+ goal_direction: zod+ .union([+ zod+ .enum(['at_most', 'at_least'])+ .describe('\* `at_most` - at_most\n\* `at_least` - at_least'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Whether success means at most or at least goal_value.\n\n\* `at_most` - at_most\n\* `at_least` - at_least'+ ),+ goal_grain: zod+ .enum(['whole_window', 'per_interval'])+ .describe('\* `whole_window` - whole_window\n\* `per_interval` - per_interval')+ .default(signalsScoutEditReportBodyMetricsItemGoalGrainDefault)+ .describe(+ 'Whether the goal compares with the whole query window or each chart bucket.\n\n\* `whole_window` - whole_window\n\* `per_interval` - per_interval'+ ),+ decision_window_days: zod+ .number()+ .min(1)+ .max(signalsScoutEditReportBodyMetricsItemDecisionWindowDaysMax)+ .nullish()+ .describe(+ 'Suggested days after release before assessing impact, not a monitoring schedule.'+ ),+ minimum_data_points: zod+ .number()+ .min(1)+ .max(signalsScoutEditReportBodyMetricsItemMinimumDataPointsMax)+ .nullish()+ .describe('Optional number of qualifying observations before assessing impact.'),comparison: zod.union([zod.object({@@ -1686,6 +1729,11 @@ export const signalsScoutEmitReportBodyMetricsItemUnitMax = 40export const signalsScoutEmitReportBodyMetricsItemCaptionMax = 500+export const signalsScoutEmitReportBodyMetricsItemGoalGrainDefault = `whole_window`+export const signalsScoutEmitReportBodyMetricsItemDecisionWindowDaysMax = 30++export const signalsScoutEmitReportBodyMetricsItemMinimumDataPointsMax = 1000+export const signalsScoutEmitReportBodyMetricsItemComparisonOneLabelMax = 40export const signalsScoutEmitReportBodyMetricsMax = 6@@ -1927,6 +1975,44 @@ export const SignalsScoutEmitReportBody = /* @__PURE__ */ zod.describe('Optional context the tile cannot show, such as a filter that narrows the count or a caveat on the data. Omit it rather than restate the title, unit, or window.'),+ goal_value: zod+ .number()+ .nullish()+ .describe(+ 'Proposed threshold after release. Informational only; does not schedule a check.'+ ),+ goal_direction: zod+ .union([+ zod+ .enum(['at_most', 'at_least'])+ .describe('\* `at_most` - at_most\n\* `at_least` - at_least'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Whether success means at most or at least goal_value.\n\n\* `at_most` - at_most\n\* `at_least` - at_least'+ ),+ goal_grain: zod+ .enum(['whole_window', 'per_interval'])+ .describe('\* `whole_window` - whole_window\n\* `per_interval` - per_interval')+ .default(signalsScoutEmitReportBodyMetricsItemGoalGrainDefault)+ .describe(+ 'Whether the goal compares with the whole query window or each chart bucket.\n\n\* `whole_window` - whole_window\n\* `per_interval` - per_interval'+ ),+ decision_window_days: zod+ .number()+ .min(1)+ .max(signalsScoutEmitReportBodyMetricsItemDecisionWindowDaysMax)+ .nullish()+ .describe(+ 'Suggested days after release before assessing impact, not a monitoring schedule.'+ ),+ minimum_data_points: zod+ .number()+ .min(1)+ .max(signalsScoutEmitReportBodyMetricsItemMinimumDataPointsMax)+ .nullish()+ .describe('Optional number of qualifying observations before assessing impact.'),comparison: zod.union([zod.object({diff --git a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsxindex b849a8295e52..cb1e67ab6e7a 100644--- a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx+++ b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx@@ -90,10 +90,41 @@ const successfulPrChecks = {const detailMocks = mswDecorator({get: {- '/api/projects/:id/signals/reports/:reportId/artefacts': (req) => [- 200,- mockArtefacts(req.params.reportId as string),- ],+ '/api/projects/:id/signals/reports/:reportId/artefacts': (req) => {+ const reportId = req.params.reportId as string+ const artefacts = mockArtefacts(reportId)+ if (reportId !== reportTabReports[0].id) {+ return [200, artefacts]+ }+ return [+ 200,+ {+ ...artefacts,+ count: artefacts.count + 1,+ results: [+ {+ id: `${reportId}-impact`,+ type: 'impact_measurement_plan',+ content: {+ metric_id: reportMetricsFixture[0].metric_id,+ title: reportMetricsFixture[0].title,+ kind: reportMetricsFixture[0].kind,+ query: reportMetricsFixture[0].query,+ value_format: reportMetricsFixture[0].value_format,+ unit: reportMetricsFixture[0].unit,+ goal_value: 50,+ goal_direction: 'at_most',+ goal_grain: 'per_interval',+ decision_window_days: 7,+ activated: false,+ },+ created_at: '2026-08-29T00:00:00Z',+ },+ ...artefacts.results,+ ],+ },+ ]+ },'/api/projects/:id/signals/reports/:reportId/artefacts/:artefactId/diff/': () => [200, mockBranchDiff()],'/api/projects/:id/signals/reports/:reportId/signals': (req) => [200,@@ -242,6 +273,58 @@ export const ReportWithMetrics: Story = {),}+export const ReportWithExpectedImpact: Story = {+ parameters: {+ mockDate: '2026-08-29',+ featureFlags: {+ [FEATURE_FLAGS.INBOX_REDESIGN]: true,+ [FEATURE_FLAGS.SIGNALS_REPORT_METRICS]: true,+ [FEATURE_FLAGS.SIGNALS_EXPECTED_IMPACT_DISPLAY]: true,+ },+ },+ render: () => (+ <Frame>+ <ReportDetail+ report={makeReport({+ ...reportTabReports[0],+ title: 'Creating an API key does nothing when validation fails',+ summary: [+ 'People cannot finish setup when the API key form hides validation errors.',+ '## Problem',+ 'The form does not show the error after the Create key button is clicked.',+ '## Expected impact',+ 'After the fix, fewer people should click Create key without getting a response.',+ '## Solution',+ 'Show the validation error in the form.',+ ].join('\n\n'),+ metrics: reportMetricsFixture.slice(0, 1),+ })}+ />+ </Frame>+ ),+}++export const ReportExpectedImpactPending: Story = {+ parameters: {+ featureFlags: {+ [FEATURE_FLAGS.INBOX_REDESIGN]: true,+ [FEATURE_FLAGS.SIGNALS_EXPECTED_IMPACT_DISPLAY]: true,+ },+ },+ render: () => (+ <Frame>+ <ReportDetail+ report={makeReport({+ ...reportTabReports[0],+ status: SignalReportStatus.IN_PROGRESS,+ summary: null,+ metrics: [],+ })}+ />+ </Frame>+ ),+}+export const ReportMinimal: Story = {render: () => (<Frame>diff --git a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx b/products/signals/frontend/inbox/components/detail/ReportDetail.tsxindex 554ec19b92a4..7c2d08a2046d 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx@@ -24,7 +24,7 @@ import { captureInboxReportAction } from '../../inboxAnalytics'import { inboxDetailLayoutLogic } from '../../logics/inboxDetailLayoutLogic'import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'import { SignalCard } from '../../SignalCard'-import { SignalReport, SignalReportStatus } from '../../types'+import { SignalReport, SignalReportArtefact, SignalReportStatus } from '../../types'import { canCreateImplementationPr } from '../../utils/reportActions'import {displayConventionalCommitTitle,@@ -51,6 +51,7 @@ import { ReportActivitySection } from './ReportActivitySection'import { ReportChart } from './ReportChart'import { ReportChecksSection } from './ReportChecksSection'import { useReportDetailActions } from './ReportDetailActions'+import { ReportExpectedImpact } from './ReportExpectedImpact'import { ReportFeedbackFooter } from './ReportFeedbackFooter'import { ReportImpactMetrics } from './ReportImpactMetrics'import { ReportPrimaryMetric } from './ReportPrimaryMetric'@@ -171,6 +172,8 @@ export function ReportDetailSkeleton(): JSX.Element {interface InboxDetailFrameProps {report: SignalReport+ impactArtefacts?: SignalReportArtefact[] | null+ onImpactApproved?: () => void/** Content closing the evidence rail, after Activity (e.g. the PR conversation). */asideFooter?: ReactNode/** Extra primary action(s) rendered after the shared report actions. */@@ -201,6 +204,8 @@ interface InboxDetailFrameProps {*/export function InboxDetailFrame({report,+ impactArtefacts,+ onImpactApproved,asideFooter,primaryAction,showFilesTab,@@ -322,12 +327,22 @@ export function InboxDetailFrame({// "Summary" tab; otherwise it sits under the "Report summary" header.// The key observation leads the evidence rail; the supporting tiles belong to the body's Impact section.const metricsEnabled = useFeatureFlag('SIGNALS_REPORT_METRICS')+ const expectedImpactEnabled = useFeatureFlag('SIGNALS_EXPECTED_IMPACT_DISPLAY')const primaryMetric = metricsEnabled ? report.metrics?.find((metric) => metric.role === 'primary') : undefinedconst supportingMetrics = metricsEnabled? (report.metrics?.filter((metric) => metric.role !== 'primary') ?? []): []const impactMetrics =supportingMetrics.length > 0 ? <ReportImpactMetrics reportId={report.id} metrics={supportingMetrics} /> : null+ const expectedImpact =+ expectedImpactEnabled && !summaryPending ? (+ <ReportExpectedImpact+ report={report}+ reportUrl={reportUrl}+ artefacts={impactArtefacts}+ onApprovalComplete={onImpactApproved}+ />+ ) : nullconst summaryColumn = (<div className="flex flex-1 flex-col gap-6">@@ -341,6 +356,7 @@ export function InboxDetailFrame({implementButton={implementButton}pullRequestNote={pullRequestNote}impactMetrics={impactMetrics}+ expectedImpact={expectedImpact}/>) : (<div className="flex flex-col gap-6">@@ -349,6 +365,7 @@ export function InboxDetailFrame({</p>{pullRequestNote}{impactMetrics}+ {expectedImpact}</div>)}{trailingCharts.length > 0 && (@@ -609,7 +626,7 @@ function OpenPullRequestButton({export function ReportDetail({ report }: { report: SignalReport }): JSX.Element {const logic = inboxReportDetailLogic({ reportId: report.id, report })const { latestCommitArtefact, reportArtefacts, selectedPullRequest } = useValues(logic)- const { selectPullRequest } = useActions(logic)+ const { selectPullRequest, loadReportArtefacts } = useActions(logic)const prUrl = safeHttpUrl(selectedPullRequest.url)const prRef = prUrl ? parsePrUrlParts(prUrl) : null@@ -639,6 +656,8 @@ export function ReportDetail({ report }: { report: SignalReport }): JSX.Elementreturn (<InboxDetailFramereport={report}+ impactArtefacts={reportArtefacts}+ onImpactApproved={loadReportArtefacts}showFilesTab={hasPr || canDiff}diffSection={canDiff && commit ? (diff --git a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.test.tsx b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.test.tsxnew file mode 100644index 000000000000..0f9b038b8bfd--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.test.tsx@@ -0,0 +1,148 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { initKeaTests } from '~/test/init'++import { signalsReportsArtefactsActivateCreate } from 'products/signals/frontend/generated/api'+import type { SignalReportArtefactWriteResponseApi } from 'products/signals/frontend/generated/api.schemas'++import { reportMetricsFixture } from '../../__mocks__/reportMetricMocks'+import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import { SignalReport, SignalReportArtefact, SignalReportStatus } from '../../types'+import { ReportExpectedImpact } from './ReportExpectedImpact'++jest.mock('./ReportExpectedImpactChart', () => ({ ReportExpectedImpactChart: () => <div>Chart</div> }))+jest.mock('products/signals/frontend/generated/api', () => ({ signalsReportsArtefactsActivateCreate: jest.fn() }))++const mockActivateMeasurement = jest.mocked(signalsReportsArtefactsActivateCreate)++const report: SignalReport = {+ id: 'report-1',+ title: 'Incomplete setup',+ summary: 'Setup fails.',+ status: SignalReportStatus.READY,+ total_weight: 0,+ signal_count: 1,+ artefact_count: 0,+ is_suggested_reviewer: false,+ created_at: '2026-08-29T00:00:00Z',+ updated_at: '2026-08-29T00:00:00Z',+}++const activatedPlanResponse: SignalReportArtefactWriteResponseApi = {+ id: 'saved-plan',+ claim_id: null,+ report_id: report.id,+ type: 'impact_measurement_plan',+ content: {},+ created_at: '2026-08-29T00:00:00Z',+ updated_at: '2026-08-29T00:00:00Z',+ task_id: null,+}++function plan(id: string, metricId: string): SignalReportArtefact {+ return {+ id,+ type: 'impact_measurement_plan',+ created_at: '2026-08-29T00:00:00Z',+ content: {+ metric_id: metricId,+ title: `Outcome ${metricId}`,+ kind: reportMetricsFixture[0].kind,+ query: reportMetricsFixture[0].query,+ goal_value: 50,+ goal_direction: 'at_most',+ goal_grain: 'per_interval',+ decision_window_days: 7,+ activated: false,+ },+ }+}++describe('ReportExpectedImpact', () => {+ beforeEach(() => {+ initKeaTests()+ inboxTaskKickoffLogic.mount()+ mockActivateMeasurement.mockReset()+ })++ afterEach(() => {+ cleanup()+ jest.restoreAllMocks()+ })++ it('saves all current proposals through Keep an eye without a separate approval button', async () => {+ mockActivateMeasurement.mockResolvedValue(activatedPlanResponse)+ const onApprovalComplete = jest.fn()+ const user = userEvent.setup()+ render(+ <ReportExpectedImpact+ report={report}+ reportUrl="https://example.test/report-1"+ artefacts={[plan('first', 'one'), plan('second', 'two')]}+ onApprovalComplete={onApprovalComplete}+ />+ )++ expect(screen.queryByText('Approve measurement')).not.toBeInTheDocument()+ await user.click(screen.getByText('Keep an eye on this for me'))++ await waitFor(() => expect(onApprovalComplete).toHaveBeenCalledTimes(1))+ expect(mockActivateMeasurement).toHaveBeenCalledTimes(2)+ expect(mockActivateMeasurement).toHaveBeenCalledWith(String(MOCK_TEAM_ID), report.id, 'first')+ expect(mockActivateMeasurement).toHaveBeenCalledWith(String(MOCK_TEAM_ID), report.id, 'second')+ expect(screen.getAllByText(/Saved measurement/)).toHaveLength(2)++ await user.click(screen.getByText('Keep an eye on this for me'))+ expect(mockActivateMeasurement).toHaveBeenCalledTimes(2)+ })++ it('keeps failed proposals available to retry without re-saving successful ones', async () => {+ mockActivateMeasurement+ .mockResolvedValueOnce(activatedPlanResponse)+ .mockRejectedValueOnce(new Error('Try again'))+ .mockResolvedValue(activatedPlanResponse)+ const user = userEvent.setup()+ render(+ <ReportExpectedImpact+ report={report}+ reportUrl="https://example.test/report-1"+ artefacts={[plan('first', 'one'), plan('second', 'two')]}+ />+ )++ await user.click(screen.getByText('Keep an eye on this for me'))+ await waitFor(() => expect(screen.getAllByText(/Saved measurement/)).toHaveLength(1))+ await user.click(screen.getByText('Keep an eye on this for me'))++ await waitFor(() => expect(screen.getAllByText(/Saved measurement/)).toHaveLength(2))+ expect(mockActivateMeasurement.mock.calls.map(([, , id]) => id)).toEqual(['first', 'second', 'second'])+ })++ it('does not offer follow-ups without a proposal', () => {+ render(<ReportExpectedImpact report={report} reportUrl="https://example.test/report-1" artefacts={[]} />)++ expect(screen.getByText('Keep an eye on this for me').closest('button')).toHaveAttribute(+ 'aria-disabled',+ 'true'+ )+ expect(screen.getByText('Suggest different metrics').closest('button')).toBeEnabled()+ })++ it('bounds the number of charts and approval requests for older oversized reports', async () => {+ mockActivateMeasurement.mockResolvedValue(activatedPlanResponse)+ const user = userEvent.setup()+ const artefacts = Array.from({ length: 7 }, (_, index) => plan(`plan-${index}`, `outcome-${index}`))+ render(<ReportExpectedImpact report={report} reportUrl="https://example.test/report-1" artefacts={artefacts} />)++ expect(screen.getAllByText('Chart')).toHaveLength(6)+ expect(screen.queryByText(/Outcome outcome-6/)).not.toBeInTheDocument()++ await user.click(screen.getByText('Keep an eye on this for me'))+ await waitFor(() => expect(mockActivateMeasurement).toHaveBeenCalledTimes(6))+ })+})diff --git a/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.tsx b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.tsxnew file mode 100644index 000000000000..06559b5298af--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportExpectedImpact.tsx@@ -0,0 +1,291 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonButton, LemonModal, LemonTextArea, lemonToast } from '@posthog/lemon-ui'++import { signalsReportsArtefactsActivateCreate } from 'products/signals/frontend/generated/api'+import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'++import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import { SignalReport, SignalReportArtefact } from '../../types'+import { asReportMetricSeriesQuery, formatReportMetricValue } from '../../utils/reportMetrics'+import { ReportExpectedImpactChart } from './ReportExpectedImpactChart'++const MAX_VISIBLE_MEASUREMENT_PLANS = 6++interface MeasurementPlan {+ metric_id: string+ title: string+ kind: ReportMetricApi['kind']+ query?: unknown+ value_format?: ReportMetricApi['value_format']+ unit?: string | null+ goal_value?: number | null+ goal_direction?: ReportMetricApi['goal_direction']+ goal_grain?: 'whole_window' | 'per_interval'+ decision_window_days?: number | null+ minimum_data_points?: number | null+ eligibility_query?: unknown+ activated?: boolean+ retired?: boolean+}++function planFromArtefact(artefact: SignalReportArtefact): MeasurementPlan | null {+ if (artefact.type !== 'impact_measurement_plan') {+ return null+ }+ const content: unknown = artefact.content+ if (+ !content ||+ typeof content !== 'object' ||+ !('metric_id' in content) ||+ typeof content.metric_id !== 'string' ||+ !('title' in content) ||+ typeof content.title !== 'string'+ ) {+ return null+ }+ return content as MeasurementPlan+}++export function ReportExpectedImpact({+ report,+ reportUrl,+ artefacts,+ onApprovalComplete,+}: {+ report: SignalReport+ reportUrl: string+ artefacts?: SignalReportArtefact[] | null+ onApprovalComplete?: () => void+}): JSX.Element {+ const [modalOpen, setModalOpen] = useState(false)+ const [description, setDescription] = useState('')+ const [saving, setSaving] = useState(false)+ const [savedIds, setSavedIds] = useState<Set<string>>(() => new Set())+ const { openReportDiscussion, discussReport } = useActions(inboxTaskKickoffLogic)+ const { aiConsentDisabledReason, currentProjectId, isDiscussing, isCreatingPr } = useValues(inboxTaskKickoffLogic)+ const newest = new Map<string, { artefact: SignalReportArtefact; plan: MeasurementPlan }>()+ for (const artefact of artefacts ?? []) {+ const plan = planFromArtefact(artefact)+ if (plan && !newest.has(plan.metric_id)) {+ newest.set(plan.metric_id, { artefact, plan })+ }+ }+ const measurements: {+ metric: ReportMetricApi+ artefact: SignalReportArtefact | null+ eligibilityQuery?: unknown+ goalGrain: 'whole_window' | 'per_interval'+ activated: boolean | undefined+ }[] = [...newest.values()]+ .filter(({ plan }) => !plan.retired)+ .slice(0, MAX_VISIBLE_MEASUREMENT_PLANS)+ .map(({ plan, artefact }) => ({+ metric: {+ metric_id: plan.metric_id,+ title: plan.title,+ kind: plan.kind ?? 'custom',+ query: plan.query,+ value_format: plan.value_format,+ unit: plan.unit,+ goal_value: plan.goal_value,+ goal_direction: plan.goal_direction,+ decision_window_days: plan.decision_window_days,+ minimum_data_points: plan.minimum_data_points,+ },+ artefact,+ eligibilityQuery: plan.eligibility_query,+ goalGrain: plan.goal_grain ?? 'whole_window',+ activated: plan.activated || savedIds.has(artefact.id),+ }))+ if (artefacts !== null) {+ for (const metric of report.metrics ?? []) {+ if (measurements.length >= MAX_VISIBLE_MEASUREMENT_PLANS) {+ break+ }+ if (metric.goal_value != null && metric.goal_direction && !newest.has(metric.metric_id)) {+ measurements.push({ metric, artefact: null, goalGrain: 'whole_window', activated: false })+ }+ }+ }++ const submit = (): void => {+ const request = description.trim()+ if (!request) {+ return+ }+ openReportDiscussion(report, reportUrl)+ discussReport(report, reportUrl, request, undefined, 'measurement_plan')+ setModalOpen(false)+ }++ const availablePlans = measurements.filter(({ artefact, metric }) => artefact && metric.query != null)+ const pendingPlans = availablePlans.flatMap(({ artefact, activated }) => (artefact && !activated ? [artefact] : []))++ const keepAnEyeOnThis = async (): Promise<void> => {+ if (saving || currentProjectId == null) {+ return+ }+ if (!pendingPlans.length) {+ lemonToast.info('Measurements are saved. Monitoring is coming soon; nothing is being tracked yet.')+ return+ }+ setSaving(true)+ try {+ const results = await Promise.allSettled(+ pendingPlans.map((artefact) =>+ signalsReportsArtefactsActivateCreate(String(currentProjectId), report.id, artefact.id)+ )+ )+ const successfulIds = pendingPlans+ .filter((_, index) => results[index].status === 'fulfilled')+ .map((artefact) => artefact.id)+ if (successfulIds.length) {+ setSavedIds((current) => new Set([...current, ...successfulIds]))+ onApprovalComplete?.()+ }+ if (successfulIds.length !== pendingPlans.length) {+ lemonToast.error('Some measurements could not be saved. Please try again.')+ } else {+ lemonToast.info('Measurements saved. Monitoring is coming soon; nothing is being tracked yet.')+ }+ } finally {+ setSaving(false)+ }+ }++ return (+ <div className="flex flex-col gap-3 rounded-lg border p-4" data-attr="report-expected-impact">+ {measurements.length ? (+ measurements.map(({ metric, artefact, eligibilityQuery, goalGrain, activated }) => {+ const query = asReportMetricSeriesQuery(metric)+ return (+ <div key={metric.metric_id} className="flex flex-col gap-2">+ <p className="m-0 font-semibold">+ {metric.title}:{' '}+ {metric.goal_value == null+ ? 'goal unavailable'+ : `${metric.goal_direction === 'at_most' ? 'at most' : 'at least'} ${formatReportMetricValue(metric, metric.goal_value) ?? metric.goal_value}`}+ </p>+ <p className="m-0 text-secondary text-sm">+ {activated ? 'Saved measurement' : 'Proposed measurement'} ·{' '}+ {goalGrain === 'per_interval'+ ? 'Goal per chart interval'+ : 'Goal for the full query window'}+ </p>+ {query ? (+ <ReportExpectedImpactChart+ reportId={report.id}+ metric={metric}+ query={query.source}+ goalGrain={goalGrain}+ version={artefact?.id ?? 'legacy'}+ />+ ) : (+ <p className="text-tertiary m-0">The query is not available to you.</p>+ )}+ {(metric.decision_window_days || metric.minimum_data_points) && (+ <p className="m-0 text-secondary text-sm">+ Suggested decision:{' '}+ {[+ metric.decision_window_days &&+ `${metric.decision_window_days} days after release`,+ metric.minimum_data_points &&+ `${metric.minimum_data_points} qualifying observations`,+ ]+ .filter(Boolean)+ .join(' and ')}+ .+ </p>+ )}+ {metric.query != null && (+ <details className="text-sm">+ <summary className="cursor-pointer">View measurement query</summary>+ <pre className="max-h-64 overflow-auto rounded bg-surface-secondary p-2 text-xs">+ {JSON.stringify(+ eligibilityQuery+ ? { metric: metric.query, qualifying_opportunities: eligibilityQuery }+ : metric.query,+ null,+ 2+ )}+ </pre>+ </details>+ )}+ </div>+ )+ })+ ) : (+ <p className="m-0 text-secondary text-sm">+ {artefacts === null+ ? 'Loading proposed measurements…'+ : 'No measurement proposed yet. Ask AI to find a metric and set a goal.'}+ </p>+ )}+ <div className="flex flex-wrap gap-2">+ <LemonButton+ data-attr="report-expected-impact-follow-up"+ type="primary"+ size="small"+ loading={saving}+ disabledReason={+ artefacts === null+ ? 'Loading proposed measurements…'+ : availablePlans.length === 0+ ? 'Add a proposed measurement first.'+ : currentProjectId == null+ ? 'Select a project to save measurements.'+ : undefined+ }+ onClick={keepAnEyeOnThis}+ >+ Keep an eye on this for me+ </LemonButton>+ <LemonButton+ data-attr="report-expected-impact-suggest-metrics"+ type="secondary"+ size="small"+ onClick={() => setModalOpen(true)}+ >+ Suggest different metrics+ </LemonButton>+ </div>+ <LemonModal+ isOpen={modalOpen}+ onClose={() => setModalOpen(false)}+ title="Describe what success would look like"+ width={560}+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setModalOpen(false)}>+ Cancel+ </LemonButton>+ <LemonButton+ data-attr="report-expected-impact-submit-suggestion"+ type="primary"+ onClick={submit}+ loading={isDiscussing}+ disabledReason={+ aiConsentDisabledReason ??+ (isCreatingPr ? 'An implementation is starting.' : undefined) ??+ (!description.trim() ? 'Describe the outcome first.' : undefined)+ }+ >+ Ask AI to update report+ </LemonButton>+ </>+ }+ >+ <LemonTextArea+ value={description}+ onChange={setDescription}+ placeholder="For example, fewer users should see the not-found page within a week."+ rows={4}+ maxLength={2000}+ data-attr="report-expected-impact-description"+ />+ </LemonModal>+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ReportExpectedImpactChart.tsx b/products/signals/frontend/inbox/components/detail/ReportExpectedImpactChart.tsxnew file mode 100644index 000000000000..29669c377644--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportExpectedImpactChart.tsx@@ -0,0 +1,106 @@+import { useValues } from 'kea'++import { LemonSkeleton } from '@posthog/lemon-ui'++import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'++import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'++import {+ asReportMetricAggregateQuery,+ asReportMetricSeriesQuery,+ formatReportMetricValue,+ reportMetricAggregate,+ reportMetricChartType,+ reportMetricSeriesPoints,+} from '../../utils/reportMetrics'+import { ReportObservationChart } from './ReportObservationChart'++export function ReportExpectedImpactChart({+ reportId,+ metric,+ query,+ goalGrain,+ version,+}: {+ reportId: string+ metric: ReportMetricApi+ query: NonNullable<ReturnType<typeof asReportMetricSeriesQuery>>['source']+ goalGrain: 'whole_window' | 'per_interval'+ version: string+}): JSX.Element {+ const props: DataNodeLogicProps = {+ key: `ReportMetricSeries.${reportId}.${metric.metric_id}.${version}`,+ query,+ dataNodeCollectionId: `report-metrics-${reportId}`,+ autoLoad: true,+ }+ const { response, responseError, responseLoading } = useValues(dataNodeLogic(props))+ const points = reportMetricSeriesPoints(response)+ const aggregateQuery = asReportMetricAggregateQuery(metric.query)+ const aggregateProps: DataNodeLogicProps = {+ key: `ImpactMeasurementTotal.${reportId}.${metric.metric_id}.${version}`,+ query: aggregateQuery?.source ?? query,+ dataNodeCollectionId: `report-metrics-${reportId}`,+ autoLoad: goalGrain === 'whole_window' && aggregateQuery !== null,+ }+ const {+ response: aggregateResponse,+ responseError: aggregateError,+ responseLoading: aggregateLoading,+ } = useValues(dataNodeLogic(aggregateProps))+ const aggregate = reportMetricAggregate(aggregateResponse)++ if (responseLoading && !response) {+ return <LemonSkeleton className="h-36 w-full" />+ }+ if (responseError) {+ return <p className="text-tertiary m-0">Couldn't load the chart. Refresh the page to try again.</p>+ }+ if (!points) {+ return <p className="text-tertiary m-0">No chart data for this window. The goal is still a proposal.</p>+ }++ const goal = metric.goal_value+ const max = Math.max(aggregate ?? 0, goal ?? 0, 1)++ return (+ <div className="flex flex-col gap-2">+ <ReportObservationChart+ metric={metric}+ points={points}+ type={reportMetricChartType(metric)}+ interval={query.interval}+ goalValue={goalGrain === 'per_interval' ? (goal ?? undefined) : undefined}+ />+ {goalGrain === 'whole_window' && goal != null && (+ <div className="text-xs text-secondary">+ <div className="mb-1 flex justify-between">+ <span>+ {aggregateLoading && aggregateResponse == null+ ? 'Loading current total'+ : aggregateError+ ? 'Current total unavailable'+ : aggregate == null+ ? 'No total for this window'+ : `Current window: ${formatReportMetricValue(metric, aggregate)}`}+ </span>+ <span>Goal: {formatReportMetricValue(metric, goal)}</span>+ </div>+ <div className="relative h-2 rounded bg-fill-highlight-50" aria-hidden>+ {aggregate != null && (+ <div+ className="absolute left-0 top-0 h-full rounded bg-accent"+ style={{ width: `${Math.min(100, (aggregate / max) * 100)}%` }}+ />+ )}+ <div+ className="absolute top-[-3px] h-4 w-0.5 bg-border-bold"+ style={{ left: `${Math.max(0, Math.min(100, (goal / max) * 100))}%` }}+ />+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsx b/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsxindex 5d3b30cae822..07454af15449 100644--- a/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportObservationChart.tsx@@ -42,11 +42,13 @@ export function ReportObservationChart({points,type,interval,+ goalValue,}: {metric: ReportMetricApipoints: ReportMetricSeriesPointstype: ReportMetricChartTypeinterval: IntervalType | null | undefined+ goalValue?: number}): JSX.Element {const theme = useChartTheme()const { timezone } = useValues(teamLogic)@@ -73,17 +75,19 @@ export function ReportObservationChart({const lineConfig = useChartConfig<TimeSeriesLineChartConfig>(() => ({xAxis,+ 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]+ [xAxis, yAxisValueFormatter, valueFormatter, goalValue])const barConfig = useChartConfig<TimeSeriesBarChartConfig>(() => ({xAxis,+ goalLines: goalValue === undefined ? undefined : [{ value: goalValue, label: 'Goal' }],yAxis: { tickFormatter: yAxisValueFormatter },...AXIS_CHROME,showCrosshair: false,@@ -93,7 +97,7 @@ export function ReportObservationChart({margins: BAR_MARGINS,tooltip: { pinnable: false, hitArea: 'band', valueFormatter },}),- [xAxis, yAxisValueFormatter, valueFormatter]+ [xAxis, yAxisValueFormatter, valueFormatter, goalValue])return (diff --git a/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsx b/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsxindex 099f5b0ed6b0..3ceb522b7db8 100644--- a/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsx@@ -49,6 +49,7 @@ interface ReportSummaryBodyProps {* gets an Impact section for them ahead of Solution, so the storyboard order holds.*/impactMetrics?: ReactNode+ expectedImpact?: ReactNode}/**@@ -61,10 +62,12 @@ export function ReportSummaryBody({implementButton,pullRequestNote,impactMetrics,+ expectedImpact,}: ReportSummaryBodyProps): JSX.Element {const parsed = useMemo(() => parseReportSummary(summary), [summary])const hasSolutionSection = parsed.sections.some((section) => section.kind === 'solution')const hasImpactSection = parsed.sections.some((section) => section.kind === 'impact')+ const hasExpectedImpactSection = parsed.sections.some((section) => section.kind === 'expected-impact')const solutionIndex = parsed.sections.findIndex((section) => section.kind === 'solution')const impactFallback =impactMetrics && !hasImpactSection ? (@@ -73,6 +76,12 @@ export function ReportSummaryBody({{impactMetrics}</section>) : null+ const expectedImpactFallback = expectedImpact && !hasExpectedImpactSection && (+ <section className="flex flex-col gap-2">+ <h2 className="m-0 text-lg font-semibold">Expected impact</h2>+ {expectedImpact}+ </section>+ )if (parsed.sections.length === 0) {return (@@ -83,6 +92,7 @@ export function ReportSummaryBody({chartPlacements={chartPlacements}/>{impactFallback}+ {expectedImpactFallback}{pullRequestNote}</div>)@@ -101,6 +111,7 @@ export function ReportSummaryBody({{parsed.sections.map((section, index) => (<Fragment key={`${section.kind}-${section.bodyOffset}`}>{index === solutionIndex && impactFallback}+ {index === solutionIndex && expectedImpactFallback}<section className="flex flex-col gap-2"><h2 className="m-0 text-lg font-semibold">{section.heading}</h2>{section.kind === 'impact' && impactMetrics && <div className="mb-1">{impactMetrics}</div>}@@ -109,6 +120,7 @@ export function ReportSummaryBody({sourceOffset={section.bodyOffset}chartPlacements={chartPlacements}/>+ {section.kind === 'expected-impact' && expectedImpact}{section.kind === 'solution' && pullRequestNote && (<div className="mt-2">{pullRequestNote}</div>)}@@ -119,6 +131,7 @@ export function ReportSummaryBody({</Fragment>))}{!hasSolutionSection && impactFallback}+ {!hasSolutionSection && expectedImpactFallback}{!hasSolutionSection && pullRequestNote}</div>)diff --git a/products/signals/frontend/inbox/components/detail/artefactTypes.ts b/products/signals/frontend/inbox/components/detail/artefactTypes.tsindex 7181ea910850..898d1d1dc8cb 100644--- a/products/signals/frontend/inbox/components/detail/artefactTypes.ts+++ b/products/signals/frontend/inbox/components/detail/artefactTypes.ts@@ -184,6 +184,7 @@ export function selectVisibleReportActivity(artefacts: SignalReportArtefact[]):return artefacts.filter((artefact) =>artefact.type !== 'implementation_dispatch' &&+ artefact.type !== 'impact_measurement_plan' &&(artefact.type !== 'implementation_handover' ||(artefact.content as ImplementationHandoverContent).status !== 'processing'))diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.tsindex a30f7ea59b5c..07dd57e1c1d4 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts@@ -190,6 +190,22 @@ describe('inboxTaskKickoffLogic', () => {})+ it('sends app-built instructions to the agent but only the reader text as the question', async () => {+ await expectLogic(logic, () =>+ logic.actions.discussReport(+ report,+ 'https://example.com/report',+ 'Fewer failed checkouts',+ "Propose a goal. The user's idea: Fewer failed checkouts"+ )+ ).toFinishAllListeners()++ expect(createdTasks[0]).toMatchObject({+ description: expect.stringContaining("Propose a goal. The user's idea: Fewer failed checkouts"),+ signal_report_discussion_question: 'Fewer failed checkouts',+ })+ })+it('warms a repo-less sandbox for the report when Ask AI opens, and only once per report', async () => {warmResponse = { task_id: 'warm-task', run_id: 'warm-run' }@@ -510,6 +526,19 @@ describe('inboxTaskKickoffLogic', () => {describe('buildDiscussReportPrompt', () => {const url = 'https://app.posthog.com/project/1/inbox/report-1'+ it('keeps measurement edits separate from state changes on a resolved report', () => {+ const prompt = buildDiscussReportPrompt(+ makeReport({ status: SignalReportStatus.RESOLVED }),+ url,+ 'Fewer failed checkouts',+ 'measurement_plan'+ )+ expect(prompt).toContain('Fewer failed checkouts')+ expect(prompt).toContain('inbox-report-artefacts-create')+ expect(prompt).toContain('Do not create a check, start monitoring, change the report state')+ expect(prompt).not.toContain('inbox-reports-set-state')+ })+it.each([SignalReportStatus.READY, SignalReportStatus.PENDING_INPUT])('tells the agent to carry out actions for a %s report',(status) => {diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex e4d667edc39f..a05413b48464 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -167,7 +167,15 @@ export function isActionCapableReport(report: SignalReport): boolean {)}-export function buildDiscussReportPrompt(report: SignalReport | null, reportUrl: string, question: string): string {+export function buildDiscussReportPrompt(+ report: SignalReport | null,+ reportUrl: string,+ question: string,+ intent?: 'measurement_plan'+): string {+ if (intent === 'measurement_plan' && report !== null) {+ return `A person asked you to revise the proposed measurement on the PostHog Inbox report at ${reportUrl}. Their description of success is:\n\n${question.trim()}\n\nRead the report and its impact_measurement_plan artefacts first. Investigate which data can test this outcome. Use inbox-report-artefacts-create to append one impact_measurement_plan per measurable outcome, with a stable metric_id, a bounded live Trends query, goal_value, goal_direction, goal_grain, and decision_window_days. Set minimum_data_points only if you also supply an eligibility_query counting qualifying opportunities (not failures). To revise a plan, append a new version with the same metric_id; keep other plans. Do not activate a plan: a person reviews it. If the requested outcome is not measurable, explain what is missing instead of inventing a query or threshold. Do not create a check, start monitoring, change the report state, or open a PR. You may use inbox-reports-update to clarify the Expected impact prose without changing other sections.\n\n${NO_CHECKOUT_INSTRUCTIONS}`+ }// The task is already linked to the report, but including the URL lets the agent open and read// the full report itself. The user's message follows after a blank line for clear separation.// `null` means the caller could not confirm the report's current state (the kickoff refetch@@ -385,8 +393,12 @@ export interface inboxTaskKickoffLogicActions {discussReport: (report: SignalReport,reportUrl: string,- question: string+ question: string,+ agentQuestion?: string,+ intent?: 'measurement_plan') => {+ agentQuestion: string | undefined+ intent: 'measurement_plan' | undefinedquestion: stringreport: SignalReportreportUrl: string@@ -485,7 +497,21 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([runId,streamKey,}),- discussReport: (report: SignalReport, reportUrl: string, question: string) => ({ report, reportUrl, question }),+ // `question` is the reader's own text: the chat shows it and the report's scout receives it as+ // reader feedback. `agentQuestion` replaces it in the agent prompt only, for app-built requests.+ discussReport: (+ report: SignalReport,+ reportUrl: string,+ question: string,+ agentQuestion?: string,+ intent?: 'measurement_plan'+ ) => ({+ report,+ reportUrl,+ question,+ agentQuestion,+ intent,+ }),createPrFromReport: (report: SignalReport, feedback?: string) => ({ report, feedback }),warmReportDiscussion: (report: SignalReport) => ({ report }),releaseReportDiscussionWarm: true,@@ -668,7 +694,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([actions.setActiveCreation({ streamKey: resolvedStreamKey ?? runId, taskId, runId })actions.openSidePanel(SidePanelTab.Max, REPORT_AI_PANEL)},- discussReport: async ({ report, reportUrl, question }) => {+ discussReport: async ({ report, reportUrl, question, agentQuestion, intent }) => {// The CTAs carry this as a `disabledReason`, but Discuss also submits on Enter, and the// run endpoint enforces no consent of its own.if (values.aiConsentDisabledReason) {@@ -707,7 +733,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([}try {const prompt = wrapWithPosthogContext(- buildDiscussReportPrompt(currentReport, reportUrl, question),+ buildDiscussReportPrompt(currentReport, reportUrl, agentQuestion ?? question, intent),contextItems)const warmLease = values.reportWarmLease?.reportId === report.id ? values.reportWarmLease : nulldiff --git a/products/signals/frontend/inbox/utils/reportSummary.test.ts b/products/signals/frontend/inbox/utils/reportSummary.test.tsindex 95031f0abfc7..f88afb664ae6 100644--- a/products/signals/frontend/inbox/utils/reportSummary.test.ts+++ b/products/signals/frontend/inbox/utils/reportSummary.test.ts@@ -27,6 +27,7 @@ describe('parseReportSummary', () => {['## Fix', 'solution', 'Solution'],['## Recommended fix:', 'solution', 'Solution'],['### The problem', 'problem', 'Problem'],+ ['## Expected impact', 'expected-impact', 'Expected impact'],['## Next steps', 'other', 'Next steps'],])('maps the heading %s to the %s section', (heading, kind, label) => {const [section] = parseReportSummary(`Lead.\n\n${heading}\n\nBody.`).sectionsdiff --git a/products/signals/frontend/inbox/utils/reportSummary.ts b/products/signals/frontend/inbox/utils/reportSummary.tsindex 5fdfa3e1ac28..3deb2c2dd6b6 100644--- a/products/signals/frontend/inbox/utils/reportSummary.ts+++ b/products/signals/frontend/inbox/utils/reportSummary.ts@@ -9,7 +9,7 @@import { fromMarkdown } from 'mdast-util-from-markdown'-export type ReportSummarySectionKind = 'problem' | 'impact' | 'solution' | 'other'+export type ReportSummarySectionKind = 'problem' | 'impact' | 'expected-impact' | 'solution' | 'other'export interface ReportSummarySection {kind: ReportSummarySectionKind@@ -32,6 +32,7 @@ export interface ParsedReportSummary {const SECTION_LABELS: Record<Exclude<ReportSummarySectionKind, 'other'>, string> = {problem: 'Problem',impact: 'Impact',+ 'expected-impact': 'Expected impact',solution: 'Solution',}@@ -40,6 +41,7 @@ const SECTION_KINDS: Record<string, Exclude<ReportSummarySectionKind, 'other'>>problem: 'problem','the problem': 'problem',impact: 'impact',+ 'expected impact': 'expected-impact',solution: 'solution',fix: 'solution','the fix': 'solution',diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 61b514344379..71b5da02926c 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -36,9 +36,14 @@ tools:has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recordedautomatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remoteby other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is- always a mistake), `note` (free-form: note). Status types are latest-wins — appending a new version- supersedes the previous one as the report's canonical status: `priority_judgment` (explanation, priority- P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment`+ always a mistake), `note` (free-form: note). `impact_measurement_plan` stores one proposed outcome:+ metric_id, title, kind, bounded InsightVizNode Trends query, goal_value, goal_direction, goal_grain+ (whole_window or per_interval), and decision_window_days or minimum_data_points (which requires an+ eligibility_query counting qualifying opportunities). Read existing plans first, then append a new version+ with the same metric_id to revise one without changing the others. Leave activated=false; approval is a+ separate action. This proposal never starts monitoring. Status types are latest-wins — appending a new+ version supersedes the previous one as the report's canonical status: `priority_judgment` (explanation,+ priority P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment`(choice), `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Statusjudgments are consequential, not advisory: the canonical priority/actionability steer what humans and agentspick up next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON@@ -1211,6 +1216,9 @@ tools:signals-report-pr-review-comments-create:operation: signals_report_pr_review_comments_createenabled: false+ signals-reports-artefacts-activate-create:+ operation: signals_reports_artefacts_activate_create+ enabled: falsesignals-reports-available-reviewers-retrieve:operation: signals_reports_available_reviewers_retrieveenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1ebc097c2d9b..f2d0f5b3a7a8 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6528,7 +6528,7 @@}},"inbox-report-artefacts-create": {- "description": "Append an artefact to a signal report so it reads as a living document. Everything is append-only. Log types accumulate — `code_reference` (a contiguous span of source lines, at most 20: file_path, start_line, end_line, contents, relevance_note; a single line is just start_line == end_line), `commit` (one commit that has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recorded automatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remote by other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is always a mistake), `note` (free-form: note). Status types are latest-wins — appending a new version supersedes the previous one as the report's canonical status: `priority_judgment` (explanation, priority P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment` (choice), `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Status judgments are consequential, not advisory: the canonical priority/actionability steer what humans and agents pick up next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON object matching the chosen type and is validated against its schema. Writes are attributed to your task automatically. Pass claim_id to associate the work with your current claim; stale or foreign claims are rejected. Returns the created artefact including its id.",+ "description": "Append an artefact to a signal report so it reads as a living document. Everything is append-only. Log types accumulate — `code_reference` (a contiguous span of source lines, at most 20: file_path, start_line, end_line, contents, relevance_note; a single line is just start_line == end_line), `commit` (one commit that has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recorded automatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remote by other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is always a mistake), `note` (free-form: note). `impact_measurement_plan` stores one proposed outcome: metric_id, title, kind, bounded InsightVizNode Trends query, goal_value, goal_direction, goal_grain (whole_window or per_interval), and decision_window_days or minimum_data_points (which requires an eligibility_query counting qualifying opportunities). Read existing plans first, then append a new version with the same metric_id to revise one without changing the others. Leave activated=false; approval is a separate action. This proposal never starts monitoring. Status types are latest-wins — appending a new version supersedes the previous one as the report's canonical status: `priority_judgment` (explanation, priority P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment` (choice), `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Status judgments are consequential, not advisory: the canonical priority/actionability steer what humans and agents pick up next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON object matching the chosen type and is validated against its schema. Writes are attributed to your task automatically. Pass claim_id to associate the work with your current claim; stale or foreign claims are rejected. Returns the created artefact including its id.","category": "Signals","feature": "signals","summary": "Append an artefact to a report",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f0d3ae0b333c..9849460b9bbd 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6725,7 +6725,7 @@}},"inbox-report-artefacts-create": {- "description": "Append an artefact to a signal report so it reads as a living document. Everything is append-only. Log types accumulate — `code_reference` (a contiguous span of source lines, at most 20: file_path, start_line, end_line, contents, relevance_note; a single line is just start_line == end_line), `commit` (one commit that has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recorded automatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remote by other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is always a mistake), `note` (free-form: note). Status types are latest-wins — appending a new version supersedes the previous one as the report's canonical status: `priority_judgment` (explanation, priority P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment` (choice), `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Status judgments are consequential, not advisory: the canonical priority/actionability steer what humans and agents pick up next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON object matching the chosen type and is validated against its schema. Writes are attributed to your task automatically. Pass claim_id to associate the work with your current claim; stale or foreign claims are rejected. Returns the created artefact including its id.",+ "description": "Append an artefact to a signal report so it reads as a living document. Everything is append-only. Log types accumulate — `code_reference` (a contiguous span of source lines, at most 20: file_path, start_line, end_line, contents, relevance_note; a single line is just start_line == end_line), `commit` (one commit that has already been pushed to a remote branch: repository, branch, commit_sha, message — usually recorded automatically when you push via git_signed_commit. Only create one yourself for a commit pushed to a remote by other means; never record a commit that is not on a remote branch — an unpushed or local-only commit is always a mistake), `note` (free-form: note). `impact_measurement_plan` stores one proposed outcome: metric_id, title, kind, bounded InsightVizNode Trends query, goal_value, goal_direction, goal_grain (whole_window or per_interval), and decision_window_days or minimum_data_points (which requires an eligibility_query counting qualifying opportunities). Read existing plans first, then append a new version with the same metric_id to revise one without changing the others. Leave activated=false; approval is a separate action. This proposal never starts monitoring. Status types are latest-wins — appending a new version supersedes the previous one as the report's canonical status: `priority_judgment` (explanation, priority P0–P4), `actionability_judgment` (explanation, actionability, already_addressed), `safety_judgment` (choice), `repo_selection` (repository, reason), `suggested_reviewers` (a list of {github_login}). Status judgments are consequential, not advisory: the canonical priority/actionability steer what humans and agents pick up next, and PostHog's automation uses them when deciding which reports to act on. `content` is a JSON object matching the chosen type and is validated against its schema. Writes are attributed to your task automatically. Pass claim_id to associate the work with your current claim; stale or foreign claims are rejected. Returns the created artefact including its id.","category": "Signals","feature": "signals","summary": "Append an artefact to a report",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 886632426a4b..c682b3d8975c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -35087,6 +35087,30 @@ export namespace Schemas {Currency: 'currency',} as const;+ /**+ * * `at_most` - at_most+ * * `at_least` - at_least+ */+ export type GoalDirectionEnum = typeof GoalDirectionEnum[keyof typeof GoalDirectionEnum];+++ export const GoalDirectionEnum = {+ AtMost: 'at_most',+ AtLeast: 'at_least',+ } as const;++ /**+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval+ */+ export type GoalGrainEnum = typeof GoalGrainEnum[keyof typeof GoalGrainEnum];+++ export const GoalGrainEnum = {+ WholeWindow: 'whole_window',+ PerInterval: 'per_interval',+ } as const;+export interface ReportMetricComparison {/** Baseline or previous value, formatted like the current value. */value: number;@@ -35166,6 +35190,35 @@ export namespace Schemas {* @nullable*/caption?: string | null;+ /**+ * Proposed threshold after release. Informational only; does not schedule a check.+ * @nullable+ */+ goal_value?: number | null;+ /** Whether success means at most or at least goal_value.+ *+ * * `at_most` - at_most+ * * `at_least` - at_least */+ goal_direction?: GoalDirectionEnum | null;+ /** Whether the goal compares with the whole query window or each chart bucket.+ *+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval */+ goal_grain?: GoalGrainEnum;+ /**+ * Suggested days after release before assessing impact, not a monitoring schedule.+ * @minimum 1+ * @maximum 30+ * @nullable+ */+ decision_window_days?: number | null;+ /**+ * Optional number of qualifying observations before assessing impact.+ * @minimum 1+ * @maximum 1000+ * @nullable+ */+ minimum_data_points?: number | null;/** Legacy optional comparison. New report metrics must omit it. */comparison?: ReportMetricComparison | null;}@@ -66872,6 +66925,7 @@ export namespace Schemas {* * `implementation_replacement` - Implementation Replacement* * `implementation_handover` - Implementation Handover* * `ranking_score` - Ranking Score+ * * `impact_measurement_plan` - Impact Measurement Plan*/export type SignalReportArtefactArtefactTypeEnum = typeof SignalReportArtefactArtefactTypeEnum[keyof typeof SignalReportArtefactArtefactTypeEnum];@@ -66908,6 +66962,7 @@ export namespace Schemas {ImplementationReplacement: 'implementation_replacement',ImplementationHandover: 'implementation_handover',RankingScore: 'ranking_score',+ ImpactMeasurementPlan: 'impact_measurement_plan',} as const;export type SignalActorKindEnum = typeof SignalActorKindEnum[keyof typeof SignalActorKindEnum];@@ -67173,6 +67228,35 @@ export namespace Schemas {* @nullable*/caption?: string | null;+ /**+ * Proposed threshold after release. Informational only; does not schedule a check.+ * @nullable+ */+ goal_value?: number | null;+ /** Whether success means at most or at least goal_value.+ *+ * * `at_most` - at_most+ * * `at_least` - at_least */+ goal_direction?: GoalDirectionEnum | null;+ /** Whether the goal compares with the whole query window or each chart bucket.+ *+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval */+ goal_grain?: GoalGrainEnum;+ /**+ * Suggested days after release before assessing impact, not a monitoring schedule.+ * @minimum 1+ * @maximum 30+ * @nullable+ */+ decision_window_days?: number | null;+ /**+ * Optional number of qualifying observations before assessing impact.+ * @minimum 1+ * @maximum 1000+ * @nullable+ */+ minimum_data_points?: number | null;}export type SignalReportAssignmentPrStateEnum = typeof SignalReportAssignmentPrStateEnum[keyof typeof SignalReportAssignmentPrStateEnum];@@ -87091,6 +87175,35 @@ export namespace Schemas {* @nullable*/caption?: string | null;+ /**+ * Proposed threshold after release. Informational only; does not schedule a check.+ * @nullable+ */+ goal_value?: number | null;+ /** Whether success means at most or at least goal_value.+ *+ * * `at_most` - at_most+ * * `at_least` - at_least */+ goal_direction?: GoalDirectionEnum | null;+ /** Whether the goal compares with the whole query window or each chart bucket.+ *+ * * `whole_window` - whole_window+ * * `per_interval` - per_interval */+ goal_grain?: GoalGrainEnum;+ /**+ * Suggested days after release before assessing impact, not a monitoring schedule.+ * @minimum 1+ * @maximum 30+ * @nullable+ */+ decision_window_days?: number | null;+ /**+ * Optional number of qualifying observations before assessing impact.+ * @minimum 1+ * @maximum 1000+ * @nullable+ */+ minimum_data_points?: number | null;}export type ReportPriority = typeof ReportPriority[keyof typeof ReportPriority];@@ -91042,7 +91155,7 @@ export namespace Schemas {export interface SignalReportArtefactLogCreate {/** Active claim to attribute this work to. Must belong to the caller and report. */claim_id?: string;- /** The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. */+ /** The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, impact_measurement_plan, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status. */artefact_type: string;/** The artefact payload as a JSON object or array; shape depends on artefact_type and is validated against its schema. */content: unknown;diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex b97feaf2cc55..724c022fceaf 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -409,7 +409,7 @@ export const SignalsReportArtefactsCreateBody = () => zodartefact_type: zod.string().describe(- "The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status."+ "The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, impact_measurement_plan, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status."),content: zod.unknown()@@ -1708,6 +1708,11 @@ export const signalsScoutEditReportBodyMetricsItemUnitMax = 40export const signalsScoutEditReportBodyMetricsItemCaptionMax = 500+export const signalsScoutEditReportBodyMetricsItemGoalGrainDefault = `whole_window`+export const signalsScoutEditReportBodyMetricsItemDecisionWindowDaysMax = 30++export const signalsScoutEditReportBodyMetricsItemMinimumDataPointsMax = 1000+export const signalsScoutEditReportBodyMetricsItemComparisonOneLabelMax = 40export const signalsScoutEditReportBodyMetricsMax = 6@@ -1937,6 +1942,44 @@ export const SignalsScoutEditReportBody = () => zod.describe('Optional context the tile cannot show, such as a filter that narrows the count or a caveat on the data. Omit it rather than restate the title, unit, or window.'),+ goal_value: zod+ .number()+ .nullish()+ .describe(+ 'Proposed threshold after release. Informational only; does not schedule a check.'+ ),+ goal_direction: zod+ .union([+ zod+ .enum(['at_most', 'at_least'])+ .describe('\* `at_most` - at_most\n\* `at_least` - at_least'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Whether success means at most or at least goal_value.\n\n\* `at_most` - at_most\n\* `at_least` - at_least'+ ),+ goal_grain: zod+ .enum(['whole_window', 'per_interval'])+ .describe('\* `whole_window` - whole_window\n\* `per_interval` - per_interval')+ .default(signalsScoutEditReportBodyMetricsItemGoalGrainDefault)+ .describe(+ 'Whether the goal compares with the whole query window or each chart bucket.\n\n\* `whole_window` - whole_window\n\* `per_interval` - per_interval'+ ),+ decision_window_days: zod+ .number()+ .min(1)+ .max(signalsScoutEditReportBodyMetricsItemDecisionWindowDaysMax)+ .nullish()+ .describe(+ 'Suggested days after release before assessing impact, not a monitoring schedule.'+ ),+ minimum_data_points: zod+ .number()+ .min(1)+ .max(signalsScoutEditReportBodyMetricsItemMinimumDataPointsMax)+ .nullish()+ .describe('Optional number of qualifying observations before assessing impact.'),comparison: zod.union([zod.object({@@ -2076,6 +2119,11 @@ export const signalsScoutEmitReportBodyMetricsItemUnitMax = 40export const signalsScoutEmitReportBodyMetricsItemCaptionMax = 500+export const signalsScoutEmitReportBodyMetricsItemGoalGrainDefault = `whole_window`+export const signalsScoutEmitReportBodyMetricsItemDecisionWindowDaysMax = 30++export const signalsScoutEmitReportBodyMetricsItemMinimumDataPointsMax = 1000+export const signalsScoutEmitReportBodyMetricsItemComparisonOneLabelMax = 40export const signalsScoutEmitReportBodyMetricsMax = 6@@ -2317,6 +2365,44 @@ export const SignalsScoutEmitReportBody = () => zod.describe('Optional context the tile cannot show, such as a filter that narrows the count or a caveat on the data. Omit it rather than restate the title, unit, or window.'),+ goal_value: zod+ .number()+ .nullish()+ .describe(+ 'Proposed threshold after release. Informational only; does not schedule a check.'+ ),+ goal_direction: zod+ .union([+ zod+ .enum(['at_most', 'at_least'])+ .describe('\* `at_most` - at_most\n\* `at_least` - at_least'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Whether success means at most or at least goal_value.\n\n\* `at_most` - at_most\n\* `at_least` - at_least'+ ),+ goal_grain: zod+ .enum(['whole_window', 'per_interval'])+ .describe('\* `whole_window` - whole_window\n\* `per_interval` - per_interval')+ .default(signalsScoutEmitReportBodyMetricsItemGoalGrainDefault)+ .describe(+ 'Whether the goal compares with the whole query window or each chart bucket.\n\n\* `whole_window` - whole_window\n\* `per_interval` - per_interval'+ ),+ decision_window_days: zod+ .number()+ .min(1)+ .max(signalsScoutEmitReportBodyMetricsItemDecisionWindowDaysMax)+ .nullish()+ .describe(+ 'Suggested days after release before assessing impact, not a monitoring schedule.'+ ),+ minimum_data_points: zod+ .number()+ .min(1)+ .max(signalsScoutEmitReportBodyMetricsItemMinimumDataPointsMax)+ .nullish()+ .describe('Optional number of qualifying observations before assessing impact.'),comparison: zod.union([zod.object({diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-create.jsonindex a551d47ba187..5f1d9cf44c28 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-report-artefacts-create.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"artefact_type": {- "description": "The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status.",+ "description": "The artefact type. One of: actionability_judgment, channel_assignment, code_reference, commit, dismissal, impact_measurement_plan, note, priority_judgment, related_to, repo_selection, safety_judgment, signal_finding, suggested_reviewers. Log types accumulate; status types (safety_judgment, actionability_judgment, priority_judgment, repo_selection, suggested_reviewers, channel_assignment) are latest-wins — appending a new version supersedes the previous one as the report's canonical status.","type": "string"},"claim_id": {