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(object-tags): generate the kind registry from one Python source of truth (#101454)

Vojta Bartoš59ddea9e2778
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml
index b3b7bda5c8a7..f71555e178dd 100644
--- a/.github/workflows/ci-python.yml
+++ b/.github/workflows/ci-python.yml
@@ -103,6 +103,10 @@ jobs:
- 'frontend/src/products.json'
# A hand-edit to the generated taxonomy JSON must reach the drift check
- 'frontend/src/taxonomy/core-filter-definitions-by-group.json'
+ # Same for the generated object-tag registries
+ - 'frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts'
+ - 'products/desktop/packages/core/src/inbox/objectKinds.generated.ts'
+ - 'products/desktop/packages/shared/src/objectTagKinds.generated.ts'
# hogli CLI changes need validation
- 'tools/hogli/**'
- 'tools/hogli-commands/hogli_commands/**'
@@ -274,6 +278,11 @@ jobs:
run: |
python3 bin/build-taxonomy-json.py --check
+ - name: Check if the generated object-tag registries are up to date
+ shell: bash
+ run: |
+ python3 bin/build-object-tags-registry.py --check
+
# Warn-only while the pre-existing violation backlog settles: findings annotate
# the diff and land in the shared CI report comment, never a job failure.
# Scoped to the PR's own diff because C901 stays off repo-wide. Skip on
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index 0148b7475dfc..dfa0475c0132 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -135,6 +135,7 @@
"services/mcp/src/**/*.md",
"services/mcp/worker-configuration.d.ts",
"frontend/src/taxonomy/core-filter-definitions-by-group.json",
+ "frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts",
"products/review_hog/backend/reviewer/prompts/**/schema.json",
"**/chart/*/templates/**",
"products/metrics/agent/tests/**/golden/**",
diff --git a/bin/build-object-tags-registry.py b/bin/build-object-tags-registry.py
new file mode 100755
index 000000000000..a75af98122c5
--- /dev/null
+++ b/bin/build-object-tags-registry.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python
+"""Emit the agent object-tag kind registry for its TypeScript consumers.
+
+The source of truth is ``posthog/object_tags/kinds.py``; Python
+consumers import it directly. This generator carries the same registry to the
+desktop packages and the web frontend, plus the kind list the rich-output
+prompt teaches agents, so none of them can drift.
+
+Run via hogli: `hogli build:object-tags`. `--check` is what ci-python.yml and
+`hogli ci:preflight` call to fail on drift without writing.
+"""
+# ruff: noqa: T201
+
+import sys
+import json
+import argparse
+from collections.abc import Callable
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+# Ahead of site-packages, so the repo's posthog wins over an installed one of the
+# same name and the check cannot compare against a different registry.
+sys.path.insert(0, str(REPO_ROOT))
+
+from posthog.object_tags.kinds import ( # noqa: E402 — needs the sys.path line above
+ FALLBACK_OBJECT_KIND,
+ OBJECT_KIND_ALIASES,
+ OBJECT_KINDS,
+ ObjectKindSpec,
+)
+
+HEADER = """\
+// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.
+// Source of truth: posthog/object_tags/kinds.py — after editing it,
+// run `hogli build:object-tags` and commit the result.
+"""
+
+DATA_INTERFACE = """\
+export interface ObjectKindData {
+ /** Human name of the kind, e.g. "Insight". */
+ kindLabel: string;
+ /** Product the object comes from, e.g. "Product analytics". */
+ source: string;
+ /**
+ * Project-relative page template where "{id}" is the URL-encoded object id,
+ * or null when the kind has no canonical page.
+ */
+ pathTemplate: string | null;
+ /**
+ * When set, the raw id must match for the kind to have a page at all
+ * (e.g. flag pages resolve by numeric id only).
+ */
+ idPattern: string | null;
+ /** display="block" renders as a full card on surfaces that support it. */
+ block: boolean;
+ /** The tag body is the object id itself rather than a label (hogql: the SQL). */
+ idIsBody: boolean;
+}
+"""
+
+
+def _entry(spec: ObjectKindSpec, indent: str) -> str:
+ fields = [
+ f"kindLabel: {json.dumps(spec.kind_label)}",
+ f"source: {json.dumps(spec.source)}",
+ f"pathTemplate: {json.dumps(spec.path_template)}",
+ f"idPattern: {json.dumps(spec.id_pattern)}",
+ f"block: {json.dumps(spec.block)}",
+ f"idIsBody: {json.dumps(spec.id_is_body)}",
+ ]
+ body = "".join(f"{indent} {field},\n" for field in fields)
+ return "{\n" + body + indent + "}"
+
+
+def render_registry_ts() -> str:
+ kinds = "".join(f" {name}: {_entry(spec, ' ')},\n" for name, spec in OBJECT_KINDS.items())
+ aliases = "".join(f" {json.dumps(alias)}: {json.dumps(kind)},\n" for alias, kind in OBJECT_KIND_ALIASES.items())
+ return (
+ HEADER
+ + "\n"
+ + DATA_INTERFACE
+ + "\n"
+ + "export const OBJECT_KIND_DATA = {\n"
+ + kinds
+ + "} satisfies Record<string, ObjectKindData>;\n"
+ + "\n"
+ + "export type ObjectKindName = keyof typeof OBJECT_KIND_DATA;\n"
+ + "\n"
+ + "/** Alternate tag names agents plausibly write, mapped to registry kinds. */\n"
+ + "export const OBJECT_KIND_ALIASES: Record<string, string> = {\n"
+ + aliases
+ + "};\n"
+ + "\n"
+ + "/** Rendering fallback for a tag whose kind nobody registered. */\n"
+ + f"export const FALLBACK_OBJECT_KIND_DATA: ObjectKindData = {_entry(FALLBACK_OBJECT_KIND, '')};\n"
+ )
+
+
+def render_prompt_kinds_ts() -> str:
+ # hogql is taught by its own prompt bullet, not the kind list.
+ names = ", ".join(name for name, spec in OBJECT_KINDS.items() if not spec.id_is_body)
+ return (
+ HEADER
+ + "\n"
+ + "/** The kind list the rich-output prompt teaches agents. */\n"
+ + f"export const OBJECT_TAG_PROMPT_KIND_LIST = {json.dumps(names)};\n"
+ )
+
+
+OUTPUTS: dict[Path, Callable[[], str]] = {
+ REPO_ROOT / "products/desktop/packages/core/src/inbox/objectKinds.generated.ts": render_registry_ts,
+ REPO_ROOT / "products/desktop/packages/shared/src/objectTagKinds.generated.ts": render_prompt_kinds_ts,
+ REPO_ROOT / "frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts": render_registry_ts,
+}
+
+
+def check() -> int:
+ stale = []
+ for path, render in OUTPUTS.items():
+ # Bytes, not text, so no newline translation can hide or invent a difference.
+ on_disk = path.read_bytes() if path.exists() else b""
+ if on_disk != render().encode():
+ stale.append(path)
+ if not stale:
+ return 0
+ # stdout, because ci:preflight reports `result.stdout or result.stderr`.
+ for path in stale:
+ print(f"{path.relative_to(REPO_ROOT)} is out of date with posthog/object_tags/kinds.py.")
+ print("Run `hogli build:object-tags` and commit the result.")
+ return 1
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Generate the object-tag kind registry for TS consumers.")
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="Exit 1 if any generated file differs from the registry, without writing anything.",
+ )
+ args = parser.parse_args()
+ if args.check:
+ return check()
+ # Do not add a formatter pass here. Nothing reformats render()'s output before it
+ # reaches the files, so the output stays byte-stable and the drift check cannot
+ # flap. The other halves of that guarantee are the ignorePatterns entries in
+ # .oxfmtrc.json (frontend copy) and the generated-files override in
+ # products/desktop/biome.jsonc (desktop copies). Keep all of them.
+ for path, render in OUTPUTS.items():
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(render().encode())
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts b/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts
new file mode 100644
index 000000000000..1520c1447c6a
--- /dev/null
+++ b/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts
@@ -0,0 +1,177 @@
+// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.
+// Source of truth: posthog/object_tags/kinds.py — after editing it,
+// run `hogli build:object-tags` and commit the result.
+
+export interface ObjectKindData {
+ /** Human name of the kind, e.g. "Insight". */
+ kindLabel: string;
+ /** Product the object comes from, e.g. "Product analytics". */
+ source: string;
+ /**
+ * Project-relative page template where "{id}" is the URL-encoded object id,
+ * or null when the kind has no canonical page.
+ */
+ pathTemplate: string | null;
+ /**
+ * When set, the raw id must match for the kind to have a page at all
+ * (e.g. flag pages resolve by numeric id only).
+ */
+ idPattern: string | null;
+ /** display="block" renders as a full card on surfaces that support it. */
+ block: boolean;
+ /** The tag body is the object id itself rather than a label (hogql: the SQL). */
+ idIsBody: boolean;
+}
+
+export const OBJECT_KIND_DATA = {
+ insight: {
+ kindLabel: "Insight",
+ source: "Product analytics",
+ pathTemplate: "/insights/{id}",
+ idPattern: null,
+ block: true,
+ idIsBody: false,
+ },
+ hogql: {
+ kindLabel: "SQL query",
+ source: "SQL editor",
+ pathTemplate: "/sql?open_query={id}",
+ idPattern: null,
+ block: true,
+ idIsBody: true,
+ },
+ dashboard: {
+ kindLabel: "Dashboard",
+ source: "Product analytics",
+ pathTemplate: "/dashboard/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ error: {
+ kindLabel: "Error issue",
+ source: "Error tracking",
+ pathTemplate: "/error_tracking/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ replay: {
+ kindLabel: "Session replay",
+ source: "Session replay",
+ pathTemplate: "/replay/{id}",
+ idPattern: null,
+ block: true,
+ idIsBody: false,
+ },
+ flag: {
+ kindLabel: "Feature flag",
+ source: "Feature flags",
+ pathTemplate: "/feature_flags/{id}",
+ idPattern: "^\\d+$",
+ block: false,
+ idIsBody: false,
+ },
+ experiment: {
+ kindLabel: "Experiment",
+ source: "Experiments",
+ pathTemplate: "/experiments/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ survey: {
+ kindLabel: "Survey",
+ source: "Surveys",
+ pathTemplate: "/surveys/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ ticket: {
+ kindLabel: "Support tickets",
+ source: "Conversations",
+ pathTemplate: "/support/tickets/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ report: {
+ kindLabel: "Inbox report",
+ source: "Inbox",
+ pathTemplate: "/inbox/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ trace: {
+ kindLabel: "LLM trace",
+ source: "AI observability",
+ pathTemplate: "/ai-observability/traces/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ eval: {
+ kindLabel: "Evaluation",
+ source: "AI evals",
+ pathTemplate: "/ai-evals/evaluations/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ event: {
+ kindLabel: "Events",
+ source: "Product analytics",
+ pathTemplate: "/data-management/events/{id}",
+ idPattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}$",
+ block: false,
+ idIsBody: false,
+ },
+ cohort: {
+ kindLabel: "Cohort",
+ source: "Product analytics",
+ pathTemplate: "/cohorts/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ action: {
+ kindLabel: "Action",
+ source: "Product analytics",
+ pathTemplate: "/data-management/actions/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ person: {
+ kindLabel: "Person",
+ source: "Product analytics",
+ pathTemplate: "/persons/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+} satisfies Record<string, ObjectKindData>;
+
+export type ObjectKindName = keyof typeof OBJECT_KIND_DATA;
+
+/** Alternate tag names agents plausibly write, mapped to registry kinds. */
+export const OBJECT_KIND_ALIASES: Record<string, string> = {
+ "session-replay": "replay",
+ "session_replay": "replay",
+ "recording": "replay",
+ "feature-flag": "flag",
+ "feature_flag": "flag",
+ "sql": "hogql",
+};
+
+/** Rendering fallback for a tag whose kind nobody registered. */
+export const FALLBACK_OBJECT_KIND_DATA: ObjectKindData = {
+ kindLabel: "Evidence",
+ source: "PostHog",
+ pathTemplate: null,
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+};
diff --git a/hogli.yaml b/hogli.yaml
index cec8d1918a5a..60029e9617a4 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -488,6 +488,9 @@ build:
build:taxonomy-json:
bin_script: build-taxonomy-json.py
description: Generate core filter definitions taxonomy JSON for frontend
+ build:object-tags:
+ bin_script: build-object-tags-registry.py
+ description: Generate the agent object-tag kind registry for TypeScript consumers
build:bot-definitions:
cmd: python livestream/bot/generate_definitions.py
description: Generate livestream bot definitions JSON from bot_definitions.py
diff --git a/posthog/object_tags/__init__.py b/posthog/object_tags/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/object_tags/kinds.py b/posthog/object_tags/kinds.py
new file mode 100644
index 000000000000..3f84bdeb02d3
--- /dev/null
+++ b/posthog/object_tags/kinds.py
@@ -0,0 +1,168 @@
+"""Single source of truth for the agent object-tag kind registry.
+
+Agents cite PostHog objects in their replies with XML-style tags
+(``<insight id="9pQx3">checkout funnel</insight>``). Each surface renders them
+its own way — desktop as chips with hover previews, Slack and the web app as
+markdown links — but they all share one vocabulary: the kinds, aliases, labels
+and web paths defined here.
+
+Every entry is declarative (path templates and regex strings, never code) so
+``bin/build-object-tags-registry.py`` can emit the same registry for the
+TypeScript consumers. After editing, run ``hogli build:object-tags`` and commit
+the regenerated files:
+
+- ``products/desktop/packages/core/src/inbox/objectKinds.generated.ts``
+- ``products/desktop/packages/shared/src/objectTagKinds.generated.ts``
+- ``frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts``
+
+Python consumers import this module directly.
+"""
+
+import re
+from functools import cache
+from urllib.parse import quote
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class ObjectKindSpec:
+ """One agent-citable object kind."""
+
+ kind_label: str
+ # Product the object comes from, e.g. "Product analytics".
+ source: str
+ # Project-relative page template where ``{id}`` is the URL-encoded object id,
+ # or None when the kind has no canonical page.
+ path_template: str | None = None
+ # When set, the raw id must match for the kind to have a page at all
+ # (e.g. flag pages resolve by numeric id only, not by key). Must stay in the
+ # re/JS-RegExp common subset with no flags, so spell out case variants inline.
+ id_pattern: str | None = None
+ # display="block" renders as a full card on surfaces that support it.
+ block: bool = False
+ # The tag body is the object id itself rather than a label (hogql: the SQL).
+ id_is_body: bool = False
+
+
+OBJECT_KINDS: dict[str, ObjectKindSpec] = {
+ "insight": ObjectKindSpec(
+ kind_label="Insight",
+ source="Product analytics",
+ path_template="/insights/{id}",
+ block=True,
+ ),
+ "hogql": ObjectKindSpec(
+ kind_label="SQL query",
+ source="SQL editor",
+ path_template="/sql?open_query={id}",
+ block=True,
+ id_is_body=True,
+ ),
+ "dashboard": ObjectKindSpec(
+ kind_label="Dashboard",
+ source="Product analytics",
+ path_template="/dashboard/{id}",
+ ),
+ "error": ObjectKindSpec(
+ kind_label="Error issue",
+ source="Error tracking",
+ path_template="/error_tracking/{id}",
+ ),
+ "replay": ObjectKindSpec(
+ kind_label="Session replay",
+ source="Session replay",
+ path_template="/replay/{id}",
+ block=True,
+ ),
+ "flag": ObjectKindSpec(
+ kind_label="Feature flag",
+ source="Feature flags",
+ path_template="/feature_flags/{id}",
+ id_pattern=r"^\d+$",
+ ),
+ "experiment": ObjectKindSpec(
+ kind_label="Experiment",
+ source="Experiments",
+ path_template="/experiments/{id}",
+ ),
+ "survey": ObjectKindSpec(
+ kind_label="Survey",
+ source="Surveys",
+ path_template="/surveys/{id}",
+ ),
+ "ticket": ObjectKindSpec(
+ kind_label="Support tickets",
+ source="Conversations",
+ path_template="/support/tickets/{id}",
+ ),
+ "report": ObjectKindSpec(
+ kind_label="Inbox report",
+ source="Inbox",
+ path_template="/inbox/{id}",
+ ),
+ "trace": ObjectKindSpec(
+ kind_label="LLM trace",
+ source="AI observability",
+ path_template="/ai-observability/traces/{id}",
+ ),
+ "eval": ObjectKindSpec(
+ kind_label="Evaluation",
+ source="AI evals",
+ path_template="/ai-evals/evaluations/{id}",
+ ),
+ "event": ObjectKindSpec(
+ kind_label="Events",
+ source="Product analytics",
+ path_template="/data-management/events/{id}",
+ # Event definition pages resolve by uuid; an event cited by name has no page.
+ id_pattern=r"^[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}$",
+ ),
+ "cohort": ObjectKindSpec(
+ kind_label="Cohort",
+ source="Product analytics",
+ path_template="/cohorts/{id}",
+ ),
+ "action": ObjectKindSpec(
+ kind_label="Action",
+ source="Product analytics",
+ path_template="/data-management/actions/{id}",
+ ),
+ "person": ObjectKindSpec(
+ kind_label="Person",
+ source="Product analytics",
+ path_template="/persons/{id}",
+ ),
+}
+
+# Alternate tag names agents plausibly write, mapped to registry kinds.
+OBJECT_KIND_ALIASES: dict[str, str] = {
+ "session-replay": "replay",
+ "session_replay": "replay",
+ "recording": "replay",
+ "feature-flag": "flag",
+ "feature_flag": "flag",
+ "sql": "hogql",
+}
+
+# Rendering fallback for a tag whose kind nobody registered.
+FALLBACK_OBJECT_KIND = ObjectKindSpec(kind_label="Evidence", source="PostHog")
+
+
+def resolve_object_kind(name: str) -> ObjectKindSpec | None:
+ """Spec for a tag name (alias-aware), or None when it isn't an object tag."""
+ return OBJECT_KINDS.get(OBJECT_KIND_ALIASES.get(name, name))
+
+
+@cache
+def _compiled_pattern(pattern: str) -> re.Pattern[str]:
+ return re.compile(pattern)
+
+
+def object_web_path(spec: ObjectKindSpec, object_id: str) -> str | None:
+ """Project-relative page path for an object id, or None when it has no page."""
+ if spec.path_template is None:
+ return None
+ if spec.id_pattern is not None and not _compiled_pattern(spec.id_pattern).match(object_id):
+ return None
+ return spec.path_template.replace("{id}", quote(object_id, safe=""))
diff --git a/posthog/object_tags/test/__init__.py b/posthog/object_tags/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/object_tags/test/test_kinds.py b/posthog/object_tags/test/test_kinds.py
new file mode 100644
index 000000000000..dc7a0d2b4b0f
--- /dev/null
+++ b/posthog/object_tags/test/test_kinds.py
@@ -0,0 +1,21 @@
+from posthog.object_tags.kinds import OBJECT_KIND_ALIASES, OBJECT_KINDS, object_web_path, resolve_object_kind
+
+
+def test_registry_is_internally_consistent():
+ for alias, kind in OBJECT_KIND_ALIASES.items():
+ assert kind in OBJECT_KINDS, f"alias {alias!r} points at unregistered kind {kind!r}"
+ assert alias not in OBJECT_KINDS, f"alias {alias!r} shadows a registered kind"
+ for name, spec in OBJECT_KINDS.items():
+ if spec.path_template is not None:
+ assert "{id}" in spec.path_template, f"kind {name!r} template has no {{id}} placeholder"
+
+
+def test_id_pattern_guards_paths():
+ flag = resolve_object_kind("feature_flag")
+ assert flag is not None
+ assert object_web_path(flag, "42") == "/feature_flags/42"
+ assert object_web_path(flag, "my-flag-key") is None
+
+ event = OBJECT_KINDS["event"]
+ assert object_web_path(event, "0192D9EA-52AA-0000-8CCC-1A25E2E7DBBC") is not None
+ assert object_web_path(event, "$pageview") is None
diff --git a/products/desktop/biome.jsonc b/products/desktop/biome.jsonc
index c2df521caac9..97420795ab6d 100644
--- a/products/desktop/biome.jsonc
+++ b/products/desktop/biome.jsonc
@@ -125,6 +125,18 @@
"enabled": false
}
},
+ {
+ // Object-tag kind registry generated from posthog/object_tags/kinds.py; the
+ // generator's byte-stable output is what `hogli build:object-tags --check`
+ // compares against, so no formatter may touch it.
+ "includes": [
+ "packages/core/src/inbox/objectKinds.generated.ts",
+ "packages/shared/src/objectTagKinds.generated.ts"
+ ],
+ "formatter": {
+ "enabled": false
+ }
+ },
{
// TanStack Router generated route tree — uses `as any` and its own
// formatting; the file header explicitly says not to lint/format it.
diff --git a/products/desktop/packages/core/src/inbox/objectKinds.generated.ts b/products/desktop/packages/core/src/inbox/objectKinds.generated.ts
new file mode 100644
index 000000000000..1520c1447c6a
--- /dev/null
+++ b/products/desktop/packages/core/src/inbox/objectKinds.generated.ts
@@ -0,0 +1,177 @@
+// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.
+// Source of truth: posthog/object_tags/kinds.py — after editing it,
+// run `hogli build:object-tags` and commit the result.
+
+export interface ObjectKindData {
+ /** Human name of the kind, e.g. "Insight". */
+ kindLabel: string;
+ /** Product the object comes from, e.g. "Product analytics". */
+ source: string;
+ /**
+ * Project-relative page template where "{id}" is the URL-encoded object id,
+ * or null when the kind has no canonical page.
+ */
+ pathTemplate: string | null;
+ /**
+ * When set, the raw id must match for the kind to have a page at all
+ * (e.g. flag pages resolve by numeric id only).
+ */
+ idPattern: string | null;
+ /** display="block" renders as a full card on surfaces that support it. */
+ block: boolean;
+ /** The tag body is the object id itself rather than a label (hogql: the SQL). */
+ idIsBody: boolean;
+}
+
+export const OBJECT_KIND_DATA = {
+ insight: {
+ kindLabel: "Insight",
+ source: "Product analytics",
+ pathTemplate: "/insights/{id}",
+ idPattern: null,
+ block: true,
+ idIsBody: false,
+ },
+ hogql: {
+ kindLabel: "SQL query",
+ source: "SQL editor",
+ pathTemplate: "/sql?open_query={id}",
+ idPattern: null,
+ block: true,
+ idIsBody: true,
+ },
+ dashboard: {
+ kindLabel: "Dashboard",
+ source: "Product analytics",
+ pathTemplate: "/dashboard/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ error: {
+ kindLabel: "Error issue",
+ source: "Error tracking",
+ pathTemplate: "/error_tracking/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ replay: {
+ kindLabel: "Session replay",
+ source: "Session replay",
+ pathTemplate: "/replay/{id}",
+ idPattern: null,
+ block: true,
+ idIsBody: false,
+ },
+ flag: {
+ kindLabel: "Feature flag",
+ source: "Feature flags",
+ pathTemplate: "/feature_flags/{id}",
+ idPattern: "^\\d+$",
+ block: false,
+ idIsBody: false,
+ },
+ experiment: {
+ kindLabel: "Experiment",
+ source: "Experiments",
+ pathTemplate: "/experiments/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ survey: {
+ kindLabel: "Survey",
+ source: "Surveys",
+ pathTemplate: "/surveys/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ ticket: {
+ kindLabel: "Support tickets",
+ source: "Conversations",
+ pathTemplate: "/support/tickets/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ report: {
+ kindLabel: "Inbox report",
+ source: "Inbox",
+ pathTemplate: "/inbox/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ trace: {
+ kindLabel: "LLM trace",
+ source: "AI observability",
+ pathTemplate: "/ai-observability/traces/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ eval: {
+ kindLabel: "Evaluation",
+ source: "AI evals",
+ pathTemplate: "/ai-evals/evaluations/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ event: {
+ kindLabel: "Events",
+ source: "Product analytics",
+ pathTemplate: "/data-management/events/{id}",
+ idPattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}$",
+ block: false,
+ idIsBody: false,
+ },
+ cohort: {
+ kindLabel: "Cohort",
+ source: "Product analytics",
+ pathTemplate: "/cohorts/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ action: {
+ kindLabel: "Action",
+ source: "Product analytics",
+ pathTemplate: "/data-management/actions/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+ person: {
+ kindLabel: "Person",
+ source: "Product analytics",
+ pathTemplate: "/persons/{id}",
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+ },
+} satisfies Record<string, ObjectKindData>;
+
+export type ObjectKindName = keyof typeof OBJECT_KIND_DATA;
+
+/** Alternate tag names agents plausibly write, mapped to registry kinds. */
+export const OBJECT_KIND_ALIASES: Record<string, string> = {
+ "session-replay": "replay",
+ "session_replay": "replay",
+ "recording": "replay",
+ "feature-flag": "flag",
+ "feature_flag": "flag",
+ "sql": "hogql",
+};
+
+/** Rendering fallback for a tag whose kind nobody registered. */
+export const FALLBACK_OBJECT_KIND_DATA: ObjectKindData = {
+ kindLabel: "Evidence",
+ source: "PostHog",
+ pathTemplate: null,
+ idPattern: null,
+ block: false,
+ idIsBody: false,
+};
diff --git a/products/desktop/packages/core/src/inbox/objectTags.ts b/products/desktop/packages/core/src/inbox/objectTags.ts
index 4632c844300a..58eadf56a329 100644
--- a/products/desktop/packages/core/src/inbox/objectTags.ts
+++ b/products/desktop/packages/core/src/inbox/objectTags.ts
@@ -1,5 +1,12 @@
import { unescapeXmlAttr } from "@posthog/shared";
+import {
+ FALLBACK_OBJECT_KIND_DATA,
+ OBJECT_KIND_ALIASES,
+ OBJECT_KIND_DATA,
+ type ObjectKindData,
+} from "./objectKinds.generated";
+
// Object tags are the message-side counterpart of the `<file path="..."/>`
// attachment convention: agents embed references to PostHog objects in their
// replies, and hosts render them as live chips instead of raw text.
@@ -8,9 +15,10 @@ import { unescapeXmlAttr } from "@posthog/shared";
// <flag id="42"/>
// <hogql label="errors today">SELECT count() FROM events ...</hogql>
//
-// This module is host-agnostic: it owns the kind registry (minus icons, which
-// are a host concern) and the parser that turns free text into an ordered run
-// of text and tag segments. Rendering lives in each host.
+// This module is host-agnostic: it reads the generated kind registry (source
+// of truth: posthog/object_tags/kinds.py; icons are a host concern) and owns
+// the parser that turns free text into an ordered run of text and tag
+// segments. Rendering lives in each host.
export interface ObjectKindMeta {
/** Human name of the kind, e.g. "Insight". */
@@ -24,108 +32,31 @@ export interface ObjectKindMeta {
webPath?: (encodedId: string, rawId: string) => string | null;
}
-const OBJECT_KINDS: Record<string, ObjectKindMeta> = {
- insight: {
- kindLabel: "Insight",
- source: "Product analytics",
- webPath: (id) => `/insights/${id}`,
- },
- // For hogql the "id" is the SQL itself; the chip opens the SQL editor.
- hogql: {
- kindLabel: "SQL query",
- source: "SQL editor",
- webPath: (id) => `/sql?open_query=${id}`,
- },
- dashboard: {
- kindLabel: "Dashboard",
- source: "Product analytics",
- webPath: (id) => `/dashboard/${id}`,
- },
- error: {
- kindLabel: "Error issue",
- source: "Error tracking",
- webPath: (id) => `/error_tracking/${id}`,
- },
- replay: {
- kindLabel: "Session replay",
- source: "Session replay",
- webPath: (id) => `/replay/${id}`,
- },
- flag: {
- kindLabel: "Feature flag",
- source: "Feature flags",
- // Flag pages only resolve by numeric id, so a flag cited by key gets no
- // direct URL until its preview resolves the numeric id.
- webPath: (id, raw) => (/^\d+$/.test(raw) ? `/feature_flags/${id}` : null),
- },
- experiment: {
- kindLabel: "Experiment",
- source: "Experiments",
- webPath: (id) => `/experiments/${id}`,
- },
- survey: {
- kindLabel: "Survey",
- source: "Surveys",
- webPath: (id) => `/surveys/${id}`,
- },
- ticket: {
- kindLabel: "Support tickets",
- source: "Conversations",
- webPath: (id) => `/support/tickets/${id}`,
- },
- report: {
- kindLabel: "Inbox report",
- source: "Inbox",
- webPath: (id) => `/inbox/${id}`,
- },
- trace: {
- kindLabel: "LLM trace",
- source: "AI observability",
- webPath: (id) => `/ai-observability/traces/${id}`,
- },
- eval: {
- kindLabel: "Evaluation",
- source: "AI evals",
- webPath: (id) => `/ai-evals/evaluations/${id}`,
- },
- event: {
- kindLabel: "Events",
- source: "Product analytics",
- webPath: (id, raw) =>
- /^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw)
- ? `/data-management/events/${id}`
- : null,
- },
- cohort: {
- kindLabel: "Cohort",
- source: "Product analytics",
- webPath: (id) => `/cohorts/${id}`,
- },
- action: {
- kindLabel: "Action",
- source: "Product analytics",
- webPath: (id) => `/data-management/actions/${id}`,
- },
- person: {
- kindLabel: "Person",
- source: "Product analytics",
- webPath: (id) => `/persons/${id}`,
- },
-};
-
-/** Alternate tag names agents plausibly write, mapped to registry kinds. */
-const OBJECT_KIND_ALIASES: Record<string, string> = {
- "session-replay": "replay",
- recording: "replay",
- "feature-flag": "flag",
- feature_flag: "flag",
- sql: "hogql",
-};
-
-const GENERIC_OBJECT_KIND: ObjectKindMeta = {
- kindLabel: "Evidence",
- source: "PostHog",
-};
+/** Builds the runtime meta (label, source, guarded webPath) for one generated entry. */
+export function objectKindMeta(data: ObjectKindData): ObjectKindMeta {
+ const meta: ObjectKindMeta = {
+ kindLabel: data.kindLabel,
+ source: data.source,
+ };
+ const template = data.pathTemplate;
+ if (template) {
+ const guard = data.idPattern ? new RegExp(data.idPattern) : null;
+ meta.webPath = (encodedId, rawId) =>
+ guard && !guard.test(rawId) ? null : template.replace("{id}", encodedId);
+ }
+ return meta;
+}
+
+const OBJECT_KINDS: Record<string, ObjectKindMeta> = Object.fromEntries(
+ Object.entries(OBJECT_KIND_DATA).map(([name, data]) => [
+ name,
+ objectKindMeta(data),
+ ]),
+);
+
+const GENERIC_OBJECT_KIND: ObjectKindMeta = objectKindMeta(
+ FALLBACK_OBJECT_KIND_DATA,
+);
/** Registry kind for a tag name, or null when the tag isn't an object tag. */
export function resolveObjectKindName(tag: string): string | null {
diff --git a/products/desktop/packages/shared/src/objectTagKinds.generated.ts b/products/desktop/packages/shared/src/objectTagKinds.generated.ts
new file mode 100644
index 000000000000..2ceeeabbb462
--- /dev/null
+++ b/products/desktop/packages/shared/src/objectTagKinds.generated.ts
@@ -0,0 +1,6 @@
+// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.
+// Source of truth: posthog/object_tags/kinds.py — after editing it,
+// run `hogli build:object-tags` and commit the result.
+
+/** The kind list the rich-output prompt teaches agents. */
+export const OBJECT_TAG_PROMPT_KIND_LIST = "insight, dashboard, error, replay, flag, experiment, survey, ticket, report, trace, eval, event, cohort, action, person";
diff --git a/products/desktop/packages/shared/src/rich-output-prompt.ts b/products/desktop/packages/shared/src/rich-output-prompt.ts
index 99bdd8b95fdb..f2a093d7ffb4 100644
--- a/products/desktop/packages/shared/src/rich-output-prompt.ts
+++ b/products/desktop/packages/shared/src/rich-output-prompt.ts
@@ -1,11 +1,15 @@
+import { OBJECT_TAG_PROMPT_KIND_LIST } from "./objectTagKinds.generated";
+
/**
* Prompt block teaching an agent the object-tag vocabulary the desktop
* renders as live references (chips, hover previews, chart cards). Shared by
* every agent runtime so its syntax stays in sync with what `remarkObjectTags`
- * parses.
+ * parses; the kind list itself is generated from the registry
+ * (posthog/object_tags/kinds.py) so the prompt cannot drift from what the
+ * renderers understand.
*/
export const RICH_OUTPUT_TAGS_PROMPT = `Embed the PostHog objects behind your conclusions as XML tags, the same convention as \`<file path="..."/>\` attachments. Every tag is a live reference the app resolves when shown - never restate the object's data in your text, and never put tags inside code fences.
-- Inline reference: \`<kind id="...">short human label</kind>\` inside a sentence, e.g. \`The <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out.\` Kinds: insight, dashboard, error, replay, flag, experiment, survey, ticket, report, trace, eval, event, cohort, action, person. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; Inbox reports: the report uuid; persons: the uuid). It renders as a chip with a live hover preview that opens the object in PostHog.
+- Inline reference: \`<kind id="...">short human label</kind>\` inside a sentence, e.g. \`The <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out.\` Kinds: ${OBJECT_TAG_PROMPT_KIND_LIST}. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; Inbox reports: the report uuid; persons: the uuid). It renders as a chip with a live hover preview that opens the object in PostHog.
- Inline SQL: \`<hogql label="signups today">SELECT count() FROM events WHERE ...</hogql>\` - the SQL is the tag body, the label is what the sentence shows. Hovering runs the query live; clicking opens the SQL editor.
- Full-size chart, for any numeric or time-series answer (always prefer this over a markdown table): a saved insight \`<insight id="9pQx3" display="block"/>\` or a query \`<hogql display="block" title="Daily active users, last 7 days" caption="optional context">SELECT ...</hogql>\`. The chart executes live on every view. Include the time range in the title, and keep blank lines out of the SQL body.
- Some PostHog MCP query tools render their result as an interactive chart in the conversation, and the tool result says so. When the tool result says the user already sees the result as an interactive view, do not embed the same data again as a \`<hogql>\` chart; write the conclusion in text and let that view carry the data. When it does not, the tool renders nothing on its own, so follow the full-size chart rule above.
diff --git a/products/desktop/packages/ui/src/utils/objectKinds.ts b/products/desktop/packages/ui/src/utils/objectKinds.ts
index 99799fd9eb2d..2020a600ed31 100644
--- a/products/desktop/packages/ui/src/utils/objectKinds.ts
+++ b/products/desktop/packages/ui/src/utils/objectKinds.ts
@@ -18,13 +18,23 @@ import {
UserIcon,
UsersThreeIcon,
} from "@phosphor-icons/react";
+import {
+ FALLBACK_OBJECT_KIND_DATA,
+ OBJECT_KIND_DATA,
+ type ObjectKindData,
+ type ObjectKindName,
+} from "@posthog/core/inbox/objectKinds.generated";
+import { objectKindMeta } from "@posthog/core/inbox/objectTags";
/**
* The registry of PostHog object kinds an agent can embed in a message as
- * `<kind id="...">label</kind>` tags (see remarkObjectTags).
+ * `<kind id="...">label</kind>` tags (see remarkObjectTags), read from the
+ * generated registry (source of truth: posthog/object_tags/kinds.py).
*
- * Adding a kind here is all it takes for the inline chip: icon, labels, and
- * the click-through URL. Two opt-ins live elsewhere:
+ * Adding a kind there is all it takes for the inline chip: labels and the
+ * click-through URL come from the registry, and the `Record<ObjectKindName>`
+ * icon map below fails typecheck until the new kind gets an icon. Two opt-ins
+ * live elsewhere:
* - a live hover preview needs a case in `PostHogAPIClient.getEvidencePreview`
* - `block: true` needs a card renderer in `MessageChartCard`
*/
@@ -52,137 +62,45 @@ export interface ObjectKindDef {
*/
export const POSTHOG_OBJECT_ICON_COLOR = "var(--primary)";
-const OBJECT_KINDS: Record<string, ObjectKindDef> = {
- insight: {
- icon: ChartLineIcon,
- kindLabel: "Insight",
- source: "Product analytics",
- webPath: (id) => `/insights/${id}`,
- block: true,
- },
- // For hogql the "id" is the SQL itself; the chip opens the SQL editor and
- // the hover card runs the query live.
- hogql: {
- icon: DatabaseIcon,
- kindLabel: "SQL query",
- source: "SQL editor",
- webPath: (id) => `/sql?open_query=${id}`,
- block: true,
- },
- dashboard: {
- icon: SquaresFourIcon,
- kindLabel: "Dashboard",
- source: "Product analytics",
- webPath: (id) => `/dashboard/${id}`,
- },
- error: {
- icon: BugIcon,
- kindLabel: "Error issue",
- source: "Error tracking",
- webPath: (id) => `/error_tracking/${id}`,
- },
- replay: {
- icon: PlayCircleIcon,
- kindLabel: "Session replay",
- source: "Session replay",
- webPath: (id) => `/replay/${id}`,
- block: true,
- },
- flag: {
- icon: FlagIcon,
- kindLabel: "Feature flag",
- source: "Feature flags",
- // Flag pages only resolve by numeric id, so a flag cited by key gets no
- // direct URL (its hover preview still resolves through the list search).
- webPath: (id, raw) => (/^\d+$/.test(raw) ? `/feature_flags/${id}` : null),
- },
- experiment: {
- icon: FlaskIcon,
- kindLabel: "Experiment",
- source: "Experiments",
- webPath: (id) => `/experiments/${id}`,
- },
- survey: {
- icon: ClipboardTextIcon,
- kindLabel: "Survey",
- source: "Surveys",
- webPath: (id) => `/surveys/${id}`,
- },
- ticket: {
- icon: ChatCircleTextIcon,
- kindLabel: "Support tickets",
- source: "Conversations",
- webPath: (id) => `/support/tickets/${id}`,
- },
- report: {
- icon: TrayIcon,
- kindLabel: "Inbox report",
- source: "Inbox",
- webPath: (id) => `/inbox/${id}`,
- },
- trace: {
- icon: SparkleIcon,
- kindLabel: "LLM trace",
- source: "AI observability",
- webPath: (id) => `/ai-observability/traces/${id}`,
- },
- eval: {
- icon: ShieldCheckIcon,
- kindLabel: "Evaluation",
- source: "AI evals",
- webPath: (id) => `/ai-evals/evaluations/${id}`,
- },
- event: {
- icon: LightningIcon,
- kindLabel: "Events",
- source: "Product analytics",
- // Cited by name; the page needs the definition id, which the hover
- // preview resolves (resolvedId) before the card can link out.
- webPath: (id, raw) =>
- /^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw)
- ? `/data-management/events/${id}`
- : null,
- },
- cohort: {
- icon: UsersThreeIcon,
- kindLabel: "Cohort",
- source: "Product analytics",
- webPath: (id) => `/cohorts/${id}`,
- },
- action: {
- icon: CursorClickIcon,
- kindLabel: "Action",
- source: "Product analytics",
- webPath: (id) => `/data-management/actions/${id}`,
- },
- person: {
- icon: UserIcon,
- kindLabel: "Person",
- source: "Product analytics",
- webPath: (id) => `/persons/${id}`,
- },
+const KIND_ICONS: Record<ObjectKindName, Icon> = {
+ insight: ChartLineIcon,
+ hogql: DatabaseIcon,
+ dashboard: SquaresFourIcon,
+ error: BugIcon,
+ replay: PlayCircleIcon,
+ flag: FlagIcon,
+ experiment: FlaskIcon,
+ survey: ClipboardTextIcon,
+ ticket: ChatCircleTextIcon,
+ report: TrayIcon,
+ trace: SparkleIcon,
+ eval: ShieldCheckIcon,
+ event: LightningIcon,
+ cohort: UsersThreeIcon,
+ action: CursorClickIcon,
+ person: UserIcon,
};
-/** Alternate tag names agents plausibly write, mapped to registry kinds. */
-const OBJECT_KIND_ALIASES: Record<string, string> = {
- "session-replay": "replay",
- recording: "replay",
- "feature-flag": "flag",
- sql: "hogql",
-};
+function toDef(data: ObjectKindData, icon: Icon): ObjectKindDef {
+ const def: ObjectKindDef = { icon, ...objectKindMeta(data) };
+ if (data.block) {
+ def.block = true;
+ }
+ return def;
+}
-const GENERIC_OBJECT_KIND: ObjectKindDef = {
- icon: PulseIcon,
- kindLabel: "Evidence",
- source: "PostHog",
-};
+const OBJECT_KINDS: Record<string, ObjectKindDef> = Object.fromEntries(
+ (Object.entries(OBJECT_KIND_DATA) as [ObjectKindName, ObjectKindData][]).map(
+ ([name, data]) => [name, toDef(data, KIND_ICONS[name])],
+ ),
+);
-/** Registry kind for a tag name, or null when the tag isn't an object tag. */
-export function resolveObjectKindName(tag: string): string | null {
- if (OBJECT_KINDS[tag]) return tag;
- const alias = OBJECT_KIND_ALIASES[tag];
- return alias && OBJECT_KINDS[alias] ? alias : null;
-}
+const GENERIC_OBJECT_KIND: ObjectKindDef = toDef(
+ FALLBACK_OBJECT_KIND_DATA,
+ PulseIcon,
+);
+
+export { resolveObjectKindName } from "@posthog/core/inbox/objectTags";
export function getObjectKind(kind: string): ObjectKindDef {
return OBJECT_KINDS[kind] ?? GENERIC_OBJECT_KIND;
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index f256d56c965f..fcd758e89b80 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -20,6 +20,7 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.event_usage import groups
from posthog.models.integration import Integration
from posthog.models.user_integration import UserIntegration
+from posthog.object_tags.kinds import OBJECT_KINDS
from posthog.security.url_validation import is_url_allowed, resolve_url_hosts_ips
from products.tasks.backend.facade import api as tasks_facade
@@ -205,23 +206,7 @@ TASK_RUN_ARTIFACT_TYPE_CHOICES = [
TASK_RUN_ARTIFACT_CONTENT_ENCODING_CHOICES = ["utf-8", "base64"]
TASK_RUN_SKILL_BUNDLE_FORMAT_CHOICES = ["zip"]
TASK_RUN_SKILL_SOURCE_CHOICES = ["user", "repo", "marketplace", "codex"]
-POSTHOG_OBJECT_KIND_CHOICES = [
- "insight",
- "hogql",
- "dashboard",
- "error",
- "replay",
- "flag",
- "experiment",
- "survey",
- "ticket",
- "trace",
- "eval",
- "event",
- "cohort",
- "action",
- "person",
-]
+POSTHOG_OBJECT_KIND_CHOICES = list(OBJECT_KINDS)
TASK_RUN_LIVING_ARTIFACT_TYPE_CHOICES = [choice for choice, _label in TaskArtifactType.choices]
TASK_RUN_LIVING_ARTIFACT_ADAPTER_CHOICES = [choice for choice, _label in TaskArtifactAdapter.choices]
TASK_RUN_LIVING_ARTIFACT_WRITE_ADAPTER_CHOICES = TASK_RUN_LIVING_ARTIFACT_ADAPTER_CHOICES
diff --git a/products/tasks/backend/temporal/slack_relay/object_tags.py b/products/tasks/backend/temporal/slack_relay/object_tags.py
index fecdf1173bad..0609d21e24c2 100644
--- a/products/tasks/backend/temporal/slack_relay/object_tags.py
+++ b/products/tasks/backend/temporal/slack_relay/object_tags.py
@@ -6,15 +6,14 @@ those into chips and chart cards; Slack has no renderer, so a raw tag reaches th
escaped XML. This module runs before markdown conversion and turns each tag into the closest
thing Slack has: a link to the object, a fenced SQL block, or just the label.
-The kind registry mirrors the desktop one (``products/desktop/packages/core/src/inbox/objectTags.ts``).
-Keep the two in sync when a kind or path changes.
+The kind registry comes from ``posthog/object_tags/kinds.py``, the same source of truth the
+desktop and web renderers are generated from.
"""
import re
-from collections.abc import Callable
-from urllib.parse import quote
from posthog.dataclasses import frozen
+from posthog.object_tags.kinds import OBJECT_KINDS, ObjectKindSpec, object_web_path, resolve_object_kind
# Slack keeps a link's URL out of the message text limit, but the chat API rejects URLs past
# this size, and a SQL editor deep link carries the whole query in the query string.
@@ -30,66 +29,11 @@ _RE_CLOSE_TAG = re.compile(r"</([a-z][\w-]*)\s*>")
_RE_ATTR = re.compile(r"([a-z][\w-]*)\s*=\s*\"([^\"]*)\"")
_RE_FENCE_LINE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
_RE_BACKTICK_RUN = re.compile(r"`+")
-_RE_UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f-]{27,}$", re.IGNORECASE)
_RE_LABEL_UNSAFE = re.compile(r"[\[\]|]")
_LABEL_ANGLE_ENTITIES = {"<": "&lt;", ">": "&gt;"}
-_RE_NUMERIC = re.compile(r"^\d+$")
_RE_BARE_ID = re.compile(r"^[\w$.:-]{1,64}$")
-
-@frozen
-class _ObjectKind:
- label: str
- # Project-relative path for an id, or None when the id has no page of its own.
- web_path: Callable[[str], str | None]
-
-
-def _plain_path(prefix: str) -> Callable[[str], str | None]:
- return lambda object_id: f"{prefix}/{quote(object_id, safe='')}"
-
-
-def _flag_path(object_id: str) -> str | None:
- # Flag pages resolve by numeric id only; a flag cited by key has no direct page.
- return f"/feature_flags/{object_id}" if _RE_NUMERIC.match(object_id) else None
-
-
-def _event_path(object_id: str) -> str | None:
- # Event definition pages resolve by uuid; an event cited by name has no direct page.
- return f"/data-management/events/{quote(object_id, safe='')}" if _RE_UUID.match(object_id) else None
-
-
-def _sql_editor_path(sql: str) -> str | None:
- return f"/sql?open_query={quote(sql, safe='')}"
-
-
-_HOGQL_KIND = _ObjectKind(label="SQL query", web_path=_sql_editor_path)
-
-_OBJECT_KINDS: dict[str, _ObjectKind] = {
- "insight": _ObjectKind(label="Insight", web_path=_plain_path("/insights")),
- "hogql": _HOGQL_KIND,
- "dashboard": _ObjectKind(label="Dashboard", web_path=_plain_path("/dashboard")),
- "error": _ObjectKind(label="Error issue", web_path=_plain_path("/error_tracking")),
- "replay": _ObjectKind(label="Session replay", web_path=_plain_path("/replay")),
- "flag": _ObjectKind(label="Feature flag", web_path=_flag_path),
- "experiment": _ObjectKind(label="Experiment", web_path=_plain_path("/experiments")),
- "survey": _ObjectKind(label="Survey", web_path=_plain_path("/surveys")),
- "ticket": _ObjectKind(label="Support ticket", web_path=_plain_path("/support/tickets")),
- "trace": _ObjectKind(label="LLM trace", web_path=_plain_path("/ai-observability/traces")),
- "eval": _ObjectKind(label="Evaluation", web_path=_plain_path("/ai-evals/evaluations")),
- "event": _ObjectKind(label="Event", web_path=_event_path),
- "cohort": _ObjectKind(label="Cohort", web_path=_plain_path("/cohorts")),
- "action": _ObjectKind(label="Action", web_path=_plain_path("/data-management/actions")),
- "person": _ObjectKind(label="Person", web_path=_plain_path("/persons")),
-}
-
-_OBJECT_KIND_ALIASES: dict[str, str] = {
- "session-replay": "replay",
- "recording": "replay",
- "session_replay": "replay",
- "feature-flag": "flag",
- "feature_flag": "flag",
- "sql": "hogql",
-}
+_HOGQL_SPEC = OBJECT_KINDS["hogql"]
# Only the five entities the desktop composer's XML serializer emits (``escapeXmlAttr``); the full
@@ -120,8 +64,8 @@ class _Tag:
end: int
-def _resolve_kind(name: str) -> _ObjectKind | None:
- return _OBJECT_KINDS.get(_OBJECT_KIND_ALIASES.get(name, name))
+def _resolve_kind(name: str) -> ObjectKindSpec | None:
+ return resolve_object_kind(name)
def _parse_attrs(raw: str) -> dict[str, str]:
@@ -241,8 +185,8 @@ def _link(label: str, url: str | None) -> str:
return f"[{label}]({url})"
-def _object_url(project_url: str, kind: _ObjectKind, object_id: str, *, unfurl: bool) -> str | None:
- path = kind.web_path(object_id)
+def _object_url(project_url: str, kind: ObjectKindSpec, object_id: str, *, unfurl: bool) -> str | None:
+ path = object_web_path(kind, object_id)
if path is None:
return None
if unfurl:
@@ -256,12 +200,12 @@ def _render_hogql(tag: _Tag, project_url: str) -> str | None:
sql = _unescape_xml(tag.body).strip()
if not sql:
return None
- url = _object_url(project_url, _HOGQL_KIND, sql, unfurl=False)
+ url = _object_url(project_url, _HOGQL_SPEC, sql, unfurl=False)
if tag.attrs.get("display") != "block":
- label = _safe_label(tag.attrs.get("label") or tag.attrs.get("title") or "") or _HOGQL_KIND.label
+ label = _safe_label(tag.attrs.get("label") or tag.attrs.get("title") or "") or _HOGQL_SPEC.kind_label
return _link(label, url)
- title = _safe_label(tag.attrs.get("title") or "") or _HOGQL_KIND.label
+ title = _safe_label(tag.attrs.get("title") or "") or _HOGQL_SPEC.kind_label
# No language hint on the fence: Slack shows one as literal text inside the block.
lines = [f"**{_link(title, url)}**", "```", sql, "```"]
caption = " ".join((tag.attrs.get("caption") or "").split())
@@ -270,7 +214,7 @@ def _render_hogql(tag: _Tag, project_url: str) -> str | None:
return "\n".join(lines)
-def _render_reference(tag: _Tag, kind: _ObjectKind, project_url: str) -> str | None:
+def _render_reference(tag: _Tag, kind: ObjectKindSpec, project_url: str) -> str | None:
object_id = (tag.attrs.get("id") or "").strip()
body = tag.body.strip()
if not object_id and _RE_BARE_ID.match(body):
@@ -280,7 +224,7 @@ def _render_reference(tag: _Tag, kind: _ObjectKind, project_url: str) -> str | N
# A tag with a title but no id (a notebook query node) has no page to link; keep the title.
return _safe_label(tag.attrs.get("title") or "") or None
is_block = tag.attrs.get("display") == "block"
- label = _safe_label(tag.attrs.get("title") or body) or f"{kind.label} {_safe_label(object_id)}"
+ label = _safe_label(tag.attrs.get("title") or body) or f"{kind.kind_label} {_safe_label(object_id)}"
return _link(label, _object_url(project_url, kind, object_id, unfurl=is_block))
@@ -291,7 +235,7 @@ def _render_tag(tag: _Tag, project_url: str) -> str | None:
# The label is still the useful part, so keep it and drop the markup.
label = _safe_label(tag.body)
return label if "id" in tag.attrs and label else None
- if kind is _HOGQL_KIND:
+ if kind.id_is_body:
return _render_hogql(tag, project_url)
return _render_reference(tag, kind, project_url)
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 1fb55dc3e4ac..d8d05cdb0673 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1525,6 +1525,7 @@ export const ReferenceTypeEnumApi = {
* * `experiment` - experiment
* * `survey` - survey
* * `ticket` - ticket
+ * * `report` - report
* * `trace` - trace
* * `eval` - eval
* * `event` - event
@@ -1544,6 +1545,7 @@ export const ObjectKindEnumApi = {
Experiment: 'experiment',
Survey: 'survey',
Ticket: 'ticket',
+ Report: 'report',
Trace: 'trace',
Eval: 'eval',
Event: 'event',
@@ -1568,6 +1570,7 @@ export interface TaskRunPostHogReferenceMetadataApi {
* * `experiment` - experiment
* * `survey` - survey
* * `ticket` - ticket
+ * * `report` - report
* * `trace` - trace
* * `eval` - eval
* * `event` - event
@@ -3910,6 +3913,7 @@ export interface TaskRunPostHogReferenceApi {
* * `experiment` - experiment
* * `survey` - survey
* * `ticket` - ticket
+ * * `report` - report
* * `trace` - trace
* * `eval` - eval
* * `event` - event
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index a4d127b8661c..c44bc1694840 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -3054,6 +3054,7 @@ export const TasksRunsArtifactsReferencesCreateBody = /* @__PURE__ */ zod.object
'experiment',
'survey',
'ticket',
+ 'report',
'trace',
'eval',
'event',
@@ -3062,10 +3063,10 @@ export const TasksRunsArtifactsReferencesCreateBody = /* @__PURE__ */ zod.object
'person',
])
.describe(
- '\* `insight` - insight\n\* `hogql` - hogql\n\* `dashboard` - dashboard\n\* `error` - error\n\* `replay` - replay\n\* `flag` - flag\n\* `experiment` - experiment\n\* `survey` - survey\n\* `ticket` - ticket\n\* `trace` - trace\n\* `eval` - eval\n\* `event` - event\n\* `cohort` - cohort\n\* `action` - action\n\* `person` - person'
+ '\* `insight` - insight\n\* `hogql` - hogql\n\* `dashboard` - dashboard\n\* `error` - error\n\* `replay` - replay\n\* `flag` - flag\n\* `experiment` - experiment\n\* `survey` - survey\n\* `ticket` - ticket\n\* `report` - report\n\* `trace` - trace\n\* `eval` - eval\n\* `event` - event\n\* `cohort` - cohort\n\* `action` - action\n\* `person` - person'
)
.describe(
- 'PostHog object kind used to resolve the reference.\n\n\* `insight` - insight\n\* `hogql` - hogql\n\* `dashboard` - dashboard\n\* `error` - error\n\* `replay` - replay\n\* `flag` - flag\n\* `experiment` - experiment\n\* `survey` - survey\n\* `ticket` - ticket\n\* `trace` - trace\n\* `eval` - eval\n\* `event` - event\n\* `cohort` - cohort\n\* `action` - action\n\* `person` - person'
+ 'PostHog object kind used to resolve the reference.\n\n\* `insight` - insight\n\* `hogql` - hogql\n\* `dashboard` - dashboard\n\* `error` - error\n\* `replay` - replay\n\* `flag` - flag\n\* `experiment` - experiment\n\* `survey` - survey\n\* `ticket` - ticket\n\* `report` - report\n\* `trace` - trace\n\* `eval` - eval\n\* `event` - event\n\* `cohort` - cohort\n\* `action` - action\n\* `person` - person'
),
object_id: zod
.string()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3030f645c9c8..868ffb4166cf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -56570,6 +56570,7 @@ export namespace Schemas {
* * `experiment` - experiment
* * `survey` - survey
* * `ticket` - ticket
+ * * `report` - report
* * `trace` - trace
* * `eval` - eval
* * `event` - event
@@ -56590,6 +56591,7 @@ export namespace Schemas {
Experiment: 'experiment',
Survey: 'survey',
Ticket: 'ticket',
+ Report: 'report',
Trace: 'trace',
Eval: 'eval',
Event: 'event',
@@ -62824,6 +62826,7 @@ export namespace Schemas {
* * `experiment` - experiment
* * `survey` - survey
* * `ticket` - ticket
+ * * `report` - report
* * `trace` - trace
* * `eval` - eval
* * `event` - event
@@ -91950,6 +91953,7 @@ export namespace Schemas {
* * `experiment` - experiment
* * `survey` - survey
* * `ticket` - ticket
+ * * `report` - report
* * `trace` - trace
* * `eval` - eval
* * `event` - event
diff --git a/tools/hogli-commands/hogli_commands/build.py b/tools/hogli-commands/hogli_commands/build.py
index e81b6c75b8d6..4767e2849705 100644
--- a/tools/hogli-commands/hogli_commands/build.py
+++ b/tools/hogli-commands/hogli_commands/build.py
@@ -38,6 +38,7 @@ TRIGGERS: dict[str, tuple[str, ...]] = {
),
"build:grammar": ("posthog/hogql/grammar/*",),
"build:taxonomy-json": ("posthog/taxonomy/*",),
+ "build:object-tags": ("posthog/object_tags/*",),
"build:products": ("products/*/frontend/*",),
"build:skills": ("products/*/skills/*",),
"build:schema-mcp": ("services/mcp/src/*",),
diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.py
index fafb0da4bb95..33b3f306da83 100644
--- a/tools/hogli-commands/hogli_commands/ci_preflight.py
+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py
@@ -272,6 +272,23 @@ DIFF_CHECKS: list[DiffCheck] = [
fix=["hogli", "build:taxonomy-json"],
requires=("python-env",),
),
+ DiffCheck(
+ key="object-tags",
+ label="generated object-tag registries out of sync with posthog/object_tags/kinds.py",
+ # From build.py so preflight and build:object-tags can't drift on which diffs
+ # need a regen, plus the generator and its outputs, so an edit to any side of
+ # the relation is caught.
+ triggers=[
+ *BUILD_TRIGGERS["build:object-tags"],
+ "bin/build-object-tags-registry.py",
+ "products/desktop/packages/core/src/inbox/objectKinds.generated.ts",
+ "products/desktop/packages/shared/src/objectTagKinds.generated.ts",
+ "frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts",
+ ],
+ verify=["hogli", "build:object-tags", "--check"],
+ fix=["hogli", "build:object-tags"],
+ requires=("python-env",),
+ ),
DiffCheck(
key="migrations",
label="migration conflict / orphaned migration",