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(today): build the report page in the backend (#111471)

Shy Alter857a33966f48
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportHoverCard.tsx b/frontend/src/scenes/project-homepage/today/TodayReportHoverCard.tsx
index ab898d764e91..b3da777ff59d 100644
--- a/frontend/src/scenes/project-homepage/today/TodayReportHoverCard.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayReportHoverCard.tsx
@@ -23,12 +23,12 @@ import { pluralize } from 'lib/utils/strings'
import type { TodayReportPreview } from '~/layout/today/todayPreviewCards'
-import { selectReportCardImpactMetric } from 'products/signals/frontend/inbox/components/cards/ReportCardImpactMetric'
import { reportChartGraphQuery } from 'products/signals/frontend/inbox/utils/reportChartQuery'
import {
asReportMetricAggregateQuery,
asReportMetricSeriesQuery,
reportMetricRowParts,
+ selectReportCardImpactMetric,
} from 'products/signals/frontend/inbox/utils/reportMetrics'
import { pullRequestStateMeta } from 'products/tasks/frontend/spaces/TaskPullRequestChip'
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index cc1abfb8b348..f0e6961b8a38 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -45,6 +45,7 @@ from products.signals.backend.briefing_reports import (
from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES, SIGNAL_VARIANT_LOOKUP, SignalRemediation
from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct
from products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRun, SignalSourceConfig
+from products.signals.backend.report_access import may_read_reports as may_read_reports
from products.signals.backend.report_actionability_repair import RepairedBatch, repair_latest_actionability
from products.signals.backend.report_metric_access import (
# Re-exported so the Today briefing reads report metrics with the viewer's access, as the Inbox does.
@@ -57,6 +58,15 @@ from products.signals.backend.report_metrics import (
REPORT_METRIC_VALUE_FORMATS as REPORT_METRIC_VALUE_FORMATS,
ReportMetricSnapshot as ReportMetricSnapshot,
)
+from products.signals.backend.report_page_source import (
+ ReportPageSource as ReportPageSource,
+ ReportSignal as ReportSignal,
+ report_page_source as report_page_source,
+)
+from products.signals.backend.report_sections import (
+ ReportSections as ReportSections,
+ report_sections as report_sections,
+)
from products.signals.backend.scout_harness.create_access import can_create_scout
from products.signals.backend.scout_harness.run_gates import (
# Re-exported so the workflows endpoint can branch on why a fire was refused without reaching
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 2f00eae5c556..d10f81a445a3 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -454,6 +454,21 @@ class SignalReport(UUIDModel):
return self.signals_researched
return max(self.signals_at_run - SIGNALS_AT_RUN_INCREMENT, 0)
+ def selected_repository(self) -> str | None:
+ """The repository the report's research selected, from the latest repo_selection artefact."""
+ content = (
+ self.artefacts.filter(type=SignalReportArtefact.ArtefactType.REPO_SELECTION)
+ .order_by("-created_at")
+ .values_list("content", flat=True)
+ .first()
+ )
+ try:
+ data = json.loads(content or "")
+ except (TypeError, ValueError):
+ return None
+ repository = data.get("repository") if isinstance(data, dict) else None
+ return repository.strip() if isinstance(repository, str) and repository.strip() else None
+
def transition_to(
self,
new_status: "SignalReport.Status",
diff --git a/products/signals/backend/report_access.py b/products/signals/backend/report_access.py
new file mode 100644
index 000000000000..ac84d3b74e37
--- /dev/null
+++ b/products/signals/backend/report_access.py
@@ -0,0 +1,7 @@
+from posthog.models import Team, User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+
+def may_read_reports(*, user: User, team: Team) -> bool:
+ return UserAccessControl(user=user, team=team).check_access_level_for_resource("task", "viewer")
diff --git a/products/signals/backend/report_page_source.py b/products/signals/backend/report_page_source.py
new file mode 100644
index 000000000000..a3eb2a0fb230
--- /dev/null
+++ b/products/signals/backend/report_page_source.py
@@ -0,0 +1,83 @@
+from datetime import datetime
+from typing import Any
+
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.signals.backend.artefact_schemas import ActionabilityChoice
+from products.signals.backend.implementation_pr import fetch_implementation_prs_for_reports
+from products.signals.backend.models import SignalReport
+from products.signals.backend.report_sections import ReportSections, report_sections
+from products.signals.backend.signal_metadata import fetch_signals_for_report_sync
+
+
+@frozen
+class ReportSignal:
+ signal_id: str
+ content: str
+ source_product: str
+ source_type: str
+ source_id: str
+ timestamp: datetime
+ extra: dict[str, Any]
+
+
+@frozen
+class ReportPageSource:
+ summary: str
+ sections: ReportSections
+ action_prompts: list[str]
+ repo_slug: str | None
+ signals: list[ReportSignal]
+
+
+_STARTABLE_STATUSES = frozenset({SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT})
+
+
+def _can_start_work(report: SignalReport, has_pull_requests: bool) -> bool:
+ return (
+ report.status in _STARTABLE_STATUSES
+ and report.latest_already_addressed is not True
+ and report.latest_actionability != ActionabilityChoice.NOT_ACTIONABLE.value
+ and not has_pull_requests
+ )
+
+
+PAGE_SIGNAL_LIMIT = 100
+
+
+def _report_signals(team: Team, report_id: str) -> list[ReportSignal]:
+ return [
+ ReportSignal(
+ signal_id=signal["signal_id"],
+ content=signal["content"],
+ source_product=signal["source_product"],
+ source_type=signal["source_type"],
+ source_id=signal["source_id"],
+ timestamp=signal["timestamp"],
+ extra=signal["extra"] if isinstance(signal["extra"], dict) else {},
+ )
+ for signal in fetch_signals_for_report_sync(team, report_id, newest=PAGE_SIGNAL_LIMIT)
+ ]
+
+
+def report_page_source(*, team: Team, report_id: str) -> ReportPageSource | None:
+ team_id = team.id
+ report = (
+ SignalReport.objects.filter(team_id=team_id, id=report_id)
+ .exclude(status=SignalReport.Status.DELETED)
+ .only("id", "status", "summary", "suggested_prompts", "latest_actionability", "latest_already_addressed")
+ .first()
+ )
+ if report is None:
+ return None
+ pull_requests = fetch_implementation_prs_for_reports([report_id], team_id=team_id, using="default")
+ has_pull_requests = bool(pull_requests.get(report_id))
+ prompts = [prompt for prompt in report.suggested_prompts or [] if isinstance(prompt, str)]
+ return ReportPageSource(
+ summary=report.summary or "",
+ sections=report_sections(report.summary),
+ action_prompts=prompts if _can_start_work(report, has_pull_requests) else [],
+ repo_slug=report.selected_repository(),
+ signals=_report_signals(team, report_id),
+ )
diff --git a/products/signals/backend/report_sections.py b/products/signals/backend/report_sections.py
new file mode 100644
index 000000000000..5d4d8608d208
--- /dev/null
+++ b/products/signals/backend/report_sections.py
@@ -0,0 +1,183 @@
+import re
+import math
+
+from markdown_it import MarkdownIt
+from markdown_it.token import Token
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class ReportSections:
+ lead: str
+ impact: str | None
+ solution: str | None
+
+
+@frozen
+class _Section:
+ heading: str
+ body: str
+
+
+@frozen
+class _Heading:
+ line: int
+ body_line: int
+ text: str
+
+
+@frozen
+class _SplitSummary:
+ lead: str
+ sections: list[_Section]
+
+
+_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
+_MARKDOWN = MarkdownIt("commonmark")
+_MAX_SECTION_DEPTH = 3
+_HEADING_WORD_LIMIT = 6
+_SECTION_ALIASES = {
+ "problem": "problem",
+ "the problem": "problem",
+ "impact": "impact",
+ "expected impact": "expected impact",
+ "solution": "solution",
+ "fix": "solution",
+ "the fix": "solution",
+ "proposed fix": "solution",
+ "recommended fix": "solution",
+ "recommendation": "solution",
+}
+_PARAGRAPH_IMPACT_HEADINGS = frozenset({"impact"})
+_PARAGRAPH_SOLUTION_HEADINGS = frozenset(
+ {
+ "solution",
+ "the solution",
+ "fix",
+ "the fix",
+ "proposed fix",
+ "recommended fix",
+ "suggested fix",
+ "smallest fix",
+ "recommendation",
+ "recommendations",
+ "recommended action",
+ "recommended next step",
+ "recommended next steps",
+ "next step",
+ "next steps",
+ }
+)
+_PARAGRAPH_HEADING = re.compile(r"^\*\*([^*\n]+?):?\*\*:?\s*$")
+_PARAGRAPH_BREAK = re.compile(r"\n\s*\n")
+_TRAILING_CHART_LINK = re.compile(r"(?<=[.!?])\s*\[[^\[\]]*\]\(chart:[^)\[]*\)\.?(?=\s*$|\n)", re.MULTILINE)
+_CHART_LINK = re.compile(r"\[([^\[\]]*)\]\(chart:[^)\[]*\)")
+
+
+def _without_chart_links(markdown: str) -> str:
+ return _CHART_LINK.sub(r"\1", _TRAILING_CHART_LINK.sub("", markdown)).strip()
+
+
+def _first_paragraph(markdown: str) -> str:
+ return next((paragraph.strip() for paragraph in _PARAGRAPH_BREAK.split(markdown) if paragraph.strip()), "")
+
+
+def _clean_section(body: str | None) -> str | None:
+ if not body or not body.strip():
+ return None
+ return _without_chart_links(body) or None
+
+
+def _heading_text(inline: Token) -> str:
+ text = "".join(child.content for child in inline.children or [] if child.type in ("text", "code_inline"))
+ return text.strip().removesuffix(":").strip()
+
+
+def _heading_sections(summary: str) -> _SplitSummary:
+ lines = summary.split("\n")
+ tokens = _MARKDOWN.parse(summary)
+ headings: list[_Heading] = []
+ open_depth = math.inf
+ for index, token in enumerate(tokens):
+ depth = int(token.tag[1:]) if token.type == "heading_open" else math.inf
+ if depth > _MAX_SECTION_DEPTH or token.level != 0 or token.map is None:
+ continue
+ heading = _heading_text(tokens[index + 1])
+ if heading.lower() in _SECTION_ALIASES or depth <= open_depth:
+ headings.append(_Heading(line=token.map[0], body_line=token.map[1], text=heading))
+ open_depth = depth
+ if not headings:
+ return _SplitSummary(lead=summary.strip(), sections=[])
+ ends = [heading.line for heading in headings[1:]] + [len(lines)]
+ sections = [
+ _Section(heading=heading.text, body="\n".join(lines[heading.body_line : end]).strip())
+ for heading, end in zip(headings, ends)
+ ]
+ return _SplitSummary(lead="\n".join(lines[: headings[0].line]).strip(), sections=sections)
+
+
+def _paragraph_heading(line: str) -> str | None:
+ match = _PARAGRAPH_HEADING.match(line.strip())
+ heading = match.group(1).strip() if match else None
+ if heading is None or heading.endswith((".", "!", "?")) or len(heading.split()) > _HEADING_WORD_LIMIT:
+ return None
+ return heading
+
+
+@frozen
+class _OpenSection:
+ heading: str
+ lines: list[str]
+
+
+def _paragraph_heading_sections(markdown: str) -> _SplitSummary:
+ lead_lines: list[str] = []
+ sections: list[_OpenSection] = []
+ current = lead_lines
+ fence: str | None = None
+ for line in markdown.split("\n"):
+ marker = _FENCE.match(line)
+ if marker and (fence is None or marker.group(1).startswith(fence)):
+ fence = marker.group(1)[:3] if fence is None else None
+ heading = _paragraph_heading(line) if fence is None and not marker else None
+ if heading:
+ sections.append(_OpenSection(heading=heading, lines=[]))
+ current = sections[-1].lines
+ else:
+ current.append(line)
+ return _SplitSummary(
+ lead="\n".join(lead_lines).strip(),
+ sections=[_Section(heading=section.heading, body="\n".join(section.lines).strip()) for section in sections],
+ )
+
+
+def _aliased_body(sections: list[_Section], kind: str) -> str | None:
+ return next((section.body for section in sections if _SECTION_ALIASES.get(section.heading.lower()) == kind), None)
+
+
+def _named_body(sections: list[_Section], names: frozenset[str]) -> str | None:
+ return next((section.body for section in sections if section.heading.lower() in names and section.body), None)
+
+
+def _opening_body(sections: list[_Section]) -> str:
+ opening = sections[0] if sections else None
+ if opening is None or _SECTION_ALIASES.get(opening.heading.lower()) not in (None, "problem"):
+ return ""
+ return opening.body
+
+
+def report_sections(summary: str | None) -> ReportSections:
+ split = _heading_sections(summary or "")
+ if split.sections:
+ return ReportSections(
+ lead=_without_chart_links(_first_paragraph(split.lead or _opening_body(split.sections))),
+ impact=_clean_section(_aliased_body(split.sections, "impact")),
+ solution=_clean_section(_aliased_body(split.sections, "solution")),
+ )
+ paragraphs = _paragraph_heading_sections(split.lead)
+ return ReportSections(
+ lead=_without_chart_links(_first_paragraph(paragraphs.lead)),
+ impact=_clean_section(_named_body(paragraphs.sections, _PARAGRAPH_IMPACT_HEADINGS)),
+ solution=_clean_section(_named_body(paragraphs.sections, _PARAGRAPH_SOLUTION_HEADINGS)),
+ )
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 1b8f18ebc95b..0a4057a6d288 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -73,6 +73,7 @@ from products.signals.backend.models import (
SignalScoutRun,
)
from products.signals.backend.pipeline_identity import pipeline_writer_identity
+from products.signals.backend.report_access import may_read_reports
from products.signals.backend.report_charts import ChartSize
from products.signals.backend.report_generation.resolve_reviewers import MAX_PROJECT_MEMBERS, list_project_members
from products.signals.backend.scout_harness.config_registry import enabled_scout_count, ensure_scout_category
@@ -360,7 +361,7 @@ def _may_read_reports(request: Request, canonical_team: Team) -> bool:
user = request.user
if not isinstance(user, User):
return False
- return UserAccessControl(user=user, team=canonical_team).check_access_level_for_resource("task", "viewer")
+ return may_read_reports(user=user, team=canonical_team)
class Conflict(exceptions.APIException):
diff --git a/products/signals/backend/signal_metadata.py b/products/signals/backend/signal_metadata.py
index ff1bb78fd8b0..a30850d2cbc5 100644
--- a/products/signals/backend/signal_metadata.py
+++ b/products/signals/backend/signal_metadata.py
@@ -8,6 +8,7 @@ keeps that import graph acyclic.
"""
import re
+import json
from dataclasses import dataclass
from datetime import datetime
@@ -439,3 +440,72 @@ def fetch_origin_sources_for_report(team: Team, report_id: str) -> list[OriginSo
)
for source_product, scout_name, first_seen, entity_ids in result.results or []
]
+
+
+def _signals_for_report_query(
+ *, include_deleted: bool = False, limit: int | None = None, newest_first: bool = False
+) -> str:
+ """Build a HogQL query that fetches signal rows for a single report.
+
+ Args:
+ include_deleted: When True the ``NOT deleted`` filter is omitted.
+ Used by soft-delete which intentionally re-processes already-deleted rows.
+ limit: Optional row cap appended as a LIMIT clause.
+ newest_first: Order by newest timestamp first, so a limit keeps the newest rows.
+ """
+ deleted_filter = "" if include_deleted else "\n AND NOT JSONExtractBool(metadata, 'deleted')"
+ limit_clause = "" if limit is None else f"\n LIMIT {limit}"
+
+ return f"""
+ SELECT
+ document_id,
+ content,
+ metadata,
+ timestamp,
+ latest_inserted_at
+ FROM ({_deduped_signals_subquery(candidate_document_filter="JSONExtractString(metadata, 'report_id') = {report_id}")})
+ WHERE JSONExtractString(metadata, 'report_id') = {{report_id}}{deleted_filter}
+ ORDER BY timestamp {"DESC" if newest_first else "ASC"}{limit_clause}
+ """
+
+
+def _report_placeholders(report_id: str) -> dict:
+ return {
+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),
+ "report_id": ast.Constant(value=report_id),
+ }
+
+
+def fetch_signals_for_report_sync(team: Team, report_id: str, newest: int | None = None) -> list[dict]:
+ """Fetch the signals of a report from ClickHouse, including full metadata. Synchronous.
+
+ With `newest`, fetch only that many of the newest signals.
+ """
+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
+ result = execute_hogql_query(
+ query_type="SignalsDebugFetchForReport",
+ query=_signals_for_report_query(limit=newest, newest_first=newest is not None),
+ team=team,
+ placeholders=_report_placeholders(report_id),
+ context=_signals_query_context(team),
+ )
+
+ signals_list = []
+ for row in result.results or []:
+ document_id, content, metadata_str, timestamp, _inserted_at = row
+ metadata = json.loads(metadata_str)
+ signals_list.append(
+ {
+ "signal_id": document_id,
+ "content": content,
+ "source_product": metadata.get("source_product", ""),
+ "source_type": metadata.get("source_type", ""),
+ "source_id": metadata.get("source_id", ""),
+ "weight": metadata.get("weight", 0.0),
+ "timestamp": timestamp,
+ "extra": metadata.get("extra", {}),
+ "match_metadata": metadata.get("match_metadata"),
+ }
+ )
+
+ return signals_list
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index d278fa9a0470..2e76fb612224 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -130,21 +130,6 @@ def _meets_min_priority(report_priority: str | None, min_priority: str | None) -
return report_rank <= min_rank
-def _report_repository(report: SignalReport) -> str | None:
- """The repository the report's research selected, from the latest repo_selection artefact."""
- art = report.artefacts.filter(type=SignalReportArtefact.ArtefactType.REPO_SELECTION).order_by("-created_at").first()
- if art is None:
- return None
- try:
- data = json.loads(art.content)
- except (json.JSONDecodeError, TypeError, ValueError):
- return None
- if not isinstance(data, dict):
- return None
- repo = data.get("repository")
- return repo.strip() if isinstance(repo, str) and repo.strip() else None
-
-
def _latest_priority(report: SignalReport) -> str | None:
art = (
report.artefacts.filter(type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT)
@@ -737,7 +722,7 @@ def _deliver_to_routes(
signals: list[dict] | None = None,
) -> int:
"""Post the report to every route, returning how many top-level messages were sent."""
- repository = _report_repository(report)
+ repository = report.selected_repository()
sent = 0
for route in routes:
if _deliver_route_notification(
diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.py
index f74ae317b697..2092c9756147 100644
--- a/products/signals/backend/temporal/inbox_notification.py
+++ b/products/signals/backend/temporal/inbox_notification.py
@@ -28,9 +28,9 @@ from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.github_writeback import post_report_link_to_github_issues
from products.signals.backend.models import SignalReport, SignalTeamConfig
+from products.signals.backend.signal_metadata import fetch_signals_for_report_sync
from products.signals.backend.support_writeback import post_report_findings_to_tickets
from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION
-from products.signals.backend.temporal.signal_queries import fetch_signals_for_report_sync
from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.py
index dd70f7e84afd..55d317dfb0d3 100644
--- a/products/signals/backend/temporal/signal_queries.py
+++ b/products/signals/backend/temporal/signal_queries.py
@@ -26,6 +26,8 @@ from products.signals.backend.signal_metadata import (
SIGNAL_DOCUMENT_RENDERING,
SIGNAL_DOCUMENT_TYPE,
_deduped_signals_subquery,
+ _report_placeholders,
+ _signals_for_report_query,
)
from products.signals.backend.temporal import metrics
from products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retry
@@ -66,37 +68,6 @@ def _ensure_tz_aware(value: Union[datetime, str]) -> datetime:
_DEDUPED_SIGNALS_SUBQUERY = _deduped_signals_subquery()
-def _signals_for_report_query(*, include_deleted: bool = False, limit: int | None = None) -> str:
- """Build a HogQL query that fetches signal rows for a single report.
-
- Args:
- include_deleted: When True the ``NOT deleted`` filter is omitted.
- Used by soft-delete which intentionally re-processes already-deleted rows.
- limit: Optional row cap appended as a LIMIT clause.
- """
- deleted_filter = "" if include_deleted else "\n AND NOT JSONExtractBool(metadata, 'deleted')"
- limit_clause = "" if limit is None else f"\n LIMIT {limit}"
-
- return f"""
- SELECT
- document_id,
- content,
- metadata,
- timestamp,
- latest_inserted_at
- FROM ({_deduped_signals_subquery(candidate_document_filter="JSONExtractString(metadata, 'report_id') = {report_id}")})
- WHERE JSONExtractString(metadata, 'report_id') = {{report_id}}{deleted_filter}
- ORDER BY timestamp ASC{limit_clause}
- """
-
-
-def _report_placeholders(report_id: str) -> dict:
- return {
- "model_name": ast.Constant(value=EMBEDDING_MODEL.value),
- "report_id": ast.Constant(value=report_id),
- }
-
-
def _parse_signal_row(row: tuple) -> SignalData:
"""Turn a ClickHouse document embedding row into a SignalData."""
document_id, content, metadata_str, timestamp_raw, inserted_at_raw = row
@@ -619,37 +590,6 @@ async def fetch_signals_for_report_activity(input: FetchSignalsForReportInput) -
raise
-def fetch_signals_for_report_sync(team: Team, report_id: str) -> list[dict]:
- """Fetch all signals for a report from ClickHouse, including full metadata. Synchronous."""
- tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
- result = execute_hogql_query(
- query_type="SignalsDebugFetchForReport",
- query=_signals_for_report_query(),
- team=team,
- placeholders=_report_placeholders(report_id),
- )
-
- signals_list = []
- for row in result.results or []:
- document_id, content, metadata_str, timestamp, _inserted_at = row
- metadata = json.loads(metadata_str)
- signals_list.append(
- {
- "signal_id": document_id,
- "content": content,
- "source_product": metadata.get("source_product", ""),
- "source_type": metadata.get("source_type", ""),
- "source_id": metadata.get("source_id", ""),
- "weight": metadata.get("weight", 0.0),
- "timestamp": timestamp,
- "extra": metadata.get("extra", {}),
- "match_metadata": metadata.get("match_metadata"),
- }
- )
-
- return signals_list
-
-
# ---------------------------------------------------------------------------
# fetch_report_ids_for_source_products — synchronous, for the viewset list filter
# ---------------------------------------------------------------------------
diff --git a/products/signals/backend/test/test_report_page_source.py b/products/signals/backend/test/test_report_page_source.py
new file mode 100644
index 000000000000..a98cf3a60544
--- /dev/null
+++ b/products/signals/backend/test/test_report_page_source.py
@@ -0,0 +1,79 @@
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import Team, User
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.signals.backend.models import SignalReport
+from products.signals.backend.report_access import may_read_reports
+from products.signals.backend.report_page_source import report_page_source
+
+
+class TestReportPageSource(BaseTest):
+ def _report(self, team: Team | None = None, **fields: Any) -> SignalReport:
+ return SignalReport.objects.create(
+ **{
+ "team": team or self.team,
+ "title": "Checkout fails",
+ "summary": "Checkout fails for some shoppers.",
+ "status": SignalReport.Status.READY,
+ "signal_count": 1,
+ "total_weight": 1.0,
+ "suggested_prompts": ["Fix the token refresh"],
+ **fields,
+ }
+ )
+
+ def _source(self, report_id: str, pull_requests: dict[str, list[str]] | None = None):
+ with (
+ patch("products.signals.backend.report_page_source.fetch_signals_for_report_sync", return_value=[]),
+ patch(
+ "products.signals.backend.report_page_source.fetch_implementation_prs_for_reports",
+ return_value=pull_requests or {},
+ ),
+ ):
+ return report_page_source(team=self.team, report_id=report_id)
+
+ @parameterized.expand(
+ [
+ ("a ready report", {}, False, ["Fix the token refresh"]),
+ ("a resolved report", {"status": SignalReport.Status.RESOLVED}, False, []),
+ ("a report judged not actionable", {"latest_actionability": "not_actionable"}, False, []),
+ ("a report already addressed", {"latest_already_addressed": True}, False, []),
+ ("a report with a pull request", {}, True, []),
+ ]
+ )
+ def test_offers_prompts_that_start_work_only_for(
+ self, _name: str, fields: dict[str, Any], has_pull_request: bool, expected: list[str]
+ ) -> None:
+ report = self._report(**fields)
+ source = self._source(str(report.id), {str(report.id): ["pull request"]} if has_pull_request else None)
+ assert source is not None
+ assert source.action_prompts == expected
+
+ def test_finds_no_page_for_a_deleted_or_foreign_report(self) -> None:
+ deleted = self._report(status=SignalReport.Status.DELETED)
+ foreign = self._report(team=Team.objects.create(organization=self.organization))
+ assert self._source(str(deleted.id)) is None
+ assert self._source(str(foreign.id)) is None
+
+
+class TestReportAccess(BaseTest):
+ def test_checks_the_environment_it_is_given(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team)
+ AccessControl.objects.create(team=environment, resource="task", resource_id=None, access_level="none")
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+
+ assert (may_read_reports(user=member, team=self.team), may_read_reports(user=member, team=environment)) == (
+ True,
+ False,
+ )
diff --git a/products/signals/backend/test/test_report_sections.py b/products/signals/backend/test/test_report_sections.py
new file mode 100644
index 000000000000..7c9846837bd7
--- /dev/null
+++ b/products/signals/backend/test/test_report_sections.py
@@ -0,0 +1,50 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.signals.backend.report_sections import ReportSections, report_sections
+
+
+class TestReportSections(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "markdown headings",
+ "Lead sentence.\n\n## Problem\n\nBroken.\n\n## Impact\n\n**12 people** hit it. [Failures](chart:failures)\n\n## Solution\n\nFix the key.",
+ ReportSections(lead="Lead sentence.", impact="**12 people** hit it.", solution="Fix the key."),
+ ),
+ (
+ "an aliased solution heading",
+ "Lead.\n\n## The fix\n\nKeep the token in a cookie.",
+ ReportSections(lead="Lead.", impact=None, solution="Keep the token in a cookie."),
+ ),
+ (
+ "a heading inside a code block",
+ "Lead.\n\n## Solution\n\nRun this:\n\n```\n# Impact\nmigrate\n```",
+ ReportSections(lead="Lead.", impact=None, solution="Run this:\n\n```\n# Impact\nmigrate\n```"),
+ ),
+ (
+ "bold paragraph headings",
+ "Lead sentence.\n\n**Evidence**\n\n- A finding.\n\n**Recommended next step**\n\n- Inspect the [rate](chart:rate) path.",
+ ReportSections(lead="Lead sentence.", impact=None, solution="- Inspect the rate path."),
+ ),
+ (
+ "a bold lead sentence",
+ "**One-page checkout won. It is safe to ship.**\n\nThe shorter checkout completed more often.",
+ ReportSections(lead="**One-page checkout won. It is safe to ship.**", impact=None, solution=None),
+ ),
+ (
+ "a summary that opens with its problem heading",
+ "## Problem\n\nCheckout drops the coupon.\n\n## Solution\n\nKeep it in the cart.",
+ ReportSections(lead="Checkout drops the coupon.", impact=None, solution="Keep it in the cart."),
+ ),
+ (
+ "a bold label inside a fenced example",
+ "Lead.\n\n**Fix**\n\nRun this:\n\n```\n**Solution**\nmigrate\n```",
+ ReportSections(lead="Lead.", impact=None, solution="Run this:\n\n```\n**Solution**\nmigrate\n```"),
+ ),
+ ("no summary", None, ReportSections(lead="", impact=None, solution=None)),
+ ]
+ )
+ def test_report_sections(self, _name: str, summary: str | None, expected: ReportSections) -> None:
+ assert report_sections(summary) == expected
diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.py
index 5ed63d407ae6..95dc75283b41 100644
--- a/products/signals/backend/test/test_signal_queries.py
+++ b/products/signals/backend/test/test_signal_queries.py
@@ -22,13 +22,13 @@ from products.signals.backend.signal_metadata import (
SignalSourceReference,
fetch_origin_sources_for_report,
fetch_signal_stats_for_source_slice,
+ fetch_signals_for_report_sync,
fetch_source_products_for_reports,
fetch_source_references_for_report,
)
from products.signals.backend.temporal.signal_queries import (
fetch_report_ids_for_scout_names,
fetch_report_ids_for_scout_prefix,
- fetch_signals_for_report_sync,
)
_MODEL_TABLE = f"distributed_posthog_document_embeddings_{EMBEDDING_MODEL.value.replace('-', '_')}"
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 6feed33b43fc..65e9e6fa5eb3 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -217,7 +217,11 @@ from products.signals.backend.serializers import (
SignalUserAutonomyConfigCreateSerializer,
SignalUserAutonomyConfigSerializer,
)
-from products.signals.backend.signal_metadata import ReportSignalMeta, fetch_source_products_for_reports
+from products.signals.backend.signal_metadata import (
+ ReportSignalMeta,
+ fetch_signals_for_report_sync,
+ fetch_source_products_for_reports,
+)
from products.signals.backend.slack_notification_targets import (
is_slack_member_target,
resolve_own_direct_message_target,
@@ -239,7 +243,6 @@ from products.signals.backend.temporal.signal_queries import (
fetch_report_ids_for_scout_names,
fetch_report_ids_for_scout_prefix,
fetch_report_ids_for_source_products,
- fetch_signals_for_report_sync,
)
from products.signals.backend.temporal.types import (
SignalReportDeletionWorkflowInputs,
diff --git a/products/signals/frontend/inbox/components/cards/ReportCardImpactMetric.tsx b/products/signals/frontend/inbox/components/cards/ReportCardImpactMetric.tsx
index 62c863da8046..72efe1c7ed72 100644
--- a/products/signals/frontend/inbox/components/cards/ReportCardImpactMetric.tsx
+++ b/products/signals/frontend/inbox/components/cards/ReportCardImpactMetric.tsx
@@ -4,24 +4,9 @@ import { TZLabel } from 'lib/components/TZLabel'
import type { ReportMetricApi } from 'products/signals/frontend/generated/api.schemas'
-import { formatReportMetricValue, reportMetricChartType, reportMetricRowParts } from '../../utils/reportMetrics'
+import { reportMetricChartType, reportMetricRowParts, selectReportCardImpactMetric } from '../../utils/reportMetrics'
import { ReportCardSparkline } from './ReportCardSparkline'
-export function selectReportCardImpactMetric(metrics?: ReportMetricApi[]): ReportMetricApi | null {
- if (!metrics?.length) {
- return null
- }
-
- const hasSnapshot = (metric: ReportMetricApi): boolean =>
- metric.value !== null && Number.isFinite(metric.value) && formatReportMetricValue(metric, metric.value) !== null
-
- return (
- metrics.find((metric) => metric.kind === 'affected_users' && hasSnapshot(metric)) ??
- metrics.find((metric) => metric.role === 'primary' && hasSnapshot(metric)) ??
- null
- )
-}
-
/**
* The row's headline impact: the trailing buckets as a bar or line strip, then the figure over its unit word.
* What it measures and when live in the tooltip.
diff --git a/products/signals/frontend/inbox/components/detail/ImplementButton.tsx b/products/signals/frontend/inbox/components/detail/ImplementButton.tsx
index 48bcafc37e83..394afb67fe2f 100644
--- a/products/signals/frontend/inbox/components/detail/ImplementButton.tsx
+++ b/products/signals/frontend/inbox/components/detail/ImplementButton.tsx
@@ -1,20 +1,10 @@
import { useActions, useValues } from 'kea'
import { useState } from 'react'
-import { IconCopy, IconLogomark, IconPullRequest } from '@posthog/icons'
+import { IconCopy, IconPullRequest } from '@posthog/icons'
import { LemonButton, LemonMenuOverlay, lemonToast } from '@posthog/lemon-ui'
-import {
- buildClaudeCodeDeepLink,
- buildClaudeCodeVSCodeDeepLink,
- buildClaudeCodeWebLink,
- buildClaudeDesktopDeepLink,
- buildCodexDeepLink,
- buildCursorDeepLink,
- buildPostHogCodeDeepLink,
-} from 'lib/components/AgentPromptButton'
import type { AgentPromptDestination } from 'lib/components/AgentPromptButton'
-import { AgentLogo, claudeLogo, cursorLogo, openaiLogo } from 'lib/components/AgentPromptButton/AgentLogo'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { addProjectIdIfMissing } from 'lib/utils/kea-router'
@@ -25,66 +15,13 @@ import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'
import { ImplementationSlotClaim, inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'
import { SignalReport } from '../../types'
import { buildReportImplementationPrompt } from './buildReportImplementationPrompt'
+import { IMPLEMENTATION_AGENTS } from './implementationAgents'
const SLOT_CLAIM_DISABLED_REASON: Record<ImplementationSlotClaim, string> = {
in_flight: 'A pull request run is already in progress for this report. Open it in the task log to follow it.',
shipped_pr: 'This report already has a pull request. Open it in the task log to continue it.',
}
-function openDeepLink(buildDeepLink: (prompt: string) => string): (prompt: string) => void {
- return (prompt) => window.open(buildDeepLink(prompt), '_blank')
-}
-
-const IMPLEMENTATION_AGENTS: {
- key: AgentPromptDestination
- name: string
- icon: JSX.Element
- open: (prompt: string) => void
-}[] = [
- {
- key: 'posthog-code',
- name: 'PostHog Desktop',
- icon: <IconLogomark />,
- open: openDeepLink(buildPostHogCodeDeepLink),
- },
- {
- key: 'claude-code',
- name: 'Claude Code CLI',
- icon: <AgentLogo logo={claudeLogo} />,
- open: openDeepLink(buildClaudeCodeDeepLink),
- },
- {
- key: 'claude-desktop',
- name: 'Claude Desktop',
- icon: <AgentLogo logo={claudeLogo} />,
- open: openDeepLink(buildClaudeDesktopDeepLink),
- },
- {
- key: 'claude-code-vscode',
- name: 'Claude Code in VS Code',
- icon: <AgentLogo logo={claudeLogo} />,
- open: openDeepLink(buildClaudeCodeVSCodeDeepLink),
- },
- {
- key: 'claude-code-web',
- name: 'Claude Code on the web',
- icon: <AgentLogo logo={claudeLogo} />,
- open: (prompt) => window.open(buildClaudeCodeWebLink(prompt), '_blank', 'noopener,noreferrer'),
- },
- {
- key: 'cursor',
- name: 'Cursor',
- icon: <AgentLogo logo={cursorLogo} logoClassName="dark:invert" />,
- open: openDeepLink(buildCursorDeepLink),
- },
- {
- key: 'codex',
- name: 'Codex',
- icon: <AgentLogo logo={openaiLogo} />,
- open: openDeepLink(buildCodexDeepLink),
- },
-]
-
export function ImplementButton({ report }: { report: SignalReport }): JSX.Element {
const { isCreatingPr, isDiscussing, createPrDisabledReason } = useValues(inboxTaskKickoffLogic)
const { implementationSlotClaim, reportTaskToOpen } = useValues(
diff --git a/products/signals/frontend/inbox/components/detail/implementationAgents.tsx b/products/signals/frontend/inbox/components/detail/implementationAgents.tsx
new file mode 100644
index 000000000000..d61d106a751f
--- /dev/null
+++ b/products/signals/frontend/inbox/components/detail/implementationAgents.tsx
@@ -0,0 +1,69 @@
+import { IconLogomark } from '@posthog/icons'
+
+import {
+ buildClaudeCodeDeepLink,
+ buildClaudeCodeVSCodeDeepLink,
+ buildClaudeCodeWebLink,
+ buildClaudeDesktopDeepLink,
+ buildCodexDeepLink,
+ buildCursorDeepLink,
+ buildPostHogCodeDeepLink,
+} from 'lib/components/AgentPromptButton'
+import type { AgentPromptDestination } from 'lib/components/AgentPromptButton'
+import { AgentLogo, claudeLogo, cursorLogo, openaiLogo } from 'lib/components/AgentPromptButton/AgentLogo'
+
+export interface ImplementationAgent {
+ key: AgentPromptDestination
+ name: string
+ icon: JSX.Element
+ open: (prompt: string) => void
+}
+
+function openDeepLink(buildDeepLink: (prompt: string) => string): (prompt: string) => void {
+ return (prompt) => window.open(buildDeepLink(prompt), '_blank')
+}
+
+export const IMPLEMENTATION_AGENTS: ImplementationAgent[] = [
+ {
+ key: 'posthog-code',
+ name: 'PostHog Desktop',
+ icon: <IconLogomark />,
+ open: openDeepLink(buildPostHogCodeDeepLink),
+ },
+ {
+ key: 'claude-code',
+ name: 'Claude Code CLI',
+ icon: <AgentLogo logo={claudeLogo} />,
+ open: openDeepLink(buildClaudeCodeDeepLink),
+ },
+ {
+ key: 'claude-desktop',
+ name: 'Claude Desktop',
+ icon: <AgentLogo logo={claudeLogo} />,
+ open: openDeepLink(buildClaudeDesktopDeepLink),
+ },
+ {
+ key: 'claude-code-vscode',
+ name: 'Claude Code in VS Code',
+ icon: <AgentLogo logo={claudeLogo} />,
+ open: openDeepLink(buildClaudeCodeVSCodeDeepLink),
+ },
+ {
+ key: 'claude-code-web',
+ name: 'Claude Code on the web',
+ icon: <AgentLogo logo={claudeLogo} />,
+ open: (prompt) => window.open(buildClaudeCodeWebLink(prompt), '_blank', 'noopener,noreferrer'),
+ },
+ {
+ key: 'cursor',
+ name: 'Cursor',
+ icon: <AgentLogo logo={cursorLogo} logoClassName="dark:invert" />,
+ open: openDeepLink(buildCursorDeepLink),
+ },
+ {
+ key: 'codex',
+ name: 'Codex',
+ icon: <AgentLogo logo={openaiLogo} />,
+ open: openDeepLink(buildCodexDeepLink),
+ },
+]
diff --git a/products/signals/frontend/inbox/utils/reportMetrics.ts b/products/signals/frontend/inbox/utils/reportMetrics.ts
index 7452c0e60ad7..fcf9e77e4436 100644
--- a/products/signals/frontend/inbox/utils/reportMetrics.ts
+++ b/products/signals/frontend/inbox/utils/reportMetrics.ts
@@ -441,3 +441,18 @@ export function mergeReportMetricSnapshots<T extends { id: string; metrics?: Rep
})
return changed ? { ...report, metrics } : report
}
+
+export function selectReportCardImpactMetric(metrics?: ReportMetricApi[]): ReportMetricApi | null {
+ if (!metrics?.length) {
+ return null
+ }
+
+ const hasSnapshot = (metric: ReportMetricApi): boolean =>
+ metric.value !== null && Number.isFinite(metric.value) && formatReportMetricValue(metric, metric.value) !== null
+
+ return (
+ metrics.find((metric) => metric.kind === 'affected_users' && hasSnapshot(metric)) ??
+ metrics.find((metric) => metric.role === 'primary' && hasSnapshot(metric)) ??
+ null
+ )
+}
diff --git a/products/today/backend/facade/api.py b/products/today/backend/facade/api.py
index f3abdc2de26e..0f5a790abe42 100644
--- a/products/today/backend/facade/api.py
+++ b/products/today/backend/facade/api.py
@@ -4,8 +4,14 @@ from posthog.models import Team, User
from products.signals.backend.facade import api as signals
-from ..feature_flags import may_get_briefing as may_get_briefing
-from ..logic import briefings
+from ..feature_flags import (
+ is_enabled_for as is_enabled_for,
+ may_get_briefing as may_get_briefing,
+)
+from ..logic import (
+ briefings,
+ report_page as report_pages,
+)
from . import contracts
from .enums import BriefingStatus
@@ -43,3 +49,8 @@ def delete_briefings_for_teams(team_ids: list[int]) -> None:
def list_candidates(*, team: Team, user: User, timezone_name: str | None) -> contracts.CandidateList:
"""Today's ranked items with their facts and reasons, without the written text."""
return briefings.list_candidates(team=team, user=user, timezone_name=timezone_name)
+
+
+def report_page(*, team: Team, report_id: str) -> contracts.ReportPage | None:
+ source = report_pages.page_source(team=team, report_id=report_id)
+ return report_pages.report_page(source) if source is not None else None
diff --git a/products/today/backend/facade/contracts.py b/products/today/backend/facade/contracts.py
index 2356285c3afc..e3a88bcccf7c 100644
--- a/products/today/backend/facade/contracts.py
+++ b/products/today/backend/facade/contracts.py
@@ -5,7 +5,16 @@ from typing import Any
from pydantic.dataclasses import dataclass
-from .enums import BriefingStatus, BriefingWriter, ItemGroup, ItemReason, ItemSource, ItemState
+from .enums import (
+ BriefingStatus,
+ BriefingWriter,
+ CitedSource,
+ ImpactNumberKey,
+ ItemGroup,
+ ItemReason,
+ ItemSource,
+ ItemState,
+)
@dataclass(frozen=True)
@@ -109,3 +118,93 @@ class CandidateList:
local_day: date
candidates: list[Candidate]
more_reports_count: int
+
+
+@dataclass(frozen=True)
+class PullRequestLink:
+ url: str
+ number: int
+
+
+@dataclass(frozen=True)
+class CodeFile:
+ repo: str
+ path: str
+
+
+@dataclass(frozen=True)
+class PreviewLine:
+ text: str
+ quiet: bool
+
+
+@dataclass(frozen=True)
+class PageLink:
+ url: str
+ text: str
+
+
+@dataclass(frozen=True)
+class SignalPreview:
+ hint: str
+ code: list[CodeFile]
+ block: list[PreviewLine]
+ text: str
+ facts: list[str]
+ link: PageLink | None
+ link_label: str | None
+
+
+@dataclass(frozen=True)
+class RecordingTarget:
+ session_id: str
+ start_at: datetime | None
+ offset: str | None
+ seek_seconds: int | None
+
+
+@dataclass(frozen=True)
+class SignalView:
+ signal_id: str
+ source_product: str
+ source_type: str
+ source_id: str
+ content: str
+ timestamp: datetime
+ extra: dict[str, Any]
+ headline: str
+ lead: str
+ meta: str
+ cited: CitedSource | None
+ recording: RecordingTarget | None
+ link: PageLink | None
+ preview: SignalPreview | None
+
+
+@dataclass(frozen=True)
+class ImpactWorking:
+ expression: str
+ result: str
+
+
+@dataclass(frozen=True)
+class ImpactNumber:
+ key: ImpactNumberKey
+ value: str
+ sentence: str
+ signal: SignalView | None
+ values: list[str]
+ working: ImpactWorking | None
+
+
+@dataclass(frozen=True)
+class ReportPage:
+ lead: str
+ proposal: str
+ impact_sentence: str
+ named_pull_request: PullRequestLink | None
+ solution_names_pull_request: bool
+ evidence: list[SignalView]
+ source_count: int
+ impact_numbers: list[ImpactNumber]
+ last_seen: datetime | None
diff --git a/products/today/backend/facade/enums.py b/products/today/backend/facade/enums.py
index afd17daf7855..0c1c463a9c8d 100644
--- a/products/today/backend/facade/enums.py
+++ b/products/today/backend/facade/enums.py
@@ -2,6 +2,8 @@
from enum import StrEnum
+from posthog.enums import LabeledStrEnum
+
class BriefingStatus(StrEnum):
COLLECTING = "collecting"
@@ -57,3 +59,13 @@ class ItemState(StrEnum):
DONE = "done"
# Dismissed or deleted since the briefing was written.
DISMISSED = "dismissed"
+
+
+class CitedSource(LabeledStrEnum):
+ CODE = "code", "Code"
+ SLACK = "slack", "Slack"
+
+
+class ImpactNumberKey(LabeledStrEnum):
+ TICKETS = "tickets", "Support tickets"
+ QUERY_HOURS = "query-hours", "Database hours"
diff --git a/products/today/backend/logic/evidence.py b/products/today/backend/logic/evidence.py
new file mode 100644
index 000000000000..9f90981240fe
--- /dev/null
+++ b/products/today/backend/logic/evidence.py
@@ -0,0 +1,132 @@
+from collections.abc import Callable
+from datetime import datetime, timedelta
+
+from ..facade import contracts
+from .formats import colon_duration_seconds
+from .signal_previews import plays_recording, preview
+from .signal_text import (
+ SignalInput as SignalInput,
+ cited_source,
+ code_file,
+ detail,
+ github_file_url,
+ headline,
+ is_pull_request,
+ meta,
+ safe_http_url,
+ slack_thread,
+ text_of,
+)
+
+_SHOWN_EVIDENCE = 3
+_PLAYER_LEAD_IN_SECONDS = 5
+_SHORT_FINDING_CHARS = 240
+
+
+def newest_first(signals: list[SignalInput]) -> list[SignalInput]:
+ return sorted(signals, key=lambda signal: signal.timestamp, reverse=True)
+
+
+def _evidence_item(signal: SignalInput) -> str:
+ alert = text_of(signal.extra.get("alert_id")) if signal.source_product == "analytics" else None
+ return f"analytics:alert:{alert}" if alert else f"{signal.source_product}:{signal.source_id}"
+
+
+def distinct_evidence_count(signals: list[SignalInput]) -> int:
+ return len({_evidence_item(signal) for signal in signals})
+
+
+def _unique_by(signals: list[SignalInput], key: Callable[[SignalInput], str]) -> list[SignalInput]:
+ seen: set[str] = set()
+ unique = []
+ for signal in signals:
+ if key(signal) not in seen:
+ seen.add(key(signal))
+ unique.append(signal)
+ return unique
+
+
+def pick_evidence(signals: list[SignalInput], count: int = _SHOWN_EVIDENCE) -> list[SignalInput]:
+ unique = _unique_by(newest_first(signals), _evidence_item)
+ leads = _unique_by(unique, lambda signal: signal.source_product)
+ rest = [signal for signal in unique if signal not in leads]
+ return newest_first([*leads, *rest][:count])
+
+
+def _offset_seconds(value: object) -> float | None:
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ return float(value)
+ return colon_duration_seconds(value) if isinstance(value, str) else None
+
+
+def _offset_label(seconds: float) -> str:
+ minutes = int(seconds // 60)
+ return f"{minutes:02d}:{int(seconds - minutes * 60):02d}"
+
+
+def _recording_start(extra: dict[str, object]) -> datetime | None:
+ start = text_of(extra.get("recording_start_time")) or text_of(extra.get("session_start_time"))
+ try:
+ return datetime.fromisoformat(start) if start else None
+ except ValueError:
+ return None
+
+
+def _recording(signal: SignalInput) -> contracts.RecordingTarget | None:
+ session_id = text_of(signal.extra.get("session_id"))
+ if not plays_recording(signal) or session_id is None:
+ return None
+ offset = _offset_seconds(signal.extra.get("start_time"))
+ start = _recording_start(signal.extra)
+ seek = max(offset - _PLAYER_LEAD_IN_SECONDS, 0) if offset is not None else None
+ return contracts.RecordingTarget(
+ session_id=session_id,
+ start_at=start + timedelta(seconds=seek) if start and seek is not None else None,
+ offset=_offset_label(offset) if offset is not None else None,
+ seek_seconds=int(seek) if seek is not None else None,
+ )
+
+
+def _scout_link(signal: SignalInput) -> contracts.PageLink | None:
+ thread = slack_thread(signal)
+ if thread:
+ return contracts.PageLink(url=thread, text="Open thread")
+ file = code_file(signal)
+ short_finding = len(signal.content) <= _SHORT_FINDING_CHARS
+ return contracts.PageLink(url=github_file_url(file), text="Open file") if file and short_finding else None
+
+
+def _github_link(signal: SignalInput) -> contracts.PageLink | None:
+ url = safe_http_url(text_of(signal.extra.get("html_url")) or "")
+ label = "Open pull request" if is_pull_request(signal) else "Open issue"
+ return contracts.PageLink(url=url, text=label) if url else None
+
+
+_EXTERNAL_LINKS: dict[str, Callable[[SignalInput], contracts.PageLink | None]] = {
+ "signals_scout": _scout_link,
+ "github": _github_link,
+}
+
+
+def _external_link(signal: SignalInput) -> contracts.PageLink | None:
+ link = _EXTERNAL_LINKS.get(signal.source_product)
+ return link(signal) if link else None
+
+
+def signal_view(signal: SignalInput) -> contracts.SignalView:
+ return contracts.SignalView(
+ signal_id=signal.signal_id,
+ source_product=signal.source_product,
+ source_type=signal.source_type,
+ source_id=signal.source_id,
+ content=signal.content,
+ timestamp=signal.timestamp,
+ extra=signal.extra,
+ headline=headline(signal),
+ lead=detail(signal).lead,
+ meta=meta(signal),
+ cited=cited_source(signal),
+ recording=_recording(signal),
+ link=_external_link(signal),
+ preview=preview(signal),
+ )
diff --git a/products/today/backend/logic/formats.py b/products/today/backend/logic/formats.py
new file mode 100644
index 000000000000..26bec41dcf37
--- /dev/null
+++ b/products/today/backend/logic/formats.py
@@ -0,0 +1,110 @@
+from collections.abc import Callable
+
+from posthog.dataclasses import frozen
+
+_GITHUB_PREFIX = "https://github.com/"
+_PATH_PUNCTUATION = frozenset(".-")
+_ISO_DATE_LENGTH = 10
+_ISO_DATE_DASHES = (4, 7)
+
+
+@frozen
+class GitHubLink:
+ start: int
+ end: int
+ kind: str
+ number: str
+
+
+def is_word_char(char: str) -> bool:
+ return char.isascii() and (char.isalnum() or char == "_")
+
+
+def is_digit(char: str) -> bool:
+ return "0" <= char <= "9"
+
+
+def digits_end(text: str, start: int) -> int:
+ end = start
+ while end < len(text) and is_digit(text[end]):
+ end += 1
+ return end
+
+
+def _path_part_end(text: str, start: int) -> int:
+ end = start
+ while end < len(text) and (is_word_char(text[end]) or text[end] in _PATH_PUNCTUATION):
+ end += 1
+ return end
+
+
+def _github_link_at(text: str, start: int) -> GitHubLink | None:
+ owner_start = start + len(_GITHUB_PREFIX)
+ owner_end = _path_part_end(text, owner_start)
+ if owner_end == owner_start or not text.startswith("/", owner_end):
+ return None
+ repo_end = _path_part_end(text, owner_end + 1)
+ if repo_end == owner_end + 1:
+ return None
+ for kind in ("pull", "issues"):
+ marker = f"/{kind}/"
+ number_start = repo_end + len(marker)
+ number_end = digits_end(text, number_start)
+ if text.startswith(marker, repo_end) and number_end > number_start:
+ return GitHubLink(start=start, end=number_end, kind=kind, number=text[number_start:number_end])
+ return None
+
+
+def github_links(text: str, accept: Callable[[GitHubLink], bool] = lambda link: True) -> list[GitHubLink]:
+ links: list[GitHubLink] = []
+ index = text.find(_GITHUB_PREFIX)
+ while index >= 0:
+ link = _github_link_at(text, index)
+ if link is not None and accept(link):
+ links.append(link)
+ index = text.find(_GITHUB_PREFIX, link.end)
+ else:
+ index = text.find(_GITHUB_PREFIX, index + 1)
+ return links
+
+
+def _is_iso_date(candidate: str) -> bool:
+ return len(candidate) == _ISO_DATE_LENGTH and all(
+ char == "-" if index in _ISO_DATE_DASHES else is_digit(char) for index, char in enumerate(candidate)
+ )
+
+
+def _word_boundary(text: str, index: int) -> bool:
+ before = text[index - 1] if index > 0 else ""
+ after = text[index] if index < len(text) else ""
+ return is_word_char(before) != is_word_char(after)
+
+
+def replace_iso_dates(text: str, replacement: Callable[[int, int, int, str], str]) -> str:
+ parts: list[str] = []
+ last = 0
+ index = 0
+ while index + _ISO_DATE_LENGTH <= len(text):
+ end = index + _ISO_DATE_LENGTH
+ candidate = text[index:end]
+ if _is_iso_date(candidate) and _word_boundary(text, index) and _word_boundary(text, end):
+ parts.append(text[last:index])
+ parts.append(replacement(int(candidate[:4]), int(candidate[5:7]), int(candidate[8:]), candidate))
+ last = end
+ index = end
+ else:
+ index += 1
+ parts.append(text[last:])
+ return "".join(parts)
+
+
+def colon_duration_seconds(value: str) -> float | None:
+ units = value.split(":")
+ if not all(1 <= len(unit) <= 2 and all(is_digit(char) for char in unit) for unit in units):
+ return None
+ scales = (1, 60, 3600, 86400, 604800)
+ return float(sum(int(unit) * scale for unit, scale in zip(reversed(units), scales)))
+
+
+def collapsed_whitespace(text: str) -> str:
+ return " ".join(text.split())
diff --git a/products/today/backend/logic/impact.py b/products/today/backend/logic/impact.py
new file mode 100644
index 000000000000..a960d0be9bb5
--- /dev/null
+++ b/products/today/backend/logic/impact.py
@@ -0,0 +1,183 @@
+import math
+from datetime import datetime
+from decimal import ROUND_HALF_UP, Decimal
+
+from posthog.dataclasses import frozen
+
+from ..facade import contracts
+from ..facade.enums import ImpactNumberKey
+from .evidence import signal_view
+from .signal_text import RECORDING_SOURCES, SignalInput, js_number, text_of
+
+_MIN_TICKETS = 2
+_WEEKS_FROM_DAYS = 14
+_MS_PER_HOUR = 3_600_000
+_SECONDS_PER_DAY = 86_400
+_TIME_LEAD = "takes "
+_TIME_TAIL = "ms on average"
+_CALLS_TAIL = " calls in last 24h"
+_TIME_CHARS = frozenset("0123456789.,")
+_CALLS_CHARS = frozenset("0123456789,")
+_TICKET_TYPE = "ticket"
+_QUERY_HOURS_SENTENCE = "database time a day, worked out from the query’s pganalyze stats."
+
+
+@frozen
+class _Occurrences:
+ count: int
+ oldest: datetime
+ newest: datetime
+
+
+@frozen
+class _QueryCost:
+ signal: SignalInput
+ average_ms: str
+ calls_per_day: str
+ hours: float
+
+
+@frozen
+class _Occurrence:
+ kind: str
+ key: str
+
+
+def _occurrence_of(signal: SignalInput) -> _Occurrence | None:
+ if signal.source_product in RECORDING_SOURCES:
+ session = text_of(signal.extra.get("session_id"))
+ return _Occurrence(kind="sessions", key=session) if session else None
+ if signal.source_type == _TICKET_TYPE:
+ ticket = js_number(signal.extra.get("ticket_number")) or signal.source_id
+ return _Occurrence(kind="tickets", key=f"{signal.source_product}:{ticket}") if ticket else None
+ if signal.source_product == "analytics" and signal.source_type == "anomaly_investigation":
+ return _Occurrence(kind="alerts", key=text_of(signal.extra.get("alert_check_id")) or signal.source_id)
+ return None
+
+
+def _is_ticket(signal: SignalInput) -> bool:
+ occurrence = _occurrence_of(signal)
+ return occurrence is not None and occurrence.kind == "tickets"
+
+
+def _occurrences_by_kind(signals: list[SignalInput]) -> dict[str, _Occurrences]:
+ first_seen: dict[str, dict[str, datetime]] = {}
+ for signal in signals:
+ occurrence = _occurrence_of(signal)
+ if occurrence is None:
+ continue
+ times = first_seen.setdefault(occurrence.kind, {})
+ times[occurrence.key] = min(signal.timestamp, times.get(occurrence.key, signal.timestamp))
+ return {
+ kind: _Occurrences(count=len(times), oldest=min(times.values()), newest=max(times.values()))
+ for kind, times in first_seen.items()
+ }
+
+
+def last_occurrence(signals: list[SignalInput]) -> datetime | None:
+ occurrences = [signal.timestamp for signal in signals if _occurrence_of(signal) is not None]
+ return max(occurrences) if occurrences else None
+
+
+def _amount(text: str) -> float:
+ try:
+ return float(text.replace(",", ""))
+ except ValueError:
+ return math.nan
+
+
+def _grouped(value: float, max_fraction_digits: int) -> str:
+ rounded = Decimal(repr(value)).quantize(Decimal(1).scaleb(-max_fraction_digits), rounding=ROUND_HALF_UP)
+ text = f"{rounded:,f}"
+ return text.rstrip("0").rstrip(".") if "." in text else text
+
+
+def _fixed(value: float, digits: int) -> str:
+ return str(Decimal(value).quantize(Decimal(1).scaleb(-digits), rounding=ROUND_HALF_UP))
+
+
+def _average_ms(content: str) -> str | None:
+ lowered = content.lower()
+ index = lowered.find(_TIME_LEAD)
+ while index >= 0:
+ start = index + len(_TIME_LEAD)
+ end = start
+ while end < len(content) and content[end] in _TIME_CHARS:
+ end += 1
+ tail = end
+ while tail < len(content) and content[tail].isspace():
+ tail += 1
+ if end > start and lowered.startswith(_TIME_TAIL, tail):
+ return content[start:end]
+ index = lowered.find(_TIME_LEAD, index + 1)
+ return None
+
+
+def _calls_per_day(content: str) -> str | None:
+ lowered = content.lower()
+ index = lowered.find(_CALLS_TAIL)
+ while index >= 0:
+ start = index
+ while start > 0 and content[start - 1] in _CALLS_CHARS:
+ start -= 1
+ if start < index:
+ return content[start:index]
+ index = lowered.find(_CALLS_TAIL, index + 1)
+ return None
+
+
+def _query_cost(signals: list[SignalInput]) -> _QueryCost | None:
+ for signal in signals:
+ time = _average_ms(signal.content) if signal.source_product == "pganalyze" else None
+ calls = _calls_per_day(signal.content)
+ if not time or not calls:
+ continue
+ count = _amount(calls)
+ hours = _amount(time) * count / _MS_PER_HOUR
+ if math.isfinite(hours) and hours > 0:
+ return _QueryCost(signal=signal, average_ms=time, calls_per_day=_grouped(count, 0), hours=hours)
+ return None
+
+
+def _occurrence_span(occurrences: _Occurrences) -> str:
+ days = max(1, int((occurrences.newest - occurrences.oldest).total_seconds() // _SECONDS_PER_DAY) + 1)
+ if days >= _WEEKS_FROM_DAYS:
+ return f"over {round(days / 7)} weeks"
+ return f"over {days} days" if days > 1 else "in one day"
+
+
+def _ticket_number(signals: list[SignalInput]) -> contracts.ImpactNumber | None:
+ tickets = _occurrences_by_kind(signals).get("tickets")
+ if tickets is None or tickets.count < _MIN_TICKETS:
+ return None
+ ticket = next((signal for signal in signals if _is_ticket(signal)), None)
+ return contracts.ImpactNumber(
+ key=ImpactNumberKey.TICKETS,
+ value=str(tickets.count),
+ sentence=f"support tickets {_occurrence_span(tickets)}.",
+ signal=signal_view(ticket) if ticket else None,
+ values=[],
+ working=None,
+ )
+
+
+def _query_hours_number(signals: list[SignalInput]) -> contracts.ImpactNumber | None:
+ cost = _query_cost(signals)
+ if cost is None:
+ return None
+ hours = _grouped(cost.hours, 1 if cost.hours < 10 else 0)
+ return contracts.ImpactNumber(
+ key=ImpactNumberKey.QUERY_HOURS,
+ value=f"{hours} {'hour' if hours == '1' else 'hours'}",
+ sentence=_QUERY_HOURS_SENTENCE,
+ signal=signal_view(cost.signal),
+ values=[cost.average_ms, cost.calls_per_day],
+ working=contracts.ImpactWorking(
+ expression=f"{cost.average_ms} ms × {cost.calls_per_day} calls",
+ result=f"{_fixed(cost.hours, 2)} hours a day",
+ ),
+ )
+
+
+def impact_numbers(signals: list[SignalInput]) -> list[contracts.ImpactNumber]:
+ return [number for number in (_ticket_number(signals), _query_hours_number(signals)) if number is not None]
diff --git a/products/today/backend/logic/prose.py b/products/today/backend/logic/prose.py
new file mode 100644
index 000000000000..d9ae59dba5e8
--- /dev/null
+++ b/products/today/backend/logic/prose.py
@@ -0,0 +1,95 @@
+import re
+
+from .formats import replace_iso_dates
+from .report_text import MARKDOWN, MONTHS, readable_date, rendered_text
+from .sentences import split_markdown_sentences
+
+_SENTENCE_BREAK = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9\"“(*`])")
+_SENTENCE_END = re.compile(r"[.!?](?=\s+[A-Z“\"(])")
+_MIN_SENTENCE_CHARS = 40
+_MONTH_DAY = re.compile(r"(?<=\bon )(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\b", re.ASCII)
+_BARE_INTEGER = re.compile(r"(?<![\w#.,/:-])(?:\d{5,7}|(?!19|20)\d{4}(?= [a-z]))(?![\w/:-]|[.,]\d)", re.ASCII)
+_CODE_BLOCK = re.compile(r"```[\s\S]*?(?:```|\Z)")
+_PARAGRAPH_BREAK = re.compile(r"\n\s*\n")
+_SENTENCE_ENDS = (".", "!", "?", ":")
+_PLAIN_LINE_STEPS: list[tuple[re.Pattern[str], str]] = [
+ (re.compile(r"^C:\s*"), ""),
+ (re.compile(r"\[([^\]]+)\]\([^)]*\)"), r"\1"),
+ (re.compile(r"(?:slack (?:reply|thread|message)|thread|link):\s*https?://\S+", re.IGNORECASE), ""),
+ (re.compile(r"\s*\(\s*https?://[^\s)]+\s*\)"), ""),
+ (re.compile(r"https?://\S+"), ""),
+]
+_CODE_SPAN = re.compile(r"`([^`]+)`")
+_MARKERS = re.compile(r"[`*]")
+_ESCAPED = re.compile(r"\\([.#()\[\]_*-])")
+_WHITESPACE = re.compile(r"\s+")
+_SPACE_BEFORE_PUNCTUATION = re.compile(r"\s+([.,;:])")
+
+
+def split_prose(line: str) -> list[str]:
+ return _SENTENCE_BREAK.split(line)
+
+
+def _quoted_code(match: re.Match[str]) -> str:
+ code = match.group(1)
+ return f"“{code}”" if re.search(r"\s", code) else code
+
+
+def plain_line(line: str) -> str:
+ text = line
+ for pattern, replacement in _PLAIN_LINE_STEPS:
+ text = pattern.sub(replacement, text)
+ text = _CODE_SPAN.sub(_quoted_code, text)
+ text = _ESCAPED.sub(r"\1", _MARKERS.sub("", text))
+ return _SPACE_BEFORE_PUNCTUATION.sub(r"\1", _WHITESPACE.sub(" ", text)).strip()
+
+
+def _inside_quote(text: str) -> bool:
+ opened = text.count("“") - text.count("”")
+ return opened > 0 or text.count('"') % 2 == 1
+
+
+def first_sentence(text: str) -> str:
+ for match in _SENTENCE_END.finditer(text):
+ end = match.start() + 1
+ if end >= _MIN_SENTENCE_CHARS and not _inside_quote(text[:end]):
+ return text[:end]
+ return text
+
+
+def _month_day(match: re.Match[str]) -> str:
+ return f"{int(match.group(2))} {MONTHS[int(match.group(1)) - 1]}"
+
+
+def readable_excerpt(text: str) -> str:
+ dated = _MONTH_DAY.sub(_month_day, replace_iso_dates(text, readable_date))
+ return _BARE_INTEGER.sub(lambda match: f"{int(match.group(0)):,}", dated)
+
+
+def without_code_blocks(text: str) -> str:
+ return _CODE_BLOCK.sub("\n", text)
+
+
+def paragraphs(markdown: str) -> list[str]:
+ return [paragraph.strip() for paragraph in _PARAGRAPH_BREAK.split(markdown) if paragraph.strip()]
+
+
+def _block_lines(markdown: str) -> list[str]:
+ inline_blocks = [token.content for token in MARKDOWN.parse(markdown) if token.type == "inline"]
+ return [line.strip() for block in inline_blocks for line in block.split("\n") if line.strip()]
+
+
+def _balanced(text: str, marker: str) -> str:
+ return f"{text}{marker}" if text.count(marker) % 2 == 1 else text
+
+
+def concise_text(markdown: str | None, max_chars: int) -> str:
+ lines = [line if line.endswith(_SENTENCE_ENDS) else f"{line}." for line in _block_lines(markdown or "")]
+ pieces = [sentence.strip() for line in lines for _, sentence in split_markdown_sentences(line) if sentence.strip()]
+ text = ""
+ for piece in pieces:
+ candidate = f"{text} {piece}" if text else piece
+ if text and len(rendered_text(candidate)) > max_chars:
+ break
+ text = candidate
+ return _balanced(_balanced(text, "**"), "`")
diff --git a/products/today/backend/logic/report_page.py b/products/today/backend/logic/report_page.py
new file mode 100644
index 000000000000..f39f468dcbd6
--- /dev/null
+++ b/products/today/backend/logic/report_page.py
@@ -0,0 +1,88 @@
+from markdown_it.token import Token
+
+from posthog.models import Team
+
+from products.signals.backend.facade import api as signals
+
+from ..facade import contracts
+from . import evidence, impact, samples
+from .formats import digits_end, github_links, is_word_char
+from .prose import concise_text
+from .report_text import MARKDOWN
+
+_PROPOSAL_CHARS = 260
+_IMPACT_CHARS = 180
+_PULL_REFERENCE = "PR #"
+
+
+def _prose_outside_code(markdown: str) -> str:
+ tokens: list[Token] = MARKDOWN.parseInline(markdown)
+ return "".join(child.content for token in tokens for child in token.children or [] if child.type == "text")
+
+
+def impact_sentence(impact: str | None) -> str:
+ text = concise_text(impact, _IMPACT_CHARS)
+ return text if any(char.isdigit() for char in _prose_outside_code(text)) else ""
+
+
+def proposal(page: signals.ReportPageSource) -> str:
+ fallback = page.action_prompts[0] if page.action_prompts else None
+ return concise_text(page.sections.solution or fallback, _PROPOSAL_CHARS)
+
+
+def _pull_reference_numbers(text: str) -> list[str]:
+ numbers: list[str] = []
+ index = text.find(_PULL_REFERENCE)
+ while index >= 0:
+ number_start = index + len(_PULL_REFERENCE)
+ number_end = digits_end(text, number_start)
+ starts_word = index == 0 or not is_word_char(text[index - 1])
+ ends_word = number_end == len(text) or not is_word_char(text[number_end])
+ if starts_word and ends_word and number_end > number_start:
+ numbers.append(text[number_start:number_end])
+ index = text.find(_PULL_REFERENCE, number_end)
+ else:
+ index = text.find(_PULL_REFERENCE, index + 1)
+ return numbers
+
+
+def _pull_requests_in(text: str | None, repo_slug: str | None) -> dict[str, str | None]:
+ body = text or ""
+ found: dict[str, str | None] = {
+ number: f"https://github.com/{repo_slug}/pull/{number}" if repo_slug else None
+ for number in _pull_reference_numbers(body)
+ }
+ found |= {link.number: body[link.start : link.end] for link in github_links(body, lambda link: link.kind == "pull")}
+ return found
+
+
+def _only_pull_request(text: str | None, repo_slug: str | None) -> contracts.PullRequestLink | None:
+ found = _pull_requests_in(text, repo_slug)
+ if len(found) != 1:
+ return None
+ [(number, url)] = found.items()
+ return contracts.PullRequestLink(url=url, number=int(number)) if url else None
+
+
+def report_page(page: signals.ReportPageSource) -> contracts.ReportPage:
+ solution = page.sections.solution
+ inputs = evidence.newest_first(page.signals)
+ return contracts.ReportPage(
+ lead=page.sections.lead,
+ proposal=proposal(page),
+ impact_sentence=impact_sentence(page.sections.impact),
+ named_pull_request=_only_pull_request(solution, page.repo_slug)
+ or _only_pull_request(page.summary, page.repo_slug),
+ solution_names_pull_request=bool(_pull_requests_in(solution, page.repo_slug)),
+ evidence=[evidence.signal_view(signal) for signal in evidence.pick_evidence(inputs)],
+ source_count=evidence.distinct_evidence_count(inputs),
+ impact_numbers=impact.impact_numbers(inputs),
+ last_seen=impact.last_occurrence(inputs),
+ )
+
+
+def page_source(*, team: Team, report_id: str) -> signals.ReportPageSource | None:
+ if not samples.is_sample_id(report_id):
+ return signals.report_page_source(team=team, report_id=report_id)
+ sample = samples.sample_report(report_id)
+ return samples.sample_page_source(sample) if sample is not None else None
diff --git a/products/today/backend/logic/report_text.py b/products/today/backend/logic/report_text.py
new file mode 100644
index 000000000000..e646c2643c9e
--- /dev/null
+++ b/products/today/backend/logic/report_text.py
@@ -0,0 +1,66 @@
+from datetime import date
+
+from markdown_it import MarkdownIt
+from markdown_it.token import Token
+
+from .formats import GitHubLink, collapsed_whitespace, github_links, is_word_char, replace_iso_dates
+
+MARKDOWN = MarkdownIt("commonmark")
+_RAW_TOKENS = frozenset({"code_inline", "html_inline"})
+_ALT_TOKENS = _RAW_TOKENS | {"text"}
+_BREAK_TOKENS = frozenset({"softbreak", "hardbreak"})
+_LINK_OPENERS = frozenset("(<[")
+MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
+
+
+def readable_date(year: int, month: int, day: int, original: str) -> str:
+ try:
+ shown = date(year, month, day)
+ except ValueError:
+ return original
+ return f"{shown.day} {MONTHS[shown.month - 1]}"
+
+
+def _is_bare_link(text: str, link: GitHubLink) -> bool:
+ opened = link.start > 0 and text[link.start - 1] in _LINK_OPENERS
+ following = text[link.end] if link.end < len(text) else ""
+ return not opened and not is_word_char(following) and following != "/"
+
+
+def _shortened_github_links(text: str) -> str:
+ parts: list[str] = []
+ last = 0
+ for link in github_links(text, lambda link: _is_bare_link(text, link)):
+ parts.extend((text[last : link.start], f"#{link.number}"))
+ last = link.end
+ parts.append(text[last:])
+ return "".join(parts)
+
+
+def _prose_text(text: str, in_link: bool) -> str:
+ return replace_iso_dates(text if in_link else _shortened_github_links(text), readable_date)
+
+
+def _inline_text(tokens: list[Token]) -> str:
+ parts: list[str] = []
+ link_depth = 0
+ for token in tokens:
+ if token.type == "link_open":
+ link_depth += 1
+ elif token.type == "link_close":
+ link_depth -= 1
+ elif token.type == "text":
+ parts.append(_prose_text(token.content, link_depth > 0))
+ elif token.type in _RAW_TOKENS:
+ parts.append(token.content)
+ elif token.type in _BREAK_TOKENS:
+ parts.append(" ")
+ elif token.type == "image":
+ parts.append("".join(child.content for child in token.children or [] if child.type in _ALT_TOKENS))
+ return "".join(parts)
+
+
+def rendered_text(markdown: str) -> str:
+ """The text a reader sees. Dates and bare GitHub links change only in prose, never in code or link targets."""
+ tokens: list[Token] = MARKDOWN.parseInline(collapsed_whitespace(markdown))
+ return "".join(_inline_text(token.children or []) for token in tokens)
diff --git a/products/today/backend/logic/sample_reports.json b/products/today/backend/logic/sample_reports.json
new file mode 100644
index 000000000000..3768572679ad
--- /dev/null
+++ b/products/today/backend/logic/sample_reports.json
@@ -0,0 +1,272 @@
+[
+ {
+ "id": "sample-pr",
+ "summary": "Safari users can’t finish checkout since Tuesday’s deploy, because the checkout sends an empty billing address to the payment service.\n\n## Problem\n\nThe deploy moved the address form into a step that Safari unmounts before payment. The payment request then goes out without the billing address.\n\n## Impact\n\nSafari checkout completion fell by 12 points while Chrome stayed flat.\n\n## Solution\n\nKeep the billing address in the checkout state, and send it with the payment request. PR #9123 does this and adds a Safari test.\n\n## Expected impact\n\nSafari checkout completion returns to **about 54%**, the same as Chrome.",
+ "signals": [
+ {
+ "source_product": "error_tracking",
+ "source_type": "issue",
+ "content": "1,284 events. The same TypeError started after deploy #4821.",
+ "hours_ago": 2
+ },
+ {
+ "source_product": "session_replay",
+ "source_type": "session_problem",
+ "content": "38 recordings. Safari users stop after they submit payment.",
+ "hours_ago": 3
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "−12 points. Safari completion fell while Chrome stayed flat.",
+ "hours_ago": 4
+ },
+ {
+ "source_product": "github",
+ "source_type": "issue",
+ "content": "PR #9123. The fix restores the missing billing address.",
+ "hours_ago": 5
+ }
+ ]
+ },
+ {
+ "id": "sample-exp",
+ "summary": "**One-page checkout won. It is safe to ship.**\n\nThe shorter checkout completed more often than the current flow. It did not increase refunds, support requests, or payment errors.\n\nThe result passed the team’s decision threshold. You can send the winning flow to everyone today.",
+ "signals": [
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Experiments · 95% likely. The one-page version is the likely winner.",
+ "hours_ago": 3
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "+6.4%. Checkout completion rose from 54.1% to 57.6%.",
+ "hours_ago": 4
+ },
+ {
+ "source_product": "session_replay",
+ "source_type": "session_problem",
+ "content": "Fewer exits. People no longer pause between address and payment.",
+ "hours_ago": 5
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Feature flags · Ready. The winning variant can reach everyone now.",
+ "hours_ago": 6
+ }
+ ]
+ },
+ {
+ "id": "sample-safari",
+ "summary": "**Safari users reach payment, then get stuck.**\n\nThe recordings show the same sequence. A person enters a card, submits payment, and sees no progress.\n\nThe problem affects Safari 17 after Tuesday’s deploy. Chrome sessions continue through the same step.",
+ "signals": [
+ {
+ "source_product": "session_replay",
+ "source_type": "session_problem",
+ "content": "38 sessions. Every sampled session stalls after payment.",
+ "hours_ago": 5
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "49% complete. Safari trails Chrome by 13 points.",
+ "hours_ago": 6
+ },
+ {
+ "source_product": "error_tracking",
+ "source_type": "issue",
+ "content": "address.ts:42. The billing address is empty at submission.",
+ "hours_ago": 7
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Data warehouse · Safari 17. Older Safari versions stay near their baseline.",
+ "hours_ago": 8
+ }
+ ]
+ },
+ {
+ "id": "sample-error",
+ "summary": "**One new error is blocking checkout completion.**\n\nThe error begins when checkout formats an empty billing address. It started with deploy #4821 and appears only after payment submission.\n\nFour hundred and twelve people saw it. The same error also explains the Safari conversion drop.",
+ "signals": [
+ {
+ "source_product": "error_tracking",
+ "source_type": "issue",
+ "content": "1,284 events. TypeError in formatAddress at address.ts:42.",
+ "hours_ago": 7
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "412 users. Most affected users arrived from Safari.",
+ "hours_ago": 8
+ },
+ {
+ "source_product": "session_replay",
+ "source_type": "session_problem",
+ "content": "19 sampled. The submit button stops after one click.",
+ "hours_ago": 9
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Data warehouse · Deploy #4821. The first event arrived six minutes after release.",
+ "hours_ago": 10
+ }
+ ]
+ },
+ {
+ "id": "sample-llm",
+ "summary": "**Document summaries became more expensive overnight.**\n\nThe summarize-doc workflow now spends 31% more per active user. Usage stayed flat, so higher traffic does not explain the change.\n\nMost of the increase comes from a model change and longer prompts. The quality score did not improve.",
+ "signals": [
+ {
+ "source_product": "llm_analytics",
+ "source_type": "evaluation",
+ "content": "+31% cost. Cost rose while the number of summaries stayed flat.",
+ "hours_ago": 9
+ },
+ {
+ "source_product": "llm_analytics",
+ "source_type": "evaluation",
+ "content": "Tracing · 2.4× tokens. The new prompt repeats the source document.",
+ "hours_ago": 10
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Usage flat. The same number of people used summaries.",
+ "hours_ago": 11
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Data warehouse · summarize-doc. One workflow accounts for 84% of the increase.",
+ "hours_ago": 12
+ }
+ ]
+ },
+ {
+ "id": "sample-nps",
+ "summary": "**Pricing is the main reason detractors hesitate.**\n\nTwenty-three detractors mention pricing in their survey response. Most of them visited the new pricing page before they replied.\n\nThey understand the product, but they cannot predict the bill. The confusion is strongest among small teams with growing data volume.",
+ "signals": [
+ {
+ "source_product": "conversations",
+ "source_type": "feedback",
+ "content": "Surveys · NPS 32. Twenty-three of 61 detractors mention pricing.",
+ "hours_ago": 20
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Customer analytics · Small teams. Growing teams express the most uncertainty.",
+ "hours_ago": 21
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "71% visited. Most detractors saw the new pricing page.",
+ "hours_ago": 22
+ },
+ {
+ "source_product": "session_replay",
+ "source_type": "session_problem",
+ "content": "3 comparisons. People revisit the usage table before leaving.",
+ "hours_ago": 23
+ }
+ ]
+ },
+ {
+ "id": "sample-browser",
+ "summary": "**Safari accounts for the checkout gap.**\n\nChrome and Firefox remain near their usual completion rates. Safari 17 falls sharply after payment submission.\n\nThe browser comparison isolates the problem to one checkout path. Mobile Safari shows the largest drop.",
+ "signals": [
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "−13 points. Safari trails the other browsers at checkout.",
+ "hours_ago": 26
+ },
+ {
+ "source_product": "session_replay",
+ "source_type": "session_problem",
+ "content": "38 sessions. The same payment stall appears across sampled sessions.",
+ "hours_ago": 27
+ },
+ {
+ "source_product": "error_tracking",
+ "source_type": "issue",
+ "content": "1,284 events. The error appears mainly in Safari 17.",
+ "hours_ago": 28
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Data warehouse · 3 browsers. Chrome and Firefox stay near their baseline.",
+ "hours_ago": 29
+ }
+ ]
+ },
+ {
+ "id": "sample-guardrails",
+ "summary": "**The winning checkout passed every guardrail.**\n\nThe shorter checkout increased completion without increasing refunds, support requests, or payment failures.\n\nEach guardrail stayed within its agreed range. The result is ready for a full rollout.",
+ "signals": [
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Experiments · 4 passed. Every release guardrail stayed within range.",
+ "hours_ago": 30
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "+6.4%. Checkout completion improved for the winning variant.",
+ "hours_ago": 31
+ },
+ {
+ "source_product": "error_tracking",
+ "source_type": "issue",
+ "content": "No increase. Payment and checkout errors stayed flat.",
+ "hours_ago": 32
+ },
+ {
+ "source_product": "conversations",
+ "source_type": "feedback",
+ "content": "Surveys · Support flat. The new flow did not increase support requests.",
+ "hours_ago": 33
+ }
+ ]
+ },
+ {
+ "id": "sample-traces",
+ "summary": "**The new summary model repeats the source document.**\n\nRecent traces show the source text twice in the prompt. This duplication explains most of the token increase.\n\nThe model change did not improve the quality score. The previous model remains the lower-cost option.",
+ "signals": [
+ {
+ "source_product": "llm_analytics",
+ "source_type": "evaluation",
+ "content": "Tracing · 24 traces. Each sampled trace contains the source text twice.",
+ "hours_ago": 40
+ },
+ {
+ "source_product": "llm_analytics",
+ "source_type": "evaluation",
+ "content": "2.4× tokens. Input tokens rose after the model change.",
+ "hours_ago": 41
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Usage flat. Traffic did not cause the higher cost.",
+ "hours_ago": 42
+ },
+ {
+ "source_product": "analytics",
+ "source_type": "anomaly_investigation",
+ "content": "Data warehouse · Quality flat. The quality score did not improve.",
+ "hours_ago": 43
+ }
+ ]
+ }
+]
diff --git a/products/today/backend/logic/samples.py b/products/today/backend/logic/samples.py
new file mode 100644
index 000000000000..f56fccc9527b
--- /dev/null
+++ b/products/today/backend/logic/samples.py
@@ -0,0 +1,69 @@
+import json
+from datetime import UTC, datetime, timedelta
+from functools import cache
+from pathlib import Path
+
+from posthog.dataclasses import frozen
+
+from products.signals.backend.facade import api as signals
+
+SAMPLE_ID_PREFIX = "sample-"
+_SAMPLE_REPO = "example/hedgebox"
+_SAMPLES_PATH = Path(__file__).with_name("sample_reports.json")
+
+
+@frozen
+class SampleSignal:
+ source_product: str
+ source_type: str
+ content: str
+ hours_ago: float
+
+
+@frozen
+class SampleReport:
+ id: str
+ summary: str
+ signals: list[SampleSignal]
+
+
+@cache
+def _samples() -> dict[str, SampleReport]:
+ rows = json.loads(_SAMPLES_PATH.read_text())
+ return {
+ row["id"]: SampleReport(**{**row, "signals": [SampleSignal(**signal) for signal in row["signals"]]})
+ for row in rows
+ }
+
+
+def is_sample_id(report_id: str) -> bool:
+ return report_id.startswith(SAMPLE_ID_PREFIX)
+
+
+def sample_report(report_id: str) -> SampleReport | None:
+ return _samples().get(report_id)
+
+
+def _sample_signals(sample: SampleReport, now: datetime) -> list[signals.ReportSignal]:
+ return [
+ signals.ReportSignal(
+ signal_id=f"{sample.id}-signal-{index}",
+ content=signal.content,
+ source_product=signal.source_product,
+ source_type=signal.source_type,
+ source_id=f"{sample.id}-source-{index}",
+ timestamp=now - timedelta(hours=signal.hours_ago),
+ extra={},
+ )
+ for index, signal in enumerate(sample.signals)
+ ]
+
+
+def sample_page_source(sample: SampleReport) -> signals.ReportPageSource:
+ return signals.ReportPageSource(
+ summary=sample.summary,
+ sections=signals.report_sections(sample.summary),
+ action_prompts=[],
+ repo_slug=_SAMPLE_REPO,
+ signals=_sample_signals(sample, datetime.now(UTC)),
+ )
diff --git a/products/today/backend/logic/sentences.py b/products/today/backend/logic/sentences.py
new file mode 100644
index 000000000000..4bc9fb0f54c9
--- /dev/null
+++ b/products/today/backend/logic/sentences.py
@@ -0,0 +1,108 @@
+_TERMINATORS = set(".!?")
+_CLOSE = set("\"'”’“‘)]}»«([{")
+_CONTINUE = set(",;:-")
+_MARKDOWN_CLOSE = _CLOSE | set("*_`~")
+_BACKTICK = "`"
+_CODE_MASK = "x"
+_TITLES = frozenset({"dr", "mr", "mrs", "ms", "prof", "st", "jr", "sr"})
+
+
+def _continues_sentence(rest: str) -> bool:
+ for char in rest:
+ if char.isalpha():
+ return char.islower()
+ if char in _TERMINATORS:
+ return False
+ return False
+
+
+def _ends_with_title(text: str, term_start: int) -> bool:
+ word_start = term_start
+ while word_start > 0 and text[word_start - 1].isalpha():
+ word_start -= 1
+ starts_word = word_start == 0 or not text[word_start - 1].isalnum()
+ return starts_word and text[word_start:term_start].lower() in _TITLES
+
+
+def _period_continues(text: str, term_start: int, term_end: int, next_index: int) -> bool:
+ following = text[next_index] if next_index < len(text) else ""
+ preceding = text[term_start - 1] if term_start > 0 else ""
+ touching = next_index == term_end
+ if touching and (following.isdigit() or (preceding.isalpha() and following.isupper())):
+ return True
+ if term_end - term_start == 1 and text[term_start] == "." and _ends_with_title(text, term_start):
+ return True
+ return _continues_sentence(text[next_index:])
+
+
+def _sentence_breaks(text: str, close: set[str]) -> list[int]:
+ breaks: list[int] = []
+ index = 0
+ while index < len(text):
+ if text[index] not in _TERMINATORS:
+ index += 1
+ continue
+ term_start = index
+ while index < len(text) and text[index] in _TERMINATORS:
+ index += 1
+ term_end = index
+ while index < len(text) and text[index] in close:
+ index += 1
+ while index < len(text) and text[index] in " \t\u00a0":
+ index += 1
+ if index >= len(text):
+ break
+ if text[index] in _CONTINUE or text[index] in _TERMINATORS:
+ continue
+ if text[term_end - 1] == "." and _period_continues(text, term_start, term_end, index):
+ continue
+ breaks.append(index)
+ return breaks
+
+
+def _sentences_at(text: str, breaks: list[int]) -> list[tuple[int, str]]:
+ edges = [0, *breaks, len(text)]
+ return [(start, text[start:end]) for start, end in zip(edges, edges[1:]) if start < end]
+
+
+def _backtick_run_end(text: str, start: int) -> int:
+ end = start
+ while end < len(text) and text[end] == _BACKTICK:
+ end += 1
+ return end
+
+
+def _closing_run(text: str, start: int, size: int) -> int | None:
+ index = start
+ while index < len(text):
+ if text[index] != _BACKTICK:
+ index += 1
+ continue
+ end = _backtick_run_end(text, index)
+ if end - index == size:
+ return index
+ index = end
+ return None
+
+
+def _without_code_spans(markdown: str) -> str:
+ masked = list(markdown)
+ index = 0
+ while index < len(markdown):
+ if markdown[index] != _BACKTICK:
+ index += 1
+ continue
+ opening_end = _backtick_run_end(markdown, index)
+ closing = _closing_run(markdown, opening_end, opening_end - index)
+ if closing is None:
+ index = opening_end
+ continue
+ masked[opening_end:closing] = [
+ _CODE_MASK if char in _TERMINATORS else char for char in markdown[opening_end:closing]
+ ]
+ index = closing + opening_end - index
+ return "".join(masked)
+
+
+def split_markdown_sentences(markdown: str) -> list[tuple[int, str]]:
+ return _sentences_at(markdown, _sentence_breaks(_without_code_spans(markdown), _MARKDOWN_CLOSE))
diff --git a/products/today/backend/logic/signal_previews.py b/products/today/backend/logic/signal_previews.py
new file mode 100644
index 000000000000..8f1049085e97
--- /dev/null
+++ b/products/today/backend/logic/signal_previews.py
@@ -0,0 +1,251 @@
+import re
+from collections.abc import Callable
+from dataclasses import replace
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+from ..facade import contracts
+from .prose import concise_text, paragraphs
+from .signal_text import RECORDING_SOURCES, SignalInput, code_file, detail, github_file_url, slack_thread, text_of
+
+_PREVIEW_CHARS = 240
+_MAX_EXCEPTIONS = 4
+_MAX_SIBLING_FILES = 2
+_FENCED_BLOCK = re.compile(r"```[^\n]*\n([\s\S]*?)(?:```|\Z)")
+_FRAME_LINE = re.compile(r"^(\S+) in (\S+) line (\d+)$")
+_IN_APP_PATH = re.compile(r"^(?:posthog|products|ee|common|services|frontend)/")
+_SECTION_LABEL = re.compile(r"^\*\*([^*\n]+?):\*\*\s*")
+_BARE_FILE_NAME = re.compile(r"`([\w-]+\.[a-z]{1,5})`", re.IGNORECASE | re.ASCII)
+_CHANNELS = {"slack": "Slack", "email": "Email", "widget": "Chat widget"}
+_CONVERSATION_MESSAGE = re.compile(r"(?:C|T|AI): ")
+
+SourcePreview = Callable[[SignalInput, contracts.SignalPreview], contracts.SignalPreview | None]
+
+
+def _sentence_case(value: str) -> str:
+ words = value.replace("_", " ").strip().lower()
+ return words[:1].upper() + words[1:]
+
+
+def _readable(signal: SignalInput, content: str) -> str:
+ found = detail(replace(signal, content=content))
+ return " ".join(part for part in (found.lead, found.rest) if part)
+
+
+@frozen
+class _Frame:
+ function: str
+ path: str
+ line: str
+
+
+@frozen
+class _Exception:
+ header: str
+ frames: list[_Frame]
+
+
+def exception_chain(content: str) -> list[contracts.PreviewLine]:
+ fenced = _FENCED_BLOCK.search(content)
+ trace = fenced.group(1) if fenced else ""
+ exceptions: list[_Exception] = []
+ for raw in trace.split("\n"):
+ line = raw.strip()
+ if not line:
+ continue
+ frame = _FRAME_LINE.match(line)
+ if frame and exceptions:
+ exceptions[-1].frames.append(_Frame(function=frame.group(1), path=frame.group(2), line=frame.group(3)))
+ elif not frame:
+ exceptions.append(_Exception(header=line, frames=[]))
+ if not any(exception.frames for exception in exceptions):
+ return []
+ prose = _FENCED_BLOCK.sub("", content, count=1)
+ lines: list[contracts.PreviewLine] = []
+ for index, exception in enumerate(exceptions):
+ if 0 < index < len(exceptions) - _MAX_EXCEPTIONS + 1:
+ continue
+ own = [frame for frame in exception.frames if _IN_APP_PATH.match(frame.path)]
+ candidates = own or exception.frames
+ shown = candidates[-1] if candidates else None
+ header = exception.header
+ if not (index == 0 and header in prose):
+ lines.append(contracts.PreviewLine(text=header if index == 0 else f"Caused by {header}", quiet=False))
+ if shown:
+ lines.append(
+ contracts.PreviewLine(text=f" {shown.path.split('/')[-1]}:{shown.line} {shown.function}", quiet=True)
+ )
+ return lines
+
+
+def _pganalyze_query(signal: SignalInput) -> str | None:
+ references = signal.extra.get("references")
+ if not isinstance(references, list):
+ return None
+ query = next((item for item in references if isinstance(item, dict) and item.get("kind") == "Query"), None)
+ return text_of(query.get("queryText")) if isinstance(query, dict) else None
+
+
+def body_paragraph(content: str, label: str | None = None, has_title: bool = True) -> str | None:
+ trimmed = content.strip()
+ title_end = trimmed.find("\n") if has_title else -1
+ body = paragraphs(trimmed[title_end + 1 :]) if title_end >= 0 or not has_title else []
+
+ def label_of(paragraph: str) -> str | None:
+ match = _SECTION_LABEL.match(paragraph)
+ return match.group(1).lower() if match else None
+
+ labelled = next((paragraph for paragraph in body if label and label_of(paragraph) == label.lower()), None)
+ chosen = labelled or next((paragraph for paragraph in body if not _SECTION_LABEL.match(paragraph)), None)
+ return (_SECTION_LABEL.sub("", chosen, count=1).strip() or None) if chosen else None
+
+
+def _github_state(extra: dict[str, Any]) -> str | None:
+ if isinstance(extra.get("merged_at"), str):
+ return "Merged"
+ open_state = text_of(extra.get("state"))
+ return _sentence_case(open_state) if open_state else None
+
+
+def _github_facts(extra: dict[str, Any]) -> list[str]:
+ state = _github_state(extra)
+ author = text_of(extra.get("author_login"))
+ raw_labels = extra.get("labels")
+ labels = [
+ text_of(label.get("name")) if isinstance(label, dict) else text_of(label)
+ for label in (raw_labels if isinstance(raw_labels, list) else [])
+ ]
+ return [fact for fact in (state, f"by {author}" if author else None, *labels) if fact is not None]
+
+
+def _ticket_facts(extra: dict[str, Any]) -> list[str]:
+ channel = text_of(extra.get("channel_source"))
+ priority = text_of(extra.get("priority"))
+ status = text_of(extra.get("status"))
+ return [
+ fact
+ for fact in (
+ _CHANNELS.get(channel, _sentence_case(channel)) if channel else None,
+ f"{_sentence_case(priority)} priority" if priority else None,
+ _sentence_case(status) if status else None,
+ )
+ if fact is not None
+ ]
+
+
+def _anomaly_facts(extra: dict[str, Any]) -> list[str]:
+ verdict = text_of(extra.get("verdict"))
+ return [_sentence_case(verdict)] if verdict else []
+
+
+def _finding_rest(signal: SignalInput) -> str:
+ lead = detail(signal).lead
+ lines = signal.content.split("\n")
+ for index, line in enumerate(lines):
+ found = detail(replace(signal, content=line))
+ if lead and found.lead == lead:
+ later = detail(replace(signal, content="\n".join(lines[index + 1 :])))
+ return " ".join(part for part in (found.rest, later.lead, later.rest) if part)
+ return ""
+
+
+def code_sibling_files(file: contracts.CodeFile, content: str) -> list[contracts.CodeFile]:
+ folder = file.path[: file.path.rfind("/") + 1]
+ own = file.path[len(folder) :]
+ names = [match.group(1) for match in _BARE_FILE_NAME.finditer(content) if match.group(1) != own]
+ unique = list(dict.fromkeys(names))[:_MAX_SIBLING_FILES]
+ return [contracts.CodeFile(repo=file.repo, path=f"{folder}{name}") for name in unique]
+
+
+def _scout_preview(signal: SignalInput, preview: contracts.SignalPreview) -> contracts.SignalPreview:
+ file = code_file(signal)
+ if file:
+ return replace(
+ preview,
+ hint="Show the code",
+ code=[file, *code_sibling_files(file, signal.content)],
+ facts=[fact for fact in preview.facts if fact != file.path.split("/")[-1]],
+ link=contracts.PageLink(url=github_file_url(file), text="Open on GitHub"),
+ )
+ thread = slack_thread(signal)
+ if thread:
+ return replace(
+ preview, hint="Show what the thread says", link=contracts.PageLink(url=thread, text="Open in Slack")
+ )
+ return preview
+
+
+def _stack_trace_preview(signal: SignalInput, preview: contracts.SignalPreview) -> contracts.SignalPreview | None:
+ block = exception_chain(signal.content)
+ return replace(preview, hint="Show the stack trace", block=block, text="") if block else None
+
+
+def _query_preview(signal: SignalInput, preview: contracts.SignalPreview) -> contracts.SignalPreview | None:
+ query = _pganalyze_query(signal)
+ if not query:
+ return None
+ return replace(preview, hint="Show the query", block=[contracts.PreviewLine(text=query, quiet=False)])
+
+
+def _description_preview(signal: SignalInput, preview: contracts.SignalPreview) -> contracts.SignalPreview | None:
+ body = body_paragraph(signal.content)
+ if not body:
+ return None
+ return replace(
+ preview,
+ hint="Show the description",
+ text=concise_text(_readable(signal, body), _PREVIEW_CHARS),
+ facts=[*preview.facts, *_github_facts(signal.extra)],
+ link_label="Open on GitHub",
+ )
+
+
+def _ticket_preview(signal: SignalInput, preview: contracts.SignalPreview) -> contracts.SignalPreview | None:
+ body = body_paragraph(signal.content, "Issue", has_title=not _CONVERSATION_MESSAGE.match(signal.content.strip()))
+ if not body:
+ return None
+ return replace(
+ preview,
+ hint="Show the ticket",
+ text=concise_text(_readable(signal, body), _PREVIEW_CHARS),
+ facts=[*preview.facts, *_ticket_facts(signal.extra)],
+ )
+
+
+def _finding_preview(signal: SignalInput, preview: contracts.SignalPreview) -> contracts.SignalPreview | None:
+ rest = _finding_rest(signal)
+ if not rest:
+ return None
+ return replace(
+ preview,
+ hint="Show the finding",
+ text=concise_text(rest, _PREVIEW_CHARS),
+ facts=[*preview.facts, *_anomaly_facts(signal.extra)],
+ )
+
+
+_SOURCE_PREVIEWS: dict[str, SourcePreview] = {
+ "signals_scout": _scout_preview,
+ "error_tracking": _stack_trace_preview,
+ "pganalyze": _query_preview,
+ "github": _description_preview,
+ "conversations": _ticket_preview,
+ "zendesk": _ticket_preview,
+ "analytics": _finding_preview,
+}
+
+
+def plays_recording(signal: SignalInput) -> bool:
+ return signal.source_product in RECORDING_SOURCES and text_of(signal.extra.get("session_id")) is not None
+
+
+def preview(signal: SignalInput) -> contracts.SignalPreview | None:
+ if plays_recording(signal):
+ return None
+ found = detail(signal)
+ base = contracts.SignalPreview(
+ hint="Read in full", code=[], block=[], text=found.rest, facts=found.facts, link=None, link_label=None
+ )
+ source_preview = _SOURCE_PREVIEWS.get(signal.source_product)
+ return source_preview(signal, base) if source_preview else base
diff --git a/products/today/backend/logic/signal_text.py b/products/today/backend/logic/signal_text.py
new file mode 100644
index 000000000000..7c5647ba40bb
--- /dev/null
+++ b/products/today/backend/logic/signal_text.py
@@ -0,0 +1,191 @@
+import re
+from urllib.parse import urlsplit
+
+from posthog.dataclasses import frozen
+
+from products.signals.backend.facade import api as signals
+
+from ..facade import contracts
+from ..facade.enums import CitedSource
+from .prose import first_sentence, plain_line, readable_excerpt, split_prose, without_code_blocks
+
+_BOILERPLATE_LINES = [
+ re.compile(pattern, re.IGNORECASE)
+ for pattern in (
+ r"^new error tracking issue created\b",
+ r"^this error tracking issue is experiencing a spike\b",
+ r"^\(baseline:",
+ r"^-{3,}$",
+ r"^(exception|uuid|commit sha|feature|type|value|filename):",
+ r"^anomaly investigation for alert\b",
+ r"^verdict changed from\b",
+ r"^insight:",
+ r"^\[(info|warning|critical)\]",
+ )
+]
+_REPO_FILE_ID = re.compile(r"^([\w.-]+/[\w.-]+):([^\s:]+)$", re.ASCII)
+_SLACK_LINK = re.compile(r"https?://[\w.-]*slack\.com/\S+", re.IGNORECASE | re.ASCII)
+_URL = re.compile(r"https?://\S+")
+_QUOTE_MARK = re.compile(r"“|”|(?<=\s)[\"']|^[\"']|[\"'](?=[\s.,;:!?]|\Z)")
+_TRAILING_PUNCTUATION = re.compile(r"[\s,;:–—-]+\Z")
+_PULL = re.compile(r"pull", re.IGNORECASE)
+_DANGLING_WORDS = frozenset(
+ "a an the and or but so with to of in on for by at from as into via than that which who".split()
+)
+_HEADLINE_CHARS = 155
+_MIN_CLAUSE_CHARS = 120
+_LINK_POINTER_WORDS = 6
+_DETAIL_ENDS = (".", "!", "?", ":", ")")
+_SCOUT = "signals_scout"
+TICKET_SOURCES = frozenset({"conversations", "zendesk"})
+RECORDING_SOURCES = frozenset({"replay_vision", "session_replay"})
+_SLACK_HOST = "slack.com"
+
+SignalInput = signals.ReportSignal
+
+
+@frozen
+class SignalDetail:
+ lead: str
+ rest: str
+ facts: list[str]
+
+
+def text_of(value: object) -> str | None:
+ return value.strip() if isinstance(value, str) and value.strip() else None
+
+
+def js_number(value: object) -> str | None:
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ return str(int(value)) if float(value).is_integer() else str(value)
+
+
+def _unclosed_quote_start(text: str) -> int:
+ opened = -1
+ for match in _QUOTE_MARK.finditer(text):
+ index = match.start()
+ mark = match.group(0)
+ opening = mark == "“" or (mark != "”" and (index == 0 or text[index - 1].isspace()))
+ opened = index if opening else -1
+ return opened
+
+
+def _without_dangling_words(text: str) -> str:
+ words = text.split(" ")
+ while len(words) > 1 and words[-1].lower() in _DANGLING_WORDS:
+ words.pop()
+ return " ".join(words)
+
+
+def _fit_headline(text: str) -> str:
+ if len(text) <= _HEADLINE_CHARS:
+ return text
+ window = text[:_HEADLINE_CHARS]
+ clause = max(window.rfind(", "), window.rfind("; "))
+ word_end = clause if clause >= _MIN_CLAUSE_CHARS else window.rfind(" ")
+ cut = text[: word_end if word_end > 0 else _HEADLINE_CHARS]
+ quote_start = _unclosed_quote_start(cut)
+ body = cut[:quote_start] if quote_start > _MIN_CLAUSE_CHARS / 2 else cut
+ trimmed = _TRAILING_PUNCTUATION.sub("", _without_dangling_words(_TRAILING_PUNCTUATION.sub("", body)))
+ return f"{trimmed}…"
+
+
+def _is_boilerplate(line: str) -> bool:
+ return any(pattern.search(line) for pattern in _BOILERPLATE_LINES)
+
+
+def headline(signal: SignalInput) -> str:
+ for raw in without_code_blocks(signal.content).split("\n"):
+ line = plain_line(raw)
+ if line and not _is_boilerplate(line):
+ return _fit_headline(readable_excerpt(first_sentence(line)))
+ return _fit_headline(readable_excerpt(plain_line(signal.content))) or "Signal"
+
+
+def _without_link_pointers(line: str) -> str:
+ def keeps(sentence: str) -> bool:
+ rest = _URL.sub("", sentence).strip()
+ return rest == sentence.strip() or len(rest.split()) > _LINK_POINTER_WORDS
+
+ return " ".join(sentence for sentence in split_prose(line) if keeps(sentence))
+
+
+def is_pull_request(signal: SignalInput) -> bool:
+ pull_request = signal.extra.get("pull_request")
+ pull_request_object = "pull_request" in signal.extra and (
+ pull_request is None or isinstance(pull_request, dict | list)
+ )
+ return bool(_PULL.search(signal.source_type)) or pull_request_object or "merged_at" in signal.extra
+
+
+def code_file(signal: SignalInput) -> contracts.CodeFile | None:
+ match = _REPO_FILE_ID.match(signal.source_id) if signal.source_product == _SCOUT else None
+ return contracts.CodeFile(repo=match.group(1), path=match.group(2)) if match else None
+
+
+def github_file_url(file: contracts.CodeFile) -> str:
+ return f"https://github.com/{file.repo}/blob/HEAD/{file.path}"
+
+
+def _is_slack_host(url: str) -> bool:
+ host = urlsplit(url).hostname or ""
+ return host == _SLACK_HOST or host.endswith(f".{_SLACK_HOST}")
+
+
+def slack_thread(signal: SignalInput) -> str | None:
+ match = _SLACK_LINK.search(signal.content) if signal.source_product == _SCOUT else None
+ url = safe_http_url(match.group(0).rstrip(").,")) if match else None
+ return url if url and _is_slack_host(url) else None
+
+
+def safe_http_url(url: str) -> str | None:
+ try:
+ parts = urlsplit(url)
+ except ValueError:
+ return None
+ return url if parts.scheme in ("http", "https") and parts.netloc else None
+
+
+def cited_source(signal: SignalInput) -> CitedSource | None:
+ if code_file(signal):
+ return CitedSource.CODE
+ return CitedSource.SLACK if slack_thread(signal) else None
+
+
+def _meta_parts(signal: SignalInput) -> list[str]:
+ if signal.source_product == "github":
+ number = js_number(signal.extra.get("number"))
+ kind = "Pull request" if is_pull_request(signal) else "Issue"
+ return [f"{kind} #{number}"] if number else []
+ if signal.source_product in TICKET_SOURCES:
+ ticket = js_number(signal.extra.get("ticket_number"))
+ return [f"Ticket #{ticket}"] if ticket else []
+ if signal.source_product == _SCOUT:
+ file = code_file(signal)
+ return [file.path.split("/")[-1]] if file else []
+ return []
+
+
+def meta(signal: SignalInput) -> str:
+ return " · ".join(_meta_parts(signal))
+
+
+def _pganalyze_facts(signal: SignalInput) -> list[str]:
+ if signal.source_product != "pganalyze":
+ return []
+ severity = text_of(signal.extra.get("severity"))
+ server = text_of(signal.extra.get("server_name"))
+ return [fact for fact in (server, f"{severity} severity" if severity else None) if fact]
+
+
+def detail(signal: SignalInput) -> SignalDetail:
+ lines = [plain_line(_without_link_pointers(line)) for line in without_code_blocks(signal.content).split("\n")]
+ kept = [line for line in lines if line and not _is_boilerplate(line)]
+ text = " ".join(line if line.endswith(_DETAIL_ENDS) else f"{line}." for line in kept)
+ lead = first_sentence(text)
+ return SignalDetail(
+ lead=readable_excerpt(lead or plain_line(signal.content)),
+ rest=readable_excerpt(text[len(lead) :].strip()),
+ facts=[*_pganalyze_facts(signal), *_meta_parts(signal)],
+ )
diff --git a/products/today/backend/presentation/serializers.py b/products/today/backend/presentation/serializers.py
index db6650124bfc..6709828aeaee 100644
--- a/products/today/backend/presentation/serializers.py
+++ b/products/today/backend/presentation/serializers.py
@@ -15,7 +15,18 @@ from ..facade.contracts import (
Candidate,
CandidateFact,
CandidateList,
+ CodeFile,
+ ImpactNumber,
+ ImpactWorking,
+ PageLink,
+ PreviewLine,
+ PullRequestLink,
+ RecordingTarget,
+ ReportPage,
+ SignalPreview,
+ SignalView,
)
+from ..facade.enums import CitedSource, ImpactNumberKey
class TodayQuerySerializer(serializers.Serializer):
@@ -176,3 +187,145 @@ class CandidateListSerializer(DataclassSerializer):
class Meta:
dataclass = CandidateList
+
+
+class PullRequestLinkSerializer(DataclassSerializer):
+ url = serializers.CharField(help_text="The pull request on GitHub.")
+ number = serializers.IntegerField(help_text="The pull request number.")
+
+ class Meta:
+ dataclass = PullRequestLink
+
+
+class CodeFileSerializer(DataclassSerializer):
+ repo = serializers.CharField(help_text="The repository as owner/name.")
+ path = serializers.CharField(help_text="The file path in the repository.")
+
+ class Meta:
+ dataclass = CodeFile
+
+
+class PreviewLineSerializer(DataclassSerializer):
+ text = serializers.CharField(help_text="One line of the preview block.")
+ quiet = serializers.BooleanField(help_text="Whether the line is secondary, such as a stack frame.")
+
+ class Meta:
+ dataclass = PreviewLine
+
+
+class PageLinkSerializer(DataclassSerializer):
+ url = serializers.CharField(help_text="Where the link goes, outside PostHog.")
+ text = serializers.CharField(help_text="The link text.")
+
+ class Meta:
+ dataclass = PageLink
+
+
+class SignalPreviewSerializer(DataclassSerializer):
+ hint = serializers.CharField(help_text="What expanding the signal shows, such as 'Show the stack trace'.")
+ code = CodeFileSerializer(many=True, help_text="Repository files to quote, the finding's own file first.")
+ block = PreviewLineSerializer(many=True, help_text="A preformatted block, such as a stack trace or a query.")
+ text = serializers.CharField(help_text="The finding's text beyond its first sentence.")
+ facts = serializers.ListField(child=serializers.CharField(), help_text="Short facts about the source.")
+ link = PageLinkSerializer(allow_null=True, help_text="A link that replaces the signal's own destination.")
+ link_label = serializers.CharField(
+ allow_null=True, help_text="A label that replaces the label of the signal's own destination."
+ )
+
+ class Meta:
+ dataclass = SignalPreview
+
+
+class RecordingTargetSerializer(DataclassSerializer):
+ session_id = serializers.CharField(help_text="The recording's session id.")
+ start_at = serializers.DateTimeField(
+ allow_null=True, help_text="Where the player starts, a few seconds before the finding."
+ )
+ offset = serializers.CharField(allow_null=True, help_text="The finding's time in the recording, as MM:SS.")
+ seek_seconds = serializers.IntegerField(
+ allow_null=True,
+ help_text="Where the player starts, in seconds from the recording start. Null without an offset.",
+ )
+
+ class Meta:
+ dataclass = RecordingTarget
+
+
+class SignalViewSerializer(DataclassSerializer):
+ signal_id = serializers.CharField(help_text="The signal's id.")
+ source_product = serializers.CharField(help_text="The product that emitted the signal.")
+ source_type = serializers.CharField(help_text="The kind of signal within its product.")
+ source_id = serializers.CharField(help_text="The id of the source object, such as an issue or a ticket.")
+ content = serializers.CharField(help_text="The signal's text as emitted.")
+ timestamp = serializers.DateTimeField(help_text="When the signal happened.")
+ extra = serializers.DictField(
+ child=serializers.JSONField(),
+ help_text="The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON.",
+ )
+ headline = serializers.CharField(help_text="The signal as one short line.")
+ lead = serializers.CharField(help_text="The signal's first sentence.")
+ meta = serializers.CharField(help_text="Identifiers such as a pull request or ticket number, joined by dots.")
+ cited = serializers.ChoiceField(
+ choices=CitedSource.choices, allow_null=True, help_text="What a scout finding cites: code or a Slack thread."
+ )
+ recording = RecordingTargetSerializer(allow_null=True, help_text="The recording the signal plays, if any.")
+ link = PageLinkSerializer(allow_null=True, help_text="Where a scout finding links outside PostHog, if anywhere.")
+ preview = SignalPreviewSerializer(allow_null=True, help_text="What expanding the signal shows, if anything.")
+
+ class Meta:
+ dataclass = SignalView
+
+
+class ImpactWorkingSerializer(DataclassSerializer):
+ expression = serializers.CharField(help_text="How the number is worked out, such as '120 ms × 30,000 calls'.")
+ result = serializers.CharField(help_text="What the working comes to, such as '1.00 hours a day'.")
+
+ class Meta:
+ dataclass = ImpactWorking
+
+
+class ImpactNumberSerializer(DataclassSerializer):
+ key = serializers.ChoiceField(
+ choices=ImpactNumberKey.choices,
+ help_text="Which number this is: distinct support tickets or database hours a day.",
+ )
+ value = serializers.CharField(help_text="The number as shown, such as '2' or '1 hour'.")
+ sentence = serializers.CharField(help_text="The sentence that follows the number.")
+ signal = SignalViewSerializer(allow_null=True, help_text="The signal the number comes from, if one does.")
+ values = serializers.ListField(
+ child=serializers.CharField(), help_text="The figures in the signal's headline to mark."
+ )
+ working = ImpactWorkingSerializer(allow_null=True, help_text="How the number is worked out, if it is.")
+
+ class Meta:
+ dataclass = ImpactNumber
+
+
+class ReportPageSerializer(DataclassSerializer):
+ lead = serializers.CharField(help_text="The summary's opening paragraph, as markdown.")
+ proposal = serializers.CharField(
+ help_text="The proposed fix cut to whole sentences, as markdown. Empty when the report proposes none."
+ )
+ impact_sentence = serializers.CharField(
+ help_text="The impact section cut to whole sentences, as markdown, when it states a measurement. Empty otherwise."
+ )
+ named_pull_request = PullRequestLinkSerializer(
+ allow_null=True,
+ help_text="The pull request the proposal names, or else the summary, when it names exactly one.",
+ )
+ solution_names_pull_request = serializers.BooleanField(help_text="Whether the proposal names any pull request.")
+ evidence = SignalViewSerializer(
+ many=True, help_text="The signals to show as evidence, at most 3, newest first, one per source first."
+ )
+ source_count = serializers.IntegerField(
+ help_text="How many distinct source objects the report's newest 100 signals come from. The impact numbers and last seen use the same signals."
+ )
+ impact_numbers = ImpactNumberSerializer(
+ many=True, help_text="Numbers the signals size the problem with, such as distinct support tickets."
+ )
+ last_seen = serializers.DateTimeField(
+ allow_null=True, help_text="When the newest session, ticket or alert behind the report happened."
+ )
+
+ class Meta:
+ dataclass = ReportPage
diff --git a/products/today/backend/presentation/views.py b/products/today/backend/presentation/views.py
index 16424fd28dde..2ed086784e84 100644
--- a/products/today/backend/presentation/views.py
+++ b/products/today/backend/presentation/views.py
@@ -5,18 +5,19 @@ from typing import cast
from drf_spectacular.utils import OpenApiResponse
from rest_framework import viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound
+from rest_framework.exceptions import NotFound, PermissionDenied
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models import User
+from posthog.utils import UUID_REGEX
from products.signals.backend.facade import api as signals
from ..facade import api
-from .serializers import BriefingSerializer, CandidateListSerializer, TodayQuerySerializer
+from .serializers import BriefingSerializer, CandidateListSerializer, ReportPageSerializer, TodayQuerySerializer
class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
@@ -31,6 +32,10 @@ class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
raise NotFound()
return user
+ def _check_report_access(self, user: User) -> None:
+ if not signals.may_read_reports(user=user, team=self.team):
+ raise PermissionDenied()
+
@validated_request(
query_serializer=TodayQuerySerializer,
responses={200: OpenApiResponse(response=BriefingSerializer)},
@@ -78,3 +83,24 @@ class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
team=self.team, user=user, timezone_name=request.validated_query_data.get("timezone")
)
return Response(CandidateListSerializer(candidates).data)
+
+ @validated_request(
+ responses={200: OpenApiResponse(response=ReportPageSerializer)},
+ summary="Get a report's page",
+ description="What the Today report page shows for a report: its lead, the proposal and the impact sentence cut to whole sentences, and the pull request it names. Sample report ids return the built-in sample reports. 404 when the report is missing or the person does not have the new navigation. 403 when the person may not read Inbox reports, and a scoped key needs task:read as well, because the page shows the report's signals.",
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path=rf"reports/(?P<report_id>{UUID_REGEX}|sample-[a-z]+)/page",
+ required_scopes=["today:read", "task:read"],
+ )
+ def report_page(self, request: Request, report_id: str, **kwargs) -> Response:
+ user = cast(User, request.user)
+ if not api.is_enabled_for(user, self.team):
+ raise NotFound()
+ self._check_report_access(user)
+ page = api.report_page(team=self.team, report_id=report_id)
+ if page is None:
+ raise NotFound()
+ return Response(ReportPageSerializer(page).data)
diff --git a/products/today/backend/tests/factories.py b/products/today/backend/tests/factories.py
new file mode 100644
index 000000000000..7b11e2142642
--- /dev/null
+++ b/products/today/backend/tests/factories.py
@@ -0,0 +1,42 @@
+from datetime import datetime
+from typing import Any
+
+from products.signals.backend.facade import api as signals
+from products.today.backend.logic.signal_text import SignalInput
+
+
+def signal(
+ *,
+ content: str = "",
+ source_product: str = "signals_scout",
+ source_type: str = "cross_source_issue",
+ source_id: str = "source-1",
+ signal_id: str = "signal-1",
+ timestamp: str = "2026-10-01T10:00:00+00:00",
+ extra: dict[str, Any] | None = None,
+) -> SignalInput:
+ return SignalInput(
+ signal_id=signal_id,
+ content=content,
+ source_product=source_product,
+ source_type=source_type,
+ source_id=source_id,
+ timestamp=datetime.fromisoformat(timestamp),
+ extra=extra or {},
+ )
+
+
+def page_source(
+ *,
+ summary: str = "",
+ solution: str | None = None,
+ impact: str | None = None,
+ action_prompts: list[str] | None = None,
+) -> signals.ReportPageSource:
+ return signals.ReportPageSource(
+ summary=summary,
+ sections=signals.ReportSections(lead="Lead.", impact=impact, solution=solution),
+ action_prompts=action_prompts or [],
+ repo_slug="example/web",
+ signals=[],
+ )
diff --git a/products/today/backend/tests/test_api.py b/products/today/backend/tests/test_api.py
index 90dcb806f399..6cec753f93a1 100644
--- a/products/today/backend/tests/test_api.py
+++ b/products/today/backend/tests/test_api.py
@@ -7,10 +7,19 @@ from unittest.mock import AsyncMock, MagicMock, patch
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
+from posthog.models import PersonalAPIKey, Team, User
+from posthog.models.personal_api_key import hash_key_value
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.signals.backend.models import SignalReport
from products.today.backend.facade.enums import BriefingStatus, BriefingTrigger
from products.today.backend.logic import briefings
from products.today.backend.models import DailyBriefing
from products.today.backend.tests.conftest import TodayTeamScopedTestMixin
+from products.today.backend.tests.factories import page_source
+
+REPORT_ID = "01a10212-6f09-0000-0ed6-46b2df6f81ca"
@patch("products.today.backend.logic.briefings.sync_connect")
@@ -148,3 +157,93 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert DailyBriefing.objects.for_team(self.team.id).filter(user_id=other.id).count() == 1
assert DailyBriefing.objects.for_team(self.team.id).count() == 2
+
+ @parameterized.expand(
+ [
+ ("a report", True, REPORT_ID, status.HTTP_200_OK, "Lead."),
+ ("flag off", False, REPORT_ID, status.HTTP_404_NOT_FOUND, None),
+ ("a sample report", True, "sample-pr", status.HTTP_200_OK, "Safari users can’t finish checkout"),
+ ("an unknown sample", True, "sample-nope", status.HTTP_404_NOT_FOUND, None),
+ ]
+ )
+ def test_report_page_answers_people_with_the_new_navigation(
+ self, _sync_connect: MagicMock, _name: str, flag: bool, report_id: str, expected: int, lead: str | None
+ ) -> None:
+ with (
+ self._flag(flag),
+ patch("products.today.backend.logic.report_page.signals.report_page_source", return_value=page_source()),
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/today/reports/{report_id}/page/")
+
+ assert response.status_code == expected
+ if lead is not None:
+ assert response.json()["lead"].startswith(lead)
+
+ @parameterized.expand(
+ [
+ ("today only", ["today:read"], status.HTTP_403_FORBIDDEN),
+ ("today and signals", ["today:read", "task:read"], status.HTTP_200_OK),
+ ]
+ )
+ def test_a_scoped_key_reads_the_report_page_only_with_the_signals_scope(
+ self, _sync_connect: MagicMock, _name: str, scopes: list[str], expected: int
+ ) -> None:
+ raw_key = "today_report_page_key"
+ PersonalAPIKey.objects.create(
+ user=self.user, label="Today", secure_value=hash_key_value(raw_key), scopes=scopes
+ )
+ self.client.logout()
+ with (
+ self._flag(True),
+ patch("products.today.backend.logic.report_page.signals.report_page_source", return_value=page_source()),
+ ):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/page/", HTTP_AUTHORIZATION=f"Bearer {raw_key}"
+ )
+
+ assert response.status_code == expected
+
+ @parameterized.expand(
+ [
+ ("can read inbox reports", None, status.HTTP_200_OK),
+ ("may not read inbox reports", "none", status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_a_member_reads_the_report_page_only_with_access_to_inbox_reports(
+ self, _sync_connect: MagicMock, _name: str, task_access: str | None, expected: int
+ ) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ if task_access is not None:
+ AccessControl.objects.create(team=self.team, resource="task", resource_id=None, access_level=task_access)
+ self.client.force_login(User.objects.create_and_join(self.organization, "[email protected]", "testtest"))
+ with (
+ self._flag(True),
+ patch("products.today.backend.logic.report_page.signals.report_page_source", return_value=page_source()),
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/page/")
+
+ assert response.status_code == expected
+
+ @parameterized.expand([("a deleted report", True, False), ("another team's report", False, True)])
+ def test_report_page_answers_404_for(
+ self, _sync_connect: MagicMock, _name: str, deleted: bool, other: bool
+ ) -> None:
+ team = Team.objects.create(organization=self.organization) if other else self.team
+ report = SignalReport.objects.create(
+ team=team,
+ title="Checkout fails",
+ summary="Checkout fails for some shoppers.",
+ status=SignalReport.Status.DELETED if deleted else SignalReport.Status.READY,
+ signal_count=1,
+ total_weight=1.0,
+ )
+ with (
+ self._flag(True),
+ patch("products.signals.backend.report_page_source.fetch_signals_for_report_sync", return_value=[]),
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/today/reports/{report.id}/page/")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
diff --git a/products/today/backend/tests/test_impact.py b/products/today/backend/tests/test_impact.py
new file mode 100644
index 000000000000..8b681f7f0154
--- /dev/null
+++ b/products/today/backend/tests/test_impact.py
@@ -0,0 +1,86 @@
+from datetime import datetime
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.today.backend.logic.impact import impact_numbers, last_occurrence
+from products.today.backend.logic.signal_text import SignalInput
+from products.today.backend.tests.factories import signal
+
+
+def ticket(number: int, timestamp: str, product: str = "conversations") -> SignalInput:
+ return signal(
+ source_product=product,
+ source_type="ticket",
+ source_id=f"ticket-{number}",
+ timestamp=timestamp,
+ extra={"ticket_number": number},
+ )
+
+
+def slow_query(content: str) -> SignalInput:
+ return signal(source_product="pganalyze", source_type="issue", content=content)
+
+
+class TestImpact(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "counts distinct support tickets over the days they span",
+ [ticket(1042, "2026-09-20T09:00:00+00:00"), ticket(1043, "2026-09-25T15:00:00+00:00")],
+ [("2", "support tickets over 6 days.")],
+ ),
+ (
+ "counts tickets from any support tool, and the same number in two tools twice",
+ [ticket(1042, "2026-09-20T09:00:00+00:00", "freshdesk"), ticket(1042, "2026-09-21T09:00:00+00:00")],
+ [("2", "support tickets over 2 days.")],
+ ),
+ (
+ "shows nothing for one ticket, however many signals cite it",
+ [ticket(1042, "2026-09-20T09:00:00+00:00"), ticket(1042, "2026-09-25T15:00:00+00:00")],
+ [],
+ ),
+ (
+ "works out the database time a slow query costs each day",
+ [slow_query("[info] orders-db — #42\nQuery #42 takes 120 ms on average (30,000 calls in last 24h)")],
+ [("1 hour", "database time a day, worked out from the query’s pganalyze stats.")],
+ ),
+ (
+ "rounds a fraction of an hour up at the half",
+ [slow_query("Query #7 takes 2.25 ms on average (4,000,000 calls in last 24h)")],
+ [("2.5 hours", "database time a day, worked out from the query’s pganalyze stats.")],
+ ),
+ ]
+ )
+ def test_sizes_impact(self, _name: str, signals: list[SignalInput], expected: list[tuple[str, str]]) -> None:
+ assert [(number.value, number.sentence) for number in impact_numbers(signals)] == expected
+
+ @parameterized.expand(
+ [
+ (
+ "the newest session, ticket or alert, not a later finding",
+ [
+ signal(
+ source_product="replay_vision",
+ timestamp="2026-09-20T10:00:00+00:00",
+ extra={"session_id": "s1"},
+ ),
+ ticket(1042, "2026-09-25T08:00:00+00:00"),
+ signal(timestamp="2026-09-30T10:00:00+00:00"),
+ ],
+ "2026-09-25T08:00:00+00:00",
+ ),
+ (
+ "a later signal about the same session",
+ [
+ signal(source_product="replay_vision", timestamp=at, extra={"session_id": "s1"})
+ for at in ("2026-09-20T10:00:00+00:00", "2026-09-27T10:00:00+00:00")
+ ],
+ "2026-09-27T10:00:00+00:00",
+ ),
+ ("nothing when no signal is an occurrence", [signal()], None),
+ ]
+ )
+ def test_dates_the_last_occurrence_as(self, _name: str, signals: list[SignalInput], expected: str | None) -> None:
+ assert last_occurrence(signals) == (datetime.fromisoformat(expected) if expected else None)
diff --git a/products/today/backend/tests/test_report_page.py b/products/today/backend/tests/test_report_page.py
new file mode 100644
index 000000000000..70a120ef7a68
--- /dev/null
+++ b/products/today/backend/tests/test_report_page.py
@@ -0,0 +1,126 @@
+from dataclasses import replace
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.signals.backend.facade import api as signals
+from products.today.backend.logic.prose import concise_text
+from products.today.backend.logic.report_page import report_page
+from products.today.backend.tests.factories import page_source
+
+SOLUTION_PR = "Reuse draft https://github.com/example/web/pull/9."
+
+
+class TestReportPage(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "keeps a title with its name",
+ "Ask Dr. Smith to review this change. Then ship it.",
+ 40,
+ "Ask Dr. Smith to review this change.",
+ ),
+ (
+ "stops before the limit",
+ "First sentence is short. Second sentence is also short. Third one.",
+ 50,
+ "First sentence is short.",
+ ),
+ (
+ "keeps one long sentence",
+ "One long sentence that runs past the limit on its own.",
+ 10,
+ "One long sentence that runs past the limit on its own.",
+ ),
+ (
+ "reads list items as sentences",
+ "- Reproduce the bug\n- Trace the state",
+ 60,
+ "Reproduce the bug. Trace the state.",
+ ),
+ (
+ "counts a link by the text it shows",
+ "Merged in [#12](https://github.com/example/web/pull/12). Land [#13](https://github.com/example/web/pull/13) next.",
+ 40,
+ "Merged in [#12](https://github.com/example/web/pull/12). Land [#13](https://github.com/example/web/pull/13) next.",
+ ),
+ (
+ "closes a bold span it cuts",
+ "**The fix is safe. It ships today.** Then measure.",
+ 20,
+ "**The fix is safe.**",
+ ),
+ (
+ "ends a sentence inside bold",
+ "That covers the ask. **One message is still open.** Then add a deletion type for events.",
+ 60,
+ "That covers the ask. **One message is still open.**",
+ ),
+ (
+ "keeps a period inside code",
+ 'Match quotes with `(?:[^"\\\\]|\\\\.)*`. Then ship it.',
+ 40,
+ 'Match quotes with `(?:[^"\\\\]|\\\\.)*`.',
+ ),
+ ]
+ )
+ def test_keeps_text_concise(self, _name: str, markdown: str, max_chars: int, expected: str) -> None:
+ assert concise_text(markdown, max_chars) == expected
+
+ @parameterized.expand(
+ [
+ ("one pull request", "Open PR https://github.com/example/web/pull/7 covers it.", None, 7),
+ (
+ "several pull requests",
+ "Merged in https://github.com/example/web/pull/7, review https://github.com/example/web/pull/8.",
+ None,
+ None,
+ ),
+ (
+ "several pull requests, one named by the solution",
+ "Merged in https://github.com/example/web/pull/7. Reuse https://github.com/example/web/pull/9.",
+ SOLUTION_PR,
+ 9,
+ ),
+ ("a bare reference in the repository", "PR #5 already fixes this.", None, 5),
+ (
+ "a link and a different bare reference",
+ "Merged in https://github.com/example/web/pull/7, and PR #8 follows.",
+ None,
+ None,
+ ),
+ ]
+ )
+ def test_names_the_pull_request(self, _name: str, summary: str, solution: str | None, expected: int | None) -> None:
+ pull_request = report_page(page_source(summary=summary, solution=solution)).named_pull_request
+ assert (pull_request.number if pull_request else None) == expected
+
+ @parameterized.expand(
+ [
+ ("a solution", page_source(solution="Keep the token.", action_prompts=["Fix it"]), "Keep the token."),
+ ("the first prompt when work can start", page_source(action_prompts=["Fix it", "Test it"]), "Fix it."),
+ ("nothing without a solution or a prompt", page_source(), ""),
+ ]
+ )
+ def test_proposes(self, _name: str, source: signals.ReportPageSource, expected: str) -> None:
+ assert report_page(source).proposal == expected
+
+ @parameterized.expand(
+ [
+ ("a measurement", "212 shoppers could not pay.", "212 shoppers could not pay."),
+ ("no number", "Shoppers could not pay.", ""),
+ ("only digits in code", "`checkout/address_v2.ts` drops it.", ""),
+ (
+ "a measurement beside a code path",
+ "`checkout/address.ts` fails for 12 users.",
+ "`checkout/address.ts` fails for 12 users.",
+ ),
+ ]
+ )
+ def test_keeps_only_a_measured_impact(self, _name: str, impact: str, expected: str) -> None:
+ assert report_page(page_source(impact=impact)).impact_sentence == expected
+
+ def test_sees_a_bare_reference_without_a_repository(self) -> None:
+ page = report_page(replace(page_source(solution="PR #5 already fixes this."), repo_slug=None))
+ assert (page.named_pull_request, page.solution_names_pull_request) == (None, True)
diff --git a/products/today/backend/tests/test_signal_views.py b/products/today/backend/tests/test_signal_views.py
new file mode 100644
index 000000000000..272ff315effa
--- /dev/null
+++ b/products/today/backend/tests/test_signal_views.py
@@ -0,0 +1,319 @@
+from datetime import datetime
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.today.backend.facade import contracts
+from products.today.backend.logic.evidence import distinct_evidence_count, pick_evidence, signal_view
+from products.today.backend.logic.signal_previews import body_paragraph, exception_chain, preview
+from products.today.backend.logic.signal_text import SignalInput, detail, headline, meta
+from products.today.backend.tests.factories import signal
+
+SLACK_THREAD = "https://example.slack.com/archives/C1/p2"
+ISSUE_URL = "https://github.com/example/web/issues/7"
+
+
+class TestSignalViews(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "an error tracking issue",
+ "New error tracking issue created - this particular exception was observed for the first time:\nValueError: `coupon_code`\n\n```\nstack\n```",
+ "ValueError: coupon_code",
+ ),
+ (
+ "a support ticket",
+ "C: Two weekly invoices show a blank total for annual plans\\. They bill in euros.",
+ "Two weekly invoices show a blank total for annual plans.",
+ ),
+ (
+ "long scout prose",
+ "The invoice export leaves out the tax column for archived plans. A nightly sync adds it back later.",
+ "The invoice export leaves out the tax column for archived plans.",
+ ),
+ (
+ "a github issue cited with a bare link",
+ "GitHub issue #4521 (https://github.com/example/shop/issues/4521) reports that `Card was declined. Use another.` shows for `card_error`. It has no PR.",
+ "GitHub issue #4521 reports that “Card was declined. Use another.” shows for card_error.",
+ ),
+ (
+ "a long sentence, cut at its last clause",
+ "Pressing Apply on the shipping rules settings screen does not keep the new rates, which means every edit to the rates is dropped and the merchant has to write to the help desk about it before the next billing run.",
+ "Pressing Apply on the shipping rules settings screen does not keep the new rates, which means every edit to the rates is dropped and the merchant has…",
+ ),
+ (
+ "a long sentence, never cut inside a quotation",
+ "In the #shop-support thread about failed payments, one merchant reported that checkouts on the mobile app fail about a third of the time with “Gateway did not answer in time” errors.",
+ "In the #shop-support thread about failed payments, one merchant reported that checkouts on the mobile app fail about a third of the time…",
+ ),
+ (
+ "a pganalyze issue",
+ "[info] orders-db — #42\nQuery #42 takes 95 ms on average (12345 calls in last 24h)",
+ "Query #42 takes 95 ms on average (12,345 calls in last 24h)",
+ ),
+ (
+ "an alert investigation",
+ "Anomaly investigation for alert 'Orders dropped' on Orders (verdict: true positive).\nInsight: AB12 / id 1.\nPaid orders fell to 12 in the 09:00 hour on 2026-08-03. The detector fired before.",
+ "Paid orders fell to 12 in the 09:00 hour on 3 Aug.",
+ ),
+ (
+ "a day its month does not have, left as written",
+ "Paid orders fell on 2026-02-30 and stayed low.",
+ "Paid orders fell on 2026-02-30 and stayed low.",
+ ),
+ (
+ "a date in year zero, left as written",
+ "Paid orders fell on 0000-01-01 and stayed low.",
+ "Paid orders fell on 0000-01-01 and stayed low.",
+ ),
+ (
+ "a scout finding that ends in a thread link",
+ f"A reviewer said the banner is too loud. Slack reply: {SLACK_THREAD}",
+ "A reviewer said the banner is too loud.",
+ ),
+ ]
+ )
+ def test_writes_a_headline(self, _name: str, content: str, expected: str) -> None:
+ assert headline(signal(content=content)) == expected
+
+ @parameterized.expand(
+ [
+ ("a support ticket", signal(source_product="conversations", extra={"ticket_number": 1042}), "Ticket #1042"),
+ (
+ "a github issue",
+ signal(source_product="github", source_type="issue", extra={"number": 7, "state": "open"}),
+ "Issue #7",
+ ),
+ ("a scout finding on a file", signal(source_id="example/web:src/checkout/Address.tsx"), "Address.tsx"),
+ ("a recording", signal(source_product="replay_vision", extra={"scanner_name": "Checkout friction"}), ""),
+ ]
+ )
+ def test_names_only_the_identifier(self, _name: str, item: SignalInput, expected: str) -> None:
+ assert meta(item) == expected
+
+ @parameterized.expand(
+ [
+ (
+ "a pganalyze issue, without its header line",
+ signal(
+ source_product="pganalyze",
+ source_type="issue",
+ content="[info] orders-db — #42\nQuery #42 takes 95 ms on average (12345 calls in last 24h)",
+ extra={"server_name": "orders-db", "severity": "info"},
+ ),
+ ("Query #42 takes 95 ms on average (12,345 calls in last 24h)", "", ["orders-db", "info severity"]),
+ ),
+ (
+ "a scout finding that cites a Slack thread, without the sentence that only points at it",
+ signal(
+ content=f"The August 12 #shop-support discussion counted 2,316 merchants using saved carts over 30 days. Most were on the annual plan. The thread is available at {SLACK_THREAD}."
+ ),
+ (
+ "The August 12 #shop-support discussion counted 2,316 merchants using saved carts over 30 days.",
+ "Most were on the annual plan.",
+ [],
+ ),
+ ),
+ ]
+ )
+ def test_opens_a_signal(self, _name: str, item: SignalInput, expected: tuple[str, str, list[str]]) -> None:
+ found = detail(item)
+ assert (found.lead, found.rest, found.facts) == expected
+
+ def test_reads_a_stack_trace_as_a_chain_of_causes_at_the_teams_own_frames(self) -> None:
+ content = "\n".join(
+ [
+ "New error tracking issue created - this particular exception was observed for the first time:",
+ "JobError: the job failed with UploadError",
+ "",
+ "```",
+ "JobError: the job failed with UploadError",
+ "run in posthog/jobs/runner.py line 40",
+ "start_upload in products/files/backend/upload.py line 12",
+ "UploadError: Failed to upload",
+ "put in products/files/backend/storage.py line 88",
+ "send in boto3/client.py line 300",
+ "```",
+ ]
+ )
+ assert exception_chain(content) == [
+ contracts.PreviewLine(text=" upload.py:12 start_upload", quiet=True),
+ contracts.PreviewLine(text="Caused by UploadError: Failed to upload", quiet=False),
+ contracts.PreviewLine(text=" storage.py:88 put", quiet=True),
+ ]
+
+ @parameterized.expand(
+ [
+ (
+ "the paragraph under a title line",
+ "Title line\nFirst paragraph.\n\nPart of #12.",
+ None,
+ "First paragraph.",
+ ),
+ (
+ "the labelled section",
+ "Title\n\n**Product area:** Billing\n\n**Issue:** The invoice is blank.\n\n**Resolution:** Fixed.",
+ "Issue",
+ "The invoice is blank.",
+ ),
+ ("nothing for a title alone", "Title only", None, None),
+ ]
+ )
+ def test_finds_the_body(self, _name: str, content: str, label: str | None, expected: str | None) -> None:
+ assert body_paragraph(content, label) == expected
+
+ def test_shows_the_files_a_finding_names_in_its_own_folder(self) -> None:
+ item = signal(
+ source_id="example/shop:src/cards/Cards.tsx",
+ content="`Cards.tsx` maps cards, and `cardsLogic.ts` caps them at `CARDS_MAX`.",
+ )
+ found = preview(item)
+ assert found is not None
+ assert [file.path for file in found.code] == ["src/cards/Cards.tsx", "src/cards/cardsLogic.ts"]
+
+ @parameterized.expand(
+ [
+ (
+ "nothing for a recording, which plays at once",
+ signal(source_product="replay_vision", content="A button does nothing.", extra={"session_id": "s1"}),
+ None,
+ ),
+ (
+ "the query behind a pganalyze issue",
+ signal(
+ source_product="pganalyze",
+ content="Query #1 takes 95 ms on average",
+ extra={"references": [{"kind": "Query", "queryText": "SELECT ... FROM orders"}]},
+ ),
+ ("Show the query", "", [contracts.PreviewLine(text="SELECT ... FROM orders", quiet=False)], None),
+ ),
+ (
+ "the description of a GitHub issue",
+ signal(
+ source_product="github",
+ source_type="issue",
+ content="Checkout drops the coupon\nThe cart forgets the coupon code after a refresh.\n\nPart of #12.",
+ extra={"html_url": "https://github.com/example/shop/issues/7", "number": 7, "state": "open"},
+ ),
+ ("Show the description", "The cart forgets the coupon code after a refresh.", [], "Open on GitHub"),
+ ),
+ (
+ "the first message of a conversation without a subject",
+ signal(
+ source_product="conversations",
+ source_type="ticket",
+ content="C: The invoice total is blank.\nT: We are looking into it.",
+ ),
+ ("Show the ticket", "The invoice total is blank. T: We are looking into it.", [], None),
+ ),
+ (
+ "the lines after an alert finding",
+ signal(
+ source_product="analytics",
+ source_type="anomaly_investigation",
+ content="Paid orders fell to 12 in the 09:00 hour.\nWhat the metric measures: paid orders per hour.",
+ ),
+ ("Show the finding", "What the metric measures: paid orders per hour.", [], None),
+ ),
+ (
+ "the thread a Slack finding cites",
+ signal(content=f"A teammate said the banner is too loud. {SLACK_THREAD}"),
+ ("Show what the thread says", "", [], None),
+ ),
+ ]
+ )
+ def test_previews(
+ self,
+ _name: str,
+ item: SignalInput,
+ expected: tuple[str, str, list[contracts.PreviewLine], str | None] | None,
+ ) -> None:
+ found = preview(item)
+ assert ((found.hint, found.text, found.block, found.link_label) if found else None) == expected
+
+ @parameterized.expand(
+ [
+ (
+ "replay vision seconds",
+ {"session_id": "s1", "start_time": 108, "recording_start_time": "2026-10-02T12:15:23+00:00"},
+ ("2026-10-02T12:17:06+00:00", "01:48", 103),
+ ),
+ (
+ "session replay offset text",
+ {"session_id": "s1", "start_time": "02:05", "session_start_time": "2026-10-02T12:00:00+00:00"},
+ ("2026-10-02T12:02:00+00:00", "02:05", 120),
+ ),
+ ("a recording without a start time", {"session_id": "s1", "start_time": 108}, (None, "01:48", 103)),
+ ]
+ )
+ def test_opens_a_recording_just_before_the_finding(
+ self, _name: str, extra: dict[str, Any], expected: tuple[str | None, str, int]
+ ) -> None:
+ recording = signal_view(signal(source_product="replay_vision", extra=extra)).recording
+ start_at, offset, seek_seconds = expected
+ assert recording == contracts.RecordingTarget(
+ session_id="s1",
+ start_at=datetime.fromisoformat(start_at) if start_at else None,
+ offset=offset,
+ seek_seconds=seek_seconds,
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "a thread",
+ f"A teammate reported it. Slack thread: {SLACK_THREAD}",
+ contracts.PageLink(url=SLACK_THREAD, text="Open thread"),
+ ),
+ ("only prose", "A long finding without any link." * 10, None),
+ ("a host that only ends in slack.com", "Slack thread: https://evilslack.com/archives/C1/p2", None),
+ ]
+ )
+ def test_links_a_scout_finding_with(self, _name: str, content: str, expected: contracts.PageLink | None) -> None:
+ assert signal_view(signal(content=content)).link == expected
+
+ @parameterized.expand(
+ [
+ ("an issue", "issue", {}, contracts.PageLink(url=ISSUE_URL, text="Open issue")),
+ (
+ "a pull request",
+ "pull_request",
+ {"merged_at": None},
+ contracts.PageLink(url=ISSUE_URL, text="Open pull request"),
+ ),
+ ("nothing for a link that is not http", "issue", {"html_url": "javascript:alert(1)"}, None),
+ ("nothing for a link that does not parse", "issue", {"html_url": "https://[::1"}, None),
+ ]
+ )
+ def test_links_a_github_signal_to(
+ self, _name: str, source_type: str, extra: dict[str, Any], expected: contracts.PageLink | None
+ ) -> None:
+ item = signal(source_product="github", source_type=source_type, extra={"html_url": ISSUE_URL, **extra})
+ assert signal_view(item).link == expected
+
+ def test_shows_the_newest_signal_from_each_source_first(self) -> None:
+ signals = [
+ signal(signal_id="old-replay", source_product="replay_vision", timestamp="2026-09-01T00:00:00+00:00"),
+ signal(signal_id="new-replay", source_product="replay_vision", timestamp="2026-09-03T00:00:00+00:00"),
+ signal(signal_id="scout", timestamp="2026-08-01T00:00:00+00:00"),
+ ]
+ assert [picked.signal_id for picked in pick_evidence(signals, 2)] == ["new-replay", "scout"]
+
+ def test_shows_one_row_for_several_checks_of_the_same_alert(self) -> None:
+ signals = [
+ signal(
+ signal_id=check_id,
+ source_product="analytics",
+ source_id=check_id,
+ timestamp=timestamp,
+ extra={"alert_id": "orders-alert"},
+ )
+ for check_id, timestamp in (
+ ("early-check", "2026-09-01T09:00:00+00:00"),
+ ("late-check", "2026-09-01T09:40:00+00:00"),
+ )
+ ]
+ assert [picked.signal_id for picked in pick_evidence(signals, 3)] == ["late-check"]
+ assert distinct_evidence_count(signals) == 1
diff --git a/products/today/frontend/generated/api.schemas.ts b/products/today/frontend/generated/api.schemas.ts
index 1f0f6bf85b9f..28443b33c23c 100644
--- a/products/today/frontend/generated/api.schemas.ts
+++ b/products/today/frontend/generated/api.schemas.ts
@@ -359,6 +359,184 @@ export interface CandidateListApi {
more_reports_count: number
}
+export interface PullRequestLinkApi {
+ /** The pull request on GitHub. */
+ url: string
+ /** The pull request number. */
+ number: number
+}
+
+/**
+ * * `code` - Code
+ * * `slack` - Slack
+ */
+export type CitedSourceEnumApi = (typeof CitedSourceEnumApi)[keyof typeof CitedSourceEnumApi]
+
+export const CitedSourceEnumApi = {
+ Code: 'code',
+ Slack: 'slack',
+} as const
+
+export interface RecordingTargetApi {
+ /** The recording's session id. */
+ session_id: string
+ /**
+ * Where the player starts, a few seconds before the finding.
+ * @nullable
+ */
+ start_at: string | null
+ /**
+ * The finding's time in the recording, as MM:SS.
+ * @nullable
+ */
+ offset: string | null
+ /**
+ * Where the player starts, in seconds from the recording start. Null without an offset.
+ * @nullable
+ */
+ seek_seconds: number | null
+}
+
+export interface PageLinkApi {
+ /** Where the link goes, outside PostHog. */
+ url: string
+ /** The link text. */
+ text: string
+}
+
+export interface CodeFileApi {
+ /** The repository as owner/name. */
+ repo: string
+ /** The file path in the repository. */
+ path: string
+}
+
+export interface PreviewLineApi {
+ /** One line of the preview block. */
+ text: string
+ /** Whether the line is secondary, such as a stack frame. */
+ quiet: boolean
+}
+
+export interface SignalPreviewApi {
+ /** What expanding the signal shows, such as 'Show the stack trace'. */
+ hint: string
+ /** Repository files to quote, the finding's own file first. */
+ code: CodeFileApi[]
+ /** A preformatted block, such as a stack trace or a query. */
+ block: PreviewLineApi[]
+ /** The finding's text beyond its first sentence. */
+ text: string
+ /** Short facts about the source. */
+ facts: string[]
+ /** A link that replaces the signal's own destination. */
+ link: PageLinkApi | null
+ /**
+ * A label that replaces the label of the signal's own destination.
+ * @nullable
+ */
+ link_label: string | null
+}
+
+/**
+ * The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON.
+ */
+export type SignalViewApiExtra = { [key: string]: unknown }
+
+export interface SignalViewApi {
+ /** The signal's id. */
+ signal_id: string
+ /** The product that emitted the signal. */
+ source_product: string
+ /** The kind of signal within its product. */
+ source_type: string
+ /** The id of the source object, such as an issue or a ticket. */
+ source_id: string
+ /** The signal's text as emitted. */
+ content: string
+ /** When the signal happened. */
+ timestamp: string
+ /** The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON. */
+ extra: SignalViewApiExtra
+ /** The signal as one short line. */
+ headline: string
+ /** The signal's first sentence. */
+ lead: string
+ /** Identifiers such as a pull request or ticket number, joined by dots. */
+ meta: string
+ /** What a scout finding cites: code or a Slack thread.
+ *
+ * * `code` - Code
+ * * `slack` - Slack */
+ cited: CitedSourceEnumApi | null
+ /** The recording the signal plays, if any. */
+ recording: RecordingTargetApi | null
+ /** Where a scout finding links outside PostHog, if anywhere. */
+ link: PageLinkApi | null
+ /** What expanding the signal shows, if anything. */
+ preview: SignalPreviewApi | null
+}
+
+/**
+ * * `tickets` - Support tickets
+ * * `query-hours` - Database hours
+ */
+export type ImpactNumberKeyEnumApi = (typeof ImpactNumberKeyEnumApi)[keyof typeof ImpactNumberKeyEnumApi]
+
+export const ImpactNumberKeyEnumApi = {
+ Tickets: 'tickets',
+ QueryHours: 'query-hours',
+} as const
+
+export interface ImpactWorkingApi {
+ /** How the number is worked out, such as '120 ms × 30,000 calls'. */
+ expression: string
+ /** What the working comes to, such as '1.00 hours a day'. */
+ result: string
+}
+
+export interface ImpactNumberApi {
+ /** Which number this is: distinct support tickets or database hours a day.
+ *
+ * * `tickets` - Support tickets
+ * * `query-hours` - Database hours */
+ key: ImpactNumberKeyEnumApi
+ /** The number as shown, such as '2' or '1 hour'. */
+ value: string
+ /** The sentence that follows the number. */
+ sentence: string
+ /** The signal the number comes from, if one does. */
+ signal: SignalViewApi | null
+ /** The figures in the signal's headline to mark. */
+ values: string[]
+ /** How the number is worked out, if it is. */
+ working: ImpactWorkingApi | null
+}
+
+export interface ReportPageApi {
+ /** The summary's opening paragraph, as markdown. */
+ lead: string
+ /** The proposed fix cut to whole sentences, as markdown. Empty when the report proposes none. */
+ proposal: string
+ /** The impact section cut to whole sentences, as markdown, when it states a measurement. Empty otherwise. */
+ impact_sentence: string
+ /** The pull request the proposal names, or else the summary, when it names exactly one. */
+ named_pull_request: PullRequestLinkApi | null
+ /** Whether the proposal names any pull request. */
+ solution_names_pull_request: boolean
+ /** The signals to show as evidence, at most 3, newest first, one per source first. */
+ evidence: SignalViewApi[]
+ /** How many distinct source objects the report's newest 100 signals come from. The impact numbers and last seen use the same signals. */
+ source_count: number
+ /** Numbers the signals size the problem with, such as distinct support tickets. */
+ impact_numbers: ImpactNumberApi[]
+ /**
+ * When the newest session, ticket or alert behind the report happened.
+ * @nullable
+ */
+ last_seen: string | null
+}
+
export type TodayBriefingRetrieveParams = {
/**
* IANA timezone of the person's browser, for example Europe/Prague. The briefing day starts at 8:00 in it. Defaults to the project timezone.
diff --git a/products/today/frontend/generated/api.ts b/products/today/frontend/generated/api.ts
index f5635280f156..4238f0aabbea 100644
--- a/products/today/frontend/generated/api.ts
+++ b/products/today/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
BriefingApi,
CandidateListApi,
+ ReportPageApi,
TodayBriefingRefreshCreateParams,
TodayBriefingRetrieveParams,
TodayCandidatesRetrieveParams,
@@ -108,3 +109,22 @@ export const todayCandidatesRetrieve = async (
method: 'GET',
})
}
+
+export const getTodayReportsPageRetrieveUrl = (projectId: string, reportId: string) => {
+ return `/api/projects/${projectId}/today/reports/${reportId}/page/`
+}
+
+/**
+ * What the Today report page shows for a report: its lead, the proposal and the impact sentence cut to whole sentences, and the pull request it names. Sample report ids return the built-in sample reports. 404 when the report is missing or the person does not have the new navigation. 403 when the person may not read Inbox reports, and a scoped key needs task:read as well, because the page shows the report's signals.
+ * @summary Get a report's page
+ */
+export const todayReportsPageRetrieve = async (
+ projectId: string,
+ reportId: string,
+ options?: RequestInit
+): Promise<ReportPageApi> => {
+ return apiMutator<ReportPageApi>(getTodayReportsPageRetrieveUrl(projectId, reportId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/today/frontend/generated/api.zod.schemas.ts b/products/today/frontend/generated/api.zod.schemas.ts
index 4788961246b6..cda8bb1c6846 100644
--- a/products/today/frontend/generated/api.zod.schemas.ts
+++ b/products/today/frontend/generated/api.zod.schemas.ts
@@ -703,3 +703,584 @@ export const CandidateListApi = zod.object({
export type CandidateListApi = zod.input<typeof CandidateListApi>
export type CandidateListApiOutput = zod.output<typeof CandidateListApi>
+
+export const PullRequestLinkApi = zod.object({
+ url: zod.string().describe('The pull request on GitHub.'),
+ number: zod.number().describe('The pull request number.'),
+})
+
+export type PullRequestLinkApi = zod.input<typeof PullRequestLinkApi>
+export type PullRequestLinkApiOutput = zod.output<typeof PullRequestLinkApi>
+
+export const CitedSourceEnumApi = zod.enum(['code', 'slack']).describe('\* `code` - Code\n\* `slack` - Slack')
+
+export type CitedSourceEnumApi = zod.input<typeof CitedSourceEnumApi>
+export type CitedSourceEnumApiOutput = zod.output<typeof CitedSourceEnumApi>
+
+export const RecordingTargetApi = zod.object({
+ session_id: zod.string().describe("The recording's session id."),
+ start_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Where the player starts, a few seconds before the finding.'),
+ offset: zod.string().nullable().describe("The finding's time in the recording, as MM:SS."),
+ seek_seconds: zod
+ .number()
+ .nullable()
+ .describe('Where the player starts, in seconds from the recording start. Null without an offset.'),
+})
+
+export type RecordingTargetApi = zod.input<typeof RecordingTargetApi>
+export type RecordingTargetApiOutput = zod.output<typeof RecordingTargetApi>
+
+export const PageLinkApi = zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+})
+
+export type PageLinkApi = zod.input<typeof PageLinkApi>
+export type PageLinkApiOutput = zod.output<typeof PageLinkApi>
+
+export const CodeFileApi = zod.object({
+ repo: zod.string().describe('The repository as owner\/name.'),
+ path: zod.string().describe('The file path in the repository.'),
+})
+
+export type CodeFileApi = zod.input<typeof CodeFileApi>
+export type CodeFileApiOutput = zod.output<typeof CodeFileApi>
+
+export const PreviewLineApi = zod.object({
+ text: zod.string().describe('One line of the preview block.'),
+ quiet: zod.boolean().describe('Whether the line is secondary, such as a stack frame.'),
+})
+
+export type PreviewLineApi = zod.input<typeof PreviewLineApi>
+export type PreviewLineApiOutput = zod.output<typeof PreviewLineApi>
+
+export const SignalPreviewApi = zod.object({
+ hint: zod.string().describe("What expanding the signal shows, such as 'Show the stack trace'."),
+ code: zod
+ .array(
+ zod.object({
+ repo: zod.string().describe('The repository as owner\/name.'),
+ path: zod.string().describe('The file path in the repository.'),
+ })
+ )
+ .describe("Repository files to quote, the finding's own file first."),
+ block: zod
+ .array(
+ zod.object({
+ text: zod.string().describe('One line of the preview block.'),
+ quiet: zod.boolean().describe('Whether the line is secondary, such as a stack frame.'),
+ })
+ )
+ .describe('A preformatted block, such as a stack trace or a query.'),
+ text: zod.string().describe("The finding's text beyond its first sentence."),
+ facts: zod.array(zod.string()).describe('Short facts about the source.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe("A link that replaces the signal's own destination."),
+ link_label: zod.string().nullable().describe("A label that replaces the label of the signal's own destination."),
+})
+
+export type SignalPreviewApi = zod.input<typeof SignalPreviewApi>
+export type SignalPreviewApiOutput = zod.output<typeof SignalPreviewApi>
+
+export const SignalViewApi = zod.object({
+ signal_id: zod.string().describe("The signal's id."),
+ source_product: zod.string().describe('The product that emitted the signal.'),
+ source_type: zod.string().describe('The kind of signal within its product.'),
+ source_id: zod.string().describe('The id of the source object, such as an issue or a ticket.'),
+ content: zod.string().describe("The signal's text as emitted."),
+ timestamp: zod.iso.datetime({ offset: true }).describe('When the signal happened.'),
+ extra: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ "The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON."
+ ),
+ headline: zod.string().describe('The signal as one short line.'),
+ lead: zod.string().describe("The signal's first sentence."),
+ meta: zod.string().describe('Identifiers such as a pull request or ticket number, joined by dots.'),
+ cited: zod
+ .union([zod.enum(['code', 'slack']).describe('\* `code` - Code\n\* `slack` - Slack'), zod.null()])
+ .describe('What a scout finding cites: code or a Slack thread.\n\n\* `code` - Code\n\* `slack` - Slack'),
+ recording: zod
+ .union([
+ zod.object({
+ session_id: zod.string().describe("The recording's session id."),
+ start_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Where the player starts, a few seconds before the finding.'),
+ offset: zod.string().nullable().describe("The finding's time in the recording, as MM:SS."),
+ seek_seconds: zod
+ .number()
+ .nullable()
+ .describe('Where the player starts, in seconds from the recording start. Null without an offset.'),
+ }),
+ zod.null(),
+ ])
+ .describe('The recording the signal plays, if any.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe('Where a scout finding links outside PostHog, if anywhere.'),
+ preview: zod
+ .union([
+ zod.object({
+ hint: zod.string().describe("What expanding the signal shows, such as 'Show the stack trace'."),
+ code: zod
+ .array(
+ zod.object({
+ repo: zod.string().describe('The repository as owner\/name.'),
+ path: zod.string().describe('The file path in the repository.'),
+ })
+ )
+ .describe("Repository files to quote, the finding's own file first."),
+ block: zod
+ .array(
+ zod.object({
+ text: zod.string().describe('One line of the preview block.'),
+ quiet: zod.boolean().describe('Whether the line is secondary, such as a stack frame.'),
+ })
+ )
+ .describe('A preformatted block, such as a stack trace or a query.'),
+ text: zod.string().describe("The finding's text beyond its first sentence."),
+ facts: zod.array(zod.string()).describe('Short facts about the source.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe("A link that replaces the signal's own destination."),
+ link_label: zod
+ .string()
+ .nullable()
+ .describe("A label that replaces the label of the signal's own destination."),
+ }),
+ zod.null(),
+ ])
+ .describe('What expanding the signal shows, if anything.'),
+})
+
+export type SignalViewApi = zod.input<typeof SignalViewApi>
+export type SignalViewApiOutput = zod.output<typeof SignalViewApi>
+
+export const ImpactNumberKeyEnumApi = zod
+ .enum(['tickets', 'query-hours'])
+ .describe('\* `tickets` - Support tickets\n\* `query-hours` - Database hours')
+
+export type ImpactNumberKeyEnumApi = zod.input<typeof ImpactNumberKeyEnumApi>
+export type ImpactNumberKeyEnumApiOutput = zod.output<typeof ImpactNumberKeyEnumApi>
+
+export const ImpactWorkingApi = zod.object({
+ expression: zod.string().describe("How the number is worked out, such as '120 ms × 30,000 calls'."),
+ result: zod.string().describe("What the working comes to, such as '1.00 hours a day'."),
+})
+
+export type ImpactWorkingApi = zod.input<typeof ImpactWorkingApi>
+export type ImpactWorkingApiOutput = zod.output<typeof ImpactWorkingApi>
+
+export const ImpactNumberApi = zod.object({
+ key: zod
+ .enum(['tickets', 'query-hours'])
+ .describe('\* `tickets` - Support tickets\n\* `query-hours` - Database hours')
+ .describe(
+ 'Which number this is: distinct support tickets or database hours a day.\n\n\* `tickets` - Support tickets\n\* `query-hours` - Database hours'
+ ),
+ value: zod.string().describe("The number as shown, such as '2' or '1 hour'."),
+ sentence: zod.string().describe('The sentence that follows the number.'),
+ signal: zod
+ .union([
+ zod.object({
+ signal_id: zod.string().describe("The signal's id."),
+ source_product: zod.string().describe('The product that emitted the signal.'),
+ source_type: zod.string().describe('The kind of signal within its product.'),
+ source_id: zod.string().describe('The id of the source object, such as an issue or a ticket.'),
+ content: zod.string().describe("The signal's text as emitted."),
+ timestamp: zod.iso.datetime({ offset: true }).describe('When the signal happened.'),
+ extra: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ "The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON."
+ ),
+ headline: zod.string().describe('The signal as one short line.'),
+ lead: zod.string().describe("The signal's first sentence."),
+ meta: zod.string().describe('Identifiers such as a pull request or ticket number, joined by dots.'),
+ cited: zod
+ .union([zod.enum(['code', 'slack']).describe('\* `code` - Code\n\* `slack` - Slack'), zod.null()])
+ .describe(
+ 'What a scout finding cites: code or a Slack thread.\n\n\* `code` - Code\n\* `slack` - Slack'
+ ),
+ recording: zod
+ .union([
+ zod.object({
+ session_id: zod.string().describe("The recording's session id."),
+ start_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Where the player starts, a few seconds before the finding.'),
+ offset: zod.string().nullable().describe("The finding's time in the recording, as MM:SS."),
+ seek_seconds: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Where the player starts, in seconds from the recording start. Null without an offset.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe('The recording the signal plays, if any.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe('Where a scout finding links outside PostHog, if anywhere.'),
+ preview: zod
+ .union([
+ zod.object({
+ hint: zod
+ .string()
+ .describe("What expanding the signal shows, such as 'Show the stack trace'."),
+ code: zod
+ .array(
+ zod.object({
+ repo: zod.string().describe('The repository as owner\/name.'),
+ path: zod.string().describe('The file path in the repository.'),
+ })
+ )
+ .describe("Repository files to quote, the finding's own file first."),
+ block: zod
+ .array(
+ zod.object({
+ text: zod.string().describe('One line of the preview block.'),
+ quiet: zod
+ .boolean()
+ .describe('Whether the line is secondary, such as a stack frame.'),
+ })
+ )
+ .describe('A preformatted block, such as a stack trace or a query.'),
+ text: zod.string().describe("The finding's text beyond its first sentence."),
+ facts: zod.array(zod.string()).describe('Short facts about the source.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe("A link that replaces the signal's own destination."),
+ link_label: zod
+ .string()
+ .nullable()
+ .describe("A label that replaces the label of the signal's own destination."),
+ }),
+ zod.null(),
+ ])
+ .describe('What expanding the signal shows, if anything.'),
+ }),
+ zod.null(),
+ ])
+ .describe('The signal the number comes from, if one does.'),
+ values: zod.array(zod.string()).describe("The figures in the signal's headline to mark."),
+ working: zod
+ .union([
+ zod.object({
+ expression: zod.string().describe("How the number is worked out, such as '120 ms × 30,000 calls'."),
+ result: zod.string().describe("What the working comes to, such as '1.00 hours a day'."),
+ }),
+ zod.null(),
+ ])
+ .describe('How the number is worked out, if it is.'),
+})
+
+export type ImpactNumberApi = zod.input<typeof ImpactNumberApi>
+export type ImpactNumberApiOutput = zod.output<typeof ImpactNumberApi>
+
+export const ReportPageApi = zod.object({
+ lead: zod.string().describe("The summary's opening paragraph, as markdown."),
+ proposal: zod
+ .string()
+ .describe('The proposed fix cut to whole sentences, as markdown. Empty when the report proposes none.'),
+ impact_sentence: zod
+ .string()
+ .describe(
+ 'The impact section cut to whole sentences, as markdown, when it states a measurement. Empty otherwise.'
+ ),
+ named_pull_request: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('The pull request on GitHub.'),
+ number: zod.number().describe('The pull request number.'),
+ }),
+ zod.null(),
+ ])
+ .describe('The pull request the proposal names, or else the summary, when it names exactly one.'),
+ solution_names_pull_request: zod.boolean().describe('Whether the proposal names any pull request.'),
+ evidence: zod
+ .array(
+ zod.object({
+ signal_id: zod.string().describe("The signal's id."),
+ source_product: zod.string().describe('The product that emitted the signal.'),
+ source_type: zod.string().describe('The kind of signal within its product.'),
+ source_id: zod.string().describe('The id of the source object, such as an issue or a ticket.'),
+ content: zod.string().describe("The signal's text as emitted."),
+ timestamp: zod.iso.datetime({ offset: true }).describe('When the signal happened.'),
+ extra: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ "The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON."
+ ),
+ headline: zod.string().describe('The signal as one short line.'),
+ lead: zod.string().describe("The signal's first sentence."),
+ meta: zod.string().describe('Identifiers such as a pull request or ticket number, joined by dots.'),
+ cited: zod
+ .union([zod.enum(['code', 'slack']).describe('\* `code` - Code\n\* `slack` - Slack'), zod.null()])
+ .describe(
+ 'What a scout finding cites: code or a Slack thread.\n\n\* `code` - Code\n\* `slack` - Slack'
+ ),
+ recording: zod
+ .union([
+ zod.object({
+ session_id: zod.string().describe("The recording's session id."),
+ start_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Where the player starts, a few seconds before the finding.'),
+ offset: zod.string().nullable().describe("The finding's time in the recording, as MM:SS."),
+ seek_seconds: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Where the player starts, in seconds from the recording start. Null without an offset.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe('The recording the signal plays, if any.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe('Where a scout finding links outside PostHog, if anywhere.'),
+ preview: zod
+ .union([
+ zod.object({
+ hint: zod
+ .string()
+ .describe("What expanding the signal shows, such as 'Show the stack trace'."),
+ code: zod
+ .array(
+ zod.object({
+ repo: zod.string().describe('The repository as owner\/name.'),
+ path: zod.string().describe('The file path in the repository.'),
+ })
+ )
+ .describe("Repository files to quote, the finding's own file first."),
+ block: zod
+ .array(
+ zod.object({
+ text: zod.string().describe('One line of the preview block.'),
+ quiet: zod
+ .boolean()
+ .describe('Whether the line is secondary, such as a stack frame.'),
+ })
+ )
+ .describe('A preformatted block, such as a stack trace or a query.'),
+ text: zod.string().describe("The finding's text beyond its first sentence."),
+ facts: zod.array(zod.string()).describe('Short facts about the source.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe("A link that replaces the signal's own destination."),
+ link_label: zod
+ .string()
+ .nullable()
+ .describe("A label that replaces the label of the signal's own destination."),
+ }),
+ zod.null(),
+ ])
+ .describe('What expanding the signal shows, if anything.'),
+ })
+ )
+ .describe('The signals to show as evidence, at most 3, newest first, one per source first.'),
+ source_count: zod
+ .number()
+ .describe(
+ "How many distinct source objects the report's newest 100 signals come from. The impact numbers and last seen use the same signals."
+ ),
+ impact_numbers: zod
+ .array(
+ zod.object({
+ key: zod
+ .enum(['tickets', 'query-hours'])
+ .describe('\* `tickets` - Support tickets\n\* `query-hours` - Database hours')
+ .describe(
+ 'Which number this is: distinct support tickets or database hours a day.\n\n\* `tickets` - Support tickets\n\* `query-hours` - Database hours'
+ ),
+ value: zod.string().describe("The number as shown, such as '2' or '1 hour'."),
+ sentence: zod.string().describe('The sentence that follows the number.'),
+ signal: zod
+ .union([
+ zod.object({
+ signal_id: zod.string().describe("The signal's id."),
+ source_product: zod.string().describe('The product that emitted the signal.'),
+ source_type: zod.string().describe('The kind of signal within its product.'),
+ source_id: zod
+ .string()
+ .describe('The id of the source object, such as an issue or a ticket.'),
+ content: zod.string().describe("The signal's text as emitted."),
+ timestamp: zod.iso.datetime({ offset: true }).describe('When the signal happened.'),
+ extra: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ "The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON."
+ ),
+ headline: zod.string().describe('The signal as one short line.'),
+ lead: zod.string().describe("The signal's first sentence."),
+ meta: zod
+ .string()
+ .describe('Identifiers such as a pull request or ticket number, joined by dots.'),
+ cited: zod
+ .union([
+ zod.enum(['code', 'slack']).describe('\* `code` - Code\n\* `slack` - Slack'),
+ zod.null(),
+ ])
+ .describe(
+ 'What a scout finding cites: code or a Slack thread.\n\n\* `code` - Code\n\* `slack` - Slack'
+ ),
+ recording: zod
+ .union([
+ zod.object({
+ session_id: zod.string().describe("The recording's session id."),
+ start_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Where the player starts, a few seconds before the finding.'),
+ offset: zod
+ .string()
+ .nullable()
+ .describe("The finding's time in the recording, as MM:SS."),
+ seek_seconds: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Where the player starts, in seconds from the recording start. Null without an offset.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe('The recording the signal plays, if any.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe('Where a scout finding links outside PostHog, if anywhere.'),
+ preview: zod
+ .union([
+ zod.object({
+ hint: zod
+ .string()
+ .describe(
+ "What expanding the signal shows, such as 'Show the stack trace'."
+ ),
+ code: zod
+ .array(
+ zod.object({
+ repo: zod.string().describe('The repository as owner\/name.'),
+ path: zod.string().describe('The file path in the repository.'),
+ })
+ )
+ .describe("Repository files to quote, the finding's own file first."),
+ block: zod
+ .array(
+ zod.object({
+ text: zod.string().describe('One line of the preview block.'),
+ quiet: zod
+ .boolean()
+ .describe(
+ 'Whether the line is secondary, such as a stack frame.'
+ ),
+ })
+ )
+ .describe('A preformatted block, such as a stack trace or a query.'),
+ text: zod.string().describe("The finding's text beyond its first sentence."),
+ facts: zod.array(zod.string()).describe('Short facts about the source.'),
+ link: zod
+ .union([
+ zod.object({
+ url: zod.string().describe('Where the link goes, outside PostHog.'),
+ text: zod.string().describe('The link text.'),
+ }),
+ zod.null(),
+ ])
+ .describe("A link that replaces the signal's own destination."),
+ link_label: zod
+ .string()
+ .nullable()
+ .describe(
+ "A label that replaces the label of the signal's own destination."
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe('What expanding the signal shows, if anything.'),
+ }),
+ zod.null(),
+ ])
+ .describe('The signal the number comes from, if one does.'),
+ values: zod.array(zod.string()).describe("The figures in the signal's headline to mark."),
+ working: zod
+ .union([
+ zod.object({
+ expression: zod
+ .string()
+ .describe("How the number is worked out, such as '120 ms × 30,000 calls'."),
+ result: zod.string().describe("What the working comes to, such as '1.00 hours a day'."),
+ }),
+ zod.null(),
+ ])
+ .describe('How the number is worked out, if it is.'),
+ })
+ )
+ .describe('Numbers the signals size the problem with, such as distinct support tickets.'),
+ last_seen: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the newest session, ticket or alert behind the report happened.'),
+})
+
+export type ReportPageApi = zod.input<typeof ReportPageApi>
+export type ReportPageApiOutput = zod.output<typeof ReportPageApi>
diff --git a/products/today/mcp/tools.yaml b/products/today/mcp/tools.yaml
index abf0d5d95a99..cf47880605bf 100644
--- a/products/today/mcp/tools.yaml
+++ b/products/today/mcp/tools.yaml
@@ -50,3 +50,6 @@ tools:
urgent first.
feature_flag: today-rail-nav
feature_flag_behavior: enable
+ today-reports-page-retrieve:
+ operation: today_reports_page_retrieve
+ enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 48aafcf9f499..daf3bcf1bb30 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22091,6 +22091,18 @@ export namespace Schemas {
CustomSql: 'custom_sql',
} as const;
+ /**
+ * * `code` - Code
+ * * `slack` - Slack
+ */
+ export type CitedSourceEnum = typeof CitedSourceEnum[keyof typeof CitedSourceEnum];
+
+
+ export const CitedSourceEnum = {
+ Code: 'code',
+ Slack: 'slack',
+ } as const;
+
export interface TagCount {
/** The tag value. */
tag: string;
@@ -22657,6 +22669,13 @@ export namespace Schemas {
StaleVersion: 'stale_version',
} as const;
+ export interface CodeFile {
+ /** The repository as owner/name. */
+ repo: string;
+ /** The file path in the repository. */
+ path: string;
+ }
+
/**
* * `connected` - Connected
* * `reauth_required` - Reauth Required
@@ -57014,6 +57033,136 @@ export namespace Schemas {
id_jag_allowed_clients?: string[];
}
+ /**
+ * * `tickets` - Support tickets
+ * * `query-hours` - Database hours
+ */
+ export type ImpactNumberKeyEnum = typeof ImpactNumberKeyEnum[keyof typeof ImpactNumberKeyEnum];
+
+
+ export const ImpactNumberKeyEnum = {
+ Tickets: 'tickets',
+ QueryHours: 'query-hours',
+ } as const;
+
+ export interface RecordingTarget {
+ /** The recording's session id. */
+ session_id: string;
+ /**
+ * Where the player starts, a few seconds before the finding.
+ * @nullable
+ */
+ start_at: string | null;
+ /**
+ * The finding's time in the recording, as MM:SS.
+ * @nullable
+ */
+ offset: string | null;
+ /**
+ * Where the player starts, in seconds from the recording start. Null without an offset.
+ * @nullable
+ */
+ seek_seconds: number | null;
+ }
+
+ export interface PageLink {
+ /** Where the link goes, outside PostHog. */
+ url: string;
+ /** The link text. */
+ text: string;
+ }
+
+ export interface PreviewLine {
+ /** One line of the preview block. */
+ text: string;
+ /** Whether the line is secondary, such as a stack frame. */
+ quiet: boolean;
+ }
+
+ export interface SignalPreview {
+ /** What expanding the signal shows, such as 'Show the stack trace'. */
+ hint: string;
+ /** Repository files to quote, the finding's own file first. */
+ code: CodeFile[];
+ /** A preformatted block, such as a stack trace or a query. */
+ block: PreviewLine[];
+ /** The finding's text beyond its first sentence. */
+ text: string;
+ /** Short facts about the source. */
+ facts: string[];
+ /** A link that replaces the signal's own destination. */
+ link: PageLink | null;
+ /**
+ * A label that replaces the label of the signal's own destination.
+ * @nullable
+ */
+ link_label: string | null;
+ }
+
+ /**
+ * The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON.
+ */
+ export type SignalViewExtra = { [key: string]: unknown };
+
+ export interface SignalView {
+ /** The signal's id. */
+ signal_id: string;
+ /** The product that emitted the signal. */
+ source_product: string;
+ /** The kind of signal within its product. */
+ source_type: string;
+ /** The id of the source object, such as an issue or a ticket. */
+ source_id: string;
+ /** The signal's text as emitted. */
+ content: string;
+ /** When the signal happened. */
+ timestamp: string;
+ /** The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON. */
+ extra: SignalViewExtra;
+ /** The signal as one short line. */
+ headline: string;
+ /** The signal's first sentence. */
+ lead: string;
+ /** Identifiers such as a pull request or ticket number, joined by dots. */
+ meta: string;
+ /** What a scout finding cites: code or a Slack thread.
+ *
+ * * `code` - Code
+ * * `slack` - Slack */
+ cited: CitedSourceEnum | null;
+ /** The recording the signal plays, if any. */
+ recording: RecordingTarget | null;
+ /** Where a scout finding links outside PostHog, if anywhere. */
+ link: PageLink | null;
+ /** What expanding the signal shows, if anything. */
+ preview: SignalPreview | null;
+ }
+
+ export interface ImpactWorking {
+ /** How the number is worked out, such as '120 ms × 30,000 calls'. */
+ expression: string;
+ /** What the working comes to, such as '1.00 hours a day'. */
+ result: string;
+ }
+
+ export interface ImpactNumber {
+ /** Which number this is: distinct support tickets or database hours a day.
+ *
+ * * `tickets` - Support tickets
+ * * `query-hours` - Database hours */
+ key: ImpactNumberKeyEnum;
+ /** The number as shown, such as '2' or '1 hour'. */
+ value: string;
+ /** The sentence that follows the number. */
+ sentence: string;
+ /** The signal the number comes from, if one does. */
+ signal: SignalView | null;
+ /** The figures in the signal's headline to mark. */
+ values: string[];
+ /** How the number is worked out, if it is. */
+ working: ImpactWorking | null;
+ }
+
/**
* Coarse type per candidate, keyed by column name: datetime, date, integer, decimal, float, string, or uuid. A candidate with no entry has a type the check could not determine.
*/
@@ -86338,6 +86487,13 @@ export namespace Schemas {
window_days: number;
}
+ export interface PullRequestLink {
+ /** The pull request on GitHub. */
+ url: string;
+ /** The pull request number. */
+ number: number;
+ }
+
export interface PullRequestList {
/** This page of pull requests, newest first, capped at `limit`. */
items: PullRequestListItem[];
@@ -90449,6 +90605,30 @@ export namespace Schemas {
minimum_data_points?: number | null;
}
+ export interface ReportPage {
+ /** The summary's opening paragraph, as markdown. */
+ lead: string;
+ /** The proposed fix cut to whole sentences, as markdown. Empty when the report proposes none. */
+ proposal: string;
+ /** The impact section cut to whole sentences, as markdown, when it states a measurement. Empty otherwise. */
+ impact_sentence: string;
+ /** The pull request the proposal names, or else the summary, when it names exactly one. */
+ named_pull_request: PullRequestLink | null;
+ /** Whether the proposal names any pull request. */
+ solution_names_pull_request: boolean;
+ /** The signals to show as evidence, at most 3, newest first, one per source first. */
+ evidence: SignalView[];
+ /** How many distinct source objects the report's newest 100 signals come from. The impact numbers and last seen use the same signals. */
+ source_count: number;
+ /** Numbers the signals size the problem with, such as distinct support tickets. */
+ impact_numbers: ImpactNumber[];
+ /**
+ * When the newest session, ticket or alert behind the report happened.
+ * @nullable
+ */
+ last_seen: string | null;
+ }
+
export type ReportPriority = typeof ReportPriority[keyof typeof ReportPriority];