From d74ddfcedc3d910dcbf36972eff11cbb68b24b01 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:47:31 -0800 Subject: [PATCH 1/7] feat(judge): the always_on judge reads what the harness's context guard did The PSI neutral harness v14's context guard hides older tool results behind stubs, cuts new ones, compacts inside a wake and resends a call refused as too long. turn_events skipped its harness.guard spans as the harness's own, so the judge graded models on text they were never shown, and read a reply the harness set aside (harness.call.resent) as the model's. - Each harness.guard span (mask, compact, cut, retry) is a note with its facts (guard). - A TOOL span's harness.guard.shown_as / shown_chars put shown on its call; staging writes it as shown_to_assistant, and the judge is told to grade on what the assistant was shown. - An LLM span marked harness.call.resent adds no text or thinking. - A compaction inside a wake reads calls_summarized and mid_wake, not "0 wakes summarized". - Staging lists guard actions in index.md and counts them in the record (context_guard_actions, results_shown_not_whole). Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 19 +- .../task_steps/verifiers/always_on_staging.py | 33 ++- .../verifiers/judge_utils/turn_events.py | 152 ++++++++++- .../test_turn_events_harness_guard.py | 240 ++++++++++++++++++ 4 files changed, 425 insertions(+), 19 deletions(-) create mode 100644 tst/unit/task_step/verifiers/judge_utils/test_turn_events_harness_guard.py diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index bdc1db2be..de3d7f97a 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 @@ -27,7 +27,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). """ @@ -143,6 +146,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" \ @@ -577,8 +590,10 @@ 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 + "".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 2a2bfbcf2..cd2c93521 100644 --- a/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py +++ b/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py @@ -4,7 +4,8 @@ - ``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 + harness put in the turn (``harness_note``: a compaction summary, a message it sent the assistant, 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, 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``) @@ -12,7 +13,8 @@ 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). + 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), named by wake and call (or line); the line keeps a preview. Lines longer than LINE_CHARS are split there, nothing dropped. - ``events.jsonl``: every line of every wake, and the run's start and end. ``triggers.jsonl``: every trigger firing. @@ -39,7 +41,13 @@ 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.turn_events import UNKNOWN, TurnEvents, compaction_words +from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( + UNKNOWN, + TurnEvents, + compaction_words, + guard_words, + shown_words, +) from agent_env.task_step.task_steps.verifiers.run_context import Firing WAKES_DIR = "wakes" @@ -68,7 +76,7 @@ _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. _IDENTITY = frozenset({"event", "wake", "at", "call", "turn", "tool", "kind", "state", "outcome", "phase", "by", - "step", "subagent", "compaction", "internal", "cut_off", "cut_off_notice", "limit"}) + "step", "subagent", "compaction", "guard", "internal", "cut_off", "cut_off_notice", "limit"}) @dataclass(frozen=True) @@ -186,6 +194,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``) def wake(self, n: Optional[int]) -> _Wake: n = n or self.current @@ -298,8 +308,10 @@ 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 lines.append(_line("harness_note", w.n, turn=which, step=e.get("step"), compaction=e.get("compaction"), - text=e["text"])) + guard=e.get("guard"), text=e["text"])) elif kind == "raw": lines.append(_line("trajectory_item", w.n, turn=which, item=e["event"])) staged = sum(len(_dumps(line).encode()) for line in lines) + side @@ -314,9 +326,11 @@ 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: @@ -384,6 +398,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()))), ("turns_by_position", self.by_position)): if value: record[key] = value @@ -465,7 +481,10 @@ 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")) + out.append(f"- {_compaction_line(line['compaction'], during=during)} ({path}:{i})") + elif event == "harness_note" and line.get("guard") is not None: + out.append(f"- context guard (the harness's): {guard_words(line['guard'])} ({path}:{i})") elif event == "app_change": changes["by the assistant" if line.get("by") == "agent" else "by others" if line.get("by") else "with no known actor"] += 1 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 6bd7a5119..9d11bf07e 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,10 +52,13 @@ @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``) 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``; 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``).""" @@ -169,12 +172,22 @@ def _settle(call: dict, result: Any, error: bool) -> None: # assistant). A model span's ``gen_ai.output.messages`` lists its parts in order: reasoning, text, tool calls (the # 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) and each message it put before the assistant (``harness.message``, with its ``purpose``). +# wrote the summary) and each message it put before the assistant (``harness.message``, with its ``purpose``). 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" +_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" @@ -207,8 +220,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. @@ -229,6 +244,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: @@ -239,6 +256,14 @@ 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 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) @@ -332,12 +357,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}} @@ -354,6 +381,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: @@ -379,6 +408,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)"} @@ -414,6 +462,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_text(attrs: dict) -> str: """A model span's own output text: OpenInference's ``llm.output_messages.N.message.content``, a GenAI ``chat`` span's text blocks, or the text parts of its ``gen_ai.output.messages``.""" 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..d3f487c09 --- /dev/null +++ b/tst/unit/task_step/verifiers/judge_utils/test_turn_events_harness_guard.py @@ -0,0 +1,240 @@ +"""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 INDEX_FILE, 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 From 5f79dee19afa022c81c2178a24cb02ab4420954d Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 13:17:56 -0800 Subject: [PATCH 2/7] fix(judge): a guard note's lists of results go to a side file, so its line stays readable whole With "guard" an identity field, fit could not move it, so one guard action over hundreds of results (a mask, a refused call's retry) left a harness_note line of about 4,000 characters, past LINE_CHARS, even after its text moved; the mask's index.md entry ran to 3,700. - fit moves the long parts of an identity field (_LONG_PARTS: a guard's handles and tools) as it moves a line's own fields, leaving _file and _preview in "guard", which keeps its action, wake, call and counts inline. - index.md shows a guard's lists by their start, as it shows an argument; the wake file has them whole. Test: test_a_guard_note_over_hundreds_of_results_stays_inside_the_line_limit_its_lists_in_a_file (mask, retry). Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/always_on_staging.py | 50 +++++++++++++----- .../test_turn_events_harness_guard.py | 51 ++++++++++++++++++- 2 files changed, 87 insertions(+), 14 deletions(-) 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 cd2c93521..66d28294c 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 @@ -15,8 +15,9 @@ ``pre_compaction_save``, where only its memory and history tools work; ``after_compaction`` and ``failed_wake`` 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), named - by wake and call (or line); the line keeps a preview. Lines longer than LINE_CHARS are split there, nothing dropped. +- ``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), named by wake and call (or line); the line keeps a preview. Lines longer + than LINE_CHARS are split there, 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 @@ -77,6 +78,10 @@ # A line's fields that say what and where it is; ``fit`` moves only the others. _IDENTITY = frozenset({"event", "wake", "at", "call", "turn", "tool", "kind", "state", "outcome", "phase", "by", "step", "subagent", "compaction", "guard", "internal", "cut_off", "cut_off_notice", "limit"}) +# The parts of an identity field that grow with what it lists, which ``fit`` moves like a field of the line's own while +# the rest of the field stays: a guard note's comma-joined lists of the results one action hid or cut (their +# result_read handles, and their tools), hundreds long for a mask or a refused call's retry. +_LONG_PARTS = {"guard": ("handles", "tools")} @dataclass(frozen=True) @@ -337,32 +342,43 @@ def call(self, w: _Wake, e: dict, which: str) -> tuple[dict, int]: line["no_result"] = True return self.fit(line, stem, ("input", "result")) - def fit(self, line: dict, stem: str, movable: Sequence[str]) -> tuple[dict, int]: + 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: 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.""" + tool call's result) and leaves a preview. A ``(field, part)`` is a part of one of the line's fields + (``_LONG_PARTS``): it moves the same way (``__`` in its file's name), its ``_file`` and + ``_preview`` left in that field. 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) + while len(_dumps(line)) > LINE_CHARS and (inline := [k for k in movable if _part(line, k) not in (None, "")]): + key = max(inline, 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) 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}" + path = f"{stem}{suffix}.{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) + holder[f"{name}_file"] = path + holder[f"{name}_preview"] = _cut(value if isinstance(value, str) else _dumps(value), PREVIEW_CHARS) return line, written 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``), and the long parts of those that do + (``_LONG_PARTS``).""" for i, line in enumerate(lines, 1): if line["event"] != "tool_call": + parts = [(k, p) for k, ps in _LONG_PARTS.items() if isinstance(line.get(k), dict) for p in ps] 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: @@ -408,6 +424,11 @@ 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 _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") @@ -484,7 +505,10 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c during = acted or bool(line["compaction"].get("mid_wake")) out.append(f"- {_compaction_line(line['compaction'], during=during)} ({path}:{i})") elif event == "harness_note" and line.get("guard") is not None: - out.append(f"- context guard (the harness's): {guard_words(line['guard'])} ({path}:{i})") + # Its lists (the results' handles and tools) cut as an argument is here: the wake file has them whole. + guard = line["guard"] + guard = {**guard, **{p: _cut(_text(guard, p), ARG_CHARS) for p in _LONG_PARTS["guard"] if _text(guard, p)}} + out.append(f"- context guard (the harness's): {guard_words(guard)} ({path}:{i})") elif event == "app_change": changes["by the assistant" if line.get("by") == "agent" else "by others" if line.get("by") else "with no known actor"] += 1 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 index d3f487c09..2fcd1254d 100644 --- 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 @@ -10,7 +10,14 @@ import pytest -from agent_env.task_step.task_steps.verifiers.always_on_staging import INDEX_FILE, StagedRun, stage_run, wake_file +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" @@ -238,3 +245,45 @@ def test_the_judge_s_files_carry_the_guard_s_notes_and_the_results_shown_not_who 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}") From c9520c54149c5675f3ea71064e36bd74916972eb Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 13:23:41 -0800 Subject: [PATCH 3/7] fix(judge): a compaction's long error goes to a side file, and index.md still says it failed "compaction" is an identity field too, and its error and save_error hold the provider's own text: a 3,000-character error left a harness_note line of about 3,500 characters even after its text moved, and an index.md entry of 3,200. - _LONG_PARTS also names a compaction's error and save_error, so fit moves a long one to a file and leaves error_file / error_preview in "compaction", whose written_by and counts stay inline. - index.md words a compaction from its error's preview when it was moved (_index_facts), so it still says the compaction (or its save turn) failed; it shows as much of an error as of a message, and a guard's lists as an argument. Test: test_a_compaction_s_long_provider_error_goes_to_a_file_and_the_index_still_says_it_failed (compaction failed, save turn failed). Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/always_on_staging.py | 33 ++++++++++++------- .../test_turn_events_harness_guard.py | 33 +++++++++++++++++++ 2 files changed, 55 insertions(+), 11 deletions(-) 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 66d28294c..d02876ca3 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 @@ -16,8 +16,8 @@ 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), named by wake and call (or line); the line keeps a preview. Lines longer - than LINE_CHARS are split there, nothing dropped. + 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. Lines longer than LINE_CHARS are split there, 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 @@ -78,10 +78,11 @@ # A line's fields that say what and where it is; ``fit`` moves only the others. _IDENTITY = frozenset({"event", "wake", "at", "call", "turn", "tool", "kind", "state", "outcome", "phase", "by", "step", "subagent", "compaction", "guard", "internal", "cut_off", "cut_off_notice", "limit"}) -# The parts of an identity field that grow with what it lists, which ``fit`` moves like a field of the line's own while -# the rest of the field stays: a guard note's comma-joined lists of the results one action hid or cut (their -# result_read handles, and their tools), hundreds long for a mask or a refused call's retry. -_LONG_PARTS = {"guard": ("handles", "tools")} +# The parts of an identity field that can run long, which ``fit`` moves like a field of the line's own while the rest +# of the field stays: a guard note's comma-joined lists of the results one action hid or cut (their result_read +# handles, and their tools), hundreds long for a mask or a refused call's retry, and a compaction's or its save turn's +# error, the provider's own text. The field's other parts are a few words or numbers each. +_LONG_PARTS = {"guard": ("handles", "tools"), "compaction": ("error", "save_error")} @dataclass(frozen=True) @@ -434,6 +435,15 @@ def _text(line: dict, key: str) -> Any: return line.get(key) if line.get(key) is not None else line.get(f"{key}_preview") +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 of its long parts + (``_LONG_PARTS``) by its start, cut to ``chars``, from its preview when ``fit`` moved it to a file, so the words + still say what it did (a compaction's error that it failed). The wake file has them whole.""" + facts = line[field] + return {**facts, **{part: _cut(_text(facts, part), chars) for part in _LONG_PARTS[field] + if _text(facts, part) is not None}} + + def _changing_tools(lines: list[dict]) -> set[str]: """The tools whose calls made the assistant's app changes in a wake, as the changes' actors name them.""" return {_short_tool(a["tool"]) for line in lines if line["event"] == "app_change" and line.get("by") == "agent" @@ -503,12 +513,13 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c 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: during = acted or bool(line["compaction"].get("mid_wake")) - out.append(f"- {_compaction_line(line['compaction'], during=during)} ({path}:{i})") + # 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) cut as an argument is here: the wake file has them whole. - guard = line["guard"] - guard = {**guard, **{p: _cut(_text(guard, p), ARG_CHARS) for p in _LONG_PARTS["guard"] if _text(guard, p)}} - out.append(f"- context guard (the harness's): {guard_words(guard)} ({path}:{i})") + # 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 == "app_change": changes["by the assistant" if line.get("by") == "agent" else "by others" if line.get("by") else "with no known actor"] += 1 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 index 2fcd1254d..52119d3ec 100644 --- 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 @@ -287,3 +287,36 @@ def test_a_guard_note_over_hundreds_of_results_stays_inside_the_line_limit_its_l 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 From 38b311a08b2953d77d6c5c54a5eb40775ed139a0 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 13:33:50 -0800 Subject: [PATCH 4/7] fix(judge): no staged line is longer than LINE_CHARS, whatever it holds The line limit held only for fields fit was told it could move. A made-up 2,000-character tool name or a plug-in's 2,000-character outcome stayed inline as an identity field (lines of 2,684 and 2,518 characters); a user sim read with six long fields went over on its previews alone (2,577); and a line of dozens of short fields grew to 7,188, since fit moved even values shorter than the preview they left. - Inside guard and compaction every part can move but those that say what the note is (_IDENTIFYING_PARTS: a guard's action, wake and call; a compaction's written_by and mid_wake). This replaces the list of known-long parts. - fit moves only a value longer than a preview. A line still too long then moves its longest values left inline, identity fields included; then cuts its previews, longest first (dropped under MIN_PREVIEW_CHARS); and failing that goes whole to a file of its own, leaving event, wake and line_file. Nothing is dropped. - index.md reads a moved field from its preview, or names its file when the preview was cut away. Tests (each failed before): test_a_made_up_tool_name_too_long_for_a_line_goes_to_a_file, test_a_user_sim_plug_in_s_long_outcome_goes_to_a_file, test_a_line_with_many_fields_in_files_cuts_their_previews_to_fit, test_a_line_of_dozens_of_short_fields_goes_whole_to_a_file_of_its_own. Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/always_on_staging.py | 147 +++++++++++++----- .../verifiers/test_always_on_staging.py | 91 ++++++++++- 2 files changed, 199 insertions(+), 39 deletions(-) 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 d02876ca3..1a01ec494 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 @@ -17,7 +17,9 @@ (``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. Lines longer than LINE_CHARS are split there, nothing dropped. + 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 @@ -56,10 +58,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 @@ -75,14 +79,17 @@ # 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", "guard", "internal", "cut_off", "cut_off_notice", "limit"}) -# The parts of an identity field that can run long, which ``fit`` moves like a field of the line's own while the rest -# of the field stays: a guard note's comma-joined lists of the results one action hid or cut (their result_read -# handles, and their tools), hundreds long for a mask or a refused call's retry, and a compaction's or its save turn's -# error, the provider's own text. The field's other parts are a few words or numbers each. -_LONG_PARTS = {"guard": ("handles", "tools"), "compaction": ("error", "save_error")} +# 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. ``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). +_IDENTIFYING_PARTS = {"guard": frozenset({"action", "wake", "call"}), + "compaction": frozenset({"written_by", "mid_wake"})} +# 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) @@ -344,14 +351,30 @@ def call(self, w: _Wake, e: dict, which: str) -> tuple[dict, int]: return self.fit(line, stem, ("input", "result")) 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: 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 the line's fields - (``_LONG_PARTS``): it moves the same way (``__`` in its file's name), its ``_file`` and - ``_preview`` left in that field. Returns the bytes it wrote.""" + """``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 len(_dumps(line)) > LINE_CHARS and (inline := [k for k in movable if _part(line, k) not in (None, "")]): - key = max(inline, key=lambda k: len(_dumps(_part(line, k)))) + 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 @@ -359,25 +382,29 @@ def fit(self, line: dict, stem: str, movable: Sequence[str | tuple[str, str]]) - else: holder, name, suffix = line, key, "" if key == "result" else "_" + key value = holder.pop(name) - 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}{suffix}.{ext}" - body = wrapped - self.files[path] = body - written += len(body.encode()) - holder[f"{name}_file"] = path + 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 line, written + 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: its - fields that don't say what and where it is (``_IDENTITY``), and the long parts of those that do - (``_LONG_PARTS``).""" + 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, ps in _LONG_PARTS.items() if isinstance(line.get(k), dict) for p in ps] + 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] + parts) return lines @@ -430,18 +457,62 @@ def _part(line: dict, key: str | tuple[str, str]) -> Any: 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 of its long parts - (``_LONG_PARTS``) by its start, cut to ``chars``, from its preview when ``fit`` moved it to a file, so the words - still say what it did (a compaction's error that it failed). The wake file has them whole.""" + """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] - return {**facts, **{part: _cut(_text(facts, part), chars) for part in _LONG_PARTS[field] - if _text(facts, part) is not None}} + 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]: @@ -476,7 +547,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)) @@ -487,7 +558,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})") diff --git a/tst/unit/task_step/verifiers/test_always_on_staging.py b/tst/unit/task_step/verifiers/test_always_on_staging.py index f769b7154..ddb5a9b14 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -18,7 +18,7 @@ judge_reads, stage_run, ) -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" @@ -607,3 +607,92 @@ 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 From 69893348e449bfd2f24088e5cc465247febce936 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 13:42:05 -0800 Subject: [PATCH 5/7] feat(judge): the files note says how to read a cut preview and a line kept whole in a file fit now shortens or leaves out a preview to keep a line under 1,800 characters, and puts a line too long even then whole in a file of its own ({event, wake, line_file}). The judge's files note says both, so it reads the file for the whole value. Test: test_the_files_note_says_a_preview_can_be_cut_and_a_line_too_long_to_show_is_in_a_file_of_its_own. The two pinned always_on judge inputs (always_on_staged, always_on_atif_staged) are re-recorded: only their prompt changed, by the 195 characters added. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 6 ++++-- tst/data/verifier_golden/judge_inputs.json | 8 ++++---- tst/unit/task_step/test_always_on_agent_verifier.py | 13 +++++++++++++ 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index de3d7f97a..429bd8670 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 @@ -107,8 +107,10 @@ order: every app change ("app_change", "by": "agent" for its own), its closing reply ("turn_end"; the user never saw \ it), each message the user got ("message_to_user"), a nudge and its calls, and the user's reads of its messages. - {results}/: what is too long for a line (a tool's input or result, a long message): the line names the file \ -("_file", such as "result_file" or "text_file") and shows its start ("_preview"). Email bodies are \ -decoded (body.text). A line longer than 1,800 characters is split across lines there, nothing dropped. +("_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. diff --git a/tst/data/verifier_golden/judge_inputs.json b/tst/data/verifier_golden/judge_inputs.json index 4dddfe780..dc0dd78f5 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": "b9f74aebb0a033e2b7a24b5c35030bb7a3ecdd3c23e2f57643667e3b7dc86c12", - "chars": 11552 + "sha256": "4e2c34a1521d312b3adafc1180609aa76f9814d695269b4918cc6ff50b313062", + "chars": 11747 }, "files": { "/tmp/always_on_run//events.jsonl": { @@ -2517,8 +2517,8 @@ }, "always_on_atif_staged": { "prompt": { - "sha256": "01b234920c6523077035db1f203b512a546e605e4b0b52f8e842c63d32d761fe", - "chars": 11549 + "sha256": "c338756b9962f7ba8e23a0369961b906195caa303b7c749b7c2345ca0652d69c", + "chars": 11744 }, "files": { "/tmp/always_on_run//events.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 66d98ca81..4f69b9fbd 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -812,6 +812,19 @@ def test_the_files_note_asks_for_a_search_of_every_wake_before_a_claim_that_some "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") From e320850220fcde3e24f47f219428fee058f55b48 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 13:47:37 -0800 Subject: [PATCH 6/7] docs(judge): index.md and the never-happened note match what fit writes - index.md's header says a too-long line names each long field's file and keeps a preview of each, shortened or left out when the line needs it, and that a line of only event, wake and line_file is kept whole in its file. - The note on searching before a "never happened" claim says events.jsonl has at most the first 300 characters of a long text. The pinned always_on judge inputs (always_on_staged, always_on_atif_staged) are re-recorded: their prompt grew by the 3 characters and index.md by the 163 characters these edits add, nothing else. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 2 +- .../task_steps/verifiers/always_on_staging.py | 6 ++++-- tst/data/verifier_golden/judge_inputs.json | 16 ++++++++-------- .../task_step/test_always_on_agent_verifier.py | 2 +- .../verifiers/test_always_on_staging.py | 3 +++ 5 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index 429bd8670..2e7767ea6 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 @@ -120,7 +120,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. 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 1a01ec494..44982e846 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 @@ -637,8 +637,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/tst/data/verifier_golden/judge_inputs.json b/tst/data/verifier_golden/judge_inputs.json index dc0dd78f5..ef0566686 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": "4e2c34a1521d312b3adafc1180609aa76f9814d695269b4918cc6ff50b313062", - "chars": 11747 + "sha256": "1adba4a1f8c26e4cc83e3cba1f34e5dc5250d116968fa67c14cd3ff35e32301e", + "chars": 11750 }, "files": { "/tmp/always_on_run//events.jsonl": { @@ -323,8 +323,8 @@ "chars": 29079 }, "/tmp/always_on_run//index.md": { - "sha256": "8a1f8a5ef9765fda6a418236a7d69bad8823a55e19ba67484f06e546fff46465", - "chars": 5044 + "sha256": "1ee92fe8b6d167f5c07900c0710e14ed88248f8e6a3a329427e94f1155192a44", + "chars": 5207 }, "/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": "c338756b9962f7ba8e23a0369961b906195caa303b7c749b7c2345ca0652d69c", - "chars": 11744 + "sha256": "2284499ef322fede5ccdff095005bbd8ee0c93722f91ee04f7a3eb962d5594b8", + "chars": 11747 }, "files": { "/tmp/always_on_run//events.jsonl": { @@ -2526,8 +2526,8 @@ "chars": 26443 }, "/tmp/always_on_run//index.md": { - "sha256": "e298b71fca2c39c8bb0a2b6664e3797ee47059d822001ea8c025fc3e5347195e", - "chars": 4947 + "sha256": "7ee011e3a9d98ca625fdd7759a78bee6e6b8c131e9ea913b7e57615919f8de01", + "chars": 5110 }, "/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 4f69b9fbd..086cde170 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -808,7 +808,7 @@ 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 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 ddb5a9b14..070cc02f0 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -696,3 +696,6 @@ def test_a_line_of_dozens_of_short_fields_goes_whole_to_a_file_of_its_own(): [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 From 2dfaf575f9919339d277ed5e41d6e5a5d7ba83bd Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 16:17:03 -0800 Subject: [PATCH 7/7] fix(judge): a failed wake's failure keeps only its kind fixed inline, like guard and compaction "failure" (#981) is an identity field, so fit moved none of its parts in its first pass: a failed wake whose failure held a long part (what was running) moved the note's text to a file first, and the long part only went in the last step. _IDENTIFYING_PARTS now names failure's kind as what says what the note is; fit moves its other parts like the line's own fields, longest first, so the text the judge reads stays in the line. The comment saying failure "stays inline" now says how it does. Test: test_a_failure_note_keeps_its_kind_and_its_text_inline_while_a_long_part_of_its_failure_moves_aside (failed before: the note's text had moved). Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/always_on_staging.py | 13 +++++++---- .../verifiers/test_always_on_staging.py | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) 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 6f0d1e6bd..b08e88259 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 @@ -88,11 +88,13 @@ "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. ``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). +# 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"})} + "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"}) @@ -333,7 +335,8 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]: 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"), guard=e.get("guard"), failure=failure, text=e["text"])) 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 e34e808b9..a1e1007d0 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -746,3 +746,26 @@ def test_a_line_of_dozens_of_short_fields_goes_whole_to_a_file_of_its_own(): 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]