From 71abfa732986b1a45fca362bd75c3ef5135dcb49 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 08:13:48 -0800 Subject: [PATCH 1/7] feat(protocol): atif/1 profile 1.1 marks a compaction's step and a harness's own messages A compaction is the source: agent step of the model call that wrote its summary, carrying that call's metrics, its profile's compaction naming who wrote the summary (assistant or harness) and what set it off (manual or auto); a message the harness itself put in the conversation is a source: system step. The builder writes both (turn.compaction, turn.system_message), the validator holds a compaction to an agent step and a named writer, and reads a 1.0 document from an agent on an older SDK as its own: a minor only adds optional fields. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/atif/PROFILE.md | 48 +++++++++++++------ .../src/agentenv_protocol/atif/__init__.py | 8 +++- .../src/agentenv_protocol/atif/builder.py | 29 +++++++++++ .../atif/fixtures/coding.json | 2 +- .../atif/fixtures/computer_use.json | 2 +- .../atif/fixtures/late_result.json | 2 +- .../atif/fixtures/multi_agent.json | 2 +- .../atif/fixtures/odd_parts.json | 2 +- .../atif/fixtures/subagent.json | 2 +- .../atif/fixtures/two_turns.json | 2 +- .../src/agentenv_protocol/atif/profile.py | 17 ++++++- .../src/agentenv_protocol/atif/validator.py | 36 +++++++++++--- .../tests/test_atif_builder.py | 43 +++++++++++++++++ .../tests/test_atif_validator.py | 24 ++++++++++ 14 files changed, 188 insertions(+), 31 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md b/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md index 442ee29d1..affd86f06 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md @@ -1,6 +1,6 @@ # The agentenv profile of ATIF -Profile 1.0. agentenv records what an agent did as an ATIF v1.8 document: Harbor's +Profile 1.1. agentenv records what an agent did as an ATIF v1.8 document: Harbor's [Agent Trajectory Interchange Format](https://github.com/harbor-framework/harbor/blob/main/rfcs/0001-trajectory-format.md), whose models are vendored in `models/`. An agent serves it as format `atif/1`, beside its native log. What ATIF has no typed field for, agentenv adds under `extra.agentenv` on the objects that have an `extra`. This file is the profile's spec. @@ -36,7 +36,7 @@ to native exactly. call's result by `subagent_trajectory_ref`. It belongs to the task of the call that spawned it. A sub-agent that wrote no step is left out, and so is the reference to it. A spawning call with no result when its task ends gets one, with no content and `status: canceled`, so its sub-agent stays referenced. -- `schema_version` is the oldest ATIF version that holds the document's fields: `ATIF-v1.8` for profile 1.0. +- `schema_version` is the oldest ATIF version that holds the document's fields: `ATIF-v1.8` for profile 1.1. - Format id: `atif/1`. The profile's own version is the root's `extra.agentenv.version`. ## Steps @@ -44,6 +44,12 @@ to native exactly. - A step is one model response, keyed by its native id (a message id), or a step with no model call (`llm_call_count` 0, no metrics or reasoning). A step closes when the next step of its trajectory starts, or when its task ends. +- A `source: system` step is a message the harness itself put in the conversation, such as a command's output: neither + the agent's words nor the user's. A reader that stages a turn for a judge shows it as a note. (1.1) +- A compaction is when the harness replaces the conversation so far with a summary, in what the agent sees from then + on. The summary is the message of the step of the model call that wrote it: a `source: agent` step carrying that + call's metrics, its profile's `compaction` saying who wrote it and what set it off. A reader that stages a turn for a + judge shows it as a note, not as the agent speaking. (1.1) - A result always sits in the step that made its call, as ATIF requires. One that arrives after that step closed records when, in `arrived`. - A live reader is served closed steps only, each trajectory up to its first step still waiting on a result or @@ -117,7 +123,7 @@ One vocabulary, in three places: | Object | Field | Meaning | Read by | | --- | --- | --- | --- | -| Trajectory | `version` | The profile version: `1.0` | every reader | +| Trajectory | `version` | The profile version: `1.1` | every reader | | Trajectory | `native_format` | The native format id the copy was built from | the worker that stores copies; renormalizing | | Trajectory | `adapter` | The adapter's `name` and `version` | the worker that stores copies; renormalizing | | Trajectory | `unmatched` | Native records no method took, counted by type | the adapter kit | @@ -126,6 +132,7 @@ One vocabulary, in three places: | Step | `attempt` | The harness attempt the step belongs to; absent means 1 | the explorer | | Step | `error` | A step-level error: `kind`, `message`, `code` | the explorer | | Step | `data` | On a task's last step: its final response's diagnostic DataParts, in order, each `data` and its `metadata` | the explorer | +| Step | `compaction` | On a compaction's step: who wrote the summary (`written_by`) and what set it off (`trigger`). (1.1) | judges' turn events | | Step | `reasoning` | Each reasoning block: `chars`, `visibility`, `signature`, `data` | resuming a session; RL replay | | Step | `media` | Details of the media the message names, by path | media transfer; the explorer | | ObservationResult | `status` | The result's status; absent means `ok` | the explorer, judges' turn events | @@ -137,12 +144,13 @@ One vocabulary, in three places: | FinalMetrics | `cost_source` | Where `total_cost_usd` came from | the run's usage and cost result | | FinalMetrics | `total_cache_write_tokens` | Cache writes summed over the steps | the run's usage and cost result | -A media entry (MediaInfo) holds `sha256`, `bytes`, and, where they apply, `width`, `height`, `duration_ms`, `pages` -and `name`, plus `media_type` for media ATIF has no part type for. A reasoning block (ReasoningBlock) holds `chars`, -its share of `reasoning_content` (0 when the provider withheld the text), its `visibility`, the provider's `signature`, -and a redacted block's ciphertext as `data`, byte for byte. A step error (StepError) holds `kind`, `message` and `code`. -An arrival (Arrival) holds `at` and `step_id`. The Agent, ToolCall and SubagentTrajectoryRef profiles define no fields -in 1.0. +A media entry (MediaInfo) holds `sha256`, `bytes`, and, where they apply, `width`, `height`, `duration_ms`, `pages` and +`name`, plus `media_type` for media ATIF has no part type for. A reasoning block (ReasoningBlock) holds `chars`, its +share of `reasoning_content` (0 when the provider withheld the text), its `visibility`, the provider's `signature`, and +a redacted block's ciphertext as `data`, byte for byte. A step error (StepError) holds `kind`, `message` and `code`. An +arrival (Arrival) holds `at` and `step_id`. A compaction (Compaction) holds `written_by`, `assistant` for the agent's +own model or `harness`, and `trigger`, `manual` when something asked for it, such as a command, or `auto` when the +harness set it off itself. The Agent, ToolCall and SubagentTrajectoryRef profiles define no fields in 1.1. ## Vocabularies @@ -155,18 +163,27 @@ A reader keeps a value it doesn't know. | `StepError.kind` | `agent_error`, `infra_error` | | `ReasoningBlock.visibility` | `raw`, `summary`, `omitted`, `redacted` | | `MetricsProfile.cost_source`, `FinalMetricsProfile.cost_source` | `harness`, `provider` | +| `Compaction.written_by` | `assistant`, `harness` | +| `Compaction.trigger` | `manual`, `auto` | ## Versions A minor version only adds optional fields and vocabulary values, each with the reader or producer that needs it. A -field added in a later minor names the version it arrived in. Proposed for a later minor, with their first producer: -`input_includes_cache` on the root and `cost_status` (`reported`, `priced` or `unpriced`), with the usage -cross-check that reads them; per-part origins, when a reader needs them; and an always-on harness's fields. +field added in a later minor names the version it arrived in, and a reader of a minor reads every one before it. + +- 1.1 adds `compaction` and `source: system` steps as the harness's own messages. Their first producer is Claude + Code's adapter, and their reader the judges' turn events. +- Proposed for a later minor, with their first producer: + - `input_includes_cache` on the root and `cost_status` (`reported`, `priced` or `unpriced`), with the usage + cross-check that reads them; + - per-part origins, when a reader needs them; + - the rest of an always-on harness's fields: the facts of its compaction (what it kept), the purpose of its + messages, and the tools it provides itself. ## Validator `validate(document)` returns findings, each with a rule id below, a severity and where in the document it is. It holds a -producer's output to profile 1.0. `reader=True` checks someone else's document for reading instead: what a producer +producer's output to this profile. `reader=True` checks someone else's document for reading instead: what a producer must not write only warns, and the document fails only where agentenv couldn't read it. `media` is the folder the document's media paths are relative to, the one holding `media/`, or the files by path; without it only the paths' form is checked. `StoredMedia(sizes)` stands for files stored beside the document whose bytes were checked against their @@ -182,8 +199,9 @@ and exits 1 when one is an error. | `json` | The document is a JSON object: UTF-8, with no NaN or infinity | error | error | | `atif` | ATIF's own models, vendored from Harbor, accept it | error | error | | `profile` | Each `extra.agentenv` parses with its profile model | error | error | -| `profile-key` | Each `extra.agentenv` holds only the fields profile 1.0 defines | error | warning | -| `profile-version` | The root's `extra.agentenv.version`, when given, is `1.0` | error | warning | +| `profile-key` | Each `extra.agentenv` holds only the fields this profile defines | error | warning | +| `profile-version` | The root's `extra.agentenv.version`, when given, is a 1.x this validator knows: 1.0 or 1.1 | error | warning | +| `compaction` | A step's `compaction` is on a `source: agent` step and names who wrote its summary | error | warning | | `vocabulary` | A vocabulary field holds one of its values | error | warning | | `outside-key` | No `extra` holds a key outside `agentenv` but `ToolCall.extra.raw_arguments` | error | warning | | `call-id` | Each `tool_call_id` is unique across the document and its sub-agents | error | warning | diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py b/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py index dda27d843..c4cc95712 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py @@ -19,17 +19,20 @@ Trajectory, ) from .profile import ( + COMPACTION_TRIGGERS, FORMAT, PROFILE_KEY, PROFILE_VERSION, PROFILES, RAW_ARGUMENTS, SCHEMA_VERSION, + SUMMARY_WRITERS, VOCABULARIES, AdapterRef, AgentProfile, Arrival, AtifError, + Compaction, FinalMetricsProfile, MediaInfo, MetricsProfile, @@ -68,13 +71,14 @@ __all__ = [ "Adapter", "AdapterRef", "AdapterRun", "AdapterSpec", "Agent", "AgentProfile", "Arrival", "atif_adapter", - "AtifError", "AtifTurn", "AudioSource", "aux", "AuxEntry", "check", "check_adapter", "check_media", "ContentItem", "ContentPart", + "AtifError", "AtifTurn", "AudioSource", "aux", "AuxEntry", "check", "check_adapter", "check_media", "Compaction", + "COMPACTION_TRIGGERS", "ContentItem", "ContentPart", "Document", "dump_profile", "errors_in", "Fed", "FinalMetrics", "FinalMetricsProfile", "Finding", "finish", "FORMAT", "ImageSource", "is_prefix", "KIT_RULES", "KitResult", "load", "Media", "MEDIA_PATH", "media_file", "media_paths", "MediaInfo", "MediaItem", "MediaRef", "media_refs", "Metrics", "MetricsProfile", "Native", "native", "Observation", "ObservationResult", "ObservationResultProfile", "PROFILE_KEY", "profile_of", "PROFILE_VERSION", "PROFILES", "RAW_ARGUMENTS", "read_profile", "ReasoningBlock", "RecordedTask", "replay", "Rule", "RULES", "SCHEMA_VERSION", "Selector", "ServedData", "ServedError", "ServedMedia", "ServedTurn", "Step", "StepData", "StepError", "StepProfile", "StoredMedia", - "strip_profile", "SubagentTrajectoryRef", "SubagentTrajectoryRefProfile", "Task", "task_document", "tasks", "tasks_document", "timestamp", "ToolCall", + "strip_profile", "SubagentTrajectoryRef", "SUMMARY_WRITERS", "SubagentTrajectoryRefProfile", "Task", "task_document", "tasks", "tasks_document", "timestamp", "ToolCall", "ToolCallProfile", "Trajectory", "TrajectoryProfile", "TurnContext", "validate", "validate_live", "validate_media", "VOCABULARIES", ] diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/builder.py b/packages/agentenv-protocol/src/agentenv_protocol/atif/builder.py index 852817160..670561a33 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/builder.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/builder.py @@ -20,6 +20,7 @@ from .adapter import AdapterSpec from .models.content import AudioMediaType, ContentPart, ImageSource from .profile import ( + COMPACTION_TRIGGERS, COST_SOURCES, ERROR_KINDS, PROFILE_KEY, @@ -27,6 +28,7 @@ RAW_ARGUMENTS, RESULT_STATUSES, SCHEMA_VERSION, + SUMMARY_WRITERS, TASK_STATES, VISIBILITIES, AtifError, @@ -345,6 +347,9 @@ def peek(self, key: str, agent: str | None) -> _Step | None: def step_for(self, key: str, agent: str | None) -> _Step: return self.peek(key, agent) or self._start(self._traj(agent), "agent", key) + def system_step(self) -> _Step: + return self._start(self._traj(None), "system", None) + def open_step(self, agent: str | None) -> _Step: step = self._traj(agent).open if step is None: @@ -899,6 +904,30 @@ def error(self, *, message: str, kind: str = "agent_error", code: str | None = N target.profile["error"] = {k: v for k, v in (("kind", kind), ("message", message), ("code", code)) if v is not None} + def system_message(self, *, text: str | None = None, content: Sequence[Any] | None = None, + time: str | datetime | None = None) -> None: + """A message the harness itself put in the conversation, such as a command's output: a ``source: system`` step + of its own in the root trajectory, which closes the step before it. Profile 1.1.""" + parts, media = self._doc.parse_parts(content, text) + when = timestamp(time) + target = self._doc.system_step() + target.parts.extend(parts) + target.media.update(media) + self._touch(target, when) + + def compaction(self, *, step: str, written_by: str, trigger: str | None = None, agent: str | None = None) -> None: + """Mark step ``step`` a compaction: its message a summary that replaced the conversation before it in what the + agent sees, written by ``written_by`` (``assistant``, the agent's own model, or ``harness``) and set off by + ``trigger`` (``manual``, something asked for it, or ``auto``). The step is the call that wrote the summary, + so its usage goes on it with ``step``. Profile 1.1.""" + if written_by not in SUMMARY_WRITERS: + raise AtifError(f"written_by {written_by!r} isn't one of {', '.join(SUMMARY_WRITERS)}") + if trigger is not None and trigger not in COMPACTION_TRIGGERS: + raise AtifError(f"trigger {trigger!r} isn't one of {', '.join(COMPACTION_TRIGGERS)}") + target = self._doc.step_for(_key(step), agent) + target.profile["compaction"] = {key: value for key, value in (("written_by", written_by), ("trigger", trigger)) + if value is not None} + def attempt(self, number: int) -> None: """A harness retry: steps from here on carry attempt ``number``.""" self._doc.set_attempt(number) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/coding.json b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/coding.json index e537c7ee7..a1558c80b 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/coding.json +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/coding.json @@ -215,7 +215,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/computer_use.json b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/computer_use.json index 80131b2da..05ba6b9d9 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/computer_use.json +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/computer_use.json @@ -235,7 +235,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/late_result.json b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/late_result.json index daa7ad0cb..77c10cc52 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/late_result.json +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/late_result.json @@ -134,7 +134,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/multi_agent.json b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/multi_agent.json index 6b5ffe8d1..5ac19951f 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/multi_agent.json +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/multi_agent.json @@ -107,7 +107,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/odd_parts.json b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/odd_parts.json index 2dde0ae8e..988766473 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/odd_parts.json +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/odd_parts.json @@ -168,7 +168,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/subagent.json b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/subagent.json index 78f6b2c97..81bd5e1dd 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/subagent.json +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/subagent.json @@ -160,7 +160,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/two_turns.json b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/two_turns.json index ef02fb44d..fd3b4fc89 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/two_turns.json +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/fixtures/two_turns.json @@ -287,7 +287,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/profile.py b/packages/agentenv-protocol/src/agentenv_protocol/atif/profile.py index 0812d00f9..991ebd5cf 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/profile.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/profile.py @@ -12,7 +12,7 @@ FORMAT = "atif/1" #: The key under each ``extra`` that holds the profile. PROFILE_KEY = "agentenv" -PROFILE_VERSION = "1.0" +PROFILE_VERSION = "1.1" #: The ATIF version producers write: the oldest that holds the fields they use. SCHEMA_VERSION = "ATIF-v1.8" #: The only key outside ``extra.agentenv`` a producer writes: Harbor's, on a ToolCall whose input wasn't an object. @@ -24,6 +24,10 @@ ERROR_KINDS = ("agent_error", "infra_error") VISIBILITIES = ("raw", "summary", "omitted", "redacted") COST_SOURCES = ("harness", "provider") +#: Who wrote a compaction's summary: the agent's own model, or the harness. Added in 1.1. +SUMMARY_WRITERS = ("assistant", "harness") +#: What set a compaction off: something asked for it (a command), or the harness on its own. Added in 1.1. +COMPACTION_TRIGGERS = ("manual", "auto") VOCABULARIES = { "StepProfile.state": TASK_STATES, "ObservationResultProfile.status": RESULT_STATUSES, @@ -31,6 +35,8 @@ "ReasoningBlock.visibility": VISIBILITIES, "MetricsProfile.cost_source": COST_SOURCES, "FinalMetricsProfile.cost_source": COST_SOURCES, + "Compaction.written_by": SUMMARY_WRITERS, + "Compaction.trigger": COMPACTION_TRIGGERS, } @@ -77,6 +83,14 @@ class StepError(_Profile): code: str | None = None +class Compaction(_Profile): + """A step whose message is a summary that replaced the conversation before it, in what the agent sees from then on: + who wrote it, and what set it off. Added in 1.1.""" + + written_by: str | None = None + trigger: str | None = None + + class Arrival(_Profile): """When a result arrived after its call's step had closed: its time, and the step open when it came.""" @@ -113,6 +127,7 @@ class StepProfile(_Profile): reasoning: list[ReasoningBlock] | None = None media: dict[str, MediaInfo] | None = None data: list[StepData] | None = None + compaction: Compaction | None = None class ToolCallProfile(_Profile): diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py b/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py index 8cb2cc30e..d7b1ef648 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py @@ -1,5 +1,5 @@ """Checking an ATIF document against ATIF and the agentenv profile: the vendored models, the profile's models, and the -rules neither checks, each a finding with a rule id PROFILE.md names. A producer is held to profile 1.0; a reader of +rules neither checks, each a finding with a rule id PROFILE.md names. A producer is held to this profile; a reader of someone else's document is warned where a producer would fail, and fails only where agentenv couldn't read it.""" from __future__ import annotations @@ -21,6 +21,7 @@ VOCABULARIES, AdapterRef, Arrival, + Compaction, MediaInfo, ReasoningBlock, StepError, @@ -31,6 +32,7 @@ ERROR = "error" WARNING = "warning" +_VERSION = re.compile(r"(\d+)\.(\d+)") TIMESTAMP = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3}|\.\d{6})?Z$") _COUNTS = (("prompt_tokens", "total_prompt_tokens"), ("completion_tokens", "total_completion_tokens"), ("cached_tokens", "total_cached_tokens")) @@ -38,7 +40,7 @@ #: A profile field that holds a nested profile object, by its owner and name. _NESTED: dict[tuple[str, str], type[BaseModel]] = { ("Trajectory", "adapter"): AdapterRef, ("Step", "error"): StepError, - ("ObservationResult", "arrived"): Arrival, + ("ObservationResult", "arrived"): Arrival, ("Step", "compaction"): Compaction, } _LISTS: dict[tuple[str, str], type[BaseModel]] = {("Step", "reasoning"): ReasoningBlock} _MAPS: dict[tuple[str, str], type[BaseModel]] = { @@ -65,8 +67,11 @@ class Rule: Rule("json", ERROR, ERROR, "The document is a JSON object: UTF-8, with no NaN or infinity"), Rule("atif", ERROR, ERROR, "ATIF's own models, vendored from Harbor, accept it"), Rule("profile", ERROR, ERROR, "Each `extra.agentenv` parses with its profile model"), - Rule("profile-key", ERROR, WARNING, "Each `extra.agentenv` holds only the fields profile 1.0 defines"), - Rule("profile-version", ERROR, WARNING, "The root's `extra.agentenv.version`, when given, is `1.0`"), + Rule("profile-key", ERROR, WARNING, "Each `extra.agentenv` holds only the fields this profile defines"), + Rule("profile-version", ERROR, WARNING, "The root's `extra.agentenv.version`, when given, is a 1.x this validator " + "knows: 1.0 or 1.1"), + Rule("compaction", ERROR, WARNING, "A step's `compaction` is on a `source: agent` step and names who wrote its " + "summary"), Rule("vocabulary", ERROR, WARNING, "A vocabulary field holds one of its values"), Rule("outside-key", ERROR, WARNING, "No `extra` holds a key outside `agentenv` but `ToolCall.extra.raw_arguments`"), Rule("call-id", ERROR, WARNING, "Each `tool_call_id` is unique across the document and its sub-agents"), @@ -283,9 +288,28 @@ def _profiles(objects: list[tuple[str, str, Mapping[str, Any]]], found: _Finding for n, block in enumerate(profile.get("reasoning") or [] if kind == "Step" else []): if isinstance(block, Mapping) and block.get("visibility") is not None: _vocabulary("ReasoningBlock.visibility", f"{at}.reasoning[{n}].visibility", block["visibility"], found) - if kind == "Trajectory" and where == "" and profile.get("version") not in (None, PROFILE_VERSION): + compaction = profile.get("compaction") if kind == "Step" else None + if isinstance(compaction, Mapping): + if obj.get("source") != "agent": + found.add("compaction", f"{at}.compaction", "a compaction is the step of the call that wrote its " + f"summary, a source: agent step, not {obj.get('source')!r}") + if compaction.get("written_by") is None: + found.add("compaction", f"{at}.compaction.written_by", "a compaction names who wrote its summary") + for name in ("written_by", "trigger"): + if compaction.get(name) is not None: + _vocabulary(f"Compaction.{name}", f"{at}.compaction.{name}", compaction[name], found) + if kind == "Trajectory" and where == "" and not _known_version(profile.get("version")): found.add("profile-version", f"{at}.version", - f"this is profile {profile['version']!r}; the validator checks profile {PROFILE_VERSION}") + f"this is profile {profile['version']!r}; the validator checks profile {PROFILE_VERSION} and " + "the minors before it") + + +def _known_version(version: Any) -> bool: + """None, or a 1.x no newer than this profile: a minor only adds optional fields, so an older one is read whole.""" + if version is None: + return True + got, have = _VERSION.fullmatch(str(version)), _VERSION.fullmatch(PROFILE_VERSION) + return got is not None and have is not None and got[1] == have[1] and int(got[2]) <= int(have[2]) def _known_keys(kind: str, at: str, profile: Mapping[str, Any], found: _Findings) -> None: diff --git a/packages/agentenv-protocol/tests/test_atif_builder.py b/packages/agentenv-protocol/tests/test_atif_builder.py index 9db3e2219..615b54d3e 100644 --- a/packages/agentenv-protocol/tests/test_atif_builder.py +++ b/packages/agentenv-protocol/tests/test_atif_builder.py @@ -87,6 +87,49 @@ def test_a_final_response_the_last_step_lacks_gets_its_own_step_with_no_model_ca check(run.document()) +@atif_adapter(native_format="toy-events/1", version="0.1.0", input_includes_cache=False) +class Compacting(Adapter): + """Toy records with a compaction: the summary a model call wrote, its usage, and the harness's own message.""" + + @native(type="say") + def say(self, r, turn): + turn.message(step=r["step"], text=r["text"]) + + @native(type="compact") + def compact(self, r, turn): + turn.message(step=r["step"], text=r["text"]) + turn.compaction(step=r["step"], written_by=r.get("by", "assistant"), trigger=r.get("trigger")) + turn.step(key=r["step"], input_tokens=100, output_tokens=20) + + @native(type="system") + def system(self, r, turn): + turn.system_message(text=r["text"]) + + +def test_a_compaction_is_the_step_of_the_call_that_wrote_its_summary_and_the_harnesss_message_a_system_step(): + run, pages = run_task([{"type": "say", "step": "s1", "text": "working"}, + {"type": "compact", "step": "c1", "text": "the summary so far", "trigger": "manual"}, + {"type": "system", "text": "Compacted"}, + {"type": "say", "step": "s2", "text": "after it"}], cls=Compacting) + user, before, compaction, system, after = run.document()["steps"] + assert (compaction["source"], compaction["message"], compaction["llm_call_count"]) == ( + "agent", "the summary so far", 1) + assert compaction["metrics"] == {"prompt_tokens": 100, "completion_tokens": 20} + assert profile_of(compaction)["compaction"] == {"written_by": "assistant", "trigger": "manual"} + assert (system["source"], system["message"]) == ("system", "Compacted") + assert not {"model_name", "metrics", "llm_call_count", "tool_calls"} & set(system) + assert after["message"] == "after it" + check(run.document()) + assert all(is_prefix(a, b) for a, b in zip(pages, pages[1:]) if a is not None) + + +@pytest.mark.parametrize("record", [{"type": "compact", "step": "c1", "text": "x", "by": "someone"}, + {"type": "compact", "step": "c1", "text": "x", "trigger": "now"}]) +def test_a_compaction_names_a_writer_and_trigger_of_its_vocabularies(record): + with pytest.raises(AtifError, match="isn't one of"): + run_task([record], cls=Compacting) + + def test_the_terminal_state_is_never_served_before_the_task_ends(): run, pages = run_task([{"type": "say", "step": "s1", "text": "a"}, {"type": "say", "step": "s2", "text": "b"}]) for page in pages[:-1]: diff --git a/packages/agentenv-protocol/tests/test_atif_validator.py b/packages/agentenv-protocol/tests/test_atif_validator.py index 6de40b289..88aee3425 100644 --- a/packages/agentenv-protocol/tests/test_atif_validator.py +++ b/packages/agentenv-protocol/tests/test_atif_validator.py @@ -78,6 +78,7 @@ def _text_parts(document: dict[str, Any]) -> None: "profile": ("coding", lambda d: d["steps"][0]["extra"]["agentenv"].update(turn="zero")), "profile-key": ("coding", lambda d: d["steps"][0]["extra"]["agentenv"].update(later=1)), "profile-version": ("coding", lambda d: d["extra"]["agentenv"].update(version="2.0")), + "compaction": ("coding", lambda d: d["steps"][0]["extra"]["agentenv"].update(compaction={"written_by": "assistant"})), "vocabulary": ("coding", lambda d: d["steps"][-1]["extra"]["agentenv"].update(state="paused")), "outside-key": ("coding", lambda d: d["steps"][0]["extra"].update(note="x")), "call-id": ("coding", _duplicate_call_id), @@ -143,6 +144,29 @@ def test_an_unknown_profile_key_fails_a_producer_and_only_warns_a_reader(tmp_pat assert "warning profile-key steps[0].extra.agentenv.later" in capsys.readouterr().out +def test_a_compaction_sits_on_an_agent_step_names_who_wrote_it_and_holds_its_vocabularies(): + document = _fixture("coding") + profile = document["steps"][1].setdefault("extra", {}).setdefault("agentenv", {}) + profile["compaction"] = {"written_by": "assistant", "trigger": "manual"} + assert errors_in(validate(document)) == [] + profile["compaction"] = {"trigger": "auto"} + assert [(f.rule, f.where) for f in errors_in(validate(document))] == [ + ("compaction", "steps[1].extra.agentenv.compaction.written_by")] + profile["compaction"] = {"written_by": "someone", "trigger": "now"} + assert [(f.rule, f.where) for f in errors_in(validate(document))] == [ + ("vocabulary", "steps[1].extra.agentenv.compaction.written_by"), + ("vocabulary", "steps[1].extra.agentenv.compaction.trigger")] + + +@pytest.mark.parametrize(("version", "known"), [("1.0", True), ("1.1", True), ("1.2", False), ("2.0", False)]) +def test_a_document_of_an_earlier_minor_is_read_whole_and_a_later_one_is_flagged(version, known): + """A minor only adds optional fields, so a validator of 1.1 checks a 1.0 copy, from an agent on an older SDK, as its + own; one it doesn't know yet is flagged, as a newer document is.""" + document = _fixture("coding") + document["extra"]["agentenv"]["version"] = version + assert ("profile-version" in _rules(errors_in(validate(document)))) is not known + + def test_media_bytes_are_checked_against_their_name_and_profile(): document = _fixture("computer_use") path = _parts(document)[0]["source"]["path"] From 52e052bbda213d42fb0a45706138629bf5a39cd1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 08:17:49 -0800 Subject: [PATCH 2/7] feat(agents): Claude Code's atif/1 copy gives a compaction its step and the CLI's own messages system steps A compact_boundary and the summary after it are the step of the call that wrote the summary, profile compaction (assistant, its trigger), holding what the turn reported beyond its other steps, which the bridge's turn record now counts; the summary waits for that count, so a live reader never sees the step change. The CLI's own messages, a command's output say, are system steps. always_on's judge reads both as the notes a native turn gives, the judges' other atif/1 readers as the harness's rather than the agent's words, and a turn with no closing message ends "". Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/claude-code/a2a_server.py | 19 +++- .../agents/claude-code/claude_code_atif.py | 103 ++++++++++++++++-- .../verifiers/judge_utils/atif_turns.py | 25 ++++- .../verifiers/judge_utils/turn_events.py | 18 ++- .../claude_code_atif/api-error.expected.json | 2 +- .../claude_code_atif/browser.expected.json | 2 +- .../claude_code_atif/coding.expected.json | 2 +- .../claude_code_atif/compacted.expected.json | 39 +++++-- .../claude_code_atif/retried.expected.json | 2 +- .../claude_code_atif/subagent.expected.json | 2 +- .../claude_code_atif/thinking.expected.json | 2 +- tst/manual/claude_code_atif/record.py | 3 + .../test_claude_code_atif_recorded.py | 29 ++--- 13 files changed, 190 insertions(+), 58 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/a2a_server.py b/src/agent_env/agents/agents/claude-code/a2a_server.py index 99f2e4aca..d16af754a 100644 --- a/src/agent_env/agents/agents/claude-code/a2a_server.py +++ b/src/agent_env/agents/agents/claude-code/a2a_server.py @@ -432,6 +432,21 @@ def _builds_atif(request: TaskRequest[ClaudeCodeConfig]) -> bool: return getattr(request.trajectory, "builds_atif", True) +def _turn_record(usage: Usage) -> dict[str, Any]: + """The turn as the atif/1 adapter's ``turn`` record: its cost, and its token counts as a session record counts a + call's, the uncached input apart from the cache, unless they're a lower bound (calls no tally counted), with the + model when it was one.""" + record: dict[str, Any] = {"type": "turn", "cost_usd": usage.cost_usd} + if usage.input_tokens is None or usage.provider_details.get("unreported_calls"): + return record + cached = (usage.cache_read_tokens or 0) + (usage.cache_write_tokens or 0) if usage.input_includes_cache else 0 + record.update(input_tokens=usage.input_tokens - cached, output_tokens=usage.output_tokens or 0, + cache_read_tokens=usage.cache_read_tokens or 0, cache_write_tokens=usage.cache_write_tokens or 0) + if len(usage.models) == 1: + record["model"] = usage.models[0].model + return record + + def _usage(result: ClaudeResult) -> Usage: """The turn's tool calls and token counts, with ``input_tokens`` counting the cache. The counts are the CLI's own tally for the turn (``_turn_tally``), which covers every call, its subagents' too, and its cost; the turn's @@ -602,8 +617,8 @@ async def _turn(self, request: TaskRequest[ClaudeCodeConfig], cfg: ClaudeCodeCon self.set_session_ref_for_context(context_id, session_id) usage = _usage(result) - if usage.cost_usd is not None and _builds_atif(request): - request.trajectory.aux("turn", {"type": "turn", "cost_usd": usage.cost_usd}) + if _builds_atif(request): + request.trajectory.aux("turn", _turn_record(usage)) data: dict[str, Any] = {"tool_call_count": result.tool_call_count} if result.attempts > 1: data["cli_attempts"] = result.attempts diff --git a/src/agent_env/agents/agents/claude-code/claude_code_atif.py b/src/agent_env/agents/agents/claude-code/claude_code_atif.py index 8e245998c..47783f4a1 100644 --- a/src/agent_env/agents/agents/claude-code/claude_code_atif.py +++ b/src/agent_env/agents/agents/claude-code/claude_code_atif.py @@ -8,7 +8,12 @@ Sub-agents are embedded trajectories, each named by the call that spawned it in its task. Their final answer reaches only their own transcript, so a message the session gives and stdout doesn't is written from the session record. Records match across the two by uuid, the CLI's own id for each. A sub-agent the CLI continues in a later task is a new -trajectory there, under the call that continued it.""" +trajectory there, under the call that continued it. + +A compaction (a ``compact_boundary``, then the summary as a user message) is the step of the call that wrote the +summary, which no session record counts: it waits for the turn's own count, then takes what the turn reported beyond +its other steps, so a live reader never sees it change. The CLI's own messages, a command's output say, are system +steps.""" from __future__ import annotations import base64 @@ -24,6 +29,8 @@ TESTED_WITH = ("2.1.322",) #: The model a message the CLI wrote itself names, such as an API error's, which no model call produced. _SYNTHETIC_MODEL = "" +#: A step's token counts as the builder takes them, and as the turn record and a session record give them. +_COUNTS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") @dataclass(eq=False) @@ -34,6 +41,12 @@ class _Entry: agent: str | None from_stdout: bool ready: bool = False + #: A compaction's summary, held until the turn's count gives its call's usage, and what set it off. + summary: bool = False + held: bool = False + trigger: str | None = None + usage: dict[str, int] | None = None + model: str | None = None def _is_mapping(value: Any) -> bool: @@ -64,8 +77,8 @@ def _function(tool: Any) -> dict[str, Any] | None: class ClaudeCodeAtif(Adapter): """One A2A context's Claude Code session as ATIF. Aux files the bridge feeds: ``session``, the transcript's message records (one already on stdout without its content); ``tools``, each request shape's tools, once per shape; - ``attempt``, the error `result` of an attempt the bridge resumed; ``turn``, the turn's cost as the agent reports - it.""" + ``attempt``, the error `result` of an attempt the bridge resumed; ``turn``, the turn's cost and token counts as the + agent reports them.""" def __init__(self, turn: Any) -> None: self._seq = 0 @@ -85,6 +98,9 @@ def __init__(self, turn: Any) -> None: self._unplaced: set[str] = set() self._inits = 0 self._attempt_step: str | None = None + self._summary_next = False + self._summary_trigger: str | None = None + self._task_counts: dict[str, int] = {} # Records @@ -98,10 +114,20 @@ def message(self, record: dict[str, Any], turn: Any) -> None: self._spawner_of_uuid[uuid] = agent self._link(uuid) entry = self._enqueue(record, uuid, agent, from_stdout=True) + if self._summary_next and agent is None and record.get("type") == "user" and _texts(record): + entry.summary, entry.held, entry.trigger = True, True, self._summary_trigger + self._summary_next = False if uuid is not None and uuid in self._session: self._match(entry) self._flush(turn) + @native(type="system", where={"subtype": "compact_boundary"}) + def boundary(self, record: dict[str, Any], turn: Any) -> None: + """The CLI's compaction: the next user message on stdout is its summary.""" + metadata = record.get("compact_metadata") if _is_mapping(record.get("compact_metadata")) else {} + self._summary_next = True + self._summary_trigger = metadata.get("trigger") if metadata.get("trigger") in ("manual", "auto") else None + @native(type="system", where={"subtype": "init"}) def init(self, record: dict[str, Any], turn: Any) -> None: self._enqueue({"type": "init"}, None, None, from_stdout=False).ready = True @@ -154,6 +180,11 @@ def cost(self, record: dict[str, Any], turn: Any) -> None: cost = record.get("cost_usd") if isinstance(cost, (int, float)) and not isinstance(cost, bool): turn.task_cost(float(cost), source="harness") + for entry in self._queue: + if entry.held: + entry.usage, entry.held = self._left_over(record), False + entry.model = record.get("model") if isinstance(record.get("model"), str) else None + self._flush(turn) @finish def end(self, turn: Any) -> None: @@ -166,6 +197,8 @@ def end(self, turn: Any) -> None: self._cli_of_uuid.clear() self._inits = 0 self._attempt_step = None + self._summary_next = False + self._task_counts = {} self._task += 1 # The queue: records in the order they came, each written once its session record is in @@ -194,7 +227,8 @@ def _link(self, uuid: str) -> None: def _flush(self, turn: Any, *, everything: bool = False) -> None: while self._queue: head = self._queue[0] - waiting = not head.ready and not (head.from_stdout and self._matched.get(head.agent, 0) > head.seq) + waiting = head.held or (not head.ready and not (head.from_stdout and self._matched.get(head.agent, 0) > + head.seq)) if waiting and not everything: return self._queue.pop(0) @@ -228,7 +262,7 @@ def _write(self, entry: _Entry, turn: Any) -> None: if kind == "assistant": self._assistant(record, session, entry.agent, turn) elif kind == "user": - self._user(record, session, turn) + self._user(entry, session, turn) def _declare(self, agent: str, turn: Any) -> None: """Embed the sub-agent the call ``agent`` spawned. One whose call already has its result, as when its first @@ -257,8 +291,8 @@ def _define(self, turn: Any, definitions: list[dict[str, Any]], agent: str | Non def _assistant(self, record: dict[str, Any], session: dict[str, Any] | None, agent: str | None, turn: Any) -> None: message = record.get("message") if _is_mapping(record.get("message")) else {} - key = message.get("id") if isinstance(message.get("id"), str) else record.get("uuid") - if not isinstance(key, str): + key = _message_key(record) + if key is None: return model = message.get("model") if isinstance(message.get("model"), str) else None synthetic = model == _SYNTHETIC_MODEL @@ -273,6 +307,8 @@ def _assistant(self, record: dict[str, Any], session: dict[str, Any] | None, age usage = self._usage(session) if usage is not None: self._stamped.add(key) + for name, value in usage.items(): + self._task_counts[name] = self._task_counts.get(name, 0) + value turn.step(key=key, model_name=model, time=when, agent=agent, **(usage or {})) if agent is None: self._attempt_step = key @@ -295,13 +331,43 @@ def _block(self, block: dict[str, Any], key: str, agent: str | None, when: Any, if _is_mapping(arguments) and isinstance(arguments.get("subagent_type"), str): self._spawn_names[block["id"]] = arguments["subagent_type"] - def _user(self, record: dict[str, Any], session: dict[str, Any] | None, turn: Any) -> None: + def _user(self, entry: _Entry, session: dict[str, Any] | None, turn: Any) -> None: + """A user record's tool results; and on the root, its text: a compaction's summary, or else a message the CLI + put in the conversation itself, as a system step. A sub-agent's prompt stays in its spawning call.""" when = session.get("timestamp") if session is not None else None - for block in _blocks(record): - if block.get("type") != "tool_result" or not isinstance(block.get("tool_use_id"), str): + for block in _blocks(entry.record): + if block.get("type") == "tool_result" and isinstance(block.get("tool_use_id"), str): + turn.tool_result(source_call_id=block["tool_use_id"], content=self._result_content(block, turn), + status="error" if block.get("is_error") else "ok", time=when) + if entry.agent is not None: + return + for text in _texts(entry.record): + if entry.summary: + key = f"compaction-{entry.uuid or entry.seq}" + turn.message(step=key, text=text, time=when) + turn.compaction(step=key, written_by="assistant", trigger=entry.trigger) + turn.step(key=key, model_name=entry.model, time=when, **(entry.usage or {})) + entry.summary = False + else: + turn.system_message(text=text, time=when) + + def _left_over(self, record: dict[str, Any]) -> dict[str, int] | None: + """What the turn reported beyond its steps written or still queued: the call no session record counts, the + summary's. None when the turn gave no counts, or counted less than its steps, a lower bound.""" + reported = {name: record.get(name) for name in _COUNTS} + if not all(isinstance(value, int) and not isinstance(value, bool) for value in reported.values()): + return None + counted, seen = dict(self._task_counts), set(self._stamped) + for queued in self._queue: + key = _message_key(queued.record) if queued.record.get("type") == "assistant" else None + usage = self._usage(self._session.get(queued.uuid)) if queued.uuid is not None else None + if key is None or key in seen or usage is None: continue - turn.tool_result(source_call_id=block["tool_use_id"], content=self._result_content(block, turn), - status="error" if block.get("is_error") else "ok", time=when) + seen.add(key) + for name, value in usage.items(): + counted[name] = counted.get(name, 0) + value + left = {name: reported[name] - counted.get(name, 0) for name in _COUNTS} + return left if all(value >= 0 for value in left.values()) else None def _result_content(self, block: dict[str, Any], turn: Any) -> list[Any]: content = block.get("content") @@ -387,6 +453,19 @@ def from_atif(cls, document: dict[str, Any]) -> Native: return Native(log=log) +def _texts(record: dict[str, Any]) -> list[str]: + """A user record's text blocks, in order, each with something in it.""" + return [block["text"] for block in _blocks(record) + if block.get("type") == "text" and isinstance(block.get("text"), str) and block["text"].strip()] + + +def _message_key(record: dict[str, Any]) -> str | None: + """An assistant record's step key: its message id, else its uuid.""" + message = record.get("message") if _is_mapping(record.get("message")) else {} + key = message.get("id") if isinstance(message.get("id"), str) else record.get("uuid") + return key if isinstance(key, str) else None + + def _text(message: Any) -> list[dict[str, Any]]: if isinstance(message, str): return [{"type": "text", "text": message}] if message else [] diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py index 5f10b02e8..509a557c5 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py @@ -16,7 +16,16 @@ from dataclasses import dataclass from typing import Any, Optional -from agentenv_protocol.atif import FORMAT, AtifError, check_media, media_file, media_paths, tasks, tasks_document +from agentenv_protocol.atif import ( + FORMAT, + AtifError, + check_media, + media_file, + media_paths, + profile_of, + tasks, + tasks_document, +) from agent_env.config import get_config from agent_env.store.base import NotFoundError @@ -192,6 +201,12 @@ def _has_image(content: Any) -> bool: for part in content) +def is_compaction(step: Mapping[str, Any]) -> bool: + """Whether ``step`` is a compaction's: a summary a model call wrote to replace the conversation, the harness's + doing rather than the agent speaking.""" + return profile_of(step).get("compaction") is not None + + def steps_of(trajectory: Mapping[str, Any]) -> list[Mapping[str, Any]]: """A trajectory's steps a reader can walk: a stored copy may be invalid, and is still graded as stored.""" steps = trajectory.get("steps") @@ -273,7 +288,7 @@ def compact_atif_trajectory( def walk(trajectory: Mapping[str, Any], tag: Mapping[str, Any]) -> None: for step in steps_of(trajectory): - if step.get("source") != "agent": + if step.get("source") != "agent" or is_compaction(step): continue timestamp = step.get("timestamp") or "" if trajectory_filter.include_thinking and step.get("reasoning_content"): @@ -302,8 +317,8 @@ def walk(trajectory: Mapping[str, Any], tag: Mapping[str, Any]) -> None: walk(document, {}) if trajectory_filter.include_response: - final = next((step for step in reversed(steps_of(document)) - if step.get("source") == "agent" and content_text(step.get("message")).strip()), None) + final = next((step for step in reversed(steps_of(document)) if step.get("source") == "agent" + and not is_compaction(step) and content_text(step.get("message")).strip()), None) if final is not None: events.append({"type": "final_response", "text": content_text(final.get("message")), "timestamp": final.get("timestamp") or ""}) @@ -325,7 +340,7 @@ def transcript_from_atif( def walk(trajectory: Mapping[str, Any]) -> None: for step in steps_of(trajectory): - if step.get("source") != "agent": + if step.get("source") != "agent" or is_compaction(step): continue text = content_text(step.get("message")) if text.strip(): 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 7875ff848..30c268da6 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 @@ -20,6 +20,7 @@ SubAgents, calls_with_results, content_text, + is_compaction, steps_of, ) from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import ( @@ -452,13 +453,20 @@ def atif_turn_events(view: Mapping[str, Any]) -> TurnEvents: """One atif/1 turn's events, from its view (its A2A task cut out of the conversation's document, as ``atif_turns.AtifDocuments.view`` gives it), in the shapes a native Claude Code turn's take: each agent step's thinking and text, then its tool calls with their results; a sub-agent's events after the result that started it, - each naming it as ``subagent`` (the call that started it, as its ``parent_tool_use_id`` is natively); and the final, - the closing message, an error when the turn's task didn't complete.""" + each naming it as ``subagent`` (the call that started it, as its ``parent_tool_use_id`` is natively); a message the + harness put in (a system step) and a compaction's summary as notes, as a native turn's user-shaped messages are; + and the final, the closing message ("" for none, as the CLI's result gives it), an error when the turn's task didn't + complete.""" events: list[dict] = [] subagents = SubAgents(view) def walk(trajectory: Mapping[str, Any], tag: dict) -> None: for step in steps_of(trajectory): + if step.get("source") == "system" or (step.get("source") == "agent" and is_compaction(step)): + text = content_text(step.get("message")) + if text.strip(): + events.append({"type": "note", "text": text, **tag}) + continue if step.get("source") != "agent": continue if isinstance(step.get("reasoning_content"), str) and step["reasoning_content"].strip(): @@ -480,10 +488,10 @@ def walk(trajectory: Mapping[str, Any], tag: dict) -> None: walk(view, {}) steps = steps_of(view) - closing = next((step for step in reversed(steps) - if step.get("source") == "agent" and content_text(step.get("message")).strip()), None) + closing = next((step for step in reversed(steps) if step.get("source") == "agent" and not is_compaction(step) + and content_text(step.get("message")).strip()), None) state = profile_of(steps[-1]).get("state") if steps else None - events.append({"type": "final", "text": content_text(closing.get("message")) if closing else None, + events.append({"type": "final", "text": content_text(closing.get("message")) if closing else "", "error": state not in (None, "completed")}) return TurnEvents(ATIF, events, len(json.dumps(view))) diff --git a/tst/data/claude_code_atif/api-error.expected.json b/tst/data/claude_code_atif/api-error.expected.json index d108f9ac9..66da7e21d 100644 --- a/tst/data/claude_code_atif/api-error.expected.json +++ b/tst/data/claude_code_atif/api-error.expected.json @@ -46,7 +46,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "claude-code-stream-json/1", "adapter": { "name": "claude-code-stream-json-atif", diff --git a/tst/data/claude_code_atif/browser.expected.json b/tst/data/claude_code_atif/browser.expected.json index de72a508f..91ed48436 100644 --- a/tst/data/claude_code_atif/browser.expected.json +++ b/tst/data/claude_code_atif/browser.expected.json @@ -218,7 +218,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "claude-code-stream-json/1", "adapter": { "name": "claude-code-stream-json-atif", diff --git a/tst/data/claude_code_atif/coding.expected.json b/tst/data/claude_code_atif/coding.expected.json index f50cab221..e4031767c 100644 --- a/tst/data/claude_code_atif/coding.expected.json +++ b/tst/data/claude_code_atif/coding.expected.json @@ -170,7 +170,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "claude-code-stream-json/1", "adapter": { "name": "claude-code-stream-json-atif", diff --git a/tst/data/claude_code_atif/compacted.expected.json b/tst/data/claude_code_atif/compacted.expected.json index c721dd9ce..aaed83898 100644 --- a/tst/data/claude_code_atif/compacted.expected.json +++ b/tst/data/claude_code_atif/compacted.expected.json @@ -99,6 +99,27 @@ }, { "step_id": 5, + "timestamp": "2026-11-23T22:10:57.245Z", + "source": "agent", + "message": "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\n\nBash\n\nSummary:\n1. Primary Request and Intent:\n The user asked: \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n\n2. Key Technical Concepts:\n - Bash `printf` with redirection to write a multi-line file.\n - Working directory is /app. It is not a git repository.\n\n3. Files and Code Sections:\n - /app/notes.txt (created)\n - Holds the three requested lines.\n - Command used: `printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt`\n - Expected content:\n ```\n alpha\n beta\n gamma\n ```\n\n4. Errors and fixes:\n - None. The command completed with no output.\n\n5. Problem Solving:\n The task was straightforward and was solved with a single command. I did not read the file back to verify it.\n\n6. All user messages:\n - \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n - (A later user turn asked for this summary of the conversation. It was text-only, with no tool calls.)\n\n7. Pending Tasks:\n - Send the final reply, which must be only \"ok\".\n\n8. Current Work:\n I had just created /app/notes.txt with the Bash tool. The only step left was the user's requested one-word confirmation reply.\n\n9. Optional Next Step:\n Reply with exactly \"ok\", as the user asked (\"then reply with only ok\"). No other work is pending.\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/agent/.claude/projects/-app/157c8db2-a73b-4404-9413-836b695e1757.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened.\n\nThe messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them.", + "llm_call_count": 1, + "extra": { + "agentenv": { + "compaction": { + "written_by": "assistant", + "trigger": "manual" + } + } + } + }, + { + "step_id": 6, + "timestamp": "2026-11-23T22:10:57.358Z", + "source": "system", + "message": "Compacted " + }, + { + "step_id": 7, "timestamp": "2026-11-23T22:10:57.292647Z", "source": "agent", "message": "", @@ -110,7 +131,7 @@ } }, { - "step_id": 6, + "step_id": 8, "timestamp": "2026-11-23T22:10:57.789981Z", "source": "user", "message": "Read notes.txt with your tools and reply with only its second line.", @@ -124,7 +145,7 @@ } }, { - "step_id": 7, + "step_id": 9, "timestamp": "2026-11-23T22:10:59.101Z", "source": "agent", "model_name": "claude-sonnet-5-5", @@ -159,7 +180,7 @@ "llm_call_count": 1 }, { - "step_id": 8, + "step_id": 10, "timestamp": "2026-11-23T22:10:59.930Z", "source": "agent", "model_name": "claude-sonnet-5-5", @@ -183,28 +204,24 @@ } ], "final_metrics": { - "total_prompt_tokens": 116072, - "total_completion_tokens": 169, - "total_cached_tokens": 83042, "total_cost_usd": 0.1066379, - "total_steps": 8, + "total_steps": 10, "extra": { "agentenv": { - "cost_source": "harness", - "total_cache_write_tokens": 33022 + "cost_source": "harness" } } }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "claude-code-stream-json/1", "adapter": { "name": "claude-code-stream-json-atif", "version": "0.1.0" }, "unmatched": { - "system": 3 + "system": 2 } } } diff --git a/tst/data/claude_code_atif/retried.expected.json b/tst/data/claude_code_atif/retried.expected.json index 096ec6395..808866c68 100644 --- a/tst/data/claude_code_atif/retried.expected.json +++ b/tst/data/claude_code_atif/retried.expected.json @@ -155,7 +155,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "claude-code-stream-json/1", "adapter": { "name": "claude-code-stream-json-atif", diff --git a/tst/data/claude_code_atif/subagent.expected.json b/tst/data/claude_code_atif/subagent.expected.json index ea0db85d6..6aaa66ec7 100644 --- a/tst/data/claude_code_atif/subagent.expected.json +++ b/tst/data/claude_code_atif/subagent.expected.json @@ -174,7 +174,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "claude-code-stream-json/1", "adapter": { "name": "claude-code-stream-json-atif", diff --git a/tst/data/claude_code_atif/thinking.expected.json b/tst/data/claude_code_atif/thinking.expected.json index c560b3d1a..5bcc44120 100644 --- a/tst/data/claude_code_atif/thinking.expected.json +++ b/tst/data/claude_code_atif/thinking.expected.json @@ -70,7 +70,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "claude-code-stream-json/1", "adapter": { "name": "claude-code-stream-json-atif", diff --git a/tst/manual/claude_code_atif/record.py b/tst/manual/claude_code_atif/record.py index ccedb6afc..06078c82f 100644 --- a/tst/manual/claude_code_atif/record.py +++ b/tst/manual/claude_code_atif/record.py @@ -64,6 +64,9 @@ def scenarios(thinking_model: str) -> dict[str, dict]: "retried": {"faults": "stall", "env": {"CLAUDE_API_ERROR_RETRIES": "1", "API_TIMEOUT_MS": "15000"}, "prompts": ["Run `echo first` with your Bash tool, then run `echo second` with it, then reply " "with both outputs on one line."]}, + "autocompacted": {"env": {"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "20"}, "prompts": [ + "Create big.txt holding 3000 numbered lines of filler text with one Bash command, print it whole with cat, " + "then reply with only its last line."]}, "compacted": {"prompts": [ "Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.", "/compact", diff --git a/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py b/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py index 1ddbe350e..844fb9f42 100644 --- a/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py +++ b/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py @@ -26,6 +26,7 @@ from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import ( # noqa: E402 compact_atif_trajectory, + is_compaction, transcript_from_atif, ) from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter # noqa: E402 @@ -93,15 +94,14 @@ def test_a_recorded_run_replays_to_its_document_under_the_live_rule(scenario): @pytest.mark.parametrize("scenario", SCENARIOS) def test_a_recorded_runs_steps_sum_to_the_usage_each_turn_reported(scenario): - """The copy's totals are the turns' reported usage. Its token counts leave out a turn that compacts the conversation: - the copy has no step for the call that wrote its summary yet, though its cost counts it.""" + """The copy's totals are the turns' reported usage, a turn that compacts the conversation's included: the step of + the call that wrote its summary carries what the turn reported beyond its other steps.""" _, usage = recorded(scenario) final = replay(scenario).document["final_metrics"] - compacted = compacted_turns(scenario) reported = [turn or {} for turn in usage] for metric, field in (("total_prompt_tokens", "input_tokens"), ("total_completion_tokens", "output_tokens"), ("total_cached_tokens", "cache_read_tokens")): - total = sum(turn.get(field) or 0 for index, turn in enumerate(reported) if index not in compacted) + total = sum(turn.get(field) or 0 for turn in reported) assert final.get(metric, 0) == total, (metric, final.get(metric), total) if all(turn.get("cost_usd") is not None for turn in reported): assert math.isclose(final["total_cost_usd"], sum(turn["cost_usd"] for turn in reported)) @@ -125,7 +125,9 @@ def test_the_recordings_cover_what_the_adapter_maps(): assert any(step.get("extra", {}).get("agentenv", {}).get("attempt") == 2 for step in retried) assert any("error" in step.get("extra", {}).get("agentenv", {}) for step in documents["api-error"]["steps"]) assert any(step.get("extra", {}).get("agentenv", {}).get("reasoning") for step in documents["thinking"]["steps"]) - assert compacted_turns("compacted") == {1} + compaction = [step for step in documents["compacted"]["steps"] if "compaction" in step.get("extra", {}).get( + "agentenv", {})] + assert compacted_turns("compacted") == {1} and len(compaction) == 1 and compaction[0]["metrics"] @pytest.mark.parametrize("scenario", SCENARIOS) @@ -144,7 +146,8 @@ def test_a_judge_reads_each_recorded_turn_with_its_calls_results_answer_and_scre assert kinds.count("tool_call") == sum(len(step.get("tool_calls") or ()) for step in steps) assert kinds.count("tool_result") == len(results) assert ("final_response" in kinds) == any(isinstance(step.get("message"), str) and step["message"].strip() - for step in view["steps"] if step["source"] == "agent") + for step in view["steps"] + if step["source"] == "agent" and not is_compaction(step)) transcript, frames = transcript_from_atif(view, lambda path: check_media(path, kit.media[path]) or kit.media[path]) assert len(transcript.actions) == kinds.count("tool_call") assert len(frames) == len(images) @@ -157,21 +160,13 @@ def test_a_judge_reads_each_recorded_turn_with_its_calls_results_answer_and_scre @pytest.mark.parametrize("scenario", SCENARIOS) def test_a_recorded_turns_copy_gives_a_judge_the_events_its_native_trajectory_does(scenario): """always_on's judge stages each wake from its events. A copy gives the native turn's, but for a sub-agent's prompt, - which only native stdout carries (as a note), and its closing text, which only its transcript, so the copy, has; and - for a turn that compacts the conversation, whose summary and "Compacted" only native stdout carries (as notes) until - the copy has a compaction step.""" + which only native stdout carries (as a note), and its closing text, which only its transcript, so the copy, has. A + turn that compacts the conversation gives its summary and the CLI's "Compacted" as notes from both.""" data = json.loads((FIXTURES / f"{scenario}.json").read_text()) document = replay(scenario).document - compacted = compacted_turns(scenario) - for index, turn in enumerate(data["turns"]): + for turn in data["turns"]: native = turn_events(json.dumps(turn["native"])).events copied = atif_turn_events(task_document(document, [turn["turn"]["task_id"]])).events - if index in compacted: - notes = [e["text"] for e in native if e["type"] == "note"] - assert len(notes) == 2 and notes[0].startswith("This session is being continued") and "Compacted" in notes[1] - assert [e for e in native if e["type"] != "note"] == [{"type": "final", "text": "", "error": False}] - assert copied == [{"type": "final", "text": None, "error": False}] - continue if scenario == "subagent": assert [e["type"] for e in native if e.get("subagent")] == ["note", "tool_call"] assert [e["type"] for e in copied if e.get("subagent")] == ["tool_call", "text"] From 58837a472ef081be1f03d6904a5bb869b3b7c4b0 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 08:29:11 -0800 Subject: [PATCH 3/7] test(agents): Claude Code's compacted recording carries the turn's counts, and its copy matches native and its usage The compacted scenario re-recorded through the bridge's counted turn record: its copy's compaction step holds the summary call's tokens, so every turn's steps sum to its reported usage, and always_on's judge gets native's events on every turn; both pins come out. The adapter's held summary, a turn that counted less than its steps and one that never reported are unit-tested, and so is the bridge's turn record. A copy newer than the worker is now profile 1.2. Co-Authored-By: Claude Opus 5.5 --- .../claude_code_atif/compacted.expected.json | 69 ++-- tst/data/claude_code_atif/compacted.json | 339 +++++++++--------- tst/data/verifier_golden/judge_inputs.json | 20 +- tst/manual/claude_code_atif/record.py | 3 - .../claude_code/test_claude_code_atif.py | 51 +++ .../agents/claude_code/test_session_tail.py | 7 +- tst/unit/agents/claude_code/test_usage.py | 15 + .../test_prompt_agent_atif_copies.py | 2 +- 8 files changed, 300 insertions(+), 206 deletions(-) diff --git a/tst/data/claude_code_atif/compacted.expected.json b/tst/data/claude_code_atif/compacted.expected.json index aaed83898..5286105ca 100644 --- a/tst/data/claude_code_atif/compacted.expected.json +++ b/tst/data/claude_code_atif/compacted.expected.json @@ -12,27 +12,27 @@ "steps": [ { "step_id": 1, - "timestamp": "2026-11-23T22:10:47.698919Z", + "timestamp": "2026-11-24T16:18:49.081829Z", "source": "user", "message": "Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.", "extra": { "agentenv": { "context_id": "ctx-compacted", - "task_id": "3187814c-b5cc-427e-8aff-fa89353ae7b6", - "message_id": "73c2fd7665cf4d22a39088941aeedb47", + "task_id": "b5f6e991-9fbb-4ab4-82df-26365cd417a2", + "message_id": "bc81b8233f354384bdc90835960f89fc", "turn": 0 } } }, { "step_id": 2, - "timestamp": "2026-11-23T22:10:49.899Z", + "timestamp": "2026-11-24T16:18:51.016Z", "source": "agent", "model_name": "claude-sonnet-5-5", "message": "", "tool_calls": [ { - "tool_call_id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "tool_call_id": "toolu_vrtx_01XsDF5WYPxcQc9hpezrmcyU", "function_name": "Bash", "arguments": { "command": "printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt", @@ -43,7 +43,7 @@ "observation": { "results": [ { - "source_call_id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "source_call_id": "toolu_vrtx_01XsDF5WYPxcQc9hpezrmcyU", "content": "(Bash completed with no output)" } ] @@ -62,7 +62,7 @@ }, { "step_id": 3, - "timestamp": "2026-11-23T22:10:50.839Z", + "timestamp": "2026-11-24T16:18:52.040Z", "source": "agent", "model_name": "claude-sonnet-5-5", "message": "ok", @@ -85,23 +85,34 @@ }, { "step_id": 4, - "timestamp": "2026-11-23T22:10:51.735809Z", + "timestamp": "2026-11-24T16:18:52.111309Z", "source": "user", "message": "/compact", "extra": { "agentenv": { "context_id": "ctx-compacted", - "task_id": "93db87a5-3825-461b-85a2-636e23b45eaa", - "message_id": "8ec3fe03a9e342ea9ca816e236111e4a", + "task_id": "3582283e-2286-4159-a3d8-081ff8818a46", + "message_id": "70b357f0f76e4928b19432afc4227521", "turn": 1 } } }, { "step_id": 5, - "timestamp": "2026-11-23T22:10:57.245Z", + "timestamp": "2026-11-24T16:18:57.853Z", "source": "agent", - "message": "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\n\nBash\n\nSummary:\n1. Primary Request and Intent:\n The user asked: \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n\n2. Key Technical Concepts:\n - Bash `printf` with redirection to write a multi-line file.\n - Working directory is /app. It is not a git repository.\n\n3. Files and Code Sections:\n - /app/notes.txt (created)\n - Holds the three requested lines.\n - Command used: `printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt`\n - Expected content:\n ```\n alpha\n beta\n gamma\n ```\n\n4. Errors and fixes:\n - None. The command completed with no output.\n\n5. Problem Solving:\n The task was straightforward and was solved with a single command. I did not read the file back to verify it.\n\n6. All user messages:\n - \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n - (A later user turn asked for this summary of the conversation. It was text-only, with no tool calls.)\n\n7. Pending Tasks:\n - Send the final reply, which must be only \"ok\".\n\n8. Current Work:\n I had just created /app/notes.txt with the Bash tool. The only step left was the user's requested one-word confirmation reply.\n\n9. Optional Next Step:\n Reply with exactly \"ok\", as the user asked (\"then reply with only ok\"). No other work is pending.\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/agent/.claude/projects/-app/157c8db2-a73b-4404-9413-836b695e1757.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened.\n\nThe messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them.", + "model_name": "anthropic/claude-sonnet-5-5", + "message": "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\n\nBash\n\nSummary:\n1. Primary Request and Intent:\n The user asked me to create notes.txt holding three lines, alpha, beta and gamma, with the Bash tool, and then reply with only \"ok\".\n\n2. Key Technical Concepts:\n - Bash `printf` for writing multi-line file content.\n - Working directory is /app, which is not a git repository.\n - A system-reminder set attribution lines for future git commits and PRs. It has not been used, because no git operations were requested.\n\n3. Files and Code Sections:\n - /app/notes.txt (created)\n - It is the file the user asked for.\n - Command used: `printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt`\n - Intended contents:\n ```\n alpha\n beta\n gamma\n ```\n\n4. Errors and fixes:\n - None. The command completed with no output and no errors. I did not run a separate check of the file contents.\n\n5. Problem Solving:\n The task was simple and was solved with a single Bash command.\n\n6. All user messages:\n - \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n - A later message asked for a text-only summary of the conversation, with no tool calls.\n\n7. Pending Tasks:\n - Send the final reply to the original request, which must be only \"ok\".\n\n8. Current Work:\n I had just created /app/notes.txt with the Bash tool. The only step left from the user's request is the one-word reply.\n\n9. Optional Next Step:\n Reply with only \"ok\", as the user asked: \"then reply with only ok.\"\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/agent/.claude/projects/-app/be7b16da-08d9-4cb5-b992-aab353b9ffa0.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened.\n\nThe messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them.", + "metrics": { + "prompt_tokens": 30626, + "cached_tokens": 28507, + "completion_tokens": 749, + "extra": { + "agentenv": { + "cache_write_tokens": 108 + } + } + }, "llm_call_count": 1, "extra": { "agentenv": { @@ -114,13 +125,13 @@ }, { "step_id": 6, - "timestamp": "2026-11-23T22:10:57.358Z", + "timestamp": "2026-11-24T16:18:57.961Z", "source": "system", "message": "Compacted " }, { "step_id": 7, - "timestamp": "2026-11-23T22:10:57.292647Z", + "timestamp": "2026-11-24T16:18:57.886758Z", "source": "agent", "message": "", "llm_call_count": 0, @@ -132,27 +143,27 @@ }, { "step_id": 8, - "timestamp": "2026-11-23T22:10:57.789981Z", + "timestamp": "2026-11-24T16:18:58.166723Z", "source": "user", "message": "Read notes.txt with your tools and reply with only its second line.", "extra": { "agentenv": { "context_id": "ctx-compacted", - "task_id": "d98aa508-6da7-4c5d-8e18-fd76b9184490", - "message_id": "63535bbb2b3445e78152cb9bc8d5b185", + "task_id": "cfe13578-8114-4f29-94c0-2f212258b1de", + "message_id": "6c15caada7af483f8f0d9f87a2553cec", "turn": 2 } } }, { "step_id": 9, - "timestamp": "2026-11-23T22:10:59.101Z", + "timestamp": "2026-11-24T16:18:59.557Z", "source": "agent", "model_name": "claude-sonnet-5-5", "message": "", "tool_calls": [ { - "tool_call_id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "tool_call_id": "toolu_vrtx_018qXuMNxTjZ49fouyUngguP", "function_name": "Read", "arguments": { "file_path": "/app/notes.txt" @@ -162,18 +173,18 @@ "observation": { "results": [ { - "source_call_id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "source_call_id": "toolu_vrtx_018qXuMNxTjZ49fouyUngguP", "content": "1\talpha\n2\tbeta\n3\tgamma\n4\t" } ] }, "metrics": { - "prompt_tokens": 29427, + "prompt_tokens": 29462, "cached_tokens": 25110, "completion_tokens": 55, "extra": { "agentenv": { - "cache_write_tokens": 4315 + "cache_write_tokens": 4350 } } }, @@ -181,13 +192,13 @@ }, { "step_id": 10, - "timestamp": "2026-11-23T22:10:59.930Z", + "timestamp": "2026-11-24T16:19:00.493Z", "source": "agent", "model_name": "claude-sonnet-5-5", "message": "beta", "metrics": { - "prompt_tokens": 29506, - "cached_tokens": 29425, + "prompt_tokens": 29541, + "cached_tokens": 29460, "completion_tokens": 4, "extra": { "agentenv": { @@ -204,11 +215,15 @@ } ], "final_metrics": { - "total_cost_usd": 0.1066379, + "total_prompt_tokens": 146768, + "total_completion_tokens": 918, + "total_cached_tokens": 111584, + "total_cost_usd": 0.1072889, "total_steps": 10, "extra": { "agentenv": { - "cost_source": "harness" + "cost_source": "harness", + "total_cache_write_tokens": 33165 } } }, diff --git a/tst/data/claude_code_atif/compacted.json b/tst/data/claude_code_atif/compacted.json index ec54d5791..870edb4f1 100644 --- a/tst/data/claude_code_atif/compacted.json +++ b/tst/data/claude_code_atif/compacted.json @@ -6,12 +6,12 @@ "turn": { "index": 0, "context_id": "ctx-compacted", - "task_id": "3187814c-b5cc-427e-8aff-fa89353ae7b6", - "message_id": "73c2fd7665cf4d22a39088941aeedb47", + "task_id": "b5f6e991-9fbb-4ab4-82df-26365cd417a2", + "message_id": "bc81b8233f354384bdc90835960f89fc", "agent_name": "Claude Code", "agent_version": "1.0.0", "agent_model": "anthropic/claude-sonnet-5-5", - "started_at": "2026-11-23T22:10:47.698919Z", + "started_at": "2026-11-24T16:18:49.081829Z", "inbound": [ "Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok." ], @@ -19,7 +19,7 @@ "final": [ "ok" ], - "ended_at": "2026-11-23T22:10:50.869088Z", + "ended_at": "2026-11-24T16:18:52.064372Z", "data": [ { "data": { @@ -33,7 +33,7 @@ "type": "system", "subtype": "init", "cwd": "/app", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", "tools": [ "Task", "Bash", @@ -188,7 +188,7 @@ ], "analytics_disabled": true, "product_feedback_disabled": true, - "uuid": "ba2efe63-759f-4c43-b465-c9e8187556d9", + "uuid": "26f3dfa4-791c-45ff-9d30-c7bec239cda8", "memory_paths": { "auto": "/home/agent/.claude/projects/-app/memory/" }, @@ -206,13 +206,13 @@ "type": "assistant", "message": { "model": "claude-sonnet-5-5", - "id": "msg_vrtx_011ChLdEeWRVHxAsDPSN33yj", + "id": "msg_vrtx_011ChN4Co8D8Yd9Tq58hYNjW", "type": "message", "role": "assistant", "content": [ { "type": "tool_use", - "id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "id": "toolu_vrtx_01XsDF5WYPxcQc9hpezrmcyU", "name": "Bash", "input": { "command": "printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt", @@ -238,10 +238,10 @@ "context_management": null }, "parent_tool_use_id": null, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "05103c57-4f92-435d-b5c0-e0f4115ca66a", - "timestamp": "2026-11-23T22:10:49.899Z", - "request_id": "req_vrtx_011ChLdEeUC7ThqZEM5ZbjNU" + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "98edf6fe-3052-4de7-9e83-6f812acfa079", + "timestamp": "2026-11-24T16:18:51.016Z", + "request_id": "req_vrtx_011ChN4Co6UDNY2fFR2zchr3" }, { "type": "user", @@ -249,7 +249,7 @@ "role": "user", "content": [ { - "tool_use_id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "tool_use_id": "toolu_vrtx_01XsDF5WYPxcQc9hpezrmcyU", "type": "tool_result", "content": "(Bash completed with no output)", "is_error": false @@ -257,9 +257,9 @@ ] }, "parent_tool_use_id": null, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "511698fe-e874-4270-92ad-9d262420a17b", - "timestamp": "2026-11-23T22:10:49.951Z", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "37a4e071-2055-44c9-8f69-748b703c1560", + "timestamp": "2026-11-24T16:18:51.056Z", "tool_use_result": { "stdout": "", "stderr": "", @@ -269,7 +269,7 @@ }, "tool_result_meta": [ { - "id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "id": "toolu_vrtx_01XsDF5WYPxcQc9hpezrmcyU", "permission_decision": { "decision": "accept", "source": "config", @@ -282,7 +282,7 @@ "type": "assistant", "message": { "model": "claude-sonnet-5-5", - "id": "msg_vrtx_011ChLdEmAmEHepkuRgEAFtA", + "id": "msg_vrtx_011ChN4CuwjKcgUt6o1XYBPr", "type": "message", "role": "assistant", "content": [ @@ -309,15 +309,15 @@ "context_management": null }, "parent_tool_use_id": null, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911", - "timestamp": "2026-11-23T22:10:50.839Z", - "request_id": "req_vrtx_011ChLdEm8nnrqLR8zzWqDVB" + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "6cb0a703-6be4-45d6-a989-ea3cfa547712", + "timestamp": "2026-11-24T16:18:52.040Z", + "request_id": "req_vrtx_011ChN4CuvEmqVZtQmhUxnLr" }, { - "duration_api_ms": 2651, + "duration_api_ms": 2645, "stop_reason": "end_turn", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", "total_cost_usd": 0.07552869999999999, "usage": { "input_tokens": 4, @@ -393,13 +393,13 @@ "subtype": "success", "api_error_status": null, "result": "ok", - "ttft_ms": 1780, + "ttft_ms": 1684, "type": "result", - "duration_ms": 2730, - "uuid": "1c3f813d-b564-42fd-a9b9-a5a14cd5e263", - "ttft_stream_ms": 1391, - "time_to_request_ms": 60, - "first_content_frame_ms": 1391, + "duration_ms": 2714, + "uuid": "3f3737a0-9d05-4184-8c1b-6edbde8ffd0b", + "ttft_stream_ms": 1288, + "time_to_request_ms": 52, + "first_content_frame_ms": 1289, "queued_turn_count": 0, "result_index": 0, "model_usage_since_last_result": { @@ -427,8 +427,8 @@ "name": "session", "record": { "type": "user", - "uuid": "4e39555c-5a67-4b67-86b4-2edcbb129349", - "timestamp": "2026-11-23T22:10:48.139Z", + "uuid": "bddc13e5-299d-49ad-b7a5-37ec6b088e53", + "timestamp": "2026-11-24T16:18:49.343Z", "isSidechain": false, "message": {} }, @@ -449,11 +449,11 @@ "name": "session", "record": { "type": "assistant", - "uuid": "05103c57-4f92-435d-b5c0-e0f4115ca66a", - "timestamp": "2026-11-23T22:10:49.899Z", + "uuid": "98edf6fe-3052-4de7-9e83-6f812acfa079", + "timestamp": "2026-11-24T16:18:51.016Z", "isSidechain": false, "message": { - "id": "msg_vrtx_011ChLdEeWRVHxAsDPSN33yj", + "id": "msg_vrtx_011ChN4Co8D8Yd9Tq58hYNjW", "model": "claude-sonnet-5-5", "usage": { "input_tokens": 2, @@ -486,8 +486,8 @@ "name": "session", "record": { "type": "user", - "uuid": "511698fe-e874-4270-92ad-9d262420a17b", - "timestamp": "2026-11-23T22:10:49.951Z", + "uuid": "37a4e071-2055-44c9-8f69-748b703c1560", + "timestamp": "2026-11-24T16:18:51.056Z", "isSidechain": false, "message": {} }, @@ -497,11 +497,11 @@ "name": "session", "record": { "type": "assistant", - "uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911", - "timestamp": "2026-11-23T22:10:50.839Z", + "uuid": "6cb0a703-6be4-45d6-a989-ea3cfa547712", + "timestamp": "2026-11-24T16:18:52.040Z", "isSidechain": false, "message": { - "id": "msg_vrtx_011ChLdEmAmEHepkuRgEAFtA", + "id": "msg_vrtx_011ChN4CuwjKcgUt6o1XYBPr", "model": "claude-sonnet-5-5", "usage": { "input_tokens": 2, @@ -534,7 +534,12 @@ "name": "turn", "record": { "type": "turn", - "cost_usd": 0.07552869999999999 + "cost_usd": 0.07552869999999999, + "input_tokens": 4, + "output_tokens": 110, + "cache_read_tokens": 28507, + "cache_write_tokens": 28628, + "model": "anthropic/claude-sonnet-5-5" }, "after": 5 } @@ -571,12 +576,12 @@ "turn": { "index": 1, "context_id": "ctx-compacted", - "task_id": "93db87a5-3825-461b-85a2-636e23b45eaa", - "message_id": "8ec3fe03a9e342ea9ca816e236111e4a", + "task_id": "3582283e-2286-4159-a3d8-081ff8818a46", + "message_id": "70b357f0f76e4928b19432afc4227521", "agent_name": "Claude Code", "agent_version": "1.0.0", "agent_model": "anthropic/claude-sonnet-5-5", - "started_at": "2026-11-23T22:10:51.735809Z", + "started_at": "2026-11-24T16:18:52.111309Z", "inbound": [ "/compact" ], @@ -584,7 +589,7 @@ "final": [ "" ], - "ended_at": "2026-11-23T22:10:57.292647Z", + "ended_at": "2026-11-24T16:18:57.886758Z", "data": [ { "data": { @@ -598,22 +603,22 @@ "type": "system", "subtype": "status", "status": "compacting", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "24570ba6-05ae-4cd6-806b-f52dd2a4690c" + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "2a8c6671-1c42-4030-ab8e-ddb5602cb7a5" }, { "type": "system", "subtype": "status", "status": null, "compact_result": "success", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "079043cd-d7ae-44ef-a43e-bc805976408e" + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "4076f78d-9dbb-4180-8fd3-ad5ff1d56297" }, { "type": "system", "subtype": "init", "cwd": "/app", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", "tools": [ "Task", "Bash", @@ -768,7 +773,7 @@ ], "analytics_disabled": true, "product_feedback_disabled": true, - "uuid": "f5dddf18-db75-4de2-8255-7eb637fd4954", + "uuid": "2fee3921-6687-4302-b105-0da2f86c3698", "memory_paths": { "auto": "/home/agent/.claude/projects/-app/memory/" }, @@ -785,41 +790,41 @@ { "type": "system", "subtype": "compact_boundary", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "5154ac5c-60a8-4618-ac8e-0c013d6d69a1", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "ec26b570-1003-4db2-8ede-5ae96b0fee65", "compact_metadata": { "trigger": "manual", "pre_tokens": 28634, - "post_tokens": 2804, - "cumulative_dropped_tokens": 25830, - "duration_ms": 5247, + "post_tokens": 2839, + "cumulative_dropped_tokens": 25795, + "duration_ms": 5515, "preserved_segment": { - "head_uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911", - "anchor_uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", - "tail_uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + "head_uuid": "6cb0a703-6be4-45d6-a989-ea3cfa547712", + "anchor_uuid": "e606ccf1-5ee3-4818-a037-2fa10e560030", + "tail_uuid": "6cb0a703-6be4-45d6-a989-ea3cfa547712" }, "preserved_messages": { - "anchor_uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", + "anchor_uuid": "e606ccf1-5ee3-4818-a037-2fa10e560030", "uuids": [ - "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + "6cb0a703-6be4-45d6-a989-ea3cfa547712" ], "all_uuids": [ - "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + "6cb0a703-6be4-45d6-a989-ea3cfa547712" ] } }, - "logical_parent_uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + "logical_parent_uuid": "6cb0a703-6be4-45d6-a989-ea3cfa547712" }, { "type": "user", "message": { "role": "user", - "content": "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\n\nBash\n\nSummary:\n1. Primary Request and Intent:\n The user asked: \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n\n2. Key Technical Concepts:\n - Bash `printf` with redirection to write a multi-line file.\n - Working directory is /app. It is not a git repository.\n\n3. Files and Code Sections:\n - /app/notes.txt (created)\n - Holds the three requested lines.\n - Command used: `printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt`\n - Expected content:\n ```\n alpha\n beta\n gamma\n ```\n\n4. Errors and fixes:\n - None. The command completed with no output.\n\n5. Problem Solving:\n The task was straightforward and was solved with a single command. I did not read the file back to verify it.\n\n6. All user messages:\n - \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n - (A later user turn asked for this summary of the conversation. It was text-only, with no tool calls.)\n\n7. Pending Tasks:\n - Send the final reply, which must be only \"ok\".\n\n8. Current Work:\n I had just created /app/notes.txt with the Bash tool. The only step left was the user's requested one-word confirmation reply.\n\n9. Optional Next Step:\n Reply with exactly \"ok\", as the user asked (\"then reply with only ok\"). No other work is pending.\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/agent/.claude/projects/-app/157c8db2-a73b-4404-9413-836b695e1757.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened.\n\nThe messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them." + "content": "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\n\nBash\n\nSummary:\n1. Primary Request and Intent:\n The user asked me to create notes.txt holding three lines, alpha, beta and gamma, with the Bash tool, and then reply with only \"ok\".\n\n2. Key Technical Concepts:\n - Bash `printf` for writing multi-line file content.\n - Working directory is /app, which is not a git repository.\n - A system-reminder set attribution lines for future git commits and PRs. It has not been used, because no git operations were requested.\n\n3. Files and Code Sections:\n - /app/notes.txt (created)\n - It is the file the user asked for.\n - Command used: `printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt`\n - Intended contents:\n ```\n alpha\n beta\n gamma\n ```\n\n4. Errors and fixes:\n - None. The command completed with no output and no errors. I did not run a separate check of the file contents.\n\n5. Problem Solving:\n The task was simple and was solved with a single Bash command.\n\n6. All user messages:\n - \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n - A later message asked for a text-only summary of the conversation, with no tool calls.\n\n7. Pending Tasks:\n - Send the final reply to the original request, which must be only \"ok\".\n\n8. Current Work:\n I had just created /app/notes.txt with the Bash tool. The only step left from the user's request is the one-word reply.\n\n9. Optional Next Step:\n Reply with only \"ok\", as the user asked: \"then reply with only ok.\"\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/agent/.claude/projects/-app/be7b16da-08d9-4cb5-b992-aab353b9ffa0.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened.\n\nThe messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them." }, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", "parent_tool_use_id": null, - "uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", - "timestamp": "2026-11-23T22:10:57.245Z", + "uuid": "e606ccf1-5ee3-4818-a037-2fa10e560030", + "timestamp": "2026-11-24T16:18:57.853Z", "isReplay": false, "isSynthetic": true }, @@ -829,10 +834,10 @@ "role": "user", "content": "Compacted " }, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", "parent_tool_use_id": null, - "uuid": "b5822639-42f5-44c2-88c7-a2046d8722d0", - "timestamp": "2026-11-23T22:10:57.358Z", + "uuid": "95e83aab-745d-467d-b887-5edea575e647", + "timestamp": "2026-11-24T16:18:57.961Z", "isReplay": true }, { @@ -840,8 +845,8 @@ "duration_api_ms": 0, "num_turns": 0, "stop_reason": null, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "total_cost_usd": 0.0896014, + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "total_cost_usd": 0.09016139999999999, "usage": { "output_tokens_details": { "thinking_tokens": 0 @@ -867,14 +872,14 @@ "modelUsage": { "anthropic/claude-sonnet-5-5": { "inputTokens": 2015, - "outputTokens": 803, + "outputTokens": 859, "thinkingTokens": 0, "cacheReadInputTokens": 57014, "cacheCreationInputTokens": 28736, "cacheCreationEphemeral5mInputTokens": 28736, "cacheCreationEphemeral1hInputTokens": 0, "webSearchRequests": 0, - "costUSD": 0.0896014, + "costUSD": 0.09016139999999999, "contextWindow": 1000000, "maxOutputTokens": 128000, "canonicalModel": "claude-sonnet-5-5", @@ -914,18 +919,18 @@ "result": "", "local_command": "compact", "type": "result", - "duration_ms": 5302, - "uuid": "97facf62-cd73-4e72-b0df-b883340b401d", + "duration_ms": 5540, + "uuid": "db18118a-fe4c-4e0f-9659-c526fcbae35f", "queued_turn_count": 0, "result_index": 0, "model_usage_since_last_result": { "anthropic/claude-sonnet-5-5": { "inputTokens": 2011, - "outputTokens": 693, + "outputTokens": 749, "cacheReadInputTokens": 28507, "cacheCreationInputTokens": 108, "webSearchRequests": 0, - "costUSD": 0.0140727, + "costUSD": 0.014632700000000002, "contextWindow": 1000000, "maxOutputTokens": 128000, "thinkingTokens": 0, @@ -943,8 +948,8 @@ "name": "session", "record": { "type": "user", - "uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", - "timestamp": "2026-11-23T22:10:57.245Z", + "uuid": "e606ccf1-5ee3-4818-a037-2fa10e560030", + "timestamp": "2026-11-24T16:18:57.853Z", "isSidechain": false, "message": {} }, @@ -954,8 +959,8 @@ "name": "session", "record": { "type": "user", - "uuid": "741e478b-0197-406a-b222-d32ca9fd40fa", - "timestamp": "2026-11-23T22:10:51.994Z", + "uuid": "a3942d75-18c4-4b45-bbae-0d8aa39d95c3", + "timestamp": "2026-11-24T16:18:52.338Z", "isSidechain": false, "message": {} }, @@ -965,8 +970,8 @@ "name": "session", "record": { "type": "user", - "uuid": "e8990ee7-182d-4d62-92a2-a5bf10de0c3d", - "timestamp": "2026-11-23T22:10:51.994Z", + "uuid": "ef592b32-4258-4d4b-94f0-cd4e314a34d7", + "timestamp": "2026-11-24T16:18:52.338Z", "isSidechain": false, "message": {} }, @@ -976,8 +981,8 @@ "name": "session", "record": { "type": "user", - "uuid": "b5822639-42f5-44c2-88c7-a2046d8722d0", - "timestamp": "2026-11-23T22:10:57.358Z", + "uuid": "95e83aab-745d-467d-b887-5edea575e647", + "timestamp": "2026-11-24T16:18:57.961Z", "isSidechain": false, "message": {} }, @@ -987,7 +992,12 @@ "name": "turn", "record": { "type": "turn", - "cost_usd": 0.014072700000000007 + "cost_usd": 0.014632699999999998, + "input_tokens": 2011, + "output_tokens": 749, + "cache_read_tokens": 28507, + "cache_write_tokens": 108, + "model": "anthropic/claude-sonnet-5-5" }, "after": 7 } @@ -995,21 +1005,21 @@ "usage": { "tool_call_count": 0, "input_tokens": 30626, - "output_tokens": 693, - "total_tokens": 31319, + "output_tokens": 749, + "total_tokens": 31375, "cache_read_tokens": 28507, "cache_write_tokens": 108, "input_includes_cache": true, - "cost_usd": 0.014072700000000007, + "cost_usd": 0.014632699999999998, "models": [ { "model": "anthropic/claude-sonnet-5-5", "input_tokens": 30626, - "output_tokens": 693, + "output_tokens": 749, "cache_read_tokens": 28507, "cache_write_tokens": 108, "input_includes_cache": true, - "cost_usd": 0.014072700000000007 + "cost_usd": 0.014632699999999998 } ], "provider_details": { @@ -1024,12 +1034,12 @@ "turn": { "index": 2, "context_id": "ctx-compacted", - "task_id": "d98aa508-6da7-4c5d-8e18-fd76b9184490", - "message_id": "63535bbb2b3445e78152cb9bc8d5b185", + "task_id": "cfe13578-8114-4f29-94c0-2f212258b1de", + "message_id": "6c15caada7af483f8f0d9f87a2553cec", "agent_name": "Claude Code", "agent_version": "1.0.0", "agent_model": "anthropic/claude-sonnet-5-5", - "started_at": "2026-11-23T22:10:57.789981Z", + "started_at": "2026-11-24T16:18:58.166723Z", "inbound": [ "Read notes.txt with your tools and reply with only its second line." ], @@ -1037,7 +1047,7 @@ "final": [ "beta" ], - "ended_at": "2026-11-23T22:10:59.958835Z", + "ended_at": "2026-11-24T16:19:00.516238Z", "data": [ { "data": { @@ -1051,7 +1061,7 @@ "type": "system", "subtype": "init", "cwd": "/app", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", "tools": [ "Task", "Bash", @@ -1206,7 +1216,7 @@ ], "analytics_disabled": true, "product_feedback_disabled": true, - "uuid": "2e434bd4-5ee2-4bec-94ed-219c8f33ab0d", + "uuid": "6afba80c-f8eb-4ac1-9a9f-ed1b0c1f4f5c", "memory_paths": { "auto": "/home/agent/.claude/projects/-app/memory/" }, @@ -1224,13 +1234,13 @@ "type": "assistant", "message": { "model": "claude-sonnet-5-5", - "id": "msg_vrtx_011ChLdFMoNGHtK9Y4GciRAT", + "id": "msg_vrtx_011ChN4DTfwTdX9AByLhH4SQ", "type": "message", "role": "assistant", "content": [ { "type": "tool_use", - "id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "id": "toolu_vrtx_018qXuMNxTjZ49fouyUngguP", "name": "Read", "input": { "file_path": "/app/notes.txt" @@ -1243,10 +1253,10 @@ "stop_details": null, "usage": { "input_tokens": 2, - "cache_creation_input_tokens": 4315, + "cache_creation_input_tokens": 4350, "cache_read_input_tokens": 25110, "cache_creation": { - "ephemeral_5m_input_tokens": 4315, + "ephemeral_5m_input_tokens": 4350, "ephemeral_1h_input_tokens": 0 }, "output_tokens": 16, @@ -1255,10 +1265,10 @@ "context_management": null }, "parent_tool_use_id": null, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "4fa57f9a-b975-4129-8b8c-2ece6558e234", - "timestamp": "2026-11-23T22:10:59.101Z", - "request_id": "req_vrtx_011ChLdFMmdXvdzY8N8dheFY" + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "9c62e59f-ddab-419b-9feb-9048f4dee74e", + "timestamp": "2026-11-24T16:18:59.557Z", + "request_id": "req_vrtx_011ChN4DTeTCKpQJiEgAGcUY" }, { "type": "user", @@ -1266,16 +1276,16 @@ "role": "user", "content": [ { - "tool_use_id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "tool_use_id": "toolu_vrtx_018qXuMNxTjZ49fouyUngguP", "type": "tool_result", "content": "1\talpha\n2\tbeta\n3\tgamma\n4\t" } ] }, "parent_tool_use_id": null, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "06ab904f-aedd-4a29-8401-b89222982527", - "timestamp": "2026-11-23T22:10:59.121Z", + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "5b63a45e-bd40-4b0d-afd0-e86280c1fc7c", + "timestamp": "2026-11-24T16:18:59.575Z", "tool_use_result": { "type": "text", "file": { @@ -1288,7 +1298,7 @@ }, "tool_result_meta": [ { - "id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "id": "toolu_vrtx_018qXuMNxTjZ49fouyUngguP", "permission_decision": { "decision": "accept", "source": "config", @@ -1301,7 +1311,7 @@ "type": "assistant", "message": { "model": "claude-sonnet-5-5", - "id": "msg_vrtx_011ChLdFSHz5S9c3j3zQAwV1", + "id": "msg_vrtx_011ChN4DYXtmuorV6yJtRp5i", "type": "message", "role": "assistant", "content": [ @@ -1317,7 +1327,7 @@ "usage": { "input_tokens": 2, "cache_creation_input_tokens": 79, - "cache_read_input_tokens": 29425, + "cache_read_input_tokens": 29460, "cache_creation": { "ephemeral_5m_input_tokens": 79, "ephemeral_1h_input_tokens": 0 @@ -1328,20 +1338,20 @@ "context_management": null }, "parent_tool_use_id": null, - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "uuid": "40b09b05-3260-4453-8b2d-148983651a34", - "timestamp": "2026-11-23T22:10:59.930Z", - "request_id": "req_vrtx_011ChLdFSFkTmSv8gA3dVZgs" + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "uuid": "358a4421-aae7-4b3f-b88a-fc7de6fcfe55", + "timestamp": "2026-11-24T16:19:00.493Z", + "request_id": "req_vrtx_011ChN4DYWQdk9uwhxjg2RRX" }, { - "duration_api_ms": 9722, + "duration_api_ms": 10188, "stop_reason": "end_turn", - "session_id": "157c8db2-a73b-4404-9413-836b695e1757", - "total_cost_usd": 0.10663790000000001, + "session_id": "be7b16da-08d9-4cb5-b992-aab353b9ffa0", + "total_cost_usd": 0.10728889999999998, "usage": { "input_tokens": 4, - "cache_creation_input_tokens": 4394, - "cache_read_input_tokens": 54535, + "cache_creation_input_tokens": 4429, + "cache_read_input_tokens": 54570, "output_tokens": 59, "output_tokens_details": { "thinking_tokens": 0 @@ -1353,7 +1363,7 @@ "service_tier": "standard", "cache_creation": { "ephemeral_1h_input_tokens": 0, - "ephemeral_5m_input_tokens": 4394 + "ephemeral_5m_input_tokens": 4429 }, "inference_geo": "", "iterations": [], @@ -1363,14 +1373,14 @@ "modelUsage": { "anthropic/claude-sonnet-5-5": { "inputTokens": 2019, - "outputTokens": 862, + "outputTokens": 918, "thinkingTokens": 0, - "cacheReadInputTokens": 111549, - "cacheCreationInputTokens": 33130, - "cacheCreationEphemeral5mInputTokens": 33130, + "cacheReadInputTokens": 111584, + "cacheCreationInputTokens": 33165, + "cacheCreationEphemeral5mInputTokens": 33165, "cacheCreationEphemeral1hInputTokens": 0, "webSearchRequests": 0, - "costUSD": 0.10663790000000001, + "costUSD": 0.10728889999999998, "contextWindow": 1000000, "maxOutputTokens": 128000, "canonicalModel": "claude-sonnet-5-5", @@ -1412,27 +1422,27 @@ "subtype": "success", "api_error_status": null, "result": "beta", - "ttft_ms": 1085, + "ttft_ms": 1173, "type": "result", - "duration_ms": 1919, - "uuid": "178b1ebc-e272-4a85-a1ec-6a4397991a7d", - "ttft_stream_ms": 927, - "time_to_request_ms": 55, - "first_content_frame_ms": 927, + "duration_ms": 2113, + "uuid": "dfd31164-a451-41a0-b5e8-f996695ac821", + "ttft_stream_ms": 1011, + "time_to_request_ms": 54, + "first_content_frame_ms": 1011, "queued_turn_count": 0, "result_index": 0, "model_usage_since_last_result": { "anthropic/claude-sonnet-5-5": { "inputTokens": 4, "outputTokens": 59, - "cacheReadInputTokens": 54535, - "cacheCreationInputTokens": 4394, + "cacheReadInputTokens": 54570, + "cacheCreationInputTokens": 4429, "webSearchRequests": 0, - "costUSD": 0.0170365, + "costUSD": 0.0171275, "contextWindow": 1000000, "maxOutputTokens": 128000, "thinkingTokens": 0, - "cacheCreationEphemeral5mInputTokens": 4394, + "cacheCreationEphemeral5mInputTokens": 4429, "cacheCreationEphemeral1hInputTokens": 0, "canonicalModel": "claude-sonnet-5-5", "provider": "firstParty", @@ -1446,8 +1456,8 @@ "name": "session", "record": { "type": "user", - "uuid": "c761d67d-0f17-453f-af10-185255d4c314", - "timestamp": "2026-11-23T22:10:58.029Z", + "uuid": "24733d07-486e-4b57-b42f-8bf8a1d7d9cf", + "timestamp": "2026-11-24T16:18:58.397Z", "isSidechain": false, "message": {} }, @@ -1457,15 +1467,15 @@ "name": "session", "record": { "type": "assistant", - "uuid": "4fa57f9a-b975-4129-8b8c-2ece6558e234", - "timestamp": "2026-11-23T22:10:59.101Z", + "uuid": "9c62e59f-ddab-419b-9feb-9048f4dee74e", + "timestamp": "2026-11-24T16:18:59.557Z", "isSidechain": false, "message": { - "id": "msg_vrtx_011ChLdFMoNGHtK9Y4GciRAT", + "id": "msg_vrtx_011ChN4DTfwTdX9AByLhH4SQ", "model": "claude-sonnet-5-5", "usage": { "input_tokens": 2, - "cache_creation_input_tokens": 4315, + "cache_creation_input_tokens": 4350, "cache_read_input_tokens": 25110, "output_tokens": 55, "output_tokens_details": { @@ -1478,7 +1488,7 @@ "service_tier": "standard", "cache_creation": { "ephemeral_1h_input_tokens": 0, - "ephemeral_5m_input_tokens": 4315 + "ephemeral_5m_input_tokens": 4350 }, "inference_geo": "", "iterations": [], @@ -1494,8 +1504,8 @@ "name": "session", "record": { "type": "user", - "uuid": "06ab904f-aedd-4a29-8401-b89222982527", - "timestamp": "2026-11-23T22:10:59.121Z", + "uuid": "5b63a45e-bd40-4b0d-afd0-e86280c1fc7c", + "timestamp": "2026-11-24T16:18:59.575Z", "isSidechain": false, "message": {} }, @@ -1505,16 +1515,16 @@ "name": "session", "record": { "type": "assistant", - "uuid": "40b09b05-3260-4453-8b2d-148983651a34", - "timestamp": "2026-11-23T22:10:59.930Z", + "uuid": "358a4421-aae7-4b3f-b88a-fc7de6fcfe55", + "timestamp": "2026-11-24T16:19:00.493Z", "isSidechain": false, "message": { - "id": "msg_vrtx_011ChLdFSHz5S9c3j3zQAwV1", + "id": "msg_vrtx_011ChN4DYXtmuorV6yJtRp5i", "model": "claude-sonnet-5-5", "usage": { "input_tokens": 2, "cache_creation_input_tokens": 79, - "cache_read_input_tokens": 29425, + "cache_read_input_tokens": 29460, "output_tokens": 4, "output_tokens_details": { "thinking_tokens": 0 @@ -1542,34 +1552,39 @@ "name": "turn", "record": { "type": "turn", - "cost_usd": 0.01703650000000001 + "cost_usd": 0.01712749999999999, + "input_tokens": 4, + "output_tokens": 59, + "cache_read_tokens": 54570, + "cache_write_tokens": 4429, + "model": "anthropic/claude-sonnet-5-5" }, "after": 5 } ], "usage": { "tool_call_count": 1, - "input_tokens": 58933, + "input_tokens": 59003, "output_tokens": 59, - "total_tokens": 58992, - "cache_read_tokens": 54535, - "cache_write_tokens": 4394, + "total_tokens": 59062, + "cache_read_tokens": 54570, + "cache_write_tokens": 4429, "input_includes_cache": true, - "cost_usd": 0.01703650000000001, + "cost_usd": 0.01712749999999999, "models": [ { "model": "anthropic/claude-sonnet-5-5", - "input_tokens": 58933, + "input_tokens": 59003, "output_tokens": 59, - "cache_read_tokens": 54535, - "cache_write_tokens": 4394, + "cache_read_tokens": 54570, + "cache_write_tokens": 4429, "input_includes_cache": true, - "cost_usd": 0.01703650000000001 + "cost_usd": 0.01712749999999999 } ], "provider_details": { "cache_creation": { - "ephemeral_5m_input_tokens": 4394, + "ephemeral_5m_input_tokens": 4429, "ephemeral_1h_input_tokens": 0 } } diff --git a/tst/data/verifier_golden/judge_inputs.json b/tst/data/verifier_golden/judge_inputs.json index d94789bf5..b1f6aeafb 100644 --- a/tst/data/verifier_golden/judge_inputs.json +++ b/tst/data/verifier_golden/judge_inputs.json @@ -1820,7 +1820,7 @@ { "model": "judge-model", "prompt": { - "sha256": "aaa80059a48c5bc5ece33ea5ce54fb16c241fdb2f72e25d455bd7a073f94a058", + "sha256": "40d801b49766d4480f0ddf25ed938cc8a23f602a3b11ad015e470a4b806b4baa", "chars": 5462 }, "images": null, @@ -1850,7 +1850,7 @@ { "model": "judge-model", "prompt": { - "sha256": "920bfc169a3fa0ac487056e7f6df39b2bad5913e0edd4fd3792718197f341039", + "sha256": "21fa9a54c66143ab1b91f7ea9a3e296de081d6673c3d4942efa4b294a7314f51", "chars": 8120 }, "images": null, @@ -1880,7 +1880,7 @@ { "model": "judge-model", "prompt": { - "sha256": "645f63dda7b6c1ff6ccdcb8c6c944afb99d15e9be5b4a8e603ad7a054d7bf287", + "sha256": "72dbf7fa2ec660a524f9fb275829287e33916b325646defd3f968673bef37456", "chars": 27161 }, "images": null, @@ -1895,7 +1895,7 @@ { "model": "judge-model", "prompt": { - "sha256": "dbf833e8bc5b8c6ff351c7d6acf9890aafc6bb8b6c6441b1323b712c1ef4ec2c", + "sha256": "08ff116ff1f18f0bca58cc5cf5d6497538899513483f4c30fd57b6041eba41ad", "chars": 6807 }, "images": [ @@ -1923,7 +1923,7 @@ { "model": "judge-model", "prompt": { - "sha256": "fc4d20b129b2578b564f11edde9825ed9ca65d7d486accdeee4aa43845d8ee4a", + "sha256": "1ef02d0872348b7ab37571c63b52b8baf0da3ddb8ce029a7ad56e68b6f400708", "chars": 6791 }, "images": null, @@ -2000,7 +2000,7 @@ }, "/tmp/prompt_trajectory_turns//turn_01.json": { "text": { - "sha256": "f05cae8d13ffa493013f44b958ea947a1e7d74200dc8b740e8ed59593cb861e4", + "sha256": "459155b7c3251a24f07dd1976dee79415435551ff7a918817a870fd8e7442a65", "chars": 3440 } } @@ -2054,13 +2054,13 @@ "files": { "/tmp/prompt_trajectory_turns//turn_01.json": { "text": { - "sha256": "4c39faba9decd82d3b793558c93f27016152f10753ffb843b0e44ae9ef195e5a", + "sha256": "915ef75b2692cd49442fd5f6775dccf3580184a9de9e3afe44743c4dc39cf67e", "chars": 4670 } }, "/tmp/prompt_trajectory_turns//turn_02.json": { "text": { - "sha256": "fd9b198db1817038df9bcdadf192958d15c3f29287bd82b4d85c7b04e1726ce1", + "sha256": "c42e98ee768d0b4d38c4c48b15251f1a4a7bc8a9fdc194a92ea48a50e03aead4", "chars": 1388 } } @@ -2111,7 +2111,7 @@ }, "/tmp/prompt_trajectory_turns//turn_02.json": { "text": { - "sha256": "fd9b198db1817038df9bcdadf192958d15c3f29287bd82b4d85c7b04e1726ce1", + "sha256": "c42e98ee768d0b4d38c4c48b15251f1a4a7bc8a9fdc194a92ea48a50e03aead4", "chars": 1388 } } @@ -2457,7 +2457,7 @@ }, "extra": { "agentenv": { - "version": "1.0", + "version": "1.1", "native_format": "toy-events/1", "adapter": { "name": "toy-events-atif", diff --git a/tst/manual/claude_code_atif/record.py b/tst/manual/claude_code_atif/record.py index 06078c82f..ccedb6afc 100644 --- a/tst/manual/claude_code_atif/record.py +++ b/tst/manual/claude_code_atif/record.py @@ -64,9 +64,6 @@ def scenarios(thinking_model: str) -> dict[str, dict]: "retried": {"faults": "stall", "env": {"CLAUDE_API_ERROR_RETRIES": "1", "API_TIMEOUT_MS": "15000"}, "prompts": ["Run `echo first` with your Bash tool, then run `echo second` with it, then reply " "with both outputs on one line."]}, - "autocompacted": {"env": {"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "20"}, "prompts": [ - "Create big.txt holding 3000 numbered lines of filler text with one Bash command, print it whole with cat, " - "then reply with only its last line."]}, "compacted": {"prompts": [ "Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.", "/compact", diff --git a/tst/unit/agents/claude_code/test_claude_code_atif.py b/tst/unit/agents/claude_code/test_claude_code_atif.py index 58c86ae8b..e7ceea36d 100644 --- a/tst/unit/agents/claude_code/test_claude_code_atif.py +++ b/tst/unit/agents/claude_code/test_claude_code_atif.py @@ -352,3 +352,54 @@ def test_a_sub_agent_a_later_task_names_by_its_first_call_is_left_to_the_native_ document = run(first, second).document assert [len(sub["steps"]) for sub in document["subagent_trajectories"]] == [2] assert agent_steps(document)[-1]["message"] == "still here" + + +def _compacting_feed(turn_counts=None): + """A turn that compacts partway: a call and its result, the CLI's boundary and its summary, its own message, then a + reply; and the turn's record with ``turn_counts``, when given.""" + first, done = assistant("msg-1", "u1", call("c1")), assistant("msg-2", "u4", text("done")) + answered = user("u2", result("c1")) + summary = {"type": "user", "uuid": "u3", "parent_tool_use_id": None, "session_id": "s", + "message": {"role": "user", "content": "The summary of the conversation so far."}} + notice = {"type": "user", "uuid": "u5", "parent_tool_use_id": None, "session_id": "s", + "message": {"role": "user", "content": "Compacted"}} + feed = Feed().out(first).transcript(first, "2026-11-22T02:01:00.000Z").out(answered) + feed.transcript(answered, "2026-11-22T02:01:01.000Z") + feed.out({"type": "system", "subtype": "compact_boundary", "session_id": "s", "uuid": "b1", + "compact_metadata": {"trigger": "auto", "pre_tokens": 90000, "post_tokens": 3000}}) + feed.out(summary).transcript(summary, "2026-11-22T02:01:02.000Z").out(notice) + feed.transcript(notice, "2026-11-22T02:01:02.500Z").out(done) + feed.transcript(done, "2026-11-22T02:01:03.000Z", usage={**USAGE, "output_tokens": 4}) + if turn_counts is not None: + feed.aux("turn", {"type": "turn", "cost_usd": 0.5, **turn_counts}) + return feed + + +def test_an_auto_compaction_is_the_step_of_its_summary_call_holding_what_the_turn_counted_beyond_its_steps(): + steps_counted = {"input_tokens": 4, "output_tokens": 79, "cache_read_tokens": 136084, "cache_write_tokens": 188} + summary_call = {"input_tokens": 500, "output_tokens": 300, "cache_read_tokens": 1000, "cache_write_tokens": 20} + feed = _compacting_feed({name: steps_counted[name] + summary_call[name] for name in steps_counted}) + kit = run(feed) + user_step, first, compaction, notice, done = kit.document["steps"][:5] + assert (compaction["source"], compaction["message"]) == ("agent", "The summary of the conversation so far.") + assert profile_of(compaction)["compaction"] == {"written_by": "assistant", "trigger": "auto"} + assert compaction["metrics"] == {"prompt_tokens": 500 + 1000 + 20, "cached_tokens": 1000, "completion_tokens": 300, + "extra": {"agentenv": {"cache_write_tokens": 20}}} + assert (notice["source"], notice["message"]) == ("system", "Compacted") + assert done["message"] == "done" and "metrics" in done + # Held for the turn's count, its last record: no live page before it serves the compaction, the one after it does. + counted = len(feed.records) + compactions = [any("compaction" in profile_of(step) for step in (page or {}).get("steps", [])) for page in kit.pages] + assert not any(compactions[:counted]) and compactions[counted] + + +def test_a_compaction_whose_turn_counted_less_than_its_steps_has_no_usage(): + kit = run(_compacting_feed({"input_tokens": 1, "output_tokens": 1, "cache_read_tokens": 1, "cache_write_tokens": 1})) + compaction = next(step for step in kit.document["steps"] if "compaction" in profile_of(step)) + assert "metrics" not in compaction and compaction["llm_call_count"] == 1 + + +def test_a_compaction_whose_turn_never_reported_is_written_as_its_task_ends(): + kit = run(_compacting_feed()) + sources = [(step["source"], "compaction" in profile_of(step)) for step in kit.document["steps"]] + assert sources[2:5] == [("agent", True), ("system", False), ("agent", False)] diff --git a/tst/unit/agents/claude_code/test_session_tail.py b/tst/unit/agents/claude_code/test_session_tail.py index 34ba68c4d..75f486f83 100644 --- a/tst/unit/agents/claude_code/test_session_tail.py +++ b/tst/unit/agents/claude_code/test_session_tail.py @@ -184,14 +184,15 @@ def test_a_task_that_builds_no_atif_copy_feeds_nothing_beside_stdout(turns, clie assert "aux_callback" not in turns[0] and "tool_shapes" not in turns[0] -def test_a_task_that_builds_an_atif_copy_is_fed_its_records_and_the_turns_cost(turns, client): +def test_a_task_that_builds_an_atif_copy_is_fed_its_records_and_the_turns_cost_and_counts(turns, client): client.post("/ext/trajectory/prescribe", json={"formats": ["atif/1"]}).raise_for_status() task = send(client, "hello", context_id="ctx-a") assert terminal(task)[0] == "completed" assert callable(turns[0]["aux_callback"]) and turns[0]["tool_shapes"] == set() read = client.post("/ext/trajectory", json={"task_id": task["id"], "format": "atif/1"}).json() - assert {"name": "turn", "record": {"type": "turn", "cost_usd": 0.25}} in [ - {key: entry[key] for key in ("name", "record")} for entry in read["aux"]] + [turn] = [entry["record"] for entry in read["aux"] if entry["name"] == "turn"] + assert turn["cost_usd"] == 0.25 + assert {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"} <= set(turn) assert read["trajectory"]["final_metrics"]["total_cost_usd"] == 0.25 diff --git a/tst/unit/agents/claude_code/test_usage.py b/tst/unit/agents/claude_code/test_usage.py index 2ffb08cd5..c2c957890 100644 --- a/tst/unit/agents/claude_code/test_usage.py +++ b/tst/unit/agents/claude_code/test_usage.py @@ -7,6 +7,7 @@ ``modelUsage`` starts from the session's tally so far, which the CLI restores, so a turn's own tally is the difference.""" import asyncio +from dataclasses import replace import pytest from agentenv_protocol.a2a_agent import ModelUsage, Usage @@ -237,3 +238,17 @@ async def hung(*cmd, printed=printed, **kwargs): after, before = results assert after.error and (after.run_usage, after.model_usage, after.unreported_calls) == (RESULTS_2, TALLY_2, 0) assert before.error and (before.run_usage, before.unreported_calls) == ([], 1) + + +def test_the_atif_turn_record_counts_the_turn_apart_from_its_cache_and_not_at_all_when_its_a_lower_bound(): + """What the atif/1 adapter gives a compaction's step from: the turn's counts as a session record counts a call's.""" + counted = Usage(input_tokens=1000, output_tokens=50, cache_read_tokens=600, cache_write_tokens=100, + input_includes_cache=True, cost_usd=0.2, models=(ModelUsage(model=HAIKU),)) + assert a2a_server._turn_record(counted) == { + "type": "turn", "cost_usd": 0.2, "input_tokens": 300, "output_tokens": 50, "cache_read_tokens": 600, + "cache_write_tokens": 100, "model": HAIKU} + two_models = replace(counted, models=(ModelUsage(model=HAIKU), ModelUsage(model="claude-sonnet-5-5"))) + assert "model" not in a2a_server._turn_record(two_models) + lower_bound = replace(counted, provider_details={"unreported_calls": 2}) + assert a2a_server._turn_record(lower_bound) == {"type": "turn", "cost_usd": 0.2} + diff --git a/tst/unit/task_step/test_prompt_agent_atif_copies.py b/tst/unit/task_step/test_prompt_agent_atif_copies.py index 5541fdd83..10b70036a 100644 --- a/tst/unit/task_step/test_prompt_agent_atif_copies.py +++ b/tst/unit/task_step/test_prompt_agent_atif_copies.py @@ -317,7 +317,7 @@ def stray_key(answer: dict) -> dict: @pytest.mark.asyncio -@pytest.mark.parametrize("field, version", [("schema_version", "ATIF-v1.9"), ("profile", "1.1")]) +@pytest.mark.parametrize("field, version", [("schema_version", "ATIF-v1.9"), ("profile", "1.2")]) async def test_a_copy_newer_than_the_worker_is_stored_and_recorded_newer(monkeypatch, tmp_path, field, version): run = _Run(monkeypatch, tmp_path) From dd5ac389d6607680cf4566e79f6c5f02e8221225 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 08:29:39 -0800 Subject: [PATCH 4/7] docs(protocol): an adapter writes the harness's own messages and a compaction's step Co-Authored-By: Claude Opus 5.5 --- packages/agentenv-protocol/README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 5349204d5..60ebbd600 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -1366,7 +1366,11 @@ the profile's spec, and `fixtures/` holds its canonical examples. The package ne with the cache included, stores media at `media/.`, embeds sub-agents and normalizes timestamps. A record no method takes is counted in the root profile. `turn.tool_definitions([...], agent=None)` writes the tools the model was offered, in OpenAI's function form, to a trajectory's `agent.tool_definitions`; a later call adds - tools and replaces those of the same name. + tools and replaces those of the same name. A message the harness itself put in the conversation, such as a + command's output, is `turn.system_message(text=...)`, a `source: system` step of its own. A compaction, a summary + that replaced the conversation in what the agent sees, is the message of the step of the call that wrote it, + marked by `turn.compaction(step=..., written_by="assistant" | "harness", trigger="manual" | "auto")`, its usage + that call's (profile 1.1). - **The runner** (`AdapterRun`, `replay`) feeds one A2A context's records through one adapter instance, a task at a time. It writes each task's user step from its `TurnContext`, and the final response once, with the task's terminal state on its last step. Its `page()` is the live view, built when it's read: closed steps only, so a From e7e2610333d7248dfbce47c04321a0dd45fcba65 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 08:40:14 -0800 Subject: [PATCH 5/7] fix(agents): a compaction takes the turn's remainder only when it's the one summary and every other call was counted Two compactions in one turn each took the whole remainder, so the copy's totals exceeded the turn's; and a call whose transcript record never came counted as nothing, so its tokens went to the summary. A compaction now takes the remainder only when it's the turn's one held summary and every other model call of the turn has its counts, and none otherwise. Co-Authored-By: Claude Opus 5.5 --- .../agents/claude-code/claude_code_atif.py | 27 ++++++++++---- .../claude_code/test_claude_code_atif.py | 37 +++++++++++++++++++ 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/claude_code_atif.py b/src/agent_env/agents/agents/claude-code/claude_code_atif.py index 47783f4a1..4433bf183 100644 --- a/src/agent_env/agents/agents/claude-code/claude_code_atif.py +++ b/src/agent_env/agents/agents/claude-code/claude_code_atif.py @@ -101,6 +101,8 @@ def __init__(self, turn: Any) -> None: self._summary_next = False self._summary_trigger: str | None = None self._task_counts: dict[str, int] = {} + #: The task's model calls written so far, by step key: those not in ``_stamped`` have no counts yet. + self._task_calls: set[str] = set() # Records @@ -180,10 +182,11 @@ def cost(self, record: dict[str, Any], turn: Any) -> None: cost = record.get("cost_usd") if isinstance(cost, (int, float)) and not isinstance(cost, bool): turn.task_cost(float(cost), source="harness") - for entry in self._queue: - if entry.held: - entry.usage, entry.held = self._left_over(record), False - entry.model = record.get("model") if isinstance(record.get("model"), str) else None + held = [entry for entry in self._queue if entry.held] + left = self._left_over(record) if len(held) == 1 else None + for entry in held: + entry.usage, entry.held = left, False + entry.model = record.get("model") if isinstance(record.get("model"), str) else None self._flush(turn) @finish @@ -199,6 +202,7 @@ def end(self, turn: Any) -> None: self._attempt_step = None self._summary_next = False self._task_counts = {} + self._task_calls = set() self._task += 1 # The queue: records in the order they came, each written once its session record is in @@ -304,6 +308,7 @@ def _assistant(self, record: dict[str, Any], session: dict[str, Any] | None, age text = "".join(b.get("text", "") for b in _blocks(record) if b.get("type") == "text") turn.error(message=text or "the CLI reported an error", kind="infra_error", step=key, agent=agent) elif key not in self._stamped: + self._task_calls.add(key) usage = self._usage(session) if usage is not None: self._stamped.add(key) @@ -352,17 +357,23 @@ def _user(self, entry: _Entry, session: dict[str, Any] | None, turn: Any) -> Non turn.system_message(text=text, time=when) def _left_over(self, record: dict[str, Any]) -> dict[str, int] | None: - """What the turn reported beyond its steps written or still queued: the call no session record counts, the - summary's. None when the turn gave no counts, or counted less than its steps, a lower bound.""" + """What the turn reported beyond its model calls written or still queued: the one call no session record + counts, the summary's. None when the turn gave no counts, counted less than its calls (a lower bound), or one of + its calls has no counts, whose tokens the remainder would hold too.""" reported = {name: record.get(name) for name in _COUNTS} if not all(isinstance(value, int) and not isinstance(value, bool) for value in reported.values()): return None + if self._task_calls - self._stamped: + return None counted, seen = dict(self._task_counts), set(self._stamped) for queued in self._queue: key = _message_key(queued.record) if queued.record.get("type") == "assistant" else None - usage = self._usage(self._session.get(queued.uuid)) if queued.uuid is not None else None - if key is None or key in seen or usage is None: + message = queued.record.get("message") if _is_mapping(queued.record.get("message")) else {} + if key is None or key in seen or message.get("model") == _SYNTHETIC_MODEL: continue + usage = self._usage(self._session.get(queued.uuid)) if queued.uuid is not None else None + if usage is None: + return None seen.add(key) for name, value in usage.items(): counted[name] = counted.get(name, 0) + value diff --git a/tst/unit/agents/claude_code/test_claude_code_atif.py b/tst/unit/agents/claude_code/test_claude_code_atif.py index e7ceea36d..45b34ae31 100644 --- a/tst/unit/agents/claude_code/test_claude_code_atif.py +++ b/tst/unit/agents/claude_code/test_claude_code_atif.py @@ -403,3 +403,40 @@ def test_a_compaction_whose_turn_never_reported_is_written_as_its_task_ends(): kit = run(_compacting_feed()) sources = [(step["source"], "compaction" in profile_of(step)) for step in kit.document["steps"]] assert sources[2:5] == [("agent", True), ("system", False), ("agent", False)] + + +def _summary(uuid, text_value): + return {"type": "user", "uuid": uuid, "parent_tool_use_id": None, "session_id": "s", + "message": {"role": "user", "content": text_value}} + + +def _boundary(uuid): + return {"type": "system", "subtype": "compact_boundary", "session_id": "s", "uuid": uuid, + "compact_metadata": {"trigger": "auto"}} + + +COUNTED_TURN = {"type": "turn", "cost_usd": 0.5, "input_tokens": 9000, "output_tokens": 900, + "cache_read_tokens": 200000, "cache_write_tokens": 2000} + + +def test_two_compactions_in_one_turn_have_no_usage_since_the_turns_remainder_cant_be_split_between_them(): + first, done = assistant("msg-1", "u1", text("working")), assistant("msg-2", "u6", text("done")) + one, two = _summary("u3", "The first summary."), _summary("u5", "The second summary.") + feed = Feed().out(first).transcript(first, "2026-11-22T02:01:00.000Z").out(_boundary("b1")).out(one) + feed.transcript(one, "2026-11-22T02:01:01.000Z").out(_boundary("b2")).out(two) + feed.transcript(two, "2026-11-22T02:01:02.000Z").out(done).transcript(done, "2026-11-22T02:01:03.000Z") + kit = run(feed.aux("turn", COUNTED_TURN)) + compactions = [step for step in kit.document["steps"] if "compaction" in profile_of(step)] + assert [step["message"] for step in compactions] == ["The first summary.", "The second summary."] + assert all("metrics" not in step for step in compactions) + + +def test_a_compaction_has_no_usage_when_one_of_its_turns_calls_lacks_its_counts(): + """A call whose transcript record never came has no counts, which the turn's remainder would hold too.""" + uncounted, done = assistant("msg-1", "u1", text("working")), assistant("msg-2", "u4", text("done")) + summary = _summary("u3", "The summary.") + feed = Feed().out(uncounted).out(_boundary("b1")).out(summary).transcript(summary, "2026-11-22T02:01:01.000Z") + feed.out(done).transcript(done, "2026-11-22T02:01:03.000Z") + kit = run(feed.aux("turn", COUNTED_TURN)) + [compaction] = [step for step in kit.document["steps"] if "compaction" in profile_of(step)] + assert "metrics" not in compaction and compaction["message"] == "The summary." From f26c174a1f7fd60a53bb1d3d8211ce0f73ea6cff Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 10:12:05 -0800 Subject: [PATCH 6/7] fix(agents): Claude Code's compaction step names its model as the agent's own calls do The turn's tally keys a model by the name it was called as, which a gateway route prefixes, while every other step names it as the API answered. The compaction step now takes the root agent's latest model, and the turn's only when no root call named one. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/claude-code/claude_code_atif.py | 6 +++++- tst/data/claude_code_atif/compacted.expected.json | 2 +- tst/unit/agents/claude_code/test_claude_code_atif.py | 12 ++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/claude_code_atif.py b/src/agent_env/agents/agents/claude-code/claude_code_atif.py index 4433bf183..90f0e7bf5 100644 --- a/src/agent_env/agents/agents/claude-code/claude_code_atif.py +++ b/src/agent_env/agents/agents/claude-code/claude_code_atif.py @@ -101,6 +101,8 @@ def __init__(self, turn: Any) -> None: self._summary_next = False self._summary_trigger: str | None = None self._task_counts: dict[str, int] = {} + #: The model the root agent's latest call named, as the API answered: a compaction's summary call is its call too. + self._root_model: str | None = None #: The task's model calls written so far, by step key: those not in ``_stamped`` have no counts yet. self._task_calls: set[str] = set() @@ -317,6 +319,8 @@ def _assistant(self, record: dict[str, Any], session: dict[str, Any] | None, age turn.step(key=key, model_name=model, time=when, agent=agent, **(usage or {})) if agent is None: self._attempt_step = key + if model is not None and not synthetic: + self._root_model = model def _block(self, block: dict[str, Any], key: str, agent: str | None, when: Any, turn: Any) -> None: kind = block.get("type") @@ -351,7 +355,7 @@ def _user(self, entry: _Entry, session: dict[str, Any] | None, turn: Any) -> Non key = f"compaction-{entry.uuid or entry.seq}" turn.message(step=key, text=text, time=when) turn.compaction(step=key, written_by="assistant", trigger=entry.trigger) - turn.step(key=key, model_name=entry.model, time=when, **(entry.usage or {})) + turn.step(key=key, model_name=self._root_model or entry.model, time=when, **(entry.usage or {})) entry.summary = False else: turn.system_message(text=text, time=when) diff --git a/tst/data/claude_code_atif/compacted.expected.json b/tst/data/claude_code_atif/compacted.expected.json index 5286105ca..318abecf3 100644 --- a/tst/data/claude_code_atif/compacted.expected.json +++ b/tst/data/claude_code_atif/compacted.expected.json @@ -101,7 +101,7 @@ "step_id": 5, "timestamp": "2026-11-24T16:18:57.853Z", "source": "agent", - "model_name": "anthropic/claude-sonnet-5-5", + "model_name": "claude-sonnet-5-5", "message": "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\n\nBash\n\nSummary:\n1. Primary Request and Intent:\n The user asked me to create notes.txt holding three lines, alpha, beta and gamma, with the Bash tool, and then reply with only \"ok\".\n\n2. Key Technical Concepts:\n - Bash `printf` for writing multi-line file content.\n - Working directory is /app, which is not a git repository.\n - A system-reminder set attribution lines for future git commits and PRs. It has not been used, because no git operations were requested.\n\n3. Files and Code Sections:\n - /app/notes.txt (created)\n - It is the file the user asked for.\n - Command used: `printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt`\n - Intended contents:\n ```\n alpha\n beta\n gamma\n ```\n\n4. Errors and fixes:\n - None. The command completed with no output and no errors. I did not run a separate check of the file contents.\n\n5. Problem Solving:\n The task was simple and was solved with a single Bash command.\n\n6. All user messages:\n - \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n - A later message asked for a text-only summary of the conversation, with no tool calls.\n\n7. Pending Tasks:\n - Send the final reply to the original request, which must be only \"ok\".\n\n8. Current Work:\n I had just created /app/notes.txt with the Bash tool. The only step left from the user's request is the one-word reply.\n\n9. Optional Next Step:\n Reply with only \"ok\", as the user asked: \"then reply with only ok.\"\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/agent/.claude/projects/-app/be7b16da-08d9-4cb5-b992-aab353b9ffa0.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened.\n\nThe messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them.", "metrics": { "prompt_tokens": 30626, diff --git a/tst/unit/agents/claude_code/test_claude_code_atif.py b/tst/unit/agents/claude_code/test_claude_code_atif.py index 45b34ae31..d6487d8c7 100644 --- a/tst/unit/agents/claude_code/test_claude_code_atif.py +++ b/tst/unit/agents/claude_code/test_claude_code_atif.py @@ -431,6 +431,18 @@ def test_two_compactions_in_one_turn_have_no_usage_since_the_turns_remainder_can assert all("metrics" not in step for step in compactions) +def test_a_compaction_names_its_model_as_the_agents_own_calls_do_else_as_the_turn_counted_it(): + """The turn's tally keys a model by the name it was called as; the agent's steps name it as the API answered.""" + counted = {**COUNTED_TURN, "model": "gateway/" + MODEL} + after_a_call = run(_compacting_feed({name: value for name, value in counted.items() if name != "type"})) + summary = _summary("u3", "The summary.") + alone = run(Feed().out(_boundary("b1")).out(summary).transcript(summary, "2026-11-22T02:01:01.000Z") + .aux("turn", counted)) + named = [next(step for step in kit.document["steps"] if "compaction" in profile_of(step))["model_name"] + for kit in (after_a_call, alone)] + assert named == [MODEL, "gateway/" + MODEL] + + def test_a_compaction_has_no_usage_when_one_of_its_turns_calls_lacks_its_counts(): """A call whose transcript record never came has no counts, which the turn's remainder would hold too.""" uncounted, done = assistant("msg-1", "u1", text("working")), assistant("msg-2", "u4", text("done")) From e912b96f6926920080d696a97dac7da29109d094 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 10:16:25 -0800 Subject: [PATCH 7/7] fix(agents): a compaction after a model change names the model its turn called The compaction took the root agent's last model across turns, so a /compact-only turn after a model change named the one before. Each turn's count now records how the model it was called as answered, and a compaction is named that way, or as called when no call of that model has answered yet. Co-Authored-By: Claude Opus 5.5 --- .../agents/claude-code/claude_code_atif.py | 18 ++++++--- .../claude_code/test_claude_code_atif.py | 37 ++++++++++++++----- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/claude_code_atif.py b/src/agent_env/agents/agents/claude-code/claude_code_atif.py index 90f0e7bf5..ff9ccaeea 100644 --- a/src/agent_env/agents/agents/claude-code/claude_code_atif.py +++ b/src/agent_env/agents/agents/claude-code/claude_code_atif.py @@ -101,8 +101,10 @@ def __init__(self, turn: Any) -> None: self._summary_next = False self._summary_trigger: str | None = None self._task_counts: dict[str, int] = {} - #: The model the root agent's latest call named, as the API answered: a compaction's summary call is its call too. - self._root_model: str | None = None + #: The model the task's latest root call named, as the API answered, and each model the turn's tally named as + #: called (a gateway route prefixes it) by the name its calls answered as: a compaction is named as they are. + self._task_model: str | None = None + self._answered_as: dict[str, str] = {} #: The task's model calls written so far, by step key: those not in ``_stamped`` have no counts yet. self._task_calls: set[str] = set() @@ -186,9 +188,12 @@ def cost(self, record: dict[str, Any], turn: Any) -> None: turn.task_cost(float(cost), source="harness") held = [entry for entry in self._queue if entry.held] left = self._left_over(record) if len(held) == 1 else None + called = record.get("model") if isinstance(record.get("model"), str) else None + if called is not None and self._task_model is not None: + self._answered_as[called] = self._task_model + model = self._answered_as.get(called, called) if called is not None else self._task_model for entry in held: - entry.usage, entry.held = left, False - entry.model = record.get("model") if isinstance(record.get("model"), str) else None + entry.usage, entry.held, entry.model = left, False, model self._flush(turn) @finish @@ -203,6 +208,7 @@ def end(self, turn: Any) -> None: self._inits = 0 self._attempt_step = None self._summary_next = False + self._task_model = None self._task_counts = {} self._task_calls = set() self._task += 1 @@ -320,7 +326,7 @@ def _assistant(self, record: dict[str, Any], session: dict[str, Any] | None, age if agent is None: self._attempt_step = key if model is not None and not synthetic: - self._root_model = model + self._task_model = model def _block(self, block: dict[str, Any], key: str, agent: str | None, when: Any, turn: Any) -> None: kind = block.get("type") @@ -355,7 +361,7 @@ def _user(self, entry: _Entry, session: dict[str, Any] | None, turn: Any) -> Non key = f"compaction-{entry.uuid or entry.seq}" turn.message(step=key, text=text, time=when) turn.compaction(step=key, written_by="assistant", trigger=entry.trigger) - turn.step(key=key, model_name=self._root_model or entry.model, time=when, **(entry.usage or {})) + turn.step(key=key, model_name=entry.model, time=when, **(entry.usage or {})) entry.summary = False else: turn.system_message(text=text, time=when) diff --git a/tst/unit/agents/claude_code/test_claude_code_atif.py b/tst/unit/agents/claude_code/test_claude_code_atif.py index d6487d8c7..ca950c60c 100644 --- a/tst/unit/agents/claude_code/test_claude_code_atif.py +++ b/tst/unit/agents/claude_code/test_claude_code_atif.py @@ -431,16 +431,33 @@ def test_two_compactions_in_one_turn_have_no_usage_since_the_turns_remainder_can assert all("metrics" not in step for step in compactions) -def test_a_compaction_names_its_model_as_the_agents_own_calls_do_else_as_the_turn_counted_it(): - """The turn's tally keys a model by the name it was called as; the agent's steps name it as the API answered.""" - counted = {**COUNTED_TURN, "model": "gateway/" + MODEL} - after_a_call = run(_compacting_feed({name: value for name, value in counted.items() if name != "type"})) - summary = _summary("u3", "The summary.") - alone = run(Feed().out(_boundary("b1")).out(summary).transcript(summary, "2026-11-22T02:01:01.000Z") - .aux("turn", counted)) - named = [next(step for step in kit.document["steps"] if "compaction" in profile_of(step))["model_name"] - for kit in (after_a_call, alone)] - assert named == [MODEL, "gateway/" + MODEL] +def _named(kit): + return next(step for step in kit.document["steps"] if "compaction" in profile_of(step))["model_name"] + + +def _compacting_only(called): + summary = _summary("u9", "The summary.") + feed = Feed().out(_boundary("b9")).out(summary).transcript(summary, "2026-11-22T02:02:01.000Z") + return feed.aux("turn", {**COUNTED_TURN, "model": called}) + + +def test_a_compaction_names_its_model_as_the_agents_calls_answered_it_and_never_names_another(): + """The turn's tally keys a model by the name it was called as, a gateway's route prefixing it; the agent's steps + name it as the API answered. A compaction is named as its model's calls answered, or as called when none has.""" + called = "gateway/" + MODEL + mid_turn = run(_compacting_feed({name: value for name, value in {**COUNTED_TURN, "model": called}.items() + if name != "type"})) + working = assistant("msg-1", "u1", text("working")) + earlier = Feed().out(working).transcript(working, "2026-11-22T02:01:00.000Z") + earlier.aux("turn", {**COUNTED_TURN, "model": called}) + same_model = run(earlier, _compacting_only(called)) + working = assistant("msg-1", "u1", text("working")) + earlier = Feed().out(working).transcript(working, "2026-11-22T02:01:00.000Z") + earlier.aux("turn", {**COUNTED_TURN, "model": called}) + another_model = run(earlier, _compacting_only("gateway/another-model")) + alone = run(_compacting_only(called)) + assert [_named(kit) for kit in (mid_turn, same_model, another_model, alone)] == [ + MODEL, MODEL, "gateway/another-model", called] def test_a_compaction_has_no_usage_when_one_of_its_turns_calls_lacks_its_counts():