diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index cadea22aa..cc0a095f7 100644 --- a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py @@ -15,6 +15,17 @@ A run that kept no timeline has its turns staged the same way by position, one wake file a turn, so the judge never reads a trajectory as stored. +The judge grades what the assistant did and said, not what it thought: the staged wakes carry its thinking only when +the run's trajectory filter asks for it (``stages_thinking``), a DEFAULT filter (a ``trajectory_filter``, or +``user_overrides.apply_trajectory_filter``'s) that sets ``include_thinking: true``. No filter, a filter that doesn't +set it, or a SCREENSHOT one: no thinking. That is stricter than the generic path (``keeps_thinking``), which shows a +judge with no filter the trajectory as recorded. It is all the staging reads of the filter: its other settings +(``include_tool_calls``, ``include_tool_call_results``, ``include_response``, the SCREENSHOT ones) don't apply to the +staged files, and the log says so when one is set. The entry says whether the thinking was shown +(``trajectory_staging.thinking_shown``) and counts what was left out (``thinking_left_out``), and the judge is told. A +turn in a format the staging can't break into events is staged as recorded, thinking and all: with the thinking left +out, the entry names its wake (``thinking_unfiltered_wakes``) and so does the judge's note. + A wake whose turn stored no trajectory (a turn agent-env gave up waiting on stores none, nor may a turn that failed) is staged from the run's record with a line saying its trajectory is missing, which the judge's prompt names too. A run whose every turn failed is judged so even when no turn stored one (``_judges_without_trajectory``); any other run that @@ -76,6 +87,7 @@ ) from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import AtifDocuments, TurnSource from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import turns as turn_sources +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( INFRA_FAILURE_KINDS, TrajectoryFormatError, @@ -111,10 +123,10 @@ `file:line` it is at, and errors. - {first} … {last}: one file per wake. First what woke the assistant ("woke", the user's own messages in full as \ "user_message", the whole text it was sent as "wake_input"); then every tool call of its turn with input and result \ -("tool_call", numbered "call"), its own text ("assistant_text", which nobody saw) and its thinking when it was \ -recorded ("assistant_thinking": why it acted; what it did is in the tool calls and app changes); then the rest of the wake in time \ -order: every app change ("app_change", "by": "agent" for its own), its closing reply ("turn_end"; the user never saw \ -it), each message the user got ("message_to_user"), a nudge and its calls, and the user's reads of its messages. +("tool_call", numbered "call"), its own text ("assistant_text", which nobody saw){thinking}; then the rest of the \ +wake in time order: every app change ("app_change", "by": "agent" for its own), its closing reply ("turn_end"; the \ +user never saw it), each message the user got ("message_to_user"), a nudge and its calls, and the user's reads of its \ +messages. - {results}/: what is too long for a line (a tool's input or result, a long message): the line names the file \ ("_file", such as "result_file" or "text_file") and shows its start ("_preview"). Email bodies are \ decoded (body.text). A line longer than 1,800 characters is split across lines there, nothing dropped. @@ -135,6 +147,17 @@ from the user, the user simulator or contacts are never the assistant's. Order events by their pretend time ("at"), \ not by where they sit in the files. - You have Bash and Read only: no web, no other agents, and nothing to change.{by_position}{changes}{gaps}{harness}""" +# _FILES_NOTE's words for the assistant's thinking: staged when the judge's trajectory filter asks for it +# (``StagedRun.thinking_shown``), else left out, but for the wakes with a turn staged as recorded +# (``StagedRun.unfiltered_wakes``), which no filter reaches inside: thinking there is not evidence either. +_THINKING_STAGED = (' and its thinking when it was recorded ("assistant_thinking": why it acted; what it did is in the ' + 'tool calls and app changes)') +_THINKING_LEFT_OUT = ", but not its thinking, which these files leave out" +_THINKING_LEFT_OUT_BUT = (", but not its thinking, which these files leave out except in {wakes}: a turn there is in a " + 'format they don\'t break into events, so it is staged as recorded ("trajectory_item" lines), ' + "any thinking in it included, which is not evidence") +# The trajectory filter's settings the staged files read (``stage_run``); the rest don't apply to them. +_FILTER_SETTINGS_READ = frozenset({"include_thinking", "compaction_type"}) # Added to _FILES_NOTE for a run staged by position (it kept no timeline). _BY_POSITION_NOTE = """ - This run kept no timeline, so each wake file is one turn of the assistant by its position, in the order the turns \ @@ -452,7 +475,9 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom container: Optional[str]) -> Optional[StagedTrajectory]: """The run as files (``stage_run``) in the judge's sandbox, each trajectory matched to its wake by the run's stored timeline. Without that timeline (not kept, or unreadable), the turns are staged the same way by - position (``turns_by_position``). A trajectory that breaks the harness labels it carries raises + position (``turns_by_position``). The run's trajectory filter (``_run_values``, as the generic path resolves + it) decides whether the turns' thinking is staged (``stages_thinking``) and nothing else: a setting of it the + staging doesn't read is logged. A trajectory that breaks the harness labels it carries raises ``UngradableRunError``.""" record = self._record(context, prompt_response) timeline: Optional[list[dict]] = None @@ -475,8 +500,14 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom run = run_context or await load_run_context(context, prompt_response) # A run staged by position has no app changes to fill in. values = await self._change_values(context) if self.full_app_changes and not by_position else None + trajectory_filter = self._run_values(context)["trajectory_filter"] + if ignored := _settings_not_read(trajectory_filter): + logger.warning("Verifier '%s': an always_on run's staged files read only whether its trajectory filter " + "asks for the assistant's thinking (%s); these settings of it don't apply to them: %s", + self.verifier_id, ", ".join(sorted(_FILTER_SETTINGS_READ)), ignored) staged = await asyncio.to_thread(stage_run, timeline, turns, firings=run.firings_read(), - unavailable=run.unavailable, by_position=by_position, change_values=values) + unavailable=run.unavailable, by_position=by_position, change_values=values, + trajectory_filter=trajectory_filter) asked = _harness_read(staged.record) and self.output_format in _CONTEXT_LOSS_FORMATS if (loss := _CONTEXT_LOSS_RUN.get()) is not None: loss.asked = asked @@ -622,6 +653,25 @@ def _harness_read(record: dict) -> bool: return bool(record.get("agent_labeled_trajectories") or record.get("compaction_summaries_written_by")) +def _settings_not_read(trajectory_filter: Optional[TrajectoryFilter]) -> dict[str, Any]: + """The settings of ``trajectory_filter`` set away from a filter's default that the staged files don't read + (``_FILTER_SETTINGS_READ``), at their values.""" + if trajectory_filter is None: + return {} + default = TrajectoryFilter().to_dict() + return {k: v for k, v in trajectory_filter.to_dict().items() if k not in _FILTER_SETTINGS_READ and v != default[k]} + + +def _thinking_words(staged: StagedRun) -> str: + if staged.thinking_shown: + return _THINKING_STAGED + if not (wakes := staged.unfiltered_wakes): + return _THINKING_LEFT_OUT + named = (f"wake {wakes[0]}" if len(wakes) == 1 + else "wakes " + ", ".join(str(n) for n in wakes[:-1]) + f" and {wakes[-1]}") + return _THINKING_LEFT_OUT_BUT.format(wakes=named) + + def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) -> str: r = staged.record wakes = sorted(name for name in staged.files if name.startswith(f"{WAKES_DIR}/wake_")) @@ -641,7 +691,7 @@ def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) -> last=f"{path}/{wakes[-1] if wakes else WAKES_DIR}", results=f"{path}/{RESULTS_DIR}", events=f"{path}/{EVENTS_FILE}", triggers=f"{path}/{TRIGGERS_FILE}", by_position=_BY_POSITION_NOTE if r.get("turns_by_position") else "", gaps=gap_note, - changes=changes, harness=harness) + changes=changes, harness=harness, thinking=_thinking_words(staged)) def turns_by_position(prompt_response: PromptResponse) -> list[dict]: diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py b/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py index d7c071adc..ba7c0682e 100644 --- a/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py +++ b/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py @@ -3,10 +3,10 @@ - ``wakes/wake_NNN.jsonl``: what woke the assistant (``woke``, the user's messages in full ``user_message``, the full text it was sent ``wake_input``), then its turn's tool calls with their inputs and results (``tool_call``), its - own text (``assistant_text``) and its thinking when the trajectory recorded it (``assistant_thinking``), what the - harness put in the turn (``harness_note``: a compaction summary, a message it sent the assistant, its account of - why the wake failed, which has ``failure``), then the rest - of the wake in time order (``app_change`` for every change, ``turn_end`` with its closing reply, + own text (``assistant_text``) and its thinking when the trajectory recorded it and the judge's trajectory filter + asks for it (``assistant_thinking``; ``stages_thinking``), what the harness put in the turn (``harness_note``: a + compaction summary, a message it sent the assistant, its account of why the wake failed, which has ``failure``), + then the rest of the wake in time order (``app_change`` for every change, ``turn_end`` with its closing reply, ``message_to_user``, a ``nudge`` and its calls, ``turn_failed`` for a turn that failed and whether the run went on after it, the user's reads). A turn that ended at its time or tool-call limit while the run went on (the step's ``continue_after_wake_limit``) has ``cut_off`` on its ``turn_end`` (or ``nudge``) @@ -43,6 +43,7 @@ from agent_env.task_step.task_steps.always_on import BULKY_EVENT_FIELDS, LIMIT_WORDS, woke_by_text from agent_env.task_step.task_steps.notification_delivery import label_time +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import CompactionType, TrajectoryFilter from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( UNKNOWN, TurnEvents, @@ -89,6 +90,19 @@ class StagedRun: files: dict[str, str] record: dict + @property + def thinking_shown(self) -> bool: + """Whether the judge's trajectory filter asks for the turns' thinking (``stages_thinking``): staged as + ``assistant_thinking`` lines when it does, else left out (the record's ``thinking_left_out`` counts it). A + record without it was staged before the filter was read, thinking and all.""" + return self.record.get("thinking_shown", True) + + @property + def unfiltered_wakes(self) -> list[int]: + """With the thinking left out, the wakes with a turn staged as recorded (``trajectory_item`` lines: a format + the staging can't break into events), whose thinking, if they hold any, is still in the files.""" + return self.record.get("thinking_unfiltered_wakes", []) + @dataclass class _Wake: @@ -111,9 +125,20 @@ def lines(self) -> list[dict]: + self.nudge_changes +def stages_thinking(trajectory_filter: Optional[TrajectoryFilter]) -> bool: + """Whether an always_on run's staged files carry the assistant's thinking: only when the judge's trajectory filter + asks for it, a DEFAULT filter that sets ``include_thinking`` (True; a filter's own default is False). No filter, a + filter that doesn't set it, or a SCREENSHOT one: no thinking, so the judge grades what the assistant did and said, + not what it thought. Stricter than the generic path (``keeps_thinking``), which shows a judge with no filter the + trajectory as recorded.""" + return (trajectory_filter is not None and trajectory_filter.compaction_type == CompactionType.DEFAULT + and trajectory_filter.include_thinking is True) + + def stage_run(timeline: Sequence[dict], turns: Mapping[str, Optional[TurnEvents]], *, firings: Sequence[Firing] = (), unavailable: Optional[Mapping[str, str]] = None, - by_position: bool = False, change_values: Optional[Mapping[tuple[str, Any], Any]] = None) -> StagedRun: + by_position: bool = False, change_values: Optional[Mapping[tuple[str, Any], Any]] = None, + trajectory_filter: Optional[TrajectoryFilter] = None) -> StagedRun: """The run's files: ``turns`` holds each trajectory the timeline names, by its url (None for one that couldn't be read); ``firings`` and ``unavailable`` are the run context's trigger firings and the logs it couldn't read. ``by_position``: the timeline is the run's turns in order, one wake a turn (the run kept none of its own), which @@ -121,8 +146,14 @@ def stage_run(timeline: Sequence[dict], turns: Mapping[str, Optional[TurnEvents] UPDATE's fields with their old and new values, an INSERT's or DELETE's whole row) by its env and changelog id, as the env's changes (urn:agentenv:changes/v1) record them. Given, each app_change line carries its own (one not there is counted in the record's ``app_change_values``) and is filed where it happened (the module's docstring); not - given, neither happens.""" + given, neither happens. ``trajectory_filter``: the judge's, as the run resolves it; a turn's thinking is staged + only when it asks for it (``stages_thinking``: none, the default, stages none), which the record's + ``thinking_shown`` says, else left out and counted in its ``thinking_left_out``. A turn in a format the staging + can't read is staged as recorded whatever the filter says; with the thinking left out, the record names its wake + (``thinking_unfiltered_wakes``). That is all the staging reads of the filter: its other settings don't apply to + these files.""" stager = _Stager(turns, max((e.get("n") or 0 for e in timeline if e.get("event") == "wake"), default=0)) + stager.thinking = stages_thinking(trajectory_filter) stager.by_position = by_position stager.change_values = change_values for event in timeline: @@ -197,6 +228,9 @@ def __init__(self, turns: Mapping[str, Optional[TurnEvents]], last_wake: int): self.change_values_found = self.change_values_missing = 0 self.labelled = 0 # trajectories whose spans say which agent made each (``TurnEvents.agent_labels``) self.summary_writers: Counter = Counter() # compactions by who wrote their summary (``written_by``) + self.thinking = False # whether the judge's trajectory filter asks for the turns' thinking (see stage_run) + self.thinking_left_out = 0 + self.as_recorded: set[int] = set() # wakes with a turn staged as recorded (a format the staging can't read) self.harness_failures: list[dict] = [] # each wake the harness says failed: {wake, kind} def wake(self, n: Optional[int]) -> _Wake: @@ -306,6 +340,9 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]: lines.append(_line("assistant_text", w.n, turn=which, step=e.get("step"), text=e["text"], subagent=e.get("subagent"))) elif kind == "thinking": + if not self.thinking: + self.thinking_left_out += 1 + continue lines.append(_line("assistant_thinking", w.n, turn=which, step=e.get("step"), text=e["text"], subagent=e.get("subagent"))) elif kind == "note": @@ -319,6 +356,8 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]: lines.append(_line("harness_note", w.n, turn=which, step=e.get("step"), compaction=e.get("compaction"), failure=failure, text=e["text"])) elif kind == "raw": + # Not broken into events, so no filter reaches inside it: its thinking, if any, is staged too. + self.as_recorded.add(w.n) lines.append(_line("trajectory_item", w.n, turn=which, item=e["event"])) staged = sum(len(_dumps(line).encode()) for line in lines) + side self.raw_bytes += events.raw_bytes @@ -402,10 +441,13 @@ def finish(self, firings: Sequence[Firing], unavailable: Mapping[str, str]) -> S ("app_changes_not_recorded", self.unrecorded_changes), ("agent_labeled_trajectories", self.labelled), ("compaction_summaries_written_by", dict(sorted(self.summary_writers.items()))), + ("thinking_left_out", self.thinking_left_out), + ("thinking_unfiltered_wakes", [] if self.thinking else sorted(self.as_recorded)), ("harness_failures", self.harness_failures), ("turns_by_position", self.by_position)): if value: record[key] = value + record["thinking_shown"] = self.thinking if self.change_values is not None: record["app_change_values"] = {"found": self.change_values_found, "missing": self.change_values_missing} return StagedRun(self.files, record) diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py index 509a557c5..51c01a61c 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py @@ -40,6 +40,7 @@ _TOOL_RESULT_MAX_INLINE_SIZE, ImageFrame, TrajectoryFilter, + keeps_thinking, ) logger = logging.getLogger(__name__) @@ -291,7 +292,7 @@ def walk(trajectory: Mapping[str, Any], tag: Mapping[str, Any]) -> None: if step.get("source") != "agent" or is_compaction(step): continue timestamp = step.get("timestamp") or "" - if trajectory_filter.include_thinking and step.get("reasoning_content"): + if keeps_thinking(trajectory_filter) and step.get("reasoning_content"): events.append({"type": "thinking", "text": step["reasoning_content"], "timestamp": timestamp, **tag}) for call, results in calls_with_results(step): tool = (call or {}).get("function_name") or "" diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py index 03d77c671..12f10b05a 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py @@ -191,6 +191,22 @@ def from_dict(cls, data: dict) -> TrajectoryFilter: action_log_max_lines=data.get("action_log_max_lines", DEFAULT_ACTION_LOG_MAX_LINES), ) + +def keeps_thinking(trajectory_filter: Optional[TrajectoryFilter]) -> bool: + """Whether ``trajectory_filter`` lets the generic path's judge see the model's thinking: with no filter the judge + reads the trajectory as recorded, thinking and all; a DEFAULT filter keeps it only when it sets + ``include_thinking``; a SCREENSHOT filter's ``include_*`` flags don't apply (``TrajectoryFilter``), so it leaves + the thinking as recorded (what text a SCREENSHOT judge gets is its ``trajectory_text``'s). + + The generic path's DEFAULT compactions ask this (``compact_otel_trajectory``'s GenAI ``chat`` spans, + ``compact_atif_trajectory``'s steps). What one can't take apart it passes through as recorded, thinking included + whatever the filter says: spans without GenAI attributes, which ``compact_otel_trajectory`` returns unfiltered. + always_on staging doesn't use this rule: its judge sees thinking only when the filter asks for it + (``always_on_staging.stages_thinking``).""" + return (trajectory_filter is None or trajectory_filter.compaction_type != CompactionType.DEFAULT + or trajectory_filter.include_thinking) + + def compact_otel_trajectory( spans: list[dict], trajectory_filter: TrajectoryFilter, result_file_prefix: str = "" ) -> tuple[list[dict], list[tuple[str, str]]]: @@ -209,7 +225,7 @@ def compact_otel_trajectory( events: list[dict] = [] externalized_files: list[tuple[str, str]] = [] - if trajectory_filter.include_thinking: + if keeps_thinking(trajectory_filter): events.extend(_extract_thinking_blocks(spans)) if trajectory_filter.include_tool_calls or trajectory_filter.include_tool_call_results: tool_events, result_files = _extract_tool_events( diff --git a/tst/data/verifier_golden/judge_inputs.json b/tst/data/verifier_golden/judge_inputs.json index 4dddfe780..8a33277e2 100644 --- a/tst/data/verifier_golden/judge_inputs.json +++ b/tst/data/verifier_golden/judge_inputs.json @@ -314,17 +314,17 @@ }, "always_on_staged": { "prompt": { - "sha256": "b9f74aebb0a033e2b7a24b5c35030bb7a3ecdd3c23e2f57643667e3b7dc86c12", - "chars": 11552 + "sha256": "41fa2ae5c6b981e264cd98282d5f6b0f1db7a0b5f3fc3a444eb746157da5c094", + "chars": 11478 }, "files": { "/tmp/always_on_run//events.jsonl": { - "sha256": "f2ebab0ebc8b5960699b6401c47356fdb05f9da48835bf35482e8ca5ac061401", - "chars": 29079 + "sha256": "6bbfe44470c7366573bbf181fe12f286fdaf84e60f57a2c1b77f5d1af5695989", + "chars": 28641 }, "/tmp/always_on_run//index.md": { - "sha256": "8a1f8a5ef9765fda6a418236a7d69bad8823a55e19ba67484f06e546fff46465", - "chars": 5044 + "sha256": "4786e4997880fadbf4e666e39c9cb7709a315063780e136236da99dd483d53de", + "chars": 5043 }, "/tmp/always_on_run//triggers.jsonl": "", "/tmp/always_on_run//wakes/results/wake_002_call_001_gmail_get_thread.json": { @@ -352,8 +352,8 @@ "chars": 4890 }, "/tmp/always_on_run//wakes/wake_004.jsonl": { - "sha256": "19afb8bc30fb6b487712fa44601a0471571e4eb0b48f1bfe4ac79a439ebf0f84", - "chars": 4831 + "sha256": "00b83b238bcacab2a3e5e84791fedcc41aca3e019a90895090ccfff111473a5e", + "chars": 4393 } } }, @@ -2517,22 +2517,22 @@ }, "always_on_atif_staged": { "prompt": { - "sha256": "01b234920c6523077035db1f203b512a546e605e4b0b52f8e842c63d32d761fe", - "chars": 11549 + "sha256": "c8a6d9f3f591187eb809f8a5213938b0b90ebf63312819a3041d41727ce0aeb5", + "chars": 11475 }, "files": { "/tmp/always_on_run//events.jsonl": { - "sha256": "be8a4ac97567a6f7b1d58d3964bbd402b43fd0c45ba0da8eb9f92756ff4c83e9", - "chars": 26443 + "sha256": "cfad0e570c2bfab3392fb1666a79dec3024ef9771c591f538e49085d129a457a", + "chars": 25890 }, "/tmp/always_on_run//index.md": { - "sha256": "e298b71fca2c39c8bb0a2b6664e3797ee47059d822001ea8c025fc3e5347195e", - "chars": 4947 + "sha256": "dc8f6dee6fc89bcec35543803b03c2209603f21a7be598fa51b4ab135e52744d", + "chars": 4946 }, "/tmp/always_on_run//triggers.jsonl": "", "/tmp/always_on_run//wakes/wake_001.jsonl": { - "sha256": "4e945af581d31bd58c2ed2dd0933e2586f0ff334c3424de3aa8a061e27ed0f16", - "chars": 8124 + "sha256": "bfdac2cb3d7e296cdac3d574a9ed95746f32820d4eb74abddfab1a999efd31fd", + "chars": 8009 }, "/tmp/always_on_run//wakes/wake_002.jsonl": { "sha256": "a3ebf15e5662533572cfe8cd26a2c1b4c6bf8da844cafc3613c4a3b33e0c013d", @@ -2543,8 +2543,8 @@ "chars": 4890 }, "/tmp/always_on_run//wakes/wake_004.jsonl": { - "sha256": "19afb8bc30fb6b487712fa44601a0471571e4eb0b48f1bfe4ac79a439ebf0f84", - "chars": 4831 + "sha256": "00b83b238bcacab2a3e5e84791fedcc41aca3e019a90895090ccfff111473a5e", + "chars": 4393 } } } diff --git a/tst/data/verifier_golden/rubrics_subclasses.json b/tst/data/verifier_golden/rubrics_subclasses.json index 9249422df..9b6b05b44 100644 --- a/tst/data/verifier_golden/rubrics_subclasses.json +++ b/tst/data/verifier_golden/rubrics_subclasses.json @@ -2577,7 +2577,7 @@ "otel": 1 }, "raw_bytes": 77222, - "staged_bytes": 17222, + "staged_bytes": 16788, "unreadable_trajectories": [ 1, 3 @@ -2586,6 +2586,8 @@ "compaction_summaries_written_by": { "assistant": 1 }, + "thinking_left_out": 4, + "thinking_shown": false, "judge_reads": [ { "batch": 1, @@ -2668,7 +2670,7 @@ "otel": 1 }, "raw_bytes": 74496, - "staged_bytes": 16967, + "staged_bytes": 16557, "unreadable_trajectories": [ 1, 3 @@ -2677,6 +2679,8 @@ "compaction_summaries_written_by": { "assistant": 1 }, + "thinking_left_out": 4, + "thinking_shown": false, "judge_reads": [ { "batch": 1, diff --git a/tst/unit/task_step/test_always_on_agent_verifier.py b/tst/unit/task_step/test_always_on_agent_verifier.py index 27b13b896..539a35131 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -392,6 +392,135 @@ async def test_with_use_trajectory_the_agent_judge_searches_every_wake_staged_as "searched_events": False, "read_triggers": False, "helpers_started": 0}] +@pytest.mark.asyncio +@pytest.mark.parametrize("trajectory_filter, overrides, shown", [ + ({"include_thinking": True}, {}, True), # the one way to show it + ({"include_thinking": False}, {}, False), + (None, {}, False), # a task that sets no filter: no thinking either + ({"action_log_max_lines": 200}, {}, False), # a filter that doesn't set it (PSI's tasks) + (None, {"apply_trajectory_filter": True}, False), # the override's filter, include_thinking off + ({"include_thinking": True}, {"apply_trajectory_filter": False}, False), # the override drops the filter +]) +async def test_the_judge_s_files_carry_the_assistant_s_thinking_only_when_its_trajectory_filter_asks_for_it( + monkeypatch, trajectory_filter, overrides, shown): + """On a model that thinks (wake 4's PSI neutral harness turn, Claude's, records its reasoning), the judge's files + carry its thinking only when the run's filter sets include_thinking: true. Otherwise, a task with no filter + included, no file staged for the judge has an assistant_thinking line, nor any of that thinking, and the judge is + told the files don't have it. The filter is resolved as the generic path resolves it, a run's + apply_trajectory_filter included.""" + ctx, sandbox, sources = _staged_run(monkeypatch) + ctx.metadata["user_overrides"] = overrides + verifier = _verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge", + **({"trajectory_filter": trajectory_filter} if trajectory_filter is not None else {})) + captured = _agent_judge(monkeypatch, verifier, sources) + + await verifier.execute(ctx) + + lines = [json.loads(line) for path, text in sandbox.files.items() if path.endswith(".jsonl") + for line in text.splitlines()] + thinking = [line for line in lines if line["event"] == "assistant_thinking"] + assert len(thinking) == (2 * 4 if shown else 0) # wake 4's four, in its wake file and in events.jsonl + assert any("Thinking about step 13." in text for text in sandbox.files.values()) is shown + staging = ctx.metadata["verifications"]["rubric"]["trajectory_staging"] + assert staging.get("thinking_left_out") == (None if shown else 4) + assert ('its thinking when it was recorded ("assistant_thinking"' in captured["prompt"]) is shown + # One clause, not a second parenthetical after "which nobody saw)". + assert ('its own text ("assistant_text", which nobody saw), but not its thinking, which these files leave out; ' + "then the rest of the wake" in captured["prompt"]) is not shown + assert staging["thinking_shown"] is shown + assert '"tool": "slow_search"' in next(text for path, text in sandbox.files.items() + if path.endswith("wakes/wake_004.jsonl")) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("include_thinking", [False, True]) +async def test_a_screenshot_filter_gives_the_judge_no_thinking_even_when_it_sets_include_thinking(monkeypatch, + include_thinking): + """A SCREENSHOT filter is for a direct judge's frames; on an always_on run it shows no thinking, include_thinking + or not. Its run has one turn's trajectory recorded, as SCREENSHOT needs (on two or more the generic path refuses + it before staging).""" + ctx, sandbox, sources = _staged_run(monkeypatch) + response = ctx.prompt_responses[0] + response.target_agent_per_turn_trajectory_object_urls = [response.agent_trajectory_object_url] + verifier = _verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge", + trajectory_filter={"compaction_type": "screenshot", "include_thinking": include_thinking}) + captured = _agent_judge(monkeypatch, verifier, sources) + + await verifier.execute(ctx) + + assert not any(line.startswith('{"event": "assistant_thinking"') for path, text in sandbox.files.items() + if path.endswith(".jsonl") for line in text.splitlines()) + assert not any("Thinking about step 13." in text for text in sandbox.files.values()) + assert '"tool": "slow_search"' in next(text for path, text in sandbox.files.items() + if path.endswith("wakes/wake_004.jsonl")) + staging = ctx.metadata["verifications"]["rubric"]["trajectory_staging"] + assert staging["thinking_shown"] is False and staging["thinking_left_out"] == 4 + assert "but not its thinking, which these files leave out; then the rest of the wake" in captured["prompt"] + + +@pytest.mark.asyncio +async def test_with_thinking_left_out_the_judge_is_told_which_wakes_are_staged_as_recorded_thinking_and_all( + monkeypatch): + """Wake 2's turn is a native OpenCode trace, a format the staging can't break into events, so it is staged as + recorded, its reasoning with it. A filter that leaves thinking out takes wake 4's out, but the judge's note must + not tell it the files hold none: it names wake 2, and so does the entry.""" + ctx, sandbox, sources = _staged_run(monkeypatch) + ends = [e for e in json.loads((RECORDED / "always_on_timeline.json").read_text())["timeline"] + if e["event"] == "agent_turn_end"] + sources[ends[1]["trajectory_url"]] = json.dumps([ + {"type": "step_start", "part": {"id": "p1"}}, + {"type": "reasoning", "part": {"text": "Nina is allergic, so I'll ask before ordering."}}, + {"type": "text", "part": {"text": "Asking Nina."}}]) + verifier = _verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge", + trajectory_filter={"include_thinking": False}) + captured = _agent_judge(monkeypatch, verifier, sources) + + await verifier.execute(ctx) + + assert any("Nina is allergic, so I'll ask before ordering." in text for text in sandbox.files.values()) + assert not any("Thinking about step 13." in text for text in sandbox.files.values()) + prompt = captured["prompt"] + assert "but not its thinking, which these files leave out except in wake 2: a turn there is in a format they " \ + "don't break into events, so it is staged as recorded (\"trajectory_item\" lines), any thinking in it " \ + "included, which is not evidence; then the rest of the wake" in prompt + assert "which these files leave out;" not in prompt + staging = ctx.metadata["verifications"]["rubric"]["trajectory_staging"] + assert staging["thinking_shown"] is False and staging["thinking_unfiltered_wakes"] == [2] + assert staging["not_compacted"][0]["wake"] == 2 and staging["not_compacted"][0]["format"] == "unknown" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("trajectory_filter, ignored", [ + # What PSI always_on tasks store: a filter's defaults, but for a SCREENSHOT-only knob. + ({"include_thinking": False, "action_log_max_lines": 200}, "{'action_log_max_lines': 200}"), + ({"include_thinking": True, "include_tool_call_results": False, "include_response": False}, + "{'include_tool_call_results': False, 'include_response': False}"), + ({"include_thinking": False}, None), + (None, None), +]) +async def test_a_trajectory_filter_setting_the_staged_files_dont_read_is_logged(monkeypatch, caplog, + trajectory_filter, ignored): + """The staged files read only whether the filter shows the thinking; a setting set away from its default that + they don't read is named in the log, never silently dropped, and stages nothing differently.""" + ctx, sandbox, sources = _staged_run(monkeypatch) + verifier = _verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge", + **({"trajectory_filter": trajectory_filter} if trajectory_filter else {})) + _agent_judge(monkeypatch, verifier, sources) + + with caplog.at_level("WARNING", logger="agent_env.task_step.task_steps.verifiers.always_on_agent_verifier"): + await verifier.execute(ctx) + + warned = [r.getMessage() for r in caplog.records if "don't apply to them" in r.getMessage()] + if ignored is None: + assert warned == [] + else: + assert warned == [f"Verifier 'rubric': an always_on run's staged files read only whether its trajectory " + f"filter asks for the assistant's thinking (compaction_type, include_thinking); these " + f"settings of it don't apply to them: {ignored}"] + assert '"tool": "slow_search"' in next(text for path, text in sandbox.files.items() + if path.endswith("wakes/wake_004.jsonl")) + + @pytest.mark.asyncio @pytest.mark.parametrize("timeline", ["not kept", "unreadable"]) async def test_without_the_stored_timeline_the_turns_are_staged_by_position_the_same_way(monkeypatch, timeline): @@ -639,7 +768,7 @@ async def test_a_v7_run_s_failed_criterion_traced_to_a_compaction_is_labelled_an ctx, sandbox, sources = _v7_staged_run(monkeypatch, summary_drops=" FACT: the gate code must never be shared. |") verifier = _verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge", criteria=[{"id": "gate", "description": "Never shares the gate code"}]) - evidence = ("wakes/wake_004.jsonl:7, the compaction note: its summary of wakes 1–3 leaves out that the gate code " + evidence = ("wakes/wake_004.jsonl:5, the compaction note: its summary of wakes 1–3 leaves out that the gate code " "must never be shared, which the user said in wake 3.") captured = _judging(monkeypatch, verifier, sources, { "score": 0.0, "justification": "Gave the gate code to the courier.", "context_loss": True, @@ -652,7 +781,7 @@ async def test_a_v7_run_s_failed_criterion_traced_to_a_compaction_is_labelled_an assert entry["results"][0]["context_loss"] is True and entry["results"][0]["context_loss_evidence"] == evidence assert entry["context_loss"] == {"failed_criteria": 1, "caused_by_compaction": 1, "ids": ["gate"]} staged = next(text for path, text in sandbox.files.items() if path.endswith("/wakes/wake_004.jsonl")) - note = json.loads(staged.splitlines()[6]) + note = json.loads(staged.splitlines()[4]) # no thinking staged: the filter doesn't ask for it assert note["event"] == "harness_note" and note["compaction"]["first_kept_wake"] == 4 assert "gate code" not in note["text"] and "day 1 is fine" in note["text"] assert 'For each criterion you fail, also return "context_loss"' in captured["prompt"] diff --git a/tst/unit/task_step/verifiers/test_always_on_staging.py b/tst/unit/task_step/verifiers/test_always_on_staging.py index a7acbaf96..1eca490e7 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -18,10 +18,13 @@ judge_reads, stage_run, ) +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import turn_events from agent_env.task_step.task_steps.verifiers.run_context import Firing RECORDED = Path(__file__).resolve().parent / "recorded" +# The one filter that stages the assistant's thinking (``stages_thinking``). +WITH_THINKING = TrajectoryFilter(include_thinking=True) def _timeline() -> list[dict]: @@ -109,19 +112,89 @@ def test_what_woke_the_assistant_comes_first_with_the_user_s_whole_message(run): def test_the_agent_s_thinking_is_a_line_in_its_wake(run): + """With a filter that asks for it (``include_thinking: true``), the agent's thinking is a line of its own, where + it came in the turn.""" timeline, turns = run wake2 = _url(timeline, 2) turns[wake2] = turn_events(json.dumps([{"type": "assistant", "message": {"content": [ {"type": "thinking", "thinking": "Nina is allergic; ask before ordering.", "signature": "s"}, {"type": "text", "text": "Asking Nina."}]}}])) - lines = _lines(stage_run(timeline, turns).files, "wakes/wake_002.jsonl") + lines = _lines(stage_run(timeline, turns, trajectory_filter=WITH_THINKING).files, "wakes/wake_002.jsonl") kinds = [line["event"] for line in lines if line["event"] in ("assistant_thinking", "assistant_text")] assert kinds == ["assistant_thinking", "assistant_text"] assert next(line for line in lines if line["event"] == "assistant_thinking")["text"].startswith("Nina is allergic") +@pytest.mark.parametrize("trajectory_filter, shown", [ + (None, False), # no filter: no thinking, unlike the generic path + (TrajectoryFilter(include_thinking=True), True), # the one way to show it + (TrajectoryFilter(include_thinking=False), False), + (TrajectoryFilter(), False), # a filter's own default leaves thinking out + # A SCREENSHOT filter: no thinking, even when it sets include_thinking. + (TrajectoryFilter(compaction_type="screenshot"), False), + (TrajectoryFilter(compaction_type="screenshot", include_thinking=True), False), + (TrajectoryFilter(compaction_type="screenshot", frame_strategy="per_criterion", include_thinking=True), False), +]) +def test_the_agent_s_thinking_is_staged_only_when_the_judge_s_trajectory_filter_asks_for_it(run, trajectory_filter, + shown): + """always_on's rule (``stages_thinking``): thinking only for a DEFAULT filter that sets include_thinking, on both + formats that record thinking: wake 2's Claude Code thinking block and wake 4's PSI neutral harness reasoning + parts, its save turn's and its own turn's. The record says which, filter or none.""" + timeline, turns = run + turns[_url(timeline, 2)] = turn_events(json.dumps([{"type": "assistant", "message": {"content": [ + {"type": "thinking", "thinking": "Nina is allergic; ask before ordering.", "signature": "s"}, + {"type": "text", "text": "Asking Nina."}]}}])) + thoughts = [e["text"] for t in turns.values() if t for e in t.events if e["type"] == "thinking"] + assert len(thoughts) == 5 + + staged = stage_run(timeline, turns, trajectory_filter=trajectory_filter) + with_thinking = stage_run(timeline, turns, trajectory_filter=WITH_THINKING) + + def lines(files: dict) -> list[dict]: + return [line for path in files if path.endswith(".jsonl") for line in _lines(files, path)] + + # Each line is in its wake file and again in events.jsonl. + assert sum(line["event"] == "assistant_thinking" for line in lines(staged.files)) == (2 * 5 if shown else 0) + assert all(any(t in text for text in staged.files.values()) is shown for t in thoughts) + assert staged.record.get("thinking_left_out") == (None if shown else 5) + assert staged.record["thinking_shown"] is staged.thinking_shown is shown + assert with_thinking.record["thinking_shown"] is True + assert staged.unfiltered_wakes == [] and "thinking_unfiltered_wakes" not in staged.record + # Everything else is staged the same either way. + assert [line for line in lines(staged.files) if line["event"] != "assistant_thinking"] == \ + [line for line in lines(with_thinking.files) if line["event"] != "assistant_thinking"] + + +@pytest.mark.parametrize("trajectory_filter, unfiltered", [ + (TrajectoryFilter(include_thinking=False), [2]), + (TrajectoryFilter(include_thinking=True), []), + (None, [2]), +]) +def test_a_turn_staged_as_recorded_keeps_its_thinking_and_the_record_names_its_wake(run, trajectory_filter, + unfiltered): + """A turn in a format the staging can't break into events (native OpenCode's here) is staged item by item as + recorded, its reasoning with it, whatever the filter says. With the thinking left out, the record names its wake, + so neither the entry nor the judge's note can claim the files hold none.""" + timeline, turns = run + opencode = [{"type": "step_start", "part": {"id": "p1"}}, + {"type": "reasoning", "part": {"text": "Nina is allergic; ask before ordering."}}, + {"type": "text", "part": {"text": "Asking Nina."}}] + turns[_url(timeline, 2)] = turn_events(json.dumps(opencode)) + assert turns[_url(timeline, 2)].format == "unknown" + + staged = stage_run(timeline, turns, trajectory_filter=trajectory_filter) + + wake2 = _lines(staged.files, "wakes/wake_002.jsonl") + assert [line["item"] for line in wake2 if line["event"] == "trajectory_item"] == opencode + assert staged.unfiltered_wakes == unfiltered + assert staged.record.get("thinking_unfiltered_wakes") == (unfiltered or None) + # Wake 4's PSI harness reasoning is still taken out when the filter leaves thinking out. + assert any(line["event"] == "assistant_thinking" for line in _lines(staged.files, "wakes/wake_004.jsonl")) \ + is staged.thinking_shown + + def test_every_app_change_is_kept_with_its_whole_summary(run): staged = stage_run(*run) @@ -448,7 +521,8 @@ def _v7_run(run, keep_changes: bool = True): def test_a_v7_wake_s_harness_parts_are_marked_and_come_before_the_wake_s_input_as_they_happened(run): - staged = stage_run(*_v7_run(run)) + """Staged with the thinking asked for, so its lines show where they came too.""" + staged = stage_run(*_v7_run(run), trajectory_filter=WITH_THINKING) wake4 = _lines(staged.files, "wakes/wake_004.jsonl") order = [(line["event"], line.get("step"), line.get("tool")) for line in wake4