From a6adbe9f05fbf4661aaa1b9c3f7bd0af64720472 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 12:27:07 -0800 Subject: [PATCH 1/3] 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) From 3ee200af8db793d2281ff40708261135b5593f4a Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 14:00:06 -0800 Subject: [PATCH 2/3] fix(always_on_agent_verifier): tell the judge the truth about thinking in raw turns, and match the generic path under SCREENSHOT Review fixes on #980: - A turn in a format the staging can't break into events (native OpenCode) is staged as recorded, reasoning included, whatever the filter says. The judge's note no longer claims the files hold no thinking: it names those wakes, and the entry does too (trajectory_staging.thinking_unfiltered_wakes). - keeps_thinking: a SCREENSHOT filter's include_* flags don't apply, so it leaves the thinking as recorded, as the generic path hands an agent judge the raw trajectory. Its docstring now names the readers that ask it and the ones that pass thinking through unfiltered. - The staged files read only include_thinking and compaction_type from the filter; any other setting set away from its default is logged, and the docstrings say so. trajectory_staging.thinking_shown is always recorded. - StagedRun exposes thinking_shown and unfiltered_wakes, so the note reads the staging's own decision instead of computing it a second time. - The note's thinking words are one clause, not a second parenthetical. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 59 ++++++++++++---- .../task_steps/verifiers/always_on_staging.py | 24 ++++++- .../judge_utils/trajectory_filter.py | 16 +++-- .../verifier_golden/rubrics_subclasses.json | 2 + .../test_always_on_agent_verifier.py | 68 ++++++++++++++++++- .../verifiers/test_always_on_staging.py | 38 ++++++++++- 6 files changed, 186 insertions(+), 21 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 cd9c54dcd..7c20a6df0 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 @@ -16,9 +16,14 @@ 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. +generic path's compaction reads (``keeps_thinking``): with no filter, as recorded; with a DEFAULT one (a +``trajectory_filter``, or ``user_overrides.apply_trajectory_filter``), only when it sets ``include_thinking``; a +SCREENSHOT one leaves it as recorded, as the generic path leaves an agent judge's trajectory. That 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. 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 @@ -70,7 +75,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.trajectory_filter import TrajectoryFilter from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( TrajectoryFormatError, TurnEvents, @@ -130,10 +135,16 @@ 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. +# (``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_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)" +_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), ' + "with any thinking it holds") +# 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 \ @@ -411,8 +422,9 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom """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``). 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``.""" + it) decides whether the turns' thinking is staged (``keeps_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 if not record.get("object_url"): @@ -435,6 +447,10 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom # 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 " + "shows 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, trajectory_filter=trajectory_filter) @@ -448,8 +464,7 @@ 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, - thinking=keeps_thinking(trajectory_filter)), + return StagedTrajectory(path=path, prompt_note=_files_note(path, staged, context_loss=asked), record=staged.record) async def _read_turns(self, urls: list[str], names: dict[str, str], @@ -584,7 +599,26 @@ 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, thinking: bool = True) -> str: +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_")) gaps = sorted(set(r.get("missing_trajectories", [])) | set(r.get("unreadable_trajectories", []))) @@ -602,8 +636,7 @@ def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False, thi 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, - thinking=_THINKING_STAGED if thinking else _THINKING_LEFT_OUT) + 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 f437c351c..34d8ca7a8 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 @@ -80,6 +80,19 @@ class StagedRun: files: dict[str, str] record: dict + @property + def thinking_shown(self) -> bool: + """Whether the judge's trajectory filter shows the turns' thinking (``keeps_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: @@ -114,8 +127,10 @@ def stage_run(timeline: Sequence[dict], turns: Mapping[str, Optional[TurnEvents] 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. ``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``.""" + only when it shows it (``keeps_thinking``), 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 = keeps_thinking(trajectory_filter) stager.by_position = by_position @@ -194,6 +209,7 @@ def __init__(self, turns: Mapping[str, Optional[TurnEvents]], last_wake: int): 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 + self.as_recorded: set[int] = set() # wakes with a turn staged as recorded (a format the staging can't read) def wake(self, n: Optional[int]) -> _Wake: n = n or self.current @@ -312,6 +328,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"), 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 @@ -396,9 +414,11 @@ def finish(self, firings: Sequence[Firing], unavailable: Mapping[str, str]) -> S ("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)), ("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/trajectory_filter.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py index c2b2022cc..99eb57474 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 @@ -193,10 +193,18 @@ def from_dict(cls, data: dict) -> TrajectoryFilter: 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 + """Whether ``trajectory_filter`` lets a 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 readers that take a trajectory's thinking apart from the rest ask this: the DEFAULT compactions + (``compact_otel_trajectory``'s GenAI ``chat`` spans, ``compact_atif_trajectory``'s steps) and always_on staging. + What a reader 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, and a turn in a format always_on + staging can't read, staged as recorded.""" + return (trajectory_filter is None or trajectory_filter.compaction_type != CompactionType.DEFAULT + or trajectory_filter.include_thinking) def compact_otel_trajectory( diff --git a/tst/data/verifier_golden/rubrics_subclasses.json b/tst/data/verifier_golden/rubrics_subclasses.json index bff2068a9..bb954d1ce 100644 --- a/tst/data/verifier_golden/rubrics_subclasses.json +++ b/tst/data/verifier_golden/rubrics_subclasses.json @@ -2586,6 +2586,7 @@ "compaction_summaries_written_by": { "assistant": 1 }, + "thinking_shown": true, "judge_reads": [ { "batch": 1, @@ -2677,6 +2678,7 @@ "compaction_summaries_written_by": { "assistant": 1 }, + "thinking_shown": true, "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 47f9d71f8..30c893f1f 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -406,7 +406,73 @@ async def test_the_judge_s_files_carry_the_assistant_s_thinking_only_when_its_tr 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 + # 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 +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), with any thinking it " \ + "holds; 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 shows 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")) 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 69228df92..4b22ad0e0 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -128,11 +128,16 @@ def test_the_agent_s_thinking_is_a_line_in_its_wake(run): (TrajectoryFilter(include_thinking=True), True), (TrajectoryFilter(include_thinking=False), False), (TrajectoryFilter(), False), # a filter's own default leaves thinking out + # A SCREENSHOT filter's include_* flags don't apply: the generic path hands an agent judge the trajectory as + # recorded, thinking and all, and so does this. + (TrajectoryFilter(compaction_type="screenshot"), True), + (TrajectoryFilter(compaction_type="screenshot", frame_strategy="per_criterion"), True), ]) 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.""" + 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"}, @@ -150,11 +155,42 @@ def lines(files: dict) -> list[dict]: 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 as_recorded.record["thinking_shown"] is True + assert staged.unfiltered_wakes == [] and "thinking_unfiltered_wakes" not in staged.record # 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"] +@pytest.mark.parametrize("trajectory_filter, unfiltered", [ + (TrajectoryFilter(include_thinking=False), [2]), + (TrajectoryFilter(include_thinking=True), []), + (None, []), +]) +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) From bedd682ec99abe4c64c508326926f1f1a6b05548 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 15:17:53 -0800 Subject: [PATCH 3/3] fix(always_on_agent_verifier): the judge reads the assistant's thinking only when its filter sets include_thinking: true An always_on judge grades what the assistant did and said, not what it thought. Its staged files now carry thinking only for a DEFAULT trajectory filter that sets include_thinking: true (always_on_staging.stages_thinking). No filter, a filter that doesn't set it (as PSI's always_on tasks store theirs), or a SCREENSHOT filter all stage none. The generic path is unchanged: keeps_thinking still shows a judge with no filter the trajectory as recorded, and its docstring now says always_on doesn't use it. thinking_shown is still recorded on every entry. The judge's note for a turn staged as recorded (an unknown format) now says any thinking in it is not evidence. Goldens re-recorded where this changes them, all four always_on cases: judge_inputs.json (always_on_staged, always_on_atif_staged: smaller wake and events files, the note's left-out wording) and rubrics_subclasses.json (ao_staged_with_what_its_judge_read, ao_context_loss_the_gate_fails: thinking_shown false, thinking_left_out 4, staged_bytes). Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 29 +++++----- .../task_steps/verifiers/always_on_staging.py | 29 +++++++--- .../judge_utils/trajectory_filter.py | 20 +++---- tst/data/verifier_golden/judge_inputs.json | 36 ++++++------ .../verifier_golden/rubrics_subclasses.json | 10 ++-- .../test_always_on_agent_verifier.py | 56 ++++++++++++++----- .../verifiers/test_always_on_staging.py | 41 ++++++++------ 7 files changed, 134 insertions(+), 87 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 7c20a6df0..9492797af 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,15 +15,16 @@ 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 a DEFAULT one (a -``trajectory_filter``, or ``user_overrides.apply_trajectory_filter``), only when it sets ``include_thinking``; a -SCREENSHOT one leaves it as recorded, as the generic path leaves an agent judge's trajectory. That 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. +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. 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 @@ -134,15 +135,15 @@ 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 +# _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. +# (``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), ' - "with any thinking it holds") + "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). @@ -422,7 +423,7 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom """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``). The run's trajectory filter (``_run_values``, as the generic path resolves - it) decides whether the turns' thinking is staged (``keeps_thinking``) and nothing else: a setting of it the + 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) @@ -449,7 +450,7 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom 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 " - "shows the assistant's thinking (%s); these settings of it don't apply to them: %s", + "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, 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 34d8ca7a8..a29efa1df 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 @@ -4,7 +4,7 @@ - ``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 and the judge's trajectory filter - shows it (``assistant_thinking``; ``keeps_thinking``), what the harness put in the turn (``harness_note``: a + 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), 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 @@ -40,7 +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.trajectory_filter import CompactionType, TrajectoryFilter 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 @@ -82,7 +82,7 @@ class StagedRun: @property def thinking_shown(self) -> bool: - """Whether the judge's trajectory filter shows the turns' thinking (``keeps_thinking``): staged as + """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) @@ -115,6 +115,16 @@ 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, @@ -127,12 +137,13 @@ def stage_run(timeline: Sequence[dict], turns: Mapping[str, Optional[TurnEvents] 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. ``trajectory_filter``: the judge's, as the run resolves it; a turn's thinking is staged - only when it shows it (``keeps_thinking``), 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.""" + 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 = keeps_thinking(trajectory_filter) + stager.thinking = stages_thinking(trajectory_filter) stager.by_position = by_position stager.change_values = change_values for event in timeline: @@ -207,7 +218,7 @@ 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 = 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) 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 99eb57474..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 @@ -193,16 +193,16 @@ def from_dict(cls, data: dict) -> TrajectoryFilter: def keeps_thinking(trajectory_filter: Optional[TrajectoryFilter]) -> bool: - """Whether ``trajectory_filter`` lets a 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 readers that take a trajectory's thinking apart from the rest ask this: the DEFAULT compactions - (``compact_otel_trajectory``'s GenAI ``chat`` spans, ``compact_atif_trajectory``'s steps) and always_on staging. - What a reader 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, and a turn in a format always_on - staging can't read, staged as recorded.""" + """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) 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 bb954d1ce..46a5b0057 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,7 +2586,8 @@ "compaction_summaries_written_by": { "assistant": 1 }, - "thinking_shown": true, + "thinking_left_out": 4, + "thinking_shown": false, "judge_reads": [ { "batch": 1, @@ -2669,7 +2670,7 @@ "otel": 1 }, "raw_bytes": 74496, - "staged_bytes": 16967, + "staged_bytes": 16557, "unreadable_trajectories": [ 1, 3 @@ -2678,7 +2679,8 @@ "compaction_summaries_written_by": { "assistant": 1 }, - "thinking_shown": true, + "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 30c893f1f..a141a139b 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -378,22 +378,24 @@ async def test_with_use_trajectory_the_agent_judge_searches_every_wake_staged_as @pytest.mark.asyncio @pytest.mark.parametrize("trajectory_filter, overrides, shown", [ + ({"include_thinking": True}, {}, True), # the one way to show it ({"include_thinking": False}, {}, False), - ({"include_thinking": True}, {}, True), - (None, {}, True), # a task that sets no filter: as before + (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": False}, {"apply_trajectory_filter": False}, True), # the override drops the filter + ({"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_shows_it( +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): - """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.""" + """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 else {})) + **({"trajectory_filter": trajectory_filter} if trajectory_filter is not None else {})) captured = _agent_judge(monkeypatch, verifier, sources) await verifier.execute(ctx) @@ -414,6 +416,32 @@ async def test_the_judge_s_files_carry_the_assistant_s_thinking_only_when_its_tr 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): @@ -437,8 +465,8 @@ async def test_with_thinking_left_out_the_judge_is_told_which_wakes_are_staged_a 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), with any thinking it " \ - "holds; then the rest of the wake" in prompt + "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] @@ -471,7 +499,7 @@ async def test_a_trajectory_filter_setting_the_staged_files_dont_read_is_logged( assert warned == [] else: assert warned == [f"Verifier 'rubric': an always_on run's staged files read only whether its trajectory " - f"filter shows the assistant's thinking (compaction_type, include_thinking); these " + 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")) @@ -724,7 +752,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, @@ -737,7 +765,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 4b22ad0e0..c3424603b 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -23,6 +23,8 @@ 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]: @@ -110,13 +112,15 @@ 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"] @@ -124,20 +128,20 @@ def test_the_agent_s_thinking_is_a_line_in_its_wake(run): @pytest.mark.parametrize("trajectory_filter, shown", [ - (None, True), # no filter: the trajectories as recorded, as before - (TrajectoryFilter(include_thinking=True), True), + (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's include_* flags don't apply: the generic path hands an agent judge the trajectory as - # recorded, thinking and all, and so does this. - (TrajectoryFilter(compaction_type="screenshot"), True), - (TrajectoryFilter(compaction_type="screenshot", frame_strategy="per_criterion"), True), + # 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_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. The record - says which, filter or none.""" +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"}, @@ -146,7 +150,7 @@ def test_the_agent_s_thinking_is_staged_only_when_the_judge_s_trajectory_filter_ assert len(thoughts) == 5 staged = stage_run(timeline, turns, trajectory_filter=trajectory_filter) - as_recorded = stage_run(timeline, turns) + 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)] @@ -156,17 +160,17 @@ def lines(files: dict) -> list[dict]: 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 as_recorded.record["thinking_shown"] is True + assert with_thinking.record["thinking_shown"] is True assert staged.unfiltered_wakes == [] and "thinking_unfiltered_wakes" not in staged.record - # Everything else is staged as it is without a filter. + # 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(as_recorded.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, []), + (None, [2]), ]) def test_a_turn_staged_as_recorded_keeps_its_thinking_and_the_record_names_its_wake(run, trajectory_filter, unfiltered): @@ -517,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