66import re
77import time
88from collections .abc import Iterator
9- from dataclasses import dataclass , field
9+ from dataclasses import dataclass , field , replace
1010from typing import Any
1111
1212from gooddata_eval .core .agentic ._conversation_context import classify_reply
6565# The copilot's own rule: a document opens with a cover and has at least one content page.
6666_COVER_PAGE = "cover"
6767_CONTENT_PAGE = "content"
68- _EXPECTATION_KEYS = frozenset ({"period" , "visualizations" , "narrative" , "expects_clarification" })
68+ _EXPECTATION_KEYS = frozenset (
69+ {"period" , "visualizations" , "narrative" , "expects_clarification" , "asked_first_required" , "clarification_reply" }
70+ )
6971# Template tokens the document renders at export time ({documentName}, {periodStart}, ...).
7072_PLACEHOLDER_RE = re .compile (r"\{\w+\}" )
7173_SUMMARY_SLOT = "summary"
@@ -299,6 +301,10 @@ def _expects_clarification(expected_output: dict) -> bool:
299301 return "expects_clarification" in expected_output
300302
301303
304+ def _asked_first_required (expected_output : dict ) -> bool :
305+ return expected_output .get ("asked_first_required" ) is True
306+
307+
302308def _validate_expectation (expected_output : Any ) -> None :
303309 """Reject a fixture the run could not score meaningfully, before the first API call.
304310
@@ -336,6 +342,19 @@ def _validate_expectation(expected_output: Any) -> None:
336342 raise ValueError (
337343 f"expects_clarification must be true or false, got { expected_output ['expects_clarification' ]!r} "
338344 )
345+ if "asked_first_required" in expected_output :
346+ if not isinstance (expected_output ["asked_first_required" ], bool ):
347+ raise ValueError (
348+ f"asked_first_required must be true or false, got { expected_output ['asked_first_required' ]!r} "
349+ )
350+ if expected_output ["asked_first_required" ] and expected_output .get ("expects_clarification" ) is not True :
351+ raise ValueError ("asked_first_required needs expects_clarification: true" )
352+ if "clarification_reply" in expected_output :
353+ reply = expected_output ["clarification_reply" ]
354+ if not isinstance (reply , str ) or not reply .strip ():
355+ raise ValueError (f"clarification_reply must be a non-empty reply, got { reply !r} " )
356+ if expected_output .get ("expects_clarification" ) is not True :
357+ raise ValueError ("clarification_reply needs expects_clarification: true" )
339358
340359
341360def _validate_user_context (user_context : dict | None ) -> None :
@@ -351,12 +370,16 @@ def _validate_user_context(user_context: dict | None) -> None:
351370 raise ValueError ("user_context.view.report is the Report name; send view.document" )
352371
353372
354- def build_simulated_reply (expected_output : dict ) -> str :
373+ def build_simulated_reply (expected_output : dict , * , asked : bool = True ) -> str :
355374 """The reply the simulated user sends when the copilot asks back instead of drafting.
356375
357376 Deterministic and LLM-free, built from what the fixture states, so a failure stays the
358377 copilot's rather than a simulated user that phrased things differently each run.
378+ A fixture's ``clarification_reply`` replaces it after a turn that ``asked``, for a question
379+ the charts and period do not answer. The run sends it once, to the first such turn.
359380 """
381+ if asked and isinstance (reply := expected_output .get ("clarification_reply" ), str ):
382+ return reply
360383 segments : list [str ] = []
361384 visualizations = expected_output .get ("visualizations" ) or []
362385 if visualizations :
@@ -380,6 +403,7 @@ class _Applies:
380403 period : bool
381404 charts : bool
382405 narrative : bool = False
406+ asked_first : bool = False
383407
384408
385409@dataclass
@@ -398,6 +422,7 @@ class DocumentEvaluation:
398422 charts_matched : bool = False
399423 summaries_present : bool = False
400424 narrative_judged : bool = False
425+ asked_first : bool = False
401426 judge_reasoning : str = ""
402427 # Set when the judge returned something unreadable. The run then has no narrative verdict:
403428 # it is neither published as a 0 nor allowed to pass on the remaining checks.
@@ -438,6 +463,8 @@ def strict_checks(self) -> dict[str, bool]:
438463 checks ["document_summaries_present" ] = self .summaries_present
439464 if self .judge_error is None :
440465 checks ["document_narrative_judged" ] = self .narrative_judged
466+ if self .applies .asked_first :
467+ checks ["document_asked_first" ] = self .asked_first
441468 return checks
442469
443470
@@ -646,10 +673,12 @@ def diagnostics(self) -> dict[str, bool]:
646673 """Observed but not scored.
647674
648675 Whether the copilot asked before drafting is recorded only when the fixture says it
649- expects a question, and never gates: how much the copilot should ask is a product
650- decision, not something a run can get wrong .
676+ expects a question. It gates only when the fixture sets ``asked_first_required``: how
677+ much the copilot should ask is a product decision, made per item .
651678 """
652- return {"document_asked_first" : self .asked_first } if self .expects_clarification else {}
679+ if not self .expects_clarification or self .evaluation .applies .asked_first :
680+ return {}
681+ return {"document_asked_first" : self .asked_first }
653682
654683 @property
655684 def judge_error (self ) -> str | None :
@@ -711,7 +740,8 @@ def _execute_single_document_run(
711740 turn_offset = 0.0
712741 tool_index_offset = 0
713742 reasoning_index_offset = 0
714- first_turn_asked = False
743+ asked_before_draft = False
744+ replied = False
715745
716746 run_started = time .monotonic ()
717747 for iteration in range (max_iterations ):
@@ -748,8 +778,8 @@ def _execute_single_document_run(
748778 break
749779
750780 response_text = (chat_result .text_response or "" ).strip () or render_answer_text (chat_result )
751- if iteration == 0 :
752- first_turn_asked = classify_reply ( chat_result , response_text ) == "question"
781+ asked = classify_reply ( chat_result , response_text ) != "no_action"
782+ asked_before_draft = asked_before_draft or asked
753783 if not response_text and not chat_result .tool_call_events :
754784 break
755785 if iteration >= max_iterations - 1 :
@@ -758,7 +788,8 @@ def _execute_single_document_run(
758788 f"[timer] document_skill { conversation_id } GoodData turn { turns } complete after "
759789 f"{ agent_elapsed :.2f} s; answering with the expected charts and period"
760790 )
761- current_question = build_simulated_reply (expected_output )
791+ current_question = build_simulated_reply (expected_output , asked = asked and not replied )
792+ replied = replied or asked
762793
763794 evaluation = evaluate_document_response (
764795 tool_result ,
@@ -767,14 +798,19 @@ def _execute_single_document_run(
767798 skill_activated = _skill_activated (all_tool_call_events , _BUILDER_SKILL ),
768799 legacy_names = legacy_wire_names (all_parts , all_tool_call_events ),
769800 )
801+ if _asked_first_required (expected_output ):
802+ evaluation .applies = replace (evaluation .applies , asked_first = True )
803+ evaluation .asked_first = asked_before_draft
804+ if tool_result is not None and not asked_before_draft :
805+ evaluation .failures .append ("the copilot drafted without asking first" )
770806 if judge is not None and _has_narrative (expected_output ):
771807 timings .judge_s += _judge_narrative (evaluation , judge , document_part , question , expected_output ["narrative" ])
772808
773809 return DocumentRunResult (
774810 conversation_id = conversation_id ,
775811 evaluation = evaluation ,
776812 expects_clarification = _expects_clarification (expected_output ),
777- asked_first = first_turn_asked ,
813+ asked_first = asked_before_draft ,
778814 tool_result = tool_result ,
779815 document_part = document_part ,
780816 total_turns = turns ,
0 commit comments