Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 \
("<field>_file", such as "result_file" or "text_file") and shows its start ("<field>_preview"). Email bodies are \
decoded (body.text). A line longer than 1,800 characters is split across lines there, nothing dropped.
Expand All @@ -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 \
Expand Down Expand Up @@ -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"):
Expand All @@ -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
Expand All @@ -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],
Expand Down Expand Up @@ -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", [])))
Expand All @@ -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]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -102,16 +104,20 @@ 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
index.md and the record (``turns_by_position``) say. ``change_values``: each app change's ``changed_fields`` (an
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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
_TOOL_RESULT_MAX_INLINE_SIZE,
ImageFrame,
TrajectoryFilter,
keeps_thinking,
)

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -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 ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]]]:
Expand All @@ -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(
Expand Down
35 changes: 35 additions & 0 deletions tst/unit/task_step/test_always_on_agent_verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading