Skip to content

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

fix(aio): guard eval report IDs by handled set, not UUID shape (#88073)

posthog[bot]e66a76219f5c
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
index 54aa37bb7403..fa4abca7d2f8 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -22,7 +22,9 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
from posthog.temporal.ai_observability.eval_reports.report_agent.state import EvalReportAgentState
from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
_ch_ts,
+ _dead_backticked_ids_in_report,
_fetch_period_summary,
+ _handled_ids,
_is_retriable_ch_error,
get_eval_report_tools,
)
@@ -183,13 +185,19 @@ def _append_references_section(content: EvalReportContent) -> None:
content.sections.append(ReportSection(title="References", content="\n".join(refs_lines)))
-def _validate_agent_output(content: EvalReportContent) -> str | None:
+def _validate_agent_output(content: EvalReportContent, handled_ids: set[str] | None = None) -> str | None:
"""Return a reason string if content is invalid, else None.
Enforced invariants:
- title must be non-empty
- section count must be within [MIN_REPORT_SECTIONS, MAX_REPORT_SECTIONS]
- every section must have a non-empty title and content
+ - no backticked ID may ship dead: a section body links only an exactly-cited ID
+ in one pair of backticks, and a title links nothing at all, so every other
+ backticked ID is a dead identifier
+
+ set_title and add_section run the same dead-ID check in the loop, so the agent can
+ correct a dead ID on its next call. This is the backstop for what reaches the end.
"""
if not content.title.strip():
return "agent did not call set_title"
@@ -202,6 +210,12 @@ def _validate_agent_output(content: EvalReportContent) -> str | None:
return f"section {idx + 1} has empty title"
if not section.content.strip():
return f"section {idx + 1} ({section.title!r}) has empty content"
+
+ titles = [content.title, *(section.title for section in content.sections)]
+ bodies = [section.content for section in content.sections]
+ dead = _dead_backticked_ids_in_report(titles, bodies, content.citations, handled_ids or set())
+ if dead:
+ return f"backticked IDs will not render as citation links: {', '.join(dead[:3])}"
return None
@@ -330,7 +344,7 @@ def run_eval_report_agent(
content.evaluation_target = evaluation_target
content.metrics = metrics
- validation_error = _validate_agent_output(content)
+ validation_error = _validate_agent_output(content, _handled_ids(result))
if validation_error:
increment_report_generated("fallback_validation")
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
index 81202d42a119..47913c6ba7b0 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
@@ -35,7 +35,8 @@ You build the report incrementally by calling three output tools:
- Don't invent sections just to fill space. One or two sections is enough for a routine report.
- Don't speculate beyond the data. Every claim should be traceable to a tool result. State uncertainty clearly.
- Don't emit emoji or marketing language. Be technical and factual.
-- Don't wrap a run_id from `list_recent_report_runs` or `get_report_run` in backticks. Only a generation, trace, or session ID you cite becomes a link; a backticked run_id renders as dead text. Name a prior run by its period instead.
+- Don't put an ID in backticks unless you already called `add_citation` for it, and then wrap that exact ID in one pair of backticks. Cite an example before you write the section that mentions it, because `add_section` rejects a section that backticks an uncited ID. That includes a session or trace ID you read but did not cite, and a run_id from `list_recent_report_runs` or `get_report_run`, which can never be cited. Name a prior run by its period instead.
+- Don't put an ID in the report title or in a section title. A title renders as plain text, so an ID there stays dead even after you cite it. `set_title` and `add_section` reject a title that backticks an ID. Mention the ID in the section body instead.
## Query tools available
@@ -68,7 +69,7 @@ These reports are generated back to back over the same evaluation, so one writte
3. {outcome_analysis_step}
4. {detail_step}
5. Call `get_report_run(run_id)` on the most recent prior run, unless `list_recent_report_runs()` returned none.
-6. Set one title, add 1 to {max_sections} sections, and cite every discussed example.
+6. Call `add_citation` for every example you will discuss, then set one title and add 1 to {max_sections} sections.
7. Return. The graph attaches the trusted metrics automatically.
{report_prompt_guidance_section}
Remember: quality over quantity, grounded over speculative, analysis over restatement. The reader should understand what happened and what, if anything, to do about it."""
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
index a627971d01ee..755f3bf82a48 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
@@ -21,6 +21,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
EvalReportMetrics,
ReportSection,
)
+from posthog.temporal.ai_observability.eval_reports.targets import SESSION_ID_ALLOWLIST_KEY, TRACE_ID_ALLOWLIST_KEY
from posthog.temporal.ai_observability.eval_reports.types import RunEvalReportAgentInput
@@ -298,6 +299,54 @@ class TestValidateAgentOutput(SimpleTestCase):
content.citations = [Citation(generation_id="g", trace_id="t", reason="r")]
self.assertIsNone(_validate_agent_output(content))
+ @parameterized.expand(
+ [
+ ("report title", "Regression in `{id}`", "Summary", "A finding."),
+ ("section title", "A valid punchline", "Regression in `{id}`", "A finding."),
+ ("section content", "A valid punchline", "Summary", "See `{id}`."),
+ ]
+ )
+ def test_dead_backticked_id_fails(self, _name, title, section_title, section_content):
+ # An opaque session ID the run handled but never cited would ship dead.
+ session_id = "chat_thread_9f2b1a"
+ content = EvalReportContent(
+ title=title.format(id=session_id),
+ sections=[
+ ReportSection(
+ title=section_title.format(id=session_id),
+ content=section_content.format(id=session_id),
+ )
+ ],
+ citations=[],
+ metrics=EvalReportMetrics(),
+ )
+ reason = _validate_agent_output(content, {session_id})
+ self.assertIsNotNone(reason)
+ self.assertIn(session_id, reason or "")
+
+ def test_cited_backticked_id_passes(self):
+ content = self._valid_content()
+ session_id = "chat_thread_9f2b1a"
+ content.sections = [ReportSection(title="Summary", content=f"See `{session_id}`.")]
+ content.citations = [Citation(session_id=session_id, reason="regression")]
+ self.assertIsNone(_validate_agent_output(content, {session_id}))
+
+ @parameterized.expand([("report title", True), ("section title", False)])
+ def test_cited_backticked_id_in_a_title_fails(self, _name, in_report_title):
+ # No renderer runs citation linking over a title, so citing the ID does not revive it.
+ session_id = "chat_thread_9f2b1a"
+ content = self._valid_content()
+ if in_report_title:
+ content.title = f"Regression in `{session_id}`"
+ else:
+ content.sections = [ReportSection(title=f"Regression in `{session_id}`", content="A finding.")]
+ content.citations = [Citation(session_id=session_id, reason="regression")]
+
+ reason = _validate_agent_output(content, {session_id})
+
+ self.assertIsNotNone(reason)
+ self.assertIn(session_id, reason or "")
+
class TestAppendReferencesSection(SimpleTestCase):
def test_no_citations_leaves_sections_untouched(self):
@@ -406,6 +455,54 @@ class TestRunEvalReportAgentRouting(SimpleTestCase):
self.assertIs(mock_create_agent.call_args.kwargs["model"], mock_build_llm.return_value)
+class TestRunEvalReportAgentDeadIdGuard(SimpleTestCase):
+ """The dead-ID guard reads the handled IDs off the finished agent state.
+
+ Opaque IDs are not UUID-shaped, so the guard only catches them while the
+ query allowlists come back on the invoke result. If that wiring breaks the
+ guard degrades to UUID-only and an uncited opaque ID ships dead again.
+ """
+
+ @patch.object(graph, "build_langchain_callbacks", return_value=[])
+ @patch.object(graph, "create_react_agent")
+ @patch.object(graph, "build_langchain_chat_client")
+ @patch.object(graph, "_compute_metrics")
+ def test_uncited_opaque_id_from_the_result_allowlist_falls_back(
+ self, mock_metrics, _mock_build_llm, mock_create_agent, _mock_build_callbacks
+ ):
+ mock_metrics.return_value = EvalReportMetrics()
+ session_id = "chat_thread_9f2b1a"
+ mock_agent = MagicMock()
+ mock_agent.invoke.return_value = {
+ "report": EvalReportContent(
+ title="A report",
+ sections=[ReportSection(title="Summary", content=f"See `{session_id}`.")],
+ metrics=EvalReportMetrics(),
+ ),
+ TRACE_ID_ALLOWLIST_KEY: [],
+ SESSION_ID_ALLOWLIST_KEY: [session_id],
+ }
+ mock_create_agent.return_value = mock_agent
+
+ content = graph.run_eval_report_agent(
+ RunEvalReportAgentInput(
+ team_id=1,
+ report_id="report-1",
+ evaluation_id="eval-1",
+ evaluation_name="Relevance",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="llm_judge",
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ previous_period_start="2026-04-08T13:00:00+00:00",
+ )
+ )
+
+ self.assertEqual(content.title, "Automated fallback report for Relevance")
+ self.assertIn(session_id, content.sections[0].content)
+
+
class TestRunEvalReportAgentMetricsUnavailable(SimpleTestCase):
@patch.object(graph, "build_langchain_chat_client")
@patch.object(graph, "create_react_agent")
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
index d823d4ee7ee5..f0d941135825 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
@@ -1,6 +1,7 @@
"""Tests for the v2 eval report agent output tools (set_title, add_section, add_citation)."""
import json
+import time
import datetime as dt
from typing import NotRequired, TypedDict
@@ -35,6 +36,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
_SESSION_TRACES_SQL,
_UUID_RE,
_ch_ts,
+ _dead_backticked_ids,
_execute_ch_query_with_retry,
_is_retriable_ch_error,
_widened_ts_window,
@@ -570,6 +572,21 @@ class TestSetTitle(SimpleTestCase):
self.assertLessEqual(len(state["report"].title), 200)
self.assertTrue(state["report"].title.endswith("..."))
+ # The title is an email subject, a Slack header, and a heading — never markdown — so
+ # citing the ID does not save it. Rejecting in the loop lets the agent retitle; the
+ # final validation can only discard the whole report.
+ @parameterized.expand([("uncited", False), ("cited", True)])
+ def test_rejects_backticked_id_in_title(self, _name: str, cite: bool) -> None:
+ state = _state_with_empty_report()
+ if cite:
+ state["report"].citations.append(Citation(generation_id=_VALID_GEN_ID, trace_id=_VALID_TRACE_ID))
+
+ result = _set_title_fn(state=state, title=f"Regression in `{_VALID_GEN_ID}`")
+
+ self.assertIn("Error", result)
+ self.assertIn(_VALID_GEN_ID, result)
+ self.assertEqual(state["report"].title, "")
+
class TestAddSection(SimpleTestCase):
def test_appends_section(self):
@@ -618,40 +635,121 @@ class TestAddSection(SimpleTestCase):
titles = [s.title for s in state["report"].sections]
self.assertEqual(titles, ["First", "Second", "Third"])
- def test_rejects_section_backticking_an_uncited_uuid(self):
- # A run_id from list_recent_report_runs is a canonical UUID but not citable,
- # so backticking it would ship a dead identifier. The guard blocks it in-loop.
+ @parameterized.expand(
+ [
+ # A run_id from list_recent_report_runs is a canonical UUID but not citable.
+ (
+ "uncited_uuid_in_content",
+ "Summary",
+ "Steady since run `{id}`.",
+ [],
+ "0195f0a1-2b3c-7d4e-8f90-1a2b3c4d5e6f",
+ ),
+ # An opaque handled ID is invisible to a UUID-shaped regex, so the in-loop
+ # guard only catches it while it reads the run's allowlists.
+ ("uncited_handled_id_in_content", "Summary", "See `{id}`.", ["chat_thread_9f2b1a"], "chat_thread_9f2b1a"),
+ (
+ "uncited_handled_id_in_title",
+ "Regression in `{id}`",
+ "A finding.",
+ ["chat_thread_9f2b1a"],
+ "chat_thread_9f2b1a",
+ ),
+ ]
+ )
+ def test_rejects_section_with_a_dead_backticked_id(
+ self, _name: str, title: str, content: str, session_allowlist: list[str], dead_id: str
+ ) -> None:
state = _state_with_empty_report()
- run_id = "0195f0a1-2b3c-7d4e-8f90-1a2b3c4d5e6f"
- result = _add_section_fn(state=state, title="Summary", content=f"Steady since run `{run_id}`.")
+ state["session_id_allowlist"] = session_allowlist
+ result = _add_section_fn(state=state, title=title.format(id=dead_id), content=content.format(id=dead_id))
self.assertIn("Error", result)
- self.assertIn(run_id, result)
+ self.assertIn(dead_id, result)
self.assertEqual(state["report"].sections, [])
- def test_allows_section_when_backticked_uuid_is_cited(self):
+ def test_allows_section_when_backticked_id_is_cited(self):
state = _state_with_empty_report()
state["report"].citations.append(Citation(generation_id=_VALID_GEN_ID, trace_id=_VALID_TRACE_ID))
result = _add_section_fn(state=state, title="Summary", content=f"See `{_VALID_GEN_ID}` for the regression.")
self.assertNotIn("Error", result)
self.assertEqual(len(state["report"].sections), 1)
- @parameterized.expand(
- [
- ("different_casing", f"`{_VALID_GEN_ID.upper()}`"),
- ("surrounding_spaces", f"` {_VALID_GEN_ID} `"),
- ("multiple_backticks", f"``{_VALID_GEN_ID}``"),
- ]
- )
- def test_rejects_cited_uuid_when_format_will_not_link(self, _name: str, formatted_id: str) -> None:
+ def test_rejects_cited_backticked_id_in_a_section_title(self):
+ # Section titles reach the reader as a heading, so citation linking never runs over them.
state = _state_with_empty_report()
state["report"].citations.append(Citation(generation_id=_VALID_GEN_ID, trace_id=_VALID_TRACE_ID))
- result = _add_section_fn(state=state, title="Summary", content=f"See {formatted_id} for the regression.")
+ result = _add_section_fn(state=state, title=f"Regression in `{_VALID_GEN_ID}`", content="A finding.")
self.assertIn("Error", result)
+ self.assertIn(_VALID_GEN_ID, result)
self.assertEqual(state["report"].sections, [])
+class TestDeadBacktickedIds(SimpleTestCase):
+ _OPAQUE_SESSION_ID = "chat_thread_9f2b1a"
+ _RUN_ID = "0195f0a1-2b3c-7d4e-8f90-1a2b3c4d5e6f"
+
+ @parameterized.expand(
+ [
+ # An opaque session ID the session handled is invisible to a UUID-shaped
+ # regex, which is exactly the dead identifier readers still chase.
+ (
+ "opaque_handled_id_uncited_is_dead",
+ f"See `{_OPAQUE_SESSION_ID}`.",
+ [],
+ {_OPAQUE_SESSION_ID},
+ [_OPAQUE_SESSION_ID],
+ ),
+ (
+ "opaque_handled_id_cited_links",
+ f"See `{_OPAQUE_SESSION_ID}`.",
+ [Citation(session_id=_OPAQUE_SESSION_ID)],
+ {_OPAQUE_SESSION_ID},
+ [],
+ ),
+ ("uncited_uuid_is_dead", f"Steady since run `{_RUN_ID}`.", [], set(), [_RUN_ID]),
+ (
+ "cited_uuid_in_one_pair_links",
+ f"See `{_VALID_GEN_ID}`.",
+ [Citation(generation_id=_VALID_GEN_ID, trace_id=_VALID_TRACE_ID)],
+ set(),
+ [],
+ ),
+ (
+ "cited_uuid_upper_case_wrapper_is_dead",
+ f"See `{_VALID_GEN_ID.upper()}`.",
+ [Citation(generation_id=_VALID_GEN_ID, trace_id=_VALID_TRACE_ID)],
+ set(),
+ [_VALID_GEN_ID.upper()],
+ ),
+ (
+ "cited_uuid_double_backticks_is_dead",
+ f"See ``{_VALID_GEN_ID}``.",
+ [Citation(generation_id=_VALID_GEN_ID, trace_id=_VALID_TRACE_ID)],
+ set(),
+ [_VALID_GEN_ID],
+ ),
+ ("backticked_prose_is_ignored", "The `total_runs` field.", [], {_OPAQUE_SESSION_ID}, []),
+ ]
+ )
+ def test_dead_backticked_ids(
+ self, _name: str, text: str, citations: list[Citation], handled_ids: set[str], expected: list[str]
+ ) -> None:
+ self.assertEqual(_dead_backticked_ids(text, citations, handled_ids), expected)
+
+ def test_scan_stays_linear_on_a_whitespace_run(self):
+ # A model that degenerates into whitespace after a stray backtick writes exactly the
+ # input that makes an ambiguous backtick pattern backtrack. The check runs inside the
+ # report activity, so a slow scan hangs the activity instead of returning an error.
+ # Two thousand characters took about seven seconds before the pattern was tightened.
+ text = "The pass rate held. `" + " " * 2000
+
+ started = time.monotonic()
+ self.assertEqual(_dead_backticked_ids(text, [], set()), [])
+ self.assertLess(time.monotonic() - started, 1.0)
+
+
class TestAddCitation(SimpleTestCase):
def test_appends_citation(self):
state = _state_with_empty_report()
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index 9d9b5eb2f156..8da6284993c7 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -11,7 +11,7 @@ import re
import json
import time
import random
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Annotated, Literal, TypeVar
@@ -65,10 +65,17 @@ logger = structlog.get_logger(__name__)
# so they use bounded validation and always flow through AST constants instead.
_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
-# Detect UUID-shaped inline-code variants broadly because only an exact cited ID
-# in one pair of backticks becomes a code-span link in every report renderer.
-_BACKTICKED_UUID_RE = re.compile(
- r"`+\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\s*`+",
+# Capture the token inside any inline-code span, so the guard can tell an ID
+# apart from prose regardless of how many backticks or spaces wrap it. The class
+# excludes only the backtick, so the run to the next one is unambiguous and the
+# scan stays linear. A class that also matched the surrounding whitespace makes
+# every split of a whitespace run a candidate, and the agent writes the input.
+_BACKTICKED_TOKEN_RE = re.compile(r"`+([^`]*)`+")
+
+# Match a canonical UUID anywhere it is used as a whole token. Opaque IDs are not
+# UUID-shaped, so the guard also checks the session's handled-ID allowlists.
+_UUID_SHAPE_RE = re.compile(
+ r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
re.IGNORECASE,
)
@@ -120,6 +127,20 @@ def _is_allowlisted(state: dict, allowlist_key: str, value: str) -> bool:
return isinstance(allowlist, list) and value in allowlist
+def _handled_ids(state: dict) -> set[str]:
+ """Return every target ID this run's queries returned, across both allowlists.
+
+ The agent state and the finished agent result are the same mapping, so the
+ in-loop guard and the final validation key on one definition of a handled ID.
+ """
+ handled: set[str] = set()
+ for allowlist_key in (TRACE_ID_ALLOWLIST_KEY, SESSION_ID_ALLOWLIST_KEY):
+ allowlist = state.get(allowlist_key)
+ if isinstance(allowlist, list):
+ handled.update(value for value in allowlist if isinstance(value, str))
+ return handled
+
+
def _report_run_target_filter(evaluation_target: str) -> Q:
target = resolve_evaluation_target(evaluation_target)
if target == GENERATION_TARGET:
@@ -1463,6 +1484,9 @@ def set_title(
clean = (title or "").strip()
if not clean:
return "Error: title cannot be empty"
+ dead = _dead_backticked_ids(clean, [], _handled_ids(state))
+ if dead:
+ return _plain_text_id_error("report title", dead)
# Clip to a sensible max so it doesn't blow up email subject lines.
if len(clean) > 200:
clean = clean[:197] + "..."
@@ -1470,17 +1494,54 @@ def set_title(
return f"Title set: {clean!r}"
-def _unlinked_backticked_uuids(content: str, citations: list[Citation]) -> list[str]:
- """Return backticked canonical UUIDs that will not be links in every report renderer."""
+def _dead_backticked_ids(text: str, citations: list[Citation], handled_ids: set[str]) -> list[str]:
+ """Return backticked IDs in `text` that no report renderer turns into a link.
+
+ A renderer links only an exactly-cited ID wrapped in one pair of backticks. An
+ ID is any backticked token the session handled (its query allowlists) or a
+ canonical UUID; other backticked spans are prose and stay untouched.
+ """
cited_ids = {citation.cited_id() for citation in citations}
- unlinked: list[str] = []
- for match in _BACKTICKED_UUID_RE.finditer(content):
- uuid_value = match.group(1)
- has_exact_citation = uuid_value in cited_ids
- uses_linkable_wrapper = match.group(0) == f"`{uuid_value}`"
- if not (has_exact_citation and uses_linkable_wrapper) and uuid_value not in unlinked:
- unlinked.append(uuid_value)
- return unlinked
+ dead: list[str] = []
+ for match in _BACKTICKED_TOKEN_RE.finditer(text):
+ token = match.group(1).strip()
+ if token not in handled_ids and _UUID_SHAPE_RE.fullmatch(token) is None:
+ continue
+ links = token in cited_ids and match.group(0) == f"`{token}`"
+ if not links and token not in dead:
+ dead.append(token)
+ return dead
+
+
+def _dead_backticked_ids_in_report(
+ titles: Iterable[str], bodies: Iterable[str], citations: list[Citation], handled_ids: set[str]
+) -> list[str]:
+ """Return the dead backticked IDs across a report's titles and bodies, in first-seen order.
+
+ Only a section body is run through citation linking. Every title reaches the reader
+ as plain text — an email subject, a Slack header, a heading — so a backticked ID in a
+ title is dead even when that ID is cited.
+ """
+ no_citations: list[Citation] = []
+ checks: list[tuple[str, list[Citation]]] = [
+ *((title, no_citations) for title in titles),
+ *((body, citations) for body in bodies),
+ ]
+ dead: list[str] = []
+ for text, text_citations in checks:
+ for token in _dead_backticked_ids(text, text_citations, handled_ids):
+ if token not in dead:
+ dead.append(token)
+ return dead
+
+
+def _plain_text_id_error(surface: str, dead: list[str]) -> str:
+ """Explain to the agent that an ID in a plain-text surface can never become a link."""
+ preview = ", ".join(f"`{token}`" for token in dead[:3])
+ return (
+ f"Error: the {surface} renders as plain text, so these backticked IDs stay dead: {preview}. "
+ f"Take the backticks off the {surface} and discuss the ID in a section body instead."
+ )
@tool
@@ -1519,9 +1580,13 @@ def add_section(
f"Error: maximum of {MAX_REPORT_SECTIONS} sections reached. "
"Merge your content into existing sections rather than fragmenting further."
)
- unlinked = _unlinked_backticked_uuids(clean_content, state["report"].citations)
- if unlinked:
- preview = ", ".join(f"`{uuid_value}`" for uuid_value in unlinked[:3])
+ handled_ids = _handled_ids(state)
+ dead_in_title = _dead_backticked_ids(clean_title, [], handled_ids)
+ if dead_in_title:
+ return _plain_text_id_error("section title", dead_in_title)
+ dead = _dead_backticked_ids(clean_content, state["report"].citations, handled_ids)
+ if dead:
+ preview = ", ".join(f"`{token}`" for token in dead[:3])
return (
f"Error: the following backticked IDs will not render as citation links: {preview}. "
"Cite each generation, trace, or session with add_citation, then use one pair of backticks around the exact cited ID. "