chore: ruff auto-fix PLR6201 resweep — tuple → set in membership tests (#27355)

Six days after #23937 (608 fixes) the codebase had accumulated 241 new
PLR6201 violations. Same mechanical `x in (...)` → `x in {...}` fix,
same zero-risk profile: set lookup is O(1) vs O(n) for tuple and the
two are semantically equivalent for hashable scalar membership tests.

All 241 instances fixed via `ruff check --select PLR6201 --fix
--unsafe-fixes`, zero remaining. Every changed value is a hashable
scalar (str/int/None/enum/signal); no risk of unhashable runtime
errors. No behavior change.

Test plan:
- 119 files changed, +244/-244 (net zero) — exactly one-line edits
- `ruff check` clean afterward
- Compile checks pass on the largest touched files (cli.py, run_agent.py,
  gateway/run.py, gateway/platforms/discord.py, model_tools.py)
- Subset broad test run on tests/gateway/ tests/hermes_cli/ tests/agent/
  tests/tools/: 18187 passed, 59 pre-existing failures (verified against
  origin/main with the same shape — identical failure count, identical
  category — all xdist test-order flakes unrelated to this change)

Follows the same template as PR #23937 ([tracker: #23972](https://github.com/NousResearch/hermes-agent/issues/23972)).
This commit is contained in:
kshitij 2026-05-17 02:29:41 -07:00 committed by GitHub
parent ad00777f04
commit 5fba236644
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
119 changed files with 244 additions and 244 deletions

View file

@ -222,7 +222,7 @@ def _fmt_summary(summary: Dict[str, Any]) -> str:
def _handle_slash(raw_args: str) -> Optional[str]:
argv = raw_args.strip().split()
if not argv or argv[0] in ("help", "-h", "--help"):
if not argv or argv[0] in {"help", "-h", "--help"}:
return _HELP_TEXT
sub = argv[0]

View file

@ -72,7 +72,7 @@ def register(ctx) -> None:
# tested path there and guest-join Chromium is flakier. Refuse to register
# rather than half-working.
system = platform.system().lower()
if system not in ("linux", "darwin"):
if system not in {"linux", "darwin"}:
logger.info(
"google_meet plugin: platform=%s not supported (linux/macos only)",
system,

View file

@ -159,7 +159,7 @@ def _cmd_setup() -> int:
print("---------------------")
system = _p.system()
system_ok = system in ("Linux", "Darwin")
system_ok = system in {"Linux", "Darwin"}
print(f" platform : {system} [{'ok' if system_ok else 'unsupported'}]")
try:
@ -231,7 +231,7 @@ def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
import subprocess as _sp
system = _p.system()
if system not in ("Linux", "Darwin"):
if system not in {"Linux", "Darwin"}:
print(f"google_meet install: {system} is not supported (linux/macos only)")
return 1
@ -242,7 +242,7 @@ def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
ans = input(f"{prompt} [y/N] ").strip().lower()
except EOFError:
return False
return ans in ("y", "yes")
return ans in {"y", "yes"}
print("google_meet install")
print("-------------------")

View file

@ -447,7 +447,7 @@ def _mac_audio_device_index(device_name: str) -> str:
def run_bot() -> int: # noqa: C901 — orchestration, explicit branches
url = os.environ.get("HERMES_MEET_URL", "").strip()
out_dir_env = os.environ.get("HERMES_MEET_OUT_DIR", "").strip()
headed = os.environ.get("HERMES_MEET_HEADED", "").lower() in ("1", "true", "yes")
headed = os.environ.get("HERMES_MEET_HEADED", "").lower() in {"1", "true", "yes"}
auth_state = os.environ.get("HERMES_MEET_AUTH_STATE", "").strip()
guest_name = os.environ.get("HERMES_MEET_GUEST_NAME", "Hermes Agent")
duration_s = _parse_duration(os.environ.get("HERMES_MEET_DURATION", ""))
@ -808,7 +808,7 @@ def _looks_like_human_speaker(speaker: str, bot_guest_name: str) -> bool:
if not speaker or not speaker.strip():
return False
spk = speaker.strip().lower()
if spk in ("unknown", "you", bot_guest_name.strip().lower()):
if spk in {"unknown", "you", bot_guest_name.strip().lower()}:
return False
return True

View file

@ -103,7 +103,7 @@ def node_command(args: argparse.Namespace) -> int:
print(f"removed {args.name!r}" if ok else f"no such node: {args.name!r}")
return 0 if ok else 1
if cmd in ("status", "ping"):
if cmd in {"status", "ping"}:
entry = reg.get(args.name)
if entry is None:
print(f"no such node: {args.name!r}", file=sys.stderr)

View file

@ -183,7 +183,7 @@ class RealtimeSession:
rid = (frame.get("response") or {}).get("id")
if rid:
self._last_response_id = rid
elif ftype in ("response.done", "response.completed", "response.cancelled"):
elif ftype in {"response.done", "response.completed", "response.cancelled"}:
break
elif ftype == "error":
err = frame.get("error") or frame

View file

@ -36,7 +36,7 @@ def check_meet_requirements() -> bool:
handlers relax the requirement when a node is addressed.
"""
import platform as _p
if _p.system().lower() not in ("linux", "darwin"):
if _p.system().lower() not in {"linux", "darwin"}:
return False
try:
import playwright # noqa: F401
@ -238,7 +238,7 @@ def handle_meet_join(args: Dict[str, Any], **_kw) -> str:
if not url:
return _err("url is required")
mode = (args.get("mode") or "transcribe").strip().lower()
if mode not in ("transcribe", "realtime"):
if mode not in {"transcribe", "realtime"}:
return _err(f"mode must be 'transcribe' or 'realtime' (got {mode!r})")
node = args.get("node")

View file

@ -628,7 +628,7 @@ def update_task(task_id: str, payload: UpdateTaskBody, board: Optional[str] = Qu
status_code=400,
detail="Cannot set status to 'running' directly; use the dispatcher/claim path",
)
elif s in ("todo", "triage"):
elif s in {"todo", "triage"}:
ok = _set_status_direct(conn, task_id, s)
else:
raise HTTPException(status_code=400, detail=f"unknown status: {s}")
@ -742,7 +742,7 @@ def _set_status_direct(
(task_id, run_id, json.dumps({"status": new_status}), int(time.time())),
)
# If we re-opened something, children may have gone stale.
if new_status in ("done", "ready"):
if new_status in {"done", "ready"}:
kanban_db.recompute_ready(conn)
return True
@ -868,7 +868,7 @@ def bulk_update(payload: BulkTaskBody, board: Optional[str] = Query(None)):
ok = kanban_db.unblock_task(conn, tid)
else:
ok = _set_status_direct(conn, tid, "ready")
elif s in ("todo", "running", "triage"):
elif s in {"todo", "running", "triage"}:
ok = _set_status_direct(conn, tid, s)
else:
entry.update(ok=False, error=f"unknown status {s!r}")

View file

@ -263,7 +263,7 @@ class ByteRoverMemoryProvider(MemoryProvider):
def on_memory_write(self, action: str, target: str, content: str) -> None:
"""Mirror built-in memory writes to ByteRover."""
if action not in ("add", "replace") or not content:
if action not in {"add", "replace"} or not content:
return
def _write():
@ -289,7 +289,7 @@ class ByteRoverMemoryProvider(MemoryProvider):
for msg in messages[-10:]: # last 10 messages
role = msg.get("role", "")
content = msg.get("content", "")
if isinstance(content, str) and content.strip() and role in ("user", "assistant"):
if isinstance(content, str) and content.strip() and role in {"user", "assistant"}:
parts.append(f"{role}: {content[:500]}")
if not parts:

View file

@ -416,7 +416,7 @@ def _build_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | No
current_base_url = config.get("llm_base_url") or os.environ.get("HINDSIGHT_API_LLM_BASE_URL", "")
# The embedded daemon expects OpenAI wire format for these providers.
daemon_provider = "openai" if current_provider in ("openai_compatible", "openrouter") else current_provider
daemon_provider = "openai" if current_provider in {"openai_compatible", "openrouter"} else current_provider
env_values = {
"HINDSIGHT_API_LLM_PROVIDER": str(daemon_provider),
@ -596,7 +596,7 @@ class HindsightMemoryProvider(MemoryProvider):
try:
cfg = _load_config()
mode = cfg.get("mode", "cloud")
if mode in ("local", "local_embedded"):
if mode in {"local", "local_embedded"}:
available, _ = _check_local_runtime()
return available
if mode == "local_external":
@ -888,7 +888,7 @@ class HindsightMemoryProvider(MemoryProvider):
from hindsight import HindsightEmbedded
HindsightEmbedded.__del__ = lambda self: None
llm_provider = self._config.get("llm_provider", "")
if llm_provider in ("openai_compatible", "openrouter"):
if llm_provider in {"openai_compatible", "openrouter"}:
llm_provider = "openai"
logger.debug("Creating HindsightEmbedded client (profile=%s, provider=%s)",
self._config.get("profile", "hermes"), llm_provider)
@ -1132,7 +1132,7 @@ class HindsightMemoryProvider(MemoryProvider):
self._mode = "disabled"
return
self._api_key = self._config.get("apiKey") or self._config.get("api_key") or os.environ.get("HINDSIGHT_API_KEY", "")
default_url = _DEFAULT_LOCAL_URL if self._mode in ("local_embedded", "local_external") else _DEFAULT_API_URL
default_url = _DEFAULT_LOCAL_URL if self._mode in {"local_embedded", "local_external"} else _DEFAULT_API_URL
self._api_url = self._config.get("api_url") or os.environ.get("HINDSIGHT_API_URL", default_url)
self._llm_base_url = self._config.get("llm_base_url", "")
@ -1152,10 +1152,10 @@ class HindsightMemoryProvider(MemoryProvider):
self._budget = budget if budget in _VALID_BUDGETS else "mid"
memory_mode = self._config.get("memory_mode", "hybrid")
self._memory_mode = memory_mode if memory_mode in ("context", "tools", "hybrid") else "hybrid"
self._memory_mode = memory_mode if memory_mode in {"context", "tools", "hybrid"} else "hybrid"
prefetch_method = self._config.get("recall_prefetch_method") or self._config.get("prefetch_method", "recall")
self._prefetch_method = prefetch_method if prefetch_method in ("recall", "reflect") else "recall"
self._prefetch_method = prefetch_method if prefetch_method in {"recall", "reflect"} else "recall"
# Bank options
self._bank_mission = self._config.get("bank_mission", "")

View file

@ -283,7 +283,7 @@ class HonchoMemoryProvider(MemoryProvider):
# ----- Port #4053: cron guard -----
agent_context = kwargs.get("agent_context", "")
platform = kwargs.get("platform", "cli")
if agent_context in ("cron", "flush") or platform == "cron":
if agent_context in {"cron", "flush"} or platform == "cron":
logger.debug("Honcho skipped: cron/flush context (agent_context=%s, platform=%s)",
agent_context, platform)
self._cron_skipped = True
@ -404,7 +404,7 @@ class HonchoMemoryProvider(MemoryProvider):
# pop_context_result() in prefetch(). Dialectic prewarm runs the
# full configured depth and writes into _prefetch_result so turn 1
# consumes the result directly.
if self._recall_mode in ("context", "hybrid"):
if self._recall_mode in {"context", "hybrid"}:
try:
self._manager.prefetch_context(self._session_key)
except Exception as e:

View file

@ -233,7 +233,7 @@ _profile_override: str | None = None
def _host_key() -> str:
"""Return the active Honcho host key, derived from the current Hermes profile."""
if _profile_override:
if _profile_override in ("default", "custom"):
if _profile_override in {"default", "custom"}:
return HOST
return f"{HOST}.{_profile_override}"
return resolve_active_host()
@ -295,13 +295,13 @@ def _resolve_api_key(cfg: dict) -> str:
parsed = urlparse(base_url)
except (TypeError, ValueError):
parsed = None
if parsed and parsed.scheme in ("http", "https") and parsed.netloc:
if parsed and parsed.scheme in {"http", "https"} and parsed.netloc:
return "local"
# Schemeless but looks like a host (contains '.' or ':' and isn't
# a boolean literal): let it through so legacy configs don't
# regress into "no API key configured" when they previously worked.
lowered = base_url.lower()
if lowered not in ("true", "false", "none", "null") and any(
if lowered not in {"true", "false", "none", "null"} and any(
c in base_url for c in ".:"
) and not base_url.isdigit():
return "local"
@ -334,7 +334,7 @@ def _ensure_sdk_installed() -> bool:
print(" honcho-ai is not installed.")
answer = _prompt("Install it now? (honcho-ai>=2.0.1)", default="y")
if answer.lower() not in ("y", "yes"):
if answer.lower() not in {"y", "yes"}:
print(" Skipping install. Run: pip install 'honcho-ai>=2.0.1'\n")
return False
@ -382,7 +382,7 @@ def cmd_setup(args) -> None:
for h in ("localhost", "127.0.0.1", "::1")
) else "cloud"
deploy = _prompt("Cloud or local?", default=current_deploy)
is_local = deploy.lower() in ("local", "l")
is_local = deploy.lower() in {"local", "l"}
# Clean up legacy snake_case key
cfg.pop("base_url", None)
@ -441,7 +441,7 @@ def cmd_setup(args) -> None:
print(" directional -- all observations on, each AI peer builds its own view (default)")
print(" unified -- shared pool, user observes self, AI observes others only")
new_obs = _prompt("Observation mode", default=current_obs)
if new_obs in ("unified", "directional"):
if new_obs in {"unified", "directional"}:
hermes_host["observationMode"] = new_obs
else:
hermes_host["observationMode"] = "directional"
@ -457,17 +457,17 @@ def cmd_setup(args) -> None:
try:
hermes_host["writeFrequency"] = int(new_wf)
except (ValueError, TypeError):
hermes_host["writeFrequency"] = new_wf if new_wf in ("async", "turn", "session") else "async"
hermes_host["writeFrequency"] = new_wf if new_wf in {"async", "turn", "session"} else "async"
# --- 6. Recall mode ---
_raw_recall = hermes_host.get("recallMode") or cfg.get("recallMode", "hybrid")
current_recall = "hybrid" if _raw_recall not in ("hybrid", "context", "tools") else _raw_recall
current_recall = "hybrid" if _raw_recall not in {"hybrid", "context", "tools"} else _raw_recall
print("\n Recall mode:")
print(" hybrid -- auto-injected context + Honcho tools available (default)")
print(" context -- auto-injected context only, Honcho tools hidden")
print(" tools -- Honcho tools only, no auto-injected context")
new_recall = _prompt("Recall mode", default=current_recall)
if new_recall in ("hybrid", "context", "tools"):
if new_recall in {"hybrid", "context", "tools"}:
hermes_host["recallMode"] = new_recall
# --- 7. Context token budget ---
@ -477,7 +477,7 @@ def cmd_setup(args) -> None:
print(" uncapped -- no limit (default)")
print(" N -- token limit per turn (e.g. 1200)")
new_ctx_tokens = _prompt("Context tokens", default=current_display)
if new_ctx_tokens.strip().lower() in ("none", "uncapped", "no limit"):
if new_ctx_tokens.strip().lower() in {"none", "uncapped", "no limit"}:
hermes_host.pop("contextTokens", None)
elif new_ctx_tokens.strip() == "":
pass # keep current
@ -517,7 +517,7 @@ def cmd_setup(args) -> None:
print(" high -- complex behavioral patterns")
print(" max -- thorough audit-level analysis")
new_reasoning = _prompt("Reasoning level", default=current_reasoning)
if new_reasoning in ("minimal", "low", "medium", "high", "max"):
if new_reasoning in {"minimal", "low", "medium", "high", "max"}:
hermes_host["dialecticReasoningLevel"] = new_reasoning
else:
hermes_host["dialecticReasoningLevel"] = "low"
@ -530,7 +530,7 @@ def cmd_setup(args) -> None:
print(" per-repo -- one session per git repository")
print(" global -- single session across all directories")
new_strat = _prompt("Session strategy", default=current_strat)
if new_strat in ("per-session", "per-repo", "per-directory", "global"):
if new_strat in {"per-session", "per-repo", "per-directory", "global"}:
hermes_host["sessionStrategy"] = new_strat
hermes_host["enabled"] = True
@ -1130,7 +1130,7 @@ def cmd_migrate(args) -> None:
print(" Paste the key when prompted.")
print()
answer = _prompt(" Run 'hermes honcho setup' now?", default="y")
if answer.lower() in ("y", "yes"):
if answer.lower() in {"y", "yes"}:
cmd_setup(args)
cfg = _read_config()
has_key = bool(cfg.get("apiKey", ""))
@ -1176,7 +1176,7 @@ def cmd_migrate(args) -> None:
print(" hermes honcho migrate — this step handles it interactively")
if has_key:
answer = _prompt(" Upload user memory files to Honcho now?", default="y")
if answer.lower() in ("y", "yes"):
if answer.lower() in {"y", "yes"}:
try:
from plugins.memory.honcho.client import (
HonchoClientConfig,
@ -1226,7 +1226,7 @@ def cmd_migrate(args) -> None:
print()
if has_key:
answer = _prompt(" Seed AI identity from all detected files now?", default="y")
if answer.lower() in ("y", "yes"):
if answer.lower() in {"y", "yes"}:
try:
from plugins.memory.honcho.client import (
HonchoClientConfig,

View file

@ -47,7 +47,7 @@ def resolve_active_host() -> str:
try:
from hermes_cli.profiles import get_active_profile_name
profile = get_active_profile_name()
if profile and profile not in ("default", "custom"):
if profile and profile not in {"default", "custom"}:
return f"{HOST}.{profile}"
except Exception:
pass
@ -653,7 +653,7 @@ class HonchoClientConfig:
return base
# per-directory: one Honcho session per working directory (default)
if self.session_strategy in ("per-directory", "per-session"):
if self.session_strategy in {"per-directory", "per-session"}:
base = Path(cwd).name
if self.session_peer_prefix and self.peer_name:
return f"{self.peer_name}-{base}"

View file

@ -357,7 +357,7 @@ def _is_windows_absolute_path(value: str) -> bool:
len(value) >= 3
and value[0].isalpha()
and value[1] == ":"
and value[2] in ("/", "\\")
and value[2] in {"/", "\\"}
)
@ -381,7 +381,7 @@ def _is_local_path_reference(value: str) -> bool:
def _path_from_file_uri(uri: str) -> Path | str:
parsed = urlparse(uri)
if parsed.netloc not in ("", "localhost"):
if parsed.netloc not in {"", "localhost"}:
return f"Unsupported non-local file URI: {uri}"
return Path(url2pathname(parsed.path)).expanduser()
@ -755,7 +755,7 @@ class OpenVikingMemoryProvider(MemoryProvider):
level = args.get("level", "overview")
summary_level = level in ("abstract", "overview")
summary_level = level in {"abstract", "overview"}
# OpenViking expects directory URIs for pseudo summary files
# (e.g. viking://user/hermes/.overview.md).
resolved_uri = self._normalize_summary_uri(uri) if summary_level else uri
@ -832,7 +832,7 @@ class OpenVikingMemoryProvider(MemoryProvider):
result = self._unwrap_result(resp)
# Format list/tree results for readability
if action in ("list", "tree"):
if action in {"list", "tree"}:
raw_entries = result
if isinstance(result, dict):
raw_entries = result.get("entries") or result.get("items") or result.get("children") or []
@ -887,7 +887,7 @@ class OpenVikingMemoryProvider(MemoryProvider):
payload: Dict[str, Any] = {}
for key in ("reason", "to", "parent", "instruction", "wait", "timeout"):
if key in args and args[key] not in (None, ""):
if key in args and args[key] not in {None, ""}:
payload[key] = args[key]
parsed_url = urlparse(url)

View file

@ -88,9 +88,9 @@ def _as_bool(value: Any, default: bool) -> bool:
return value
if isinstance(value, str):
lowered = value.strip().lower()
if lowered in ("true", "1", "yes", "y", "on"):
if lowered in {"true", "1", "yes", "y", "on"}:
return True
if lowered in ("false", "0", "no", "n", "off"):
if lowered in {"false", "0", "no", "n", "off"}:
return False
return default
@ -508,7 +508,7 @@ class SupermemoryMemoryProvider(MemoryProvider):
self._allowed_containers = [self._container_tag] + list(self._custom_containers)
agent_context = kwargs.get("agent_context", "")
self._write_enabled = agent_context not in ("cron", "flush", "subagent")
self._write_enabled = agent_context not in {"cron", "flush", "subagent"}
self._active = bool(self._api_key)
self._client = None
if self._active:
@ -598,7 +598,7 @@ class SupermemoryMemoryProvider(MemoryProvider):
cleaned = []
for message in messages or []:
role = message.get("role")
if role not in ("user", "assistant"):
if role not in {"user", "assistant"}:
continue
content = _clean_text_for_capture(str(message.get("content", "")))
if content:

View file

@ -74,9 +74,9 @@ class DeepSeekProfile(ProviderProfile):
# its server default (currently high).
if isinstance(reasoning_config, dict):
effort = (reasoning_config.get("effort") or "").strip().lower()
if effort in ("xhigh", "max"):
if effort in {"xhigh", "max"}:
top_level["reasoning_effort"] = "max"
elif effort in ("low", "medium", "high"):
elif effort in {"low", "medium", "high"}:
top_level["reasoning_effort"] = effort
return extra_body, top_level

View file

@ -37,7 +37,7 @@ class KimiProfile(ProviderProfile):
# Enabled
extra_body["thinking"] = {"type": "enabled"}
effort = (reasoning_config.get("effort") or "").strip().lower()
if effort in ("low", "medium", "high"):
if effort in {"low", "medium", "high"}:
top_level["reasoning_effort"] = effort
else:
top_level["reasoning_effort"] = "medium"

View file

@ -1539,7 +1539,7 @@ class GoogleChatAdapter(BasePlatformAdapter):
if sender_email and space_name:
self._last_sender_by_chat[space_name] = sender_email.strip().lower()
chat_type = "dm" if space_type in ("DIRECT_MESSAGE", "DM") else "group"
chat_type = "dm" if space_type in {"DIRECT_MESSAGE", "DM"} else "group"
text = msg.get("argumentText") or msg.get("text") or ""
text = text.strip()
@ -1935,7 +1935,7 @@ class GoogleChatAdapter(BasePlatformAdapter):
return True
except HttpError as exc:
status = getattr(getattr(exc, "resp", None), "status", None)
if status in (403, 404):
if status in {403, 404}:
return False
logger.debug(
"[GoogleChat] delete_message failed: %s",
@ -1958,7 +1958,7 @@ class GoogleChatAdapter(BasePlatformAdapter):
update_mask = ",".join(update_mask_fields) or "text"
# Patch body cannot carry thread (immutable).
patch_body = {k: v for k, v in body.items() if k not in ("thread",)}
patch_body = {k: v for k, v in body.items() if k not in {"thread",}}
def _do_patch() -> Dict[str, Any]:
return (
@ -2791,7 +2791,7 @@ class GoogleChatAdapter(BasePlatformAdapter):
upload_resp = await asyncio.to_thread(_upload)
except HttpError as exc:
status = getattr(getattr(exc, "resp", None), "status", None)
if status in (401, 403):
if status in {401, 403}:
logger.warning(
"[GoogleChat] media.upload auth failure for identity=%s "
"(token revoked or scope missing) — falling back to "
@ -2927,7 +2927,7 @@ class GoogleChatAdapter(BasePlatformAdapter):
display = info.get("displayName") or chat_id
return {
"name": display,
"type": "dm" if space_type in ("DIRECT_MESSAGE", "DM") else "group",
"type": "dm" if space_type in {"DIRECT_MESSAGE", "DM"} else "group",
"chat_id": chat_id,
}

View file

@ -112,7 +112,7 @@ class IRCAdapter(BasePlatformAdapter):
self.nickname = os.getenv("IRC_NICKNAME") or extra.get("nickname", "hermes-bot")
self.channel = os.getenv("IRC_CHANNEL") or extra.get("channel", "")
self.use_tls = (
os.getenv("IRC_USE_TLS", "").lower() in ("1", "true", "yes")
os.getenv("IRC_USE_TLS", "").lower() in {"1", "true", "yes"}
if os.getenv("IRC_USE_TLS")
else extra.get("use_tls", True)
)
@ -680,7 +680,7 @@ def _env_enablement() -> dict | None:
seed["nickname"] = nickname
use_tls = os.getenv("IRC_USE_TLS", "").strip().lower()
if use_tls:
seed["use_tls"] = use_tls in ("1", "true", "yes")
seed["use_tls"] = use_tls in {"1", "true", "yes"}
# Passwords live in PlatformConfig.extra as well for back-compat with
# existing config.yaml users; env-reads at construct time still win.
if os.getenv("IRC_SERVER_PASSWORD"):
@ -756,7 +756,7 @@ async def _standalone_send(
nickname = os.getenv("IRC_NICKNAME") or extra.get("nickname", "hermes-bot")
use_tls_env = os.getenv("IRC_USE_TLS")
if use_tls_env is not None:
use_tls = use_tls_env.lower() in ("1", "true", "yes")
use_tls = use_tls_env.lower() in {"1", "true", "yes"}
else:
use_tls = bool(extra.get("use_tls", True))
@ -821,7 +821,7 @@ async def _standalone_send(
await _raw(f"PONG :{payload}")
elif cmd == "001":
registered = True
elif cmd in ("432", "433"):
elif cmd in {"432", "433"}:
nick_attempts += 1
if nick_attempts > max_nick_attempts:
return {"error": "IRC standalone send: too many nick collisions"}
@ -829,7 +829,7 @@ async def _standalone_send(
# mutated value, so the suffix stays bounded.
standalone_nick = f"{nick_base}-cron-{nick_attempts}"[:30]
await _raw(f"NICK {standalone_nick}")
elif cmd in ("464", "465"):
elif cmd in {"464", "465"}:
return {"error": f"IRC standalone send: server rejected client ({cmd})"}
if nickserv_password:
@ -860,9 +860,9 @@ async def _standalone_send(
if jcmd == "PING":
payload = jmsg["params"][0] if jmsg["params"] else ""
await _raw(f"PONG :{payload}")
elif jcmd in ("366", "JOIN"):
elif jcmd in {"366", "JOIN"}:
joined = True
elif jcmd in ("403", "405", "471", "473", "474", "475"):
elif jcmd in {"403", "405", "471", "473", "474", "475"}:
return {"error": f"IRC standalone send: JOIN {target} rejected ({jcmd})"}
# Bytes-aware per-line splitting so multi-line plain text never

View file

@ -325,7 +325,7 @@ class RequestCache:
def mark_delivered(self, request_id: str) -> None:
entry = self._entries.get(request_id)
if entry is None or entry.state not in (State.READY, State.ERROR):
if entry is None or entry.state not in {State.READY, State.ERROR}:
return
entry.state = State.DELIVERED
entry.updated_at = time.time()
@ -614,7 +614,7 @@ def _truthy_env(name: str, default: bool = False) -> bool:
v = os.getenv(name)
if v is None:
return default
return v.strip().lower() in ("1", "true", "yes", "on")
return v.strip().lower() in {"1", "true", "yes", "on"}
# ---------------------------------------------------------------------------
@ -910,7 +910,7 @@ class LineAdapter(BasePlatformAdapter):
await self._handle_message_event(event)
elif event_type == "postback":
await self._handle_postback_event(event)
elif event_type in ("follow", "unfollow", "join", "leave"):
elif event_type in {"follow", "unfollow", "join", "leave"}:
logger.info("LINE: lifecycle event %s from %s", event_type, source)
else:
logger.debug("LINE: ignoring event type %r", event_type)
@ -939,7 +939,7 @@ class LineAdapter(BasePlatformAdapter):
if msg_type == "text":
text = msg.get("text", "") or ""
elif msg_type in ("image", "audio", "video", "file"):
elif msg_type in {"image", "audio", "video", "file"}:
local_path = await self._download_media(message_id, msg_type)
if local_path:
media_urls.append(local_path)

View file

@ -101,11 +101,11 @@ def _guess_extension(data: bytes) -> str:
def _is_image_ext(ext: str) -> bool:
return ext.lower() in (".jpg", ".jpeg", ".png", ".gif", ".webp")
return ext.lower() in {".jpg", ".jpeg", ".png", ".gif", ".webp"}
def _is_audio_ext(ext: str) -> bool:
return ext.lower() in (".mp3", ".wav", ".ogg", ".m4a", ".aac")
return ext.lower() in {".mp3", ".wav", ".ogg", ".m4a", ".aac"}
# ---------------------------------------------------------------------------
@ -326,12 +326,12 @@ class SimplexAdapter(BasePlatformAdapter):
# Filter out messages sent by us (direction == "snd")
meta = chat_item.get("meta") or {}
direction = (meta.get("itemStatus") or {}).get("type", "")
if direction in ("sndSent", "sndSentDirect", "sndSentViaProxy", "sndNew"):
if direction in {"sndSent", "sndSentDirect", "sndSentViaProxy", "sndNew"}:
return
# Determine chat type and IDs
chat_type_raw = chat_info.get("type", "")
is_group = chat_type_raw in ("group", "groupInfo")
is_group = chat_type_raw in {"group", "groupInfo"}
if is_group:
group_info = chat_info.get("groupInfo") or chat_info.get("group") or {}
@ -374,7 +374,7 @@ class SimplexAdapter(BasePlatformAdapter):
media_urls: List[str] = []
media_types: List[str] = []
file_info = chat_item.get("file") or {}
if file_info and file_info.get("fileStatus") not in ("cancelled", "error"):
if file_info and file_info.get("fileStatus") not in {"cancelled", "error"}:
file_id = file_info.get("fileId")
file_name = file_info.get("fileName", "file")
if file_id:

View file

@ -841,7 +841,7 @@ class TeamsAdapter(BasePlatformAdapter):
# bot silently treated every clicker as authorized — meaning any
# Teams user who could message the bot could approve dangerous commands.
allowed_csv = os.getenv("TEAMS_ALLOWED_USERS", "").strip()
allow_all = os.getenv("TEAMS_ALLOW_ALL_USERS", "").strip().lower() in ("1", "true", "yes")
allow_all = os.getenv("TEAMS_ALLOW_ALL_USERS", "").strip().lower() in {"1", "true", "yes"}
if not allow_all:
if not allowed_csv:

View file

@ -99,15 +99,15 @@ def teams_pipeline_command(args: argparse.Namespace) -> int:
return 2
try:
if action in ("list", "ls"):
if action in {"list", "ls"}:
_cmd_list(args)
elif action == "show":
_cmd_show(args)
elif action in ("run", "replay"):
elif action in {"run", "replay"}:
_cmd_run(args)
elif action in ("fetch", "test"):
elif action in {"fetch", "test"}:
_cmd_fetch(args)
elif action in ("subscriptions", "subs"):
elif action in {"subscriptions", "subs"}:
_cmd_subscriptions(args)
elif action == "subscribe":
_cmd_subscribe(args)
@ -117,7 +117,7 @@ def teams_pipeline_command(args: argparse.Namespace) -> int:
_cmd_delete_subscription(args)
elif action == "maintain-subscriptions":
_cmd_maintain_subscriptions(args)
elif action in ("token-health", "token"):
elif action in {"token-health", "token"}:
_cmd_token_health(args)
elif action == "validate":
_cmd_validate(args)

View file

@ -33,7 +33,7 @@ def _meeting_path(meeting_ref: TeamsMeetingRef | str) -> str:
def _wrap_graph_error(exc: MicrosoftGraphAPIError, *, missing_message: str) -> TeamsMeetingError:
if exc.status_code in (401, 403):
if exc.status_code in {401, 403}:
return TeamsMeetingPermissionError(str(exc))
if exc.status_code == 404:
return TeamsMeetingNotFoundError(missing_message)
@ -286,7 +286,7 @@ async def fetch_call_record_artifact(
try:
payload = await client.get_json(f"/communications/callRecords/{quote(call_record_id, safe='')}")
except MicrosoftGraphAPIError as exc:
if exc.status_code in (401, 403) and allow_permission_errors:
if exc.status_code in {401, 403} and allow_permission_errors:
return None
if exc.status_code == 404:
return None

View file

@ -145,7 +145,7 @@ class MeetingArtifact:
metadata: dict[str, Any] = field(default_factory=dict)
def __post_init__(self) -> None:
if self.artifact_type not in ("transcript", "recording", "call_record"):
if self.artifact_type not in {"transcript", "recording", "call_record"}:
raise ValueError(
"MeetingArtifact.artifact_type must be transcript, recording, or call_record."
)

View file

@ -62,7 +62,7 @@ def build_pipeline_runtime_config(gateway_config: Any) -> dict[str, Any]:
"chat_id",
):
value = teams_extra.get(key)
if value not in (None, ""):
if value not in {None, ""}:
teams_delivery[key] = value
if teams_delivery: