:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): structured investigation verdict and blocker-awa… (#101128)
Alex V186d397ef0cf
diff --git a/products/conversations/backend/api/tests/test_ticket_views.py b/products/conversations/backend/api/tests/test_ticket_views.pyindex f31fe428fd75..5c2193f1794c 100644--- a/products/conversations/backend/api/tests/test_ticket_views.py+++ b/products/conversations/backend/api/tests/test_ticket_views.py@@ -330,7 +330,7 @@ class TestTicketViewFiltersValidation(SimpleTestCase):"priority": ["high", "critical"],"channel": "email","sla": "at-risk",- "aiTriageResult": ["escalated_no_reply", "in_progress"],+ "aiTriageResult": ["escalated_no_reply", "in_progress", "suggested", "escalated_with_findings"],"assignee": ["me", "unassigned", {"type": "user", "id": 1}, {"type": "role", "id": "abc"}],"tags": ["billing"],"tagsMatch": "all",diff --git a/products/conversations/backend/api/ticket_filters.py b/products/conversations/backend/api/ticket_filters.pyindex 4159c220db20..b85d0959bd0c 100644--- a/products/conversations/backend/api/ticket_filters.py+++ b/products/conversations/backend/api/ticket_filters.py@@ -40,6 +40,8 @@ MAX_SEARCH_LENGTH = 200SLA_FILTER_VALUES = ["breached", "at-risk", "on-track"]AI_TRIAGE_FILTER_VALUES = ["persisted",+ "suggested",+ "escalated_with_findings","escalated_with_best","escalated_no_reply","skipped_unactionable",@@ -182,7 +184,9 @@ class TicketViewFiltersSerializer(serializers.Serializer):aiTriageResult = serializers.ListField(child=serializers.ChoiceField(choices=AI_TRIAGE_FILTER_VALUES),required=False,- help_text="AI triage outcomes to include. 'in_progress' matches tickets still being triaged.",+ help_text="AI triage outcomes to include. 'in_progress' matches tickets still being triaged. "+ "Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, "+ "escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress.",)assignee = TicketViewAssigneeFilterField(required=False,diff --git a/products/conversations/backend/temporal/ai_reply/activities/draft.py b/products/conversations/backend/temporal/ai_reply/activities/draft.pyindex 340848e15213..c64b9ab07486 100644--- a/products/conversations/backend/temporal/ai_reply/activities/draft.py+++ b/products/conversations/backend/temporal/ai_reply/activities/draft.py@@ -19,10 +19,15 @@ from products.conversations.backend.temporal.ai_reply.constants import (DRAFT_MODEL,DRAFT_POLL_SECONDS,DRAFT_RUNTIME_ADAPTER,+ DRAFT_VERDICTS,MAX_CHUNK_CONTENT_CHARS,+ MAX_CLARIFYING_QUESTIONS,MAX_EXCERPT_CHARS,+ MAX_INVESTIGATION_SUMMARY_CHARS,MAX_SAFETY_REVIEWED_CHARS,MAX_SOURCES,+ MAX_UNKNOWN_CHARS,+ MAX_UNKNOWNS,PUBLISHABLE_DRAFT_SCOPES,TICKET_TYPE_HINTS,)@@ -55,6 +60,17 @@ def _hydrate_chunks(team_id: int, chunk_ids: list[str]) -> list[dict[str, Any]]:]+def _bounded_unknowns(unknowns: list[str]) -> list[str]:+ trimmed: list[str] = []+ for item in unknowns:+ text = item.strip()[:MAX_UNKNOWN_CHARS]+ if text:+ trimmed.append(text)+ if len(trimmed) >= MAX_UNKNOWNS:+ break+ return trimmed++@activity.defn@close_db_connectionsasync def support_draft_activity(input: DraftInput) -> DraftOutput:@@ -195,15 +211,19 @@ KNOWLEDGE BASE RESULTS:TICKET TYPE: {input.ticket_type} — {TICKET_TYPE_HINTS.get(input.ticket_type, "")}{data_safety_block}{diagnostic_block}INSTRUCTIONS:-- Draft a helpful, accurate reply to the customer's question. Lead with the answer, be concise and friendly.+- PLAN first: list what you need to know, which tools answer each of those questions, then execute that plan before you draft.+- If a fact you need can only come from the customer, do not guess. Set verdict=blocked_on_customer, put the one question that unblocks you in clarifying_questions, and put what you already checked in investigation_summary.+- If the knowledge base and docs do not cover the question, set verdict=blocked_on_knowledge.+- If the ticket is not a support question this team can answer, set verdict=out_of_scope.+- If verdict is answerable, draft a helpful, accurate reply. Lead with the answer, be concise and friendly.+- If verdict is not answerable, do not write an answer to send. Keep reply to one short sentence and put what you checked in investigation_summary.- The KNOWLEDGE BASE RESULTS above are a starting point, not a ceiling. Use your tools to search for additional information:- docs-search: searches the official PostHog documentation (https://posthog.com/docs) via Inkeep. Best for product features, billing, setup, SDKs, APIs, etc.- business-knowledge-documents-search: searches this team's own business knowledge for team-specific answers.{config_tools_block}- Ground your reply in sources. Include citations (chunk_id UUIDs or doc URLs) and populate `sources` with the supporting excerpts so the reply can be validated.-- If you cannot find sufficient information after searching, set confidence to 0 and reply with a brief note saying you cannot answer.- 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}})."""+Return your response as a JSON object with keys: reply, citations, confidence, sources (a list of {{ref, excerpt}}), verdict, clarifying_questions, investigation_summary, unknowns."""session: MultiTurnSession | None = Nonestarted = monotonic()@@ -225,6 +245,10 @@ Return your response as a JSON object with keys: reply, citations, confidence, ssources=[{"ref": s.ref, "excerpt": s.excerpt[:MAX_EXCERPT_CHARS]} for s in result.sources[:MAX_SOURCES]],task_run_id=str(session.task_run.id),sandbox_seconds=monotonic() - started,+ verdict=result.verdict if result.verdict in DRAFT_VERDICTS else "blocked_on_knowledge",+ clarifying_questions=[q for q in result.clarifying_questions if q][:MAX_CLARIFYING_QUESTIONS],+ investigation_summary=result.investigation_summary[:MAX_INVESTIGATION_SUMMARY_CHARS],+ unknowns=_bounded_unknowns(result.unknowns),)finally:if session is not None:diff --git a/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py b/products/conversations/backend/temporal/ai_reply/activities/persist_reply.pyindex 05102205ba89..3b40ad5e1fee 100644--- a/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py+++ b/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py@@ -11,7 +11,8 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.conversations.backend.models import Ticketfrom products.conversations.backend.temporal.ai_reply.constants import PUBLISHABLE_TICKET_TYPES-from products.conversations.backend.temporal.ai_reply.schemas import PersistReplyInput+from products.conversations.backend.temporal.ai_reply.gate import format_findings_comment+from products.conversations.backend.temporal.ai_reply.schemas import PersistReplyInput, coerce_dataclass@activity.defn@@ -23,11 +24,13 @@ async def support_persist_reply_activity(input: PersistReplyInput) -> None:def _persist_reply_sync(input: PersistReplyInput) -> None:+ input = coerce_dataclass(PersistReplyInput, input)+ persist_as = input.persist_asis_private = True# Only how_to replies may be published. diagnostic/account_billing draw on project data and# must stay private regardless of the team's ai_reply_modes — guards against stale settings# since validation now rejects bot_reply for those types. Controlled by team-level opt-in.- if input.allow_bot_reply and input.ticket_type in PUBLISHABLE_TICKET_TYPES:+ if persist_as != "findings" and input.allow_bot_reply and input.ticket_type in PUBLISHABLE_TICKET_TYPES:ticket = Ticket.objects.select_related("team").filter(team_id=input.team_id, id=input.ticket_id).first()if ticket:settings_dict = ticket.team.conversations_settings or {}@@ -37,17 +40,33 @@ def _persist_reply_sync(input: PersistReplyInput) -> None:if mode == "bot_reply":is_private = False+ content = input.reply+ item_context: dict[str, object] = {+ "author_type": "AI",+ "is_private": is_private,+ "citations": input.citations,+ "confidence": input.confidence,+ "persist_as": persist_as,+ }+ if persist_as == "findings":+ content = format_findings_comment(+ investigation_summary=input.investigation_summary,+ unknowns=input.unknowns,+ clarifying_questions=input.clarifying_questions,+ findings_reason=input.findings_reason,+ citations=input.citations,+ )+ item_context["investigation_summary"] = input.investigation_summary+ item_context["unknowns"] = input.unknowns+ item_context["clarifying_questions"] = input.clarifying_questions+ item_context["findings_reason"] = input.findings_reason+# ATOMIC_REQUESTS is off, so wrap the comment insert with the email-outbox write.with transaction.atomic():Comment.objects.create(team_id=input.team_id,scope="conversations_ticket",item_id=input.ticket_id,- content=input.reply,- item_context={- "author_type": "AI",- "is_private": is_private,- "citations": input.citations,- "confidence": input.confidence,- },+ content=content,+ item_context=item_context,)diff --git a/products/conversations/backend/temporal/ai_reply/activities/validate.py b/products/conversations/backend/temporal/ai_reply/activities/validate.pyindex adb982b163a0..84c1d0122cee 100644--- a/products/conversations/backend/temporal/ai_reply/activities/validate.py+++ b/products/conversations/backend/temporal/ai_reply/activities/validate.py@@ -11,7 +11,15 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeaterfrom products.conversations.backend.temporal.ai_reply.activities.draft import _hydrate_chunks-from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYPE_HINTS, VALIDATOR_MODEL+from products.conversations.backend.temporal.ai_reply.constants import (+ MAX_CHUNK_CONTENT_CHARS,+ MAX_EXCERPT_CHARS,+ MAX_SAFETY_REVIEWED_CHARS,+ MAX_VALIDATE_EVIDENCE_CHARS,+ TICKET_TYPE_HINTS,+ VALIDATE_BLOCKERS,+ VALIDATOR_MODEL,+)from products.conversations.backend.temporal.ai_reply.llms import (anthropic_text,create_message,@@ -35,7 +43,7 @@ async def _validate(input: ValidateInput) -> ValidateOutput:# Only the cited chunks need rehydrating — fetch their content from the DB by id.cited_ids = [cid for cid in input.chunk_ids if cid in set(input.citations)]cited_chunks = await database_sync_to_async(_hydrate_chunks, thread_sensitive=False)(input.team_id, cited_ids)- evidence_parts = [f"[{c['chunk_id']}] {c['content'][:500]}" for c in cited_chunks]+ evidence_parts = [f"[{c['chunk_id']}] {c['content'][:MAX_CHUNK_CONTENT_CHARS]}" 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}@@ -44,8 +52,8 @@ async def _validate(input: ValidateInput) -> ValidateOutput: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)+ evidence_parts.append(f"[{ref}] {excerpt[:MAX_EXCERPT_CHARS]}")+ chunks_text = "\n\n".join(evidence_parts)[:MAX_VALIDATE_EVIDENCE_CHARS]type_hint = TICKET_TYPE_HINTS.get(input.ticket_type, "")system = f"""You validate whether a support reply is grounded in the provided knowledge base chunks.@@ -57,17 +65,22 @@ Return a JSON object with these keys:- 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.+- blocker: one of none, customer_info, knowledge, contradiction.+ none: the reply can be judged on groundedness and coverage alone.+ customer_info: a fact only the customer can provide is missing (SDK, project, error text).+ knowledge: docs and the knowledge base do not cover what was asked.+ contradiction: the reply asserts something the sources refute.Return ONLY the JSON object, no other text."""user_content = f"""TICKET CONTEXT:-{input.ticket_context[:3000]}+{input.ticket_context[:MAX_SAFETY_REVIEWED_CHARS]}REPLY:{input.reply}CITED CHUNKS:-{chunks_text[:6000]}"""+{chunks_text}"""client = get_async_anthropic_gateway_client(product="conversations", team_id=input.team_id)message = await create_message(@@ -82,12 +95,18 @@ CITED CHUNKS:try:parsed = json_module.loads(strip_json_fence(content))+ blocker = parsed.get("blocker", "knowledge")+ if blocker not in VALIDATE_BLOCKERS:+ blocker = "knowledge"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", [])),+ blocker=blocker,)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"])+ return ValidateOutput(+ grounded=False, coverage=0.0, confidence=0.0, missing=["parse_failure"], blocker="knowledge"+ )diff --git a/products/conversations/backend/temporal/ai_reply/constants.py b/products/conversations/backend/temporal/ai_reply/constants.pyindex 10f91670b1c8..f6376437f902 100644--- a/products/conversations/backend/temporal/ai_reply/constants.py+++ b/products/conversations/backend/temporal/ai_reply/constants.py@@ -1,14 +1,29 @@from typing import Literalfrom uuid import UUID-MAX_ATTEMPTS = 5+MAX_ATTEMPTS = 2+# Replay of histories without BLOCKER_AWARE_LOOP_PATCH must iterate this many times so the+# recorded refine/draft/validate command count matches.+LEGACY_MAX_ATTEMPTS = 5# Histories without this marker must retain the legacy persistence command during replay.DEFER_KNOWLEDGE_GAPS_UNTIL_RESOLUTION_PATCH = "defer-knowledge-gaps-until-resolution-2026-09"+# Histories without this marker must retain the LEGACY_MAX_ATTEMPTS SCORE_THRESHOLD loop.+BLOCKER_AWARE_LOOP_PATCH = "blocker-aware-loop-2026-09"# Stable namespace for deterministic per-ticket trace ids (uuid5).AI_REPLY_TRACE_NAMESPACE = UUID("a1b2c3d4-5678-4e9f-ab12-cd34ef567890")+# Gate used when BLOCKER_AWARE_LOOP_PATCH is absent. Replay of those histories still+# compares validator confidence to this value.SCORE_THRESHOLD = 0.5+# Validator and draft are uncalibrated judges, so auto-send requires both plus coverage and grounding.+AUTO_SEND_THRESHOLD = 0.85+AUTO_SEND_MIN_COVERAGE = 0.8+DRAFT_SELF_CONFIDENCE_FLOOR = 0.7+SUGGEST_THRESHOLD = 0.5++DRAFT_VERDICTS = ("answerable", "blocked_on_customer", "blocked_on_knowledge", "out_of_scope")+VALIDATE_BLOCKERS = ("none", "customer_info", "knowledge", "contradiction")RERANK_TOP_K = 5# Ticket types whose replies may ever be published to the (untrusted) ticket author.# diagnostic/account_billing draw on project data and must stay private regardless of settings.@@ -24,10 +39,17 @@ WIDEN_RADIUS = 3MAX_TICKET_CONTEXT_CHARS = 16000MAX_CHUNK_CONTENT_CHARS = 2000MAX_CHUNKS = 25+# Per-item caps still apply. This bound keeps one validation prompt from carrying every+# cited chunk plus every source excerpt at those caps.+MAX_VALIDATE_EVIDENCE_CHARS = 12000# 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 = 25MAX_EXCERPT_CHARS = 1000+MAX_INVESTIGATION_SUMMARY_CHARS = 4000+MAX_UNKNOWNS = 10+MAX_UNKNOWN_CHARS = 300+MAX_CLARIFYING_QUESTIONS = 2# The safety filter and draft prompt must review/consume the exact same ticket text. This# constant is the single source of truth for that window; the workflow slices once and passes# the result to both activities so there's no mismatch.diff --git a/products/conversations/backend/temporal/ai_reply/gate.py b/products/conversations/backend/temporal/ai_reply/gate.pynew file mode 100644index 000000000000..58813646591a--- /dev/null+++ b/products/conversations/backend/temporal/ai_reply/gate.py@@ -0,0 +1,117 @@+from __future__ import annotations++from typing import Literal++from products.conversations.backend.temporal.ai_reply.constants import (+ AUTO_SEND_MIN_COVERAGE,+ AUTO_SEND_THRESHOLD,+ DRAFT_SELF_CONFIDENCE_FLOOR,+ MAX_CLARIFYING_QUESTIONS,+ SUGGEST_THRESHOLD,+)++ReplyAction = Literal["auto_send", "retry", "clarify", "suggest", "findings"]++FINDINGS_WITHHELD_REASON = "Investigation notes withheld because they contained sensitive data."++_FINDINGS_BLOCKERS = frozenset({"contradiction", "customer_info", "knowledge"})+_FINDINGS_VERDICTS = frozenset({"out_of_scope", "blocked_on_customer", "blocked_on_knowledge"})+++def decide_reply_action(+ *,+ grounded: bool,+ coverage: float,+ validator_confidence: float,+ draft_confidence: float,+ blocker: str,+ verdict: str,+ attempt: int,+ max_attempts: int,+) -> ReplyAction:+ # Either judge alone can be overconfident, so a public reply needs both plus coverage.+ if (+ grounded+ and coverage >= AUTO_SEND_MIN_COVERAGE+ and validator_confidence >= AUTO_SEND_THRESHOLD+ and draft_confidence >= DRAFT_SELF_CONFIDENCE_FLOOR+ and blocker == "none"+ and verdict == "answerable"+ ):+ return "auto_send"+ if blocker == "customer_info" or verdict == "blocked_on_customer":+ return "clarify"+ if blocker == "contradiction" or verdict == "out_of_scope":+ return "findings"+ # Retry only on a validator knowledge gap. The draft verdict is not a retry signal.+ if blocker == "knowledge":+ if attempt < max_attempts - 1:+ return "retry"+ return "findings"+ # The agent said it could not answer. Do not present that draft as a proposed reply.+ if verdict == "blocked_on_knowledge":+ return "findings"+ if blocker == "none" and verdict == "answerable" and grounded and validator_confidence >= SUGGEST_THRESHOLD:+ return "suggest"+ return "findings"+++def findings_reason_for(*, blocker: str, verdict: str, grounded: bool) -> str:+ if blocker == "contradiction":+ return "This answer contradicts the cited sources, so it was not sent."+ if verdict == "out_of_scope":+ return "This ticket is outside what support can answer."+ if blocker == "customer_info" or verdict == "blocked_on_customer":+ return "Need more information from the customer."+ if blocker == "knowledge" or verdict == "blocked_on_knowledge":+ return "The knowledge base and docs did not cover this."+ if not grounded:+ return "This draft does not match the sources, so it was not sent."+ return "This draft was not confident enough to propose as a reply."+++def should_persist_findings(+ *,+ investigation_summary: str,+ unknowns: list[str],+ clarifying_questions: list[str],+ citations: list[str],+ blocker: str,+ verdict: str,+) -> bool:+ if investigation_summary.strip() or unknowns or clarifying_questions or citations:+ return True+ return blocker in _FINDINGS_BLOCKERS or verdict in _FINDINGS_VERDICTS+++def format_findings_comment(+ *,+ investigation_summary: str,+ unknowns: list[str],+ clarifying_questions: list[str],+ findings_reason: str = "",+ citations: list[str] | None = None,+) -> str:+ # Format here so PersistReplyInput.reply is investigation notes even if persist_as+ # is ignored during a rolling deploy.+ parts = ["Investigation notes"]+ if findings_reason:+ parts.extend(["", findings_reason])+ if investigation_summary:+ parts.extend(["", investigation_summary])+ if unknowns:+ parts.extend(["", "Still unknown:"])+ parts.extend(f"- {item}" for item in unknowns)+ if clarifying_questions:+ heading = (+ "Suggested questions for the customer:"+ if len(clarifying_questions) > 1+ else "Suggested question for the customer:"+ )+ parts.extend(["", heading])+ parts.extend(f"- {item}" for item in clarifying_questions[:MAX_CLARIFYING_QUESTIONS])+ refs = [ref for ref in (citations or []) if ref]+ if refs:+ parts.extend(["", "Sources:"])+ parts.extend(f"- {ref}" for ref in refs)+ return "\n".join(parts)diff --git a/products/conversations/backend/temporal/ai_reply/schemas.py b/products/conversations/backend/temporal/ai_reply/schemas.pyindex e983b1ef4c44..7d17d53cbf68 100644--- a/products/conversations/backend/temporal/ai_reply/schemas.py+++ b/products/conversations/backend/temporal/ai_reply/schemas.py@@ -8,9 +8,32 @@ structured LLM response schemas used by the draft sandbox step.from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, Literal, TypeVar-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validator++from products.conversations.backend.temporal.ai_reply.constants import DRAFT_VERDICTS, MAX_CLARIFYING_QUESTIONS++_T = TypeVar("_T")+++def coerce_dataclass(cls: type[_T], value: object) -> _T:+ """Rebuild a dataclass from a typed instance or a raw dict.++ Temporal's converter usually applies field defaults, but a rolling deploy can+ deliver an activity payload as a dict. Reconstructing here fills omitted fields+ and drops unknown keys so gating can read verdict/blocker without AttributeError.+ """+ if isinstance(value, cls):+ return value+ if isinstance(value, dict):+ known = set(getattr(cls, "__dataclass_fields__", {}))+ kwargs = {key: val for key, val in value.items() if key in known and val is not None}+ try:+ return cls(**kwargs)+ except TypeError as exc:+ raise TypeError(f"Could not coerce into {cls.__name__} (keys={sorted(value)}): {exc}") from exc+ raise TypeError(f"Unexpected type {type(value).__name__}; expected {cls.__name__} or dict")@dataclass@@ -114,9 +137,13 @@ class DraftOutput:sources: list[dict[str, str]] = field(default_factory=list)# The Tasks TaskRun id for this draft session -- join key to LLMA cost data.task_run_id: str = ""- # Wall time of the sandbox session, recorded for ai_triage.cost. Defaults so- # histories from before this field still deserialize.+ # Wall time of the sandbox session, recorded for ai_triage.cost.sandbox_seconds: float = 0.0+ # Default blocked_on_knowledge so a missing verdict cannot auto-send.+ verdict: str = "blocked_on_knowledge"+ clarifying_questions: list[str] = field(default_factory=list)+ investigation_summary: str = ""+ unknowns: list[str] = field(default_factory=list)@dataclass@@ -139,9 +166,11 @@ class ValidateOutput:confidence: floatmissing: list[str]llm_attempts: int = 1+ # Default knowledge so a missing blocker cannot auto-send.+ blocker: str = "knowledge"-@dataclass+@dataclass(frozen=False)class PersistReplyInput:team_id: intticket_id: str@@ -150,6 +179,11 @@ class PersistReplyInput:confidence: floatticket_type: str = "how_to"allow_bot_reply: bool = False+ persist_as: Literal["reply", "findings"] = "reply"+ investigation_summary: str = ""+ unknowns: list[str] = field(default_factory=list)+ clarifying_questions: list[str] = field(default_factory=list)+ findings_reason: str = ""@dataclass@@ -215,3 +249,33 @@ class SupportReplyDraft(BaseModel):default_factory=list,description="Every source used, each with the exact supporting excerpt, so the reply can be validated",)+ verdict: Literal["answerable", "blocked_on_customer", "blocked_on_knowledge", "out_of_scope"] = Field(+ default="blocked_on_knowledge",+ description="Whether the ticket can be answered now, or what blocks an answer",+ )+ clarifying_questions: list[str] = Field(+ default_factory=list,+ description="At most two questions that would unblock a blocked_on_customer verdict",+ )+ investigation_summary: str = Field(+ default="",+ description="What was checked and found, for a human reading a private note",+ )+ unknowns: list[str] = Field(+ default_factory=list,+ description="Facts that remain unknown after the investigation",+ )++ @field_validator("verdict", mode="before")+ @classmethod+ def _coerce_verdict(cls, value: object) -> str:+ if isinstance(value, str) and value in DRAFT_VERDICTS:+ return value+ return "blocked_on_knowledge"++ @field_validator("clarifying_questions", mode="before")+ @classmethod+ def _cap_clarifying_questions(cls, value: object) -> list[str]:+ if not isinstance(value, list):+ return []+ return [str(item) for item in value if item][:MAX_CLARIFYING_QUESTIONS]diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.pyindex 04eb669889fe..513562328ea4 100644--- a/products/conversations/backend/temporal/pipeline.py+++ b/products/conversations/backend/temporal/pipeline.py@@ -1,5 +1,6 @@from __future__ import annotations+from dataclasses import replacefrom datetime import timedeltafrom typing import Anyfrom uuid import uuid5@@ -23,14 +24,24 @@ from products.conversations.backend.temporal.ai_reply.activities.safety_filter ifrom products.conversations.backend.temporal.ai_reply.activities.validate import support_validate_activityfrom products.conversations.backend.temporal.ai_reply.constants import (AI_REPLY_TRACE_NAMESPACE,+ BLOCKER_AWARE_LOOP_PATCH,DEFER_KNOWLEDGE_GAPS_UNTIL_RESOLUTION_PATCH,+ LEGACY_MAX_ATTEMPTS,MAX_ATTEMPTS,MAX_SAFETY_REVIEWED_CHARS,SCORE_THRESHOLD,)+from products.conversations.backend.temporal.ai_reply.gate import (+ FINDINGS_WITHHELD_REASON,+ decide_reply_action,+ findings_reason_for,+ format_findings_comment,+ should_persist_findings,+)from products.conversations.backend.temporal.ai_reply.schemas import (ClassifyInput,DraftInput,+ DraftOutput,PersistKnowledgeGapInput,PersistReplyInput,RecordTriageInput,@@ -40,6 +51,8 @@ from products.conversations.backend.temporal.ai_reply.schemas import (SafetyFilterInput,SupportReplyInput,ValidateInput,+ ValidateOutput,+ coerce_dataclass,)# These modules (Django models, langchain, pydantic models, etc.) are non-deterministic@@ -68,8 +81,9 @@ 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.+ Iterate while the current gate says retry, hard cap MAX_ATTEMPTS (2) when+ BLOCKER_AWARE_LOOP_PATCH is present. Without that marker, replay uses+ LEGACY_MAX_ATTEMPTS and SCORE_THRESHOLD so the recorded command count matches.Triage lifecycle (`ai_triage.status`), recorded via `_record_triage`:- in_progress: run started, context built, draft loop not yet terminal.@@ -82,14 +96,18 @@ class SupportReplyWorkflow:- skipped_unactionable: classifier judged the ticket has no answerablequestion (spam / bare feedback); draft loop skipped. Distinct fromescalated_no_reply, which means we tried and failed.- - persisted: a draft cleared SCORE_THRESHOLD and passed the output review- gate; auto-sent to the customer (allow_bot_reply=True).+ - persisted: a draft cleared the auto-send gate (or SCORE_THRESHOLD when+ BLOCKER_AWARE_LOOP_PATCH is absent) and passed the output review gate;+ auto-sent to the customer (allow_bot_reply=True).+ - suggested: grounded private note with a proposed reply, below auto-send.- blocked_unsafe_reply: a draft was good enough to send but the outputreview gate caught a PII leak / exfil, so it was withheld.- - escalated_with_best: exhausted MAX_ATTEMPTS without clearing the- threshold, but the best draft (>0 confidence) passed output review and- was saved as an internal/human-gated note (allow_bot_reply=False).- - escalated_no_reply: exhausted MAX_ATTEMPTS with no usable draft at all;+ - escalated_with_findings: investigation notes only, never a reply+ presented as an answer.+ - escalated_with_best: histories without BLOCKER_AWARE_LOOP_PATCH: best+ draft (>0 confidence) saved as an internal/human-gated note+ (allow_bot_reply=False). Replay only.+ - escalated_no_reply: exhausted attempts with no usable draft or findings;nothing persisted, ticket handed to a human cold."""@@ -226,8 +244,31 @@ class SupportReplyWorkflow:best_citations: list[str] = []best_sources: list[dict[str, str]] = []best_missing: list[str] = []+ last_draft = None+ last_validate = None+ attempts_used = 0+ blocker_aware = workflow.patched(BLOCKER_AWARE_LOOP_PATCH)+ max_attempts = MAX_ATTEMPTS if blocker_aware else LEGACY_MAX_ATTEMPTS++ def _base_triage() -> dict[str, Any]:+ return {+ "ticket_type": ticket_type,+ "needs_diagnostics": needs_diagnostics,+ "diagnostics_allowed": ctx_output.diagnostics_allowed,+ }++ def _judge_triage(draft: DraftOutput, validate: ValidateOutput) -> dict[str, Any]:+ return {+ "verdict": draft.verdict,+ "blocker": validate.blocker,+ "draft_confidence": draft.confidence,+ "validator_confidence": validate.confidence,+ "coverage": validate.coverage,+ "grounded": validate.grounded,+ }- for attempt in range(MAX_ATTEMPTS):+ for attempt in range(max_attempts):+ attempts_used = attempt + 1widen = attempt > 0# Refine queries@@ -265,45 +306,52 @@ class SupportReplyWorkflow:workflow.logger.info("support_reply: no seed chunks; drafting via MCP tools only")# Draft via sandbox- draft_output = await workflow.execute_activity(- support_draft_activity,- DraftInput(- team_id=input.team_id,- ticket_context=reviewed_context,- chunk_ids=retrieve_output.chunk_ids,- prior_reply=prior_reply,- prior_missing=missing,- always_on_context=ctx_output.always_on_context,- ticket_type=ticket_type,- needs_diagnostics=needs_diagnostics,- diagnostics_allowed=ctx_output.diagnostics_allowed,- auto_publishable=auto_publishable,+ draft_output = coerce_dataclass(+ DraftOutput,+ await workflow.execute_activity(+ support_draft_activity,+ DraftInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ chunk_ids=retrieve_output.chunk_ids,+ prior_reply=prior_reply,+ prior_missing=missing,+ always_on_context=ctx_output.always_on_context,+ ticket_type=ticket_type,+ needs_diagnostics=needs_diagnostics,+ diagnostics_allowed=ctx_output.diagnostics_allowed,+ auto_publishable=auto_publishable,+ ),+ start_to_close_timeout=timedelta(minutes=20),+ retry_policy=RetryPolicy(maximum_attempts=2),),- start_to_close_timeout=timedelta(minutes=20),- retry_policy=RetryPolicy(maximum_attempts=2),)- # Default 0.0 on histories recorded before DraftOutput.sandbox_seconds existed.- sandbox_seconds += getattr(draft_output, "sandbox_seconds", 0.0) or 0.0+ sandbox_seconds += draft_output.sandbox_seconds or 0.0if draft_output.task_run_id:draft_task_run_ids.append(draft_output.task_run_id)# Validate- validate_output = await _llm(- support_validate_activity,- ValidateInput(- team_id=input.team_id,- ticket_context=reviewed_context,- reply=draft_output.reply,- citations=draft_output.citations,- chunk_ids=retrieve_output.chunk_ids,- sources=draft_output.sources,- ticket_type=ticket_type,- trace_id=trace_id,- ticket_id=ticket_id,+ validate_output = coerce_dataclass(+ ValidateOutput,+ await _llm(+ support_validate_activity,+ ValidateInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ reply=draft_output.reply,+ citations=draft_output.citations,+ chunk_ids=retrieve_output.chunk_ids,+ sources=draft_output.sources,+ ticket_type=ticket_type,+ trace_id=trace_id,+ ticket_id=ticket_id,+ ),+ timeout=timedelta(minutes=2),),- timeout=timedelta(minutes=2),)+ last_draft = draft_output+ last_validate = validate_output# 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 —@@ -315,6 +363,82 @@ class SupportReplyWorkflow:best_sources = draft_output.sourcesbest_missing = validate_output.missing+ if blocker_aware:+ action = decide_reply_action(+ grounded=validate_output.grounded,+ coverage=validate_output.coverage,+ validator_confidence=validate_output.confidence,+ draft_confidence=draft_output.confidence,+ blocker=validate_output.blocker,+ verdict=draft_output.verdict,+ attempt=attempt,+ max_attempts=max_attempts,+ )+ if action in ("auto_send", "suggest"):+ review_output = await _llm(+ support_review_reply_activity,+ ReviewReplyInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ reply=draft_output.reply,+ sources=draft_output.sources,+ ticket_type=ticket_type,+ trace_id=trace_id,+ ticket_id=ticket_id,+ ),+ timeout=timedelta(minutes=2),+ )+ if not review_output.safe:+ workflow.logger.info(+ "support_reply: reply blocked by output review",+ extra={"reason": review_output.reason},+ )+ outcome = {+ **_base_triage(),+ **_judge_triage(draft_output, validate_output),+ "investigation_summary": "",+ "unknowns": [],+ "clarifying_questions": [],+ "result": "blocked_unsafe_reply",+ "confidence": validate_output.confidence,+ "attempts": attempt + 1,+ }+ return "blocked_unsafe_reply"++ result_name = "persisted" if action == "auto_send" else "suggested"+ await workflow.execute_activity(+ support_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,+ ticket_type=ticket_type,+ allow_bot_reply=action == "auto_send",+ ),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if validate_output.missing:+ await _persist_gaps(validate_output.missing, ticket_type, result_name)+ outcome = {+ **_base_triage(),+ **_judge_triage(draft_output, validate_output),+ "result": result_name,+ "confidence": validate_output.confidence,+ "attempts": attempt + 1,+ "missing": validate_output.missing,+ }+ return f"{result_name} (confidence={validate_output.confidence:.2f}, attempts={attempt + 1})"++ if action == "retry":+ missing = validate_output.missing+ prior_citations = draft_output.citations+ prior_reply = draft_output.reply+ continue+ break+if validate_output.confidence >= SCORE_THRESHOLD:# Output safety gate: check for PII leaks / exfil before the reply reaches# the (untrusted) ticket author.@@ -378,6 +502,107 @@ class SupportReplyWorkflow:prior_citations = best_citationsprior_reply = best_reply+ if blocker_aware:+ if last_draft is not None and last_validate is not None:+ last_draft = coerce_dataclass(DraftOutput, last_draft)+ last_validate = coerce_dataclass(ValidateOutput, last_validate)+ last_verdict = last_draft.verdict+ last_blocker = last_validate.blocker+ findings_reason = findings_reason_for(+ blocker=last_blocker,+ verdict=last_verdict,+ grounded=last_validate.grounded,+ )+ if should_persist_findings(+ investigation_summary=last_draft.investigation_summary,+ unknowns=list(last_draft.unknowns),+ clarifying_questions=list(last_draft.clarifying_questions),+ citations=list(last_draft.citations),+ blocker=last_blocker,+ verdict=last_verdict,+ ):+ findings_text = format_findings_comment(+ investigation_summary=last_draft.investigation_summary,+ unknowns=list(last_draft.unknowns),+ clarifying_questions=list(last_draft.clarifying_questions),+ findings_reason=findings_reason,+ citations=list(last_draft.citations),+ )+ review_output = await _llm(+ support_review_reply_activity,+ ReviewReplyInput(+ team_id=input.team_id,+ ticket_context=reviewed_context,+ reply=findings_text,+ sources=last_draft.sources,+ ticket_type=ticket_type,+ trace_id=trace_id,+ ticket_id=ticket_id,+ ),+ timeout=timedelta(minutes=2),+ )+ if not review_output.safe:+ last_draft = replace(+ last_draft,+ citations=[],+ investigation_summary="",+ unknowns=[],+ clarifying_questions=[],+ )+ findings_reason = FINDINGS_WITHHELD_REASON+ findings_text = format_findings_comment(+ investigation_summary="",+ unknowns=[],+ clarifying_questions=[],+ findings_reason=findings_reason,+ citations=[],+ )+ await workflow.execute_activity(+ support_persist_reply_activity,+ PersistReplyInput(+ team_id=input.team_id,+ ticket_id=input.ticket_id,+ reply=findings_text,+ citations=last_draft.citations,+ confidence=last_validate.confidence,+ ticket_type=ticket_type,+ allow_bot_reply=False,+ persist_as="findings",+ investigation_summary=last_draft.investigation_summary,+ unknowns=list(last_draft.unknowns),+ clarifying_questions=list(last_draft.clarifying_questions),+ findings_reason=findings_reason,+ ),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if last_validate.missing:+ await _persist_gaps(last_validate.missing, ticket_type, "escalated_with_findings")+ outcome = {+ **_base_triage(),+ **_judge_triage(last_draft, last_validate),+ "investigation_summary": last_draft.investigation_summary,+ "unknowns": list(last_draft.unknowns),+ "clarifying_questions": list(last_draft.clarifying_questions),+ "result": "escalated_with_findings",+ "confidence": last_validate.confidence,+ "attempts": attempts_used,+ "missing": last_validate.missing,+ }+ return f"escalated_with_findings (confidence={last_validate.confidence:.2f})"+ if last_validate.missing:+ await _persist_gaps(last_validate.missing, ticket_type, "escalated_no_reply")+ outcome = {+ **_base_triage(),+ **_judge_triage(last_draft, last_validate),+ "result": "escalated_no_reply",+ "attempts": attempts_used,+ "missing": last_validate.missing,+ }+ return "escalated_no_reply"+ outcome = {**_base_triage(), "result": "escalated_no_reply", "attempts": max_attempts}+ return "escalated_no_reply"+# Exhausted attempts — persist best if we have one with non-zero confidenceif best_reply and best_confidence > 0:review_output = await _llm(@@ -403,7 +628,7 @@ class SupportReplyWorkflow:"needs_diagnostics": needs_diagnostics,"diagnostics_allowed": ctx_output.diagnostics_allowed,"confidence": best_confidence,- "attempts": MAX_ATTEMPTS,+ "attempts": LEGACY_MAX_ATTEMPTS,}return "blocked_unsafe_reply"@@ -429,7 +654,7 @@ class SupportReplyWorkflow:"needs_diagnostics": needs_diagnostics,"diagnostics_allowed": ctx_output.diagnostics_allowed,"confidence": best_confidence,- "attempts": MAX_ATTEMPTS,+ "attempts": LEGACY_MAX_ATTEMPTS,"missing": best_missing,}return f"escalated_with_best (confidence={best_confidence:.2f})"@@ -441,7 +666,7 @@ class SupportReplyWorkflow:"ticket_type": ticket_type,"needs_diagnostics": needs_diagnostics,"diagnostics_allowed": ctx_output.diagnostics_allowed,- "attempts": MAX_ATTEMPTS,+ "attempts": LEGACY_MAX_ATTEMPTS,"missing": best_missing,}return "escalated_no_reply"diff --git a/products/conversations/backend/temporal/tests/test_gate.py b/products/conversations/backend/temporal/tests/test_gate.pynew file mode 100644index 000000000000..c3136c2e65ab--- /dev/null+++ b/products/conversations/backend/temporal/tests/test_gate.py@@ -0,0 +1,192 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.conversations.backend.temporal.ai_reply.gate import (+ decide_reply_action,+ findings_reason_for,+ should_persist_findings,+)+from products.conversations.backend.temporal.ai_reply.schemas import (+ DraftOutput,+ SupportReplyDraft,+ ValidateOutput,+ coerce_dataclass,+)+++class TestFailClosedDefaults(SimpleTestCase):+ def test_omitted_draft_verdict_is_blocked_on_knowledge(self):+ draft = SupportReplyDraft(reply="ok", citations=[], confidence=0.9)+ assert draft.verdict == "blocked_on_knowledge"++ def test_unknown_draft_verdict_is_blocked_on_knowledge(self):+ draft = SupportReplyDraft(reply="ok", citations=[], confidence=0.9, verdict="idk")+ assert draft.verdict == "blocked_on_knowledge"++ def test_activity_defaults_do_not_auto_send(self):+ draft = DraftOutput(reply="Looks right.", citations=[], confidence=0.9)+ validate = ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[])+ assert draft.verdict == "blocked_on_knowledge"+ assert validate.blocker == "knowledge"+ assert (+ decide_reply_action(+ grounded=validate.grounded,+ coverage=validate.coverage,+ validator_confidence=validate.confidence,+ draft_confidence=draft.confidence,+ blocker=validate.blocker,+ verdict=draft.verdict,+ attempt=0,+ max_attempts=2,+ )+ == "retry"+ )+++class TestDecideReplyAction(SimpleTestCase):+ def _decide(+ self,+ *,+ grounded: bool = True,+ coverage: float = 0.9,+ validator_confidence: float = 0.9,+ draft_confidence: float = 0.9,+ blocker: str = "none",+ verdict: str = "answerable",+ attempt: int = 0,+ max_attempts: int = 2,+ ):+ return decide_reply_action(+ grounded=grounded,+ coverage=coverage,+ validator_confidence=validator_confidence,+ draft_confidence=draft_confidence,+ blocker=blocker,+ verdict=verdict,+ attempt=attempt,+ max_attempts=max_attempts,+ )++ def test_auto_send_when_both_judges_agree(self):+ assert self._decide() == "auto_send"++ def test_validator_high_draft_low_does_not_auto_send(self):+ assert self._decide(draft_confidence=0.3) == "suggest"++ def test_ungrounded_never_auto_sends(self):+ assert self._decide(grounded=False, validator_confidence=0.9, draft_confidence=0.9) == "findings"++ def test_low_coverage_never_auto_sends(self):+ assert self._decide(coverage=0.7) == "suggest"++ def test_customer_info_exits_to_clarify_before_suggest(self):+ assert self._decide(blocker="customer_info", validator_confidence=0.6) == "clarify"++ def test_blocked_on_customer_verdict_exits_to_clarify(self):+ assert self._decide(verdict="blocked_on_customer", blocker="none") == "clarify"++ def test_knowledge_retries_on_first_attempt(self):+ assert self._decide(blocker="knowledge", grounded=False, validator_confidence=0.2) == "retry"++ def test_blocked_on_knowledge_without_knowledge_blocker_does_not_retry(self):+ assert self._decide(verdict="blocked_on_knowledge", blocker="none", validator_confidence=0.6) == "findings"++ def test_knowledge_does_not_retry_on_last_attempt(self):+ assert (+ self._decide(blocker="knowledge", grounded=False, validator_confidence=0.2, attempt=1, max_attempts=2)+ == "findings"+ )++ def test_knowledge_does_not_suggest_after_retry(self):+ assert self._decide(blocker="knowledge", validator_confidence=0.6, attempt=1, max_attempts=2) == "findings"++ def test_blocked_on_knowledge_does_not_suggest(self):+ assert (+ self._decide(+ verdict="blocked_on_knowledge",+ blocker="none",+ validator_confidence=0.6,+ attempt=1,+ max_attempts=2,+ )+ == "findings"+ )++ @parameterized.expand(+ [+ ("contradiction", {"blocker": "contradiction"}, "findings"),+ ("out_of_scope", {"verdict": "out_of_scope"}, "findings"),+ ]+ )+ def test_terminal_findings_blockers(self, _name, overrides, expected):+ assert self._decide(**overrides) == expected+++class TestFindingsNote(SimpleTestCase):+ def test_knowledge_blocker_persists_even_without_investigation_text(self):+ assert should_persist_findings(+ investigation_summary="",+ unknowns=[],+ clarifying_questions=[],+ citations=[],+ blocker="knowledge",+ verdict="answerable",+ )+ assert findings_reason_for(blocker="knowledge", verdict="answerable", grounded=False) == (+ "The knowledge base and docs did not cover this."+ )++ def test_ungrounded_cited_draft_persists_findings(self):+ assert should_persist_findings(+ investigation_summary="",+ unknowns=[],+ clarifying_questions=[],+ citations=["https://example.com/docs"],+ blocker="none",+ verdict="answerable",+ )+ assert findings_reason_for(blocker="none", verdict="answerable", grounded=False) == (+ "This draft does not match the sources, so it was not sent."+ )++ def test_empty_ungrounded_draft_does_not_persist_findings(self):+ assert not should_persist_findings(+ investigation_summary="",+ unknowns=[],+ clarifying_questions=[],+ citations=[],+ blocker="none",+ verdict="answerable",+ )+++class TestCoerceActivityResults(SimpleTestCase):+ def test_dict_without_verdict_fails_closed(self):+ draft = coerce_dataclass(DraftOutput, {"reply": "ok", "citations": [], "confidence": 0.9})+ assert draft.verdict == "blocked_on_knowledge"+ assert draft.unknowns == []+ assert draft.investigation_summary == ""++ def test_dict_without_blocker_fails_closed(self):+ validate = coerce_dataclass(+ ValidateOutput, {"grounded": True, "coverage": 0.9, "confidence": 0.9, "missing": []}+ )+ assert validate.blocker == "knowledge"++ def test_legacy_json_payload_decodes_with_defaults(self):+ import json++ from temporalio.api.common.v1 import Payload+ from temporalio.converter import JSONPlainPayloadConverter++ converter = JSONPlainPayloadConverter()+ payload = Payload(+ metadata={"encoding": b"json/plain"},+ data=json.dumps(+ {"reply": "ok", "citations": [], "confidence": 0.9, "sources": [], "task_run_id": ""}+ ).encode(),+ )+ decoded = coerce_dataclass(DraftOutput, converter.from_payload(payload, DraftOutput))+ assert decoded.verdict == "blocked_on_knowledge"+ assert decoded.sandbox_seconds == 0.0diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.pyindex e2358ed266a3..321d5a1b3b1a 100644--- a/products/conversations/backend/temporal/tests/test_pipeline.py+++ b/products/conversations/backend/temporal/tests/test_pipeline.py@@ -1,10 +1,13 @@from __future__ import annotations+from collections.abc import Callable, Sequencefrom typing import Anyimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom temporalio.exceptions import ActivityError, RetryState@@ -25,10 +28,13 @@ from products.conversations.backend.temporal.ai_reply.activities.validate importfrom products.conversations.backend.temporal.ai_reply.constants import (BASE_DRAFT_SCOPES,DIAGNOSTIC_SCOPES_PRESET,+ LEGACY_MAX_ATTEMPTS,LLM_REQUEST_TIMEOUT_SECONDS,MAX_ATTEMPTS,+ MAX_VALIDATE_EVIDENCE_CHARS,PUBLISHABLE_DRAFT_SCOPES,)+from products.conversations.backend.temporal.ai_reply.gate import FINDINGS_WITHHELD_REASON, format_findings_commentfrom products.conversations.backend.temporal.ai_reply.llms import (create_message as _create_message,strip_json_fence as _strip_json_fence,@@ -134,12 +140,14 @@ async def test_workflow_persists_on_high_score(reply="You can install via pip.",citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],confidence=0.9,+ verdict="answerable",)mock_validate.return_value = ValidateOutput(grounded=True,coverage=0.9,confidence=0.85,missing=["setup prerequisites"],+ blocker="none",)mock_review.return_value = ReviewReplyOutput(safe=True)@@ -188,7 +196,7 @@ async def test_workflow_persists_on_high_score(@patch(f"{CLASSIFY_MODULE}._classify", new_callable=AsyncMock)@patch(f"{SAFETY_FILTER_MODULE}._safety_filter", new_callable=AsyncMock)@patch(f"{BUILD_CONTEXT_MODULE}._build_context_sync")-async def test_workflow_widens_on_low_score(+async def test_workflow_retries_once_on_knowledge_blocker(mock_build,mock_safety,mock_classify,@@ -215,7 +223,8 @@ async def test_workflow_widens_on_low_score(mock_draft.return_value = DraftOutput(reply="Here's pricing info.",citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],- confidence=0.7,+ confidence=0.9,+ verdict="answerable",)mock_review.return_value = ReviewReplyOutput(safe=True)@@ -223,9 +232,11 @@ async def test_workflow_widens_on_low_score(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=[])+ if validate_count["n"] < 2:+ return ValidateOutput(+ grounded=False, coverage=0.4, confidence=0.3, missing=["pricing info"], blocker="knowledge"+ )+ return ValidateOutput(grounded=True, coverage=0.9, confidence=0.85, missing=[], blocker="none")mock_validate.side_effect = validate_side_effect@@ -255,13 +266,411 @@ async def test_workflow_widens_on_low_score()assert "persisted" in result- assert validate_count["n"] == 3- assert mock_refine.call_count >= 3+ assert validate_count["n"] == 2+ assert mock_refine.call_count == 2refine_missing = [call.args[0].missing for call in mock_refine.call_args_list]assert refine_missing[0] == []assert ["pricing info"] in refine_missing[1:]+_WORKFLOW_ACTIVITIES: Sequence[Callable[..., Any]] = [+ support_build_context_activity,+ support_safety_filter_activity,+ support_classify_activity,+ support_refine_queries_activity,+ support_retrieve_activity,+ support_draft_activity,+ support_validate_activity,+ support_review_reply_activity,+ support_persist_reply_activity,+ support_record_triage_activity,+]+++ "name,draft_kwargs,validate_kwargs,expected_result,expect_review,expect_persist_as,expect_allow_bot,expect_drafts",+ [+ (+ "auto_send",+ {"confidence": 0.9, "verdict": "answerable"},+ {"grounded": True, "coverage": 0.9, "confidence": 0.85, "blocker": "none"},+ "persisted",+ True,+ "reply",+ True,+ 1,+ ),+ (+ "draft_low_does_not_auto_send",+ {"confidence": 0.3, "verdict": "answerable"},+ {"grounded": True, "coverage": 0.9, "confidence": 0.9, "blocker": "none"},+ "suggested",+ True,+ "reply",+ False,+ 1,+ ),+ (+ "ungrounded_findings",+ {+ "confidence": 0.9,+ "verdict": "answerable",+ "investigation_summary": "Checked docs. Could not confirm the claim.",+ },+ {"grounded": False, "coverage": 0.9, "confidence": 0.9, "blocker": "none"},+ "escalated_with_findings",+ True,+ "findings",+ False,+ 1,+ ),+ (+ "ungrounded_citations_persist_findings",+ {"confidence": 0.9, "verdict": "answerable"},+ {"grounded": False, "coverage": 0.9, "confidence": 0.9, "blocker": "none"},+ "escalated_with_findings",+ True,+ "findings",+ False,+ 1,+ ),+ (+ "customer_info_does_not_retry",+ {+ "confidence": 0.2,+ "verdict": "blocked_on_customer",+ "clarifying_questions": ["Which SDK are you using?"],+ "investigation_summary": "SDK not named.",+ },+ {"grounded": False, "coverage": 0.2, "confidence": 0.2, "blocker": "customer_info"},+ "escalated_with_findings",+ True,+ "findings",+ False,+ 1,+ ),+ (+ "contradiction_findings",+ {"confidence": 0.4, "verdict": "answerable", "investigation_summary": "Docs say 30 days, ticket says 3."},+ {"grounded": True, "coverage": 0.5, "confidence": 0.4, "blocker": "contradiction"},+ "escalated_with_findings",+ True,+ "findings",+ False,+ 1,+ ),+ (+ "blocked_on_knowledge_does_not_suggest",+ {+ "confidence": 0.6,+ "verdict": "blocked_on_knowledge",+ "investigation_summary": "Searched docs. No match.",+ },+ {"grounded": True, "coverage": 0.6, "confidence": 0.6, "blocker": "none"},+ "escalated_with_findings",+ True,+ "findings",+ False,+ 1,+ ),+ (+ "knowledge_after_retry_is_findings",+ {+ "confidence": 0.6,+ "verdict": "answerable",+ "investigation_summary": "Searched docs. Still missing the procedure.",+ },+ {"grounded": True, "coverage": 0.6, "confidence": 0.6, "blocker": "knowledge"},+ "escalated_with_findings",+ True,+ "findings",+ False,+ 2,+ ),+ ],+)+@patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync")+@patch(f"{PERSIST_REPLY_MODULE}._persist_reply_sync")+@patch(f"{REVIEW_REPLY_MODULE}._review_reply", new_callable=AsyncMock)+@patch(f"{VALIDATE_MODULE}._validate", new_callable=AsyncMock)+@patch(f"{DRAFT_MODULE}._draft_async", new_callable=AsyncMock)+@patch(f"{RETRIEVE_MODULE}._retrieve_sync")+@patch(f"{REFINE_QUERIES_MODULE}._refine_queries", new_callable=AsyncMock)+@patch(f"{CLASSIFY_MODULE}._classify", new_callable=AsyncMock)+@patch(f"{SAFETY_FILTER_MODULE}._safety_filter", new_callable=AsyncMock)+@patch(f"{BUILD_CONTEXT_MODULE}._build_context_sync")+async def test_blocker_aware_routing(+ mock_build,+ mock_safety,+ mock_classify,+ mock_refine,+ mock_retrieve,+ mock_draft,+ mock_validate,+ mock_review,+ mock_persist,+ mock_record_triage,+ name,+ draft_kwargs,+ validate_kwargs,+ expected_result,+ expect_review,+ expect_persist_as,+ expect_allow_bot,+ expect_drafts,+ workflow_input,+ sample_chunk_ids,+):+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Worker++ mock_build.return_value = BuildContextOutput(ticket_context="Customer question", ticket_title="Help")+ mock_safety.return_value = SafetyFilterOutput(safe=True)+ mock_classify.return_value = ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=["q"])+ mock_refine.return_value = RefineQueriesOutput(queries=["q"])+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=sample_chunk_ids)+ mock_draft.return_value = DraftOutput(+ reply="Drafted answer.",+ citations=sample_chunk_ids,+ **draft_kwargs,+ )+ mock_validate.return_value = ValidateOutput(missing=[], **validate_kwargs)+ mock_review.return_value = ReviewReplyOutput(safe=True)++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-queue",+ workflows=[SupportReplyWorkflow],+ activities=_WORKFLOW_ACTIVITIES,+ ):+ result = await env.client.execute_workflow(+ SupportReplyWorkflow.run,+ workflow_input,+ id=f"test-routing-{name}",+ task_queue="test-queue",+ )++ assert expected_result in result+ assert mock_draft.call_count == expect_drafts+ if expect_review:+ mock_review.assert_called_once()+ else:+ mock_review.assert_not_called()+ mock_persist.assert_called_once()+ persist_input = mock_persist.call_args[0][0]+ assert persist_input.persist_as == expect_persist_as+ assert persist_input.allow_bot_reply is expect_allow_bot+ if expect_persist_as == "findings":+ assert persist_input.reply != "Drafted answer."+ assert "Drafted answer." not in persist_input.reply+ assert "Investigation notes" in persist_input.reply+ assert persist_input.findings_reason+ if persist_input.investigation_summary:+ assert persist_input.investigation_summary in persist_input.reply+ last_triage = mock_record_triage.call_args_list[-1][0][0].patch+ assert last_triage["result"] == expected_result+ assert "draft_confidence" in last_triage+ assert "validator_confidence" in last_triage+ assert "blocker" in last_triage+ assert "verdict" in last_triage+++@patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync")+@patch(f"{PERSIST_REPLY_MODULE}._persist_reply_sync")+@patch(f"{REVIEW_REPLY_MODULE}._review_reply", new_callable=AsyncMock)+@patch(f"{VALIDATE_MODULE}._validate", new_callable=AsyncMock)+@patch(f"{DRAFT_MODULE}._draft_async", new_callable=AsyncMock)+@patch(f"{RETRIEVE_MODULE}._retrieve_sync")+@patch(f"{REFINE_QUERIES_MODULE}._refine_queries", new_callable=AsyncMock)+@patch(f"{CLASSIFY_MODULE}._classify", new_callable=AsyncMock)+@patch(f"{SAFETY_FILTER_MODULE}._safety_filter", new_callable=AsyncMock)+@patch(f"{BUILD_CONTEXT_MODULE}._build_context_sync")+async def test_findings_review_withholds_sensitive_notes(+ mock_build,+ mock_safety,+ mock_classify,+ mock_refine,+ mock_retrieve,+ mock_draft,+ mock_validate,+ mock_review,+ mock_persist,+ mock_record_triage,+ workflow_input,+ sample_chunk_ids,+):+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Worker++ mock_build.return_value = BuildContextOutput(ticket_context="Customer question", ticket_title="Help")+ mock_safety.return_value = SafetyFilterOutput(safe=True)+ mock_classify.return_value = ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=["q"])+ mock_refine.return_value = RefineQueriesOutput(queries=["q"])+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=sample_chunk_ids)+ mock_draft.return_value = DraftOutput(+ reply="Drafted answer.",+ citations=sample_chunk_ids,+ confidence=0.9,+ verdict="answerable",+ investigation_summary="User email is [email protected] and the key is sk-live-secret.",+ unknowns=["internal host 10.0.0.1"],+ clarifying_questions=["What is the API key in use?"],+ )+ mock_validate.return_value = ValidateOutput(+ grounded=False, coverage=0.9, confidence=0.9, missing=[], blocker="none"+ )+ mock_review.return_value = ReviewReplyOutput(safe=False, reason="PII leak")++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-queue",+ workflows=[SupportReplyWorkflow],+ activities=_WORKFLOW_ACTIVITIES,+ ):+ result = await env.client.execute_workflow(+ SupportReplyWorkflow.run,+ workflow_input,+ id="test-findings-review-withholds",+ task_queue="test-queue",+ )++ assert "escalated_with_findings" in result+ mock_review.assert_called_once()+ persist_input = mock_persist.call_args[0][0]+ assert persist_input.persist_as == "findings"+ assert persist_input.findings_reason == FINDINGS_WITHHELD_REASON+ assert persist_input.investigation_summary == ""+ assert persist_input.unknowns == []+ assert persist_input.clarifying_questions == []+ assert persist_input.citations == []+ assert "[email protected]" not in persist_input.reply+ assert "sk-live-secret" not in persist_input.reply+ assert "What is the API key in use?" not in persist_input.reply+ assert sample_chunk_ids[0] not in persist_input.reply+ last_triage = mock_record_triage.call_args_list[-1][0][0].patch+ assert last_triage["investigation_summary"] == ""+ assert last_triage["unknowns"] == []+ assert last_triage["clarifying_questions"] == []+++@patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync")+@patch(f"{PERSIST_REPLY_MODULE}._persist_reply_sync")+@patch(f"{REVIEW_REPLY_MODULE}._review_reply", new_callable=AsyncMock)+@patch(f"{VALIDATE_MODULE}._validate", new_callable=AsyncMock)+@patch(f"{DRAFT_MODULE}._draft_async", new_callable=AsyncMock)+@patch(f"{RETRIEVE_MODULE}._retrieve_sync")+@patch(f"{REFINE_QUERIES_MODULE}._refine_queries", new_callable=AsyncMock)+@patch(f"{CLASSIFY_MODULE}._classify", new_callable=AsyncMock)+@patch(f"{SAFETY_FILTER_MODULE}._safety_filter", new_callable=AsyncMock)+@patch(f"{BUILD_CONTEXT_MODULE}._build_context_sync")+async def test_workflow_replays_blocker_aware_findings_history(+ mock_build,+ mock_safety,+ mock_classify,+ mock_refine,+ mock_retrieve,+ mock_draft,+ mock_validate,+ mock_review,+ mock_persist,+ mock_record_triage,+ workflow_input,+ sample_chunk_ids,+):+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker++ mock_build.return_value = BuildContextOutput(ticket_context="Unknown widget", ticket_title="Widget")+ mock_safety.return_value = SafetyFilterOutput(safe=True)+ mock_classify.return_value = ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=[])+ mock_refine.return_value = RefineQueriesOutput(queries=["widget"])+ mock_retrieve.return_value = RetrieveOutput(chunk_ids=sample_chunk_ids)+ mock_draft.return_value = DraftOutput(+ reply="I cannot find this.",+ citations=[],+ confidence=0.0,+ verdict="blocked_on_knowledge",+ investigation_summary="Searched docs. No match.",+ unknowns=["how to enable the widget"],+ )+ mock_validate.return_value = ValidateOutput(+ grounded=False, coverage=0.0, confidence=0.0, missing=["docs"], blocker="knowledge"+ )+ mock_review.return_value = ReviewReplyOutput(safe=True)++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-queue",+ workflows=[SupportReplyWorkflow],+ activities=_WORKFLOW_ACTIVITIES,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ handle = await env.client.start_workflow(+ SupportReplyWorkflow.run,+ workflow_input,+ id="test-replay-blocker-aware-findings",+ task_queue="test-queue",+ )+ result = await handle.result()+ history = await handle.fetch_history()++ assert "escalated_with_findings" in result+ assert mock_draft.call_count == MAX_ATTEMPTS+ mock_review.assert_called_once()+ persist_input = mock_persist.call_args[0][0]+ assert persist_input.persist_as == "findings"+ assert persist_input.reply != "I cannot find this."+ assert "Searched docs. No match." in persist_input.reply++ await Replayer(+ workflows=[SupportReplyWorkflow],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ).replay_workflow(history)+++class TestFormatFindingsComment(SimpleTestCase):+ def test_findings_note_does_not_include_the_draft_reply(self):+ text = format_findings_comment(+ investigation_summary="Checked the docs. SDK was not named.",+ unknowns=["SDK in use"],+ clarifying_questions=["Which SDK are you using?"],+ findings_reason="",+ )+ assert "Investigation notes" in text+ assert "Checked the docs" in text+ assert "Which SDK are you using?" in text+ assert "This is the answer to send" not in text++ def test_findings_note_lists_citations_as_sources(self):+ text = format_findings_comment(+ investigation_summary="Checked the docs.",+ unknowns=[],+ clarifying_questions=[],+ citations=["https://example.com/docs/sdk"],+ )+ assert "Sources:" in text+ assert "https://example.com/docs/sdk" in text++ def test_contradiction_reason_is_called_out(self):+ text = format_findings_comment(+ investigation_summary="Retention docs say 30 days.",+ unknowns=[],+ clarifying_questions=[],+ findings_reason="This answer contradicts the cited sources, so it was not sent.",+ )+ assert "contradicts the cited sources" in text+ assert "Retention docs say 30 days." in text++@pytest.mark.django_db@pytest.mark.asyncio@patch(f"{PERSIST_KNOWLEDGE_GAP_MODULE}._persist_sync")@@ -337,7 +746,7 @@ async def test_workflow_replays_pre_patch_gap_persistence(pre_patch_history = await handle.fetch_history()assert "escalated_with_best" in result- assert mock_validate.call_count == MAX_ATTEMPTS+ assert mock_validate.call_count == LEGACY_MAX_ATTEMPTSmock_persist.assert_called_once()mock_persist_gaps.assert_called_once()last_triage = mock_record_triage.call_args_list[-1][0][0].patch@@ -383,8 +792,15 @@ async def test_workflow_drafts_via_mcp_when_no_seed_chunks(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"])+ mock_draft.return_value = DraftOutput(+ reply="I cannot answer this.",+ citations=[],+ confidence=0.0,+ verdict="answerable",+ )+ mock_validate.return_value = ValidateOutput(+ grounded=False, coverage=0.0, confidence=0.0, missing=["everything"], blocker="none"+ )async with await WorkflowEnvironment.start_time_skipping() as env:async with Worker(@@ -445,6 +861,80 @@ class TestPersistReplyActivity:assert comment.item_context["is_private"] is Trueassert comment.item_context["citations"] == ["chunk-1", "chunk-2"]assert comment.item_context["confidence"] == 0.85+ assert comment.item_context["persist_as"] == "reply"+ assert "investigation_summary" not in comment.item_context++ def test_findings_note_does_not_present_reply_as_answer(self):+ from posthog.models.comment import Comment+ from posthog.models.organization import Organization+ from posthog.models.team.team import Team++ org = Organization.objects.create(name="Test Org")+ team = Team.objects.create(organization=org, name="Test Team")++ _persist_reply_sync(+ PersistReplyInput(+ team_id=team.id,+ ticket_id="test-ticket-id",+ reply="Here is a guessed answer you should not send.",+ citations=["chunk-1"],+ confidence=0.1,+ persist_as="findings",+ investigation_summary="Checked the docs. SDK was not named.",+ unknowns=["SDK in use"],+ clarifying_questions=["Which SDK are you using?"],+ )+ )++ comment = Comment.objects.get(team_id=team.id, item_id="test-ticket-id")+ assert comment.content is not None+ assert "Here is a guessed answer you should not send." not in comment.content+ assert "Checked the docs. SDK was not named." in comment.content+ assert "Which SDK are you using?" in comment.content+ assert "chunk-1" in comment.content+ assert comment.item_context is not None+ assert comment.item_context["is_private"] is True+ assert comment.item_context["persist_as"] == "findings"++ def test_findings_note_stays_private_on_bot_reply_channel(self):+ from posthog.models.comment import Comment+ from posthog.models.organization import Organization+ from posthog.models.team.team import Team++ org = Organization.objects.create(name="Test Org")+ team = Team.objects.create(+ organization=org,+ name="Test Team",+ conversations_settings={"ai_reply_modes": {"email": {"how_to": "bot_reply"}}},+ )+ ticket = Ticket.objects.create_with_number(+ team=team,+ channel_source="email",+ widget_session_id="",+ distinct_id="[email protected]",+ email_from="[email protected]",+ )++ _persist_reply_sync(+ PersistReplyInput(+ team_id=team.id,+ ticket_id=str(ticket.id),+ reply="Guessed public answer.",+ citations=[],+ confidence=0.2,+ ticket_type="how_to",+ allow_bot_reply=True,+ persist_as="findings",+ investigation_summary="SDK was not named.",+ )+ )++ comment = Comment.objects.get(team_id=team.id, item_id=str(ticket.id))+ assert comment.content is not None+ assert "Guessed public answer." not in comment.content+ assert comment.item_context is not None+ assert comment.item_context["is_private"] is True+ assert comment.item_context["persist_as"] == "findings"def test_public_email_reply_rolls_back_when_outbox_create_fails(self):from posthog.models.comment import Comment@@ -699,6 +1189,32 @@ class TestUntrustedTicketGuard:assert injection in insideassert injection not in before+ @pytest.mark.asyncio+ async def test_draft_prompt_requires_plan_and_verdict(self):+ captured: dict[str, str] = {}++ async def fake_start(prompt, context, **kwargs):+ captured["prompt"] = prompt+ result = SupportReplyDraft(reply="ok", citations=[], confidence=0.0, sources=[])+ return AsyncMock(), result++ with (+ patch(f"{DRAFT_MODULE}._hydrate_chunks", return_value=[]),+ patch(f"{DRAFT_MODULE}.resolve_user_id_for_support", return_value=1),+ patch(f"{DRAFT_MODULE}.get_or_create_support_sandbox_env", return_value="env-1"),+ patch(f"{DRAFT_MODULE}.MultiTurnSession.start", new=AsyncMock(side_effect=fake_start)),+ ):+ output = await _draft_async(DraftInput(team_id=1, ticket_context="how do I install", chunk_ids=[]))++ prompt = captured["prompt"]+ assert "PLAN first" in prompt+ assert "blocked_on_customer" in prompt+ assert "blocked_on_knowledge" in prompt+ assert "verdict is not answerable" in prompt+ assert "verdict" in prompt+ assert "set confidence to 0 and reply with a brief note" not in prompt+ assert output.verdict in ("answerable", "blocked_on_knowledge", "blocked_on_customer", "out_of_scope")+class TestDiagnosticScopes:"""Customer-data scopes are granted only when the org opted in AND the reply won't be@@ -1062,12 +1578,16 @@ class TestReviewReplyActivity:reply="Here are all emails: [email protected], [email protected]",citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],confidence=0.9,+ verdict="answerable",+ investigation_summary="User email is [email protected] and the key is sk-live-secret.",+ unknowns=["internal host 10.0.0.1"],+ clarifying_questions=["What is the API key in use?"],),),patch(f"{VALIDATE_MODULE}._validate",new_callable=AsyncMock,- return_value=ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[]),+ return_value=ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[], blocker="none"),),patch(f"{REVIEW_REPLY_MODULE}._review_reply",@@ -1075,7 +1595,7 @@ class TestReviewReplyActivity:return_value=ReviewReplyOutput(safe=False, reason="reply dumps raw emails"),),patch(f"{PERSIST_REPLY_MODULE}._persist_reply_sync") as mock_persist,- patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync"),+ patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync") as mock_record_triage,):async with await WorkflowEnvironment.start_time_skipping() as env:async with Worker(@@ -1104,6 +1624,16 @@ class TestReviewReplyActivity:assert result == "blocked_unsafe_reply"mock_persist.assert_not_called()+ last_triage = mock_record_triage.call_args_list[-1][0][0].patch+ assert last_triage["result"] == "blocked_unsafe_reply"+ assert last_triage["investigation_summary"] == ""+ assert last_triage["unknowns"] == []+ assert last_triage["clarifying_questions"] == []+ triage_blob = str(last_triage)+ assert "[email protected]" not in triage_blob+ assert "sk-live-secret" not in triage_blob+ assert "10.0.0.1" not in triage_blob+ assert "API key" not in triage_blobclass TestCreateMessage:@@ -1171,19 +1701,21 @@ class TestValidateActivity:[("valid_json",- '{"grounded": true, "coverage": 0.8, "confidence": 0.75, "missing": ["deployment details"]}',+ '{"grounded": true, "coverage": 0.8, "confidence": 0.75, "missing": ["deployment details"], "blocker": "none"}',True,0.8,0.75,["deployment details"],+ "none",),("json_in_fence",- '```json\n{"grounded": true, "coverage": 0.9, "confidence": 0.85, "missing": []}\n```',+ '```json\n{"grounded": true, "coverage": 0.9, "confidence": 0.85, "missing": [], "blocker": "knowledge"}\n```',True,0.9,0.85,[],+ "knowledge",),("partial_fields",@@ -1192,6 +1724,7 @@ class TestValidateActivity:0.5,0.0,[],+ "knowledge",),])@@ -1204,6 +1737,7 @@ class TestValidateActivity:expected_coverage,expected_confidence,expected_missing,+ expected_blocker,):cited = [{"chunk_id": "chunk-1", "content": "Docker compose deployment guide"}]with (@@ -1226,6 +1760,7 @@ class TestValidateActivity:assert result.coverage == expected_coverageassert result.confidence == expected_confidenceassert result.missing == expected_missing+ assert result.blocker == expected_blocker@parameterized.expand([@@ -1256,6 +1791,62 @@ class TestValidateActivity:assert result.grounded is Falseassert result.confidence == 0.0assert "parse_failure" in result.missing+ assert result.blocker == "knowledge"++ @pytest.mark.asyncio+ async def test_validate_prompt_uses_full_chunk_and_ticket_window(self):+ ticket = "T" * 4000+ chunk_content = "C" * 800+ client = _mock_gateway_client(+ '{"grounded": true, "coverage": 1, "confidence": 1, "missing": [], "blocker": "none"}'+ )+ with (+ patch(f"{VALIDATE_MODULE}.get_async_anthropic_gateway_client", return_value=client),+ patch(+ f"{VALIDATE_MODULE}._hydrate_chunks",+ return_value=[{"chunk_id": "chunk-1", "content": chunk_content}],+ ),+ ):+ await _validate(+ ValidateInput(+ team_id=1,+ ticket_context=ticket,+ reply="Answer",+ citations=["chunk-1"],+ chunk_ids=["chunk-1"],+ )+ )++ system = client.messages.create.call_args.kwargs["system"]+ user = client.messages.create.call_args.kwargs["messages"][0]["content"]+ assert "blocker" in system+ assert ticket in user+ assert chunk_content in user++ @pytest.mark.asyncio+ async def test_validate_prompt_caps_total_evidence(self):+ chunks = [{"chunk_id": f"c{i}", "content": "C" * 2000} for i in range(25)]+ client = _mock_gateway_client(+ '{"grounded": true, "coverage": 1, "confidence": 1, "missing": [], "blocker": "none"}'+ )+ with (+ patch(f"{VALIDATE_MODULE}.get_async_anthropic_gateway_client", return_value=client),+ patch(f"{VALIDATE_MODULE}._hydrate_chunks", return_value=chunks),+ ):+ await _validate(+ ValidateInput(+ team_id=1,+ ticket_context="How to deploy?",+ reply="Answer",+ citations=[c["chunk_id"] for c in chunks],+ chunk_ids=[c["chunk_id"] for c in chunks],+ )+ )++ user = client.messages.create.call_args.kwargs["messages"][0]["content"]+ cited = user.split("CITED CHUNKS:", 1)[1]+ assert len(cited.strip()) <= MAX_VALIDATE_EVIDENCE_CHARS+ assert "[c24]" not in cited@pytest.mark.django_db@@ -1372,7 +1963,9 @@ async def test_classify_threading_and_diagnostics_gating(confidence=0.3,)# Never clears threshold → loops MAX_ATTEMPTS so we can prove classify is one-shot.- mock_validate.return_value = ValidateOutput(grounded=False, coverage=0.2, confidence=0.2, missing=["why"])+ mock_validate.return_value = ValidateOutput(+ grounded=False, coverage=0.2, confidence=0.2, missing=["why"], blocker="knowledge"+ )mock_review.return_value = ReviewReplyOutput(safe=True)async with await WorkflowEnvironment.start_time_skipping() as env:@@ -1400,7 +1993,7 @@ async def test_classify_threading_and_diagnostics_gating(task_queue="test-queue",)- # Classify is one-shot up front; the loop still ran MAX_ATTEMPTS times.+ # Classify is one-shot up front; knowledge blocker retries once (MAX_ATTEMPTS=2).assert mock_classify.call_count == 1assert mock_validate.call_count == MAX_ATTEMPTSdraft_input = mock_draft.call_args[0][0]@@ -1515,7 +2108,7 @@ class TestRecordTriageActivity:"persisted",ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=["setup"]),SafetyFilterOutput(safe=True),- ValidateOutput(grounded=True, coverage=0.9, confidence=0.85, missing=[]),+ ValidateOutput(grounded=True, coverage=0.9, confidence=0.85, missing=[], blocker="none"),ReviewReplyOutput(safe=True),"persisted",),@@ -1539,7 +2132,7 @@ class TestRecordTriageActivity:"blocked_unsafe_reply",ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, seed_queries=[]),SafetyFilterOutput(safe=True),- ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[]),+ ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[], blocker="none"),ReviewReplyOutput(safe=False, reason="PII leak"),"blocked_unsafe_reply",),@@ -1587,12 +2180,14 @@ class TestRecordTriageActivity:citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],confidence=0.9,sandbox_seconds=1.5,+ verdict="answerable",),),patch(f"{VALIDATE_MODULE}._validate",new_callable=AsyncMock,- return_value=validate_output or ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[]),+ return_value=validate_output+ or ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[], blocker="none"),),patch(f"{REVIEW_REPLY_MODULE}._review_reply",@@ -1692,12 +2287,20 @@ class TestRecordTriageActivity:patch(f"{DRAFT_MODULE}._draft_async",new_callable=AsyncMock,- return_value=DraftOutput(reply="", citations=[], confidence=0.0, sandbox_seconds=0.25),+ return_value=DraftOutput(+ reply="",+ citations=[],+ confidence=0.0,+ sandbox_seconds=0.25,+ verdict="answerable",+ ),),patch(f"{VALIDATE_MODULE}._validate",new_callable=AsyncMock,- return_value=ValidateOutput(grounded=False, coverage=0.0, confidence=0.0, missing=["everything"]),+ return_value=ValidateOutput(+ grounded=False, coverage=0.0, confidence=0.0, missing=["everything"], blocker="none"+ ),),patch(f"{REVIEW_REPLY_MODULE}._review_reply",@@ -1737,9 +2340,9 @@ class TestRecordTriageActivity:last_call_patch = mock_record_triage.call_args_list[-1][0][0].patchassert last_call_patch["status"] == "done"assert last_call_patch["result"] == "escalated_no_reply"- assert last_call_patch["attempts"] == MAX_ATTEMPTS- assert last_call_patch["cost"]["sandbox_seconds"] == pytest.approx(0.25 * MAX_ATTEMPTS)- assert last_call_patch["cost"]["llm_calls"] == 2 + MAX_ATTEMPTS * 2+ assert last_call_patch["attempts"] == 1+ assert last_call_patch["cost"]["sandbox_seconds"] == pytest.approx(0.25)+ assert last_call_patch["cost"]["llm_calls"] == 4@pytest.mark.django_db@pytest.mark.asynciodiff --git a/products/conversations/backend/tests/test_support_reply_eval.py b/products/conversations/backend/tests/test_support_reply_eval.pyindex 649b135a38c7..db982049ae59 100644--- a/products/conversations/backend/tests/test_support_reply_eval.py+++ b/products/conversations/backend/tests/test_support_reply_eval.py@@ -27,6 +27,13 @@ class TestEvalOutcomeFromTriage(SimpleTestCase):[("persisted_is_answerable", {"status": "done", "result": "persisted"}, "answerable"),("escalated_with_best", {"status": "done", "result": "escalated_with_best"}, "escalate"),+ ("suggested_is_escalate", {"status": "done", "result": "suggested"}, "escalate"),+ ("findings_is_escalate", {"status": "done", "result": "escalated_with_findings"}, "escalate"),+ (+ "customer_info_blocker_is_clarification",+ {"status": "done", "result": "escalated_with_findings", "blocker": "customer_info"},+ "needs_clarification",+ ),("skipped_unactionable", {"status": "done", "result": "skipped_unactionable"}, "escalate"),("unknown_result_is_unscored", {"status": "done", "result": "mystery"}, None),(@@ -35,6 +42,16 @@ class TestEvalOutcomeFromTriage(SimpleTestCase):"needs_clarification",),("unfinished_run", {"status": "in_progress"}, None),+ (+ "unfinished_run_keeps_stale_blocker_unscored",+ {"status": "in_progress", "blocker": "customer_info", "verdict": "blocked_on_customer"},+ None,+ ),+ (+ "blocked_on_customer_verdict_is_clarification",+ {"status": "done", "result": "escalated_with_findings", "verdict": "blocked_on_customer"},+ "needs_clarification",+ ),])def test_maps_triage(self, _name, triage, expected):diff --git a/products/conversations/evals/constants.py b/products/conversations/evals/constants.pyindex 91f7812bfc04..b04cb250a12b 100644--- a/products/conversations/evals/constants.py+++ b/products/conversations/evals/constants.py@@ -22,6 +22,7 @@ TICKET_TYPES: tuple[TicketType, ...] = ("how_to", "diagnostic", "account_billing# the fixture asks for.PIPELINE_RESULT_TO_EVAL_OUTCOME: dict[str, EvalOutcome] = {"persisted": "answerable",+ "suggested": "escalate","escalated_with_best": "escalate","escalated_no_reply": "escalate","escalated_with_findings": "escalate",diff --git a/products/conversations/evals/fixtures.py b/products/conversations/evals/fixtures.pyindex 5187aaffb832..5938002f4504 100644--- a/products/conversations/evals/fixtures.py+++ b/products/conversations/evals/fixtures.py@@ -28,6 +28,10 @@ class MockedDraft:citation_sources: tuple[str, ...]confidence: floatexcerpts: tuple[tuple[str, str], ...] = ()+ verdict: str = "answerable"+ clarifying_questions: tuple[str, ...] = ()+ investigation_summary: str = ""+ unknowns: tuple[str, ...] = ()@frozen@@ -36,6 +40,7 @@ class MockedValidate:coverage: floatconfidence: floatmissing: tuple[str, ...] = ()+ blocker: str = "none"@frozen@@ -69,12 +74,6 @@ def expected_for(fixture: SupportReplyFixture) -> dict[str, Any]:_ANSWERABLE_VALIDATE = MockedValidate(grounded=True, coverage=0.9, confidence=0.9)-_LOW_VALIDATE = MockedValidate(- grounded=False,- coverage=0.2,- confidence=0.2,- missing=("customer did not specify the missing fact",),-)FIXTURES: tuple[SupportReplyFixture, ...] = (@@ -157,8 +156,18 @@ FIXTURES: tuple[SupportReplyFixture, ...] = (reply="Which SDK are you using?",citation_sources=(),confidence=0.2,+ verdict="blocked_on_customer",+ clarifying_questions=("Which SDK are you using?",),+ investigation_summary="The ticket does not name an SDK, so I cannot give install steps.",+ unknowns=("SDK in use",),+ ),+ mocked_validate=MockedValidate(+ grounded=False,+ coverage=0.2,+ confidence=0.2,+ missing=("customer did not specify the missing fact",),+ blocker="customer_info",),- mocked_validate=_LOW_VALIDATE,),SupportReplyFixture(name="diagnostic_its_broken",@@ -172,8 +181,18 @@ FIXTURES: tuple[SupportReplyFixture, ...] = (reply="Which product surface is broken?",citation_sources=(),confidence=0.1,+ verdict="blocked_on_customer",+ clarifying_questions=("Which product surface is broken?",),+ investigation_summary="The report does not say what is failing.",+ unknowns=("affected product surface",),+ ),+ mocked_validate=MockedValidate(+ grounded=False,+ coverage=0.2,+ confidence=0.2,+ missing=("customer did not specify the missing fact",),+ blocker="customer_info",),- mocked_validate=_LOW_VALIDATE,),SupportReplyFixture(name="account_billing_why_charged",@@ -187,8 +206,18 @@ FIXTURES: tuple[SupportReplyFixture, ...] = (reply="Which organization is this for?",citation_sources=(),confidence=0.2,+ verdict="blocked_on_customer",+ clarifying_questions=("Which organization is this for?",),+ investigation_summary="The charge question does not name an organization.",+ unknowns=("organization",),+ ),+ mocked_validate=MockedValidate(+ grounded=False,+ coverage=0.2,+ confidence=0.2,+ missing=("customer did not specify the missing fact",),+ blocker="customer_info",),- mocked_validate=_LOW_VALIDATE,),SupportReplyFixture(name="how_to_holographic_widget",@@ -203,12 +232,16 @@ FIXTURES: tuple[SupportReplyFixture, ...] = (reply="I cannot find the holographic dashboard widget in the knowledge base.",citation_sources=(),confidence=0.0,+ verdict="blocked_on_knowledge",+ investigation_summary="Searched docs and the knowledge base. No holographic dashboard widget exists.",+ unknowns=("how to enable holographic dashboard widget",),),mocked_validate=MockedValidate(grounded=False,coverage=0.0,confidence=0.0,missing=("no documentation for holographic dashboard widget",),+ blocker="knowledge",),),SupportReplyFixture(@@ -237,6 +270,7 @@ FIXTURES: tuple[SupportReplyFixture, ...] = (coverage=0.5,confidence=0.4,missing=("why this project deleted at 3 days",),+ blocker="contradiction",),),SupportReplyFixture(diff --git a/products/conversations/evals/outcomes.py b/products/conversations/evals/outcomes.pyindex bce12a975f13..99c8ecb77245 100644--- a/products/conversations/evals/outcomes.py+++ b/products/conversations/evals/outcomes.py@@ -16,6 +16,10 @@ def eval_outcome_from_triage(ai_triage: dict[str, Any] | None) -> EvalOutcome |triage = ai_triage or {}if triage.get("status") == CLARIFICATION_TRIAGE_STATUS:return "needs_clarification"+ if triage.get("status") != "done":+ return None+ if triage.get("blocker") == "customer_info" or triage.get("verdict") == "blocked_on_customer":+ return "needs_clarification"result = triage.get("result")if not isinstance(result, str) or not result:return Nonediff --git a/products/conversations/evals/runner.py b/products/conversations/evals/runner.pyindex 25fa05022b0e..d0bc27addc04 100644--- a/products/conversations/evals/runner.py+++ b/products/conversations/evals/runner.py@@ -107,6 +107,10 @@ def _mocked_draft(fixture: SupportReplyFixture, seed: SeededCase) -> DraftOutputconfidence=draft.confidence,sources=sources,sandbox_seconds=0.0,+ verdict=draft.verdict,+ clarifying_questions=list(draft.clarifying_questions),+ investigation_summary=draft.investigation_summary,+ unknowns=list(draft.unknowns),)@@ -119,6 +123,7 @@ def _mocked_validate(fixture: SupportReplyFixture) -> ValidateOutput:coverage=validate.coverage,confidence=validate.confidence,missing=list(validate.missing),+ blocker=validate.blocker,)diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 9a78bd56eee8..bddf634a076c 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -609,6 +609,8 @@ export const TicketSlaFilterEnumApi = {/*** * `persisted` - persisted+ * * `suggested` - suggested+ * * `escalated_with_findings` - escalated_with_findings* * `escalated_with_best` - escalated_with_best* * `escalated_no_reply` - escalated_no_reply* * `skipped_unactionable` - skipped_unactionable@@ -620,6 +622,8 @@ export type AiTriageResultEnumApi = (typeof AiTriageResultEnumApi)[keyof typeofexport const AiTriageResultEnumApi = {Persisted: 'persisted',+ Suggested: 'suggested',+ EscalatedWithFindings: 'escalated_with_findings',EscalatedWithBest: 'escalated_with_best',EscalatedNoReply: 'escalated_no_reply',SkippedUnactionable: 'skipped_unactionable',@@ -693,7 +697,7 @@ export interface TicketViewFiltersApi {* * `on-track` - on-track* * `all` - all */sla?: TicketSlaFilterEnumApi- /** AI triage outcomes to include. 'in_progress' matches tickets still being triaged. */+ /** AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress. */aiTriageResult?: AiTriageResultEnumApi[]/** Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), or an object with type ('user' or 'role') and id. Send a list. Views saved earlier can hold a single value instead of a list, or the value 'all'. Wrap a single value in a list, and replace 'all' with an empty list to apply no assignee filter. */assignee?: TicketViewFiltersApiAssigneeItem[]@@ -916,7 +920,7 @@ export interface ZendeskImportErrorApi {export type ConversationsTicketsListParams = {/**- * Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.+ * Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `suggested`, `escalated_with_findings`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.*/ai_triage_result?: string/**diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 43093c887432..6f3b7ebcd1a8 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -348,6 +348,8 @@ export const ConversationsViewsCreateBody = /* @__PURE__ */ zod.object({zod.enum(['persisted',+ 'suggested',+ 'escalated_with_findings','escalated_with_best','escalated_no_reply','skipped_unactionable',@@ -356,11 +358,13 @@ export const ConversationsViewsCreateBody = /* @__PURE__ */ zod.object({'in_progress',]).describe(- '\* `persisted` - persisted\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress'+ '\* `persisted` - persisted\n\* `suggested` - suggested\n\* `escalated_with_findings` - escalated_with_findings\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress')).optional()- .describe("AI triage outcomes to include. 'in_progress' matches tickets still being triaged."),+ .describe(+ "AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress."+ ),assignee: zod.array(zod.union([@@ -488,6 +492,8 @@ export const ConversationsViewsPartialUpdateBody = /* @__PURE__ */ zod.object({zod.enum(['persisted',+ 'suggested',+ 'escalated_with_findings','escalated_with_best','escalated_no_reply','skipped_unactionable',@@ -496,11 +502,13 @@ export const ConversationsViewsPartialUpdateBody = /* @__PURE__ */ zod.object({'in_progress',]).describe(- '\* `persisted` - persisted\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress'+ '\* `persisted` - persisted\n\* `suggested` - suggested\n\* `escalated_with_findings` - escalated_with_findings\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress')).optional()- .describe("AI triage outcomes to include. 'in_progress' matches tickets still being triaged."),+ .describe(+ "AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress."+ ),assignee: zod.array(zod.union([diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex c1c7ebcfe8a1..1fa3678427d0 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -54,6 +54,8 @@ export type TicketTagsMatch = 'any' | 'all'export type AITriageStatus = 'in_progress' | 'done'export type AITriageResult =| 'persisted'+ | 'suggested'+ | 'escalated_with_findings'| 'escalated_with_best'| 'escalated_no_reply'| 'skipped_unactionable'@@ -75,6 +77,15 @@ export interface AITriage {run_id?: stringai_trace_id?: stringmissing?: string[]+ verdict?: 'answerable' | 'blocked_on_customer' | 'blocked_on_knowledge' | 'out_of_scope'+ blocker?: 'none' | 'customer_info' | 'knowledge' | 'contradiction'+ unknowns?: string[]+ clarifying_questions?: string[]+ investigation_summary?: string+ draft_confidence?: number+ validator_confidence?: number+ coverage?: number+ grounded?: booleancost?: {sandbox_seconds?: numberllm_calls?: number@@ -283,6 +294,8 @@ export const slaOptions: { value: TicketSlaState | 'all'; label: string }[] = [export const aiTriageResultLabel: Record<AITriageResult, string> = {persisted: 'Resolved',+ suggested: 'Suggested reply',+ escalated_with_findings: 'Escalated with notes',escalated_with_best: 'Escalated with draft',escalated_no_reply: 'Escalated, no draft',skipped_unactionable: 'Skipped',@@ -305,6 +318,8 @@ export function aiTriageResultTagType(result: AITriageResult): AITriageTagType {switch (result) {case 'persisted':return 'success'+ case 'suggested':+ case 'escalated_with_findings':case 'escalated_with_best':case 'escalated_no_reply':return 'warning'diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9ef9772bdaca..7368bc7a4ff9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9734,6 +9734,8 @@ export namespace Schemas {/*** * `persisted` - persisted+ * * `suggested` - suggested+ * * `escalated_with_findings` - escalated_with_findings* * `escalated_with_best` - escalated_with_best* * `escalated_no_reply` - escalated_no_reply* * `skipped_unactionable` - skipped_unactionable@@ -9746,6 +9748,8 @@ export namespace Schemas {export const AiTriageResultEnum = {Persisted: 'persisted',+ Suggested: 'suggested',+ EscalatedWithFindings: 'escalated_with_findings',EscalatedWithBest: 'escalated_with_best',EscalatedNoReply: 'escalated_no_reply',SkippedUnactionable: 'skipped_unactionable',@@ -62558,7 +62562,7 @@ export namespace Schemas {* * `on-track` - on-track* * `all` - all */sla?: TicketSlaFilterEnum;- /** AI triage outcomes to include. 'in_progress' matches tickets still being triaged. */+ /** AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress. */aiTriageResult?: AiTriageResultEnum[];/** Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), or an object with type ('user' or 'role') and id. Send a list. Views saved earlier can hold a single value instead of a list, or the value 'all'. Wrap a single value in a list, and replace 'all' with an empty list to apply no assignee filter. */assignee?: TicketViewFiltersAssigneeItem[];@@ -98320,7 +98324,7 @@ export namespace Schemas {export type ConversationsTicketsListParams = {/**- * Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.+ * Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `suggested`, `escalated_with_findings`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.*/ai_triage_result?: string;/**diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex c2948887974a..6bb1a14d3986 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -24,7 +24,7 @@ export const ConversationsTicketsListQueryParams = () => zod.object({.string().optional().describe(- 'Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.'+ 'Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `suggested`, `escalated_with_findings`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.'),assignee: zod.string()@@ -373,6 +373,8 @@ export const ConversationsViewsCreateBody = () => zod.object({zod.enum(['persisted',+ 'suggested',+ 'escalated_with_findings','escalated_with_best','escalated_no_reply','skipped_unactionable',@@ -381,11 +383,13 @@ export const ConversationsViewsCreateBody = () => zod.object({'in_progress',]).describe(- '\* `persisted` - persisted\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress'+ '\* `persisted` - persisted\n\* `suggested` - suggested\n\* `escalated_with_findings` - escalated_with_findings\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress')).optional()- .describe("AI triage outcomes to include. 'in_progress' matches tickets still being triaged."),+ .describe(+ "AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress."+ ),assignee: zod.array(zod.union([@@ -531,6 +535,8 @@ export const ConversationsViewsPartialUpdateBody = () => zod.object({zod.enum(['persisted',+ 'suggested',+ 'escalated_with_findings','escalated_with_best','escalated_no_reply','skipped_unactionable',@@ -539,11 +545,13 @@ export const ConversationsViewsPartialUpdateBody = () => zod.object({'in_progress',]).describe(- '\* `persisted` - persisted\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress'+ '\* `persisted` - persisted\n\* `suggested` - suggested\n\* `escalated_with_findings` - escalated_with_findings\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress')).optional()- .describe("AI triage outcomes to include. 'in_progress' matches tickets still being triaged."),+ .describe(+ "AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress."+ ),assignee: zod.array(zod.union([diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.jsonindex 844136d81148..dff3c476fda4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"ai_triage_result": {- "description": "Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.",+ "description": "Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `suggested`, `escalated_with_findings`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.","type": "string"},"assignee": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-create.jsonindex a6027bde637e..2506cb31ca41 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-create.json@@ -5,11 +5,13 @@"description": "Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search.","properties": {"aiTriageResult": {- "description": "AI triage outcomes to include. 'in_progress' matches tickets still being triaged.",+ "description": "AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress.","items": {- "description": "* `persisted` - persisted\n* `escalated_with_best` - escalated_with_best\n* `escalated_no_reply` - escalated_no_reply\n* `skipped_unactionable` - skipped_unactionable\n* `blocked_unsafe` - blocked_unsafe\n* `blocked_unsafe_reply` - blocked_unsafe_reply\n* `in_progress` - in_progress",+ "description": "* `persisted` - persisted\n* `suggested` - suggested\n* `escalated_with_findings` - escalated_with_findings\n* `escalated_with_best` - escalated_with_best\n* `escalated_no_reply` - escalated_no_reply\n* `skipped_unactionable` - skipped_unactionable\n* `blocked_unsafe` - blocked_unsafe\n* `blocked_unsafe_reply` - blocked_unsafe_reply\n* `in_progress` - in_progress","enum": ["persisted",+ "suggested",+ "escalated_with_findings","escalated_with_best","escalated_no_reply","skipped_unactionable",diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-update.jsonindex bb4bc730f384..d28f4fc396d4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-views-update.json@@ -5,11 +5,13 @@"description": "Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search.","properties": {"aiTriageResult": {- "description": "AI triage outcomes to include. 'in_progress' matches tickets still being triaged.",+ "description": "AI triage outcomes to include. 'in_progress' matches tickets still being triaged. Valid values: persisted, suggested, escalated_with_findings, escalated_with_best, escalated_no_reply, skipped_unactionable, blocked_unsafe, blocked_unsafe_reply, in_progress.","items": {- "description": "* `persisted` - persisted\n* `escalated_with_best` - escalated_with_best\n* `escalated_no_reply` - escalated_no_reply\n* `skipped_unactionable` - skipped_unactionable\n* `blocked_unsafe` - blocked_unsafe\n* `blocked_unsafe_reply` - blocked_unsafe_reply\n* `in_progress` - in_progress",+ "description": "* `persisted` - persisted\n* `suggested` - suggested\n* `escalated_with_findings` - escalated_with_findings\n* `escalated_with_best` - escalated_with_best\n* `escalated_no_reply` - escalated_no_reply\n* `skipped_unactionable` - skipped_unactionable\n* `blocked_unsafe` - blocked_unsafe\n* `blocked_unsafe_reply` - blocked_unsafe_reply\n* `in_progress` - in_progress","enum": ["persisted",+ "suggested",+ "escalated_with_findings","escalated_with_best","escalated_no_reply","skipped_unactionable",