From a6adbe9f05fbf4661aaa1b9c3f7bd0af64720472 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 12:27:07 -0800 Subject: [PATCH] fix(always_on_agent_verifier): stage the assistant's thinking only when the judge's trajectory filter shows it On the always_on path the judge reads files always_on_staging builds itself, and those carried every recorded thought as an assistant_thinking line whatever the task's trajectory_filter said: include_thinking was applied only on the generic path's compaction. A task that set include_thinking: false had its judge read (and cite) the reasoning of models whose thinking is recorded (Claude, DeepSeek, GLM, Kimi, Qwen), never of GPT, whose reasoning is encrypted. - trajectory_filter.keeps_thinking: the one rule, read by the generic path's OTel and atif/1 compaction and by always_on staging: no filter, the trajectory as recorded; a filter, thinking only with include_thinking. - stage_run takes the judge's trajectory filter, resolved as the generic path resolves it (_run_values, a run's user_overrides.apply_trajectory_filter included); thinking it leaves out is counted in the record (trajectory_staging.thinking_left_out), and the judge's files note says the files don't have it. - A task that sets no filter stages thinking as before. Tests: a filter with include_thinking false (or a filter's default, or the apply_trajectory_filter override's) stages no assistant_thinking line and none of the thinking text, in stage_run and through the verifier into the judge's sandbox; true, no filter, or an override that drops the filter stages it as before. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 36 +++++++++++++------ .../task_steps/verifiers/always_on_staging.py | 24 +++++++++---- .../verifiers/judge_utils/atif_turns.py | 3 +- .../judge_utils/trajectory_filter.py | 10 +++++- .../test_always_on_agent_verifier.py | 35 ++++++++++++++++++ .../verifiers/test_always_on_staging.py | 33 +++++++++++++++++ 6 files changed, 123 insertions(+), 18 deletions(-) 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 bdc1db2be..cd9c54dcd 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,11 @@ 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 staged wakes carry the assistant's thinking only when the run's trajectory filter shows it, by the rule the +generic path's compaction reads (``keeps_thinking``): with no filter, as recorded; with one (a ``trajectory_filter``, +or ``user_overrides.apply_trajectory_filter``), only when it sets ``include_thinking``. Thinking left out is counted in +the entry (``trajectory_staging.thinking_left_out``), and the judge is told the files don't have it. + With full_app_changes (opt-in, with use_trajectory), each staged app change also carries its changed fields in full, an UPDATE's old and new values, an INSERT's or DELETE's whole row, from the run's ``metadata["env_changes"]`` (what a snapshot_env step with include_env_changes records, which the task must run after the always_on step and before this @@ -65,6 +70,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 keeps_thinking from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( TrajectoryFormatError, TurnEvents, @@ -99,10 +105,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. @@ -123,6 +129,11 @@ 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 shows it +# (``keeps_thinking``), else not in the files at all. +_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 = " (the assistant's thinking is not in these files)" # 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 \ @@ -399,8 +410,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 - ``UngradableRunError``.""" + position (``turns_by_position``). The run's trajectory filter (``_run_values``, as the generic path resolves + it) decides whether the turns' thinking is staged (``keeps_thinking``). A trajectory that breaks the harness + labels it carries raises ``UngradableRunError``.""" record = self._record(context, prompt_response) timeline: Optional[list[dict]] = None if not record.get("object_url"): @@ -422,8 +434,10 @@ 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"] 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 @@ -434,7 +448,8 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom # Its turns carry no labels: each trajectory's format is the one its shape reads as. judge.read([{"format": fmt, "trajectories": count, "guessed": True} for fmt, count in (staged.record.get("formats") or {}).items()]) - return StagedTrajectory(path=path, prompt_note=_files_note(path, staged, context_loss=asked), + return StagedTrajectory(path=path, prompt_note=_files_note(path, staged, context_loss=asked, + thinking=keeps_thinking(trajectory_filter)), record=staged.record) async def _read_turns(self, urls: list[str], names: dict[str, str], @@ -569,7 +584,7 @@ def _harness_read(record: dict) -> bool: return bool(record.get("agent_labeled_trajectories") or record.get("compaction_summaries_written_by")) -def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) -> str: +def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False, thinking: bool = True) -> str: r = staged.record wakes = sorted(name for name in staged.files if name.startswith(f"{WAKES_DIR}/wake_")) gaps = sorted(set(r.get("missing_trajectories", [])) | set(r.get("unreadable_trajectories", []))) @@ -587,7 +602,8 @@ 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_STAGED if thinking else _THINKING_LEFT_OUT) 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 2a2bfbcf2..f437c351c 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,11 @@ - ``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), 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, the user's reads). A turn that ended at its time or tool-call limit + own text (``assistant_text``) and its thinking when the trajectory recorded it and the judge's trajectory filter + shows it (``assistant_thinking``; ``keeps_thinking``), what the harness put in the turn (``harness_note``: a + compaction summary, a message it sent the assistant), 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, 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``) and a ``wake_cut_off`` line; the next wake's ``woke`` line has ``cut_off_notice``. A turn's trajectory is matched to its wake by the timeline's ``trajectory_url``; one that's missing is a line saying so. A @@ -39,6 +40,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 TrajectoryFilter, keeps_thinking from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import UNKNOWN, TurnEvents, compaction_words from agent_env.task_step.task_steps.verifiers.run_context import Firing @@ -102,7 +104,8 @@ def lines(self) -> list[dict]: 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 @@ -110,8 +113,11 @@ 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 shows it (``keeps_thinking``: no filter, or ``include_thinking``), else left out and counted in the + record's ``thinking_left_out``.""" stager = _Stager(turns, max((e.get("n") or 0 for e in timeline if e.get("event") == "wake"), default=0)) + stager.thinking = keeps_thinking(trajectory_filter) stager.by_position = by_position stager.change_values = change_values for event in timeline: @@ -186,6 +192,8 @@ 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 = True # whether the judge's trajectory filter shows the turns' thinking (see stage_run) + self.thinking_left_out = 0 def wake(self, n: Optional[int]) -> _Wake: n = n or self.current @@ -293,6 +301,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": @@ -384,6 +395,7 @@ 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), ("turns_by_position", self.by_position)): if value: record[key] = value 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..c2b2022cc 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,14 @@ 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 a judge reading a trajectory through ``trajectory_filter`` is shown the model's thinking: with no filter + it reads the trajectory as recorded, thinking and all; with one, only when the filter sets ``include_thinking``. + Every reader that stages or renders a trajectory's thinking for a judge asks this, so they can't disagree.""" + return trajectory_filter is None 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 +217,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/unit/task_step/test_always_on_agent_verifier.py b/tst/unit/task_step/test_always_on_agent_verifier.py index 66d98ca81..47f9d71f8 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -376,6 +376,41 @@ 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": False}, {}, False), + ({"include_thinking": True}, {}, True), + (None, {}, True), # a task that sets no filter: as before + (None, {"apply_trajectory_filter": True}, False), # the override's filter, include_thinking off + ({"include_thinking": False}, {"apply_trajectory_filter": False}, True), # the override drops the filter +]) +async def test_the_judge_s_files_carry_the_assistant_s_thinking_only_when_its_trajectory_filter_shows_it( + monkeypatch, trajectory_filter, overrides, shown): + """A task whose judge sets include_thinking false, on a model that thinks (wake 4's PSI neutral harness turn, + Claude's, records its reasoning): 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 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 + assert ("the assistant's thinking is not in these files" in captured["prompt"]) is not 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("timeline", ["not kept", "unreadable"]) async def test_without_the_stored_timeline_the_turns_are_staged_by_position_the_same_way(monkeypatch, timeline): 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 f769b7154..69228df92 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -18,6 +18,7 @@ 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 @@ -122,6 +123,38 @@ def test_the_agent_s_thinking_is_a_line_in_its_wake(run): assert next(line for line in lines if line["event"] == "assistant_thinking")["text"].startswith("Nina is allergic") +@pytest.mark.parametrize("trajectory_filter, shown", [ + (None, True), # no filter: the trajectories as recorded, as before + (TrajectoryFilter(include_thinking=True), True), + (TrajectoryFilter(include_thinking=False), False), + (TrajectoryFilter(), False), # a filter's own default leaves thinking out +]) +def test_the_agent_s_thinking_is_staged_only_when_the_judge_s_trajectory_filter_shows_it(run, trajectory_filter, + shown): + """The generic path's rule (``keeps_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.""" + 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) + as_recorded = stage_run(timeline, turns) + + 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) + # Everything else is staged as it is without a filter. + assert [line for line in lines(staged.files) if line["event"] != "assistant_thinking"] == \ + [line for line in lines(as_recorded.files) if line["event"] != "assistant_thinking"] + + def test_every_app_change_is_kept_with_its_whole_summary(run): staged = stage_run(*run)