:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): let activity summary themes cite tasks and mcp sessions (#126920)
posthog[bot]acf0408a4ea7
diff --git a/products/signals/backend/activity_summary/computed.py b/products/signals/backend/activity_summary/computed.pyindex 77bf07331176..d8c3c1fe723c 100644--- a/products/signals/backend/activity_summary/computed.py+++ b/products/signals/backend/activity_summary/computed.py@@ -19,7 +19,9 @@ from products.signals.backend.activity_summary.render import (ACTIVITY_NAME_CHARS,SCENE_VIEW_TYPE,ActivityItem,+ LineRef,Product,+ RenderedInput,TaskItem,ViewItem,cap_line,@@ -34,7 +36,9 @@ from products.signals.backend.activity_summary.render import ()# Bump on any change to the shape or the meaning of a field, so a consumer can tell old rows apart.-COMPUTED_SCHEMA_VERSION = 1+COMPUTED_SCHEMA_VERSION = 2+# Versions that `read.py` still serves. Version 1 has no `tasks` and no `mcp_sessions`.+READABLE_COMPUTED_SCHEMA_VERSIONS: frozenset[int] = frozenset({1, COMPUTED_SCHEMA_VERSION})MAX_OWNED = 20# Owned objects one type takes in the first pass, so a burst of insights cannot fill the list.MAX_OWNED_PER_TYPE = 8@@ -93,6 +97,12 @@ class ComputedFields:pages: tuple[PageVisits, ...]products: ProductSplittask_count: int+ # The task and MCP lines of the rendered input, which themes cite as "t" and "m" refs.+ tasks: tuple[LineRef, ...] = ()+ mcp_sessions: tuple[LineRef, ...] = ()++ def with_line_refs(self, rendered: RenderedInput) -> "ComputedFields":+ return dataclasses.replace(self, tasks=rendered.task_refs, mcp_sessions=rendered.mcp_refs)def as_json(self) -> dict[str, Any]:# JSON has no tuples, so the stored value and this one compare equal.diff --git a/products/signals/backend/activity_summary/logic.py b/products/signals/backend/activity_summary/logic.pyindex ce511fd2ede4..4a4be9488a38 100644--- a/products/signals/backend/activity_summary/logic.py+++ b/products/signals/backend/activity_summary/logic.py@@ -422,10 +422,11 @@ def update_activity_summary()# An incremental update reads only the rows after the watermark, so the computed fields read the full window.if start == window_start:- computed = compute_fields(tasks, activity, views).as_json()+ fields = compute_fields(tasks, activity, views)else:full = _read_inputs(team_id, user_id, window_start, now)- computed = compute_fields(full.tasks, full.activity, full.views).as_json()+ fields = compute_fields(full.tasks, full.activity, full.views)+ computed = fields.with_line_refs(rendered).as_json()previous = stored.summary if stored is not None and not rebuild else Noneoutcome, cost = _call_model(team_id, user_id, rendered, computed, previous=previous, as_of=now, limits=limits)if outcome.summary is not None:@@ -541,7 +542,9 @@ def render_as_of(inputs_used = _inputs_used(rendered, limits, window.mcp)inputs_used["drops"] = {**rendered.drops, **excluded}return AsOfInput(- rendered=rendered, computed=compute_fields(tasks, activity, views).as_json(), inputs_used=inputs_used+ rendered=rendered,+ computed=compute_fields(tasks, activity, views).with_line_refs(rendered).as_json(),+ inputs_used=inputs_used,)diff --git a/products/signals/backend/activity_summary/measure.py b/products/signals/backend/activity_summary/measure.pyindex 2ced137fb919..5494c5a3faad 100644--- a/products/signals/backend/activity_summary/measure.py+++ b/products/signals/backend/activity_summary/measure.py@@ -295,7 +295,7 @@ def leave_one_out_pair(previous_summary=None,model=DEFAULT_MODEL,as_of=now.date(),- computed=compute_fields(variant_tasks, variant_activity, []).as_json(),+ computed=compute_fields(variant_tasks, variant_activity, []).with_line_refs(rendered).as_json(),)records.append({diff --git a/products/signals/backend/activity_summary/prompt.py b/products/signals/backend/activity_summary/prompt.pyindex 06e4297d47b6..7f50b4354e0f 100644--- a/products/signals/backend/activity_summary/prompt.py+++ b/products/signals/backend/activity_summary/prompt.py@@ -12,6 +12,7 @@ from typing import Anyfrom django.db import models+from products.signals.backend.activity_summary.computed import MIN_WATCHED_OPEN_DAYSfrom products.signals.backend.activity_summary.render import (PRODUCT_LABELS,PROFILE_MAX_CHARS,@@ -20,9 +21,13 @@ from products.signals.backend.activity_summary.render import (days_text,)-PROMPT_VERSION = 7+PROMPT_VERSION = 8MAX_THEMES = 6+MAX_MODES = 3+# The computed lists whose refs a theme can cite. A "p" ref is the pages of one product.+_REF_LISTS = ("owned", "watched", "pages", "tasks", "mcp_sessions")+_PAGES_REF_PREFIX = "p"# Per-field caps, so one runaway field cannot make the stored summary large. A cut ends at a word boundary.MAX_LABEL_CHARS = 60MAX_RECENT_SHIFT_CHARS = 300@@ -54,11 +59,11 @@ MODES = tuple(str(mode) for mode in ActivitySummaryMode)_SYSTEM_PROMPT = """You write an activity summary: what one person works on and cares about in one PostHog project, built only from the input below. Other features read it to rank inbox reports, to pick reviewers and to route work. Write for a reader who needs facts they can act on.The input has these parts:-- Objects and pages: a list that code computed from the last weeks of activity. Each line starts with a ref. An "o" ref is an object. An object they edited shows the number of days with edits, and "created" when they made it. An object they only opened shows the number of days they opened it, and "not theirs" when someone else made it. A "p" ref is the pages of one product. The list ends with the products they work in and the products they only visit.-- Tasks: work the person gave to PostHog AI or the Slack agent. Each line has the day, the tags in brackets and the goal. "(xN)" is the number of runs.+- Objects and pages: a list that code computed from the last weeks of activity. Each line starts with a ref. An "o" ref is an object. An object they edited shows the number of days with edits, and "created" when they made it. An object they only opened shows the number of days they opened it, and "not theirs" when someone else made it. An object they edited and opened shows both counts. A "p" ref is the pages of one product. The list ends with the products they work in and the products they only visit.+- Tasks: work the person gave to PostHog AI or the Slack agent. Each line starts with a "t" ref, then has the day, the tags in brackets and the goal. "(xN)" is the number of runs.- Things they created or changed in PostHog: each line has the day, the action, the type and the name of the object. "(xN)" is the number of changes. "agent" is the reason their coding agent gave for the change.-- What their AI agent looked into over MCP: one line per agent session, with the day, the number of calls and the intents the agent stated, in order. The agent looked these up for the person, and changed nothing. Treat them as the person's interests and open questions. Never write that the person built or changed something because of them.-- Things they opened in PostHog: one line per object, or per product for its pages, with the number of days they opened it and the last day.+- What their AI agent looked into over MCP: one line per agent session. Each line starts with an "m" ref, then has the day, the number of calls and the intents the agent stated, in order. The agent looked these up for the person, and changed nothing. Treat them as the person's interests and open questions. Never write that the person built or changed something because of them.+- Things they opened in PostHog: one line per object, with the number of days they opened it and the last day.- The previous summary, when there is one.The tasks and the lines of changes, MCP sessions and opens cover only the time since the previous summary. Keep what the previous summary says unless the new activity changes it.@@ -69,18 +74,21 @@ How to write:- Summarize a long list by count and topic, such as "12 insights about checkout conversion".- Write plain statements. Do not hedge, and do not write about what the input does not show.- Write about the work, not a job title.+- Settings, integrations, API keys and project configuration are setup. They are never a theme and never in the headline.+- Day counts, change counts and dates in the input are for ranking. Do not repeat them in the headline or the profile. Say how often in words.+- Never write `<token>` or a numeric id.Return JSON:- `headline`: one or two sentences about what they work on and care about in this project.-- `themes`: 3 to 6 threads of work, the strongest first. Give fewer only when the input shows fewer. Each theme has:- - `label`: the topic of the thread in at most 60 characters, such as "Experiment recalculation reliability". Name the topic, not a list of objects.- - `mode`: one of {modes}.+- `themes`: at most 6 threads of work, the strongest first. A thread is work that repeats or a question the person keeps coming back to. Give only the threads that the input shows. One or two themes, or none, is correct for thin input. Do not add a theme to reach a number. Each theme has:+ - `label`: the topic of the thread in at most 60 characters, such as "Experiment recalculation reliability". Name the topic, not a list of objects. Not "Feature flag updates": name what the flags are for, such as "Live stream rollout".+ - `mode`: one of {modes}. `building` is creating or changing objects, including dashboards and alerts. `analyzing` is querying or reading to answer a question, without saving. `monitoring` is opening the same things again and again. `investigating` is finding the cause of a specific problem. `operating` is running day-to-day work, such as tickets. `experimenting` is A/B tests and controlled rollouts.- `strength`: high, medium or low, by how much of the activity is about this thread.- - `refs`: the refs from the objects and pages list that show this thread. Every theme needs at least one ref.-- `modes`: the modes that describe how they work in this project overall, from the same list, the main one first.+ - `refs`: the refs that show this thread. A ref is the evidence for the theme, so cite only lines that are about this thread. Use the "o" refs of its objects, the "t" refs of its tasks and the "m" refs of its MCP sessions. A "p" ref only shows that the person opened the pages of a product, so cite one only when no other ref shows the thread. Every theme needs at least one ref. Leave out a theme that no ref shows.+- `modes`: at most {max_modes} modes that describe how they work in this project overall, from the same list, the main one first. Use only modes that a theme has.- `profile`: markdown, at most {profile_max_chars} characters, with these sections in this order:- - `## Working on`: the threads they build or change, with the objects by name.- - `## Keeps an eye on`: what they open again and again but do not change.+ - `## Working on`: the threads they build or change, with the objects by name. A task or MCP session never goes here.+ - `## Keeps an eye on`: objects they opened on {min_watched_days} or more days and did not edit. Mention product pages at most once, without counts. Leave out this section when there is nothing to name.- `## Recently asked about`: what they asked PostHog AI or the Slack agent, and what their agent looked into over MCP. Only when there are tasks or MCP sessions.- `## Earlier context`: what the previous summary says that the new activity does not repeat. Only when there is a previous summary.Leave out a section that has nothing to say. Do not add other sections, such as one for page visits or for evidence.@@ -88,7 +96,12 @@ Return JSON:def system_prompt(profile_max_chars: int = PROFILE_MAX_CHARS) -> str:- return _SYSTEM_PROMPT.format(profile_max_chars=profile_max_chars, modes=", ".join(MODES))+ return _SYSTEM_PROMPT.format(+ profile_max_chars=profile_max_chars,+ modes=", ".join(MODES),+ max_modes=MAX_MODES,+ min_watched_days=MIN_WATCHED_OPEN_DAYS,+ )# Strict structured output. The normalization below still checks every rule, because a provider@@ -256,7 +269,23 @@ def ref_days(computed: Mapping[str, Any] | None) -> dict[str, str]:"""The last day of each ref in the computed lists."""if not computed:return {}- return {item["ref"]: item["last_at"] for key in ("owned", "watched", "pages") for item in computed.get(key, [])}+ return {item["ref"]: item["last_at"] for key in _REF_LISTS for item in computed.get(key, [])}+++def _page_open_days(computed: Mapping[str, Any] | None) -> dict[str, int]:+ return {item["ref"]: item["open_days"] for item in computed.get("pages", [])} if computed else {}+++def _theme_refs(raw_refs: Any, days: Mapping[str, str], page_open_days: Mapping[str, int]) -> list[str]:+ """The known refs, once each. "p" refs go when another ref exists, and a "p" ref alone needs+ `MIN_WATCHED_OPEN_DAYS` open days, so a page visit cannot carry a theme."""+ refs: list[str] = []+ for raw in raw_refs if isinstance(raw_refs, list) else []:+ if (ref := _clean(raw)) is not None and ref in days and ref not in refs:+ refs.append(ref)+ if other := [ref for ref in refs if not ref.startswith(_PAGES_REF_PREFIX)]:+ return other+ return [ref for ref in refs if page_open_days.get(ref, 0) >= MIN_WATCHED_OPEN_DAYS]def _mode(value: Any) -> str | None:@@ -264,19 +293,17 @@ def _mode(value: Any) -> str | None:return mode if mode in MODES else None-def _themes(value: Any, days: Mapping[str, str]) -> list[dict[str, Any]]:- """At most `MAX_THEMES` themes. A theme keeps only the refs in `days`, and a theme with none is dropped."""+def _themes(value: Any, computed: Mapping[str, Any] | None) -> list[dict[str, Any]]:+ """At most `MAX_THEMES` themes. A theme keeps only the refs that `_theme_refs` keeps, and a theme with none is dropped."""if not isinstance(value, list):return []+ days = ref_days(computed)+ page_open_days = _page_open_days(computed)themes: list[dict[str, Any]] = []for item in value:if not isinstance(item, dict) or (label := _clean(item.get("label"), MAX_LABEL_CHARS)) is None:continue- raw_refs = item.get("refs")- refs: list[str] = []- for raw in raw_refs if isinstance(raw_refs, list) else []:- if (ref := _clean(raw)) is not None and ref in days and ref not in refs:- refs.append(ref)+ refs = _theme_refs(item.get("refs"), days, page_open_days)if not refs:continuestrength = (_clean(item.get("strength")) or "").lower()@@ -297,7 +324,7 @@ def _themes(value: Any, days: Mapping[str, str]) -> list[dict[str, Any]]:def _modes(value: Any) -> list[str]:if not isinstance(value, list):return []- return list(dict.fromkeys(mode for item in value if (mode := _mode(item)) is not None))+ return list(dict.fromkeys(mode for item in value if (mode := _mode(item)) is not None))[:MAX_MODES]def normalize_summary(@@ -334,7 +361,7 @@ def normalize_summary(return {"profile": profile,"headline": cap_line(headline, MAX_HEADLINE_CHARS),- "themes": _themes(parsed.get("themes"), ref_days(computed)),+ "themes": _themes(parsed.get("themes"), computed),"modes": _modes(parsed.get("modes")),"recent_shift": recent_shift,}diff --git a/products/signals/backend/activity_summary/read.py b/products/signals/backend/activity_summary/read.pyindex 52a8b5434d11..95f9b7ba5907 100644--- a/products/signals/backend/activity_summary/read.py+++ b/products/signals/backend/activity_summary/read.py@@ -12,7 +12,7 @@ from django.db import modelsfrom posthog.dataclasses import frozenfrom posthog.models import Team-from products.signals.backend.activity_summary.computed import COMPUTED_SCHEMA_VERSION+from products.signals.backend.activity_summary.computed import READABLE_COMPUTED_SCHEMA_VERSIONSfrom products.signals.backend.activity_summary.config import ActivitySummaryConfig, read_configfrom products.signals.backend.activity_summary.logic import is_stalefrom products.signals.backend.activity_summary.queue import is_team_enrolled_for_read@@ -100,8 +100,11 @@ def _themes(summary: dict[str, Any]) -> tuple[ActivitySummaryTheme, ...]:def _computed(value: Any) -> dict[str, Any] | None:- # A row from before the field existed has none. A row from another schema version has another shape.- return value if isinstance(value, dict) and value.get("schema_version") == COMPUTED_SCHEMA_VERSION else None+ # A row from before the field existed has none. A row from an unknown schema version has another shape.+ # A version 1 row has no task or MCP refs, so it gets empty lists.+ if not isinstance(value, dict) or value.get("schema_version") not in READABLE_COMPUTED_SCHEMA_VERSIONS:+ return None+ return {"tasks": [], "mcp_sessions": [], **value}def _readable_config(team: Team) -> ActivitySummaryConfig | None:diff --git a/products/signals/backend/activity_summary/render.py b/products/signals/backend/activity_summary/render.pyindex 4b613f12b0b5..5b0908785680 100644--- a/products/signals/backend/activity_summary/render.py+++ b/products/signals/backend/activity_summary/render.py@@ -25,7 +25,7 @@ from posthog.dataclasses import frozen# Bump on any code change to the filters, the default caps, the sampling or the rendered layout, so summaries# stay comparable. Limits from the flag payload go into `inputs_used` instead.-RENDER_VERSION = 10+RENDER_VERSION = 11WINDOW_DAYS = 28RECENCY_HALF_LIFE_DAYS = 7@@ -124,6 +124,7 @@ _LETTER = re.compile(r"[A-Za-z]")# A name that is only masks, digits and punctuation after `clean_text` names nothing._MEANINGLESS_NAME = re.compile(r"(?:<token>|<email>|\d|[^\w<>]|_)*")_WHITESPACE = re.compile(r"\s+")+_LINE_REF = re.compile(r"^- [tm]\d+")# Inbox onboarding creates a scout config for each canonical scout, named after its skill.ONBOARDING_CONFIG_SCOPES: frozenset[str] = frozenset({"SignalScoutConfig"})@@ -415,6 +416,14 @@ class _ActivityLine:intent_keys: frozenset[str] = frozenset()+@frozen+class LineRef:+ """The ref of one rendered task or MCP line, such as "t1" or "m2", with the day of the line."""++ ref: str+ last_at: str++@frozenclass RenderedInput:text: str@@ -439,6 +448,9 @@ class RenderedInput:mcp_pool: int = 0# Products whose pages the person opened. They render in the computed block, not here, but count as units.n_page_units: int = 0+ # The refs of the task and MCP lines in `text`, in the order of the lines.+ task_refs: tuple[LineRef, ...] = ()+ mcp_refs: tuple[LineRef, ...] = ()@propertydef units(self) -> int:@@ -1273,6 +1285,28 @@ def enforce_budget(drops[Drop.SECTIONS_BUDGET] += 1+def _with_refs(units: Sequence[Unit], prefix: str, max_chars: int) -> list[Unit]:+ """The units with a ref after the leading "- " of each line, numbered from 1 in the order of the units."""+ return [+ dataclasses.replace(unit, text=cap_line(f"- {prefix}{index} {unit.text.removeprefix('- ')}", max_chars))+ for index, unit in enumerate(units, start=1)+ ]+++def _renumbered(units: Sequence[Unit], prefix: str) -> list[Unit]:+ """The units numbered from 1, with the text they had. A new cut could keep one more word than the budget measured."""+ return [+ dataclasses.replace(unit, text=_LINE_REF.sub(f"- {prefix}{index}", unit.text, count=1))+ for index, unit in enumerate(units, start=1)+ ]+++def _line_refs(units: Sequence[Unit], prefix: str) -> tuple[LineRef, ...]:+ return tuple(+ LineRef(ref=f"{prefix}{index}", last_at=_day(unit.at).isoformat()) for index, unit in enumerate(units, start=1)+ )++def build_input(tasks: Iterable[TaskItem],activity: Iterable[ActivityItem],@@ -1310,13 +1344,16 @@ def build_input(drops[Drop.SAMPLE_CAP] += len(task_pool) - len(chosen_tasks)chosen_mcp = sample_units(mcp_pool, limit=limits.mcp_lines, as_of=as_of, seed=seed)drops[Drop.SAMPLE_CAP] += len(mcp_pool) - len(chosen_mcp)+ # The budget counts the refs too. It drops the oldest lines, so the numbers after it only get shorter.sections = [- (TASKS_HEADER, chosen_tasks),+ (TASKS_HEADER, _with_refs(chosen_tasks, "t", limits.task_line_chars)),(ACTIVITY_HEADER, activity_lines),- (MCP_HEADER, chosen_mcp),+ (MCP_HEADER, _with_refs(chosen_mcp, "m", limits.mcp_line_chars)),(VIEWS_HEADER, view_lines),]enforce_budget(sections, drops, limits.sections_max_chars)+ sections[0] = (TASKS_HEADER, _renumbered(sections[0][1], "t"))+ sections[2] = (MCP_HEADER, _renumbered(sections[2][1], "m"))sections[3] = (VIEWS_HEADER, sorted(sections[3][1], key=lambda unit: unit.text))rendered = [_section(header, units) for header, units in sections]text = "\n\n".join(part for part in rendered if part)@@ -1339,4 +1376,6 @@ def build_input(mcp_chars=len(rendered[2]),mcp_pool=len(mcp_pool),n_page_units=len(pages),+ task_refs=_line_refs(sections[0][1], "t"),+ mcp_refs=_line_refs(sections[2][1], "m"),)diff --git a/products/signals/backend/presentation/activity_summary.py b/products/signals/backend/presentation/activity_summary.pyindex 7a03090c0aad..8ec7680eb617 100644--- a/products/signals/backend/presentation/activity_summary.py+++ b/products/signals/backend/presentation/activity_summary.py@@ -51,8 +51,9 @@ class ActivitySummaryThemeSerializer(serializers.Serializer):)refs = serializers.ListField(child=serializers.CharField(),- help_text="Refs into `computed.owned`, `computed.watched` and `computed.pages` of the same version, "- "such as `o1` or `p2`, that show this thread. A ref is valid only inside one version.",+ help_text="Refs into `computed.owned`, `computed.watched`, `computed.pages`, `computed.tasks` and "+ "`computed.mcp_sessions` of the same version, such as `o1`, `p2`, `t3` or `m1`, that show this thread. "+ "A ref is valid only inside one version.",)last_seen = serializers.CharField(allow_null=True, help_text="The last day of activity on the refs of this thread, as YYYY-MM-DD."@@ -88,6 +89,13 @@ class ActivitySummaryPageVisitsSerializer(serializers.Serializer):last_at = serializers.CharField(help_text="The last day the user opened its pages, as YYYY-MM-DD.")+class ActivitySummaryLineRefSerializer(serializers.Serializer):+ ref = serializers.CharField(+ help_text="The ref that themes cite, such as `t1` for a task or `m1` for an MCP session."+ )+ last_at = serializers.CharField(help_text="The day of the task or MCP session, as YYYY-MM-DD.")++class ActivitySummaryProductSplitSerializer(serializers.Serializer):works_in = serializers.ListField(child=serializers.ChoiceField(choices=ActivitySummaryProduct.choices),@@ -116,6 +124,16 @@ class ActivitySummaryComputedSerializer(serializers.Serializer):task_count = serializers.IntegerField(help_text="The number of tasks the user gave to PostHog AI or the Slack agent.")+ tasks = ActivitySummaryLineRefSerializer(+ many=True,+ help_text="Tasks the user gave to PostHog AI or the Slack agent that the summary input showed, oldest first. "+ "Empty on summaries from before task refs existed.",+ )+ mcp_sessions = ActivitySummaryLineRefSerializer(+ many=True,+ help_text="Sessions of the user's AI agent over MCP that the summary input showed, oldest first. "+ "Empty on summaries from before MCP refs existed.",+ )@extend_schema_serializer(many=False)diff --git a/products/signals/backend/test/test_activity_summary_api.py b/products/signals/backend/test/test_activity_summary_api.pyindex bdab22b6619f..f9634acc1851 100644--- a/products/signals/backend/test/test_activity_summary_api.py+++ b/products/signals/backend/test/test_activity_summary_api.py@@ -26,7 +26,7 @@ SUMMARY = {"recent_shift": "Moved from dashboards to funnels.",}COMPUTED = {- "schema_version": 1,+ "schema_version": 2,"owned": [{"ref": "o1",@@ -41,7 +41,13 @@ COMPUTED = {"watched": [],"pages": [{"ref": "p1", "product": "session_replay", "open_days": 2, "last_at": "2026-10-17"}],"products": {"works_in": ["product_analytics"], "visits": ["session_replay"]},- "task_count": 0,+ "task_count": 1,+ "tasks": [{"ref": "t1", "last_at": "2026-10-16"}],+ "mcp_sessions": [{"ref": "m1", "last_at": "2026-10-18"}],+}+COMPUTED_V1 = {+ **{key: value for key, value in COMPUTED.items() if key not in ("tasks", "mcp_sessions")},+ "schema_version": 1,}@@ -58,7 +64,14 @@ class TestActivitySummaryAPI(APIBaseTest):read_config.start()self.addCleanup(read_config.stop)- def _summary(self, user: User | None = None, *, summary: dict[str, Any] | None = None, version: int = 1) -> None:+ def _summary(+ self,+ user: User | None = None,+ *,+ summary: dict[str, Any] | None = None,+ version: int = 1,+ computed: dict[str, Any] = COMPUTED,+ ) -> None:UserActivitySummary.objects.for_team(self.team.id).create(team=self.team,user=user or self.user,@@ -69,7 +82,7 @@ class TestActivitySummaryAPI(APIBaseTest):prompt_version=PROMPT_VERSION,render_version=RENDER_VERSION,version=version,- computed=COMPUTED,+ computed=computed,)def _versions(self, count: int) -> None:@@ -184,6 +197,23 @@ class TestActivitySummaryAPI(APIBaseTest):assert properties["status"] == expected["status"]assert not any(isinstance(value, str) and "funnel" in value.lower() for value in properties.values())+ @parameterized.expand(+ [+ ("current", COMPUTED, COMPUTED),+ ("version_1", COMPUTED_V1, {**COMPUTED_V1, "tasks": [], "mcp_sessions": []}),+ ("unknown_version", {**COMPUTED, "schema_version": 99}, None),+ ]+ )+ def test_get_reads_the_computed_fields_of_older_schema_versions(+ self, _name: str, computed: dict[str, Any], expected: dict[str, Any] | None+ ) -> None:+ self._summary(computed=computed)++ response = self._get()++ assert response.status_code == 200+ assert response.json()["computed"] == expected+def test_versions_come_newest_first_and_the_limit_is_capped(self) -> None:self.config = ActivitySummaryConfig(enabled=True, organization_ids=(str(self.organization.id),), max_versions=3)self._versions(5)diff --git a/products/signals/backend/test/test_activity_summary_render.py b/products/signals/backend/test/test_activity_summary_render.pyindex 84f802a9ab5e..d1900a72ab8e 100644--- a/products/signals/backend/test/test_activity_summary_render.py+++ b/products/signals/backend/test/test_activity_summary_render.py@@ -33,6 +33,7 @@ from products.signals.backend.activity_summary.render import (VIEWS_HEADER,ActivityItem,Drop,+ LineRef,McpItem,Parent,Product,@@ -43,6 +44,7 @@ from products.signals.backend.activity_summary.render import (activity_units,build_input,burst_cap,+ cap_line,clean_text,mcp_units,sample_units,@@ -628,13 +630,13 @@ def test_build_input_renders_the_four_sections_in_order() -> None:assert rendered.text == "\n".join([TASKS_HEADER,- "- 2026-10-16 [growth] why did signups drop?",+ "- t1 2026-10-16 [growth] why did signups drop?","",ACTIVITY_HEADER,'- 2026-10-18 created Dashboard "Growth overview"',"",MCP_HEADER,- "- 2026-10-17, 1 call: signups by country",+ "- m1 2026-10-17, 1 call: signups by country","",VIEWS_HEADER,'- Dashboard "Growth overview": opened 3 days, last 2026-10-17, edited 1 day',@@ -643,6 +645,10 @@ def test_build_input_renders_the_four_sections_in_order() -> None:)assert (rendered.n_tasks, rendered.n_activity_lines, rendered.n_mcp_lines, rendered.n_view_lines) == (1, 1, 1, 2)assert rendered.units == 5+ assert (rendered.task_refs, rendered.mcp_refs) == (+ (LineRef(ref="t1", last_at="2026-10-16"),),+ (LineRef(ref="m1", last_at="2026-10-17"),),+ )assert rendered.input_chars == len(rendered.text)assert build_input([_task("root cause")], [], as_of=AS_OF, seed=1) is Noneassert build_input([], [], as_of=AS_OF, seed=1, views=[_view("scene", "Settings")]) is None@@ -804,7 +810,7 @@ def test_compute_fields_split_owned_watched_and_visited() -> None:computed = compute_fields(tasks, activity, views).as_json()assert computed == {- "schema_version": 1,+ "schema_version": 2,"owned": [{"ref": "o1",@@ -863,6 +869,8 @@ def test_compute_fields_split_owned_watched_and_visited() -> None:"visits": ["session_replay"],},"task_count": 1,+ "tasks": [],+ "mcp_sessions": [],}@@ -933,6 +941,52 @@ def test_build_input_stays_inside_its_bounds_for_a_very_active_person(_name: strassert rendered.drops[Drop.BURST_CAP] > 0 and rendered.drops[Drop.SAMPLE_CAP] > 0+def test_build_input_numbers_the_task_refs_that_survive_the_budget_from_one() -> None:+ tasks = [+ _task("old", summary="Asked: why did signups drop last month?", days_ago=3),+ _task("new", summary="Asked: why did signups drop?", days_ago=1),+ ]+ expected = f"{TASKS_HEADER}\n- t1 2026-10-18 why did signups drop?"+ # Each of the four sections adds a two-character separator to the budget, empty or not.+ budget = len(expected.replace("t1", "t2")) + 2 * 4++ rendered = build_input(tasks, [], as_of=AS_OF, seed=1, limits=RenderLimits(sections_max_chars=budget))++ assert rendered is not None+ assert rendered.text == expected+ assert rendered.task_refs == (LineRef(ref="t1", last_at="2026-10-18"),)+ assert rendered.drops[Drop.SECTIONS_BUDGET] == 1+++def test_build_input_stays_inside_the_budget_when_a_shorter_ref_would_fit_another_word() -> None:+ goal = f"check the revenue report {'w' * 40}"+ tasks = [+ *[+ _task(topic, summary=f"Asked: why did {topic} change?", days_ago=index + 2)+ for index, topic in enumerate(+ ("signups", "churn", "pricing", "invoices", "retention", "referrals", "trials", "refunds", "upgrades")+ )+ ],+ _task("newest", summary=f"Asked: {goal}", days_ago=1),+ ]+ line_chars = len(f"- t1 2026-10-18 {goal}")+ cut_line = cap_line(f"- t10 2026-10-18 {goal}", line_chars)+ # Each of the four sections adds a two-character separator to the budget, empty or not.+ budget = len(f"{TASKS_HEADER}\n{cut_line}") + 2 * 4++ rendered = build_input(+ tasks,+ [],+ as_of=AS_OF,+ seed=1,+ limits=RenderLimits(task_line_chars=line_chars, task_lines=10, sections_max_chars=budget),+ )++ assert rendered is not None+ assert rendered.task_refs == (LineRef(ref="t1", last_at="2026-10-18"),)+ assert rendered.text == f"{TASKS_HEADER}\n{cut_line.replace('- t10', '- t1', 1)}"++def test_build_input_drops_every_unit_for_a_budget_below_the_section_overhead() -> None:rendered = build_input([_task("why", summary="Asked: why did signups drop?", days_ago=3)],@@ -979,9 +1033,14 @@ COMPUTED: dict[str, Any] = {"not_theirs": True,}],- "pages": [{"ref": "p1", "product": "session_replay", "open_days": 2, "last_at": "2026-10-18"}],+ "pages": [+ {"ref": "p1", "product": "session_replay", "open_days": 2, "last_at": "2026-10-18"},+ {"ref": "p2", "product": "feature_flags", "open_days": 3, "last_at": "2026-10-15"},+ ],"products": {"works_in": ["product_analytics"], "visits": ["session_replay"]},- "task_count": 0,+ "task_count": 1,+ "tasks": [{"ref": "t1", "last_at": "2026-10-17"}],+ "mcp_sessions": [{"ref": "m1", "last_at": "2026-10-19"}],}PREVIOUS_BEFORE_PROFILES = {"summary": "Builds the signup funnel.", "focus_areas": [], "products": []}@@ -1027,7 +1086,8 @@ def test_user_message_lists_the_computed_objects_and_pages_with_their_refs() ->'- o1 insight "Signup funnel": edited on 3 days, opened on 9 days, last 2026-10-18, created\n''- o3 insight "Churn": edited on 1 day, last 2026-10-16, created\n''- o2 dashboard "Growth overview": opened on 4 days, last 2026-10-17, not theirs\n'- "- p1 Session replay pages: opened on 2 days, last 2026-10-18\n\n"+ "- p1 Session replay pages: opened on 2 days, last 2026-10-18\n"+ "- p2 Feature flags pages: opened on 3 days, last 2026-10-15\n\n") in message@@ -1073,9 +1133,21 @@ def _answer(**overrides: Any) -> str:),("a theme keeps only known refs, once each, and its last_seen is the last day of its refs",- _answer(themes=[_theme(refs=["o1", "o7", "p1", "o1", 3])]),+ _answer(themes=[_theme(refs=["o1", "o7", "t1", "o1", 3, "m1", "m9"])]),+ False,+ {"themes": [{**_theme(refs=["o1", "t1", "m1"]), "last_seen": "2026-10-19"}]},+ ),+ (+ "a theme drops its page refs when it has another ref",+ _answer(themes=[_theme(refs=["p2", "t1"])]),+ False,+ {"themes": [{**_theme(refs=["t1"]), "last_seen": "2026-10-17"}]},+ ),+ (+ "a theme with only page refs keeps the pages opened on enough days",+ _answer(themes=[_theme("Flags", refs=["p1", "p2"]), _theme("Replay", refs=["p1"])]),False,- {"themes": [{**_theme(refs=["o1", "p1"]), "last_seen": "2026-10-18"}]},+ {"themes": [{**_theme("Flags", refs=["p2"]), "last_seen": "2026-10-15"}]},),("a theme with no known ref or no label is dropped",@@ -1095,10 +1167,10 @@ def _answer(**overrides: Any) -> str:},),(- "modes keep only known modes, once each",- _answer(modes=["Building", "leading", "building", "monitoring"]),+ "modes keep only known modes, once each, and at most three",+ _answer(modes=["Building", "leading", "building", "monitoring", "operating", "analyzing"]),False,- {"modes": ["building", "monitoring"]},+ {"modes": ["building", "monitoring", "operating"]},),("label and recent_shift are cut at a word boundary inside their caps",diff --git a/products/signals/backend/test/test_activity_summary_update.py b/products/signals/backend/test/test_activity_summary_update.pyindex f84901d80ede..de11a1b2c03b 100644--- a/products/signals/backend/test/test_activity_summary_update.py+++ b/products/signals/backend/test/test_activity_summary_update.py@@ -212,7 +212,7 @@ class TestUpdateActivitySummary(BaseTest):assert off.rendered_input is not None and MCP_HEADER not in off.rendered_inputassert off.inputs_used is not None and "mcp_records" not in off.inputs_usedassert on.status == UpdateStatus.OK and on.rendered_input is not None- section = f"{MCP_HEADER}\n- 2026-10-18, 2 calls: why signups dropped --> signups by country"+ section = f"{MCP_HEADER}\n- m1 2026-10-18, 2 calls: why signups dropped --> signups by country"assert section in on.rendered_inputassert on.inputs_used is not Noneassert {key: value for key, value in on.inputs_used.items() if key.startswith("mcp_")} == {@@ -225,6 +225,8 @@ class TestUpdateActivitySummary(BaseTest):}stored = self._stored()assert stored is not None and stored.input_watermark == newest+ assert stored.computed is not None+ assert stored.computed["mcp_sessions"] == [{"ref": "m1", "last_at": "2026-10-18"}]self._changes(3, days_ago=0.5)with time_machine.travel(NOW + datetime.timedelta(days=2), tick=False):diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 8635e76aef51..62d4da530391 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -55,7 +55,7 @@ export interface ActivitySummaryThemeApi {* @nullable*/strength: string | null- /** Refs into `computed.owned`, `computed.watched` and `computed.pages` of the same version, such as `o1` or `p2`, that show this thread. A ref is valid only inside one version. */+ /** Refs into `computed.owned`, `computed.watched`, `computed.pages`, `computed.tasks` and `computed.mcp_sessions` of the same version, such as `o1`, `p2`, `t3` or `m1`, that show this thread. A ref is valid only inside one version. */refs: string[]/*** The last day of activity on the refs of this thread, as YYYY-MM-DD.@@ -209,6 +209,13 @@ export interface ActivitySummaryProductSplitApi {visits: ActivitySummaryProductEnumApi[]}+export interface ActivitySummaryLineRefApi {+ /** The ref that themes cite, such as `t1` for a task or `m1` for an MCP session. */+ ref: string+ /** The day of the task or MCP session, as YYYY-MM-DD. */+ last_at: string+}+export interface ActivitySummaryComputedApi {/** The version of the shape of these fields. */schema_version: number@@ -222,6 +229,10 @@ export interface ActivitySummaryComputedApi {products: ActivitySummaryProductSplitApi/** The number of tasks the user gave to PostHog AI or the Slack agent. */task_count: number+ /** Tasks the user gave to PostHog AI or the Slack agent that the summary input showed, oldest first. Empty on summaries from before task refs existed. */+ tasks: ActivitySummaryLineRefApi[]+ /** Sessions of the user's AI agent over MCP that the summary input showed, oldest first. Empty on summaries from before MCP refs existed. */+ mcp_sessions: ActivitySummaryLineRefApi[]}export interface ActivitySummaryApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c5dde97114e3..28c2b1fd044a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -5464,7 +5464,7 @@ export namespace Schemas {* @nullable*/strength: string | null;- /** Refs into `computed.owned`, `computed.watched` and `computed.pages` of the same version, such as `o1` or `p2`, that show this thread. A ref is valid only inside one version. */+ /** Refs into `computed.owned`, `computed.watched`, `computed.pages`, `computed.tasks` and `computed.mcp_sessions` of the same version, such as `o1`, `p2`, `t3` or `m1`, that show this thread. A ref is valid only inside one version. */refs: string[];/*** The last day of activity on the refs of this thread, as YYYY-MM-DD.@@ -5618,6 +5618,13 @@ export namespace Schemas {visits: ActivitySummaryProductEnum[];}+ export interface ActivitySummaryLineRef {+ /** The ref that themes cite, such as `t1` for a task or `m1` for an MCP session. */+ ref: string;+ /** The day of the task or MCP session, as YYYY-MM-DD. */+ last_at: string;+ }+export interface ActivitySummaryComputed {/** The version of the shape of these fields. */schema_version: number;@@ -5631,6 +5638,10 @@ export namespace Schemas {products: ActivitySummaryProductSplit;/** The number of tasks the user gave to PostHog AI or the Slack agent. */task_count: number;+ /** Tasks the user gave to PostHog AI or the Slack agent that the summary input showed, oldest first. Empty on summaries from before task refs existed. */+ tasks: ActivitySummaryLineRef[];+ /** Sessions of the user's AI agent over MCP that the summary input showed, oldest first. Empty on summaries from before MCP refs existed. */+ mcp_sessions: ActivitySummaryLineRef[];}export interface ActivitySummary {