chore: ruff auto-fix C401, C416, C408, PLR1722 (#23940)

C401:   set(x for x in y) -> {x for x in y}      (set comprehension)
C416:   [(k,v) for k,v in d] -> list(d.items())  (unnecessary listcomp)
C408:   tuple()/dict() -> ()/{}                   (unnecessary collection call)
PLR1722: exit() -> sys.exit()                     (adds import sys where needed)

21 instances fixed, 0 remaining. 19 files, +40/-36.
This commit is contained in:
kshitij 2026-05-11 11:20:58 -07:00 committed by GitHub
parent 7b76366552
commit ce0f529cde
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 40 additions and 36 deletions

View file

@ -919,7 +919,7 @@ class TerminalBench2EvalEnv(HermesAgentBaseEnv):
eval_metrics[f"eval/pass_rate_{cat_key}"] = cat_pass_rate
# Store metrics for wandb_log
self.eval_metrics = [(k, v) for k, v in eval_metrics.items()]
self.eval_metrics = list(eval_metrics.items())
# ---- Print summary ----
print(f"\n{'='*60}")

View file

@ -759,7 +759,7 @@ class YCBenchEvalEnv(HermesAgentBaseEnv):
eval_metrics[f"eval/survival_rate_{key}"] = ps / pt if pt else 0
eval_metrics[f"eval/avg_score_{key}"] = pa
self.eval_metrics = [(k, v) for k, v in eval_metrics.items()]
self.eval_metrics = list(eval_metrics.items())
# --- Print summary ---
print(f"\n{'='*60}")

View file

@ -3724,7 +3724,7 @@ class DiscordAdapter(BasePlatformAdapter):
return None
# DMs, voice channels, and existing threads can't host child threads.
if isinstance(parent, getattr(discord, "DMChannel", tuple())):
if isinstance(parent, getattr(discord, "DMChannel", ())):
logger.info(
"[%s] Handoff thread: parent %s is a DM; threads not supported here",
self.name, parent_chat_id,

View file

@ -1428,8 +1428,8 @@ class FeishuAdapter(BasePlatformAdapter):
per_chat_require_mention = _to_boolean(rule_cfg.get("require_mention"))
group_rules[str(chat_id)] = FeishuGroupRule(
policy=str(rule_cfg.get("policy", "open")).strip().lower(),
allowlist=set(str(u).strip() for u in rule_cfg.get("allowlist", []) if str(u).strip()),
blacklist=set(str(u).strip() for u in rule_cfg.get("blacklist", []) if str(u).strip()),
allowlist={str(u).strip() for u in rule_cfg.get("allowlist", []) if str(u).strip()},
blacklist={str(u).strip() for u in rule_cfg.get("blacklist", []) if str(u).strip()},
require_mention=per_chat_require_mention,
)

View file

@ -228,7 +228,7 @@ def _load_pairing_approved() -> set:
if isinstance(approved, dict):
return set(approved.keys())
if isinstance(approved, list):
return set(str(u) for u in approved if u)
return {str(u) for u in approved if u}
return set()

View file

@ -59,7 +59,7 @@ class TelegramFallbackTransport(httpx.AsyncBaseTransport):
"""
def __init__(self, fallback_ips: Iterable[str], **transport_kwargs):
self._fallback_ips = [ip for ip in dict.fromkeys(_normalize_fallback_ips(fallback_ips))]
self._fallback_ips = list(dict.fromkeys(_normalize_fallback_ips(fallback_ips)))
proxy_url = _resolve_proxy_url(target_hosts=[_TELEGRAM_API_HOST, *self._fallback_ips])
if proxy_url and "proxy" not in transport_kwargs:
transport_kwargs["proxy"] = proxy_url

View file

@ -2337,7 +2337,7 @@ class SessionDB:
"SELECT id FROM sessions WHERE started_at < ? AND ended_at IS NOT NULL",
(cutoff,),
)
session_ids = set(row["id"] for row in cursor.fetchall())
session_ids = {row["id"] for row in cursor.fetchall()}
if not session_ids:
return 0

View file

@ -343,7 +343,7 @@ def key_metrics(data: dict[str, Any]) -> dict[str, float]:
metrics["backpressure_frames"] = bp
if react:
for pid in set(e["id"] for e in react):
for pid in {e["id"] for e in react}:
ms = [e["actualMs"] for e in react if e["id"] == pid]
metrics[f"react_{pid}_p99"] = pct(ms, 0.99)
metrics[f"react_{pid}_max"] = max(ms)

View file

@ -1426,7 +1426,7 @@ def main():
print(f" SemVer: v{current_version} → v{new_version}")
print(f" Previous tag: {prev_tag or '(none — first release)'}")
print(f" Commits: {len(commits)}")
print(f" Unique authors: {len(set(c['github_author'] for c in commits))}")
print(f" Unique authors: {len({c['github_author'] for c in commits})}")
print(f" Mode: {'PUBLISH' if args.publish else 'DRY RUN'}")
print(f"{'='*60}")
print()

View file

@ -291,7 +291,7 @@ class MemoryStore:
if len(matches) > 1:
# If all matches are identical (exact duplicates), operate on the first one
unique_texts = set(e for _, e in matches)
unique_texts = {e for _, e in matches}
if len(unique_texts) > 1:
previews = [e[:80] + ("..." if len(e) > 80 else "") for _, e in matches]
return {
@ -341,7 +341,7 @@ class MemoryStore:
if len(matches) > 1:
# If all matches are identical (exact duplicates), remove the first one
unique_texts = set(e for _, e in matches)
unique_texts = {e for _, e in matches}
if len(unique_texts) > 1:
previews = [e[:80] + ("..." if len(e) > 80 else "") for _, e in matches]
return {

View file

@ -54,6 +54,7 @@ from typing import Dict, Any, List, Optional
from tools.openrouter_client import get_async_client as _get_openrouter_client, check_api_key as check_openrouter_api_key
from agent.auxiliary_client import extract_content_or_reasoning
from tools.debug_helpers import DebugSession
import sys
logger = logging.getLogger(__name__)
@ -451,7 +452,7 @@ if __name__ == "__main__":
print("❌ OPENROUTER_API_KEY environment variable not set")
print("Please set your API key: export OPENROUTER_API_KEY='your-key-here'")
print("Get API key at: https://openrouter.ai/")
exit(1)
sys.exit(1)
else:
print("✅ OpenRouter API key found")

View file

@ -928,5 +928,5 @@ def _build_summary(name: str, source: str, trust: str, verdict: str, findings: L
if not findings:
return f"{name}: clean scan, no threats detected"
categories = set(f.category for f in findings)
categories = {f.category for f in findings}
return f"{name}: {verdict}{len(findings)} finding(s) in {', '.join(sorted(categories))}"

View file

@ -345,7 +345,7 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
manifest = _read_manifest()
bundled_dir = _get_bundled_dir()
bundled_skills = _discover_bundled_skills(bundled_dir)
bundled_by_name = {skill_name: skill_dir for skill_name, skill_dir in bundled_skills}
bundled_by_name = dict(bundled_skills)
in_manifest = name in manifest
is_bundled = name in bundled_by_name

View file

@ -721,7 +721,7 @@ def skills_list(category: str = None, task_id: str = None) -> str:
# Extract unique categories
categories = sorted(
set(s.get("category") for s in all_skills if s.get("category"))
{s.get("category") for s in all_skills if s.get("category")}
)
return json.dumps(

View file

@ -888,6 +888,7 @@ from tools.environments.docker import DockerEnvironment as _DockerEnvironment
from tools.environments.modal import ModalEnvironment as _ModalEnvironment
from tools.environments.managed_modal import ManagedModalEnvironment as _ManagedModalEnvironment
from tools.managed_tool_gateway import is_managed_tool_gateway_ready
import sys
# Tool description for LLM
@ -2243,7 +2244,7 @@ if __name__ == "__main__":
if not check_terminal_requirements():
print("\n❌ Requirements not met. Please check the messages above.")
exit(1)
sys.exit(1)
print("\n✅ All requirements met!")
print("\nAvailable Tool:")

View file

@ -848,13 +848,13 @@ def _generate_openai_tts(text: str, output_path: str, tts_config: Dict[str, Any]
OpenAIClient = _import_openai_client()
client = OpenAIClient(api_key=api_key, base_url=base_url)
try:
create_kwargs = dict(
model=model,
voice=voice,
input=text,
response_format=response_format,
extra_headers={"x-idempotency-key": str(uuid.uuid4())},
)
create_kwargs = {
"model": model,
"voice": voice,
"input": text,
"response_format": response_format,
"extra_headers": {"x-idempotency-key": str(uuid.uuid4())},
}
if speed != 1.0:
create_kwargs["speed"] = max(0.25, min(4.0, speed))
response = client.audio.speech.create(**create_kwargs)

View file

@ -41,6 +41,7 @@ from agent.auxiliary_client import async_call_llm, extract_content_or_reasoning
from hermes_constants import get_hermes_dir
from tools.debug_helpers import DebugSession
from tools.website_policy import check_website_access
import sys
logger = logging.getLogger(__name__)
@ -937,7 +938,7 @@ if __name__ == "__main__":
if not api_available:
print("❌ No auxiliary vision model available")
print("Configure a supported multimodal backend (OpenRouter, Nous, Codex, Anthropic, or a custom OpenAI-compatible endpoint).")
exit(1)
sys.exit(1)
else:
print("✅ Vision model available")

View file

@ -100,6 +100,7 @@ from tools.managed_tool_gateway import (
from tools.tool_backend_helpers import managed_nous_tools_enabled, prefers_gateway
from tools.url_safety import is_safe_url
from tools.website_policy import check_website_access
import sys
logger = logging.getLogger(__name__)
@ -2153,7 +2154,7 @@ if __name__ == "__main__":
print(f"✅ Auxiliary model available: {default_summarizer_model}")
if not web_available:
exit(1)
sys.exit(1)
print("🛠️ Web tools ready for use!")

View file

@ -1624,27 +1624,27 @@ def _on_tool_progress(
def _agent_cbs(sid: str) -> dict:
return dict(
tool_start_callback=lambda tc_id, name, args: _on_tool_start(
return {
"tool_start_callback": lambda tc_id, name, args: _on_tool_start(
sid, tc_id, name, args
),
tool_complete_callback=lambda tc_id, name, args, result: _on_tool_complete(
"tool_complete_callback": lambda tc_id, name, args, result: _on_tool_complete(
sid, tc_id, name, args, result
),
tool_progress_callback=lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
"tool_progress_callback": lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
sid, event_type, name, preview, args, **kwargs
),
tool_gen_callback=lambda name: _tool_progress_enabled(sid)
"tool_gen_callback": lambda name: _tool_progress_enabled(sid)
and _emit("tool.generating", sid, {"name": name}),
thinking_callback=lambda text: _emit("thinking.delta", sid, {"text": text}),
reasoning_callback=lambda text: _emit("reasoning.delta", sid, {"text": text}),
status_callback=lambda kind, text=None: _status_update(
"thinking_callback": lambda text: _emit("thinking.delta", sid, {"text": text}),
"reasoning_callback": lambda text: _emit("reasoning.delta", sid, {"text": text}),
"status_callback": lambda kind, text=None: _status_update(
sid, str(kind), None if text is None else str(text)
),
clarify_callback=lambda q, c: _block(
"clarify_callback": lambda q, c: _block(
"clarify.request", sid, {"question": q, "choices": c}
),
)
}
def _wire_callbacks(sid: str):