Skip to content

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

feat(signals): show a report's plan and its steps in the inbox (#122212)

Alex Lebedevda76a246506a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5f2fb63924b2..52a46ee9acfa 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11594,6 +11594,14 @@ snapshots:
hash: v1.k794b7964.7b457e88868510c008646ab0ed37de232ec66ccbd001e82256e156e44a4cfa23.38qy-CrE1s8-psQTdpOZqMVW5alFzYnH7On3bETCnGU
scenes-app-inbox-detail--report-minimal--light:
hash: v1.k794b7964.1ec199f350734471b4a0b1463ff94a4654a30424276fc64c115c3d65db3cdb41.Tc9W_NbKBqiZUS8nJ_J48f161oSMbOpTNtd99CK-a5I
+ scenes-app-inbox-detail--report-plan--dark:
+ hash: v1.k794b7964.3bd0bb67a3f73cf102a6ab2da7ed94817744f19a2eeb0bca91077088f0f4ee6e.PgIhCTvuL03_JcLIGHTksFyaseCli1TR-Jl74AgFpGA
+ scenes-app-inbox-detail--report-plan--light:
+ hash: v1.k794b7964.cb79a27a0c4c5d30251a870ec7f7d7913a2fadd91f42f7b3b15d8f484bae5d62.xq3ZKL-mvrAw7PCVe9Fb7PTyxvjXoMJL5FupuOc6BGc
+ scenes-app-inbox-detail--report-plan-step--dark:
+ hash: v1.k794b7964.8b9f7671949fb08abe68ed0c2ec6c26462ec72307aa3f6b4db81eb2dce244b4c.DUI2oN8EiKIDzb5xxbJAyrkwL5HimUWTnsJ6MN0BXxY
+ scenes-app-inbox-detail--report-plan-step--light:
+ hash: v1.k794b7964.c27fa5839b1de55887931abfa594406bed0cea5a662e83af4b7def9709d4155d.H52fftX-TxlggstqPn395ijIxNufNuRxA89aKmPt45A
scenes-app-inbox-detail--report-ready-to-implement--dark:
hash: v1.k794b7964.2e98fb53587691240518fe22cb0ba7ecb491d5378be4d3b47a51740f129507ec.rL5vS5MBz1zF9hLDv1oRNO7wJWo6KxWU8NAh02bb6zs
scenes-app-inbox-detail--report-ready-to-implement--light:
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 098f171a7904..0c025c27a61f 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1511,6 +1511,8 @@ The implementation path checks these gates again under the report lock before ta
**Stacked plans** (`backend/stack_plan.py`). Research can return an optional `layers` plan on `ReportPresentationOutput`: two to six layers, each with a title, a scope, and the index of an earlier layer it depends on. A forward reference falls back to the previous layer, so the order is always acyclic. When the pass settles ready, `mark_report_ready_activity` creates one ready child report per layer in the same transaction. Each child gets the scope as its summary, the plan's latest safety, actionability, priority, repository and reviewer judgments, a `part_of` link to the plan, and a `depends_on` link to its dependency. A layer is born ready without `promoted_at`, like a scout report: it runs no research, so it fires no `signal_report_started`, and the inbox ranking spine takes it in through its born-visible branch. A plan that already has children keeps them on a re-research. The plan itself is held by the `plan_parent` gate, and its settle-point auto-start then starts the layers whose dependencies already have a pull request. After that, each pull request sync on a report queues `start_dependent_stack_layers`, which starts the waiting layers. A layer whose dependency has an open or draft pull request starts on that dependency's automation branch, and the run state carries `stack_base_branch`, so the task launch protects that branch as the PR base instead of the base of the dependency's PR. A merged dependency leaves the layer on the default base. Replacing a whole stack after a lower layer is superseded, a server-side GitHub stack link, and a collapsed inbox list are not built yet.
+**Report detail** (`backend/report_plan.py`). The report detail response carries a `plan` field: the plan the report leads or belongs to, with each step's title, status, primary pull request, and the steps of the same plan it `depends_on`. A report with incoming `part_of` edges is a plan and lists its own steps, even when it is also a step of a larger plan. Otherwise its oldest outgoing `part_of` names the plan. Deleted steps, and dependencies on reports outside the plan, are left out. The field is null in list responses, because the incoming read is a team-scoped scan. The inbox renders it as a Plan block in the summary, after the Solution section, and hides the `## Plan` sentence that `_layer_summary` writes on each layer. The frontend finds that sentence by its text (`isGeneratedPlanSection`), so the two must change together.
+
**The recurrence chain** (`backend/recurrence.py`) reads incoming `recurrence_of` edges to follow a forked report to its current live successor.
The inbox renders both types in the work log: a `report_link` row shows its kind, reason, and a link to the other report, and an `autostart_skip` row says in plain words why nothing started and links the deciding report.
diff --git a/products/signals/backend/report_plan.py b/products/signals/backend/report_plan.py
new file mode 100644
index 000000000000..c4b956f6e912
--- /dev/null
+++ b/products/signals/backend/report_plan.py
@@ -0,0 +1,83 @@
+"""The plan a report leads or belongs to, read for the report detail view.
+
+A plan is a report that other reports point at with a `part_of` link. Research writes these links
+when it splits work into stacked layers (`stack_plan.py`), and scouts can write them too. A link
+lives only on the step, so finding a plan's steps is an incoming-link scan.
+"""
+
+from posthog.dataclasses import frozen
+
+from products.signals.backend.enums import ReportLinkKind
+from products.signals.backend.implementation_pr import fetch_implementation_prs_for_reports, primary_pull_request
+from products.signals.backend.typed_report_links import (
+ incoming_links,
+ linked_reports,
+ outgoing_links,
+ outgoing_links_by_report,
+)
+
+
+@frozen
+class ReportPlanStep:
+ id: str
+ title: str | None
+ status: str
+ depends_on: tuple[str, ...]
+ implementation_pr_url: str | None
+ implementation_pr_state: str | None
+
+
+@frozen
+class ReportPlan:
+ id: str
+ title: str | None
+ status: str
+ steps: tuple[ReportPlanStep, ...]
+
+
+def report_plan(*, team_id: int, report_id: str) -> ReportPlan | None:
+ """The plan this report leads or belongs to, or None when the report is in no plan.
+
+ A report with steps of its own is a plan, so it gets its own steps even when it is also a step
+ of a larger plan. Otherwise the plan is the report that its oldest `part_of` link names.
+ """
+ step_edges = incoming_links(team_id=team_id, report_id=report_id, kinds=(ReportLinkKind.PART_OF,))
+ plan_id = report_id
+ if not step_edges:
+ parent_edges = outgoing_links(team_id=team_id, report_id=report_id, kinds=(ReportLinkKind.PART_OF,))
+ if not parent_edges:
+ return None
+ plan_id = parent_edges[0].target_id
+ step_edges = incoming_links(team_id=team_id, report_id=plan_id, kinds=(ReportLinkKind.PART_OF,))
+
+ # Incoming links are oldest first, and research writes its layers in landing order.
+ step_ids = list(dict.fromkeys(edge.source_id for edge in step_edges))
+ reports = linked_reports(team_id=team_id, report_ids=[plan_id, *step_ids])
+ plan = reports.get(plan_id)
+ step_ids = [step_id for step_id in step_ids if step_id in reports]
+ if plan is None or not step_ids:
+ return None
+
+ step_id_set = set(step_ids)
+ dependencies = outgoing_links_by_report(team_id=team_id, report_ids=step_ids, kinds=(ReportLinkKind.DEPENDS_ON,))
+ pull_requests = fetch_implementation_prs_for_reports(step_ids, team_id=team_id)
+ steps: list[ReportPlanStep] = []
+ for step_id in step_ids:
+ step = reports[step_id]
+ prs = pull_requests.get(step_id)
+ pr = primary_pull_request(prs) if prs else None
+ steps.append(
+ ReportPlanStep(
+ id=step_id,
+ title=step.title,
+ status=step.status,
+ depends_on=tuple(
+ dict.fromkeys(
+ edge.target_id for edge in dependencies.get(step_id, []) if edge.target_id in step_id_set
+ )
+ ),
+ implementation_pr_url=pr.url if pr else None,
+ implementation_pr_state=pr.state if pr else None,
+ )
+ )
+ return ReportPlan(id=str(plan.id), title=plan.title, status=plan.status, steps=tuple(steps))
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 1e7cf27952c7..8c4dcd0c9b5e 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -1,5 +1,6 @@
import json
import uuid
+import dataclasses
from collections.abc import Mapping
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, cast
@@ -65,6 +66,7 @@ if TYPE_CHECKING:
from products.signals.backend.implementation_pr import ImplementationPr
from products.signals.backend.report_claims import ReportClaim
+ from products.signals.backend.report_plan import ReportPlan
from .artefact_schemas import (
NON_WRITABLE_ARTEFACT_TYPES,
@@ -1300,6 +1302,48 @@ class ReviewerControlResponseSerializer(serializers.Serializer):
}
+class ReportPlanStepSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="The step's report id.")
+ title = serializers.CharField(read_only=True, allow_null=True, help_text="The step's report title.")
+ status = serializers.ChoiceField(
+ read_only=True,
+ choices=SignalReport.Status.choices,
+ help_text="The step's report status. Monitoring reads as resolved when its rollout is disabled.",
+ )
+ depends_on = serializers.ListField(
+ child=serializers.UUIDField(),
+ read_only=True,
+ help_text="Ids of the other steps in this plan that this step builds on. Empty when it builds on none.",
+ )
+ implementation_pr_url = serializers.CharField(
+ read_only=True, allow_null=True, help_text="The step's implementation pull request, if one is attached."
+ )
+ implementation_pr_state = serializers.ChoiceField(
+ read_only=True,
+ choices=SignalReportAssignment.PrState.choices,
+ allow_null=True,
+ help_text="Latest known state of that pull request: unknown, draft, open, closed, or merged.",
+ )
+
+
+class ReportPlanSerializer(serializers.Serializer):
+ id = serializers.UUIDField(
+ read_only=True,
+ help_text="The plan's report id. Equals the report's own id when the report is the plan.",
+ )
+ title = serializers.CharField(read_only=True, allow_null=True, help_text="The plan's report title.")
+ status = serializers.ChoiceField(
+ read_only=True,
+ choices=SignalReport.Status.choices,
+ help_text="The plan's report status. Monitoring reads as resolved when its rollout is disabled.",
+ )
+ steps = ReportPlanStepSerializer(
+ many=True,
+ read_only=True,
+ help_text="The reports linked to the plan with `part_of`, in the order they were linked. Deleted steps are left out.",
+ )
+
+
class SignalReportSerializerExtension(OpenApiSerializerExtension):
target_class = "products.signals.backend.serializers.SignalReportSerializer"
match_subclasses = True
@@ -1499,6 +1543,13 @@ class SignalReportSerializer(serializers.ModelSerializer):
"place of the entries."
),
)
+ plan = serializers.SerializerMethodField(
+ help_text=(
+ "The plan this report leads or is a step of, with every step in it. A report that other reports "
+ "link to with `part_of` is a plan. Null when the report is in no plan, and always null in list "
+ "responses, because finding a plan's steps scans the project's report links."
+ ),
+ )
class Meta:
model = SignalReport
@@ -1547,6 +1598,7 @@ class SignalReportSerializer(serializers.ModelSerializer):
"billing_exempt_reason",
"channel_id",
"ranking",
+ "plan",
]
read_only_fields = fields
extra_kwargs = {
@@ -1571,11 +1623,29 @@ class SignalReportSerializer(serializers.ModelSerializer):
representation.pop("monitoring_started_at", None)
return representation
+ def _display_status(self, obj: SignalReport, status: str) -> str:
+ if status == SignalReport.Status.MONITORING and not self._monitoring_enabled(obj):
+ return SignalReport.Status.RESOLVED
+ return status
+
@extend_schema_field(serializers.ChoiceField(choices=SignalReport.Status.choices))
def get_status(self, obj: SignalReport) -> str:
- if obj.status == SignalReport.Status.MONITORING and not self._monitoring_enabled(obj):
- return SignalReport.Status.RESOLVED
- return obj.status
+ return self._display_status(obj, obj.status)
+
+ @extend_schema_field(ReportPlanSerializer(allow_null=True))
+ def get_plan(self, obj: SignalReport) -> dict | None:
+ plans_map: dict[str, ReportPlan | None] = self.context.get("report_plans_map", {})
+ plan = plans_map.get(str(obj.id))
+ if plan is None:
+ return None
+ plan = dataclasses.replace(
+ plan,
+ status=self._display_status(obj, plan.status),
+ steps=tuple(
+ dataclasses.replace(step, status=self._display_status(obj, step.status)) for step in plan.steps
+ ),
+ )
+ return dict(ReportPlanSerializer(plan).data)
def _get_actionability_artefact_data(self, obj: SignalReport) -> dict | None:
prefetched = getattr(obj, "prefetched_actionability_artefacts", None)
diff --git a/products/signals/backend/stack_plan.py b/products/signals/backend/stack_plan.py
index b79b22fb84eb..30f98b052070 100644
--- a/products/signals/backend/stack_plan.py
+++ b/products/signals/backend/stack_plan.py
@@ -62,6 +62,8 @@ _STACKABLE_PR_STATES = (
def _layer_summary(*, parent: SignalReport, layer: ReportLayer, index: int, total: int) -> str:
+ # The inbox hides this section behind its plan block by matching the sentence, so keep it in sync
+ # with `isGeneratedPlanSection` in products/signals/frontend/inbox/utils/reportSummary.ts.
return f"{layer.scope}\n\n## Plan\n\nThis is layer {index + 1} of {total} of the plan '{parent.title}'."
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 60a9dddb83e0..89706e764869 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -792,6 +792,35 @@ class TestSignalReportListAPI(APIBaseTest):
with patch("posthog.data_freshness._probe_app_metrics", side_effect=RuntimeError("store unavailable")):
assert self.client.get(url).json()["source_suggestion"] is None
+ def test_plan_shows_on_the_detail_of_a_step_and_not_in_the_list(self):
+ plan = self._create_report(title="feat(x): the plan")
+ step = self._create_report(title="feat(x): a step")
+ SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(step.id),
+ content=ReportLink(kind=ReportLinkKind.PART_OF, report_id=str(plan.id)),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ detail = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{step.id}/").json()
+ assert detail["plan"] == {
+ "id": str(plan.id),
+ "title": "feat(x): the plan",
+ "status": "ready",
+ "steps": [
+ {
+ "id": str(step.id),
+ "title": "feat(x): a step",
+ "status": "ready",
+ "depends_on": [],
+ "implementation_pr_url": None,
+ "implementation_pr_state": None,
+ }
+ ],
+ }
+ row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(step.id))
+ assert row["plan"] is None
+
@parameterized.expand([("unassigned", False), ("assigned", True)])
def test_channel_id_is_the_same_in_the_list_and_the_detail(self, _name, assign):
channel = Channel.objects.create(team=self.team, name="Reports") if assign else None
diff --git a/products/signals/backend/test/test_stack_plan.py b/products/signals/backend/test/test_stack_plan.py
index 7d927b5f2ef1..c07dfdab5233 100644
--- a/products/signals/backend/test/test_stack_plan.py
+++ b/products/signals/backend/test/test_stack_plan.py
@@ -27,6 +27,7 @@ from products.signals.backend.report_generation.research import (
ReportPresentationOutput,
)
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
+from products.signals.backend.report_plan import report_plan
from products.signals.backend.stack_plan import (
create_layer_reports,
dependency_head_branch,
@@ -183,6 +184,22 @@ class TestStackPlan(BaseTest):
"repo_selection",
}
+ @parameterized.expand([("from_the_plan", None), ("from_a_layer", 2)])
+ def test_the_plan_and_each_layer_read_the_same_plan(self, _name: str, viewed_layer: int | None):
+ child_ids = self._create_layers()
+ self._attach_pull_request(child_ids[0], 101, SignalReportPullRequest.State.OPEN)
+ SignalReport.objects.filter(id=child_ids[1]).update(status=SignalReport.Status.DELETED)
+ viewed_id = str(self.parent.id) if viewed_layer is None else child_ids[viewed_layer]
+
+ plan = report_plan(team_id=self.team.id, report_id=viewed_id)
+
+ assert plan is not None
+ assert plan.id == str(self.parent.id)
+ assert [(step.id, step.depends_on, step.implementation_pr_state) for step in plan.steps] == [
+ (child_ids[0], (), SignalReportPullRequest.State.OPEN),
+ (child_ids[2], (), None),
+ ]
+
@parameterized.expand(
[
("pipeline_list_is_inherited", False, 3),
diff --git a/products/signals/backend/typed_report_links.py b/products/signals/backend/typed_report_links.py
index 9c562a602b52..ec64d52766e8 100644
--- a/products/signals/backend/typed_report_links.py
+++ b/products/signals/backend/typed_report_links.py
@@ -86,6 +86,25 @@ def outgoing_links(
return _edges_from_rows(list(rows), kinds=kinds)
+def outgoing_links_by_report(
+ *, team_id: int, report_ids: Collection[str], kinds: Collection[ReportLinkKind] | None = None
+) -> dict[str, list[ReportEdge]]:
+ """`outgoing_links` for several reports in one query, keyed by source report id."""
+ source_ids = [source_id for source_id in map(_canonical_report_id, report_ids) if source_id is not None]
+ if not source_ids:
+ return {}
+ rows = (
+ SignalReportArtefact.objects.using("default")
+ .filter(team_id=team_id, report_id__in=source_ids, type=SignalReportArtefact.ArtefactType.REPORT_LINK)
+ .order_by("created_at", "id")
+ .values_list("report_id", "content")[: SignalReportArtefact.MAX_REPORT_LINK_GRAPH_ROWS]
+ )
+ edges_by_report: dict[str, list[ReportEdge]] = {}
+ for edge in _edges_from_rows(list(rows), kinds=kinds):
+ edges_by_report.setdefault(edge.source_id, []).append(edge)
+ return edges_by_report
+
+
def incoming_links(
*,
team_id: int,
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 36e0303bec30..10c796f1f0f1 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -204,6 +204,7 @@ from products.signals.backend.report_merge import (
)
from products.signals.backend.report_metric_access import ReportMetricAccessPolicy
from products.signals.backend.report_metric_refresh import CURRENT_REPORT_STATUSES, refresh_report_metric_snapshots
+from products.signals.backend.report_plan import report_plan
from products.signals.backend.report_priority import update_report_priority
from products.signals.backend.report_read_state import (
ReportReadStateRequestSerializer,
@@ -2213,6 +2214,11 @@ class SignalReportViewSet(
except Exception:
logger.exception("signals.enriched_context.source_suggestion_failed", report_id=str(report.id))
source_suggestion = None
+ try:
+ plan = report_plan(team_id=self.team_id, report_id=str(report.id))
+ except Exception:
+ logger.exception("signals.enriched_context.report_plan_failed", report_id=str(report.id))
+ plan = None
return {
**self.get_serializer_context(),
"source_products_map": {rid: meta.source_products for rid, meta in signal_meta_map.items()},
@@ -2223,6 +2229,7 @@ class SignalReportViewSet(
"implementation_pr_state_map": {rid: pr.state for rid, pr in implementation_pr_by_report.items()},
"implementation_pr_merged_ids": {rid for rid, pr in implementation_pr_by_report.items() if pr.merged},
"source_suggestions_map": {str(report.id): source_suggestion},
+ "report_plans_map": {str(report.id): plan},
}
def retrieve(self, request, *args, **kwargs):
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 3202e8902cc2..e635ca259d26 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -907,6 +907,18 @@ export interface ReviewerControlResponseApi {
enabled: boolean
}
+/**
+ * * `potential` - Potential
+ * * `candidate` - Candidate
+ * * `in_progress` - In Progress
+ * * `pending_input` - Pending Input
+ * * `ready` - Ready
+ * * `monitoring` - Monitoring
+ * * `resolved` - Resolved
+ * * `failed` - Failed
+ * * `deleted` - Deleted
+ * * `suppressed` - Suppressed
+ */
export type SignalReportStatusEnumApi = (typeof SignalReportStatusEnumApi)[keyof typeof SignalReportStatusEnumApi]
export const SignalReportStatusEnumApi = {
@@ -1178,6 +1190,13 @@ export const SignalReportSuppressionSourceEnumApi = {
System: 'system',
} as const
+/**
+ * * `unknown` - Unknown
+ * * `draft` - Draft
+ * * `open` - Open
+ * * `closed` - Closed
+ * * `merged` - Merged
+ */
export type SignalReportAssignmentPrStateEnumApi =
(typeof SignalReportAssignmentPrStateEnumApi)[keyof typeof SignalReportAssignmentPrStateEnumApi]
@@ -1428,6 +1447,69 @@ export interface ReportRankingApi {
stale: boolean
}
+export interface ReportPlanStepApi {
+ /** The step's report id. */
+ readonly id: string
+ /**
+ * The step's report title.
+ * @nullable
+ */
+ readonly title: string | null
+ /** The step's report status. Monitoring reads as resolved when its rollout is disabled.
+ *
+ * * `potential` - Potential
+ * * `candidate` - Candidate
+ * * `in_progress` - In Progress
+ * * `pending_input` - Pending Input
+ * * `ready` - Ready
+ * * `monitoring` - Monitoring
+ * * `resolved` - Resolved
+ * * `failed` - Failed
+ * * `deleted` - Deleted
+ * * `suppressed` - Suppressed */
+ readonly status: SignalReportStatusEnumApi
+ /** Ids of the other steps in this plan that this step builds on. Empty when it builds on none. */
+ readonly depends_on: readonly string[]
+ /**
+ * The step's implementation pull request, if one is attached.
+ * @nullable
+ */
+ readonly implementation_pr_url: string | null
+ /** Latest known state of that pull request: unknown, draft, open, closed, or merged.
+ *
+ * * `unknown` - Unknown
+ * * `draft` - Draft
+ * * `open` - Open
+ * * `closed` - Closed
+ * * `merged` - Merged */
+ readonly implementation_pr_state: SignalReportAssignmentPrStateEnumApi | null
+}
+
+export interface ReportPlanApi {
+ /** The plan's report id. Equals the report's own id when the report is the plan. */
+ readonly id: string
+ /**
+ * The plan's report title.
+ * @nullable
+ */
+ readonly title: string | null
+ /** The plan's report status. Monitoring reads as resolved when its rollout is disabled.
+ *
+ * * `potential` - Potential
+ * * `candidate` - Candidate
+ * * `in_progress` - In Progress
+ * * `pending_input` - Pending Input
+ * * `ready` - Ready
+ * * `monitoring` - Monitoring
+ * * `resolved` - Resolved
+ * * `failed` - Failed
+ * * `deleted` - Deleted
+ * * `suppressed` - Suppressed */
+ readonly status: SignalReportStatusEnumApi
+ /** The reports linked to the plan with `part_of`, in the order they were linked. Deleted steps are left out. */
+ readonly steps: readonly ReportPlanStepApi[]
+}
+
export interface SignalReportListApi {
readonly id: string
/** @nullable */
@@ -1555,6 +1637,8 @@ export interface SignalReportListApi {
readonly channel_id: string | null
/** The served model's score from the latest ranking score artefact. Null for users who are neither staff nor in the inbox model sort rollout, and null when the report has no score. */
readonly ranking: ReportRankingApi | null
+ /** The plan this report leads or is a step of, with every step in it. A report that other reports link to with `part_of` is a plan. Null when the report is in no plan, and always null in list responses, because finding a plan's steps scans the project's report links. */
+ readonly plan: ReportPlanApi | null
/**
* Coarse sort key from the ranker named by the list response's ranker field, for sort=recommended only. Lower keys rank first. It is the score decile of the ranker's head (open, action or fixed), then the priority as a tiebreak. The priority ranker uses the priority only. Reports without a usable score sort after scored ones. Null for every other sort.
* @nullable
@@ -1803,6 +1887,8 @@ export interface SignalReportApi {
readonly channel_id: string | null
/** The served model's score from the latest ranking score artefact. Null for users who are neither staff nor in the inbox model sort rollout, and null when the report has no score. */
readonly ranking: ReportRankingApi | null
+ /** The plan this report leads or is a step of, with every step in it. A report that other reports link to with `part_of` is a plan. Null when the report is in no plan, and always null in list responses, because finding a plan's steps scans the project's report links. */
+ readonly plan: ReportPlanApi | null
}
/**
diff --git a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx
index 3ae23e741c79..6cfef0c71fd7 100644
--- a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx
+++ b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx
@@ -7,6 +7,8 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { mswDecorator } from '~/mocks/browser'
+import type { ReportPlanApi } from 'products/signals/frontend/generated/api.schemas'
+
import {
makeReport,
mockArtefacts,
@@ -359,6 +361,78 @@ export const ReportMinimal: Story = {
),
}
+const exportsPlan: ReportPlanApi = {
+ id: '019e64b8-0000-7000-8000-000000000201',
+ title: 'feat(exports): Make large exports reliable',
+ status: 'ready',
+ steps: [
+ {
+ id: '019e64b8-0000-7000-8000-000000000211',
+ title: 'feat(exports): Split large exports into chunks',
+ status: 'resolved',
+ depends_on: [],
+ implementation_pr_url: 'https://github.com/example/app/pull/41',
+ implementation_pr_state: 'merged',
+ },
+ {
+ id: '019e64b8-0000-7000-8000-000000000212',
+ title: 'feat(exports): Retry failed chunks with backoff',
+ status: 'ready',
+ depends_on: ['019e64b8-0000-7000-8000-000000000211'],
+ implementation_pr_url: 'https://github.com/example/app/pull/42',
+ implementation_pr_state: 'open',
+ },
+ {
+ id: '019e64b8-0000-7000-8000-000000000213',
+ title: 'feat(exports): Show export progress while it runs',
+ status: 'ready',
+ depends_on: ['019e64b8-0000-7000-8000-000000000212'],
+ implementation_pr_url: null,
+ implementation_pr_state: null,
+ },
+ ],
+}
+
+export const ReportPlanStep: Story = {
+ render: () => (
+ <Frame>
+ <ReportDetail
+ report={makeReport({
+ id: exportsPlan.steps[1].id,
+ title: exportsPlan.steps[1].title,
+ summary:
+ 'Retry a failed chunk up to three times with exponential backoff before the export fails. ' +
+ 'Keep the chunks that already succeeded.\n\n## Plan\n\n' +
+ `This is layer 2 of 3 of the plan '${exportsPlan.title}'.`,
+ priority: 'P2',
+ actionability: 'immediately_actionable',
+ plan: exportsPlan,
+ })}
+ />
+ </Frame>
+ ),
+}
+
+export const ReportPlan: Story = {
+ render: () => (
+ <Frame>
+ <ReportDetail
+ report={makeReport({
+ id: exportsPlan.id,
+ title: exportsPlan.title,
+ summary:
+ 'Large exports time out and leave people without their data.\n\n## Problem\n\n' +
+ 'An export runs as one job, so one slow query fails the whole export.\n\n## Solution\n\n' +
+ 'Split exports into chunks, retry the chunks that fail, and show progress while it runs.',
+ priority: 'P2',
+ actionability: 'immediately_actionable',
+ plan: exportsPlan,
+ })}
+ />
+ </Frame>
+ ),
+}
+
export const PullRequest: Story = {
render: () => (
<Frame>
diff --git a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx
index 7cdcc216e449..1d01b48096ea 100644
--- a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx
+++ b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx
@@ -55,6 +55,7 @@ import { useReportDetailActions } from './ReportDetailActions'
import { ReportExpectedImpact } from './ReportExpectedImpact'
import { ReportFeedbackFooter } from './ReportFeedbackFooter'
import { ReportImpactMetrics } from './ReportImpactMetrics'
+import { ReportPlanBlock } from './ReportPlanBlock'
import { ReportPrimaryMetric } from './ReportPrimaryMetric'
import { ReportSourceSuggestion } from './ReportSourceSuggestion'
import { ReportStatusSection } from './ReportStatusSection'
@@ -346,6 +347,7 @@ export function InboxDetailFrame({
expectedImpactEnabled && !summaryPending && (reportChecks === null || reportChecksError || hasMeasurements) ? (
<ReportExpectedImpact report={report} reportUrl={reportUrl} />
) : null
+ const planBlock = report.plan ? <ReportPlanBlock reportId={report.id} plan={report.plan} /> : null
const summaryColumn = (
<div className="flex flex-1 flex-col gap-6">
@@ -361,6 +363,7 @@ export function InboxDetailFrame({
pullRequestNote={pullRequestNote}
impactMetrics={impactMetrics}
expectedImpact={expectedImpact}
+ planBlock={planBlock}
/>
) : (
<div className="flex flex-col gap-6">
@@ -370,6 +373,7 @@ export function InboxDetailFrame({
{pullRequestNote}
{impactMetrics}
{expectedImpact}
+ {planBlock}
</div>
)}
{trailingCharts.length > 0 && (
diff --git a/products/signals/frontend/inbox/components/detail/ReportPlanBlock.tsx b/products/signals/frontend/inbox/components/detail/ReportPlanBlock.tsx
new file mode 100644
index 000000000000..6abefbe3bc57
--- /dev/null
+++ b/products/signals/frontend/inbox/components/detail/ReportPlanBlock.tsx
@@ -0,0 +1,81 @@
+import { Link } from '@posthog/lemon-ui'
+
+import { derivePrState } from 'lib/signals/prState'
+import { PrBadge } from 'lib/signals/SignalReportPrBadge'
+import { cn } from 'lib/utils/css-classes'
+import { urls } from 'scenes/urls'
+
+import type { ReportPlanApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { SignalReportStatus } from '../../types'
+import { displayConventionalCommitTitle, parsePrUrlParts, safeHttpUrl } from '../../utils/reportPresentation'
+import { SignalReportStatusBadge } from '../badges/SignalReportStatusBadge'
+
+export function ReportPlanBlock({ reportId, plan }: { reportId: string; plan: ReportPlanApi }): JSX.Element {
+ const stepNumbers = new Map(plan.steps.map((step, index) => [step.id, index + 1]))
+ const stepNumber = stepNumbers.get(reportId)
+ const planTitle = displayConventionalCommitTitle(plan.title, 'Untitled plan')
+
+ return (
+ <section className="flex flex-col gap-2" data-attr="inbox-report-plan">
+ <h2 className="m-0 text-lg font-semibold">Plan</h2>
+ {plan.id === reportId ? (
+ <p className="m-0 text-sm text-secondary">
+ {`Split into ${plan.steps.length} steps. Each step is its own report.`}
+ </p>
+ ) : (
+ <p className="m-0 text-sm text-secondary">
+ <span>{stepNumber ? `Step ${stepNumber} of ${plan.steps.length} in ` : 'A step in '}</span>
+ <Link to={urls.inboxReport('reports', plan.id)} data-attr="inbox-report-plan-open">
+ {planTitle}
+ </Link>
+ </p>
+ )}
+ <ol className="m-0 flex list-none flex-col divide-y divide-primary rounded border border-primary p-0">
+ {plan.steps.map((step, index) => {
+ const isCurrent = step.id === reportId
+ const title = displayConventionalCommitTitle(step.title, 'Untitled report')
+ const prUrl = safeHttpUrl(step.implementation_pr_url)
+ const prNumber = prUrl ? parsePrUrlParts(prUrl)?.number : null
+ const buildsOn = step.depends_on.flatMap((id) => stepNumbers.get(id) ?? [])
+ return (
+ <li
+ key={step.id}
+ aria-current={isCurrent ? 'step' : undefined}
+ className={cn(
+ 'flex items-start gap-2 px-3 py-2 text-sm',
+ isCurrent && 'bg-fill-highlight-100'
+ )}
+ >
+ <span className="w-5 shrink-0 text-tertiary tabular-nums">{`${index + 1}.`}</span>
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1">
+ {isCurrent ? (
+ <span className="min-w-0 break-words font-semibold">{title}</span>
+ ) : (
+ <Link
+ to={urls.inboxReport('reports', step.id)}
+ className="min-w-0 break-words"
+ data-attr="inbox-report-plan-step-open"
+ >
+ {title}
+ </Link>
+ )}
+ <SignalReportStatusBadge status={step.status as SignalReportStatus} />
+ {prNumber ? (
+ <PrBadge
+ prNumber={prNumber}
+ prUrl={prUrl}
+ state={derivePrState(step.status, false, step.implementation_pr_state)}
+ />
+ ) : null}
+ {buildsOn.length > 0 ? (
+ <span className="text-xs text-tertiary">{`Builds on ${buildsOn.join(', ')}`}</span>
+ ) : null}
+ </div>
+ </li>
+ )
+ })}
+ </ol>
+ </section>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsx b/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsx
index 3ceb522b7db8..07edb42b32c5 100644
--- a/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsx
+++ b/products/signals/frontend/inbox/components/detail/ReportSummaryBody.tsx
@@ -3,7 +3,7 @@ import { Fragment, ReactNode, useCallback, useMemo } from 'react'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { ChartPlacements } from '../../utils/chartPlacement'
-import { parseReportSummary } from '../../utils/reportSummary'
+import { isGeneratedPlanSection, parseReportSummary } from '../../utils/reportSummary'
import { ReportChart } from './ReportChart'
const PROSE_CLASS =
@@ -50,6 +50,7 @@ interface ReportSummaryBodyProps {
*/
impactMetrics?: ReactNode
expectedImpact?: ReactNode
+ planBlock?: ReactNode
}
/**
@@ -63,12 +64,14 @@ export function ReportSummaryBody({
pullRequestNote,
impactMetrics,
expectedImpact,
+ planBlock,
}: 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 sections = planBlock ? parsed.sections.filter((section) => !isGeneratedPlanSection(section)) : parsed.sections
+ const hasSolutionSection = sections.some((section) => section.kind === 'solution')
+ const hasImpactSection = sections.some((section) => section.kind === 'impact')
+ const hasExpectedImpactSection = sections.some((section) => section.kind === 'expected-impact')
+ const solutionIndex = sections.findIndex((section) => section.kind === 'solution')
const impactFallback =
impactMetrics && !hasImpactSection ? (
<section className="flex flex-col gap-2">
@@ -93,6 +96,7 @@ export function ReportSummaryBody({
/>
{impactFallback}
{expectedImpactFallback}
+ {planBlock}
{pullRequestNote}
</div>
)
@@ -108,7 +112,7 @@ export function ReportSummaryBody({
className="text-base text-primary leading-relaxed break-words [&>*+*]:mt-3.5"
/>
)}
- {parsed.sections.map((section, index) => (
+ {sections.map((section, index) => (
<Fragment key={`${section.kind}-${section.bodyOffset}`}>
{index === solutionIndex && impactFallback}
{index === solutionIndex && expectedImpactFallback}
@@ -128,10 +132,12 @@ export function ReportSummaryBody({
<div className="mt-2">{implementButton}</div>
)}
</section>
+ {index === solutionIndex && planBlock}
</Fragment>
))}
{!hasSolutionSection && impactFallback}
{!hasSolutionSection && expectedImpactFallback}
+ {!hasSolutionSection && planBlock}
{!hasSolutionSection && pullRequestNote}
</div>
)
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index 2d8a7aaec22f..bb94728053dc 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -4,6 +4,7 @@ import {
type SignalReportApi,
type ReportChartApi,
type ReportMetricApi,
+ type ReportPlanApi,
type ReportRankingApi,
type ReportSourceSuggestionApi,
type SignalReportPullRequestApi,
@@ -108,6 +109,8 @@ export interface SignalReport extends Pick<SignalReportApi, 'monitoring_started_
suggested_prompts?: string[]
/** A product the team doesn't use that would have given this report better evidence. Detail responses only. */
source_suggestion?: ReportSourceSuggestionApi | null
+ /** The plan this report leads or is a step of, with every step in it. Detail responses only. */
+ plan?: ReportPlanApi | null
/** Count of signals at the time the latest research run kicked off. */
signals_at_run?: number
/** Scout notes the work log dropped because they restate earlier ones. 0 when nothing was dropped. */
diff --git a/products/signals/frontend/inbox/utils/reportSummary.test.ts b/products/signals/frontend/inbox/utils/reportSummary.test.ts
index f88afb664ae6..ff3e956283a7 100644
--- a/products/signals/frontend/inbox/utils/reportSummary.test.ts
+++ b/products/signals/frontend/inbox/utils/reportSummary.test.ts
@@ -1,4 +1,4 @@
-import { parseReportSummary } from './reportSummary'
+import { isGeneratedPlanSection, parseReportSummary } from './reportSummary'
describe('parseReportSummary', () => {
const PROMPT_SHAPED =
@@ -85,6 +85,15 @@ describe('parseReportSummary', () => {
expect(summary.slice(parsed.sections[0].bodyOffset)).toMatch(/^\[Daily\]\[d\]/)
})
+ it.each([
+ ["This is layer 2 of 3 of the plan 'feat(x): the plan'.", true],
+ ['Ship the schema first, then the API.', false],
+ ])('marks only the plan note the pipeline writes as generated: %s', (body, expected) => {
+ const [section] = parseReportSummary(`Scope.\n\n## Plan\n\n${body}`).sections
+
+ expect(isGeneratedPlanSection(section)).toBe(expected)
+ })
+
it('treats an empty or missing summary as an empty lead', () => {
expect(parseReportSummary(null)).toEqual({ lead: '', leadOffset: 0, sections: [] })
expect(parseReportSummary(' \n')).toEqual({ lead: '', leadOffset: 0, sections: [] })
diff --git a/products/signals/frontend/inbox/utils/reportSummary.ts b/products/signals/frontend/inbox/utils/reportSummary.ts
index 3deb2c2dd6b6..d26ac290e25f 100644
--- a/products/signals/frontend/inbox/utils/reportSummary.ts
+++ b/products/signals/frontend/inbox/utils/reportSummary.ts
@@ -50,6 +50,14 @@ const SECTION_KINDS: Record<string, Exclude<ReportSummarySectionKind, 'other'>>
recommendation: 'solution',
}
+// `_layer_summary` in products/signals/backend/stack_plan.py appends this section to every layer it
+// creates. Keep the two in sync, or layer pages show the plain-text sentence beside the plan block.
+const GENERATED_PLAN_SECTION_BODY = /^This is layer \d+ of \d+ of the plan '.*'\.$/
+
+export function isGeneratedPlanSection(section: ReportSummarySection): boolean {
+ return section.kind === 'other' && section.heading === 'Plan' && GENERATED_PLAN_SECTION_BODY.test(section.body)
+}
+
function headingText(node: any): string {
const collect = (child: any): string =>
typeof child?.value === 'string' ? child.value : (child?.children ?? []).map(collect).join('')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8269178fce79..14fb2b14d8eb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -76927,6 +76927,18 @@ export namespace Schemas {
enabled: boolean;
}
+ /**
+ * * `potential` - Potential
+ * * `candidate` - Candidate
+ * * `in_progress` - In Progress
+ * * `pending_input` - Pending Input
+ * * `ready` - Ready
+ * * `monitoring` - Monitoring
+ * * `resolved` - Resolved
+ * * `failed` - Failed
+ * * `deleted` - Deleted
+ * * `suppressed` - Suppressed
+ */
export type SignalReportStatusEnum = typeof SignalReportStatusEnum[keyof typeof SignalReportStatusEnum];
@@ -77081,6 +77093,13 @@ export namespace Schemas {
System: 'system',
} as const;
+ /**
+ * * `unknown` - Unknown
+ * * `draft` - Draft
+ * * `open` - Open
+ * * `closed` - Closed
+ * * `merged` - Merged
+ */
export type SignalReportAssignmentPrStateEnum = typeof SignalReportAssignmentPrStateEnum[keyof typeof SignalReportAssignmentPrStateEnum];
@@ -77314,6 +77333,69 @@ export namespace Schemas {
stale: boolean;
}
+ export interface ReportPlanStep {
+ /** The step's report id. */
+ readonly id: string;
+ /**
+ * The step's report title.
+ * @nullable
+ */
+ readonly title: string | null;
+ /** The step's report status. Monitoring reads as resolved when its rollout is disabled.
+ *
+ * * `potential` - Potential
+ * * `candidate` - Candidate
+ * * `in_progress` - In Progress
+ * * `pending_input` - Pending Input
+ * * `ready` - Ready
+ * * `monitoring` - Monitoring
+ * * `resolved` - Resolved
+ * * `failed` - Failed
+ * * `deleted` - Deleted
+ * * `suppressed` - Suppressed */
+ readonly status: SignalReportStatusEnum;
+ /** Ids of the other steps in this plan that this step builds on. Empty when it builds on none. */
+ readonly depends_on: readonly string[];
+ /**
+ * The step's implementation pull request, if one is attached.
+ * @nullable
+ */
+ readonly implementation_pr_url: string | null;
+ /** Latest known state of that pull request: unknown, draft, open, closed, or merged.
+ *
+ * * `unknown` - Unknown
+ * * `draft` - Draft
+ * * `open` - Open
+ * * `closed` - Closed
+ * * `merged` - Merged */
+ readonly implementation_pr_state: SignalReportAssignmentPrStateEnum | null;
+ }
+
+ export interface ReportPlan {
+ /** The plan's report id. Equals the report's own id when the report is the plan. */
+ readonly id: string;
+ /**
+ * The plan's report title.
+ * @nullable
+ */
+ readonly title: string | null;
+ /** The plan's report status. Monitoring reads as resolved when its rollout is disabled.
+ *
+ * * `potential` - Potential
+ * * `candidate` - Candidate
+ * * `in_progress` - In Progress
+ * * `pending_input` - Pending Input
+ * * `ready` - Ready
+ * * `monitoring` - Monitoring
+ * * `resolved` - Resolved
+ * * `failed` - Failed
+ * * `deleted` - Deleted
+ * * `suppressed` - Suppressed */
+ readonly status: SignalReportStatusEnum;
+ /** The reports linked to the plan with `part_of`, in the order they were linked. Deleted steps are left out. */
+ readonly steps: readonly ReportPlanStep[];
+ }
+
export interface SignalReportList {
readonly id: string;
/** @nullable */
@@ -77441,6 +77523,8 @@ export namespace Schemas {
readonly channel_id: string | null;
/** The served model's score from the latest ranking score artefact. Null for users who are neither staff nor in the inbox model sort rollout, and null when the report has no score. */
readonly ranking: ReportRanking | null;
+ /** The plan this report leads or is a step of, with every step in it. A report that other reports link to with `part_of` is a plan. Null when the report is in no plan, and always null in list responses, because finding a plan's steps scans the project's report links. */
+ readonly plan: ReportPlan | null;
/**
* Coarse sort key from the ranker named by the list response's ranker field, for sort=recommended only. Lower keys rank first. It is the score decile of the ranker's head (open, action or fixed), then the priority as a tiebreak. The priority ranker uses the priority only. Reports without a usable score sort after scored ones. Null for every other sort.
* @nullable
@@ -99478,6 +99562,8 @@ export namespace Schemas {
readonly channel_id: string | null;
/** The served model's score from the latest ranking score artefact. Null for users who are neither staff nor in the inbox model sort rollout, and null when the report has no score. */
readonly ranking: ReportRanking | null;
+ /** The plan this report leads or is a step of, with every step in it. A report that other reports link to with `part_of` is a plan. Null when the report is in no plan, and always null in list responses, because finding a plan's steps scans the project's report links. */
+ readonly plan: ReportPlan | null;
}
/**