Skip to content
Merged
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,17 @@
A run that kept no timeline has its turns staged the same way by position, one wake file a turn, so the judge never
reads a trajectory as stored.

The judge grades what the assistant did and said, not what it thought: the staged wakes carry its thinking only when
the run's trajectory filter asks for it (``stages_thinking``), a DEFAULT filter (a ``trajectory_filter``, or
``user_overrides.apply_trajectory_filter``'s) that sets ``include_thinking: true``. No filter, a filter that doesn't
set it, or a SCREENSHOT one: no thinking. That is stricter than the generic path (``keeps_thinking``), which shows a
judge with no filter the trajectory as recorded. It is all the staging reads of the filter: its other settings
(``include_tool_calls``, ``include_tool_call_results``, ``include_response``, the SCREENSHOT ones) don't apply to the
staged files, and the log says so when one is set. The entry says whether the thinking was shown
(``trajectory_staging.thinking_shown``) and counts what was left out (``thinking_left_out``), and the judge is told. A
turn in a format the staging can't break into events is staged as recorded, thinking and all: with the thinking left
out, the entry names its wake (``thinking_unfiltered_wakes``) and so does the judge's note.

A wake whose turn stored no trajectory (a turn agent-env gave up waiting on stores none, nor may a turn that failed) is
staged from the run's record with a line saying its trajectory is missing, which the judge's prompt names too. A run
whose every turn failed is judged so even when no turn stored one (``_judges_without_trajectory``); any other run that
Expand Down Expand Up @@ -76,6 +87,7 @@
)
from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import AtifDocuments, TurnSource
from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import turns as turn_sources
from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter
from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import (
INFRA_FAILURE_KINDS,
TrajectoryFormatError,
Expand Down Expand Up @@ -111,10 +123,10 @@
`file:line` it is at, and errors.
- {first} … {last}: one file per wake. First what woke the assistant ("woke", the user's own messages in full as \
"user_message", the whole text it was sent as "wake_input"); then every tool call of its turn with input and result \
("tool_call", numbered "call"), its own text ("assistant_text", which nobody saw) and its thinking when it was \
recorded ("assistant_thinking": why it acted; what it did is in the tool calls and app changes); then the rest of the wake in time \
order: every app change ("app_change", "by": "agent" for its own), its closing reply ("turn_end"; the user never saw \
it), each message the user got ("message_to_user"), a nudge and its calls, and the user's reads of its messages.
("tool_call", numbered "call"), its own text ("assistant_text", which nobody saw){thinking}; then the rest of the \
wake in time order: every app change ("app_change", "by": "agent" for its own), its closing reply ("turn_end"; the \
user never saw it), each message the user got ("message_to_user"), a nudge and its calls, and the user's reads of its \
messages.
- {results}/: what is too long for a line (a tool's input or result, a long message): the line names the file \
("<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 @@ -135,6 +147,17 @@
from the user, the user simulator or contacts are never the assistant's. Order events by their pretend time ("at"), \
not by where they sit in the files.
- You have Bash and Read only: no web, no other agents, and nothing to change.{by_position}{changes}{gaps}{harness}"""
# _FILES_NOTE's words for the assistant's thinking: staged when the judge's trajectory filter asks for it
# (``StagedRun.thinking_shown``), else left out, but for the wakes with a turn staged as recorded
# (``StagedRun.unfiltered_wakes``), which no filter reaches inside: thinking there is not evidence either.
_THINKING_STAGED = (' and its thinking when it was recorded ("assistant_thinking": why it acted; what it did is in the '
'tool calls and app changes)')
_THINKING_LEFT_OUT = ", but not its thinking, which these files leave out"
_THINKING_LEFT_OUT_BUT = (", but not its thinking, which these files leave out except in {wakes}: a turn there is in a "
'format they don\'t break into events, so it is staged as recorded ("trajectory_item" lines), '
"any thinking in it included, which is not evidence")
# The trajectory filter's settings the staged files read (``stage_run``); the rest don't apply to them.
_FILTER_SETTINGS_READ = frozenset({"include_thinking", "compaction_type"})
# Added to _FILES_NOTE for a run staged by position (it kept no timeline).
_BY_POSITION_NOTE = """
- This run kept no timeline, so each wake file is one turn of the assistant by its position, in the order the turns \
Expand Down Expand Up @@ -452,7 +475,9 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom
container: Optional[str]) -> Optional[StagedTrajectory]:
"""The run as files (``stage_run``) in the judge's sandbox, each trajectory matched to its wake by the run's
stored timeline. Without that timeline (not kept, or unreadable), the turns are staged the same way by
position (``turns_by_position``). A trajectory that breaks the harness labels it carries raises
position (``turns_by_position``). The run's trajectory filter (``_run_values``, as the generic path resolves
it) decides whether the turns' thinking is staged (``stages_thinking``) and nothing else: a setting of it the
staging doesn't read is logged. A trajectory that breaks the harness labels it carries raises
``UngradableRunError``."""
record = self._record(context, prompt_response)
timeline: Optional[list[dict]] = None
Expand All @@ -475,8 +500,14 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom
run = run_context or await load_run_context(context, prompt_response)
# A run staged by position has no app changes to fill in.
values = await self._change_values(context) if self.full_app_changes and not by_position else None
trajectory_filter = self._run_values(context)["trajectory_filter"]
if ignored := _settings_not_read(trajectory_filter):
logger.warning("Verifier '%s': an always_on run's staged files read only whether its trajectory filter "
"asks for the assistant's thinking (%s); these settings of it don't apply to them: %s",
self.verifier_id, ", ".join(sorted(_FILTER_SETTINGS_READ)), ignored)
staged = await asyncio.to_thread(stage_run, timeline, turns, firings=run.firings_read(),
unavailable=run.unavailable, by_position=by_position, change_values=values)
unavailable=run.unavailable, by_position=by_position, change_values=values,
trajectory_filter=trajectory_filter)
asked = _harness_read(staged.record) and self.output_format in _CONTEXT_LOSS_FORMATS
if (loss := _CONTEXT_LOSS_RUN.get()) is not None:
loss.asked = asked
Expand Down Expand Up @@ -622,6 +653,25 @@ def _harness_read(record: dict) -> bool:
return bool(record.get("agent_labeled_trajectories") or record.get("compaction_summaries_written_by"))


def _settings_not_read(trajectory_filter: Optional[TrajectoryFilter]) -> dict[str, Any]:
"""The settings of ``trajectory_filter`` set away from a filter's default that the staged files don't read
(``_FILTER_SETTINGS_READ``), at their values."""
if trajectory_filter is None:
return {}
default = TrajectoryFilter().to_dict()
return {k: v for k, v in trajectory_filter.to_dict().items() if k not in _FILTER_SETTINGS_READ and v != default[k]}


def _thinking_words(staged: StagedRun) -> str:
if staged.thinking_shown:
return _THINKING_STAGED
if not (wakes := staged.unfiltered_wakes):
return _THINKING_LEFT_OUT
named = (f"wake {wakes[0]}" if len(wakes) == 1
else "wakes " + ", ".join(str(n) for n in wakes[:-1]) + f" and {wakes[-1]}")
return _THINKING_LEFT_OUT_BUT.format(wakes=named)


def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) -> str:
r = staged.record
wakes = sorted(name for name in staged.files if name.startswith(f"{WAKES_DIR}/wake_"))
Expand All @@ -641,7 +691,7 @@ def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) ->
last=f"{path}/{wakes[-1] if wakes else WAKES_DIR}", results=f"{path}/{RESULTS_DIR}",
events=f"{path}/{EVENTS_FILE}", triggers=f"{path}/{TRIGGERS_FILE}",
by_position=_BY_POSITION_NOTE if r.get("turns_by_position") else "", gaps=gap_note,
changes=changes, harness=harness)
changes=changes, harness=harness, thinking=_thinking_words(staged))


