Skip to content

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

feat(signals): add activity summary prompt v6 with themes and computed refs (#123033)

posthog[bot]f1b5c17c6aa0
diff --git a/products/signals/backend/activity_summary/logic.py b/products/signals/backend/activity_summary/logic.py
index 84d63b3698d6..d1c830566d32 100644
--- a/products/signals/backend/activity_summary/logic.py
+++ b/products/signals/backend/activity_summary/logic.py
@@ -318,6 +318,7 @@ def update_activity_summary(
as_of=now.date(),
max_completion_tokens=limits.max_completion_tokens,
profile_max_chars=limits.profile_max_chars,
+ computed=computed,
)
cost = cost_usd(outcome.tokens_in, outcome.tokens_out, MODEL_PRICES.get(model))
result = ActivitySummaryUpdate(
diff --git a/products/signals/backend/activity_summary/measure.py b/products/signals/backend/activity_summary/measure.py
index 2b8c6a2096ab..2ced137fb919 100644
--- a/products/signals/backend/activity_summary/measure.py
+++ b/products/signals/backend/activity_summary/measure.py
@@ -15,6 +15,7 @@ from typing import Any
from posthog.dataclasses import frozen
from posthog.models import ActivityLog, Team
+from products.signals.backend.activity_summary.computed import compute_fields
from products.signals.backend.activity_summary.inputs import TASK_ORIGIN_PRODUCTS, user_activity, user_tasks
from products.signals.backend.activity_summary.queue import ActivitySummaryPair
from products.signals.backend.activity_summary.render import (
@@ -269,19 +270,32 @@ def leave_one_out_pair(
pair: ActivitySummaryPair, *, start: datetime.datetime, now: datetime.datetime, min_units: int
) -> list[dict[str, Any]]:
"""One record per variant. With no previous summary, so each summary reflects its input only."""
+ tasks = user_tasks(pair.team_id, pair.user_id, start, now)
+ activity = user_activity(pair.team_id, pair.user_id, start, now)
variants = leave_one_out_inputs(
- user_tasks(pair.team_id, pair.user_id, start, now),
- user_activity(pair.team_id, pair.user_id, start, now),
+ tasks,
+ activity,
as_of=now,
seed=sampling_seed(now.date().isoformat(), pair.team_id, pair.user_id),
)
if Variant.ALL not in variants or variants[Variant.ALL].units < min_units:
return []
client = gateway_client(pair.team_id, pair.user_id, now.date())
+ sources = {
+ Variant.ALL: (tasks, activity),
+ Variant.WITHOUT_TASKS: ([], activity),
+ Variant.WITHOUT_ACTIVITY: (tasks, []),
+ }
records: list[dict[str, Any]] = []
for variant, rendered in variants.items():
+ variant_tasks, variant_activity = sources[variant]
outcome = summarize(
- client, rendered_input=rendered.text, previous_summary=None, model=DEFAULT_MODEL, as_of=now.date()
+ client,
+ rendered_input=rendered.text,
+ previous_summary=None,
+ model=DEFAULT_MODEL,
+ as_of=now.date(),
+ computed=compute_fields(variant_tasks, variant_activity, []).as_json(),
)
records.append(
{
diff --git a/products/signals/backend/activity_summary/prompt.py b/products/signals/backend/activity_summary/prompt.py
index 010f67fbdd7e..c8c842cbd039 100644
--- a/products/signals/backend/activity_summary/prompt.py
+++ b/products/signals/backend/activity_summary/prompt.py
@@ -7,47 +7,79 @@ changes.
import json
import datetime
+from collections.abc import Mapping
from typing import Any
-from products.signals.backend.activity_summary.render import PROFILE_MAX_CHARS, cap_line
+from django.db import models
-PROMPT_VERSION = 5
+from products.signals.backend.activity_summary.render import PRODUCT_LABELS, PROFILE_MAX_CHARS, Product, cap_line
-MAX_FOCUS_AREAS = 6
-MAX_PRODUCTS = 10
+PROMPT_VERSION = 6
+
+MAX_THEMES = 6
# Per-field caps, so one runaway field cannot make the stored summary large. A cut ends at a word boundary.
-MAX_TOPIC_CHARS = 80
-MAX_PRODUCT_CHARS = 40
+MAX_LABEL_CHARS = 60
MAX_RECENT_SHIFT_CHARS = 300
MAX_HEADLINE_CHARS = 600
+# The computed block sits outside the render budget, so it has its own caps. `max_update_cost_usd` counts them.
+COMPUTED_LINE_CHARS = 200
+COMPUTED_MAX_CHARS = 8000
STRENGTHS = ("high", "medium", "low")
DEFAULT_STRENGTH = "low"
# Strings a model writes in place of a JSON null.
_NULL_STRINGS = frozenset({"", "none", "null", "n/a", "na", "nil"})
-_SYSTEM_PROMPT = """You write an activity summary: what one person has been doing in one PostHog project, built only from the activity below. People and their agents read it to understand what this person works on and cares about.
-The input has up to three sections, plus the previous summary if there is one:
-- Tasks: work the person gave to PostHog AI or the Slack agent. Each line has the day, the tags in brackets, and the stated goal.
+class ActivitySummaryMode(models.TextChoices):
+ """How a person works on a theme, or in the project overall."""
+
+ BUILDING = "building"
+ ANALYZING = "analyzing"
+ MONITORING = "monitoring"
+ INVESTIGATING = "investigating"
+ OPERATING = "operating"
+ EXPERIMENTING = "experimenting"
+
+
+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.
- 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.
-- Things they opened in PostHog: one line per object, or per product for its pages. Each line has the number of distinct days they opened it, the last day, the number of days they edited it if any, and "not theirs" when someone else made it. Treat what they open on many days as part of their work, even when they changed nothing.
+- 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.
+- The previous summary, when there is one.
-Each section shows a different side of the same person, and the evidence can overlap. Use your own judgment about what matters. Stay with what the input shows, and say so when something is unclear.
-The activity covers only the time since the previous summary. Keep what the previous summary says unless the new activity changes it.
-Give a line to every thread that has repeated evidence. Use the concrete names that the input uses, such as features, dashboards and experiments.
+The tasks and the lines of changes and opens cover only the time since the previous summary. Keep what the previous summary says unless the new activity changes it.
-Write about the work, not the person: no names, emails, IDs, secrets, or quotes from the input.
+How to write:
+- Be concrete. Name the dashboards, insights, flags, experiments, accounts, features and goals that matter. Use the names that the input uses.
+- Be selective. Write about the work that repeats and the objects the person owns or opens again and again. Leave out one-time visits and setup chores.
+- 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.
Return JSON:
-- `profile`: a one-page markdown profile of the person's work in this project, at most {profile_max_chars} characters. Choose your own sections.
-- `headline`: two or three plain sentences that capture the profile.
-- `focus_areas`: the main threads, up to 6, each with `topic`, `strength` (high, medium or low) and `last_seen` as YYYY-MM-DD.
-- `products`: the PostHog products they use, by name.
+- `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}.
+ - `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.
+- `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.
+ - `## Recently asked about`: what they asked PostHog AI or the Slack agent. Only when there are tasks.
+ - `## 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.
- `recent_shift`: one sentence about what changed since the previous summary, or null when there is no previous summary or no real change."""
def system_prompt(profile_max_chars: int = PROFILE_MAX_CHARS) -> str:
- return _SYSTEM_PROMPT.format(profile_max_chars=profile_max_chars)
+ return _SYSTEM_PROMPT.format(profile_max_chars=profile_max_chars, modes=", ".join(MODES))
# Strict structured output. The normalization below still checks every rule, because a provider
@@ -60,25 +92,26 @@ RESPONSE_FORMAT: Any = {
"schema": {
"type": "object",
"properties": {
- "profile": {"type": "string"},
"headline": {"type": "string"},
- "focus_areas": {
+ "themes": {
"type": "array",
"items": {
"type": "object",
"properties": {
- "topic": {"type": "string"},
+ "label": {"type": "string"},
+ "mode": {"type": "string", "enum": list(MODES)},
"strength": {"type": "string", "enum": list(STRENGTHS)},
- "last_seen": {"type": "string"},
+ "refs": {"type": "array", "items": {"type": "string"}},
},
- "required": ["topic", "strength", "last_seen"],
+ "required": ["label", "mode", "strength", "refs"],
"additionalProperties": False,
},
},
- "products": {"type": "array", "items": {"type": "string"}},
+ "modes": {"type": "array", "items": {"type": "string", "enum": list(MODES)}},
+ "profile": {"type": "string"},
"recent_shift": {"type": ["string", "null"]},
},
- "required": ["profile", "headline", "focus_areas", "products", "recent_shift"],
+ "required": ["headline", "themes", "modes", "profile", "recent_shift"],
"additionalProperties": False,
},
},
@@ -106,30 +139,81 @@ def _profile(value: Any, max_chars: int) -> str | None:
def _previous(previous_summary: dict[str, Any], profile_max_chars: int) -> dict[str, Any]:
# A summary stored before prompt version 3 has a `summary` and no `headline` or `profile`.
# A profile stored under a larger limit gets cut to the current one, so the input stays inside the cost bound.
+ # A ref is valid only inside one update, so the themes go without their refs.
+ themes = previous_summary.get("themes")
return {
"headline": previous_summary.get("headline") or previous_summary.get("summary"),
"profile": _profile(previous_summary.get("profile"), profile_max_chars),
- "focus_areas": previous_summary.get("focus_areas"),
- "products": previous_summary.get("products"),
+ "themes": [
+ {key: theme.get(key) for key in ("label", "mode", "strength", "last_seen")}
+ for theme in themes
+ if isinstance(theme, dict)
+ ]
+ if isinstance(themes, list)
+ else None,
+ "modes": previous_summary.get("modes"),
}
+def _product_label(key: str) -> str:
+ return PRODUCT_LABELS.get(Product(key), key) if key in Product._value2member_map_ else key
+
+
+def computed_lines(computed: Mapping[str, Any] | None) -> str:
+ """The computed lists of `computed.py` with their refs, at most `COMPUTED_MAX_CHARS` long.
+
+ The products come first, then one line per object or product page, so a cut drops the least used ones."""
+ if not computed:
+ return "None"
+ lines: list[str] = []
+ products = computed.get("products", {})
+ for title, key in (("Products they work in", "works_in"), ("Products they only visit", "visits")):
+ if names := [_product_label(product) for product in products.get(key, [])]:
+ lines.append(f"{title}: {', '.join(names)}")
+ for item in computed.get("owned", []):
+ created = ", created" if item["created"] else ""
+ lines.append(
+ f'- {item["ref"]} {item["type"]} "{item["name"]}": edited on {item["edit_days"]} days, last {item["last_at"]}{created}'
+ )
+ for item in computed.get("watched", []):
+ not_theirs = ", not theirs" if item["not_theirs"] else ""
+ lines.append(
+ f'- {item["ref"]} {item["type"]} "{item["name"]}": opened on {item["open_days"]} days, last {item["last_at"]}{not_theirs}'
+ )
+ for item in computed.get("pages", []):
+ lines.append(
+ f"- {item['ref']} {_product_label(item['product'])} pages: opened on {item['open_days']} days, last {item['last_at']}"
+ )
+ kept: list[str] = []
+ chars = 0
+ for line in (cap_line(line, COMPUTED_LINE_CHARS) for line in lines):
+ if chars + len(line) + 1 > COMPUTED_MAX_CHARS:
+ break
+ kept.append(line)
+ chars += len(line) + 1
+ return "\n".join(kept) or "None"
+
+
def user_message(
rendered_input: str,
previous_summary: dict[str, Any] | None,
as_of: datetime.date,
profile_max_chars: int = PROFILE_MAX_CHARS,
+ computed: Mapping[str, Any] | None = None,
) -> str:
- """The user turn: the day the activity ends, the previous summary and the rendered input.
+ """The user turn: the day the activity ends, the previous summary, the computed lists and the rendered input.
- The rendered input comes from `build_input` as is, and the previous summary is this pipeline's
- own stored output, so no other text reaches the model."""
+ The rendered input comes from `build_input` as is, the computed lists from `compute_fields`, and the
+ previous summary is this pipeline's own stored output, so no other text reaches the model."""
previous = (
json.dumps(_previous(previous_summary, profile_max_chars), ensure_ascii=False, sort_keys=True)
if previous_summary
else "None"
)
- return f"Today is {as_of.isoformat()}.\n\nPrevious summary:\n{previous}\n\nRecent activity:\n{rendered_input}"
+ return (
+ f"Today is {as_of.isoformat()}.\n\nPrevious summary:\n{previous}\n\n"
+ f"Objects and pages:\n{computed_lines(computed)}\n\nRecent activity:\n{rendered_input}"
+ )
def _clean(value: Any, max_chars: int | None = None) -> str | None:
@@ -141,54 +225,66 @@ def _clean(value: Any, max_chars: int | None = None) -> str | None:
return cap_line(text, max_chars) if max_chars is not None else text
-def _last_seen(value: Any) -> str | None:
- text = _clean(value)
- if text is None:
- return None
- try:
- return datetime.date.fromisoformat(text).isoformat()
- except ValueError:
- return None
+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, [])}
+
+
+def _mode(value: Any) -> str | None:
+ mode = (_clean(value) or "").lower()
+ return mode if mode in MODES else None
-def _focus_areas(value: Any) -> list[dict[str, str | 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."""
if not isinstance(value, list):
return []
- areas: list[dict[str, str | None]] = []
+ themes: list[dict[str, Any]] = []
for item in value:
- if not isinstance(item, dict) or (topic := _clean(item.get("topic"), MAX_TOPIC_CHARS)) is None:
+ 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)
+ if not refs:
continue
strength = (_clean(item.get("strength")) or "").lower()
- areas.append(
+ themes.append(
{
- "topic": topic,
+ "label": label,
+ "mode": _mode(item.get("mode")),
"strength": strength if strength in STRENGTHS else DEFAULT_STRENGTH,
- "last_seen": _last_seen(item.get("last_seen")),
+ "refs": refs,
+ "last_seen": max(days[ref] for ref in refs),
}
)
- if len(areas) == MAX_FOCUS_AREAS:
+ if len(themes) == MAX_THEMES:
break
- return areas
+ return themes
-def _products(value: Any) -> list[str]:
+def _modes(value: Any) -> list[str]:
if not isinstance(value, list):
return []
- products: list[str] = []
- for item in value:
- product = _clean(item, MAX_PRODUCT_CHARS)
- if product is not None and product not in products:
- products.append(product)
- return products[:MAX_PRODUCTS]
+ return list(dict.fromkeys(mode for item in value if (mode := _mode(item)) is not None))
def normalize_summary(
- content: str | None, *, had_previous_summary: bool, profile_max_chars: int = PROFILE_MAX_CHARS
+ content: str | None,
+ *,
+ had_previous_summary: bool,
+ computed: Mapping[str, Any] | None = None,
+ profile_max_chars: int = PROFILE_MAX_CHARS,
) -> dict[str, Any]:
"""The model's JSON answer under the output rules, or `MalformedSummaryError`.
Only a missing or empty `profile` or `headline` makes an answer malformed. Every other field
- degrades to an empty or null value, so one bad focus area does not cost the row."""
+ degrades to an empty or null value, so one bad theme does not cost the row. A theme ref must be
+ in `computed`, and a theme's `last_seen` is the last day of its refs."""
if not content:
raise MalformedSummaryError("empty response")
try:
@@ -207,13 +303,13 @@ def normalize_summary(
return {
"profile": profile,
"headline": cap_line(headline, MAX_HEADLINE_CHARS),
- "focus_areas": _focus_areas(parsed.get("focus_areas")),
- "products": _products(parsed.get("products")),
+ "themes": _themes(parsed.get("themes"), ref_days(computed)),
+ "modes": _modes(parsed.get("modes")),
"recent_shift": recent_shift,
}
def summary_text(summary: dict[str, Any]) -> str:
- """The text that gets embedded: the headline, then the focus area topics in the model's order."""
- topics = [area["topic"] for area in summary.get("focus_areas", [])]
- return f"{summary['headline']}\nFocus areas: {'; '.join(topics)}" if topics else summary["headline"]
+ """The text that gets embedded: the headline, then the theme labels in the model's order."""
+ labels = [theme["label"] for theme in summary.get("themes", [])]
+ return f"{summary['headline']}\nThemes: {'; '.join(labels)}" if labels else summary["headline"]
diff --git a/products/signals/backend/activity_summary/queue.py b/products/signals/backend/activity_summary/queue.py
index 0391e46aa011..d169174ccde2 100644
--- a/products/signals/backend/activity_summary/queue.py
+++ b/products/signals/backend/activity_summary/queue.py
@@ -41,7 +41,7 @@ from posthog.models import ActivityLog, FileSystemViewLog, Team
from products.signals.backend.activity_summary.config import ActivitySummaryConfig
from products.signals.backend.activity_summary.inputs import TASK_ORIGIN_PRODUCTS
from products.signals.backend.activity_summary.logic import EXCEPTION_ERROR_PREFIX
-from products.signals.backend.activity_summary.prompt import PROMPT_VERSION, system_prompt
+from products.signals.backend.activity_summary.prompt import COMPUTED_MAX_CHARS, PROMPT_VERSION, system_prompt
from products.signals.backend.activity_summary.render import (
DEFAULT_LIMITS,
MAX_LIMITS,
@@ -119,17 +119,22 @@ class DailyUsage:
cost_usd: float
-def max_update_cost_usd(limits: RenderLimits = DEFAULT_LIMITS, model: str = DEFAULT_MODEL) -> float:
- """The most one update can cost: every attempt with the largest input and output."""
+def max_input_chars(limits: RenderLimits = DEFAULT_LIMITS) -> int:
+ """The longest input of one attempt: the system prompt and the user turn."""
# The previous summary is a profile, cut to `limits.profile_max_chars`, plus fields that `MAX_SUMMARY_CHARS` covers.
- input_chars = (
+ return (
limits.sections_max_chars
+ limits.profile_max_chars
+ MAX_SUMMARY_CHARS
+ + COMPUTED_MAX_CHARS
+ len(system_prompt(limits.profile_max_chars))
)
+
+
+def max_update_cost_usd(limits: RenderLimits = DEFAULT_LIMITS, model: str = DEFAULT_MODEL) -> float:
+ """The most one update can cost: every attempt with the largest input and output."""
bound = cost_usd(
- MAX_ATTEMPTS * input_chars // _BOUND_CHARS_PER_TOKEN,
+ MAX_ATTEMPTS * max_input_chars(limits) // _BOUND_CHARS_PER_TOKEN,
MAX_ATTEMPTS * limits.max_completion_tokens,
MODEL_PRICES.get(model),
)
diff --git a/products/signals/backend/activity_summary/read.py b/products/signals/backend/activity_summary/read.py
index 73ff24f57ecd..52a8b5434d11 100644
--- a/products/signals/backend/activity_summary/read.py
+++ b/products/signals/backend/activity_summary/read.py
@@ -12,6 +12,7 @@ from django.db import models
from posthog.dataclasses import frozen
from posthog.models import Team
+from products.signals.backend.activity_summary.computed import COMPUTED_SCHEMA_VERSION
from products.signals.backend.activity_summary.config import ActivitySummaryConfig, read_config
from products.signals.backend.activity_summary.logic import is_stale
from products.signals.backend.activity_summary.queue import is_team_enrolled_for_read
@@ -27,9 +28,12 @@ class ActivitySummaryStatus(models.TextChoices):
@frozen
-class ActivitySummaryFocusArea:
- topic: str
+class ActivitySummaryTheme:
+ label: str
+ # Null on themes from before prompt version 6.
+ mode: str | None
strength: str | None
+ refs: tuple[str, ...]
last_seen: str | None
@@ -38,9 +42,10 @@ class ActivitySummaryView:
status: ActivitySummaryStatus
headline: str | None = None
profile: str | None = None
- focus_areas: tuple[ActivitySummaryFocusArea, ...] = ()
- products: tuple[str, ...] = ()
+ themes: tuple[ActivitySummaryTheme, ...] = ()
+ modes: tuple[str, ...] = ()
recent_shift: str | None = None
+ computed: dict[str, Any] | None = None
generated_at: datetime.datetime | None = None
version: int = 0
prompt_version: int | None = None
@@ -54,9 +59,11 @@ class ActivitySummaryVersionView:
prompt_version: int
headline: str | None
recent_shift: str | None
- focus_areas: tuple[ActivitySummaryFocusArea, ...]
- # Only a read of one version carries the profile, so a list stays small.
+ themes: tuple[ActivitySummaryTheme, ...]
+ modes: tuple[str, ...]
+ # Only a read of one version carries the profile and the computed fields, so a list stays small.
profile: str | None = None
+ computed: dict[str, Any] | None = None
def _text(value: Any) -> str | None:
@@ -68,20 +75,33 @@ def _headline(summary: dict[str, Any]) -> str | None:
return _text(summary.get("headline")) or _text(summary.get("summary"))
-def _focus_areas(value: Any) -> tuple[ActivitySummaryFocusArea, ...]:
- if not isinstance(value, list):
+def _strings(value: Any) -> tuple[str, ...]:
+ return tuple(item for item in value if _text(item) is not None) if isinstance(value, list) else ()
+
+
+def _themes(summary: dict[str, Any]) -> tuple[ActivitySummaryTheme, ...]:
+ # A summary stored before prompt version 6 has `focus_areas` with a `topic`, and no mode or refs.
+ themes = summary.get("themes")
+ items: Any = themes if isinstance(themes, list) else summary.get("focus_areas")
+ label_key = "label" if isinstance(themes, list) else "topic"
+ if not isinstance(items, list):
return ()
return tuple(
- ActivitySummaryFocusArea(
- topic=topic, strength=_text(item.get("strength")), last_seen=_text(item.get("last_seen"))
+ ActivitySummaryTheme(
+ label=label,
+ mode=_text(item.get("mode")),
+ strength=_text(item.get("strength")),
+ refs=_strings(item.get("refs")),
+ last_seen=_text(item.get("last_seen")),
)
- for item in value
- if isinstance(item, dict) and (topic := _text(item.get("topic"))) is not None
+ for item in items
+ if isinstance(item, dict) and (label := _text(item.get(label_key))) is not None
)
-def _products(value: Any) -> tuple[str, ...]:
- return tuple(item for item in value if _text(item) is not None) if isinstance(value, list) else ()
+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
def _readable_config(team: Team) -> ActivitySummaryConfig | None:
@@ -101,9 +121,10 @@ def get_summary(team: Team, user_id: int) -> ActivitySummaryView | None:
status=ActivitySummaryStatus.READY,
headline=_headline(row.summary),
profile=_text(row.summary.get("profile")),
- focus_areas=_focus_areas(row.summary.get("focus_areas")),
- products=_products(row.summary.get("products")),
+ themes=_themes(row.summary),
+ modes=_strings(row.summary.get("modes")),
recent_shift=_text(row.summary.get("recent_shift")),
+ computed=_computed(row.computed),
generated_at=row.generated_at,
version=row.version,
prompt_version=row.prompt_version,
@@ -119,8 +140,10 @@ def _version_view(row: UserActivitySummaryVersion, *, with_profile: bool) -> Act
prompt_version=row.prompt_version,
headline=_headline(summary),
recent_shift=_text(summary.get("recent_shift")),
- focus_areas=_focus_areas(summary.get("focus_areas")),
+ themes=_themes(summary),
+ modes=_strings(summary.get("modes")),
profile=_text(summary.get("profile")) if with_profile else None,
+ computed=_computed(row.computed) if with_profile else None,
)
diff --git a/products/signals/backend/activity_summary/summaries.py b/products/signals/backend/activity_summary/summaries.py
index 2d7b5fe6fabd..0814253df7a2 100644
--- a/products/signals/backend/activity_summary/summaries.py
+++ b/products/signals/backend/activity_summary/summaries.py
@@ -89,11 +89,17 @@ def summarize(
as_of: datetime.date,
max_completion_tokens: int = MAX_COMPLETION_TOKENS,
profile_max_chars: int = PROFILE_MAX_CHARS,
+ computed: dict[str, Any] | None = None,
) -> SummaryOutcome:
- """One summary. Tokens and latency add up over the attempts, because the retry costs too."""
+ """One summary. Tokens and latency add up over the attempts, because the retry costs too.
+
+ `computed` holds the refs the themes can cite. Without it, every theme is dropped."""
messages: list[ChatCompletionMessageParam] = [
{"role": "system", "content": system_prompt(profile_max_chars)},
- {"role": "user", "content": user_message(rendered_input, previous_summary, as_of, profile_max_chars)},
+ {
+ "role": "user",
+ "content": user_message(rendered_input, previous_summary, as_of, profile_max_chars, computed),
+ },
]
tokens_in: int | None = None
tokens_out: int | None = None
@@ -122,6 +128,7 @@ def summarize(
summary = normalize_summary(
choice.message.content if choice is not None else None,
had_previous_summary=previous_summary is not None,
+ computed=computed,
profile_max_chars=profile_max_chars,
)
except MalformedSummaryError as malformed:
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 54e710d4798f..16f02d4c1ee2 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -31,7 +31,7 @@ from posthog.temporal.common.client import async_connect
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.signals.backend.activity_summary import read as activity_summary_read
from products.signals.backend.activity_summary.read import (
- ActivitySummaryFocusArea as ActivitySummaryFocusArea,
+ ActivitySummaryTheme as ActivitySummaryTheme,
ActivitySummaryVersionView as ActivitySummaryVersionView,
ActivitySummaryView as ActivitySummaryView,
)
diff --git a/products/signals/backend/presentation/activity_summary.py b/products/signals/backend/presentation/activity_summary.py
index 430affda35ac..7a03090c0aad 100644
--- a/products/signals/backend/presentation/activity_summary.py
+++ b/products/signals/backend/presentation/activity_summary.py
@@ -1,6 +1,8 @@
from dataclasses import asdict
from typing import Any
+from django.db import models
+
from drf_spectacular.utils import OpenApiResponse, extend_schema_serializer
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
@@ -21,19 +23,98 @@ from posthog.event_usage import report_user_action
from posthog.models import User
from posthog.permissions import APIScopePermission, is_service_auth
+from products.signals.backend.activity_summary.prompt import ActivitySummaryMode
from products.signals.backend.activity_summary.read import DEFAULT_VERSIONS_LIMIT, ActivitySummaryStatus
+from products.signals.backend.activity_summary.render import Product
from products.signals.backend.facade import api as signals_facade
READ_EVENT = "activity summary read"
-class ActivitySummaryFocusAreaSerializer(serializers.Serializer):
- topic = serializers.CharField(help_text="A main thread of the user's work, in the words of their activity.")
+# Built from `Product`, so the API enum cannot drift from the keys that `computed.py` writes.
+ActivitySummaryProduct = models.TextChoices( # type: ignore[call-overload] # the stubs lack the functional API
+ "ActivitySummaryProduct", [(product.name, product.value) for product in Product]
+)
+
+
+class ActivitySummaryThemeSerializer(serializers.Serializer):
+ label = serializers.CharField( # type: ignore[assignment] # DRF Field.label collides with a field named label
+ help_text="A main thread of the user's work, in at most 60 characters."
+ )
+ mode = serializers.ChoiceField(
+ choices=ActivitySummaryMode.choices,
+ allow_null=True,
+ help_text="How the user works on this thread. Null on summaries from before themes had a mode.",
+ )
strength = serializers.CharField(
allow_null=True, help_text="How much of the recent activity is about this thread: high, medium or low."
)
+ 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.",
+ )
last_seen = serializers.CharField(
- allow_null=True, help_text="The last day with activity on this thread, as YYYY-MM-DD."
+ allow_null=True, help_text="The last day of activity on the refs of this thread, as YYYY-MM-DD."
+ )
+
+
+class ActivitySummaryOwnedObjectSerializer(serializers.Serializer):
+ ref = serializers.CharField(help_text="The ref that themes cite, such as `o1`.")
+ type = serializers.CharField(help_text="The object type in snake case, such as `dashboard` or `feature_flag`.")
+ id = serializers.CharField(help_text="The id of the object.")
+ name = serializers.CharField(help_text="The latest name of the object.")
+ edit_days = serializers.IntegerField(help_text="The number of distinct days the user changed the object.")
+ last_at = serializers.CharField(help_text="The last day the user changed the object, as YYYY-MM-DD.")
+ created = serializers.BooleanField(help_text="True when the user created the object in the window.")
+
+
+class ActivitySummaryWatchedObjectSerializer(serializers.Serializer):
+ ref = serializers.CharField(help_text="The ref that themes cite, such as `o21`.")
+ type = serializers.CharField(help_text="The object type, such as `dashboard` or `insight`.")
+ id = serializers.CharField(help_text="The id of the object.")
+ name = serializers.CharField(help_text="The name of the object.")
+ open_days = serializers.IntegerField(help_text="The number of distinct days the user opened the object.")
+ last_at = serializers.CharField(help_text="The last day the user opened the object, as YYYY-MM-DD.")
+ not_theirs = serializers.BooleanField(help_text="True when someone else made the object.")
+
+
+class ActivitySummaryPageVisitsSerializer(serializers.Serializer):
+ ref = serializers.CharField(help_text="The ref that themes cite, such as `p1`.")
+ product = serializers.ChoiceField(
+ choices=ActivitySummaryProduct.choices, help_text="The product whose pages the user opened."
+ )
+ open_days = serializers.IntegerField(help_text="The number of distinct days the user opened its pages.")
+ last_at = serializers.CharField(help_text="The last day the user opened its pages, as YYYY-MM-DD.")
+
+
+class ActivitySummaryProductSplitSerializer(serializers.Serializer):
+ works_in = serializers.ListField(
+ child=serializers.ChoiceField(choices=ActivitySummaryProduct.choices),
+ help_text="Products where the user changed something or tagged a task, the most active first.",
+ )
+ visits = serializers.ListField(
+ child=serializers.ChoiceField(choices=ActivitySummaryProduct.choices),
+ help_text="Products the user only opened, the most opened first.",
+ )
+
+
+class ActivitySummaryComputedSerializer(serializers.Serializer):
+ schema_version = serializers.IntegerField(help_text="The version of the shape of these fields.")
+ owned = ActivitySummaryOwnedObjectSerializer(
+ many=True, help_text="Objects the user created or changed, the most edited first."
+ )
+ watched = ActivitySummaryWatchedObjectSerializer(
+ many=True, help_text="Objects the user opened on 3 or more days, the most opened first."
+ )
+ pages = ActivitySummaryPageVisitsSerializer(
+ many=True, help_text="Products whose pages the user opened, the most opened first."
+ )
+ products = ActivitySummaryProductSplitSerializer(
+ help_text="The products the user works in and the products they only visit."
+ )
+ task_count = serializers.IntegerField(
+ help_text="The number of tasks the user gave to PostHog AI or the Slack agent."
)
@@ -43,18 +124,26 @@ class ActivitySummarySerializer(serializers.Serializer):
choices=ActivitySummaryStatus.choices,
help_text="`ready` when a summary exists. `not_ready` when no summary exists yet, which is normal for new or quiet users.",
)
- headline = serializers.CharField(allow_null=True, help_text="Two or three sentences that capture the profile.")
+ headline = serializers.CharField(
+ allow_null=True, help_text="One or two sentences about what the user works on and cares about in this project."
+ )
profile = serializers.CharField(
allow_null=True,
help_text="A one-page markdown profile of the user's work in this project. Null on summaries from before profiles existed.",
)
- focus_areas = ActivitySummaryFocusAreaSerializer(many=True, help_text="The main threads of the user's work.")
- products = serializers.ListField(
- child=serializers.CharField(), help_text="The PostHog products the user works with, by name."
+ themes = ActivitySummaryThemeSerializer(many=True, help_text="The main threads of the user's work.")
+ modes = serializers.ListField(
+ child=serializers.ChoiceField(choices=ActivitySummaryMode.choices),
+ help_text="How the user works in this project overall, the main mode first.",
)
recent_shift = serializers.CharField(
allow_null=True, help_text="What changed since the version before this one, or null when nothing changed."
)
+ computed = ActivitySummaryComputedSerializer(
+ allow_null=True,
+ help_text="Exact fields that code computed from the user's activity, with ids. The theme refs point into them. "
+ "Null before the first update that computed them.",
+ )
generated_at = serializers.DateTimeField(allow_null=True, help_text="When this version of the summary was written.")
version = serializers.IntegerField(help_text="The number of this version of the summary. 0 before the first.")
prompt_version = serializers.IntegerField(
@@ -67,15 +156,26 @@ class ActivitySummaryVersionSerializer(serializers.Serializer):
version = serializers.IntegerField(help_text="The number of this version. Higher numbers are newer.")
generated_at = serializers.DateTimeField(help_text="When this version was written.")
prompt_version = serializers.IntegerField(help_text="The version of the prompt that wrote this version.")
- headline = serializers.CharField(allow_null=True, help_text="Two or three sentences that capture the profile.")
+ headline = serializers.CharField(
+ allow_null=True, help_text="One or two sentences about what the user works on and cares about in this project."
+ )
recent_shift = serializers.CharField(
allow_null=True, help_text="What changed since the version before this one, or null when nothing changed."
)
- focus_areas = ActivitySummaryFocusAreaSerializer(many=True, help_text="The main threads of the user's work.")
+ themes = ActivitySummaryThemeSerializer(many=True, help_text="The main threads of the user's work.")
+ modes = serializers.ListField(
+ child=serializers.ChoiceField(choices=ActivitySummaryMode.choices),
+ help_text="How the user works in this project overall, the main mode first.",
+ )
profile = serializers.CharField(
allow_null=True,
help_text="The one-page markdown profile. Set only when the request asks for one version with `version`.",
)
+ computed = ActivitySummaryComputedSerializer(
+ allow_null=True,
+ help_text="Exact fields that code computed from the user's activity, with ids. The theme refs point into them. "
+ "Set only when the request asks for one version with `version`.",
+ )
class ActivitySummaryVersionsQuerySerializer(serializers.Serializer):
diff --git a/products/signals/backend/test/test_activity_summary_api.py b/products/signals/backend/test/test_activity_summary_api.py
index c95ab2b57cb9..bdab22b6619f 100644
--- a/products/signals/backend/test/test_activity_summary_api.py
+++ b/products/signals/backend/test/test_activity_summary_api.py
@@ -19,10 +19,30 @@ NOW = datetime.datetime(2026, 10, 19, 12, tzinfo=datetime.UTC)
SUMMARY = {
"profile": "## Funnels\n- Builds the signup funnel.",
"headline": "Builds the signup funnel.",
- "focus_areas": [{"topic": "signup funnel", "strength": "high", "last_seen": "2026-10-18"}],
- "products": ["product_analytics"],
+ "themes": [
+ {"label": "Signup funnel", "mode": "building", "strength": "high", "refs": ["o1"], "last_seen": "2026-10-18"}
+ ],
+ "modes": ["building"],
"recent_shift": "Moved from dashboards to funnels.",
}
+COMPUTED = {
+ "schema_version": 1,
+ "owned": [
+ {
+ "ref": "o1",
+ "type": "insight",
+ "id": "12",
+ "name": "Signup funnel",
+ "edit_days": 2,
+ "last_at": "2026-10-18",
+ "created": True,
+ }
+ ],
+ "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,
+}
@time_machine.travel(NOW, tick=False)
@@ -49,6 +69,7 @@ class TestActivitySummaryAPI(APIBaseTest):
prompt_version=PROMPT_VERSION,
render_version=RENDER_VERSION,
version=version,
+ computed=COMPUTED,
)
def _versions(self, count: int) -> None:
@@ -66,6 +87,7 @@ class TestActivitySummaryAPI(APIBaseTest):
prompt_version=PROMPT_VERSION,
render_version=RENDER_VERSION,
input_watermark=NOW,
+ computed=COMPUTED,
)
def _get(self, path: str = "") -> Any:
@@ -113,17 +135,36 @@ class TestActivitySummaryAPI(APIBaseTest):
@parameterized.expand(
[
- ("no_row", None, {"status": "not_ready", "headline": None, "profile": None}),
+ ("no_row", None, {"status": "not_ready", "headline": None, "profile": None, "computed": None}),
(
"current_row",
SUMMARY,
- {"status": "ready", "headline": "Builds the signup funnel.", "profile": SUMMARY["profile"]},
+ {
+ "status": "ready",
+ "headline": "Builds the signup funnel.",
+ "profile": SUMMARY["profile"],
+ "themes": SUMMARY["themes"],
+ "modes": ["building"],
+ "computed": COMPUTED,
+ },
),
(
"pre_profile_row",
{"summary": "Builds funnels.", "focus_areas": [], "products": []},
{"status": "ready", "headline": "Builds funnels.", "profile": None},
),
+ (
+ "pre_theme_row",
+ {
+ **SUMMARY,
+ "themes": None,
+ "focus_areas": [{"topic": "funnels", "strength": "high", "last_seen": None}],
+ },
+ {
+ "status": "ready",
+ "themes": [{"label": "funnels", "mode": None, "strength": "high", "refs": [], "last_seen": None}],
+ },
+ ),
]
)
def test_get_returns_the_summary_of_the_calling_user(
@@ -151,7 +192,7 @@ class TestActivitySummaryAPI(APIBaseTest):
assert response.status_code == 200
assert [item["version"] for item in response.json()] == [5, 4, 3]
- assert all(item["profile"] is None for item in response.json())
+ assert all(item["profile"] is None and item["computed"] is None for item in response.json())
@parameterized.expand([("existing", 2, 200), ("missing", 9, 404)])
def test_one_version_returns_its_profile(self, _name: str, version: int, status_code: int) -> None:
@@ -168,7 +209,9 @@ class TestActivitySummaryAPI(APIBaseTest):
"prompt_version": PROMPT_VERSION,
"headline": "Version 2",
"recent_shift": SUMMARY["recent_shift"],
- "focus_areas": SUMMARY["focus_areas"],
+ "themes": SUMMARY["themes"],
+ "modes": SUMMARY["modes"],
"profile": SUMMARY["profile"],
+ "computed": COMPUTED,
}
]
diff --git a/products/signals/backend/test/test_activity_summary_measure.py b/products/signals/backend/test/test_activity_summary_measure.py
index dd418c526515..3e93f7fb488d 100644
--- a/products/signals/backend/test/test_activity_summary_measure.py
+++ b/products/signals/backend/test/test_activity_summary_measure.py
@@ -25,8 +25,8 @@ ANSWER = json.dumps(
{
"profile": "## Funnels\n- Builds the signup funnel.",
"headline": "Builds the signup funnel.",
- "focus_areas": [{"topic": "signup funnel", "strength": "high", "last_seen": "2026-10-18"}],
- "products": ["product_analytics"],
+ "themes": [{"label": "Signup funnel", "mode": "building", "strength": "high", "refs": ["o1"]}],
+ "modes": ["building"],
"recent_shift": None,
}
)
diff --git a/products/signals/backend/test/test_activity_summary_render.py b/products/signals/backend/test/test_activity_summary_render.py
index 467fed8fdcfc..92f76cb3ffa1 100644
--- a/products/signals/backend/test/test_activity_summary_render.py
+++ b/products/signals/backend/test/test_activity_summary_render.py
@@ -11,9 +11,8 @@ from parameterized import parameterized
from products.signals.backend.activity_summary.computed import compute_fields
from products.signals.backend.activity_summary.prompt import (
- MAX_PRODUCT_CHARS,
+ MAX_LABEL_CHARS,
MAX_RECENT_SHIFT_CHARS,
- MAX_TOPIC_CHARS,
MalformedSummaryError,
normalize_summary,
summary_text,
@@ -680,10 +679,40 @@ def test_build_input_drops_every_unit_for_a_budget_below_the_section_overhead()
PREVIOUS = {
"profile": "## Funnels\n- Builds the signup funnel.",
"headline": "Builds the signup funnel.",
- "focus_areas": [],
- "products": ["product_analytics"],
+ "themes": [
+ {"label": "Signup funnel", "mode": "building", "strength": "high", "refs": ["o9"], "last_seen": "2026-10-16"}
+ ],
+ "modes": ["building"],
"recent_shift": "Moved from flags to funnels.",
}
+COMPUTED = {
+ "schema_version": 1,
+ "owned": [
+ {
+ "ref": "o1",
+ "type": "insight",
+ "id": "12",
+ "name": "Signup funnel",
+ "edit_days": 3,
+ "last_at": "2026-10-16",
+ "created": True,
+ }
+ ],
+ "watched": [
+ {
+ "ref": "o2",
+ "type": "dashboard",
+ "id": "34",
+ "name": "Growth overview",
+ "open_days": 4,
+ "last_at": "2026-10-17",
+ "not_theirs": True,
+ }
+ ],
+ "pages": [{"ref": "p1", "product": "session_replay", "open_days": 2, "last_at": "2026-10-18"}],
+ "products": {"works_in": ["product_analytics"], "visits": ["session_replay"]},
+ "task_count": 0,
+}
PREVIOUS_BEFORE_PROFILES = {"summary": "Builds the signup funnel.", "focus_areas": [], "products": []}
@@ -692,7 +721,7 @@ PREVIOUS_BEFORE_PROFILES = {"summary": "Builds the signup funnel.", "focus_areas
(
"with a previous summary",
PREVIOUS,
- ["## Funnels\\n- Builds the signup funnel.", "Builds the signup funnel."],
+ ["## Funnels\\n- Builds the signup funnel.", "Builds the signup funnel.", '"label": "Signup funnel"'],
),
("with a summary from before profiles", PREVIOUS_BEFORE_PROFILES, ['"headline": "Builds the signup funnel."']),
("cold start", None, ["Previous summary:\nNone"]),
@@ -703,9 +732,32 @@ def test_user_message_sends_only_the_rendered_input_and_the_previous_summary(
) -> None:
message = user_message("- 2026-10-17 Build a funnel", previous, datetime.date(2026, 10, 18))
assert message.startswith("Today is 2026-10-18.")
- assert message.endswith("Recent activity:\n- 2026-10-17 Build a funnel")
+ assert message.endswith("Objects and pages:\nNone\n\nRecent activity:\n- 2026-10-17 Build a funnel")
assert all(text in message for text in expected)
assert "Moved from flags" not in message
+ assert "o9" not in message
+
+
+def test_user_message_lists_the_computed_objects_and_pages_with_their_refs() -> None:
+ message = user_message("- a line", None, datetime.date(2026, 10, 18), computed=COMPUTED)
+ assert (
+ "Objects and pages:\n"
+ "Products they work in: Product analytics\n"
+ "Products they only visit: Session replay\n"
+ '- o1 insight "Signup funnel": edited on 3 days, 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"
+ ) in message
+
+
+def _theme(label: str | None = "Signup funnel", refs: list[Any] | None = None, **overrides: Any) -> dict[str, Any]:
+ return {
+ "label": label,
+ "mode": "building",
+ "strength": "high",
+ "refs": ["o1"] if refs is None else refs,
+ **overrides,
+ }
def _answer(**overrides: Any) -> str:
@@ -713,8 +765,8 @@ def _answer(**overrides: Any) -> str:
{
"profile": "## Funnels\n- Builds the signup funnel.",
"headline": "Builds the signup funnel.",
- "focus_areas": [{"topic": "signup funnel", "strength": "high", "last_seen": "2026-10-17"}],
- "products": ["product_analytics"],
+ "themes": [_theme()],
+ "modes": ["building"],
"recent_shift": "Moved from flags to funnels.",
**overrides,
}
@@ -739,47 +791,54 @@ def _answer(**overrides: Any) -> str:
{"profile": "## Funnels\n" + " ".join(["word"] * 1197) + "…"},
),
(
- "at most six focus areas, an unknown strength is low and a bad date is null",
- _answer(focus_areas=[{"topic": f"t{i}", "strength": "huge", "last_seen": "soon"} for i in range(8)]),
+ "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])]),
False,
- {"focus_areas": [{"topic": f"t{i}", "strength": "low", "last_seen": None} for i in range(6)]},
+ {"themes": [{**_theme(refs=["o1", "p1"]), "last_seen": "2026-10-18"}]},
),
(
- "a focus area without a topic is dropped",
- _answer(focus_areas=[{"strength": "high"}]),
+ "a theme with no known ref or no label is dropped",
+ _answer(themes=[_theme("Unknown", refs=["o7"]), _theme("No refs", refs=[]), _theme(None)]),
False,
- {"focus_areas": []},
+ {"themes": []},
),
(
- "topic, product and recent_shift are cut at a word boundary inside their caps",
- _answer(
- focus_areas=[{"topic": "adoption " * 50, "strength": "high", "last_seen": "2026-10-17"}],
- products=["analytics " * 50],
- recent_shift="shift " * 400,
- ),
+ "at most six themes, an unknown mode is null and an unknown strength is low",
+ _answer(themes=[_theme(f"t{i}", mode="leading", strength="huge") for i in range(8)]),
+ False,
+ {
+ "themes": [
+ {"label": f"t{i}", "mode": None, "strength": "low", "refs": ["o1"], "last_seen": "2026-10-16"}
+ for i in range(6)
+ ]
+ },
+ ),
+ (
+ "modes keep only known modes, once each",
+ _answer(modes=["Building", "leading", "building", "monitoring"]),
+ False,
+ {"modes": ["building", "monitoring"]},
+ ),
+ (
+ "label and recent_shift are cut at a word boundary inside their caps",
+ _answer(themes=[_theme("adoption " * 50)], recent_shift="shift " * 400),
True,
{
- "focus_areas": [
+ "themes": [
{
- "topic": " ".join(["adoption"] * ((MAX_TOPIC_CHARS - 1) // 9)) + "…",
- "strength": "high",
- "last_seen": "2026-10-17",
+ **_theme(" ".join(["adoption"] * ((MAX_LABEL_CHARS - 1) // 9)) + "…"),
+ "last_seen": "2026-10-16",
}
],
- "products": [" ".join(["analytics"] * ((MAX_PRODUCT_CHARS - 1) // 10)) + "…"],
"recent_shift": " ".join(["shift"] * ((MAX_RECENT_SHIFT_CHARS - 1) // 6)) + "…",
},
),
- (
- "one long word is cut and marked",
- _answer(products=["p" * 500]),
- False,
- {"products": ["p" * (MAX_PRODUCT_CHARS - 1) + "…"]},
- ),
]
)
def test_normalize_summary(_name: str, content: str, had_previous: bool, expected: dict[str, Any]) -> None:
- assert normalize_summary(content, had_previous_summary=had_previous).items() >= expected.items()
+ summary = normalize_summary(content, had_previous_summary=had_previous, computed=COMPUTED)
+ assert summary.items() >= expected.items()
+ assert "products" not in summary
@parameterized.expand(
@@ -796,19 +855,13 @@ def test_normalize_summary_rejects_a_malformed_answer(_name: str, content: str |
normalize_summary(content, had_previous_summary=False)
-def test_summary_text_is_deterministic_and_keeps_the_focus_order() -> None:
+def test_summary_text_is_the_headline_and_the_theme_labels_in_order() -> None:
summary = normalize_summary(
- _answer(
- focus_areas=[
- {"topic": "b", "strength": "high", "last_seen": ""},
- {"topic": "a", "strength": "low", "last_seen": ""},
- ]
- ),
- had_previous_summary=False,
+ _answer(themes=[_theme("b"), _theme("a", refs=["o2"])]), had_previous_summary=False, computed=COMPUTED
)
reloaded = json.loads(json.dumps(summary, sort_keys=True))
- assert summary_text(summary) == summary_text(reloaded) == "Builds the signup funnel.\nFocus areas: b; a"
- assert summary_text({**summary, "focus_areas": []}) == "Builds the signup funnel."
+ assert summary_text(summary) == summary_text(reloaded) == "Builds the signup funnel.\nThemes: b; a"
+ assert summary_text({**summary, "themes": []}) == "Builds the signup funnel."
_PRICES = SummaryPrices(input_price_per_million_tokens=0.1, output_price_per_million_tokens=0.5)
@@ -939,6 +992,6 @@ def test_summarize_cuts_a_previous_profile_to_a_lowered_limit() -> None:
)
user_turn = llm.requests[0]["messages"][1]["content"]
- previous = json.loads(user_turn.split("Previous summary:\n", 1)[1].split("\n\nRecent activity:", 1)[0])
+ previous = json.loads(user_turn.split("Previous summary:\n", 1)[1].split("\n\nObjects and pages:", 1)[0])
assert len(previous["profile"]) <= 500
assert previous["profile"].startswith("## Funnels\nBuilds the signup funnel.")
diff --git a/products/signals/backend/test/test_activity_summary_tick.py b/products/signals/backend/test/test_activity_summary_tick.py
index feb1a485d17a..860102c96cdd 100644
--- a/products/signals/backend/test/test_activity_summary_tick.py
+++ b/products/signals/backend/test/test_activity_summary_tick.py
@@ -25,8 +25,17 @@ from products.signals.backend.activity_summary import (
schedule as tick_schedule,
tick,
)
+from products.signals.backend.activity_summary.computed import MAX_OWNED, MAX_WATCHED
from products.signals.backend.activity_summary.config import ActivitySummaryConfig, parse_config
-from products.signals.backend.activity_summary.prompt import PROMPT_VERSION
+from products.signals.backend.activity_summary.prompt import (
+ MAX_HEADLINE_CHARS,
+ MAX_LABEL_CHARS,
+ MAX_THEMES,
+ MODES,
+ PROMPT_VERSION,
+ system_prompt,
+ user_message,
+)
from products.signals.backend.activity_summary.queue import (
ActivitySummaryPair,
ActivitySummaryTierStats,
@@ -37,12 +46,19 @@ from products.signals.backend.activity_summary.queue import (
feed_queue,
is_team_enrolled_for_generation,
is_team_enrolled_for_read,
+ max_input_chars,
max_update_cost_usd,
organization_rollout_bucket,
seed_queue,
select_pairs,
)
-from products.signals.backend.activity_summary.render import DEFAULT_LIMITS, MAX_LIMITS, RENDER_VERSION, RenderLimits
+from products.signals.backend.activity_summary.render import (
+ DEFAULT_LIMITS,
+ MAX_LIMITS,
+ RENDER_VERSION,
+ Product,
+ RenderLimits,
+)
from products.signals.backend.activity_summary.schedule import (
ACTIVITY_SUMMARY_TICK_SCHEDULE_ID,
create_activity_summary_tick_schedule,
@@ -73,8 +89,8 @@ ANSWER = json.dumps(
{
"profile": "## Funnels\n- Builds the signup funnel.",
"headline": "Builds the signup funnel.",
- "focus_areas": [{"topic": "signup funnel", "strength": "high", "last_seen": "2026-10-18"}],
- "products": ["product_analytics"],
+ "themes": [{"label": "Signup funnel", "mode": "building", "strength": "high", "refs": ["o1"]}],
+ "modes": ["building"],
"recent_shift": None,
}
)
@@ -745,7 +761,7 @@ class TestActivitySummaryQueue(BaseTest):
assert (result.status, result.called_model, result.new_summary) == ("ok", True, True)
assert emit.call_args.kwargs["document_id"] == f"{self.user.id}:2026-10-19"
- assert emit.call_args.kwargs["content"] == "Builds the signup funnel.\nFocus areas: signup funnel"
+ assert emit.call_args.kwargs["content"] == "Builds the signup funnel.\nThemes: Signup funnel"
event = capture.call_args.kwargs
assert event["event"] == "activity summary generated"
assert "signup funnel" not in json.dumps(event["properties"]).lower()
@@ -899,3 +915,49 @@ def test_a_payload_recorded_before_limits_existed_decodes_with_the_default_limit
assert decoded == build()
assert decoded.limits == DEFAULT_LIMITS
+
+
+def _longest_computed() -> dict[str, Any]:
+ long_text = "x" * 500
+ products = [str(product) for product in Product]
+ owned = {"type": long_text, "id": long_text, "name": long_text, "edit_days": 28, "last_at": "2026-10-18"}
+ watched = {"type": long_text, "id": long_text, "name": long_text, "open_days": 28, "last_at": "2026-10-18"}
+ return {
+ "schema_version": 1,
+ "owned": [{"ref": f"o{index}", **owned, "created": True} for index in range(1, MAX_OWNED + 1)],
+ "watched": [{"ref": f"o{index}", **watched, "not_theirs": True} for index in range(1, MAX_WATCHED + 1)],
+ "pages": [
+ {"ref": f"p{index}", "product": product, "open_days": 28, "last_at": "2026-10-18"}
+ for index, product in enumerate(products, start=1)
+ ],
+ "products": {"works_in": products, "visits": products},
+ "task_count": 200,
+ }
+
+
+ [
+ ("default limits", DEFAULT_LIMITS),
+ ("reduced limits", RenderLimits(sections_max_chars=500, profile_max_chars=500)),
+ ("largest limits", MAX_LIMITS),
+ ]
+)
+def test_the_cost_bound_covers_the_longest_input(_name: str, limits: RenderLimits) -> None:
+ previous = {
+ "headline": "h" * MAX_HEADLINE_CHARS,
+ "profile": "p" * limits.profile_max_chars,
+ "themes": [
+ {"label": "l" * MAX_LABEL_CHARS, "mode": "investigating", "strength": "medium", "last_seen": "2026-10-18"}
+ ]
+ * MAX_THEMES,
+ "modes": list(MODES),
+ }
+ message = user_message(
+ "r" * limits.sections_max_chars,
+ previous,
+ datetime.date(2026, 10, 18),
+ limits.profile_max_chars,
+ _longest_computed(),
+ )
+
+ assert len(system_prompt(limits.profile_max_chars)) + len(message) <= max_input_chars(limits)
diff --git a/products/signals/backend/test/test_activity_summary_update.py b/products/signals/backend/test/test_activity_summary_update.py
index 42e11126ae9a..96d357a7c03a 100644
--- a/products/signals/backend/test/test_activity_summary_update.py
+++ b/products/signals/backend/test/test_activity_summary_update.py
@@ -26,8 +26,8 @@ ANSWER = json.dumps(
{
"profile": "## Funnels\n- Builds the signup funnel.",
"headline": "Builds the signup funnel.",
- "focus_areas": [{"topic": "signup funnel", "strength": "high", "last_seen": "2026-10-18"}],
- "products": ["product_analytics"],
+ "themes": [{"label": "Signup funnel", "mode": "building", "strength": "high", "refs": ["o1"]}],
+ "modes": ["building"],
"recent_shift": None,
}
)
@@ -83,7 +83,7 @@ class TestUpdateActivitySummary(BaseTest):
stored = self._stored()
assert stored is not None
assert stored.status == UserActivitySummary.Status.OK
- assert stored.summary_text == "Builds the signup funnel.\nFocus areas: signup funnel"
+ assert stored.summary_text == "Builds the signup funnel.\nThemes: Signup funnel"
assert stored.input_watermark == NOW - datetime.timedelta(days=1)
assert stored.next_eligible_at == NOW + datetime.timedelta(days=1)
assert (stored.tokens_in, stored.tokens_out) == (100, 20)
@@ -212,7 +212,7 @@ class TestUpdateActivitySummary(BaseTest):
assert (result.status, result.rebuilt) == (UpdateStatus.OK, rebuilt)
sent = json.dumps(llm.requests[0]["messages"])
assert ("Old stored summary." not in sent) == rebuilt
- assert ("Old dashboard" in sent) == rebuilt
+ assert ("Old dashboard" in sent.split("Recent activity")[1]) == rebuilt
stored = self._stored()
assert stored is not None
assert (stored.prompt_version, stored.render_version) == (PROMPT_VERSION, RENDER_VERSION)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index adc9a1f59643..fa77dfddfcfd 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -19,21 +19,211 @@ export const ActivitySummaryStatusEnumApi = {
NotReady: 'not_ready',
} as const
-export interface ActivitySummaryFocusAreaApi {
- /** A main thread of the user's work, in the words of their activity. */
- topic: string
+/**
+ * * `building` - Building
+ * * `analyzing` - Analyzing
+ * * `monitoring` - Monitoring
+ * * `investigating` - Investigating
+ * * `operating` - Operating
+ * * `experimenting` - Experimenting
+ */
+export type ActivitySummaryModeEnumApi = (typeof ActivitySummaryModeEnumApi)[keyof typeof ActivitySummaryModeEnumApi]
+
+export const ActivitySummaryModeEnumApi = {
+ Building: 'building',
+ Analyzing: 'analyzing',
+ Monitoring: 'monitoring',
+ Investigating: 'investigating',
+ Operating: 'operating',
+ Experimenting: 'experimenting',
+} as const
+
+export interface ActivitySummaryThemeApi {
+ /** A main thread of the user's work, in at most 60 characters. */
+ label: string
+ /** How the user works on this thread. Null on summaries from before themes had a mode.
+ *
+ * * `building` - Building
+ * * `analyzing` - Analyzing
+ * * `monitoring` - Monitoring
+ * * `investigating` - Investigating
+ * * `operating` - Operating
+ * * `experimenting` - Experimenting */
+ mode: ActivitySummaryModeEnumApi | null
/**
* How much of the recent activity is about this thread: high, medium or low.
* @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: string[]
/**
- * The last day with activity on this thread, as YYYY-MM-DD.
+ * The last day of activity on the refs of this thread, as YYYY-MM-DD.
* @nullable
*/
last_seen: string | null
}
+export interface ActivitySummaryOwnedObjectApi {
+ /** The ref that themes cite, such as `o1`. */
+ ref: string
+ /** The object type in snake case, such as `dashboard` or `feature_flag`. */
+ type: string
+ /** The id of the object. */
+ id: string
+ /** The latest name of the object. */
+ name: string
+ /** The number of distinct days the user changed the object. */
+ edit_days: number
+ /** The last day the user changed the object, as YYYY-MM-DD. */
+ last_at: string
+ /** True when the user created the object in the window. */
+ created: boolean
+}
+
+export interface ActivitySummaryWatchedObjectApi {
+ /** The ref that themes cite, such as `o21`. */
+ ref: string
+ /** The object type, such as `dashboard` or `insight`. */
+ type: string
+ /** The id of the object. */
+ id: string
+ /** The name of the object. */
+ name: string
+ /** The number of distinct days the user opened the object. */
+ open_days: number
+ /** The last day the user opened the object, as YYYY-MM-DD. */
+ last_at: string
+ /** True when someone else made the object. */
+ not_theirs: boolean
+}
+
+/**
+ * * `product_analytics` - Product Analytics
+ * * `dashboards` - Dashboards
+ * * `web_analytics` - Web Analytics
+ * * `session_replay` - Session Replay
+ * * `heatmaps` - Heatmaps
+ * * `error_tracking` - Error Tracking
+ * * `experiments` - Experiments
+ * * `feature_flags` - Feature Flags
+ * * `early_access_features` - Early Access Features
+ * * `surveys` - Surveys
+ * * `product_tours` - Product Tours
+ * * `notebooks` - Notebooks
+ * * `cohorts` - Cohorts
+ * * `persons` - Persons
+ * * `data_management` - Data Management
+ * * `data_warehouse` - Data Warehouse
+ * * `data_pipelines` - Data Pipelines
+ * * `workflows` - Workflows
+ * * `ai_observability` - Ai Observability
+ * * `mcp_analytics` - Mcp Analytics
+ * * `logs` - Logs
+ * * `tracing` - Tracing
+ * * `endpoints` - Endpoints
+ * * `revenue_analytics` - Revenue Analytics
+ * * `customer_analytics` - Customer Analytics
+ * * `inbox` - Inbox
+ * * `canvases` - Canvases
+ * * `support` - Support
+ */
+export type ActivitySummaryProductEnumApi =
+ (typeof ActivitySummaryProductEnumApi)[keyof typeof ActivitySummaryProductEnumApi]
+
+export const ActivitySummaryProductEnumApi = {
+ ProductAnalytics: 'product_analytics',
+ Dashboards: 'dashboards',
+ WebAnalytics: 'web_analytics',
+ SessionReplay: 'session_replay',
+ Heatmaps: 'heatmaps',
+ ErrorTracking: 'error_tracking',
+ Experiments: 'experiments',
+ FeatureFlags: 'feature_flags',
+ EarlyAccessFeatures: 'early_access_features',
+ Surveys: 'surveys',
+ ProductTours: 'product_tours',
+ Notebooks: 'notebooks',
+ Cohorts: 'cohorts',
+ Persons: 'persons',
+ DataManagement: 'data_management',
+ DataWarehouse: 'data_warehouse',
+ DataPipelines: 'data_pipelines',
+ Workflows: 'workflows',
+ AiObservability: 'ai_observability',
+ McpAnalytics: 'mcp_analytics',
+ Logs: 'logs',
+ Tracing: 'tracing',
+ Endpoints: 'endpoints',
+ RevenueAnalytics: 'revenue_analytics',
+ CustomerAnalytics: 'customer_analytics',
+ Inbox: 'inbox',
+ Canvases: 'canvases',
+ Support: 'support',
+} as const
+
+export interface ActivitySummaryPageVisitsApi {
+ /** The ref that themes cite, such as `p1`. */
+ ref: string
+ /** The product whose pages the user opened.
+ *
+ * * `product_analytics` - Product Analytics
+ * * `dashboards` - Dashboards
+ * * `web_analytics` - Web Analytics
+ * * `session_replay` - Session Replay
+ * * `heatmaps` - Heatmaps
+ * * `error_tracking` - Error Tracking
+ * * `experiments` - Experiments
+ * * `feature_flags` - Feature Flags
+ * * `early_access_features` - Early Access Features
+ * * `surveys` - Surveys
+ * * `product_tours` - Product Tours
+ * * `notebooks` - Notebooks
+ * * `cohorts` - Cohorts
+ * * `persons` - Persons
+ * * `data_management` - Data Management
+ * * `data_warehouse` - Data Warehouse
+ * * `data_pipelines` - Data Pipelines
+ * * `workflows` - Workflows
+ * * `ai_observability` - Ai Observability
+ * * `mcp_analytics` - Mcp Analytics
+ * * `logs` - Logs
+ * * `tracing` - Tracing
+ * * `endpoints` - Endpoints
+ * * `revenue_analytics` - Revenue Analytics
+ * * `customer_analytics` - Customer Analytics
+ * * `inbox` - Inbox
+ * * `canvases` - Canvases
+ * * `support` - Support */
+ product: ActivitySummaryProductEnumApi
+ /** The number of distinct days the user opened its pages. */
+ open_days: number
+ /** The last day the user opened its pages, as YYYY-MM-DD. */
+ last_at: string
+}
+
+export interface ActivitySummaryProductSplitApi {
+ /** Products where the user changed something or tagged a task, the most active first. */
+ works_in: ActivitySummaryProductEnumApi[]
+ /** Products the user only opened, the most opened first. */
+ visits: ActivitySummaryProductEnumApi[]
+}
+
+export interface ActivitySummaryComputedApi {
+ /** The version of the shape of these fields. */
+ schema_version: number
+ /** Objects the user created or changed, the most edited first. */
+ owned: ActivitySummaryOwnedObjectApi[]
+ /** Objects the user opened on 3 or more days, the most opened first. */
+ watched: ActivitySummaryWatchedObjectApi[]
+ /** Products whose pages the user opened, the most opened first. */
+ pages: ActivitySummaryPageVisitsApi[]
+ /** The products the user works in and the products they only visit. */
+ products: ActivitySummaryProductSplitApi
+ /** The number of tasks the user gave to PostHog AI or the Slack agent. */
+ task_count: number
+}
+
export interface ActivitySummaryApi {
/** `ready` when a summary exists. `not_ready` when no summary exists yet, which is normal for new or quiet users.
*
@@ -41,7 +231,7 @@ export interface ActivitySummaryApi {
* * `not_ready` - Not Ready */
status: ActivitySummaryStatusEnumApi
/**
- * Two or three sentences that capture the profile.
+ * One or two sentences about what the user works on and cares about in this project.
* @nullable
*/
headline: string | null
@@ -51,14 +241,16 @@ export interface ActivitySummaryApi {
*/
profile: string | null
/** The main threads of the user's work. */
- focus_areas: ActivitySummaryFocusAreaApi[]
- /** The PostHog products the user works with, by name. */
- products: string[]
+ themes: ActivitySummaryThemeApi[]
+ /** How the user works in this project overall, the main mode first. */
+ modes: ActivitySummaryModeEnumApi[]
/**
* What changed since the version before this one, or null when nothing changed.
* @nullable
*/
recent_shift: string | null
+ /** Exact fields that code computed from the user's activity, with ids. The theme refs point into them. Null before the first update that computed them. */
+ computed: ActivitySummaryComputedApi | null
/**
* When this version of the summary was written.
* @nullable
@@ -83,7 +275,7 @@ export interface ActivitySummaryVersionApi {
/** The version of the prompt that wrote this version. */
prompt_version: number
/**
- * Two or three sentences that capture the profile.
+ * One or two sentences about what the user works on and cares about in this project.
* @nullable
*/
headline: string | null
@@ -93,12 +285,16 @@ export interface ActivitySummaryVersionApi {
*/
recent_shift: string | null
/** The main threads of the user's work. */
- focus_areas: ActivitySummaryFocusAreaApi[]
+ themes: ActivitySummaryThemeApi[]
+ /** How the user works in this project overall, the main mode first. */
+ modes: ActivitySummaryModeEnumApi[]
/**
* The one-page markdown profile. Set only when the request asks for one version with `version`.
* @nullable
*/
profile: string | null
+ /** Exact fields that code computed from the user's activity, with ids. The theme refs point into them. Set only when the request asks for one version with `version`. */
+ computed: ActivitySummaryComputedApi | null
}
/**
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 9bfe55952748..3e6f7da482aa 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -13,12 +13,15 @@ tools:
title: Get your activity summary
description: >
Get a summary of what the current user has been working on in this project: a one-page markdown profile, a
- short headline, the main focus areas with the day each was last seen, and the PostHog products they use. It
- is built only from the user's own recent activity in PostHog, such as tasks they gave to PostHog AI and
- things they created, changed or opened. It updates at most once a day, when there is enough new activity.
- Use it to tailor answers and suggestions to what this person works on. `status: not_ready` means no summary
- exists yet, which is normal for new or quiet users. `stale: true` means a newer version will replace it
- soon. A 404 means activity summaries are not available for this project.
+ short headline, 3 to 6 themes with a mode and the day each was last seen, and their overall work modes. The
+ `computed` fields list, with ids, the objects they created or changed (`owned`), the objects they open again
+ and again (`watched`), the product pages they open, the products they work in or only visit, and their task
+ count. Each theme's `refs` point at entries in `computed`. It is built only from the user's own recent
+ activity in PostHog, such as tasks they gave to PostHog AI and things they created, changed or opened. It
+ updates at most once a day, when there is enough new activity. Use it to tailor answers and suggestions to
+ what this person works on. `status: not_ready` means no summary exists yet, which is normal for new or quiet
+ users. `stale: true` means a newer version will replace it soon. A 404 means activity summaries are not
+ available for this project.
feature_flag: activity-summary
activity-summary-versions-list:
operation: signals_activity_summary_versions_retrieve
@@ -26,10 +29,11 @@ tools:
title: List your activity summary versions
description: >
List earlier versions of the current user's activity summary in this project, newest first, to see how their
- focus changed over time. Each version has a headline, the focus areas and `recent_shift`, which says what
- changed since the version before it. The list leaves out the profile to stay small. Pass `version` to get
- one version with its full profile. A 404 means activity summaries are not available for this project, or
- that the requested version does not exist.
+ focus changed over time. Each version has a headline, the themes, the modes and `recent_shift`, which says
+ what changed since the version before it. The list leaves out the profile and the `computed` fields to stay
+ small. Pass `version` to get one version with its full profile and the `computed` fields that its theme refs
+ point at. A 404 means activity summaries are not available for this project, or that the requested version
+ does not exist.
feature_flag: activity-summary
inbox-ranking-outcomes-list:
operation: signals_reports_ranking_outcomes_list
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 19968e12818b..e7ffbcf9d6a8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -648,7 +648,7 @@
}
},
"activity-summary-get": {
- "description": "Get a summary of what the current user has been working on in this project: a one-page markdown profile, a short headline, the main focus areas with the day each was last seen, and the PostHog products they use. It is built only from the user's own recent activity in PostHog, such as tasks they gave to PostHog AI and things they created, changed or opened. It updates at most once a day, when there is enough new activity. Use it to tailor answers and suggestions to what this person works on. `status: not_ready` means no summary exists yet, which is normal for new or quiet users. `stale: true` means a newer version will replace it soon. A 404 means activity summaries are not available for this project.",
+ "description": "Get a summary of what the current user has been working on in this project: a one-page markdown profile, a short headline, 3 to 6 themes with a mode and the day each was last seen, and their overall work modes. The `computed` fields list, with ids, the objects they created or changed (`owned`), the objects they open again and again (`watched`), the product pages they open, the products they work in or only visit, and their task count. Each theme's `refs` point at entries in `computed`. It is built only from the user's own recent activity in PostHog, such as tasks they gave to PostHog AI and things they created, changed or opened. It updates at most once a day, when there is enough new activity. Use it to tailor answers and suggestions to what this person works on. `status: not_ready` means no summary exists yet, which is normal for new or quiet users. `stale: true` means a newer version will replace it soon. A 404 means activity summaries are not available for this project.",
"category": "Signals",
"feature": "signals",
"summary": "Get your activity summary",
@@ -664,7 +664,7 @@
"feature_flag": "activity-summary"
},
"activity-summary-versions-list": {
- "description": "List earlier versions of the current user's activity summary in this project, newest first, to see how their focus changed over time. Each version has a headline, the focus areas and `recent_shift`, which says what changed since the version before it. The list leaves out the profile to stay small. Pass `version` to get one version with its full profile. A 404 means activity summaries are not available for this project, or that the requested version does not exist.",
+ "description": "List earlier versions of the current user's activity summary in this project, newest first, to see how their focus changed over time. Each version has a headline, the themes, the modes and `recent_shift`, which says what changed since the version before it. The list leaves out the profile and the `computed` fields to stay small. Pass `version` to get one version with its full profile and the `computed` fields that its theme refs point at. A 404 means activity summaries are not available for this project, or that the requested version does not exist.",
"category": "Signals",
"feature": "signals",
"summary": "List your activity summary versions",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9c97c674e247..7862763957f8 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -648,7 +648,7 @@
}
},
"activity-summary-get": {
- "description": "Get a summary of what the current user has been working on in this project: a one-page markdown profile, a short headline, the main focus areas with the day each was last seen, and the PostHog products they use. It is built only from the user's own recent activity in PostHog, such as tasks they gave to PostHog AI and things they created, changed or opened. It updates at most once a day, when there is enough new activity. Use it to tailor answers and suggestions to what this person works on. `status: not_ready` means no summary exists yet, which is normal for new or quiet users. `stale: true` means a newer version will replace it soon. A 404 means activity summaries are not available for this project.",
+ "description": "Get a summary of what the current user has been working on in this project: a one-page markdown profile, a short headline, 3 to 6 themes with a mode and the day each was last seen, and their overall work modes. The `computed` fields list, with ids, the objects they created or changed (`owned`), the objects they open again and again (`watched`), the product pages they open, the products they work in or only visit, and their task count. Each theme's `refs` point at entries in `computed`. It is built only from the user's own recent activity in PostHog, such as tasks they gave to PostHog AI and things they created, changed or opened. It updates at most once a day, when there is enough new activity. Use it to tailor answers and suggestions to what this person works on. `status: not_ready` means no summary exists yet, which is normal for new or quiet users. `stale: true` means a newer version will replace it soon. A 404 means activity summaries are not available for this project.",
"category": "Signals",
"feature": "signals",
"summary": "Get your activity summary",
@@ -664,7 +664,7 @@
"feature_flag": "activity-summary"
},
"activity-summary-versions-list": {
- "description": "List earlier versions of the current user's activity summary in this project, newest first, to see how their focus changed over time. Each version has a headline, the focus areas and `recent_shift`, which says what changed since the version before it. The list leaves out the profile to stay small. Pass `version` to get one version with its full profile. A 404 means activity summaries are not available for this project, or that the requested version does not exist.",
+ "description": "List earlier versions of the current user's activity summary in this project, newest first, to see how their focus changed over time. Each version has a headline, the themes, the modes and `recent_shift`, which says what changed since the version before it. The list leaves out the profile and the `computed` fields to stay small. Pass `version` to get one version with its full profile and the `computed` fields that its theme refs point at. A 404 means activity summaries are not available for this project, or that the requested version does not exist.",
"category": "Signals",
"feature": "signals",
"summary": "List your activity summary versions",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 69d7fa6e26c6..b2eebe8ea900 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5314,21 +5314,212 @@ export namespace Schemas {
NotReady: 'not_ready',
} as const;
- export interface ActivitySummaryFocusArea {
- /** A main thread of the user's work, in the words of their activity. */
- topic: string;
+ /**
+ * * `building` - Building
+ * * `analyzing` - Analyzing
+ * * `monitoring` - Monitoring
+ * * `investigating` - Investigating
+ * * `operating` - Operating
+ * * `experimenting` - Experimenting
+ */
+ export type ActivitySummaryModeEnum = typeof ActivitySummaryModeEnum[keyof typeof ActivitySummaryModeEnum];
+
+
+ export const ActivitySummaryModeEnum = {
+ Building: 'building',
+ Analyzing: 'analyzing',
+ Monitoring: 'monitoring',
+ Investigating: 'investigating',
+ Operating: 'operating',
+ Experimenting: 'experimenting',
+ } as const;
+
+ export interface ActivitySummaryTheme {
+ /** A main thread of the user's work, in at most 60 characters. */
+ label: string;
+ /** How the user works on this thread. Null on summaries from before themes had a mode.
+ *
+ * * `building` - Building
+ * * `analyzing` - Analyzing
+ * * `monitoring` - Monitoring
+ * * `investigating` - Investigating
+ * * `operating` - Operating
+ * * `experimenting` - Experimenting */
+ mode: ActivitySummaryModeEnum | null;
/**
* How much of the recent activity is about this thread: high, medium or low.
* @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: string[];
/**
- * The last day with activity on this thread, as YYYY-MM-DD.
+ * The last day of activity on the refs of this thread, as YYYY-MM-DD.
* @nullable
*/
last_seen: string | null;
}
+ export interface ActivitySummaryOwnedObject {
+ /** The ref that themes cite, such as `o1`. */
+ ref: string;
+ /** The object type in snake case, such as `dashboard` or `feature_flag`. */
+ type: string;
+ /** The id of the object. */
+ id: string;
+ /** The latest name of the object. */
+ name: string;
+ /** The number of distinct days the user changed the object. */
+ edit_days: number;
+ /** The last day the user changed the object, as YYYY-MM-DD. */
+ last_at: string;
+ /** True when the user created the object in the window. */
+ created: boolean;
+ }
+
+ export interface ActivitySummaryWatchedObject {
+ /** The ref that themes cite, such as `o21`. */
+ ref: string;
+ /** The object type, such as `dashboard` or `insight`. */
+ type: string;
+ /** The id of the object. */
+ id: string;
+ /** The name of the object. */
+ name: string;
+ /** The number of distinct days the user opened the object. */
+ open_days: number;
+ /** The last day the user opened the object, as YYYY-MM-DD. */
+ last_at: string;
+ /** True when someone else made the object. */
+ not_theirs: boolean;
+ }
+
+ /**
+ * * `product_analytics` - Product Analytics
+ * * `dashboards` - Dashboards
+ * * `web_analytics` - Web Analytics
+ * * `session_replay` - Session Replay
+ * * `heatmaps` - Heatmaps
+ * * `error_tracking` - Error Tracking
+ * * `experiments` - Experiments
+ * * `feature_flags` - Feature Flags
+ * * `early_access_features` - Early Access Features
+ * * `surveys` - Surveys
+ * * `product_tours` - Product Tours
+ * * `notebooks` - Notebooks
+ * * `cohorts` - Cohorts
+ * * `persons` - Persons
+ * * `data_management` - Data Management
+ * * `data_warehouse` - Data Warehouse
+ * * `data_pipelines` - Data Pipelines
+ * * `workflows` - Workflows
+ * * `ai_observability` - Ai Observability
+ * * `mcp_analytics` - Mcp Analytics
+ * * `logs` - Logs
+ * * `tracing` - Tracing
+ * * `endpoints` - Endpoints
+ * * `revenue_analytics` - Revenue Analytics
+ * * `customer_analytics` - Customer Analytics
+ * * `inbox` - Inbox
+ * * `canvases` - Canvases
+ * * `support` - Support
+ */
+ export type ActivitySummaryProductEnum = typeof ActivitySummaryProductEnum[keyof typeof ActivitySummaryProductEnum];
+
+
+ export const ActivitySummaryProductEnum = {
+ ProductAnalytics: 'product_analytics',
+ Dashboards: 'dashboards',
+ WebAnalytics: 'web_analytics',
+ SessionReplay: 'session_replay',
+ Heatmaps: 'heatmaps',
+ ErrorTracking: 'error_tracking',
+ Experiments: 'experiments',
+ FeatureFlags: 'feature_flags',
+ EarlyAccessFeatures: 'early_access_features',
+ Surveys: 'surveys',
+ ProductTours: 'product_tours',
+ Notebooks: 'notebooks',
+ Cohorts: 'cohorts',
+ Persons: 'persons',
+ DataManagement: 'data_management',
+ DataWarehouse: 'data_warehouse',
+ DataPipelines: 'data_pipelines',
+ Workflows: 'workflows',
+ AiObservability: 'ai_observability',
+ McpAnalytics: 'mcp_analytics',
+ Logs: 'logs',
+ Tracing: 'tracing',
+ Endpoints: 'endpoints',
+ RevenueAnalytics: 'revenue_analytics',
+ CustomerAnalytics: 'customer_analytics',
+ Inbox: 'inbox',
+ Canvases: 'canvases',
+ Support: 'support',
+ } as const;
+
+ export interface ActivitySummaryPageVisits {
+ /** The ref that themes cite, such as `p1`. */
+ ref: string;
+ /** The product whose pages the user opened.
+ *
+ * * `product_analytics` - Product Analytics
+ * * `dashboards` - Dashboards
+ * * `web_analytics` - Web Analytics
+ * * `session_replay` - Session Replay
+ * * `heatmaps` - Heatmaps
+ * * `error_tracking` - Error Tracking
+ * * `experiments` - Experiments
+ * * `feature_flags` - Feature Flags
+ * * `early_access_features` - Early Access Features
+ * * `surveys` - Surveys
+ * * `product_tours` - Product Tours
+ * * `notebooks` - Notebooks
+ * * `cohorts` - Cohorts
+ * * `persons` - Persons
+ * * `data_management` - Data Management
+ * * `data_warehouse` - Data Warehouse
+ * * `data_pipelines` - Data Pipelines
+ * * `workflows` - Workflows
+ * * `ai_observability` - Ai Observability
+ * * `mcp_analytics` - Mcp Analytics
+ * * `logs` - Logs
+ * * `tracing` - Tracing
+ * * `endpoints` - Endpoints
+ * * `revenue_analytics` - Revenue Analytics
+ * * `customer_analytics` - Customer Analytics
+ * * `inbox` - Inbox
+ * * `canvases` - Canvases
+ * * `support` - Support */
+ product: ActivitySummaryProductEnum;
+ /** The number of distinct days the user opened its pages. */
+ open_days: number;
+ /** The last day the user opened its pages, as YYYY-MM-DD. */
+ last_at: string;
+ }
+
+ export interface ActivitySummaryProductSplit {
+ /** Products where the user changed something or tagged a task, the most active first. */
+ works_in: ActivitySummaryProductEnum[];
+ /** Products the user only opened, the most opened first. */
+ visits: ActivitySummaryProductEnum[];
+ }
+
+ export interface ActivitySummaryComputed {
+ /** The version of the shape of these fields. */
+ schema_version: number;
+ /** Objects the user created or changed, the most edited first. */
+ owned: ActivitySummaryOwnedObject[];
+ /** Objects the user opened on 3 or more days, the most opened first. */
+ watched: ActivitySummaryWatchedObject[];
+ /** Products whose pages the user opened, the most opened first. */
+ pages: ActivitySummaryPageVisits[];
+ /** The products the user works in and the products they only visit. */
+ products: ActivitySummaryProductSplit;
+ /** The number of tasks the user gave to PostHog AI or the Slack agent. */
+ task_count: number;
+ }
+
export interface ActivitySummary {
/** `ready` when a summary exists. `not_ready` when no summary exists yet, which is normal for new or quiet users.
*
@@ -5336,7 +5527,7 @@ export namespace Schemas {
* * `not_ready` - Not Ready */
status: ActivitySummaryStatusEnum;
/**
- * Two or three sentences that capture the profile.
+ * One or two sentences about what the user works on and cares about in this project.
* @nullable
*/
headline: string | null;
@@ -5346,14 +5537,16 @@ export namespace Schemas {
*/
profile: string | null;
/** The main threads of the user's work. */
- focus_areas: ActivitySummaryFocusArea[];
- /** The PostHog products the user works with, by name. */
- products: string[];
+ themes: ActivitySummaryTheme[];
+ /** How the user works in this project overall, the main mode first. */
+ modes: ActivitySummaryModeEnum[];
/**
* What changed since the version before this one, or null when nothing changed.
* @nullable
*/
recent_shift: string | null;
+ /** Exact fields that code computed from the user's activity, with ids. The theme refs point into them. Null before the first update that computed them. */
+ computed: ActivitySummaryComputed | null;
/**
* When this version of the summary was written.
* @nullable
@@ -5378,7 +5571,7 @@ export namespace Schemas {
/** The version of the prompt that wrote this version. */
prompt_version: number;
/**
- * Two or three sentences that capture the profile.
+ * One or two sentences about what the user works on and cares about in this project.
* @nullable
*/
headline: string | null;
@@ -5388,12 +5581,16 @@ export namespace Schemas {
*/
recent_shift: string | null;
/** The main threads of the user's work. */
- focus_areas: ActivitySummaryFocusArea[];
+ themes: ActivitySummaryTheme[];
+ /** How the user works in this project overall, the main mode first. */
+ modes: ActivitySummaryModeEnum[];
/**
* The one-page markdown profile. Set only when the request asks for one version with `version`.
* @nullable
*/
profile: string | null;
+ /** Exact fields that code computed from the user's activity, with ids. The theme refs point into them. Set only when the request asks for one version with `version`. */
+ computed: ActivitySummaryComputed | null;
}
export interface ActorsPropertyTaxonomyResponse {