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: grounded self-validating reply pipeline (#64212)

Alex V0ff0b240022b
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index bca8f5f03689..f850afc4c62a 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -22,6 +22,7 @@ Product = Literal[
"product_analytics",
"subscriptions",
"signals",
+ "conversations",
] # If you add a product here, make sure it's also in services/llm-gateway/src/llm_gateway/products/config.py
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 9677064b8d6f..12e3100e3749 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -179,6 +179,10 @@ from products.business_knowledge.backend.temporal import (
ACTIVITIES as BUSINESS_KNOWLEDGE_ACTIVITIES,
WORKFLOWS as BUSINESS_KNOWLEDGE_WORKFLOWS,
)
+from products.conversations.backend.temporal import (
+ ACTIVITIES as CONVERSATIONS_ACTIVITIES,
+ WORKFLOWS as CONVERSATIONS_WORKFLOWS,
+)
from products.error_tracking.backend.facade.temporal import (
ACTIVITIES as ERROR_TRACKING_ACTIVITIES,
WORKFLOWS as ERROR_TRACKING_WORKFLOWS,
@@ -312,8 +316,14 @@ _task_queue_specs = [
),
(
settings.VIDEO_EXPORT_TASK_QUEUE,
- SIGNALS_PRODUCT_WORKFLOWS + DATA_IMPORT_EMIT_SIGNALS_WORKFLOWS + BUSINESS_KNOWLEDGE_WORKFLOWS,
- SIGNALS_PRODUCT_ACTIVITIES + DATA_IMPORT_EMIT_SIGNALS_ACTIVITIES + BUSINESS_KNOWLEDGE_ACTIVITIES,
+ SIGNALS_PRODUCT_WORKFLOWS
+ + DATA_IMPORT_EMIT_SIGNALS_WORKFLOWS
+ + BUSINESS_KNOWLEDGE_WORKFLOWS
+ + CONVERSATIONS_WORKFLOWS,
+ SIGNALS_PRODUCT_ACTIVITIES
+ + DATA_IMPORT_EMIT_SIGNALS_ACTIVITIES
+ + BUSINESS_KNOWLEDGE_ACTIVITIES
+ + CONVERSATIONS_ACTIVITIES,
),
(
settings.SESSION_REPLAY_TASK_QUEUE,
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 897db8b97293..ab4ebb2f305f 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -2024,6 +2024,55 @@ def get_document_window(
]
+@with_team_scope(canonical=True)
+def get_chunks_by_ids(team_id: int, chunk_ids: list[UUID]) -> list[KnowledgeSearchResult]:
+ """
+ Rehydrate full chunk content + source context for a set of chunk ids,
+ preserving the order of ``chunk_ids`` and dropping any id that no longer
+ resolves (unsafe/tombstoned/deleted). Applies the same safety filters as
+ ``search_knowledge``.
+
+ Lets callers pass chunk ids across a process/serialization boundary (e.g.
+ between Temporal activities) and re-fetch content on demand — deterministic
+ retrieval — instead of shipping the content itself through workflow history.
+ """
+ if not chunk_ids:
+ return []
+
+ chunks = (
+ _safe_chunks_qs(team_id)
+ .filter(id__in=chunk_ids)
+ .select_related("source", "document")
+ .only(
+ "id",
+ "source_id",
+ "document_id",
+ "heading_path",
+ "ordinal",
+ "content",
+ "source__name",
+ "source__source_type",
+ "document__title",
+ )
+ )
+ by_id = {c.id: c for c in chunks}
+ return [
+ KnowledgeSearchResult(
+ chunk_id=c.id,
+ source_id=c.source_id,
+ source_name=c.source.name,
+ source_type=c.source.source_type,
+ document_id=c.document_id,
+ document_title=c.document.title,
+ heading_path=c.heading_path,
+ ordinal=c.ordinal,
+ content=c.content,
+ )
+ for chunk_id in chunk_ids
+ if (c := by_id.get(chunk_id)) is not None
+ ]
+
+
# ---------------------------------------------------------------------------
# Background-refresh coordinator helpers (cross-team)
#
diff --git a/products/conversations/backend/management/__init__.py b/products/conversations/backend/management/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/conversations/backend/management/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/conversations/backend/management/commands/__init__.py b/products/conversations/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/conversations/backend/management/commands/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/conversations/backend/management/commands/run_support_reply.py b/products/conversations/backend/management/commands/run_support_reply.py
new file mode 100644
index 000000000000..80d8200e65e2
--- /dev/null
+++ b/products/conversations/backend/management/commands/run_support_reply.py
@@ -0,0 +1,45 @@
+"""Run the grounded support reply pipeline against a single ticket end-to-end.
+
+Used for dogfooding the Temporal pipeline before the coordinator auto-trigger is wired up.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.temporal.common.client import async_connect
+
+from products.conversations.backend.models import Ticket
+from products.conversations.backend.temporal.pipeline import SupportReplyInput, SupportReplyWorkflow
+
+
+class Command(BaseCommand):
+ help = "Run the grounded support reply pipeline for a single ticket."
+
+ def add_arguments(self, parser) -> None:
+ parser.add_argument("ticket_id", type=str, help="UUID of the ticket to process")
+ parser.add_argument("--team-id", type=int, required=True)
+
+ def handle(self, *args, **options) -> None:
+ ticket_id: str = options["ticket_id"]
+ team_id: int = options["team_id"]
+
+ if not Ticket.objects.filter(id=ticket_id, team_id=team_id).exists():
+ raise CommandError(f"Ticket {ticket_id} not found for team {team_id}")
+
+ result = asyncio.run(self._run_workflow(team_id, ticket_id))
+ self.stdout.write(self.style.SUCCESS(f"Pipeline result: {result}"))
+
+ async def _run_workflow(self, team_id: int, ticket_id: str) -> str:
+ client = await async_connect()
+ workflow_id = f"support-reply-manual-{ticket_id}"
+ result = await client.execute_workflow(
+ SupportReplyWorkflow.run,
+ SupportReplyInput(team_id=team_id, ticket_id=ticket_id),
+ id=workflow_id,
+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
+ )
+ return result
diff --git a/products/conversations/backend/temporal/__init__.py b/products/conversations/backend/temporal/__init__.py
new file mode 100644
index 000000000000..4ab5b57aa72f
--- /dev/null
+++ b/products/conversations/backend/temporal/__init__.py
@@ -0,0 +1,22 @@
+from products.conversations.backend.temporal.pipeline import (
+ SupportReplyWorkflow,
+ build_context_activity,
+ draft_activity,
+ persist_reply_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ validate_activity,
+)
+
+WORKFLOWS = [
+ SupportReplyWorkflow,
+]
+
+ACTIVITIES = [
+ build_context_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ draft_activity,
+ validate_activity,
+ persist_reply_activity,
+]
diff --git a/products/conversations/backend/temporal/helpers.py b/products/conversations/backend/temporal/helpers.py
new file mode 100644
index 000000000000..11d12c7bfe07
--- /dev/null
+++ b/products/conversations/backend/temporal/helpers.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+from django.db import transaction
+
+import structlog
+
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team
+
+from products.tasks.backend.models import SandboxEnvironment
+
+logger = structlog.get_logger(__name__)
+
+CONVERSATIONS_SUPPORT_REPLY_ENV_NAME = "CONVERSATIONS_SUPPORT_REPLY"
+
+_SANDBOX_DEFAULTS = {
+ "network_access_level": SandboxEnvironment.NetworkAccessLevel.TRUSTED,
+ "private": False,
+ "internal": True,
+}
+
+
+def get_or_create_support_sandbox_env(team_id: int) -> str:
+ """Get or create the sandbox environment for conversations support reply drafting.
+
+ Returns the env ID as a string. Uses update_or_create to reassert policy on every call.
+
+ SandboxEnvironment has no unique constraint on (team_id, name), so concurrent calls
+ can race past the SELECT and both INSERT. We catch MultipleObjectsReturned, keep the
+ oldest row, delete the rest, and retry.
+ """
+ try:
+ env, _ = SandboxEnvironment.objects.update_or_create(
+ team_id=team_id,
+ name=CONVERSATIONS_SUPPORT_REPLY_ENV_NAME,
+ defaults=_SANDBOX_DEFAULTS,
+ )
+ return str(env.id)
+ except SandboxEnvironment.MultipleObjectsReturned:
+ logger.warning(
+ "support_sandbox_env_duplicate_detected",
+ team_id=team_id,
+ name=CONVERSATIONS_SUPPORT_REPLY_ENV_NAME,
+ )
+ with transaction.atomic():
+ dupes = list(
+ SandboxEnvironment.objects.filter(team_id=team_id, name=CONVERSATIONS_SUPPORT_REPLY_ENV_NAME).order_by(
+ "created_at"
+ )
+ )
+ keeper = dupes[0]
+ SandboxEnvironment.objects.filter(id__in=[d.id for d in dupes[1:]]).delete()
+ for key, value in _SANDBOX_DEFAULTS.items():
+ setattr(keeper, key, value)
+ keeper.save(update_fields=list(_SANDBOX_DEFAULTS.keys()))
+ return str(keeper.id)
+
+
+def resolve_user_id_for_support(team_id: int) -> int:
+ """Resolve a user for autonomous sandbox runs — picks the oldest active org member.
+
+ Unlike the Signals resolver, this does NOT require a GitHub integration. The support
+ reply pipeline is autonomous with no human trigger and no repo context.
+ """
+ team = Team.objects.select_related("organization").get(id=team_id)
+ membership = (
+ OrganizationMembership.objects.select_related("user")
+ .filter(organization=team.organization, user__is_active=True)
+ .order_by("id")
+ .first()
+ )
+ if not membership:
+ raise RuntimeError(f"No active users in organization '{team.organization.name}' (team {team.id})")
+ return membership.user_id
diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.py
new file mode 100644
index 000000000000..34356d1e8c79
--- /dev/null
+++ b/products/conversations/backend/temporal/pipeline.py
@@ -0,0 +1,664 @@
+from __future__ import annotations
+
+import json as json_module
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Any
+from uuid import UUID
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+# These modules (Django models, langchain, pydantic models, etc.) are non-deterministic
+# and/or define classes the Temporal workflow sandbox proxies — importing them inside the
+# sandbox crashes workflow validation. Only the activities touch them at runtime, so pass
+# them through the sandbox unmodified.
+with workflow.unsafe.imports_passed_through():
+ import structlog
+ from pydantic import BaseModel, Field
+
+ from posthog.llm.gateway_client import get_async_anthropic_gateway_client
+ from posthog.models.comment import Comment
+ from posthog.models.team.team import Team
+ from posthog.sync import database_sync_to_async
+ from posthog.temporal.common.heartbeat import Heartbeater
+ from posthog.temporal.common.utils import close_db_connections
+
+ from products.business_knowledge.backend.logic import (
+ get_chunks_by_ids,
+ get_document_window,
+ rerank_chunks,
+ search_knowledge_for_team,
+ )
+ from products.business_knowledge.backend.models import KnowledgeChunk
+ from products.conversations.backend.ai.suggest import _build_ticket_context
+ from products.conversations.backend.models import Ticket
+ from products.conversations.backend.temporal.helpers import (
+ get_or_create_support_sandbox_env,
+ resolve_user_id_for_support,
+ )
+ from products.tasks.backend.models import Task
+ from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+ from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
+
+logger = structlog.get_logger(__name__)
+
+MAX_ATTEMPTS = 5
+SCORE_THRESHOLD = 0.5
+RERANK_TOP_K = 5
+RETRIEVE_LIMIT = 15
+DRAFT_POLL_SECONDS = 600
+WIDEN_RADIUS = 3
+
+# Temporal records every activity input/output in workflow history (per-payload limit ~2 MiB,
+# total history limit ~50 MiB). This loop replays ticket_context + chunks into refine/draft/
+# validate across up to MAX_ATTEMPTS iterations, so bound both at the source to keep history
+# small. Downstream prompts already slice harder than these caps, so nothing useful is lost.
+MAX_TICKET_CONTEXT_CHARS = 16000
+MAX_CHUNK_CONTENT_CHARS = 2000
+MAX_CHUNKS = 25
+# The draft's `sources` are model-controlled (count + excerpt length), so bound them before
+# they flow into validate's input and the workflow's best-so-far tracking.
+MAX_SOURCES = 25
+MAX_EXCERPT_CHARS = 1000
+
+# Plain-LLM utility calls (refine, validate) go through the internal LLM gateway via the
+# raw Anthropic SDK — the gateway captures $ai_generation itself, so no langchain wrapper.
+UTILITY_MODEL = "claude-haiku-4-5"
+
+
+def _anthropic_text(message: Any) -> str:
+ """Concatenate the text blocks of an Anthropic Messages response."""
+ return "".join(block.text for block in message.content if getattr(block, "type", None) == "text")
+
+
+# ---------------------------------------------------------------------------
+# Dataclasses for activity I/O
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class SupportReplyInput:
+ team_id: int
+ ticket_id: str
+
+
+@dataclass
+class BuildContextOutput:
+ ticket_context: str
+ ticket_title: str
+
+
+@dataclass
+class RefineQueriesInput:
+ team_id: int
+ ticket_context: str
+ missing: list[str] = field(default_factory=list)
+
+
+@dataclass
+class RefineQueriesOutput:
+ queries: list[str]
+
+
+@dataclass
+class RetrieveInput:
+ team_id: int
+ queries: list[str]
+ prior_citation_chunk_ids: list[str] = field(default_factory=list)
+ widen: bool = False
+
+
+@dataclass
+class RetrieveOutput:
+ # Only chunk ids cross the activity boundary — content is rehydrated from the DB
+ # (deterministic) where it's needed, to keep workflow history small.
+ chunk_ids: list[str]
+
+
+@dataclass
+class DraftInput:
+ team_id: int
+ ticket_context: str
+ chunk_ids: list[str]
+ # Refinement feedback from the previous attempt so the agent improves a good draft
+ # instead of re-rolling blind (which tends to drift to a worse, less-grounded answer).
+ prior_reply: str = ""
+ prior_missing: list[str] = field(default_factory=list)
+
+
+@dataclass
+class DraftOutput:
+ reply: str
+ citations: list[str]
+ confidence: float
+ # Evidence the agent actually relied on (BK chunk or doc URL + supporting excerpt).
+ # Lets validation ground against sources gathered via MCP tools, not just seed chunks.
+ sources: list[dict[str, str]] = field(default_factory=list)
+
+
+@dataclass
+class ValidateInput:
+ team_id: int
+ ticket_context: str
+ reply: str
+ citations: list[str]
+ chunk_ids: list[str]
+ sources: list[dict[str, str]] = field(default_factory=list)
+
+
+@dataclass
+class ValidateOutput:
+ grounded: bool
+ coverage: float
+ confidence: float
+ missing: list[str]
+
+
+@dataclass
+class PersistReplyInput:
+ team_id: int
+ ticket_id: str
+ reply: str
+ citations: list[str]
+ confidence: float
+
+
+class SupportReplySource(BaseModel):
+ ref: str = Field(description="The citation reference: a chunk_id UUID or a documentation URL")
+ excerpt: str = Field(description="The exact text from this source that supports the reply")
+
+
+class SupportReplyDraft(BaseModel):
+ reply: str = Field(description="The drafted reply text")
+ citations: list[str] = Field(description="List of chunk_id UUIDs or doc URLs cited in the reply")
+ confidence: float = Field(description="Confidence score 0-1 that the reply is correct and grounded")
+ sources: list[SupportReplySource] = Field(
+ default_factory=list,
+ description="Every source used, each with the exact supporting excerpt, so the reply can be validated",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Activities
+# ---------------------------------------------------------------------------
+
+
+@close_db_connections
+async def build_context_activity(input: SupportReplyInput) -> BuildContextOutput:
+ """Build the full ticket context string reusing the existing suggest.py helper."""
+ async with Heartbeater():
+ return await database_sync_to_async(_build_context_sync, thread_sensitive=False)(input.team_id, input.ticket_id)
+
+
+def _build_context_sync(team_id: int, ticket_id: str) -> BuildContextOutput:
+ team = Team.objects.get(id=team_id)
+ ticket = Ticket.objects.get(id=ticket_id, team_id=team_id)
+ comments = list(
+ Comment.objects.filter(
+ team_id=team_id,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ )
+ .exclude(item_context__is_private=True)
+ .order_by("created_at")
+ )
+ context = _build_ticket_context(ticket, comments, team)[:MAX_TICKET_CONTEXT_CHARS]
+ title = getattr(ticket, "title", "") or f"Ticket {ticket_id}"
+ return BuildContextOutput(ticket_context=context, ticket_title=title)
+
+
+async def refine_queries_activity(input: RefineQueriesInput) -> RefineQueriesOutput:
+ """Use a lightweight LLM to generate search queries from ticket context + missing gaps."""
+ async with Heartbeater():
+ return await _refine_queries(input.team_id, input.ticket_context, input.missing)
+
+
+async def _refine_queries(team_id: int, ticket_context: str, missing: list[str]) -> RefineQueriesOutput:
+ system = """You are a search query generator for a customer support knowledge base.
+Given a customer ticket and optionally a list of missing information from a previous attempt,
+generate 2-4 concise search queries that would find the most relevant documentation.
+Return ONLY the queries, one per line. No numbering, no explanation."""
+
+ user_parts = [f"Ticket context:\n{ticket_context[:4000]}"]
+ if missing:
+ user_parts.append("\nMissing from previous attempt:\n" + "\n".join(f"- {m}" for m in missing))
+
+ client = get_async_anthropic_gateway_client(product="conversations", team_id=team_id)
+ message = await client.messages.create(
+ model=UTILITY_MODEL,
+ max_tokens=512,
+ system=system,
+ messages=[{"role": "user", "content": "\n".join(user_parts)}],
+ )
+ content = _anthropic_text(message)
+ queries = [line.strip() for line in content.strip().split("\n") if line.strip()]
+ return RefineQueriesOutput(queries=queries[:4] if queries else ["help"])
+
+
+@close_db_connections
+async def retrieve_activity(input: RetrieveInput) -> RetrieveOutput:
+ """Search BK + rerank. On widen attempts, also fetch document windows around prior citations."""
+ async with Heartbeater():
+ return await database_sync_to_async(_retrieve_sync, thread_sensitive=False)(
+ input.team_id, input.queries, input.prior_citation_chunk_ids, input.widen
+ )
+
+
+def _retrieve_sync(
+ team_id: int, queries: list[str], prior_citation_chunk_ids: list[str], widen: bool
+) -> RetrieveOutput:
+ team = Team.objects.select_related("organization").get(id=team_id)
+ all_results = []
+ seen_chunk_ids: set[str] = set()
+
+ for query in queries:
+ results = search_knowledge_for_team(team, query, limit=RETRIEVE_LIMIT)
+ reranked = rerank_chunks(team, query, results, top_k=RERANK_TOP_K)
+ for r in reranked:
+ cid = str(r.chunk_id)
+ if cid not in seen_chunk_ids:
+ seen_chunk_ids.add(cid)
+ all_results.append(r)
+
+ if widen and prior_citation_chunk_ids:
+ for cid_str in prior_citation_chunk_ids[:5]:
+ # Citations can be doc URLs (from the docs-search MCP tool) rather than BK
+ # chunk UUIDs — only BK chunks can be widened via get_document_window, so
+ # skip anything that isn't a UUID instead of treating it as an error.
+ try:
+ chunk_uuid = UUID(cid_str)
+ except ValueError:
+ continue
+ try:
+ # KnowledgeChunk is fail-closed (TeamScopedManager) — scope explicitly
+ # since we're outside any request context (Temporal activity).
+ chunk = KnowledgeChunk.objects.for_team(team_id).get(id=chunk_uuid)
+ window = get_document_window(
+ team_id=team_id,
+ document_id=chunk.document_id,
+ center_ordinal=chunk.ordinal,
+ radius=WIDEN_RADIUS,
+ )
+ for r in window:
+ wid = str(r.chunk_id)
+ if wid not in seen_chunk_ids:
+ seen_chunk_ids.add(wid)
+ all_results.append(r)
+ except Exception:
+ logger.warning("support_reply_widen_failed", chunk_id=cid_str, exc_info=True)
+
+ return RetrieveOutput(chunk_ids=[str(r.chunk_id) for r in all_results[:MAX_CHUNKS]])
+
+
+def _hydrate_chunks(team_id: int, chunk_ids: list[str]) -> list[dict[str, Any]]:
+ """Rehydrate chunk content + context from the DB for the ids passed across the workflow.
+
+ Deterministic re-fetch — keeps content out of Temporal history. Content is capped here
+ (not in the DB) since this is the only place it's materialized for prompts/validation.
+ """
+ results = get_chunks_by_ids(team_id, [UUID(cid) for cid in chunk_ids])
+ return [
+ {
+ "chunk_id": str(r.chunk_id),
+ "document_id": str(r.document_id),
+ "document_title": r.document_title,
+ "heading_path": r.heading_path,
+ "content": r.content[:MAX_CHUNK_CONTENT_CHARS],
+ "source_name": r.source_name,
+ }
+ for r in results
+ ]
+
+
+@close_db_connections
+async def draft_activity(input: DraftInput) -> DraftOutput:
+ """Run a sandbox session with read-only MCP to draft a reply."""
+ async with Heartbeater():
+ return await _draft_async(
+ input.team_id, input.ticket_context, input.chunk_ids, input.prior_reply, input.prior_missing
+ )
+
+
+async def _draft_async(
+ team_id: int,
+ ticket_context: str,
+ chunk_ids: list[str],
+ prior_reply: str = "",
+ prior_missing: list[str] | None = None,
+) -> DraftOutput:
+ chunks = await database_sync_to_async(_hydrate_chunks, thread_sensitive=False)(team_id, chunk_ids)
+ user_id = await database_sync_to_async(resolve_user_id_for_support, thread_sensitive=False)(team_id)
+ env_id = await database_sync_to_async(get_or_create_support_sandbox_env, thread_sensitive=False)(team_id)
+
+ context = CustomPromptSandboxContext(
+ team_id=team_id,
+ user_id=user_id,
+ repository=None,
+ sandbox_environment_id=env_id,
+ # business_knowledge:read → BK search/window MCP tools (team's own knowledge).
+ # project:read → docs-search MCP tool (Inkeep RAG over the official PostHog docs).
+ # Both read-only; persistence happens in a plain activity, so no write scope is needed.
+ posthog_mcp_scopes=["business_knowledge:read", "project:read"],
+ )
+
+ chunks_text = "\n\n".join(
+ f"[chunk_id={c['chunk_id']}] ({c['document_title']} > {c['heading_path']})\n{c['content']}" for c in chunks[:20]
+ )
+
+ refinement = ""
+ if prior_reply:
+ missing_text = "\n".join(f" - {m}" for m in (prior_missing or [])) or " - (none specified)"
+ refinement = f"""
+
+PREVIOUS ATTEMPT (improve this — do NOT start over from scratch):
+{prior_reply[:4000]}
+
+A validator reviewed the previous attempt and flagged these gaps / ungrounded claims:
+{missing_text}
+
+Keep everything in the previous reply that was correct and grounded. Fix the flagged issues by
+searching for sources that close those gaps, and REMOVE any claim you cannot back with a source
+excerpt. Do not introduce new unsupported information."""
+
+ prompt = f"""You are a support agent drafting a reply to a customer ticket.
+
+TICKET CONTEXT:
+{ticket_context[:6000]}
+
+KNOWLEDGE BASE RESULTS:
+{chunks_text[:12000]}{refinement}
+
+INSTRUCTIONS:
+- Draft a helpful, accurate reply to the customer's question.
+- Search for sources before answering. The KNOWLEDGE BASE RESULTS above may be empty — that's expected, so use your tools:
+ - docs-search: searches the official PostHog documentation (https://posthog.com/docs) via Inkeep. This is the best source for questions about PostHog products and features (billing, support, replay, flags, etc.).
+ - business-knowledge-documents-search: searches this team's own business knowledge for team-specific answers.
+- Answer ONLY the customer's actual question. Do not pad the reply with adjacent features, options, or tips the customer didn't ask about — every extra claim is something the validator must verify, and unsupported padding lowers the score.
+- Every factual sentence must be backed by a source. Cite the exact chunk_id UUID for knowledge-base/business-knowledge chunks, or the doc URL for docs-search results.
+- For EVERY citation, also include it in `sources` with the exact supporting excerpt (the snippet of text your tool returned that backs the claim, verbatim). This excerpt is what the validator uses to verify the reply, so do not paraphrase it, and make sure it literally contains the facts your reply states.
+- If, after searching, you still can't find sufficient information to answer, set confidence to 0 and reply with a brief note saying you cannot answer.
+- Be concise, professional, and empathetic.
+- Do NOT make up information — only use what your tools return.
+
+Return your response as a JSON object with keys: reply, citations, confidence, sources (a list of {{ref, excerpt}})."""
+
+ session: MultiTurnSession | None = None
+ try:
+ session, result = await MultiTurnSession.start(
+ prompt,
+ context,
+ model=SupportReplyDraft,
+ step_name="support_reply",
+ origin_product=Task.OriginProduct.SUPPORT_REPLY,
+ internal=True,
+ max_poll_seconds=DRAFT_POLL_SECONDS,
+ )
+ return DraftOutput(
+ reply=result.reply,
+ citations=result.citations,
+ confidence=result.confidence,
+ sources=[{"ref": s.ref, "excerpt": s.excerpt[:MAX_EXCERPT_CHARS]} for s in result.sources[:MAX_SOURCES]],
+ )
+ finally:
+ if session is not None:
+ await session.end()
+
+
+async def validate_activity(input: ValidateInput) -> ValidateOutput:
+ """Validate the draft reply against the source chunks for groundedness and coverage."""
+ async with Heartbeater():
+ return await _validate(
+ input.team_id, input.ticket_context, input.reply, input.citations, input.chunk_ids, input.sources
+ )
+
+
+def _strip_json_fence(text: str) -> str:
+ """Strip a leading/trailing markdown code fence (```json ... ```) the LLM may wrap JSON in."""
+ s = text.strip()
+ if s.startswith("```"):
+ s = s[3:]
+ if s[:4].lower() == "json":
+ s = s[4:]
+ close = s.rfind("```")
+ if close != -1:
+ s = s[:close]
+ return s.strip()
+
+
+async def _validate(
+ team_id: int,
+ ticket_context: str,
+ reply: str,
+ citations: list[str],
+ chunk_ids: list[str],
+ sources: list[dict[str, str]] | None = None,
+) -> ValidateOutput:
+ # Only the cited chunks need rehydrating — fetch their content from the DB by id.
+ cited_ids = [cid for cid in chunk_ids if cid in set(citations)]
+ cited_chunks = await database_sync_to_async(_hydrate_chunks, thread_sensitive=False)(team_id, cited_ids)
+ evidence_parts = [f"[{c['chunk_id']}] {c['content'][:500]}" for c in cited_chunks]
+ # Ground against evidence the agent gathered via MCP tools too (e.g. docs-search URLs),
+ # not just the seed chunks — otherwise docs-based answers always look unsupported.
+ seen_refs = {c["chunk_id"] for c in cited_chunks}
+ for s in sources or []:
+ ref = s.get("ref", "")
+ excerpt = s.get("excerpt", "")
+ if excerpt and ref not in seen_refs:
+ seen_refs.add(ref)
+ evidence_parts.append(f"[{ref}] {excerpt[:500]}")
+ chunks_text = "\n\n".join(evidence_parts)
+
+ system = """You validate whether a support reply is grounded in the provided knowledge base chunks.
+Return a JSON object with these keys:
+- grounded: boolean — is every factual claim in the reply supported by the cited chunks?
+- coverage: float 0-1 — what fraction of the customer's question does the reply address?
+- confidence: float 0-1 — overall confidence the reply is correct and complete.
+- missing: list of strings — topics the customer asked about that are NOT covered by the reply or chunks.
+
+Return ONLY the JSON object, no other text."""
+
+ user_content = f"""TICKET CONTEXT:
+{ticket_context[:3000]}
+
+REPLY:
+{reply}
+
+CITED CHUNKS:
+{chunks_text[:6000]}"""
+
+ client = get_async_anthropic_gateway_client(product="conversations", team_id=team_id)
+ message = await client.messages.create(
+ model=UTILITY_MODEL,
+ max_tokens=1024,
+ system=system,
+ messages=[{"role": "user", "content": user_content}],
+ )
+ content = _anthropic_text(message)
+
+ try:
+ parsed = json_module.loads(_strip_json_fence(content))
+ return ValidateOutput(
+ grounded=bool(parsed.get("grounded", False)),
+ coverage=float(parsed.get("coverage", 0.0)),
+ confidence=float(parsed.get("confidence", 0.0)),
+ missing=list(parsed.get("missing", [])),
+ )
+ except (json_module.JSONDecodeError, ValueError, TypeError):
+ logger.warning("support_reply_validate_parse_failed", raw=str(content)[:200])
+ return ValidateOutput(grounded=False, coverage=0.0, confidence=0.0, missing=["parse_failure"])
+
+
+@close_db_connections
+async def persist_reply_activity(input: PersistReplyInput) -> None:
+ """Persist the validated reply as a private AI comment on the ticket."""
+ async with Heartbeater():
+ await database_sync_to_async(_persist_reply_sync, thread_sensitive=False)(
+ input.team_id, input.ticket_id, input.reply, input.citations, input.confidence
+ )
+
+
+def _persist_reply_sync(team_id: int, ticket_id: str, reply: str, citations: list[str], confidence: float) -> None:
+ Comment.objects.create(
+ team_id=team_id,
+ scope="conversations_ticket",
+ item_id=ticket_id,
+ content=reply,
+ item_context={
+ "author_type": "AI",
+ "is_private": True,
+ "citations": citations,
+ "confidence": confidence,
+ },
+ )
+
+
+# ---------------------------------------------------------------------------
+# Workflow
+# ---------------------------------------------------------------------------
+
+
[email protected](name="support-reply-pipeline")
+class SupportReplyWorkflow:
+ """Grounded self-validating support reply pipeline.
+
+ Loop: refine -> retrieve -> draft -> validate
+ Iterate while validate score < threshold, hard cap MAX_ATTEMPTS.
+ Feed validate.missing back into refine on each iteration.
+ """
+
+ @workflow.run
+ async def run(self, input: SupportReplyInput) -> str:
+ # Build context
+ ctx_output = await workflow.execute_activity(
+ build_context_activity,
+ input,
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ missing: list[str] = []
+ prior_citations: list[str] = []
+ prior_reply: str = ""
+ best_reply: str = ""
+ best_confidence: float = 0.0
+ best_citations: list[str] = []
+ best_missing: list[str] = []
+
+ for attempt in range(MAX_ATTEMPTS):
+ widen = attempt > 0
+
+ # Refine queries
+ refine_output = await workflow.execute_activity(
+ refine_queries_activity,
+ RefineQueriesInput(
+ team_id=input.team_id,
+ ticket_context=ctx_output.ticket_context,
+ missing=missing,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ # Retrieve + rerank
+ retrieve_output = await workflow.execute_activity(
+ retrieve_activity,
+ RetrieveInput(
+ team_id=input.team_id,
+ queries=refine_output.queries,
+ prior_citation_chunk_ids=prior_citations,
+ widen=widen,
+ ),
+ start_to_close_timeout=timedelta(minutes=3),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ # Don't short-circuit on empty in-process retrieval — the draft agent has
+ # read-only MCP tools (PostHog docs via docs-search, the team's business
+ # knowledge) and can find sources itself. Seed chunks are just a head start.
+ if not retrieve_output.chunk_ids:
+ workflow.logger.info("support_reply: no seed chunks; drafting via MCP tools only")
+
+ # Draft via sandbox
+ draft_output = await workflow.execute_activity(
+ draft_activity,
+ DraftInput(
+ team_id=input.team_id,
+ ticket_context=ctx_output.ticket_context,
+ chunk_ids=retrieve_output.chunk_ids,
+ prior_reply=prior_reply,
+ prior_missing=missing,
+ ),
+ start_to_close_timeout=timedelta(minutes=15),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ # Validate
+ validate_output = await workflow.execute_activity(
+ validate_activity,
+ ValidateInput(
+ team_id=input.team_id,
+ ticket_context=ctx_output.ticket_context,
+ reply=draft_output.reply,
+ citations=draft_output.citations,
+ chunk_ids=retrieve_output.chunk_ids,
+ sources=draft_output.sources,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ # Track best-so-far by the validator's confidence (the trusted score, same
+ # signal the threshold gate uses) — not the draft's self-reported confidence —
+ # so an escalated note carries an honest confidence and the best-validated draft.
+ if validate_output.confidence >= best_confidence:
+ best_reply = draft_output.reply
+ best_confidence = validate_output.confidence
+ best_citations = draft_output.citations
+ best_missing = validate_output.missing
+
+ if validate_output.confidence >= SCORE_THRESHOLD:
+ # Persist the reply
+ await workflow.execute_activity(
+ persist_reply_activity,
+ PersistReplyInput(
+ team_id=input.team_id,
+ ticket_id=input.ticket_id,
+ reply=draft_output.reply,
+ citations=draft_output.citations,
+ confidence=validate_output.confidence,
+ ),
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ return f"persisted (confidence={validate_output.confidence:.2f}, attempts={attempt + 1})"
+
+ # Prepare for next iteration: refine the best-validated draft (not necessarily
+ # the last one, which may have drifted) using the gaps the validator found in it.
+ missing = best_missing
+ prior_citations = best_citations
+ prior_reply = best_reply
+
+ # Exhausted attempts — persist best if we have one with non-zero confidence
+ if best_reply and best_confidence > 0:
+ await workflow.execute_activity(
+ persist_reply_activity,
+ PersistReplyInput(
+ team_id=input.team_id,
+ ticket_id=input.ticket_id,
+ reply=best_reply,
+ citations=best_citations,
+ confidence=best_confidence,
+ ),
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ return f"escalated_with_best (confidence={best_confidence:.2f})"
+
+ return "escalated_no_reply"
diff --git a/products/conversations/backend/temporal/tests/__init__.py b/products/conversations/backend/temporal/tests/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/conversations/backend/temporal/tests/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
new file mode 100644
index 000000000000..33667e8f5892
--- /dev/null
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -0,0 +1,432 @@
+from __future__ import annotations
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from parameterized import parameterized
+
+from products.conversations.backend.temporal.pipeline import (
+ MAX_ATTEMPTS,
+ BuildContextOutput,
+ DraftOutput,
+ RefineQueriesOutput,
+ RetrieveOutput,
+ SupportReplyInput,
+ SupportReplyWorkflow,
+ ValidateOutput,
+ build_context_activity,
+ draft_activity,
+ persist_reply_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ validate_activity,
+)
+
+
+def sample_chunk_ids() -> list[str]:
+ return ["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"]
+
+
+def workflow_input() -> SupportReplyInput:
+ return SupportReplyInput(team_id=1, ticket_id="deadbeef-0000-0000-0000-000000000001")
+
+
+PIPELINE_MODULE = "products.conversations.backend.temporal.pipeline"
+
+
+@patch(f"{PIPELINE_MODULE}._persist_reply_sync")
+@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._draft_async", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._retrieve_sync")
+@patch(f"{PIPELINE_MODULE}._refine_queries", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._build_context_sync")
+async def test_workflow_persists_on_high_score(
+ mock_build,
+ mock_refine,
+ mock_retrieve,
+ mock_draft,
+ mock_validate,
+ mock_persist,
+ workflow_input,
+ sample_chunk_ids,
+):
+ from temporalio.testing import WorkflowEnvironment
+ from temporalio.worker import Worker
+
+ mock_build.return_value = BuildContextOutput(ticket_context="Customer asks about setup", ticket_title="Setup help")
+ mock_refine.return_value = RefineQueriesOutput(queries=["how to install"])
+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=sample_chunk_ids)
+ mock_draft.return_value = DraftOutput(
+ reply="You can install via pip.",
+ citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
+ confidence=0.9,
+ )
+ mock_validate.return_value = ValidateOutput(grounded=True, coverage=0.9, confidence=0.85, missing=[])
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue="test-queue",
+ workflows=[SupportReplyWorkflow],
+ activities=[
+ build_context_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ draft_activity,
+ validate_activity,
+ persist_reply_activity,
+ ],
+ ):
+ result = await env.client.execute_workflow(
+ SupportReplyWorkflow.run,
+ workflow_input,
+ id="test-persist-high-score",
+ task_queue="test-queue",
+ )
+
+ assert "persisted" in result
+ assert "confidence=0.85" in result
+ assert "attempts=1" in result
+ mock_persist.assert_called_once()
+
+
+@patch(f"{PIPELINE_MODULE}._persist_reply_sync")
+@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._draft_async", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._retrieve_sync")
+@patch(f"{PIPELINE_MODULE}._refine_queries", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._build_context_sync")
+async def test_workflow_widens_on_low_score(
+ mock_build,
+ mock_refine,
+ mock_retrieve,
+ mock_draft,
+ mock_validate,
+ mock_persist,
+ workflow_input,
+ sample_chunk_ids,
+):
+ from temporalio.testing import WorkflowEnvironment
+ from temporalio.worker import Worker
+
+ mock_build.return_value = BuildContextOutput(ticket_context="Question about pricing", ticket_title="Pricing")
+ mock_refine.return_value = RefineQueriesOutput(queries=["pricing", "plans"])
+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=sample_chunk_ids)
+ mock_draft.return_value = DraftOutput(
+ reply="Here's pricing info.",
+ citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
+ confidence=0.7,
+ )
+
+ validate_count = {"n": 0}
+
+ def validate_side_effect(*args, **kwargs):
+ validate_count["n"] += 1
+ if validate_count["n"] < 3:
+ return ValidateOutput(grounded=False, coverage=0.4, confidence=0.3, missing=["pricing info"])
+ return ValidateOutput(grounded=True, coverage=0.9, confidence=0.8, missing=[])
+
+ mock_validate.side_effect = validate_side_effect
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue="test-queue",
+ workflows=[SupportReplyWorkflow],
+ activities=[
+ build_context_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ draft_activity,
+ validate_activity,
+ persist_reply_activity,
+ ],
+ ):
+ result = await env.client.execute_workflow(
+ SupportReplyWorkflow.run,
+ workflow_input,
+ id="test-widen-low-score",
+ task_queue="test-queue",
+ )
+
+ assert "persisted" in result
+ assert validate_count["n"] == 3
+ assert mock_refine.call_count >= 3
+
+
+@patch(f"{PIPELINE_MODULE}._persist_reply_sync")
+@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._draft_async", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._retrieve_sync")
+@patch(f"{PIPELINE_MODULE}._refine_queries", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._build_context_sync")
+async def test_workflow_escalates_after_max_attempts(
+ mock_build,
+ mock_refine,
+ mock_retrieve,
+ mock_draft,
+ mock_validate,
+ mock_persist,
+ workflow_input,
+ sample_chunk_ids,
+):
+ from temporalio.testing import WorkflowEnvironment
+ from temporalio.worker import Worker
+
+ mock_build.return_value = BuildContextOutput(ticket_context="Complex question", ticket_title="Complex")
+ mock_refine.return_value = RefineQueriesOutput(queries=["complex topic"])
+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=sample_chunk_ids)
+ mock_draft.return_value = DraftOutput(
+ reply="Partial answer.",
+ citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
+ confidence=0.4,
+ )
+ mock_validate.return_value = ValidateOutput(grounded=False, coverage=0.3, confidence=0.2, missing=["everything"])
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue="test-queue",
+ workflows=[SupportReplyWorkflow],
+ activities=[
+ build_context_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ draft_activity,
+ validate_activity,
+ persist_reply_activity,
+ ],
+ ):
+ result = await env.client.execute_workflow(
+ SupportReplyWorkflow.run,
+ workflow_input,
+ id="test-escalate-max-attempts",
+ task_queue="test-queue",
+ )
+
+ assert "escalated_with_best" in result
+ assert mock_validate.call_count == MAX_ATTEMPTS
+ mock_persist.assert_called_once()
+
+
+@patch(f"{PIPELINE_MODULE}._persist_reply_sync")
+@patch(f"{PIPELINE_MODULE}._validate", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._draft_async", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._retrieve_sync")
+@patch(f"{PIPELINE_MODULE}._refine_queries", new_callable=AsyncMock)
+@patch(f"{PIPELINE_MODULE}._build_context_sync")
+async def test_workflow_drafts_via_mcp_when_no_seed_chunks(
+ mock_build,
+ mock_refine,
+ mock_retrieve,
+ mock_draft,
+ mock_validate,
+ mock_persist,
+ workflow_input,
+):
+ from temporalio.testing import WorkflowEnvironment
+ from temporalio.worker import Worker
+
+ mock_build.return_value = BuildContextOutput(ticket_context="Off-topic question", ticket_title="Off-topic")
+ mock_refine.return_value = RefineQueriesOutput(queries=["unrelated"])
+ # Empty seed retrieval must NOT short-circuit — the draft agent has MCP tools and runs anyway.
+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=[])
+ mock_draft.return_value = DraftOutput(reply="I cannot answer this.", citations=[], confidence=0.0)
+ mock_validate.return_value = ValidateOutput(grounded=False, coverage=0.0, confidence=0.0, missing=["everything"])
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue="test-queue",
+ workflows=[SupportReplyWorkflow],
+ activities=[
+ build_context_activity,
+ refine_queries_activity,
+ retrieve_activity,
+ draft_activity,
+ validate_activity,
+ persist_reply_activity,
+ ],
+ ):
+ result = await env.client.execute_workflow(
+ SupportReplyWorkflow.run,
+ workflow_input,
+ id="test-no-chunks-draft-via-mcp",
+ task_queue="test-queue",
+ )
+
+ # Agent ran via MCP but couldn't find anything (confidence 0) → escalates without persisting.
+ assert result == "escalated_no_reply"
+ mock_draft.assert_called()
+ mock_persist.assert_not_called()
+
+
+class TestPersistReplyActivity:
+ def test_creates_private_ai_comment(self):
+ from posthog.models.comment import Comment
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+ from products.conversations.backend.temporal.pipeline import _persist_reply_sync
+
+ org = Organization.objects.create(name="Test Org")
+ team = Team.objects.create(organization=org, name="Test Team")
+
+ _persist_reply_sync(
+ team_id=team.id,
+ ticket_id="test-ticket-id",
+ reply="Here's how to do X.",
+ citations=["chunk-1", "chunk-2"],
+ confidence=0.85,
+ )
+
+ comment = Comment.objects.get(team_id=team.id, item_id="test-ticket-id")
+ assert comment.content == "Here's how to do X."
+ assert comment.scope == "conversations_ticket"
+ assert comment.item_context is not None
+ assert comment.item_context["author_type"] == "AI"
+ assert comment.item_context["is_private"] is True
+ assert comment.item_context["citations"] == ["chunk-1", "chunk-2"]
+ assert comment.item_context["confidence"] == 0.85
+
+
+class TestStripJsonFence:
+ @parameterized.expand(
+ [
+ ("plain_json", '{"grounded": true}', '{"grounded": true}'),
+ ("json_fence", '```json\n{"grounded": true}\n```', '{"grounded": true}'),
+ ("json_fence_no_newline", '```json{"grounded": true}```', '{"grounded": true}'),
+ ("plain_fence", '```\n{"grounded": true}\n```', '{"grounded": true}'),
+ ("uppercase_json", '```JSON\n{"grounded": true}\n```', '{"grounded": true}'),
+ ("with_whitespace", ' ```json\n{"grounded": true}\n``` ', '{"grounded": true}'),
+ (
+ "nested_content",
+ '```json\n{\n "grounded": true,\n "missing": []\n}\n```',
+ '{\n "grounded": true,\n "missing": []\n}',
+ ),
+ (
+ "trailing_text_after_fence",
+ '```json\n{"grounded": true}\n```\n\nHere is a summary.',
+ '{"grounded": true}',
+ ),
+ ]
+ )
+ def test_strips_fence_correctly(self, _name, input_text, expected):
+ from products.conversations.backend.temporal.pipeline import _strip_json_fence
+
+ assert _strip_json_fence(input_text) == expected
+
+
+def _mock_gateway_client(text: str) -> MagicMock:
+ """Build a mock Anthropic gateway client whose messages.create returns `text`."""
+ block = MagicMock()
+ block.type = "text"
+ block.text = text
+ message = MagicMock()
+ message.content = [block]
+ client = MagicMock()
+ client.messages.create = AsyncMock(return_value=message)
+ return client
+
+
+class TestValidateActivity:
+ @parameterized.expand(
+ [
+ (
+ "valid_json",
+ '{"grounded": true, "coverage": 0.8, "confidence": 0.75, "missing": ["deployment details"]}',
+ True,
+ 0.8,
+ 0.75,
+ ["deployment details"],
+ ),
+ (
+ "json_in_fence",
+ '```json\n{"grounded": true, "coverage": 0.9, "confidence": 0.85, "missing": []}\n```',
+ True,
+ 0.9,
+ 0.85,
+ [],
+ ),
+ (
+ "partial_fields",
+ '{"grounded": false, "coverage": 0.5}',
+ False,
+ 0.5,
+ 0.0,
+ [],
+ ),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_parses_llm_response(
+ self,
+ _name,
+ llm_response,
+ expected_grounded,
+ expected_coverage,
+ expected_confidence,
+ expected_missing,
+ ):
+ from products.conversations.backend.temporal.pipeline import _validate
+
+ cited = [{"chunk_id": "chunk-1", "content": "Docker compose deployment guide"}]
+ with (
+ patch(
+ f"{PIPELINE_MODULE}.get_async_anthropic_gateway_client", return_value=_mock_gateway_client(llm_response)
+ ),
+ patch(f"{PIPELINE_MODULE}._hydrate_chunks", return_value=cited),
+ ):
+ result = await _validate(
+ team_id=1,
+ ticket_context="How to deploy?",
+ reply="Use docker compose.",
+ citations=["chunk-1"],
+ chunk_ids=["chunk-1"],
+ )
+
+ assert result.grounded is expected_grounded
+ assert result.coverage == expected_coverage
+ assert result.confidence == expected_confidence
+ assert result.missing == expected_missing
+
+ @parameterized.expand(
+ [
+ ("invalid_json", "not valid json at all"),
+ ("empty_string", ""),
+ ("html_response", "<html><body>Error</body></html>"),
+ ("truncated_json", '{"grounded": true, "coverage":'),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_returns_zero_on_parse_failure(self, _name, llm_response):
+ from products.conversations.backend.temporal.pipeline import _validate
+
+ with (
+ patch(
+ f"{PIPELINE_MODULE}.get_async_anthropic_gateway_client", return_value=_mock_gateway_client(llm_response)
+ ),
+ patch(f"{PIPELINE_MODULE}._hydrate_chunks", return_value=[]),
+ ):
+ result = await _validate(
+ team_id=1,
+ ticket_context="Question",
+ reply="Answer",
+ citations=[],
+ chunk_ids=[],
+ )
+
+ assert result.grounded is False
+ assert result.confidence == 0.0
+ assert "parse_failure" in result.missing
diff --git a/products/tasks/backend/migrations/0038_task_origin_product_conversations_support.py b/products/tasks/backend/migrations/0038_task_origin_product_conversations_support.py
new file mode 100644
index 000000000000..2b9000a0beb0
--- /dev/null
+++ b/products/tasks/backend/migrations/0038_task_origin_product_conversations_support.py
@@ -0,0 +1,29 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ """State-only AlterField — `choices` is enforced at the application layer, no DB-level change."""
+
+ dependencies = [("tasks", "0037_codeworkflowconfig_codeprsnapshot_codeworkstream")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="task",
+ name="origin_product",
+ field=models.CharField(
+ choices=[
+ ("error_tracking", "Error Tracking"),
+ ("eval_clusters", "Eval Clusters"),
+ ("user_created", "User Created"),
+ ("automation", "Automation"),
+ ("slack", "Slack"),
+ ("support_queue", "Support Queue"),
+ ("session_summaries", "Session Summaries"),
+ ("signal_report", "Signal Report"),
+ ("signals_scout", "Signals Scout"),
+ ("support_reply", "Support Reply"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 6f8b9e4bc09c..b71f7634fd25 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0037_codeworkflowconfig_codeprsnapshot_codeworkstream
+0038_task_origin_product_conversations_support
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 6dc6a976bf2f..c91daab0a281 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -70,6 +70,8 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
SIGNAL_REPORT = "signal_report", "Signal Report"
# Headless Signals scout — proactively explores a project and emits signals.
SIGNALS_SCOUT = "signals_scout", "Signals Scout"
+ # Conversations support reply pipeline — autonomous grounded draft replies.
+ SUPPORT_REPLY = "support_reply", "Support Reply"
# nosemgrep: prefer-uuid7-django-pk -- TODO: migrate to uuid7 or clarify intent
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 3a6c8b314331..b9efe62f49cf 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -297,6 +297,7 @@ export interface PatchedTaskAutomationApi {
* * `session_summaries` - Session Summaries
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply
*/
export type OriginProductEnumApi = (typeof OriginProductEnumApi)[keyof typeof OriginProductEnumApi]
@@ -310,6 +311,7 @@ export const OriginProductEnumApi = {
SessionSummaries: 'session_summaries',
SignalReport: 'signal_report',
SignalsScout: 'signals_scout',
+ SupportReply: 'support_reply',
} as const
/**
@@ -351,7 +353,8 @@ export interface TaskApi {
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
* * `signal_report` - Signal Report
- * * `signals_scout` - Signals Scout */
+ * * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply */
origin_product?: OriginProductEnumApi
/**
* Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
@@ -433,7 +436,8 @@ export interface PatchedTaskApi {
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
* * `signal_report` - Signal Report
- * * `signals_scout` - Signals Scout */
+ * * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply */
origin_product?: OriginProductEnumApi
/**
* Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index a6eaf83b1674..7d090faf20ba 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -206,13 +206,14 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
'session_summaries',
'signal_report',
'signals_scout',
+ 'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout'
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
@@ -275,13 +276,14 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.object({
'session_summaries',
'signal_report',
'signals_scout',
+ 'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout'
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
@@ -344,13 +346,14 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
'session_summaries',
'signal_report',
'signals_scout',
+ 'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout'
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index a6a8cef80249..a141e87c3c63 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -151,6 +151,12 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
allowed_models=frozenset({"gpt-4.1-mini"}),
allow_api_keys=True,
),
+ "conversations": ProductConfig(
+ allowed_application_ids=None,
+ allowed_models=frozenset({"claude-haiku-4-5"}),
+ allow_api_keys=True,
+ billable=False,
+ ),
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bf1454127d88..1828a5171bbc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27954,6 +27954,7 @@ export namespace Schemas {
* * `session_summaries` - Session Summaries
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply
*/
export type OriginProductEnum = typeof OriginProductEnum[keyof typeof OriginProductEnum];
@@ -27968,6 +27969,7 @@ export namespace Schemas {
SessionSummaries: 'session_summaries',
SignalReport: 'signal_report',
SignalsScout: 'signals_scout',
+ SupportReply: 'support_reply',
} as const;
/**
@@ -31209,7 +31211,8 @@ export namespace Schemas {
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
* * `signal_report` - Signal Report
- * * `signals_scout` - Signals Scout */
+ * * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply */
origin_product?: OriginProductEnum;
/**
* Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
@@ -38085,7 +38088,8 @@ export namespace Schemas {
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
* * `signal_report` - Signal Report
- * * `signals_scout` - Signals Scout */
+ * * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply */
origin_product?: OriginProductEnum;
/**
* Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
diff --git a/tach.toml b/tach.toml
index efa76a0aeb7c..32ecaa07254c 100644
--- a/tach.toml
+++ b/tach.toml
@@ -185,7 +185,7 @@ path = "products.conversations"
depends_on = [
"ee",
"posthog",
- "products.posthog_ai",
+ "products.posthog_ai", "products.tasks", "products.business_knowledge",
]
layer = "modules"