def turns_by_position(prompt_response: PromptResponse) -> list[dict]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

- ``wakes/wake_NNN.jsonl``: what woke the assistant (``woke``, the user's messages in full ``user_message``, the full
text it was sent ``wake_input``), then its turn's tool calls with their inputs and results (``tool_call``), its
own text (``assistant_text``) and its thinking when the trajectory recorded it (``assistant_thinking``), what the
harness put in the turn (``harness_note``: a compaction summary, a message it sent the assistant, its account of
why the wake failed, which has ``failure``), then the rest
of the wake in time order (``app_change`` for every change, ``turn_end`` with its closing reply,
own text (``assistant_text``) and its thinking when the trajectory recorded it and the judge's trajectory filter
asks for it (``assistant_thinking``; ``stages_thinking``), what the harness put in the turn (``harness_note``: a
compaction summary, a message it sent the assistant, its account of why the wake failed, which has ``failure``),
then the rest of the wake in time order (``app_change`` for every change, ``turn_end`` with its closing reply,
``message_to_user``, a ``nudge`` and its calls, ``turn_failed`` for a turn that failed and whether the run went on
after it, the user's reads). A turn that ended at its time or tool-call limit
while the run went on (the step's ``continue_after_wake_limit``) has ``cut_off`` on its ``turn_end`` (or ``nudge``)
Expand Down Expand Up @@ -43,6 +43,7 @@

from agent_env.task_step.task_steps.always_on import BULKY_EVENT_FIELDS, LIMIT_WORDS, woke_by_text
from agent_env.task_step.task_steps.notification_delivery import label_time
from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import CompactionType, TrajectoryFilter
from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import (
UNKNOWN,
TurnEvents,
Expand Down Expand Up @@ -89,6 +90,19 @@ class StagedRun:
files: dict[str, str]
record: dict

@property
def thinking_shown(self) -> bool:
"""Whether the judge's trajectory filter asks for the turns' thinking (``stages_thinking``): staged as
``assistant_thinking`` lines when it does, else left out (the record's ``thinking_left_out`` counts it). A
record without it was staged before the filter was read, thinking and all."""
return self.record.get("thinking_shown", True)

@property
def unfiltered_wakes(self) -> list[int]:
"""With the thinking left out, the wakes with a turn staged as recorded (``trajectory_item`` lines: a format
the staging can't break into events), whose thinking, if they hold any, is still in the files."""
return self.record.get("thinking_unfiltered_wakes", [])


@dataclass
class _Wake:
Expand All @@ -111,18 +125,35 @@ def lines(self) -> list[dict]:
+ self.nudge_changes


def stages_thinking(trajectory_filter: Optional[TrajectoryFilter]) -> bool:
"""Whether an always_on run's staged files carry the assistant's thinking: only when the judge's trajectory filter
asks for it, a DEFAULT filter that sets ``include_thinking`` (True; a filter's own default is False). No filter, a
filter that doesn't set it, or a SCREENSHOT one: no thinking, so the judge grades what the assistant did and said,
not what it thought. Stricter than the generic path (``keeps_thinking``), which shows a judge with no filter the
trajectory as recorded."""
return (trajectory_filter is not None and trajectory_filter.compaction_type == CompactionType.DEFAULT
and trajectory_filter.include_thinking is True)


def stage_run(timeline: Sequence[dict], turns: Mapping[str, Optional[TurnEvents]], *,
firings: Sequence[Firing] = (), unavailable: Optional[Mapping[str, str]] = None,
by_position: bool = False, change_values: Optional[Mapping[tuple[str, Any], Any]] = None) -> StagedRun:
by_position: bool = False, change_values: Optional[Mapping[tuple[str, Any], Any]] = None,
trajectory_filter: Optional[TrajectoryFilter] = None) -> StagedRun:
"""The run's files: ``turns`` holds each trajectory the timeline names, by its url (None for one that couldn't be
read); ``firings`` and ``unavailable`` are the run context's trigger firings and the logs it couldn't read.
``by_position``: the timeline is the run's turns in order, one wake a turn (the run kept none of its own), which
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 asks for it (``stages_thinking``: none, the default, stages none), which the record's
``thinking_shown`` says, else left out and counted in its ``thinking_left_out``. A turn in a format the staging
can't read is staged as recorded whatever the filter says; with the thinking left out, the record names its wake
(``thinking_unfiltered_wakes``). That is all the staging reads of the filter: its other settings don't apply to
these files."""
stager = _Stager(turns, max((e.get("n") or 0 for e in timeline if e.get("event") == "wake"), default=0))
stager.thinking = stages_thinking(trajectory_filter)
stager.by_position = by_position
stager.change_values = change_values
for event in timeline:
Expand Down Expand Up @@ -197,6 +228,9 @@ def __init__(self, turns: Mapping[str, Optional[TurnEvents]], last_wake: int):
self.change_values_found = self.change_values_missing = 0
self.labelled = 0 # trajectories whose spans say which agent made each (``TurnEvents.agent_labels``)
self.summary_writers: Counter = Counter() # compactions by who wrote their summary (``written_by``)
self.thinking = False # whether the judge's trajectory filter asks for the turns' thinking (see stage_run)
self.thinking_left_out = 0
self.as_recorded: set[int] = set() # wakes with a turn staged as recorded (a format the staging can't read)
self.harness_failures: list[dict] = [] # each wake the harness says failed: {wake, kind}

def wake(self, n: Optional[int]) -> _Wake:
Expand Down Expand Up @@ -306,6 +340,9 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]:
lines.append(_line("assistant_text", w.n, turn=which, step=e.get("step"), text=e["text"],
subagent=e.get("subagent")))
elif kind == "thinking":
if not self.thinking:
self.thinking_left_out += 1
continue
lines.append(_line("assistant_thinking", w.n, turn=which, step=e.get("step"), text=e["text"],
subagent=e.get("subagent")))
elif kind == "note":
Expand All @@ -319,6 +356,8 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]:
lines.append(_line("harness_note", w.n, turn=which, step=e.get("step"), compaction=e.get("compaction"),
failure=failure, text=e["text"]))
elif kind == "raw":
# Not broken into events, so no filter reaches inside it: its thinking, if any, is staged too.
self.as_recorded.add(w.n)
lines.append(_line("trajectory_item", w.n, turn=which, item=e["event"]))
staged = sum(len(_dumps(line).encode()) for line in lines) + side
self.raw_bytes += events.raw_bytes
Expand Down Expand Up @@ -402,10 +441,13 @@ def finish(self, firings: Sequence[Firing], unavailable: Mapping[str, str]) -> S
("app_changes_not_recorded", self.unrecorded_changes),
("agent_labeled_trajectories", self.labelled),
("compaction_summaries_written_by", dict(sorted(self.summary_writers.items()))),
("thinking_left_out", self.thinking_left_out),
("thinking_unfiltered_wakes", [] if self.thinking else sorted(self.as_recorded)),
("harness_failures", self.harness_failures),
("turns_by_position", self.by_position)):
if value:
record[key] = value
record["thinking_shown"] = self.thinking
if self.change_values is not None:
record["app_change_values"] = {"found": self.change_values_found, "missing": self.change_values_missing}
return StagedRun(self.files, record)
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
Loading
Loading