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 cc0a095f7..642fef40f 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 @@ -43,7 +43,10 @@ or the harness, not held against the assistant), and, with a per-criterion format, says for each failed criterion whether it traces to context a compaction lost (``context_loss`` on the row; the entry counts them): reported next to the score, never changing it. A trajectory whose compaction doesn't say who wrote its summary leaves the run ungraded -(``UngradableRunError``), never misread. Every entry also says what the run records of the assistant's harness +(``UngradableRunError``), never misread. What the harness's context guard did (v14: results hidden behind stubs or +cut, a compaction inside a wake, a refused call sent again) is in the files as its notes, a result the assistant was +shown cut or as a stub says so on its call, and the judge is told to grade on what the assistant was shown. Every +entry also says what the run records of the assistant's harness (``assistant_harness``: its agent name, its card's name and version and, when its wakes are staged, the harness version and settings its trace reports). """ @@ -128,8 +131,10 @@ 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. +("_file", such as "result_file" or "text_file") and shows its start ("_preview"). A preview can be \ +shortened or left out; the "_file" always holds the whole value. A line with only "event", "wake" and \ +"line_file" was too long to show, and its file holds the whole line. Email bodies are decoded (body.text). A line \ +longer than 1,800 characters is split across lines there, nothing dropped. - {events}: every wake's events in one file, so "did it ever do X" is one search. {triggers}: every trigger firing, \ fired or failed, with its pretend time and the wake it came after. @@ -139,7 +144,7 @@ follow-ups before you decide. - Before you conclude that something never happened, or was never said or done, search every wake for it, long \ texts included: grep -r {wakes}/ (the wake files and {results}/, where a text too long for a line is kept whole; \ -{events} has only its first 300 characters), and name that search in your reason. +{events} has at most the first 300 characters), and name that search in your reason. - The user's messages are the "user_message" lines (and the first wake's "wake_input"); the user saw only the \ "message_to_user" lines. - Cite the wake (and call) number of every piece of evidence, and quote it. @@ -178,6 +183,16 @@ _NOTES_ORDER = """ - Harness notes have no "at": read them in file order.""" _HARNESS_NOTE = _HARNESS_LINES + _LABELLED_LINES + _NOTES_ORDER +# Added after _HARNESS_NOTE for a run in which the harness's context guard acted (its record's +# "context_guard_actions" or "results_shown_not_whole"): what the assistant was shown is not always what the files hold. +_GUARD_NOTE = """ +- "harness_note" lines with "guard" are what the harness's context guard did to keep the assistant's requests inside \ +its model's context window: it hid older tool results behind short stubs, cut new ones short, compacted the history \ +inside a wake, or sent a call refused as too long again. They are the harness's doing, not the assistant's. +- A tool call with "shown_to_assistant" holds the whole result, but the assistant was not shown all of it, as that \ +field says. Grade the assistant on what it was shown: a result cut before it saw it, it saw only that part; a result \ +hidden behind a stub, it saw whole when it came back and only the stub after that. Either way it saw more only where \ +it read the result with result_read, which its later calls show.""" # Added to _FILES_NOTE for a run staged with full_app_changes (its record's "app_change_values"). _FULL_CHANGES_NOTE = """ - Each "app_change" line is one change to an app's data. "by" says whose: "agent" is the assistant's own, "others" \ @@ -680,9 +695,11 @@ def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) -> "for them only the run's record is there: " + ", ".join(str(n) for n in gaps) + ".") if gaps else "" writers = r.get("compaction_summaries_written_by") or {} lines = _HARNESS_NOTE if r.get("agent_labeled_trajectories") else _HARNESS_LINES + _NOTES_ORDER + guarded = r.get("context_guard_actions") or r.get("results_shown_not_whole") harness = (lines + (_FAILURE_NOTE if r.get("harness_failures") else "") + "".join(note for writer, note in _COMPACTION_NOTES.items() if writer in writers) - + (_CONTEXT_LOSS_NOTE if context_loss else "")) if _harness_read(r) else "" + + (_GUARD_NOTE if guarded else "") + (_CONTEXT_LOSS_NOTE if context_loss else "") + ) if _harness_read(r) else "" values = r.get("app_change_values") missing = (f"\n- {values['missing']} app changes have no \"changed_fields\": the run's record of its apps' changes " "doesn't have them, so their \"summary\" is all there is.") if values and values["missing"] else "" 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 ba7c0682e..458d05886 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 @@ -5,8 +5,9 @@ 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 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, + compaction summary, a message it sent the assistant, its account of why the wake failed, which has ``failure``, + what its context guard did, with ``guard``), 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``) @@ -15,9 +16,13 @@ trajectory is matched to its wake by the timeline's ``trajectory_url``; one that's missing is a line saying so. A helper agent's lines carry ``subagent``; those of a turn the harness asked for carry ``step`` (the PSI harness's ``pre_compaction_save``, where only its memory and history tools work; ``after_compaction`` and ``failed_wake`` - for its messages). -- ``wakes/results/``: what is too long for a line to be read whole (a tool's input or result, a long message), named - by wake and call (or line); the line keeps a preview. Lines longer than LINE_CHARS are split there, nothing dropped. + for its messages). A call whose result the harness showed the assistant cut or as a stub says so + (``shown_to_assistant``); the line keeps the whole result. +- ``wakes/results/``: what is too long for a line to be read whole (a tool's input or result, a long message, a guard + note's lists of the results it hid or cut, a compaction's error), named by wake and call (or line); the line keeps a + preview. No line is longer than LINE_CHARS, whatever it holds: one still too long then moves a field that says what + it is too (a made-up tool name) and cuts its previews, and failing that goes whole to a file of its own + (``line_file``). Lines longer than LINE_CHARS in those files are split, nothing dropped. - ``events.jsonl``: every line of every wake, and the run's start and end. ``triggers.jsonl``: every trigger firing. - ``index.md``: a block per wake with its time, what woke it, the user's message, its write actions (tool and key arguments) and messages with the ``file:line`` they're at, a @@ -48,7 +53,9 @@ UNKNOWN, TurnEvents, compaction_words, + guard_words, is_infra_failure, + shown_words, ) from agent_env.task_step.task_steps.verifiers.run_context import Firing @@ -57,10 +64,12 @@ INDEX_FILE = "index.md" EVENTS_FILE = "events.jsonl" TRIGGERS_FILE = "triggers.jsonl" -# A tool call's line stays under this, so a reader shows it whole: past it, its input or result (the longer first) goes -# to its own file under RESULTS_DIR and the line keeps a preview. +# No staged line is longer than this, so a reader shows it whole: past it, the line's longest fields (a tool call's +# input or result first) go to their own files under RESULTS_DIR and the line keeps a preview of each (``fit``). LINE_CHARS = 1800 PREVIEW_CHARS = 300 +# A preview ``fit`` would cut shorter than this to fit its line is dropped instead: its file has the whole. +MIN_PREVIEW_CHARS = 40 # What index.md shows of a message (the wake file has it whole), of one argument, and of one action line. INDEX_TEXT_CHARS = 400 ARG_CHARS = 40 @@ -76,11 +85,20 @@ # assistant. _SAVE_STEP = "pre_compaction_save" _BEFORE_WAKE_STEPS = frozenset({_SAVE_STEP, "after_compaction", "failed_wake"}) -# A line's fields that say what and where it is; ``fit`` moves only the others. +# A line's fields that say what and where it is; ``fit`` moves the others first. _IDENTITY = frozenset({"event", "wake", "at", "call", "turn", "tool", "kind", "state", "outcome", "phase", "by", - "step", "subagent", "compaction", "failure", "internal", "cut_off", "cut_off_notice", - "failed_turn_notice", - "limit"}) + "step", "subagent", "compaction", "guard", "failure", "internal", "cut_off", "cut_off_notice", + "failed_turn_notice", "limit"}) +# The parts of an identity field that say what its note is: a guard's action and the wake and call it ran before, who +# wrote a compaction's summary and whether it ran inside a wake, the kind of a failed wake's failure. ``fit`` moves the +# field's other parts as it moves the line's own fields: a guard's lists of the results it hid or cut (hundreds long +# for a mask or a refused call's retry), a compaction's or its save turn's error (the provider's own text), what a +# failed wake was running. +_IDENTIFYING_PARTS = {"guard": frozenset({"action", "wake", "call"}), + "compaction": frozenset({"written_by", "mid_wake"}), + "failure": frozenset({"kind"})} +# What is left of a line that goes whole to a file of its own (``fit``'s last step), besides that file's name. +_KEPT = frozenset({"event", "wake"}) @dataclass(frozen=True) @@ -228,6 +246,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.guard_actions: Counter = Counter() # the harness's context guard's actions, by ``action`` + self.shown: Counter = Counter() # results the harness showed the assistant not whole, by how (``shown.as``) 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) @@ -348,13 +368,16 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]: elif kind == "note": if e.get("compaction"): self.summary_writers[e["compaction"]["written_by"]] += 1 + if e.get("guard"): + self.guard_actions[str(e["guard"].get("action"))] += 1 failure = e.get("failure") if failure: self.harness_failures.append({"wake": w.n, "kind": failure.get("kind")}) - # Its message is in the note's text, which moves to a file when long; ``failure`` stays inline. + # Its message is already in the note's text. The rest stays in ``failure``, whose kind is always + # inline; ``fit`` moves a long part of it to a file (``_IDENTIFYING_PARTS``). failure = {k: v for k, v in failure.items() if k != "message"} lines.append(_line("harness_note", w.n, turn=which, step=e.get("step"), compaction=e.get("compaction"), - failure=failure, text=e["text"])) + guard=e.get("guard"), 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) @@ -371,41 +394,74 @@ def call(self, w: _Wake, e: dict, which: str) -> tuple[dict, int]: """The call's line; while it is longer than LINE_CHARS its longer of input and result goes to a file.""" name = re.sub(r"[^A-Za-z0-9_.-]", "_", _short_tool(e["tool"]))[:60] stem = f"{RESULTS_DIR}/wake_{w.n:0{self.width}d}_call_{w.call_count:03d}_{name}" + if e.get("shown"): + self.shown[e["shown"]["as"]] += 1 line = _line("tool_call", w.n, call=w.call_count, turn=which, step=e.get("step"), tool=e["tool"], subagent=e.get("subagent"), internal=e.get("internal"), input=e.get("input"), - error=e.get("error")) + error=e.get("error"), shown_to_assistant=shown_words(e["shown"]) if e.get("shown") else None) if "result" in e: line["result"] = e["result"] else: line["no_result"] = True return self.fit(line, stem, ("input", "result")) - def fit(self, line: dict, stem: str, movable: Sequence[str]) -> tuple[dict, int]: - """``line`` shortened to LINE_CHARS, so a reader shows it whole: its longest ``movable`` field at a time goes to - a file named from ``stem`` (``.json``, ``.txt``, or with ``_`` for a field other than a - tool call's result) and leaves a preview. Returns the bytes it wrote.""" - written = 0 - while len(_dumps(line)) > LINE_CHARS and (inline := [k for k in movable if line.get(k) not in (None, "")]): - key = max(inline, key=lambda k: len(_dumps(line[k]))) - value = line.pop(key) - body = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, indent=1, default=str) - wrapped = _wrapped(body) - # A wrapped file is .txt even when it held JSON: it no longer parses as one. - ext = "txt" if isinstance(value, str) or wrapped != body else "json" - path = f"{stem}{'' if key == 'result' else '_' + key}.{ext}" - body = wrapped - self.files[path] = body - written += len(body.encode()) - line[f"{key}_file"] = path - line[f"{key}_preview"] = _cut(value if isinstance(value, str) else _dumps(value), PREVIEW_CHARS) + def fit(self, line: dict, stem: str, movable: Sequence[str | tuple[str, str]]) -> tuple[dict, int]: + """``line`` shortened to LINE_CHARS, so a reader shows it whole, whatever it holds. First its longest + ``movable`` field at a time goes to a file named from ``stem`` (``.json``, ``.txt``, or with + ``_`` for a field other than a tool call's result) and leaves a preview; a ``(field, part)`` is a part + of one of its fields, whose ``_file`` and ``_preview`` stay in that field (``__`` in + the file's name). A value no longer than a preview stays: moving it would only lengthen the line. A line still + too long then moves its longest values left inline the same way, those of fields that say what it is included + (a made-up tool name, a plug-in's outcome); then cuts its previews, longest first, their files having them + whole; and one too long even then goes whole to a file of its own (``_line``), leaving its event, its + wake and that file (``line_file``). Returns the bytes it wrote.""" + written = self._move(line, stem, movable) + if _too_long(line): + written += self._move(line, stem, _inline(line)) + _cut_previews(line) + if _too_long(line): + whole = {k: line.pop(k) for k in list(line) if k not in _KEPT} + written += self._write(line, "line", f"{stem}_line", whole) return line, written + def _move(self, line: dict, stem: str, keys: Sequence[str | tuple[str, str]]) -> int: + """While ``line`` is longer than LINE_CHARS, the longest of ``keys`` longer than a preview to a file (``fit``), + its preview left in its place; the bytes it wrote.""" + written = 0 + while _too_long(line) and (long := [k for k in keys if len(_dumps(_part(line, k))) > PREVIEW_CHARS]): + key = max(long, key=lambda k: len(_dumps(_part(line, k)))) + if isinstance(key, tuple): + outer, name = key + holder = line[outer] = dict(line[outer]) # a copy: the trajectory's own event keeps every part + suffix = f"_{outer}_{name}" + else: + holder, name, suffix = line, key, "" if key == "result" else "_" + key + value = holder.pop(name) + written += self._write(holder, name, f"{stem}{suffix}", value) + holder[f"{name}_preview"] = _cut(value if isinstance(value, str) else _dumps(value), PREVIEW_CHARS) + return written + + def _write(self, holder: dict, name: str, stem: str, value: Any) -> int: + """``value`` to the file ``.json`` (``.txt`` for a text, or for JSON split into lines of LINE_CHARS), + named in ``holder`` as ``_file``; the bytes it wrote.""" + body = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, indent=1, default=str) + wrapped = _wrapped(body) + # A wrapped file is .txt even when it held JSON: it no longer parses as one. + path = f"{stem}.{'txt' if isinstance(value, str) or wrapped != body else 'json'}" + self.files[path] = wrapped + holder[f"{name}_file"] = path + return len(wrapped.encode()) + def fit_all(self, lines: list[dict], prefix: str) -> list[dict]: - """Every line but a tool call's (``call`` fits those) shortened by ``fit``, its files named by line number.""" + """Every line but a tool call's (``call`` fits those) shortened by ``fit``, its files named by line number: its + fields that don't say what and where it is (``_IDENTITY``) first, with the parts of those that do which don't + say what their note is (``_IDENTIFYING_PARTS``).""" for i, line in enumerate(lines, 1): if line["event"] != "tool_call": + parts = [(k, p) for k, keep in _IDENTIFYING_PARTS.items() if isinstance(line.get(k), dict) + for p in line[k] if p not in keep] self.fit(line, f"{RESULTS_DIR}/{prefix}_line_{i:03d}_{line['event']}", - [k for k in line if k not in _IDENTITY]) + [k for k in line if k not in _IDENTITY] + parts) return lines def finish(self, firings: Sequence[Firing], unavailable: Mapping[str, str]) -> StagedRun: @@ -441,6 +497,8 @@ 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()))), + ("context_guard_actions", dict(sorted(self.guard_actions.items()))), + ("results_shown_not_whole", dict(sorted(self.shown.items()))), ("thinking_left_out", self.thinking_left_out), ("thinking_unfiltered_wakes", [] if self.thinking else sorted(self.as_recorded)), ("harness_failures", self.harness_failures), @@ -453,9 +511,67 @@ def finish(self, firings: Sequence[Firing], unavailable: Mapping[str, str]) -> S return StagedRun(self.files, record) +def _part(line: dict, key: str | tuple[str, str]) -> Any: + """A field of a line, or for ``(field, part)`` that part of one of its fields.""" + return (line.get(key[0]) or {}).get(key[1]) if isinstance(key, tuple) else line.get(key) + + +def _too_long(line: dict) -> bool: + return len(_dumps(line)) > LINE_CHARS + + +def _left(holder: dict, key: str) -> bool: + """Whether ``key`` is what ``fit`` left in ``holder`` (a line or one of its fields) for a value it moved: a + ``_file``, or the ``_preview`` beside one. A field of the run's own named ``…_file`` counts too: it + stays inline, and if that leaves its line too long the line goes whole to a file.""" + return key.endswith("_file") or (key.endswith("_preview") and f"{key[:-len('_preview')]}_file" in holder) + + +def _inline(line: dict) -> list[str | tuple[str, str]]: + """What ``line`` still holds inline, as ``fit`` names it: each of its fields but its event and wake and what + ``fit`` left, a field that is a dict by its parts.""" + fields = [k for k, v in line.items() if k not in _KEPT and not _left(line, k)] + return ([k for k in fields if not isinstance(line[k], dict)] + + [(k, p) for k in fields if isinstance(line[k], dict) for p in line[k] if not _left(line[k], p)]) + + +def _cut_previews(line: dict) -> None: + """While ``line`` is longer than LINE_CHARS, its longest preview (``fit``'s, in the line or one of its fields) cut + by as much as the line is over, or dropped once that leaves it under MIN_PREVIEW_CHARS: its file has it whole.""" + if not _too_long(line): + return + for k, v in list(line.items()): + if isinstance(v, dict): + line[k] = dict(v) # a copy: the trajectory's own event keeps its own + holders = [line, *(v for v in line.values() if isinstance(v, dict))] + while _too_long(line) and (previews := [(h, k) for h in holders for k in h + if k.endswith("_preview") and _left(h, k)]): + holder, key = max(previews, key=lambda hk: len(hk[0][hk[1]])) + keep = len(holder[key]) - (len(_dumps(line)) - LINE_CHARS) - 1 + if keep < MIN_PREVIEW_CHARS: + del holder[key] + else: + holder[key] = holder[key][:keep] + "…" + + def _text(line: dict, key: str) -> Any: - """A field of a line, or its preview when ``fit`` moved it to a file.""" - return line.get(key) if line.get(key) is not None else line.get(f"{key}_preview") + """A field of a line, or its preview when ``fit`` moved it to a file, or that file's name when ``fit`` cut its + preview away.""" + if line.get(key) is not None: + return line[key] + if line.get(f"{key}_preview") is not None: + return line[f"{key}_preview"] + return f"(in {line[f'{key}_file']})" if line.get(f"{key}_file") else None + + +def _index_facts(line: dict, field: str, chars: int) -> dict: + """A line's ``field`` (a note's ``guard`` or ``compaction``) as index.md words it: each part by its value or, when + ``fit`` moved it to a file, its preview, and a text cut to ``chars``, so the words stay short and still say what + the note did (that a compaction failed). The wake file has every part whole.""" + facts = line[field] + parts = [k for k in facts if not _left(facts, k)] + [k[:-len("_file")] for k in facts if k.endswith("_file")] + shown = {part: _text(facts, part) for part in parts} + return {part: _cut(value, chars) if isinstance(value, str) else value for part, value in shown.items()} def _changing_tools(lines: list[dict]) -> set[str]: @@ -492,7 +608,7 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c for i, line in enumerate(lines, 1): event = line["event"] acted = acted or (event in ("assistant_text", "assistant_thinking", "tool_call") and not line.get("step")) - tool = line.get("tool") or "" + tool = _text(line, "tool") or "" # a made-up name too long for its line: its preview # A tool the harness provides itself ("internal": its notes, its look-ups of past wakes) changes no app. own = bool(line.get("internal")) writes = not own and (_short_tool(tool) in changing if by_changes else is_write_action(tool)) @@ -503,7 +619,7 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c kind = "possible action (no app change names this tool)" if guessed else "action" out.append(f"- {'FAILED ' if line.get('error') else ''}{kind}: {action} ({path}:{i})") elif event == "tool_call" and line.get("error"): - out.append(f"- error: {_short_tool(line['tool'])} failed ({path}:{i})") + out.append(f"- error: {_cut(_short_tool(tool), ACTION_CHARS)} failed ({path}:{i})") elif event == "message_to_user": out.append(f"- sent the user ({label_time(line.get('at'))}): \"{_cut(_text(line, 'text'), INDEX_TEXT_CHARS)}\" " f"({path}:{i})") @@ -538,7 +654,14 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c if line.get("cut_off") else "") out.append(f"- nudged after closing text; then {line.get('outcome')}{cut} ({path}:{i})") elif event == "harness_note" and line.get("compaction") is not None: - out.append(f"- {_compaction_line(line['compaction'], during=acted)} ({path}:{i})") + during = acted or bool(line["compaction"].get("mid_wake")) + # Its errors as much as index.md shows of a message. + facts = _index_facts(line, "compaction", INDEX_TEXT_CHARS) + out.append(f"- {_compaction_line(facts, during=during)} ({path}:{i})") + elif event == "harness_note" and line.get("guard") is not None: + # Its lists (the results' handles and tools) as much as index.md shows of an argument. + out.append(f"- context guard (the harness's): {guard_words(_index_facts(line, 'guard', ARG_CHARS))} " + f"({path}:{i})") elif event == "harness_note" and line.get("failure"): failure = line["failure"] whose = "; an infrastructure failure isn't the assistant's doing" if is_infra_failure(failure) else "" @@ -589,8 +712,10 @@ def _index(stager: _Stager, blocks: list[str], start: list[dict], end: list[dict f"Each wake's events are in {wake_file(1, width)} … {wake_file(max(stager.wakes or [1]), width)}, one JSON " "object a line; `file:line` below points into them. Long tool results and inputs are in " f"{RESULTS_DIR}/ (the tool_call line names its file). {EVENTS_FILE} has every wake's lines in one file; " - f"{TRIGGERS_FILE} has every trigger firing. A line too long to read whole keeps a preview of its longest " - f"fields and names the file in {RESULTS_DIR}/ that holds them (\"_file\").", + f"{TRIGGERS_FILE} has every trigger firing. A line too long to read whole names the file in {RESULTS_DIR}/ " + "that holds each of its longest fields (\"_file\") and keeps a preview of each, shortened or left " + "out when the line needs it; a line that is only \"event\", \"wake\" and \"line_file\" was too long to " + "show, and its file holds the whole line.", "", "Actions below are the assistant's tool calls of a tool that changed the apps' data in that wake (from the " "apps' change logs). A \"possible action\" is a call of a tool no app change in the run names whose name " diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py index 7561c9328..a3c43305c 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py @@ -52,11 +52,14 @@ @dataclass(frozen=True) class TurnEvents: """``events`` in turn order, each ``{"type": "text", "text"}``, ``{"type": "tool_call", "tool", "id", "input", - "result", "error"}`` (``result`` absent when none came back; ``internal`` for a tool the harness provides itself), ``{"type": "prompt", "text"}`` (the turn's input, - when the format records it), ``{"type": "note", "text"}`` (a message the harness put in the turn; a compaction's - also has ``compaction``, what its span recorded: ``written_by``, ``wakes_summarized``, ``wakes_kept``, - ``first_kept_wake``, ``waited_s``; the harness's account of a failed wake has ``failure``: its ``kind`` and what - else its span recorded) or ``{"type": "final", "text", "error"}``; for an unknown format, + "result", "error"}`` (``result`` absent when none came back; ``internal`` for a tool the harness provides itself; + ``shown``, ``{"as", "chars"}``, for a result the harness showed the model cut or as a stub, not whole), + ``{"type": "prompt", "text"}`` (the turn's input, when the format records it), ``{"type": "note", "text"}`` (a + message the harness put in the turn; a compaction's also has ``compaction``, what its span recorded: + ``written_by``, ``wakes_summarized``, ``wakes_kept``, ``first_kept_wake``, ``waited_s``, and for one inside a wake + ``mid_wake`` and ``calls_summarized``; the harness's account of a failed wake has ``failure``: its ``kind`` and what + else its span recorded; one for an action of the harness's context guard has ``guard``, its facts) or + ``{"type": "final", "text", "error"}``; for an unknown format, ``{"type": "raw", "event"}`` per stored item. ``agent_labels``: its spans say which agent made each, or hold the harness's own compaction or messages (``has_agent_labels``).""" @@ -171,13 +174,23 @@ def _settle(call: dict, result: Any, error: bool) -> None: # summary call's text is a ``compaction`` part). The harness's own records are ``harness.*`` spans: the compaction # (``harness.compaction``, from the start of the save turn to the end of the summary, its ``written_by`` saying who # wrote the summary), each message it put before the assistant (``harness.message``, with its ``purpose``), and why a -# wake failed (``harness.error``, its ``kind`` also on that wake's ``failed_wake`` message). +# wake failed (``harness.error``, its ``kind`` also on that wake's ``failed_wake`` message). From v14 its context guard, +# which keeps each model call inside the model's window, records each action before a call as a ``harness.guard`` span +# (``harness.guard.action``: mask, compact, cut or retry), marks a tool span whose result the model was shown cut or as +# a stub (``harness.guard.shown_as``, ``harness.guard.shown_chars``), and marks a model call whose reply it set aside +# and sent again (``harness.call.resent``: "empty" or "cut"), that reply never the run's. _AGENT = "gen_ai.agent.name" _MAIN_AGENT = "gen_ai.main_agent.name" _OUTPUT_MESSAGES = "gen_ai.output.messages" _COMPACTION = "harness.compaction" _MESSAGE = "harness.message" _ERROR = "harness.error" +_GUARD = "harness.guard" +_RESENT = "harness.call.resent" +_SHOWN_AS = "harness.guard.shown_as" +_SHOWN_CHARS = "harness.guard.shown_chars" +# A tool span's shown_as that says the model saw the result whole. +_SHOWN_WHOLE = frozenset({"full", "whole"}) _SAVE = "pre_compaction_save" _AFTER = "after_compaction" _FAILED_WAKE = "failed_wake" @@ -215,8 +228,10 @@ def _otel_events(spans: list[dict]) -> list[dict]: those of a step the harness asked for carry ``step`` (``_steps``). A model span of an agent other than the main one, not nested under a tool call, is the harness's step (the compaction summary call): its text and reasoning are left out, the summary being the compaction note's. The compaction (at its end, once the summary is written) and - each message the harness sent are notes. A compaction that doesn't say who wrote its summary (``written_by``, one - of ``SUMMARY_WRITERS``) raises ``TrajectoryFormatError``.""" + each message the harness sent are notes, as is each action of its context guard (``harness.guard``); a tool call + whose result the guard showed the model cut or as a stub says so (``shown``), and a model call's reply the harness + set aside and sent again (``harness.call.resent``) is left out. A compaction that doesn't say who wrote its summary + (``written_by``, one of ``SUMMARY_WRITERS``) raises ``TrajectoryFormatError``.""" by_id = {_span_id(s): s for s in spans if _span_id(s)} # Only a trace that carries a harness's own labels (``harness.*``) gets the harness reading: its summary call # left out and its save turn marked. A plain OpenTelemetry trace keeps every agent's words, a hand-off's too. @@ -237,6 +252,8 @@ def _otel_events(spans: list[dict]) -> list[dict]: _settle(call, output, (span.get("status") or {}).get("status_code") == "ERROR") if attrs.get("harness.tool") is True: # a tool the harness provides itself (its notes, past wakes) call["internal"] = True + if shown := _shown(attrs): + call["shown"] = shown timed.append((start, i, {**call, **tag})) continue if span.get("name") == _COMPACTION: @@ -247,10 +264,18 @@ def _otel_events(spans: list[dict]) -> list[dict]: if span.get("name") == _MESSAGE: timed.append((start, i, {"type": "note", "text": _harness_message_note(attrs), **tag})) continue + if span.get("name") == _GUARD: + facts = _span_guard_facts(attrs) + # Before the call it guarded; a compaction's once it is done, after the compaction's own note. + at = str(span.get("end_time") or start) if facts.get("action") == "compact" else start + timed.append((at, i, {"type": "note", "text": guard_note(facts), "guard": facts})) + continue if span.get("name") == _ERROR: # the harness's own span, which _is_harness_own would leave out failure = _span_failure(attrs) timed.append((start, i, {"type": "note", "text": _failure_note(failure), "failure": failure})) continue + if attrs.get(_RESENT): # a reply the harness set aside and sent the call again for: none of it reached the run + continue if harness and _is_harness_own(span, attrs, by_id): continue thinking = _span_thinking(attrs) @@ -344,12 +369,14 @@ def compaction_facts(written_by: Any, trigger: Any = None, tokens_before: Any = def _span_compaction_facts(attrs: dict) -> dict: """What a ``harness.compaction`` span recorded: who wrote the summary (``written_by``: "assistant", its own model, or "harness"), the wakes it summarized and kept (the harness's wake numbers, from the first kept one), how late - (real seconds) the wake it came before started (``waited_s``, the span's ``next_wake_waited_s``), and a failed save - turn's or compaction's error. Raises ``TrajectoryFormatError`` for a span that doesn't say who wrote the summary.""" + (real seconds) the wake it came before started (``waited_s``, the span's ``next_wake_waited_s``), a failed save + turn's or compaction's error, and for one the context guard ran inside a wake, ``mid_wake`` and how many of the + wake's tool calls it summarized (``calls_summarized``). Raises ``TrajectoryFormatError`` for a span that doesn't say who wrote the summary.""" facts = compaction_facts(attrs.get(f"{_COMPACTION}.written_by"), said=f"its {_COMPACTION} span has {_COMPACTION}.written_by") named = {"wakes_summarized": "wakes_summarized", "wakes_kept": "wakes_kept", "first_kept_wake": "first_kept_wake", - "waited_s": "next_wake_waited_s", "save_error": "save_error", "error": "error"} + "waited_s": "next_wake_waited_s", "save_error": "save_error", "error": "error", "mid_wake": "mid_wake", + "calls_summarized": "calls_summarized"} return {**facts, **{key: attrs[f"{_COMPACTION}.{attr}"] for key, attr in named.items() if attrs.get(f"{_COMPACTION}.{attr}") is not None}} @@ -366,6 +393,8 @@ def compaction_words(facts: dict) -> list[str]: first, kept = facts.get("first_kept_wake"), facts.get("wakes_kept") if facts.get("error") is not None: words.append(f"it failed, so the history was left whole: {facts['error']}") + elif facts.get("mid_wake"): + words += _mid_wake_words(facts) elif isinstance(first, int) and first > 1: words.append(f"{_wakes(1, first - 1)} {'is' if first == 2 else 'are'} now in the summary") if isinstance(kept, int) and kept > 0: @@ -391,6 +420,25 @@ def compaction_words(facts: dict) -> list[str]: return words +def _mid_wake_words(facts: dict) -> list[str]: + """A compaction inside a wake (the context guard's) in words: the earlier wakes (``wakes_summarized``, the wakes + before this one) and this wake's first tool calls (``calls_summarized``) now in the summary, this wake's message and + latest turns kept.""" + wakes, calls = facts.get("wakes_summarized"), facts.get("calls_summarized") + summarized = [] + if isinstance(wakes, int) and wakes > 0: + summarized.append(_wakes(1, wakes)) + if isinstance(calls, int) and calls > 0: + summarized.append(f"this wake's first {calls} tool call{'s' if calls != 1 else ''}") + words = ["it ran inside this wake, between two of the assistant's model calls, to keep the request inside the " + "model's context window"] + if summarized: + singular = len(summarized) == 1 and (summarized[0] == "wake 1" or calls == 1) + words.append(f"{' and '.join(summarized)} {'is' if singular else 'are'} now in the summary") + words.append("this wake's message and its latest turns kept word for word") + return words + + # What set a compaction off, as its note says it. _TRIGGER_WORDS = {"manual": "it was set off on request, such as by a command (manual)", "auto": "the harness set it off on its own (auto)"} @@ -428,6 +476,90 @@ def _harness_message_note(attrs: dict) -> str: + str(attrs.get("harness.message.text") or "")) +def _count(value: Any) -> Optional[int]: + """A count a span recorded, as an int (an attribute exported as a string included); None for anything else.""" + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + return int(value) if isinstance(value, str) and value.strip().isdigit() else None + + +def _shown(attrs: dict) -> Optional[dict]: + """How the harness showed the model a tool span's result when not whole (``harness.guard.shown_as``: "cut" or + "stub"), with the characters it saw (``harness.guard.shown_chars``); None for one it saw whole.""" + shown_as = attrs.get(_SHOWN_AS) + if shown_as in (None, "") or str(shown_as) in _SHOWN_WHOLE: + return None + chars = _count(attrs.get(_SHOWN_CHARS)) + return {"as": str(shown_as), **({"chars": chars} if chars is not None else {})} + + +def shown_words(shown: dict) -> str: + """A tool call's ``shown`` in words, for the judge: how much of the result the assistant was shown.""" + chars = f" of {shown['chars']:,} characters" if isinstance(shown.get("chars"), int) else "" + if shown.get("as") == "cut": + to = f" to {shown['chars']:,} characters" if chars else "" + return (f"the harness's context guard cut this result{to} before the assistant was shown it, so the assistant " + "saw the rest only if it read it with result_read") + if shown.get("as") == "stub": + return (f"the harness's context guard hid this result after the assistant was first sent it: from then on the " + f"assistant was shown a stub{chars} in its place, and saw it again only if it read it with result_read") + return f"the harness showed the assistant this result as {shown.get('as')}{chars}, not whole" + + +# What a harness.guard span's attributes are, by the name its facts give them. +_GUARD_FACTS = ("action", "wake", "call", "tokens_before", "tokens_after", "results", "handles", "tools", + "calls_summarized", "kept_items", "outcome", "retried", "exhausted", "hidden", "cut", "refused_tokens") + + +def _span_guard_facts(attrs: dict) -> dict: + """What a ``harness.guard`` span recorded: its action (mask, compact, cut or retry), the wake and its model call it + ran before, the request's tokens before and after, the results it hid or cut (their count, ``result_read`` handles + and tools), a compaction's calls summarized, and a retry's outcome. The refusal's own text is left out.""" + return {key: attrs[f"{_GUARD}.{key}"] for key in _GUARD_FACTS if attrs.get(f"{_GUARD}.{key}") not in (None, "")} + + +def guard_words(facts: dict) -> str: + """What the harness's context guard did (a ``harness.guard`` note's ``guard``), in words.""" + action = facts.get("action") + n, tools = _count(facts.get("results")), facts.get("tools") + results = (f"{n} tool result{'s' if n != 1 else ''}" if n is not None else "tool results") + ( + f" ({tools})" if tools else "") + before, after = _count(facts.get("tokens_before")), _count(facts.get("tokens_after")) + size = f" (the request went from {before:,} tokens to {after:,})" if before is not None and after is not None else "" + handles = f" ({facts['handles']})" if facts.get("handles") else "" + if action == "mask": + return (f"before the assistant's next model call it hid {results} the assistant had already been sent, to keep " + f"the request inside the model's context window{size}; from then on the assistant was shown a short " + f"stub in place of each, and could read them again with result_read{handles}") + if action == "cut": + return (f"before the assistant's next model call it cut {results} short, to keep the request inside the " + f"model's context window{size}; the assistant saw the rest only if it read it with result_read{handles}") + if action == "compact": + calls = _count(facts.get("calls_summarized")) + summarized = f", summarizing this wake's first {calls} tool calls" if calls else "" + return (f"it compacted the history inside this wake{summarized}, to keep the request inside the model's " + f"context window{size}; the compaction's note has the summary") + if action == "retry": + refused = _count(facts.get("refused_tokens")) + head = ("a model call was refused as too long for the model's context window" + + (f" ({refused:,} tokens)" if refused is not None else "")) + if facts.get("outcome") == "nothing_to_hide": + return f"{head}, and it had nothing left to hide or cut, so the wake ended with the context full" + hid, cut = _count(facts.get("hidden")) or 0, _count(facts.get("cut")) or 0 + redo = f"it hid {hid} and cut {cut} tool results and sent the call again" + if facts.get("outcome") == "refused": + return f"{head}; {redo}, which was refused too, so the wake ended with the context full" + return f"{head}; {redo}, and it was answered" + (f" ({after:,} tokens)" if after is not None else "") + return f"before the assistant's next model call it acted ({action}){size}" + + +def guard_note(facts: dict) -> str: + """A ``harness.guard`` span as a note: what the harness's context guard did, never the assistant's doing.""" + return "Context guard (the harness's own action, not the assistant's or the user's): " + guard_words(facts) + "." + + def _span_failure(attrs: dict) -> dict: """What a ``harness.error`` span recorded, by its attributes' names after ``harness.error.``: ``kind``, ``class``, ``message``, and when they apply ``http_status``, ``retries``, ``timeout_s``, ``during`` and the gateway's ids.""" diff --git a/tst/data/verifier_golden/judge_inputs.json b/tst/data/verifier_golden/judge_inputs.json index 8a33277e2..cc4684822 100644 --- a/tst/data/verifier_golden/judge_inputs.json +++ b/tst/data/verifier_golden/judge_inputs.json @@ -314,8 +314,8 @@ }, "always_on_staged": { "prompt": { - "sha256": "41fa2ae5c6b981e264cd98282d5f6b0f1db7a0b5f3fc3a444eb746157da5c094", - "chars": 11478 + "sha256": "d5335985351c37a774291b92ea270e40ebf54a17c0e639320c0fb5e040fc347d", + "chars": 11676 }, "files": { "/tmp/always_on_run//events.jsonl": { @@ -323,8 +323,8 @@ "chars": 28641 }, "/tmp/always_on_run//index.md": { - "sha256": "4786e4997880fadbf4e666e39c9cb7709a315063780e136236da99dd483d53de", - "chars": 5043 + "sha256": "d44506530e44f44b7944a6102a34b165f2d37234f429d268dbf52011a5cb0f11", + "chars": 5206 }, "/tmp/always_on_run//triggers.jsonl": "", "/tmp/always_on_run//wakes/results/wake_002_call_001_gmail_get_thread.json": { @@ -2517,8 +2517,8 @@ }, "always_on_atif_staged": { "prompt": { - "sha256": "c8a6d9f3f591187eb809f8a5213938b0b90ebf63312819a3041d41727ce0aeb5", - "chars": 11475 + "sha256": "97f36d5449620dfc68e95f32a6f8dee9d8e5eea44c2a5fdccfadada9a4ae98ec", + "chars": 11673 }, "files": { "/tmp/always_on_run//events.jsonl": { @@ -2526,8 +2526,8 @@ "chars": 25890 }, "/tmp/always_on_run//index.md": { - "sha256": "dc8f6dee6fc89bcec35543803b03c2209603f21a7be598fa51b4ab135e52744d", - "chars": 4946 + "sha256": "b249e3e50388e5336dad9b896c09315f1172a5b00ffddc1d148c65a84bbe1713", + "chars": 5109 }, "/tmp/always_on_run//triggers.jsonl": "", "/tmp/always_on_run//wakes/wake_001.jsonl": { 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 539a35131..b65b0a576 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -953,10 +953,23 @@ def test_the_files_note_asks_for_a_search_of_every_wake_before_a_claim_that_some assert ("- Before you conclude that something never happened, or was never said or done, search every wake for it, " "long texts included: grep -r /s/wakes/ (the wake files and /s/wakes/results/, where a text too long for a " - "line is kept whole; /s/events.jsonl has only its first 300 characters), and name that search in your " + "line is kept whole; /s/events.jsonl has at most the first 300 characters), and name that search in your " "reason.") in note +def test_the_files_note_says_a_preview_can_be_cut_and_a_line_too_long_to_show_is_in_a_file_of_its_own(): + """Staging keeps every line under 1,800 characters by cutting or leaving out previews and, failing that, by putting + a line whole in a file of its own; the judge is told how to read both.""" + from agent_env.task_step.task_steps.verifiers.always_on_agent_verifier import _files_note + from agent_env.task_step.task_steps.verifiers.always_on_staging import StagedRun + + note = _files_note("/s", StagedRun({"wakes/wake_001.jsonl": ""}, {})) + + assert ('shows its start ("_preview"). A preview can be shortened or left out; the "_file" always ' + 'holds the whole value. A line with only "event", "wake" and "line_file" was too long to show, and its ' + 'file holds the whole line.') in note + + @pytest.mark.asyncio async def test_a_summary_the_harness_wrote_is_not_held_against_the_assistant(monkeypatch): ctx, _, sources = _v7_staged_run(monkeypatch, written_by="harness") diff --git a/tst/unit/task_step/verifiers/judge_utils/test_turn_events_harness_guard.py b/tst/unit/task_step/verifiers/judge_utils/test_turn_events_harness_guard.py new file mode 100644 index 000000000..52119d3ec --- /dev/null +++ b/tst/unit/task_step/verifiers/judge_utils/test_turn_events_harness_guard.py @@ -0,0 +1,322 @@ +"""What the PSI neutral harness's context guard did is in what the judge reads: each ``harness.guard`` span (mask, +compact, cut, retry) is a note, a tool result the model was shown cut or as a stub says so, a reply the harness set +aside and sent the call again for (``harness.call.resent``) isn't read as the model's, and a compaction inside a wake +says what it summarized. The spans are built in the harness's own shape (neutral_patch.py: ``_psi_harness_span``, its +``_psi_guard_span``, the guard's ``harness.compaction`` and its marks on a call's LLM span).""" + +from __future__ import annotations + +import json + +import pytest + +from agent_env.task_step.task_steps.verifiers.always_on_staging import ( + EVENTS_FILE, + INDEX_FILE, + LINE_CHARS, + StagedRun, + stage_run, + wake_file, +) +from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import guard_note, shown_words, turn_events + +MAIN = "Orchestrator" +_ids = iter(range(1, 10_000)) + + +def _at(second: int) -> str: + return f"2026-12-02T10:00:{second:02d}.000000Z" + + +def _span(name: str, start: int, attrs: dict, *, agent: str = MAIN, end: int | None = None) -> dict: + """A span as the harness exports it: every one labelled with its agent and the main agent.""" + return {"name": name, "context": {"trace_id": "0x" + "a" * 32, "span_id": f"0x{next(_ids):016x}", + "trace_state": "[]"}, + "kind": "SpanKind.INTERNAL", "parent_id": None, "start_time": _at(start), + "end_time": _at(end if end is not None else start), "status": {"status_code": "OK"}, + "attributes": {"gen_ai.agent.name": agent, "gen_ai.main_agent.name": MAIN, + "gen_ai.main_agent.id": "psi-neutral-harness", **attrs}, + "events": [], "links": [], "resource": {"attributes": {}, "schema_url": ""}} + + +def _harness(name: str, start: int, attrs: dict, end: int | None = None) -> dict: + """One of the harness's own spans (``_psi_harness_span``): agent "harness", under no tool call.""" + return _span(name, start, attrs, agent="harness", end=end) + + +def _guard(action: str, start: int, end: int | None = None, **extra) -> dict: + """A ``harness.guard`` span as ``_psi_guard_span`` writes it.""" + attrs = {"harness.guard.action": action, "harness.guard.wake": 2, "harness.guard.call": 7, + "harness.guard.tokens_before": 140_000, "harness.guard.tokens_after": 61_000, + "harness.guard.results": 3, "harness.guard.handles": "h1,h2,h3", + "harness.guard.call_ids": "call_1,call_2,call_3", "harness.guard.tools": "orders_list,web_fetch", + "harness.guard.window": 262_144, "harness.guard.rate": 0.27, "harness.guard.rate_source": "usage"} + attrs.update({f"harness.guard.{k}": v for k, v in extra.items()}) + return _harness("harness.guard", start, attrs, end) + + +def _llm(start: int, text: str, thinking: str = "", **attrs) -> dict: + """A model call's LLM span: its reasoning and text in ``gen_ai.output.messages``, OpenInference's text too.""" + parts = ([{"type": "reasoning", "content": thinking}] if thinking else []) + [{"type": "text", "content": text}] + return _span("generation", start, {"openinference.span.kind": "LLM", "llm.model_name": "gpt-5.5", + "llm.output_messages.0.message.role": "assistant", + "llm.output_messages.0.message.content": text, + "gen_ai.output.messages": json.dumps([{"role": "assistant", "parts": parts}]), + **attrs}) + + +def _tool(start: int, tool: str, output: str, **attrs) -> dict: + """A tool call's TOOL span (``execute_tool``), its result whole as the stored history keeps it.""" + return _span(tool, start, {"openinference.span.kind": "TOOL", "gen_ai.operation.name": "execute_tool", + "gen_ai.tool.name": tool, "gen_ai.prompt": json.dumps({"input": {"q": "holiday"}}), + "gen_ai.completion": json.dumps({"output": output}), **attrs}) + + +def _notes(events) -> list[dict]: + return [e for e in events.events if e["type"] == "note"] + + +# ---- (a) the guard's actions are notes --------------------------------------------------------------------------------- + +def test_a_guard_span_is_a_note_in_its_place_not_skipped_as_the_harness_s_own(): + spans = [_llm(1, "Looking up the orders."), _tool(2, "orders_list", "x" * 9000), + _guard("mask", 3, threshold_tokens=131_072, target_tokens=65_536, protected_tokens=26_214, + freed_chars=240_000), + _llm(4, "Three orders are late.")] + + events = turn_events(json.dumps(spans)) + + assert events.agent_labels is True + assert [e["type"] for e in events.events] == ["text", "tool_call", "note", "text"] + [note] = _notes(events) + assert note["guard"] == {"action": "mask", "wake": 2, "call": 7, "tokens_before": 140_000, "tokens_after": 61_000, + "results": 3, "handles": "h1,h2,h3", "tools": "orders_list,web_fetch"} + assert note["text"] == ( + "Context guard (the harness's own action, not the assistant's or the user's): before the assistant's next " + "model call it hid 3 tool results (orders_list,web_fetch) the assistant had already been sent, to keep the " + "request inside the model's context window (the request went from 140,000 tokens to 61,000); from then on the " + "assistant was shown a short stub in place of each, and could read them again with result_read (h1,h2,h3).") + + +@pytest.mark.parametrize("action,extra,words", [ + ("cut", {"threshold_tokens": 235_929}, + "before the assistant's next model call it cut 3 tool results (orders_list,web_fetch) short, to keep the request " + "inside the model's context window (the request went from 140,000 tokens to 61,000); the assistant saw the rest " + "only if it read it with result_read (h1,h2,h3)"), + ("compact", {"threshold_tokens": 196_608, "calls_summarized": 40, "kept_items": 12}, + "it compacted the history inside this wake, summarizing this wake's first 40 tool calls, to keep the request " + "inside the model's context window (the request went from 140,000 tokens to 61,000); the compaction's note has " + "the summary"), + ("retry", {"retried": True, "exhausted": False, "outcome": "answered", "hidden": 5, "cut": 1, + "refusal": "BadRequestError: prompt is too long", "refused_tokens": 270_000}, + "a model call was refused as too long for the model's context window (270,000 tokens); it hid 5 and cut 1 tool " + "results and sent the call again, and it was answered (61,000 tokens)"), + ("retry", {"retried": True, "exhausted": True, "outcome": "refused", "hidden": 5, "cut": 1, + "refused_tokens": 270_000}, + "a model call was refused as too long for the model's context window (270,000 tokens); it hid 5 and cut 1 tool " + "results and sent the call again, which was refused too, so the wake ended with the context full"), + ("retry", {"retried": False, "exhausted": True, "outcome": "nothing_to_hide", "refused_tokens": 270_000}, + "a model call was refused as too long for the model's context window (270,000 tokens), and it had nothing left " + "to hide or cut, so the wake ended with the context full"), +], ids=["cut", "compact", "retry answered", "retry refused", "retry with nothing to hide"]) +def test_each_guard_action_says_what_the_harness_did(action, extra, words): + [note] = _notes(turn_events(json.dumps([_guard(action, 3, **extra), _llm(4, "Done.")]))) + + assert note["guard"]["action"] == action + assert note["text"] == f"Context guard (the harness's own action, not the assistant's or the user's): {words}." + assert "prompt is too long" not in note["text"] # the refusal's own text stays out + + +def test_a_guard_compaction_s_note_follows_the_compaction_it_reports(): + compaction = _harness("harness.compaction", 3, { + "harness.compaction.written_by": "assistant", "harness.compaction.mid_wake": True, + "harness.compaction.wakes_summarized": 0, "harness.compaction.calls_summarized": 40, + "gen_ai.output.messages": json.dumps([{"role": "assistant", "parts": [ + {"type": "compaction", "content": "SUMMARY: three late orders."}]}])}, end=8) + spans = [_tool(1, "orders_list", "late"), _guard("compact", 2, end=9, calls_summarized=40), compaction, + _llm(10, "Writing to Rae.")] + + notes = _notes(turn_events(json.dumps(spans))) + + assert [n.get("guard", {}).get("action") or "compaction" for n in notes] == ["compaction", "compact"] + + +# ---- (a) a result the model was shown cut or as a stub ------------------------------------------------------------- + +@pytest.mark.parametrize("shown_as,chars,words", [ + ("cut", 26_214, "the harness's context guard cut this result to 26,214 characters before the assistant was shown " + "it, so the assistant saw the rest only if it read it with result_read"), + ("stub", 640, "the harness's context guard hid this result after the assistant was first sent it: from then on " + "the assistant was shown a stub of 640 characters in its place, and saw it again only if it read it " + "with result_read"), +], ids=["cut", "stub"]) +def test_a_tool_result_shown_cut_or_as_a_stub_says_so_and_keeps_the_whole_result(shown_as, chars, words): + whole = "row " * 20_000 + spans = [_tool(1, "orders_list", whole, **{"harness.guard.shown_as": shown_as, + "harness.guard.shown_chars": chars})] + + [call] = [e for e in turn_events(json.dumps(spans)).events if e["type"] == "tool_call"] + + assert call["shown"] == {"as": shown_as, "chars": chars} and call["result"] == whole + assert shown_words(call["shown"]) == words + + +@pytest.mark.parametrize("attrs", [{}, {"harness.guard.shown_as": "full", "harness.guard.shown_chars": 9000}], + ids=["unmarked", "shown whole"]) +def test_a_tool_result_shown_whole_has_no_shown(attrs): + [call] = [e for e in turn_events(json.dumps([_tool(1, "orders_list", "ok", **attrs)])).events + if e["type"] == "tool_call"] + + assert "shown" not in call + + +# ---- (b) a reply the harness set aside ------------------------------------------------------------------------------- + +@pytest.mark.parametrize("resent", ["empty", "cut"]) +def test_a_reply_the_harness_set_aside_and_sent_again_is_not_read_as_the_model_s(resent): + spans = [_llm(1, "I already refunded order 17", "the refund is done", **{"harness.call.resent": resent}), + _llm(2, "Let me check order 17 first.", "check before refunding")] + + events = turn_events(json.dumps(spans)).events + + assert [(e["type"], e["text"]) for e in events] == [("thinking", "check before refunding"), + ("text", "Let me check order 17 first.")] + + +# ---- (c) a compaction inside a wake ---------------------------------------------------------------------------------- + +@pytest.mark.parametrize("wakes,words", [ + (0, "it ran inside this wake, between two of the assistant's model calls, to keep the request inside the model's " + "context window; this wake's first 40 tool calls are now in the summary; this wake's message and its latest " + "turns kept word for word"), + (2, "it ran inside this wake, between two of the assistant's model calls, to keep the request inside the model's " + "context window; wakes 1–2 and this wake's first 40 tool calls are now in the summary; this wake's message " + "and its latest turns kept word for word"), +], ids=["in the first wake", "after two wakes"]) +def test_a_compaction_inside_a_wake_says_what_it_summarized_not_0_wakes(wakes, words): + span = _harness("harness.compaction", 3, { + "harness.compaction.written_by": "assistant", "harness.compaction.mid_wake": True, + "harness.compaction.wake": wakes + 1, "harness.compaction.trigger_source": "guard", + "harness.compaction.wakes_summarized": wakes, "harness.compaction.calls_summarized": 40, + "harness.compaction.kept_items": 12, + "gen_ai.output.messages": json.dumps([{"role": "assistant", "parts": [ + {"type": "compaction", "content": "SUMMARY: three late orders."}]}])}) + + [note] = _notes(turn_events(json.dumps([span]))) + + assert note["compaction"] == {"written_by": "assistant", "wakes_summarized": wakes, "mid_wake": True, + "calls_summarized": 40} + assert "0 wakes summarized" not in note["text"] + assert note["text"] == ("Compaction summary (written by the assistant's own model, in a summary turn the harness " + f"asked for; it replaces the older history the assistant sees; {words}):\n" + "SUMMARY: three late orders.") + + +# ---- staged for the always_on judge ---------------------------------------------------------------------------------- + +def _timeline(url: str) -> list[dict]: + return [{"event": "start", "virtual_time": "2026-12-02T09:00:00Z"}, + {"event": "wake", "n": 1, "virtual_time": "2026-12-02T09:00:00Z", "woke_by": ["start"], + "parts_text": "Rae: any late orders?"}, + {"event": "agent_turn_end", "n": 1, "virtual_time": "2026-12-02T09:05:00Z", "state": "completed", + "trajectory_url": url, "plain_reply": "", "tool_calls": 1}, + {"event": "end", "reason": "finished_nothing_pending", "virtual_time": "2026-12-02T09:05:00Z"}] + + +def test_the_judge_s_files_carry_the_guard_s_notes_and_the_results_shown_not_whole(): + from agent_env.task_step.task_steps.verifiers.always_on_agent_verifier import _GUARD_NOTE, _files_note + + spans = [_llm(1, "Looking up the orders."), + _tool(2, "orders_list", "row " * 5000, **{"harness.guard.shown_as": "cut", + "harness.guard.shown_chars": 26_214}), + _guard("mask", 3), _llm(4, "Three orders are late.")] + staged = stage_run(_timeline("mem://wake1.json"), {"mem://wake1.json": turn_events(json.dumps(spans))}) + + lines = [json.loads(line) for line in staged.files[wake_file(1)].splitlines()] + [call] = [line for line in lines if line["event"] == "tool_call"] + assert call["shown_to_assistant"].startswith("the harness's context guard cut this result to 26,214 characters") + [note] = [line for line in lines if line["event"] == "harness_note"] + assert note["guard"]["action"] == "mask" and note["text"] == guard_note(note["guard"]) + assert "- context guard (the harness's): before the assistant's next model call it hid 3 tool results" in ( + staged.files[INDEX_FILE]) + assert (staged.record["context_guard_actions"], staged.record["results_shown_not_whole"]) == ( + {"mask": 1}, {"cut": 1}) + assert _GUARD_NOTE in _files_note("/s", staged) + plain = StagedRun(staged.files, {k: v for k, v in staged.record.items() + if k not in ("context_guard_actions", "results_shown_not_whole")}) + assert _GUARD_NOTE not in _files_note("/s", plain) # a run the guard never acted in isn't told about it + + +@pytest.mark.parametrize("action,extra,said", [ + ("mask", {}, "before the assistant's next model call it hid 400 tool results (mcp__app_00__"), + ("retry", {"retried": True, "exhausted": False, "outcome": "answered", "hidden": 400, "cut": 0, + "refused_tokens": 270_000}, + "a model call was refused as too long for the model's context window (270,000 tokens); it hid 400 and cut 0 tool " + "results and sent the call again"), +], ids=["mask", "retry"]) +def test_a_guard_note_over_hundreds_of_results_stays_inside_the_line_limit_its_lists_in_a_file(action, extra, said): + """One guard action can hide hundreds of results (a mask down to its low-water mark, a refused call's retry that + hides every one it may), and its span lists each one's result_read handle and every tool among them. Its note's + line still fits LINE_CHARS, and so does its index.md entry: the guard's own facts (its action, the wake and call it + ran before, its counts) stay inline in "guard", its long lists go to a file it names, nothing dropped, and a result + shown as a stub still says so on its call.""" + handles = ",".join(f"h{n}" for n in range(1, 401)) + tools = ",".join(f"mcp__app_{n:02d}__records_list_everything" for n in range(40)) + spans = [_llm(1, "Looking up the orders."), + _tool(2, "orders_list", "row " * 5000, **{"harness.guard.shown_as": "stub", + "harness.guard.shown_chars": 640}), + _guard(action, 3, results=400, handles=handles, tools=tools, **extra), + _llm(4, "Three orders are late.")] + staged = stage_run(_timeline("mem://wake1.json"), {"mem://wake1.json": turn_events(json.dumps(spans))}) + + for path in (wake_file(1), EVENTS_FILE, INDEX_FILE): + too_long = [len(line) for line in staged.files[path].splitlines() if len(line) > LINE_CHARS] + assert not too_long, f"{path} has lines of {too_long} characters, over {LINE_CHARS}" + lines = [json.loads(line) for line in staged.files[wake_file(1)].splitlines()] + [note] = [line for line in lines if line["event"] == "harness_note"] + guard = note["guard"] + assert {k: guard.get(k) for k in ("action", "wake", "call", "results", *extra)} == { + "action": action, "wake": 2, "call": 7, "results": 400, **extra} + for part, whole in (("handles", handles), ("tools", tools)): + kept = guard.get(part) or staged.files[guard[f"{part}_file"]].replace("\n", "") + assert kept == whole, part # nothing dropped + assert guard["handles_file"].startswith("wakes/results/wake_001_line_") and guard["handles_preview"].startswith( + "h1,h2,h3,") + [call] = [line for line in lines if line["event"] == "tool_call"] + assert call["shown_to_assistant"].startswith("the harness's context guard hid this result") + assert staged.record["context_guard_actions"] == {action: 1} + [entry] = [line for line in staged.files[INDEX_FILE].splitlines() if line.startswith("- context guard")] + assert entry.startswith(f"- context guard (the harness's): {said}") + + +@pytest.mark.parametrize("field,said", [ + ("error", "it failed, so the history was left whole: BadRequestError: prompt is too long."), + ("save_error", "the save turn before it failed: BadRequestError: prompt is too long."), +], ids=["compaction failed", "save turn failed"]) +def test_a_compaction_s_long_provider_error_goes_to_a_file_and_the_index_still_says_it_failed(field, said): + """A compaction's (or its save turn's) error is the provider's own text, which can run to thousands of characters. + Its note's line still fits LINE_CHARS: who wrote the summary stays inline in "compaction", the error goes to a file + it names with its start kept as a preview, and index.md still says the compaction (or its save turn) failed.""" + error = ("BadRequestError: prompt is too long. " * 100)[:3000] + summary = [] if field == "error" else [{"type": "compaction", "content": "SUMMARY: three late orders."}] + compaction = _harness("harness.compaction", 2, { + "harness.compaction.written_by": "assistant", "harness.compaction.wakes_summarized": 2, + "harness.compaction.wakes_kept": 1, f"harness.compaction.{field}": error, + "gen_ai.output.messages": json.dumps([{"role": "assistant", "parts": summary}])}) + spans = [compaction, _llm(3, "Three orders are late.")] + staged = stage_run(_timeline("mem://wake1.json"), {"mem://wake1.json": turn_events(json.dumps(spans))}) + + for path in (wake_file(1), EVENTS_FILE, INDEX_FILE): + too_long = [len(line) for line in staged.files[path].splitlines() if len(line) > LINE_CHARS] + assert not too_long, f"{path} has lines of {too_long} characters, over {LINE_CHARS}" + lines = [json.loads(line) for line in staged.files[wake_file(1)].splitlines()] + [note] = [line for line in lines if line["event"] == "harness_note"] + facts = note["compaction"] + assert facts["written_by"] == "assistant" and field not in facts + assert staged.files[facts[f"{field}_file"]].replace("\n", "") == error # nothing dropped + assert facts[f"{field}_file"].startswith("wakes/results/wake_001_line_") + assert facts[f"{field}_preview"].startswith("BadRequestError: prompt is too long.") + assert staged.record["compaction_summaries_written_by"] == {"assistant": 1} + [entry] = [line for line in staged.files[INDEX_FILE].splitlines() if line.startswith("- compaction")] + assert entry.startswith("- compaction by the harness, before this wake's turn, its summary written by the " + "assistant's own model: ") and said in entry 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 1eca490e7..fa713ecaa 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -19,7 +19,7 @@ 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.judge_utils.turn_events import TurnEvents, turn_events from agent_env.task_step.task_steps.verifiers.run_context import Firing RECORDED = Path(__file__).resolve().parent / "recorded" @@ -728,3 +728,118 @@ def test_a_turn_staged_by_position_keeps_how_it_ended_failed_included(): assert (ends[0]["state"], ends[0]["closing_reply"]) == ("completed", "Booked the 7pm table.") assert ends[1]["state"] == "failed" and "Quota exceeded" in ends[1]["closing_reply"] assert "- error: its turn ended failed" in staged.files[INDEX_FILE] + + +# ---- no line over LINE_CHARS, whatever it holds ---------------------------------------------------------------------- + +def _one_wake(events: list[dict], *after: dict): + """A run of one wake whose turn is ``events``, with ``after`` logged once the turn ended.""" + url = "mem://wake1.json" + timeline = [{"event": "start", "virtual_time": "2026-12-02T09:00:00Z"}, + {"event": "wake", "n": 1, "virtual_time": "2026-12-02T09:00:00Z", "woke_by": ["start"], + "parts_text": "Rae: any late orders?"}, + {"event": "agent_turn_end", "n": 1, "virtual_time": "2026-12-02T09:05:00Z", "state": "completed", + "trajectory_url": url, "plain_reply": "", "tool_calls": len(events)}, + *after, + {"event": "end", "reason": "finished_nothing_pending", "virtual_time": "2026-12-02T09:10:00Z"}] + return stage_run(timeline, {url: TurnEvents("otel", events, raw_bytes=1)}) + + +def _no_line_over_the_limit(files: dict) -> None: + for path, text in files.items(): + if path.endswith(".jsonl") or path == INDEX_FILE: + too_long = [len(line) for line in text.splitlines() if len(line) > LINE_CHARS] + assert not too_long, f"{path} has lines of {too_long} characters, over {LINE_CHARS}" + + +def _whole(files: dict, path: str) -> str: + """A side file's text as it was before it was split into lines of LINE_CHARS.""" + return files[path].replace("\n", "") + + +def test_a_made_up_tool_name_too_long_for_a_line_goes_to_a_file(): + """A tool's name says what a call is, so it stays when the call's input and result go to files, but a model can + make one up of any length: one that still leaves the line too long goes to a file too, its start kept as a + preview, and index.md names the call by that start.""" + name = ("lookup_" + "everything_about_the_late_orders_" * 70)[:2000] + staged = _one_wake([{"type": "tool_call", "tool": name, "id": "c1", "input": {"q": "late"}, + "result": "row " * 1000, "error": True}]) + + _no_line_over_the_limit(staged.files) + [call] = [line for line in _lines(staged.files, "wakes/wake_001.jsonl") if line["event"] == "tool_call"] + assert "tool" not in call and _whole(staged.files, call["tool_file"]) == name # nothing dropped + assert call["tool_preview"].startswith("lookup_everything_about") and call["call"] == 1 + assert _whole(staged.files, call["result_file"]) == "row " * 1000 + assert "- error: lookup_everything_about_the_late_orders_" in staged.files[INDEX_FILE] + + +def test_a_user_sim_plug_in_s_long_outcome_goes_to_a_file(): + """A user sim read's outcome says what the read did, but a plug-in can return any outcome: one too long for its + line goes to a file, its start kept as a preview.""" + outcome = ("reply, since the assistant asked a question the user would answer at once; " * 30)[:2000] + staged = _one_wake([], {"event": "user_sim_read", "virtual_time": "2026-12-02T09:06:00Z", "version": "v3", + "outcome": outcome, "message": "Yes, refund it.", "mode": "scheduled", + "real_seconds": 1.2}) + + _no_line_over_the_limit(staged.files) + [read] = [line for line in _lines(staged.files, "wakes/wake_001.jsonl") if line["event"] == "user_sim_read"] + assert "outcome" not in read and _whole(staged.files, read["outcome_file"]) == outcome + assert read["outcome_preview"].startswith("reply, since the assistant") and read["message"] == "Yes, refund it." + + +def test_a_line_with_many_fields_in_files_cuts_their_previews_to_fit(): + """Each field that goes to a file leaves a preview. A line with many of them (a user sim read's message, error, + gate record and the rest) would be too long with every preview whole, so they are cut, longest first: the files + have them whole.""" + texts = {k: f"{k}: " + "word " * 700 for k in ("message", "first_message", "used", "user_sim_error")} + listed = {"schema_errors": [f"error {n}: the answer's field {n} is not text, it is a number" for n in range(40)], + "user_sim_gate": {"verdict": "rewrite", "first_message": "gate " * 300, "why": "too long " * 50}} + staged = _one_wake([], {"event": "user_sim_read", "virtual_time": "2026-12-02T09:06:00Z", "outcome": "reply", + **texts, **listed}) + + _no_line_over_the_limit(staged.files) + [read] = [line for line in _lines(staged.files, "wakes/wake_001.jsonl") if line["event"] == "user_sim_read"] + assert read["outcome"] == "reply" + for key, value in texts.items(): + assert key not in read and _whole(staged.files, read[f"{key}_file"]) == value, key + for key, value in listed.items(): + assert key not in read and json.loads(staged.files[read[f"{key}_file"]]) == value, key + + +def test_a_line_of_dozens_of_short_fields_goes_whole_to_a_file_of_its_own(): + """No field of the line is long enough to gain from a file of its own, but together they are too long: the line + goes whole to a file, leaving its event, its wake and that file's name, nothing dropped.""" + fields = {f"check_{n:02d}": f"trigger {n} was still at work when the world settled, its last run unsettled" + for n in range(40)} + staged = _one_wake([], {"event": "settle_timeout", "wake": 1, **fields}) + + _no_line_over_the_limit(staged.files) + [line] = [line for line in _lines(staged.files, "wakes/wake_001.jsonl") if line["event"] == "settle_timeout"] + assert set(line) == {"event", "wake", "line_file"} + assert json.loads(staged.files[line["line_file"]]) == fields + assert ('keeps a preview of each, shortened or left out when the line needs it; a line that is only "event", ' + '"wake" and "line_file" was too long to show, and its file holds the whole line.') in ( + staged.files[INDEX_FILE]) # index.md says how to read it + + +def test_a_failure_note_keeps_its_kind_and_its_text_inline_while_a_long_part_of_its_failure_moves_aside(): + """A failed wake's note says why in its text, and its "failure" keeps its kind inline: the kind says what the note + is. Any other part of the failure is moved like a field of the line's own, the longest first, so a long one (what + was running when the wake failed) goes to a file before the text the judge reads does.""" + message = "APIStatusError: Error code: 502 - Bad Gateway; " + "the gateway said the upstream was gone. " * 12 + during = ",".join(f"mcp__orders__orders_get_{n}" for n in range(80)) + span = {"name": "harness.error", "start_time": "9", "end_time": "9", "parent_id": None, + "status": {"status_code": "ERROR"}, + "attributes": {"gen_ai.agent.name": "harness", "gen_ai.main_agent.name": "Orchestrator", + "harness.error.kind": "gateway", "harness.error.class": "APIStatusError", + "harness.error.message": message, "harness.error.http_status": 502, + "harness.error.during": during}} + staged = _one_wake(turn_events(json.dumps([span])).events) + + _no_line_over_the_limit(staged.files) + [note] = [line for line in _lines(staged.files, "wakes/wake_001.jsonl") if line.get("failure")] + assert note["failure"]["kind"] == "gateway" and note["failure"]["http_status"] == 502 + assert "during" not in note["failure"] and _whole(staged.files, note["failure"]["during_file"]) == during + assert note["text"].startswith("The harness says this wake failed: gateway") and message in note["text"] + assert ("- error: the harness says the wake failed (gateway); an infrastructure failure isn't the assistant's " + "doing (wakes/wake_001.jsonl:") in staged.files[INDEX_FILE]