The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(codex): keep the read-only quota guard, drop the preserve_corrupt plumbing
kshitijk4poora25542c69574
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 4e5043dd69b..3473e436496 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -528,7 +528,7 @@ def _load_global_auth_store() -> Dict[str, Any]:except Exception:passtry:- store = _load_auth_store(global_path, preserve_corrupt=False)+ store = _load_auth_store(global_path)except Exception:_global_auth_store_cache = Nonereturn {}@@ -658,9 +658,7 @@ def _empty_auth_store() -> Dict[str, Any]:return {"version": AUTH_STORE_VERSION, "providers": {}}-def _load_auth_store(- auth_file: Optional[Path] = None, *, preserve_corrupt: bool = True,-) -> Dict[str, Any]:+def _load_auth_store(auth_file: Optional[Path] = None) -> Dict[str, Any]:auth_file = auth_file or _auth_file_path()if not auth_file.exists():return _empty_auth_store()@@ -679,21 +677,18 @@ def _load_auth_store(# Genuine corruption: unparseable JSON or non-UTF-8 bytes. Preserve a copy, but never# advertise a backup that was not written.corrupt_path = auth_file.with_suffix(".json.corrupt")- preserved = False- if preserve_corrupt:- try:- shutil.copy2(auth_file, corrupt_path)- preserved = True- except Exception:- logger.debug(- "auth: could not preserve a copy of the corrupt store at %s",- corrupt_path, exc_info=True)+ try:+ shutil.copy2(auth_file, corrupt_path)+ preserved = True+ except Exception:+ preserved = False+ logger.debug("auth: could not preserve a copy of the corrupt store at %s", corrupt_path,+ exc_info=True)logger.warning(- "auth: failed to parse %s (%s), starting with empty store.%s",+ "auth: failed to parse %s (%s), starting with empty store. %s %s",auth_file, exc,- (f" Corrupt file preserved at {corrupt_path}" if preserved else- " Corrupt backup skipped for this read-only operation." if not preserve_corrupt else- f" A copy could NOT be preserved at {corrupt_path}"))+ "Corrupt file preserved at" if preserved else "A copy could NOT be preserved at",+ corrupt_path)return _empty_auth_store()if isinstance(raw, dict) and (@@ -872,16 +867,12 @@ def is_runtime_provider_routable(provider_id: str) -> bool:return True-def read_credential_pool(- provider_id: Optional[str] = None, *, preserve_corrupt: bool = True,-) -> Dict[str, Any]:+def read_credential_pool(provider_id: Optional[str] = None) -> Dict[str, Any]:"""Return the persisted credential pool, or one provider slice.In profile mode the global-root ``auth.json`` is a read-only fallback applied per provider ONLYwhen the profile has zero entries for it (``hermes auth add`` in the profile shadows global)."""- store = (_load_auth_store() if preserve_corrupt else- _load_auth_store(preserve_corrupt=False))- pool = store.get("credential_pool")+ pool = _load_auth_store().get("credential_pool")pool = pool if isinstance(pool, dict) else {}global_pool = _load_global_auth_store().get("credential_pool")global_pool = global_pool if isinstance(global_pool, dict) else {}diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex d3f4e8a55d4..45e5f6368fe 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -10,15 +10,15 @@ so ``hermes_cli.auth.<name>`` patches still intercept (and no import cycle).from __future__ import annotations+import loggingimport hashlibimport json-import loggingimport osimport threadingimport timefrom contextlib import suppressfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple, cast+from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuplefrom hermes_cli.auth_constants import (_decode_jwt_claims, AUTH_LOCK_TIMEOUT_SECONDS, AuthError,CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL,@@ -78,26 +78,19 @@ def _codex_runtime_result("source": source, "last_refresh": last_refresh, "auth_mode": "chatgpt"}-def _load_auth_store_maybe_locked(- lock: bool, *, preserve_corrupt: bool = True,-) -> Dict[str, Any]:+def _load_auth_store_maybe_locked(lock: bool) -> Dict[str, Any]:"""Load the auth store, taking the cross-process lock unless the caller already holds it."""from hermes_cli.auth import _auth_store_lock, _load_auth_storeif lock:with _auth_store_lock():- return (_load_auth_store() if preserve_corrupt else- _load_auth_store(preserve_corrupt=False))- return (_load_auth_store() if preserve_corrupt else- _load_auth_store(preserve_corrupt=False))+ return _load_auth_store()+ return _load_auth_store()-def _read_codex_tokens(- *, _lock: bool = True, _preserve_corrupt: bool = True,-) -> Dict[str, Any]:+def _read_codex_tokens(*, _lock: bool = True) -> Dict[str, Any]:"""Read Codex OAuth tokens from Hermes auth store (~/.hermes/auth.json)."""from hermes_cli.auth import _load_provider_state, _nonempty_str- auth_store = _load_auth_store_maybe_locked(- _lock, preserve_corrupt=_preserve_corrupt)+ auth_store = _load_auth_store_maybe_locked(_lock)state = _load_provider_state(auth_store, "openai-codex")if not state:raise _codex_err(_NO_CREDENTIALS_MSG.format(relogin=_codex_relogin_command()),@@ -585,7 +578,7 @@ def resolve_codex_runtime_credentials(# A read-only report takes no store lock: ``_save_auth_store`` replaces auth.json# atomically, and materialising ``auth.lock`` is itself a write a diagnostic must not# make. No recovery follows a read-only read, so no observed token is needed.- data = _read_codex_tokens(_lock=False, _preserve_corrupt=False)+ data = _read_codex_tokens(_lock=False)else:with _auth_store_lock():# Observe the singleton in the same locked snapshot the read validates, so recovery@@ -604,7 +597,7 @@ def resolve_codex_runtime_credentials(if imported:data = {"tokens": imported, "last_refresh": imported.get("last_refresh")}if data is None:- pool_token = _pool_codex_access_token(preserve_corrupt=not read_only)+ pool_token = _pool_codex_access_token()if pool_token and force_refresh and not read_only:# Pool-only setup: a forced refresh must rotate the pool entry, not resend its token.from agent.credential_pool import load_pool@@ -612,10 +605,12 @@ def resolve_codex_runtime_credentials(pool_token = refreshed.runtime_api_key if refreshed is not None else ""if pool_token:return _codex_runtime_result(pool_token, source="credential_pool", last_refresh=None)- pool_rate_limit = _codex_pool_rate_limit_status(preserve_corrupt=not read_only)+ pool_rate_limit = _codex_pool_rate_limit_status()if pool_rate_limit:- # Before surfacing the persisted cooldown, the runtime may ask whether quota reset early.- # Read-only callers must never refresh OAuth, query usage or rewrite cooldown state.+ # Before surfacing the persisted cooldown, ask the usage endpoint whether the quota+ # reset early (banked reset redeemed, plan upgraded): ``last_error_reset_at`` can be+ # days in the future while the account is already usable again. Never from a+ # read-only caller: the picker fingerprint resolves on every cache-only read.if not read_only and _probe_codex_pool_entry_quota_restored(pool_rate_limit):logger.info("Codex quota restored upstream — clearing stale pool cooldown(s).")clear_codex_pool_quota_cooldowns()@@ -847,9 +842,7 @@ def _codex_pool_dicts(entries: Optional[List[Any]]) -> Iterator[Dict[str, Any]]:yield entry-def _codex_pool_rate_limit_status(- *, preserve_corrupt: bool = True,-) -> Optional[Dict[str, Any]]:+def _codex_pool_rate_limit_status() -> Optional[Dict[str, Any]]:"""Return metadata for a pool-only Codex credential in quota cooldown.Reads through ``read_credential_pool`` so a named profile with no Codex rows of its own sees@@ -858,9 +851,7 @@ def _codex_pool_rate_limit_status(from agent.credential_pool import _parse_absolute_timestamptry:now = time.time()- entries = cast(List[Any], read_credential_pool(- "openai-codex", preserve_corrupt=preserve_corrupt))- for entry in _codex_pool_dicts(entries):+ for entry in _codex_pool_dicts(read_credential_pool("openai-codex")):token = entry.get("access_token")if not _nonempty_str(token) or not _entry_is_rate_limit_exhausted(entry):continue@@ -884,7 +875,7 @@ def _pool_entries(auth_store: Dict[str, Any], provider_id: str) -> Optional[Listreturn entries if isinstance(entries, list) else None-def _pool_codex_access_token(*, preserve_corrupt: bool = True) -> str:+def _pool_codex_access_token() -> str:"""First non-empty pool access_token not in an exhaustion cooldown window, else "".Fallback for ``resolve_codex_runtime_credentials`` when the singleton has no creds; reads@@ -893,9 +884,7 @@ def _pool_codex_access_token(*, preserve_corrupt: bool = True) -> str:from agent.credential_pool import _parse_absolute_timestampfrom hermes_cli.auth import _nonempty_str, read_credential_pooltry:- entries = cast(List[Any], read_credential_pool(- "openai-codex", preserve_corrupt=preserve_corrupt))- for entry in _codex_pool_dicts(entries):+ for entry in _codex_pool_dicts(read_credential_pool("openai-codex")):token = entry.get("access_token")# Same normaliser as ``_codex_pool_rate_limit_status``: a millisecond epoch compared# raw reads as far-future here and as elapsed there, hiding a usable entry (#103349).diff --git a/tests/hermes_cli/test_global_auth_store_memo.py b/tests/hermes_cli/test_global_auth_store_memo.pyindex 4c853506fc0..a8f062cfce3 100644--- a/tests/hermes_cli/test_global_auth_store_memo.py+++ b/tests/hermes_cli/test_global_auth_store_memo.py@@ -66,9 +66,9 @@ class TestLoadGlobalAuthStoreMemo:reads = {"n": 0}orig = auth_mod._load_auth_store- def counting_load(store_path=None, **kwargs):+ def counting_load(store_path=None):reads["n"] += 1- return orig(store_path, **kwargs)+ return orig(store_path)monkeypatch.setattr(auth_mod, "_load_auth_store", counting_load)@@ -90,9 +90,9 @@ class TestLoadGlobalAuthStoreMemo:reads = {"n": 0}orig = auth_mod._load_auth_store- def counting_load(store_path=None, **kwargs):+ def counting_load(store_path=None):reads["n"] += 1- return orig(store_path, **kwargs)+ return orig(store_path)monkeypatch.setattr(auth_mod, "_load_auth_store", counting_load)diff --git a/tests/hermes_cli/test_oauth_status_pool_observation.py b/tests/hermes_cli/test_oauth_status_pool_observation.pyindex 7686c6e200e..a0e5cad2b1f 100644--- a/tests/hermes_cli/test_oauth_status_pool_observation.py+++ b/tests/hermes_cli/test_oauth_status_pool_observation.py@@ -133,25 +133,6 @@ def test_read_only_resolver_never_probes_or_mutates_an_exhausted_pool(tmp_path,assert not (home / "auth.lock").exists()-def test_read_only_resolver_does_not_back_up_a_malformed_auth_store(tmp_path, monkeypatch):- from hermes_cli.auth import resolve_codex_runtime_credentials-- home = tmp_path / "home"- home.mkdir()- auth_path = home / "auth.json"- malformed = b'{"credential_pool":'- auth_path.write_bytes(malformed)- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv("CODEX_HOME", str(tmp_path / "missing-codex-home"))-- with pytest.raises(AuthError):- resolve_codex_runtime_credentials(read_only=True)-- assert auth_path.read_bytes() == malformed- assert not auth_path.with_suffix(".json.corrupt").exists()- assert not (home / "auth.lock").exists()--def _singleton_only_codex_home(tmp_path, monkeypatch, *, tokens: dict, codex_cli_tokens: dict):"""HERMES_HOME whose Codex credentials are the ``providers.openai-codex`` singleton only, with avalid Codex CLI login sitting beside it in ``CODEX_HOME``."""