Skip to content

The agent that grows with you

ci: RUF007

Maciej Lisiewski4ee5e8e0f31c
diff --git a/agent/insights.py b/agent/insights.py
index f48665c582e..d540d303fe1 100644
--- a/agent/insights.py
+++ b/agent/insights.py
@@ -12,6 +12,7 @@ from typing import Any, Dict, List, Optional
from agent.usage_pricing import CanonicalUsage, estimate_usage_cost, format_cost_label, format_duration_compact, has_known_pricing
from hermes_cli.timefmt import coerce_epoch
from hermes_time import safe_strftime
+import itertools
_TOKEN_KEYS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens")
_SKILL_TOOLS = {"skill_view", "skill_manage"}
@@ -427,7 +428,7 @@ class InsightsEngine:
if daily_counts:
dates = [datetime.strptime(d, "%Y-%m-%d") for d in sorted(daily_counts)]
current_streak = max_streak = 1
- for prev, cur in zip(dates, dates[1:]):
+ for prev, cur in itertools.pairwise(dates):
current_streak = current_streak + 1 if (cur - prev).days == 1 else 1
max_streak = max(max_streak, current_streak)
return {"by_day": day_breakdown, "by_hour": hour_breakdown, "busiest_day": max(day_breakdown, key=lambda x: x["count"]),
diff --git a/agent/vault_login_classifier.py b/agent/vault_login_classifier.py
index 1a55935f44f..50634b77089 100644
--- a/agent/vault_login_classifier.py
+++ b/agent/vault_login_classifier.py
@@ -23,6 +23,7 @@ import re
import unicodedata
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
+import itertools
LOGIN_AUTOFILL_TOKENS = ("username", "email", "tel", "current-password")
@@ -236,7 +237,7 @@ def build_otp_fills(otp_controls: list[ClassifiedLoginControl], code: str) -> li
boxes = sorted((c for c in otp_controls if c.control.max_length == 1), key=lambda c: c.control.index)
if (len(boxes) == len(code)
and len({b.control.form_index for b in boxes}) == 1
- and all(b.control.index - a.control.index == 1 for a, b in zip(boxes, boxes[1:]))):
+ and all(b.control.index - a.control.index == 1 for a, b in itertools.pairwise(boxes))):
return [{"index": b.control.index, "token": "one-time-code", "value": ch} for b, ch in zip(boxes, code)]
return [{"index": best.control.index, "token": "one-time-code", "value": code}]
diff --git a/evals/postmortem/forensics/logcalls.py b/evals/postmortem/forensics/logcalls.py
index 9153e6456c4..edfb0794494 100644
--- a/evals/postmortem/forensics/logcalls.py
+++ b/evals/postmortem/forensics/logcalls.py
@@ -23,6 +23,7 @@ import statistics
from typing import Any, Dict, List
from evals.postmortem.forensics.common import Run
+import itertools
_LINE = re.compile(
r"^(\S+ \S+) INFO \[(\S+)\] agent\.conversation_loop: API call #(\d+): model=(\S+) provider=\S+ "
@@ -100,7 +101,7 @@ def main(argv=None) -> int:
strict_pairs = strict_uncached = loose_pairs = loose_uncached = pairs = uncached_total = 0
for cs in by_sid.values():
cs.sort(key=lambda c: c["n"])
- for prev, cur in zip(cs, cs[1:]):
+ for prev, cur in itertools.pairwise(cs):
pairs += 1
u = max(0, cur["inp"] - cur["hit"]); uncached_total += u
if cur["inp"] > prev["inp"]:
diff --git a/evals/postmortem/live_ab/cache_concurrency_probe.py b/evals/postmortem/live_ab/cache_concurrency_probe.py
index f95997a0394..a9a56276839 100644
--- a/evals/postmortem/live_ab/cache_concurrency_probe.py
+++ b/evals/postmortem/live_ab/cache_concurrency_probe.py
@@ -166,6 +166,7 @@ if API_MODE == "chat_completions": Completions.create = patched_create
import agent.prompt_caching as _pc
_pc.effective_cache_ttl = lambda ttl, *, model="", provider="": ARGS.ttl # the probe pins the TTL; user config must not leak in
from run_agent import AIAgent
+import itertools
def creds():
if PROVIDER == "openrouter":
key = ARGS.api_key or os.environ.get("OPENROUTER_API_KEY") or sys.exit("OPENROUTER_API_KEY or --api-key required")
@@ -215,7 +216,7 @@ for r in rows: byw[r["worker"]].append(r)
for v in byw.values(): v.sort(key=lambda r: r["t_start"])
cat = collections.Counter(); stuck_tok = 0; bad = []
for w, cs in byw.items():
- for p, c in zip(cs, cs[1:]):
+ for p, c in itertools.pairwise(cs):
if c["system_sha"] != p["system_sha"]: cat["compaction"] += 1; continue
if abs(c["cache_read"] - p["prompt_tokens"]) <= 0.01 * p["prompt_tokens"] + 50: cat["ideal"] += 1
elif abs(c["cache_read"] - p["cache_read"]) <= 50: cat["stuck"] += 1; stuck_tok += p["prompt_tokens"] - p["cache_read"]; bad.append((w, p, c, "stuck"))
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index da29e193237..f06e70ebcd7 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -45,6 +45,7 @@ _bootstrap_root = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pa
if _bootstrap_root not in sys.path:
sys.path.insert(0, _bootstrap_root)
from hermes_cli import _startup_fast
+import itertools
# A literal ``~``/``$VAR`` in HERMES_HOME (fish, or any quoted value) must become absolute
# before the first reader — otherwise it resolves against cwd and scaffolds <cwd>/~/.hermes.
@@ -60,7 +61,7 @@ _startup_fast.normalize_hermes_home_env()
# too — a pre-loop wedge is just as dead without a supervisor; GatewayRunner
# disarms once the event loop is live.
def _argv_is_gateway_run(argv: list) -> bool:
- return any(a == "gateway" and b == "run" for a, b in zip(argv, argv[1:]))
+ return any(a == "gateway" and b == "run" for a, b in itertools.pairwise(argv))
if _argv_is_gateway_run(sys.argv[1:]):
diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.py
index 60a12e42afc..b3cd5fb26af 100644
--- a/hermes_cli/update_custody.py
+++ b/hermes_cli/update_custody.py
@@ -45,6 +45,7 @@ import os
import subprocess
import sys
from collections.abc import Sequence
+import itertools
logger = logging.getLogger(__name__)
@@ -417,7 +418,7 @@ def _partial_clone(git_cmd: Sequence[str], kwargs: dict) -> bool:
from hermes_cli.update_lock import _git_common_dir
cwd = kwargs.get("cwd")
- for flag, value in zip(git_cmd, git_cmd[1:]):
+ for flag, value in itertools.pairwise(git_cmd):
if flag == "-C":
cwd = Path(cwd or ".") / value
common = _git_common_dir(Path(cwd or "."))
diff --git a/hermes_state_portability.py b/hermes_state_portability.py
index 337ae2b0baa..11071c13070 100644
--- a/hermes_state_portability.py
+++ b/hermes_state_portability.py
@@ -18,6 +18,7 @@ from hermes_cli.timefmt import coerce_epoch
from hermes_state_ids import new_session_id
from hermes_state_common import SCHEMA_SQL, _shape_preview, _sql_preview_raw, _sql_session_last_active
from hermes_state_messages import _parse_tool_calls, _tool_calls_count
+import itertools
# Pre-split logger identity so log filtering/capture is unchanged.
logger = logging.getLogger("hermes_state")
@@ -107,7 +108,7 @@ def _export_timings(messages: list[dict[str, Any]], session_id: Optional[str] =
"from_message_id": prev.get("id"), "to_message_id": nxt.get("id"),
"from_role": prev.get("role"), "to_role": nxt.get("role"),
"gap_ms": max(0, round((nxt_ts - prev_ts) * 1000)),
- } for (prev, prev_ts), (nxt, nxt_ts) in zip(timestamped, timestamped[1:])]
+ } for (prev, prev_ts), (nxt, nxt_ts) in itertools.pairwise(timestamped)]
iso = lambda ts: datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
first_ts, last_ts = (timestamped[0][1], timestamped[-1][1]) if timestamped else (None, None)
return {
diff --git a/ruff.strict.toml b/ruff.strict.toml
index d6b88e6a708..6bc60acf826 100644
--- a/ruff.strict.toml
+++ b/ruff.strict.toml
@@ -412,7 +412,7 @@ select = [
"FURB181",
# "FURB188",
# "FURB192",
- # "RUF007",
+ "RUF007",
"RUF008",
# "RUF009",
"RUF010",
diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.py
index 2528cacf660..c0358b609b0 100644
--- a/scripts/code_health/py_rules.py
+++ b/scripts/code_health/py_rules.py
@@ -11,6 +11,7 @@ import ast
import re
from collections.abc import Callable, Iterable, Iterator
from dataclasses import dataclass, field
+import itertools
_FUNCS = (ast.FunctionDef, ast.AsyncFunctionDef)
_CAPTURE_CALLS = {
@@ -716,7 +717,7 @@ def _reaped_after_kill(tree: ast.Module, kinds: dict[int, str]) -> set[int]:
stmts = getattr(node, field, None)
if not isinstance(stmts, list):
continue
- for first, second in zip(stmts, stmts[1:]):
+ for first, second in itertools.pairwise(stmts):
kill = first.value if isinstance(first, ast.Expr) else None
wait = second.value if isinstance(second, _WAIT_STATEMENTS) else None
if not (isinstance(kill, ast.Call) and isinstance(wait, ast.Call)):
diff --git a/tests/agent/test_codex_reasoning_only_streak.py b/tests/agent/test_codex_reasoning_only_streak.py
index 78c1429d170..6760f24c667 100644
--- a/tests/agent/test_codex_reasoning_only_streak.py
+++ b/tests/agent/test_codex_reasoning_only_streak.py
@@ -22,6 +22,7 @@ from tests.agent.test_run_agent_codex_responses import (
_codex_message_response,
_codex_reasoning_only_response,
)
+import itertools
def _spy_fallback(agent, monkeypatch):
@@ -134,4 +135,4 @@ def test_cross_protocol_fallback_wire_drops_codex_nudge_and_replay_state(monkeyp
assert not any(_CODEX_INCOMPLETE_NUDGE in str(m.get("content") or "") for m in wire)
assert not any(m.get("codex_reasoning_items") for m in wire)
roles = [m["role"] for m in wire]
- assert roles and all(a != b for a, b in zip(roles, roles[1:]))
+ assert roles and all(a != b for a, b in itertools.pairwise(roles))
diff --git a/tests/agent/test_compression_busy_steer_anchor.py b/tests/agent/test_compression_busy_steer_anchor.py
index 3aed06becec..7a37e017223 100644
--- a/tests/agent/test_compression_busy_steer_anchor.py
+++ b/tests/agent/test_compression_busy_steer_anchor.py
@@ -19,6 +19,7 @@ from agent.conversation_compression import (
_ensure_compressed_has_user_turn,
)
from agent.prompt_builder import STEER_MARKER_OPEN, format_steer_marker
+import itertools
REQUEST_A = "Historical request A: audit the auth module."
STEER_B = "Steer B: stop, switch to fixing the login bug instead."
@@ -53,7 +54,7 @@ def _summary_row() -> dict:
def _assert_alternation(messages: list[dict]) -> None:
roles = [m.get("role") for m in messages]
- for left, right in zip(roles, roles[1:]):
+ for left, right in itertools.pairwise(roles):
assert not (left == right == "user"), f"user/user adjacency in {roles}"
assert not (left == right == "assistant"), f"assistant/assistant adjacency in {roles}"
diff --git a/tests/agent/test_compression_last_assistant_anchor.py b/tests/agent/test_compression_last_assistant_anchor.py
index 5542d53c50c..36a7ea961fe 100644
--- a/tests/agent/test_compression_last_assistant_anchor.py
+++ b/tests/agent/test_compression_last_assistant_anchor.py
@@ -21,6 +21,7 @@ from agent.context_compressor import SUMMARY_PREFIX
from agent.conversation_compression_reply_anchor import (
_ensure_compressed_keeps_last_assistant_reply,
)
+import itertools
# Trailing whitespace on purpose: a conforming engine may hand the row back stripped.
REPLY = "x" * 200 + " just-delivered verdict report the user is still reading. "
@@ -33,7 +34,7 @@ def _assert_no_same_role_adjacency(messages):
"""Strict alternation, tool rows included: a tool-call assistant is an assistant row
too, so never assistant;assistant (or user;user / tool;tool) anywhere in the view."""
roles = [m.get("role") for m in messages]
- assert not any(a == b for a, b in zip(roles, roles[1:])), f"same-role adjacency in {roles}"
+ assert not any(a == b for a, b in itertools.pairwise(roles)), f"same-role adjacency in {roles}"
def _count_reply(messages):
diff --git a/tests/agent/test_compression_rotation_state.py b/tests/agent/test_compression_rotation_state.py
index c7cf03a6aca..6db586dec2a 100644
--- a/tests/agent/test_compression_rotation_state.py
+++ b/tests/agent/test_compression_rotation_state.py
@@ -33,6 +33,7 @@ from agent.conversation_compression import (
)
from agent.message_metadata import DB_ROW_SNAPSHOT
from hermes_state import SessionDB
+import itertools
def _build_agent_with_db(db: SessionDB, session_id: str, platform: str = "telegram"):
@@ -1289,7 +1290,7 @@ class TestTodoSnapshotMergedNotDuplicated:
assert "task A" in tail["content"]
assert not any(
previous.get("role") == current.get("role") == "user"
- for previous, current in zip(compressed, compressed[1:])
+ for previous, current in itertools.pairwise(compressed)
)
@@ -1356,7 +1357,7 @@ class TestTodoSnapshotMergedNotDuplicated:
)
assert not any(
previous.get("role") == current.get("role") == "user"
- for previous, current in zip(compressed, compressed[1:])
+ for previous, current in itertools.pairwise(compressed)
)
db_msgs = db.get_messages(agent.session_id)
@@ -1369,7 +1370,7 @@ class TestTodoSnapshotMergedNotDuplicated:
)
assert not any(
previous.get("role") == current.get("role") == "user"
- for previous, current in zip(db_msgs, db_msgs[1:])
+ for previous, current in itertools.pairwise(db_msgs)
)
@@ -1426,7 +1427,7 @@ class TestTodoSnapshotScaffoldingTails:
assert "api_content" not in tail
assert not any(
previous.get("role") == current.get("role") == "user"
- for previous, current in zip(compressed, compressed[1:])
+ for previous, current in itertools.pairwise(compressed)
)
def test_empty_todo_store_injects_nothing(self, tmp_path: Path):
@@ -1621,7 +1622,7 @@ class TestTodoSnapshotScaffoldingTails:
assert "api_content" not in repaired
assert not any(
previous.get("role") == current.get("role")
- for previous, current in zip(compressed, compressed[1:])
+ for previous, current in itertools.pairwise(compressed)
)
def test_multimodal_content_survives_and_synthetic_provenance_clears(
diff --git a/tests/agent/test_compressor_actionable_tail_anchor.py b/tests/agent/test_compressor_actionable_tail_anchor.py
index bacadbce06d..d47e0d042e7 100644
--- a/tests/agent/test_compressor_actionable_tail_anchor.py
+++ b/tests/agent/test_compressor_actionable_tail_anchor.py
@@ -11,6 +11,7 @@ from agent.context_compressor import (
SUMMARY_PREFIX,
ContextCompressor,
)
+import itertools
@pytest.fixture()
@@ -64,7 +65,7 @@ def _compress(compressor: ContextCompressor, messages: list[dict]) -> list[dict]
def _assert_no_adjacent_user_roles(messages: list[dict]) -> None:
- for previous, current in zip(messages, messages[1:]):
+ for previous, current in itertools.pairwise(messages):
assert (previous.get("role"), current.get("role")) != ("user", "user")
diff --git a/tests/agent/test_compressor_zero_user_guard.py b/tests/agent/test_compressor_zero_user_guard.py
index 27973befc9f..0d4b214f31c 100644
--- a/tests/agent/test_compressor_zero_user_guard.py
+++ b/tests/agent/test_compressor_zero_user_guard.py
@@ -30,6 +30,7 @@ from __future__ import annotations
from unittest.mock import patch
import pytest
+import itertools
@pytest.fixture()
@@ -122,7 +123,7 @@ class TestCompressAlwaysKeepsAUserTurn:
with patch.object(c, "_generate_summary", return_value=mocked):
out = c.compress(messages, current_tokens=90_000)
- for prev, cur in zip(out, out[1:]):
+ for prev, cur in itertools.pairwise(out):
assert not (
prev.get("role") == "user" and cur.get("role") == "user"
), "compression introduced consecutive user-role messages"
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index 87b854154de..60c07e473af 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -22,6 +22,7 @@ from agent.context_compressor import (
from agent.compression_marker import _COMPRESSION_MARKER_PREFIX
from hermes_state import SessionDB
from agent.auxiliary_client import CODEX_STREAM_STALL_MARKER
+import itertools
_REQ = httpx.Request("POST", "http://x")
@@ -3317,7 +3318,7 @@ class TestSummaryPromptBounding:
assert coverage["sampled_record_count"] == len(shown)
# At least one initial gap was closed: fewer markers than the n-1 the n slices started with.
assert sampled.count("chars elided") < ContextCompressor._SAMPLED_INPUT_SLICES - 1
- for a, b in zip(shown, shown[1:]):
+ for a, b in itertools.pairwise(shown):
if b == a + 1:
assert f"{records[a]}\n\n{records[b]}" in sampled, (a, b)
else:
diff --git a/tests/agent/test_cron_inflight_prompt_reappend.py b/tests/agent/test_cron_inflight_prompt_reappend.py
index e0580f4634b..c5e1507dc7b 100644
--- a/tests/agent/test_cron_inflight_prompt_reappend.py
+++ b/tests/agent/test_cron_inflight_prompt_reappend.py
@@ -25,6 +25,7 @@ from agent.context_compressor import (
SUMMARY_PREFIX,
ContextCompressor,
)
+import itertools
JOB_SENTINEL = "CRON_JOB_PROMPT_sentinel_brief_the_inbox_and_write_a_digest"
@@ -155,7 +156,7 @@ def test_role_alternation_and_head_are_preserved():
or (m.get("role") == "assistant" and m.get("tool_calls"))
)
]
- for previous, current in zip(visible, visible[1:]):
+ for previous, current in itertools.pairwise(visible):
assert not (previous == current == "user"), (
f"consecutive user rows in compressed transcript: {visible}"
)
@@ -400,7 +401,7 @@ def test_replay_replaces_surviving_user_row_with_same_message_uid():
assert compressed[1]["role"] == "user", [m["role"] for m in compressed]
visible = [r for r in map(_template_visible_role, compressed[1:]) if r is not None]
assert visible[0] == "user", visible
- assert all(a != b for a, b in zip(visible, visible[1:])), visible
+ assert all(a != b for a, b in itertools.pairwise(visible)), visible
assert JOB_SENTINEL in _text(compressed[_handoff_idx(compressed)]).split(_SUMMARY_END_MARKER)[-1]
# Visible assistant text in the tail makes the summary merge into tail[0],
diff --git a/tests/agent/test_image_eviction_policy.py b/tests/agent/test_image_eviction_policy.py
index 2f3cfa6de20..108ca383771 100644
--- a/tests/agent/test_image_eviction_policy.py
+++ b/tests/agent/test_image_eviction_policy.py
@@ -17,6 +17,7 @@ from agent.image_eviction_policy import (
OUTBOUND_IMAGE_LIMIT,
outbound_image_retire_count,
)
+import itertools
MB = 1_000_000
@@ -64,5 +65,5 @@ def test_quantum_shrinks_to_the_fit_window_for_heavy_carriers():
counts = [outbound_image_retire_count([3] * n, 0) for n in range(window + 1, window + 10)]
assert all(c > 0 for c in counts)
assert all(3 * (n - c) <= OUTBOUND_IMAGE_LIMIT for n, c in zip(range(window + 1, window + 10), counts))
- moves = sum(a != b for a, b in zip(counts, counts[1:]))
+ moves = sum(a != b for a, b in itertools.pairwise(counts))
assert moves <= len(counts) // (window - OUTBOUND_IMAGE_FLOOR)
diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.py
index 1d0f6bad47c..a62d3a05e6c 100644
--- a/tests/agent/test_micro_compaction.py
+++ b/tests/agent/test_micro_compaction.py
@@ -28,6 +28,7 @@ from agent.context_compressor import (
ContextCompressor,
_MICRO_COMPACT_MAX_CONSECUTIVE_FAILURES,
)
+import itertools
def _compressor(summary="ROLLING SUMMARY") -> ContextCompressor:
@@ -572,7 +573,7 @@ class TestMicroCompaction:
for _ in range(4):
msgs = cc._micro_compact(msgs)
- for a, b in zip(msgs, msgs[1:]):
+ for a, b in itertools.pairwise(msgs):
ra, rb = a.get("role"), b.get("role")
assert not (ra == rb and ra in ("user", "assistant")), (
f"consecutive {ra} messages after micro-compaction"
diff --git a/tests/agent/test_moa_alternation_recovery.py b/tests/agent/test_moa_alternation_recovery.py
index e8d0c05a812..99e712fe2f7 100644
--- a/tests/agent/test_moa_alternation_recovery.py
+++ b/tests/agent/test_moa_alternation_recovery.py
@@ -12,6 +12,7 @@ import pytest
from agent import moa_loop
from agent.error_classifier import FailoverReason, classify_api_error
+import itertools
ALTERNATION_MSG = "Conversation roles must alternate user/assistant/user/assistant/..."
@@ -30,7 +31,7 @@ def _strict_destination(calls, strict_models):
def call_llm(**kw):
calls.append(kw)
msgs = [m for m in kw["messages"] if m["role"] != "system"]
- if kw["model"] in strict_models and any(a["role"] == b["role"] for a, b in zip(msgs, msgs[1:])):
+ if kw["model"] in strict_models and any(a["role"] == b["role"] for a, b in itertools.pairwise(msgs)):
raise _AlternationRejected()
return SimpleNamespace(choices=[])
return call_llm
diff --git a/tests/agent/test_outbound_stale_vision.py b/tests/agent/test_outbound_stale_vision.py
index 30b9aad5aeb..736d5d0016e 100644
--- a/tests/agent/test_outbound_stale_vision.py
+++ b/tests/agent/test_outbound_stale_vision.py
@@ -20,6 +20,7 @@ from agent.image_eviction_policy import (
OUTBOUND_IMAGE_FLOOR,
OUTBOUND_IMAGE_LIMIT,
)
+import itertools
def _image_tool(i: int, *, blob: str = "A" * 80) -> list[dict]:
@@ -139,7 +140,7 @@ class TestOutboundStaleVisionEviction:
kept = [surviving(n) for n in span]
assert all(len(k) <= OUTBOUND_IMAGE_LIMIT for k in kept), [len(k) for k in kept]
frontier = [k[0] for k in kept]
- moves = sum(a != b for a, b in zip(frontier, frontier[1:]))
+ moves = sum(a != b for a, b in itertools.pairwise(frontier))
assert moves == 3, (
f"frontier moved {moves} times over {len(span)} images (frontier={frontier}); "
"each move rewrites a cached row and restarts the prefix"
@@ -192,7 +193,7 @@ class TestOutboundStaleVisionEviction:
window = OUTBOUND_IMAGE_LIMIT // 3
span = range(window + 1, window + 1 + 4 * (window - OUTBOUND_IMAGE_FLOOR))
frontier = [surviving(n)[0] for n in span]
- moves = sum(a != b for a, b in zip(frontier, frontier[1:]))
+ moves = sum(a != b for a, b in itertools.pairwise(frontier))
assert moves <= len(span) // (window - OUTBOUND_IMAGE_FLOOR), (
f"frontier moved {moves} times over {len(span)} turns (frontier={frontier}); "
"a per-image frontier rewrites the cached prefix every turn"
diff --git a/tests/agent/test_summary_role_template_alternation.py b/tests/agent/test_summary_role_template_alternation.py
index 2de622445f9..dbd2186c7fc 100644
--- a/tests/agent/test_summary_role_template_alternation.py
+++ b/tests/agent/test_summary_role_template_alternation.py
@@ -44,6 +44,7 @@ from agent.context_compressor import (
SUMMARY_PREFIX,
_template_visible_role,
)
+import itertools
@pytest.fixture()
@@ -234,7 +235,7 @@ class TestForcedUserGuardsStillWin:
with patch.object(c, "_generate_summary", return_value=mocked):
out = c.compress(messages, current_tokens=90_000)
- for prev, cur in zip(out, out[1:]):
+ for prev, cur in itertools.pairwise(out):
assert not (
prev.get("role") == "user" and cur.get("role") == "user"
), "compression introduced literal consecutive user-role messages"
diff --git a/tests/cron/test_blueprint_catalog.py b/tests/cron/test_blueprint_catalog.py
index dd76451ea03..1db4366e6ee 100644
--- a/tests/cron/test_blueprint_catalog.py
+++ b/tests/cron/test_blueprint_catalog.py
@@ -20,6 +20,7 @@ from cron.blueprint_catalog import (
get_blueprint,
blueprint_deeplink,
)
+import itertools
class TestCatalog:
@@ -87,7 +88,7 @@ class TestValidation:
first_three = [it.get_next(datetime) for _ in range(3)]
gaps = {
(b - a).total_seconds()
- for a, b in zip(first_three, first_three[1:])
+ for a, b in itertools.pairwise(first_three)
}
assert gaps == {7200.0}, f"expected 2h gaps, got {spec['schedule']} -> {first_three}"
diff --git a/tests/e2e/core/compaction/_helpers.py b/tests/e2e/core/compaction/_helpers.py
index 59f2d84fc5b..0ae68b5b3e6 100644
--- a/tests/e2e/core/compaction/_helpers.py
+++ b/tests/e2e/core/compaction/_helpers.py
@@ -31,6 +31,7 @@ from pathlib import Path
from typing import Any, Callable, Iterable
from tests.fakes.fake_llm_provider import MODEL_ID, Error, FakeLLMServer, Hang, Text, ToolCall
+import itertools
# Every compaction knob is tiny so a handful of turns crosses the trigger. The window must stay at the
# 64K agent floor; ``threshold_tokens`` (an absolute cap) pulls the trigger far below the ratio floor.
@@ -385,7 +386,7 @@ def assert_wire_request_ok(body: dict[str, Any], turn_marker: str, base_system:
assert text.rfind(turn_marker) > text.rfind(GOOD_SUMMARY_TOKEN), (
f"{where}: the in-flight user message {turn_marker} only survives inside/before the summary")
assert_tool_pairs(msgs, where)
- for a, b in zip(msgs, msgs[1:]):
+ for a, b in itertools.pairwise(msgs):
assert not (a["role"] == "user" and b["role"] == "user"), f"{where}: two consecutive user messages"
assert msgs[-1]["role"] in ("user", "tool"), f"{where}: request ends with {msgs[-1]['role']}"
diff --git a/tests/e2e/core/dashboard/test_dashboard_sessions.py b/tests/e2e/core/dashboard/test_dashboard_sessions.py
index 508bde2c508..5cf6495f303 100644
--- a/tests/e2e/core/dashboard/test_dashboard_sessions.py
+++ b/tests/e2e/core/dashboard/test_dashboard_sessions.py
@@ -24,6 +24,7 @@ from typing import Callable
import pytest
from . import _helpers as H
+import itertools
pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="POSIX dashboard process")
@@ -151,7 +152,7 @@ def test_session_routes_stay_consistent_under_a_concurrent_writer(env) -> None:
assert w.done >= 20, f"writer committed only {w.done} sessions: the contention window never opened"
assert len(totals) >= 10 and len(series) >= 10, f"too few reads overlapped the writer ({len(totals)}, {len(series)})"
assert not problems, f"{len(problems)} inconsistent read(s) while writing:\n " + "\n ".join(dict.fromkeys(problems[:30]))
- backwards = [(a, b) for a, b in zip(series, series[1:]) if b < a]
+ backwards = [(a, b) for a, b in itertools.pairwise(series) if b < a]
assert not backwards, f"session total went backwards between sequential reads: {backwards[:5]}"
raw = H.db_rows(p.db, "SELECT COUNT(*) FROM sessions WHERE parent_session_id IS NULL")[0][0]
diff --git a/tests/e2e/core/platforms/_contract.py b/tests/e2e/core/platforms/_contract.py
index 7f53914af74..a7a6fd026b1 100644
--- a/tests/e2e/core/platforms/_contract.py
+++ b/tests/e2e/core/platforms/_contract.py
@@ -249,7 +249,7 @@ def _split_seam(visible: list[Visible], aid: str) -> Optional[str]:
"""The seam, as the user reads it, where the answer's ending is cut mid-word across two
consecutive messages (a continuation that resumed mid-word instead of at a word boundary)."""
texts, end = [norm(v.text) for v in visible], foot(aid)
- for a, b in zip(texts, texts[1:]):
+ for a, b in itertools.pairwise(texts):
for i in range(1, len(end)):
if a.endswith(end[:i]) and b.startswith(end[i:]):
return f"{a[-40:]!r} | {b[:40]!r}"
diff --git a/tests/e2e/core/providers/test_anthropic_errors.py b/tests/e2e/core/providers/test_anthropic_errors.py
index 9feecd6c0f3..d8c4fdc0c4d 100644
--- a/tests/e2e/core/providers/test_anthropic_errors.py
+++ b/tests/e2e/core/providers/test_anthropic_errors.py
@@ -18,6 +18,7 @@ import pytest
from tests.e2e.core._pending_fixes import known_gate
from tests.e2e.core.providers._anthropic_helpers import Rig, dump, normalised, start_rig, thinking_of
from tests.fakes.providers.anthropic_messages import ApiError, DropStream, Reply, Text, Thinking
+import itertools
pytestmark = [pytest.mark.skipif(not sys.platform.startswith("linux"), reason="process-tree cleanup uses /proc"),
pytest.mark.live_system_guard_bypass]
@@ -55,7 +56,7 @@ def rig_factory(tmp_path: Path):
def _gaps(rig: Rig) -> list[float]:
t = [r["t"] for r in rig.srv.main_requests()]
- return [round(b - a, 2) for a, b in zip(t, t[1:])]
+ return [round(b - a, 2) for a, b in itertools.pairwise(t)]
def test_429_waits_the_retry_after_then_succeeds(rig_factory) -> None:
diff --git a/tests/fakes/providers/gemini_native.py b/tests/fakes/providers/gemini_native.py
index ce6f932ae8d..f2b4862112e 100644
--- a/tests/fakes/providers/gemini_native.py
+++ b/tests/fakes/providers/gemini_native.py
@@ -38,6 +38,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Callable
from urllib.parse import parse_qs, urlsplit
+import itertools
GEMINI_HOST = "generativelanguage.googleapis.com"
MODEL_ID = "gemini-3-flash-preview"
@@ -342,7 +343,7 @@ def validate_generate_request(body: Any, version: str, model: str, issued: set[s
raise InvalidArgument(f"* GenerateContentRequest.contents[{ci}].parts: contents.parts must not be empty.")
norm.append({"role": role, "parts": [_validate_part(p, f"contents[{ci}].parts[{pi}]")
for pi, p in enumerate(parts)]})
- for a, b in zip(norm, norm[1:]):
+ for a, b in itertools.pairwise(norm):
if a["role"] == b["role"]:
raise InvalidArgument("Please ensure that multiturn requests alternate between user and model.")
if norm[-1]["role"] != "user":
diff --git a/tests/gateway/test_stale_confirmation_expiry.py b/tests/gateway/test_stale_confirmation_expiry.py
index 2fb0d690568..46272c9cad7 100644
--- a/tests/gateway/test_stale_confirmation_expiry.py
+++ b/tests/gateway/test_stale_confirmation_expiry.py
@@ -24,6 +24,7 @@ from agent.replay_cleanup import (
strip_stale_dangerous_confirmations as _strip_stale_dangerous_confirmations,
)
from gateway.run import _build_gateway_agent_history
+import itertools
# High-risk confirmation patterns. A user message matching one of these
@@ -132,6 +133,6 @@ def test_redaction_preserves_role_alternation():
assert "EXPIRED" in redacted["content"]
# No two consecutive same-role messages anywhere.
roles = [m["role"] for m in cleaned]
- assert all(a != b for a, b in zip(roles, roles[1:])), roles
+ assert all(a != b for a, b in itertools.pairwise(roles)), roles
# Original history object is not mutated.
assert history[2]["content"] == "confirm forced restart"
diff --git a/tests/gateway/test_telegram_split_send_flood.py b/tests/gateway/test_telegram_split_send_flood.py
index 43e4c42055b..90ec30a6a7b 100644
--- a/tests/gateway/test_telegram_split_send_flood.py
+++ b/tests/gateway/test_telegram_split_send_flood.py
@@ -12,6 +12,7 @@ import pytest
from gateway.config import PlatformConfig
from plugins.platforms.telegram.adapter import TelegramAdapter
+import itertools
class _FloodError(Exception):
@@ -111,5 +112,5 @@ async def test_concurrent_split_sends_to_one_chat_do_not_interleave():
await asyncio.gather(adapter.send("1", long("REPORT")), adapter.send("1", long("ALERT")))
assert len(order) >= 4
- switches = sum(1 for a, b in zip(order, order[1:]) if a != b)
+ switches = sum(1 for a, b in itertools.pairwise(order) if a != b)
assert switches == 1, order
diff --git a/tests/hermes_cli/test_context_policy.py b/tests/hermes_cli/test_context_policy.py
index 23a2c7241d5..429772d4c00 100644
--- a/tests/hermes_cli/test_context_policy.py
+++ b/tests/hermes_cli/test_context_policy.py
@@ -33,6 +33,7 @@ from hermes_cli.local_runtime.estimator import (
ctx_bytes,
physics_check,
)
+import itertools
GIB = 1 << 30
MIB = 1 << 20
@@ -172,9 +173,9 @@ def test_ladder_shape():
rungs = ladder(262144)
assert rungs[0] == FLOOR
assert rungs[-1] == 262144
- assert all(a < b for a, b in zip(rungs, rungs[1:]))
+ assert all(a < b for a, b in itertools.pairwise(rungs))
# geometric-ish: each step grows, none more than 2x
- assert all(b / a <= 2.0 for a, b in zip(rungs, rungs[1:]))
+ assert all(b / a <= 2.0 for a, b in itertools.pairwise(rungs))
def test_initial_window_never_below_floor_and_never_above_native():
@@ -193,7 +194,7 @@ def test_initial_window_monotone_in_vram():
d = initial_window(p, card(vram))
assert isinstance(d, WindowDecision)
windows.append(d.window)
- assert all(a <= b for a, b in zip(windows, windows[1:]))
+ assert all(a <= b for a, b in itertools.pairwise(windows))
def test_flat_curve_reaches_native_where_dense_does_not():
diff --git a/tests/hermes_cli/test_foreign_sessions.py b/tests/hermes_cli/test_foreign_sessions.py
index 07914268534..5bb59b2cc2f 100644
--- a/tests/hermes_cli/test_foreign_sessions.py
+++ b/tests/hermes_cli/test_foreign_sessions.py
@@ -16,6 +16,7 @@ from hermes_cli.foreign_sessions import (
parse_claude_session,
parse_codex_session,
)
+import itertools
# ── fixture builders ─────────────────────────────────────────────────────
@@ -108,7 +109,7 @@ def _assert_alternating(messages):
roles = [m["role"] for m in messages]
assert roles, "no messages"
assert roles[0] == "user"
- for a, b in zip(roles, roles[1:]):
+ for a, b in itertools.pairwise(roles):
assert a != b, f"two consecutive {a} messages"
diff --git a/tests/hermes_state/test_restore_alternation_repair.py b/tests/hermes_state/test_restore_alternation_repair.py
index f665aae2c84..924a48c1d2c 100644
--- a/tests/hermes_state/test_restore_alternation_repair.py
+++ b/tests/hermes_state/test_restore_alternation_repair.py
@@ -14,6 +14,7 @@ export consumers (trace upload, context guard) read the transcript as-is.
import pytest
from hermes_state import SessionDB
+import itertools
@pytest.fixture()
@@ -94,7 +95,7 @@ def test_acp_restore_heals_alternation_for_live_replay(db):
roles = [m["role"] for m in state.history]
# No consecutive user turns — the durable user;user wedge was healed.
assert roles == ["user", "assistant", "user", "assistant"], roles
- for a, b in zip(roles, roles[1:]):
+ for a, b in itertools.pairwise(roles):
assert not (a == "user" and b == "user"), "unhealed user;user in ACP live replay"
# No user input lost — both user texts survive, merged in order.
merged = state.history[2]["content"]
diff --git a/tests/scripts/test_termux_deb_version.py b/tests/scripts/test_termux_deb_version.py
index 1d314c1fc88..c8e82729568 100644
--- a/tests/scripts/test_termux_deb_version.py
+++ b/tests/scripts/test_termux_deb_version.py
@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
from scripts.termux.deb_version import channel_for_tag, deb_version_for_tag
+import itertools
SCRIPT = Path(__file__).resolve().parents[2] / "scripts/termux/deb_version.py"
@@ -84,5 +85,5 @@ def test_cli_dispatch(args, status, output):
def test_dpkg_orders_canary_and_numeric_versions():
tags = ["v1.2.3+canary.20260831T000000Z", "v1.2.3+canary.20260831T235959Z", "v1.2.3", "v1.2.10"]
versions = list(map(deb_version_for_tag, tags))
- for earlier, later in zip(versions, versions[1:]):
+ for earlier, later in itertools.pairwise(versions):
subprocess.run(["dpkg", "--compare-versions", earlier, "lt", later], check=True)
diff --git a/tests/skills/test_skill_blueprint_contracts.py b/tests/skills/test_skill_blueprint_contracts.py
index 8e03d5eb73e..8bc24822942 100644
--- a/tests/skills/test_skill_blueprint_contracts.py
+++ b/tests/skills/test_skill_blueprint_contracts.py
@@ -6,6 +6,7 @@ import pytest
from croniter import croniter
from cron.blueprint_catalog import CATALOG, fill_blueprint, get_blueprint
+import itertools
REPO = Path(__file__).resolve().parents[2]
@@ -56,4 +57,4 @@ def test_price_watch_fills_and_persists_with_chosen_cadence(hours, tmp_path, mon
ticks = croniter(saved["schedule"]["expr"], datetime(2026, 1, 1, tzinfo=timezone.utc))
# Span a day boundary: wrong-field steps can otherwise look valid once.
times = [ticks.get_next(datetime) for _ in range(26)]
- assert {b - a for a, b in zip(times, times[1:])} == {timedelta(hours=int(hours))}
+ assert {b - a for a, b in itertools.pairwise(times)} == {timedelta(hours=int(hours))}
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index 567b61bb42a..8bc8147b853 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -10,6 +10,7 @@ from typing import Any, Dict, List, Optional, cast
from unittest.mock import MagicMock, patch
import pytest
+import itertools
# ---------------------------------------------------------------------------
@@ -595,7 +596,7 @@ class TestAnthropicAdapterMultimodal:
span = range(OUTBOUND_IMAGE_LIMIT - 2, OUTBOUND_IMAGE_LIMIT + 3 * IMAGE_EVICTION_BATCH)
counts = [placeholder_count(n) for n in span]
assert all(n - c <= OUTBOUND_IMAGE_LIMIT for n, c in zip(span, counts)), counts
- steps = sum(a != b for a, b in zip(counts, counts[1:]))
+ steps = sum(a != b for a, b in itertools.pairwise(counts))
assert steps == 3, (
f"eviction frontier moved {steps} times over {len(span)} screenshots (counts={counts}); "
"each step invalidates the cached prefix"
diff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.py
index e6f0a2e36d6..4d6c83ce434 100644
--- a/tools/file_tools_write_guards.py
+++ b/tools/file_tools_write_guards.py
@@ -25,6 +25,7 @@ from tools.binary_extensions import (
from tools.file_tools_paths import (
_expand_tilde, _resolve_path_for_task, _ssh_path_escapes_home, _terminal_env_type_for_task)
from tools.file_tools_read_tracking import _has_full_write_baseline, _is_own_blind_patch, _read_mtime_drifted
+import itertools
# Prefixes matched after realpath. macOS: /private/var mirrors /var — block the
# sensitive subtrees only; a blanket "/private/var/" refuses every temp-file
@@ -634,7 +635,7 @@ def _looks_like_read_file_line_numbered_content(content: str) -> bool:
numbered.append(int(prefix))
if len(numbered) < 2 or len(numbered) / len(lines) < 0.6:
return False
- consecutive_pairs = sum(1 for prev, current in zip(numbered, numbered[1:]) if current == prev + 1)
+ consecutive_pairs = sum(1 for prev, current in itertools.pairwise(numbered) if current == prev + 1)
return consecutive_pairs >= len(numbered) - 1