Skip to content

The agent that grows with you

refactor(auth): trim the guest handoff to the paths sign-in uses

alt-glitch18de67093ac5
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 927c98b2002..294598c622d 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -170,7 +170,7 @@ export interface AppHandoffStatus {
lines: string[]
moved_toolkits?: string[]
probably_moved?: boolean
- state: 'claimed' | 'failed' | 'gone' | 'idle' | 'paused' | 'pending' | 'retrying'
+ state: 'claimed' | 'failed' | 'gone' | 'idle' | 'pending' | 'retrying'
updated_at?: null | string
}
diff --git a/hermes_cli/anon_sign_in.py b/hermes_cli/anon_sign_in.py
index 2bd4601c679..9c2d56fcb36 100644
--- a/hermes_cli/anon_sign_in.py
+++ b/hermes_cli/anon_sign_in.py
@@ -238,8 +238,8 @@ def _handoff_lines(results: list[dict[str, Any]]) -> tuple[str, ...]:
def _handoff_status(results: list[dict[str, Any]], replaced: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
"""The handoff a completed sign-in reports (``guest_handoff.wire_status`` form): the latest record its
- own run attempted, else the replaced free tier's saved record (another process held the claim, or
- the run's budget ran out first), else None when it replaced no free tier. Read under the scope."""
+ own run attempted, else the replaced free tier's saved record (another process held it), else
+ None when it replaced no free tier. Read under the scope."""
from hermes_cli import anon_auth as _core
from hermes_cli.guest_handoff import record_status, wire_status
if results:
@@ -283,7 +283,7 @@ def run_sign_in(
from hermes_cli.auth_device_flow import DeviceFlowCancelled, _request_device_code
from hermes_cli.auth_error_copy import is_device_code_expired
from hermes_cli.auth_nous import _nous_http_client, _nous_portal_base_url
- from hermes_cli.guest_handoff import deferred
+ from hermes_cli.guest_handoff import drain
is_cancelled = cancelled or (lambda: False)
open_scope = scope or contextlib.nullcontext
@@ -344,14 +344,14 @@ def run_sign_in(
guard = persist_guard or _default_persist_guard(is_cancelled)
try:
with open_scope():
- # The handoff runs once the surface's lock is released, never inside it.
- with deferred() as handoff:
- with guard() as may_persist:
- if may_persist:
- _core.persist_nous_credentials(account_state)
+ with guard() as may_persist:
+ if may_persist:
+ _core.persist_nous_credentials(account_state)
if may_persist:
+ # The handoff runs once the surface's lock is released, never inside it.
+ handoff = drain()
settled = _core.settle_after_upgrade(account_state)
- handoff_status = _handoff_status(handoff.results, state)
+ handoff_status = _handoff_status(handoff, state)
except Exception as exc:
# persist_nous_credentials takes the auth-store lock, writes auth.json, takes the shared
# store's file lock and reseeds the credential pool: a lock timeout or a read-only home
@@ -363,8 +363,8 @@ def run_sign_in(
return
yield Completed(
- email=_account_email(account_state, handoff.account_email),
+ email=_account_email(account_state, next((v["account_email"] for v in handoff if v["account_email"]), None)),
model=str(settled.get("model") or ""),
model_changed=bool(settled.get("changed")),
- handoff=_handoff_lines(handoff.results),
+ handoff=_handoff_lines(handoff),
handoff_status=handoff_status)
diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.py
index 592c6dfdb0b..c54be834a0c 100644
--- a/hermes_cli/auth_commands.py
+++ b/hermes_cli/auth_commands.py
@@ -313,14 +313,14 @@ def _add_nous_oauth_credential(args, provider: str) -> PooledCredential:
# `--label` is embedded into providers.nous so label_from_token doesn't overwrite it on every
# subsequent load_pool("nous").
from hermes_cli.anon_auth import settle_after_upgrade
- from hermes_cli.guest_handoff import deferred, result_lines
- with deferred() as handoff: # a replaced free tier hands its apps over once the save lands
- entry = auth_mod.persist_nous_credentials(creds, label=custom_label)
+ from hermes_cli.guest_handoff import drain, result_lines
+ entry = auth_mod.persist_nous_credentials(creds, label=custom_label)
+ handoff = drain() # a replaced free tier hands its apps over once the save lands
settle_after_upgrade(creds) # a config left on the free tier's route moves to the account
shown_label = entry.label if entry is not None else label_from_token(
creds.get("access_token", ""), f"{provider}-oauth-1")
print(f'{what} {provider} OAuth {"device-code " if what == "Saved" else ""}credentials: "{shown_label}"')
- for line in (line for view in handoff.results for line in result_lines(view)):
+ for line in (line for view in handoff for line in result_lines(view)):
print(f" {line}")
return entry
@@ -710,7 +710,7 @@ def auth_status_command(args) -> None:
print(f" {key}: {value}")
if provider == "nous":
from hermes_cli.guest_handoff import drain, handoff_status, status_lines
- drain() # a move left retrying (or failed transiently by an older build) gets its next try now
+ drain() # a move left retrying gets its next try now
for line in status_lines(handoff_status()):
print(f" {line}")
diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.py
index aeba8d6d0c2..9fc4aaae705 100644
--- a/hermes_cli/auth_nous.py
+++ b/hermes_cli/auth_nous.py
@@ -25,7 +25,7 @@ from hermes_cli.auth_constants import (
DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS, NOUS_AUTH_PATH_INVOKE_JWT, NOUS_BILLING_MANAGE_SCOPE,
NOUS_DEVICE_CODE_SOURCE, NOUS_INFERENCE_INVOKE_SCOPE, NOUS_INVOKE_JWT_MIN_TTL_SECONDS,
WELCOME_CLAIM_FLAG, _nous_err, httpx)
-from hermes_cli.guest_handoff import deferred, drain, note_replacement, result_lines
+from hermes_cli.guest_handoff import drain, note_replacement, result_lines
if TYPE_CHECKING: # annotation-only; the runtime import would be a cycle
from hermes_cli.auth import ProviderConfig
@@ -499,8 +499,6 @@ def _write_shared_nous_state(state: dict[str, Any], *, renewal: bool) -> None:
refresh_token_fp=_token_fingerprint(refresh_token))
except Exception as exc:
logger.debug("Failed to write shared Nous auth store: %s", exc)
- # The account is saved everywhere now: hand the replaced guest over (a no-op under a lock).
- drain()
def _read_shared_nous_state() -> Optional[dict[str, Any]]:
@@ -1519,6 +1517,7 @@ def step_up_nous_billing_scope(
open_browser=open_browser, timeout_seconds=timeout_seconds, on_verification=on_verification)
_save_active_provider_state("nous", auth_state)
_mirror_nous_state_best_effort(auth_state)
+ drain() # a step-up that replaced the free tier hands its apps over
# Every caller replays the refused billing action next: drop the billing client's 30s token cache
# here (not per caller) so that replay sends the new token, not the pre-approval one (403 again).
try:
@@ -1680,17 +1679,17 @@ def _login_nous(args, pconfig: ProviderConfig) -> None:
# model-picker "Skip (keep current)" can restore the user's previous provider.
with _auth_store_lock():
prior_active_provider = _load_auth_store().get("active_provider")
- with deferred() as handoff: # a replaced free tier hands its apps over once both saves land
- saved_to = _save_active_provider_state("nous", auth_state)
- # Mirror to the shared store so other profiles can one-tap import (best-effort inside).
- _write_shared_nous_state(auth_state, renewal=False)
+ saved_to = _save_active_provider_state("nous", auth_state)
+ # Mirror to the shared store so other profiles can one-tap import (best-effort inside).
+ _write_shared_nous_state(auth_state, renewal=False)
+ handoff = drain() # a replaced free tier hands its apps over once both saves land
_sync_nous_pool_from_auth_store()
from hermes_cli.anon_auth import settle_after_upgrade
settle_after_upgrade(auth_state) # a config left on the free tier's route moves to the account
print()
print("Login successful!")
print(f" Auth state: {saved_to}")
- for line in (line for view in handoff.results for line in result_lines(view)):
+ for line in (line for view in handoff for line in result_lines(view)):
print(f" {line}")
# Pick the model BEFORE writing the provider to config.yaml so config is never half-updated.
selected_model = None
diff --git a/hermes_cli/guest_handoff.py b/hermes_cli/guest_handoff.py
index 39fdd5b109c..20f466aaaad 100644
--- a/hermes_cli/guest_handoff.py
+++ b/hermes_cli/guest_handoff.py
@@ -4,20 +4,15 @@ The account service moves a free-tier identity's connected apps (and its preview
signed-in account with one call, ``POST /api/anonymous/claim {"token": "<anon_...>"}``, authorized by
the account's own ``hermes-cli`` Bearer token. Hermes never asks first: the move just happens after
the account is saved, and the result (the account email, what moved, what needs reconnecting) is
-shown afterwards. Sign-in code knows nothing about this; two halves keep it that way:
+shown afterwards. Two halves:
- :func:`note_replacement` runs at the lowest write seams (``auth._store_provider_state`` and
``auth_nous._write_shared_nous_state``), under the caller's auth-store locks, whenever a non-guest
Nous state replaces a guest. It writes a pending record and does no network. Records sit beside
- the shared Nous store, keyed by a hash of the ``anon_`` credential and bound to the destination
- account, so profiles that share one free-tier identity share one record and one claim.
-- :func:`drain` runs the claim outside every lock: when a shared-store write finishes, when a
- :func:`deferred` block exits, after a free-tier reconcile, and on each Nous keepalive tick (a
- retry left by an earlier process). The synchronous run is bounded (``SYNC_BUDGET_SECONDS``) so a
- CLI or the desktop sees a result; what is still retrying resumes on a later run.
-
-The apps only ever go to the record's destination: every attempt is reserved in one locked
-read-modify-write that also proves the Bearer about to be sent belongs to that destination.
+ the shared Nous store, keyed by a hash of the ``anon_`` credential.
+- :func:`drain` makes one attempt per due record, outside every lock: each sign-in surface calls it
+ after its save, and the retry worker, ``hermes auth status`` and ``hermes auth upgrade`` call it
+ for a move a transient error left retrying.
User copy never says guest / anonymous / claim.
"""
@@ -30,7 +25,6 @@ import logging
import threading
import time
from contextlib import contextmanager
-from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Iterator, Optional
@@ -38,51 +32,30 @@ from typing import Any, Iterator, Optional
logger = logging.getLogger("hermes_cli.auth")
IDLE, PENDING, RETRYING, CLAIMED, GONE, FAILED = "idle", "pending", "retrying", "claimed", "gone", "failed"
-# Read side only: an active record bound to an account this profile no longer holds.
-PAUSED = "paused"
_ACTIVE = frozenset({PENDING, RETRYING})
HANDOFF_FILENAME = "guest_handoff.json"
-SYNC_BUDGET_SECONDS = 10.0
CLAIM_TIMEOUT_SECONDS = 10.0
-# The service reaps an idle free-tier identity after 14 days, apps included. Transient failures keep
-# retrying (the slowest rung repeats) until this long after the record was made, safely before that.
-RETRY_WINDOW_SECONDS = 13 * 24 * 3600
-_BACKOFF_SECONDS = (2.0, 5.0, 15.0, 60.0, 300.0, 900.0, 3600.0)
+# While an attempt is in flight its record is not due, so a second process never sends it too.
+_LEASE_SECONDS = CLAIM_TIMEOUT_SECONDS + 20.0
+# Wait before each retry of a transient failure; the attempt after the last one is final.
+_RETRY_DELAYS_SECONDS = (60.0, 600.0, 3600.0, 6 * 3600.0)
# ``_is_expiring`` treats any token as expiring inside this skew, so the account token refreshes now.
_FORCE_REFRESH_SKEW = 10**9
# Outcome of one claim response.
-_CLAIMED, _GONE, _RETRY, _FAIL, _REAUTH = "claimed", "gone", "retry", "fail", "reauth"
-# Codes no later attempt can change. Every other refusal, unknown codes included, retries: a wrong
-# "final" loses the apps for good, a wrong retry costs one request an hour.
-_FINAL_CODES = frozenset({"client_not_allowed", "account_locked", "invalid_request", "retry_window_ended"})
+_CLAIMED, _GONE, _RETRY, _FAIL = "claimed", "gone", "retry", "fail"
# A plain reason per final code; any other code shows only the generic sentence, never the code.
_FAILURE_COPY = {
"client_not_allowed": "This sign-in can't receive them. Sign in again with `hermes auth add nous`.",
"account_locked": "This Nous account is locked.",
- "retry_window_ended": "Hermes kept trying for nearly two weeks, then stopped.",
}
# The service's refusal codes; anything unlisted retries (``_classify``).
_REFUSALS = {
"unknown_token": _GONE, "already_retired": _GONE,
- **{code: _FAIL for code in _FINAL_CODES},
+ "client_not_allowed": _FAIL, "account_locked": _FAIL, "invalid_request": _FAIL,
}
_records_lock_holder = threading.local()
-_claim_lock_holder = threading.local()
-_local = threading.local()
-_sleep = time.sleep
-
-
-@dataclass
-class HandoffBatch:
- """What one :func:`drain` did: the public view of each record it ran."""
-
- results: list[dict[str, Any]] = field(default_factory=list)
-
- @property
- def account_email(self) -> Optional[str]:
- return next((r["account_email"] for r in self.results if r.get("account_email")), None)
def _now() -> float:
@@ -107,55 +80,35 @@ def _records_path() -> Path:
return _nous_shared_store_path().with_name(HANDOFF_FILENAME)
-@contextmanager
-def _lock(path: Path, holder: threading.local, timeout_seconds: float) -> Iterator[None]:
- from hermes_cli.auth import _file_lock
- with _file_lock(path, holder, timeout_seconds, f"Timed out waiting for {path.name}"):
- yield
-
-
-def _load(path: Path, *, heal: bool = False) -> dict[str, Any]:
- """The records file. An unparseable one reads as empty; *heal* (writers, under the records lock)
- moves it aside to ``.corrupt`` first, so a bad file neither blocks a sign-in nor loses its data."""
+def _load(path: Path) -> dict[str, Any]:
try:
- data = json.loads(path.read_text(encoding="utf-8-sig"))
+ return json.loads(path.read_text(encoding="utf-8-sig"))
except FileNotFoundError:
- data = {}
- except ValueError:
- logger.warning("Free-tier handoff records at %s are unreadable%s", path,
- "; moved aside to .corrupt" if heal else "")
- if heal:
- path.replace(path.with_suffix(".json.corrupt"))
- data = {}
- records = data.get("records") if isinstance(data, dict) else None
- return {"_schema": 1, "records": records if isinstance(records, dict) else {}}
+ return {"_schema": 1, "records": {}}
-def _save(path: Path, data: dict[str, Any]) -> None:
- from hermes_cli.auth import _save_private_json
- _save_private_json(path, data, sort_keys=True)
+def _records() -> dict[str, Any]:
+ try:
+ return _load(_records_path())["records"]
+ except RuntimeError:
+ return {} # the test seat belt on the shared store path
def _update(path: Path, key: str, change) -> Optional[dict[str, Any]]:
"""Apply *change(record) -> record | None* to one record under the records lock and return what
was written (None: nothing written). The innermost lock: the hook takes it under the auth-store
locks, and it never holds another lock itself."""
- with _lock(path.with_suffix(".lock"), _records_lock_holder, 15.0):
- data = _load(path, heal=True)
+ from hermes_cli.auth import _file_lock, _save_private_json
+ with _file_lock(path.with_suffix(".lock"), _records_lock_holder, 15.0, f"Timed out waiting for {path.name}"):
+ data = _load(path)
record = change(data["records"].get(key))
if record is not None:
record["updated_at"] = _iso(_now())
data["records"][key] = record
- _save(path, data)
+ _save_private_json(path, data, sort_keys=True)
return record
-def _subject(access_token: Any) -> Optional[str]:
- from hermes_cli.auth_constants import _decode_jwt_claims
- sub = _decode_jwt_claims(access_token).get("sub")
- return str(sub) if sub else None
-
-
# --- The hook: no network, runs under the writer's locks ------------------------------------------
def note_store_write(auth_store: dict[str, Any], provider_id: str, state: Any) -> None:
@@ -167,28 +120,24 @@ def note_store_write(auth_store: dict[str, Any], provider_id: str, state: Any) -
def note_replacement(previous: Any, new: Any) -> None:
- """Record that a non-guest Nous state replaced the guest *previous*. Called from the lowest write
- seams; idempotent per ``anon_`` credential. A Claimed or Gone record is never reopened; a record
- not yet attempted follows the newest destination, one already attempted keeps its own (a lost
- answer may have moved the apps there)."""
+ """Record that a non-guest Nous state replaced the guest *previous*. Idempotent per ``anon_``
+ credential; a finished record is never reopened."""
from hermes_cli.anon_auth import is_guest_state
if not is_guest_state(previous) or is_guest_state(new) or not isinstance(new, dict):
return
- anon_token, destination = previous.get("anon_token"), _subject(new.get("access_token"))
- if not isinstance(anon_token, str) or not anon_token or not destination:
- return # no account subject: nothing a claim could ever be proven to land in
+ anon_token = previous.get("anon_token")
+ if not isinstance(anon_token, str) or not anon_token:
+ return
try:
path = _records_path()
except RuntimeError:
- return # no Hermes home yet (pre-setup): there is no shared store either
+ return
home = _home_key()
def change(record: Optional[dict[str, Any]]) -> dict[str, Any]:
if record is None:
- record = {"state": PENDING, "anon_token": anon_token, "destination": destination,
- "attempts": 0, "profiles": [], "created_at": _iso(_now())}
- elif record["state"] in _ACTIVE and not record.get("attempts"):
- record["destination"] = destination
+ record = {"state": PENDING, "anon_token": anon_token, "attempts": 0, "profiles": [],
+ "created_at": _iso(_now())}
if home not in record["profiles"]:
record["profiles"].append(home)
return record
@@ -200,285 +149,69 @@ def note_replacement(previous: Any, new: Any) -> None:
# --- The runner: outside every lock ---------------------------------------------------------------
-def _holds_auth_locks() -> bool:
- from hermes_cli import auth, auth_nous
- if getattr(auth_nous._nous_shared_lock_holder, "depth", 0):
- return True
- with auth._auth_target_lock_holders_guard:
- holders = list(auth._auth_target_lock_holders.values())
- return any(getattr(holder, "depth", 0) for holder in holders)
-
-
-@contextmanager
-def deferred() -> Iterator[HandoffBatch]:
- """Hold every drain on this thread until the block exits, then drain once (outside the caller's
- lock): a surface that saves a sign-in under its own lock wraps the save in this."""
- batch = HandoffBatch()
- _local.holds = getattr(_local, "holds", 0) + 1
- try:
- yield batch
- finally:
- _local.holds -= 1
- ran = drain()
- if ran is not None:
- batch.results = ran.results
-
-
-def drain() -> Optional[HandoffBatch]:
- """Run this profile's due records now. None when a lock or a :func:`deferred` block on this
- thread holds it back."""
- if getattr(_local, "holds", 0) or getattr(_local, "running", False) or _holds_auth_locks():
- return None
- _local.running = True
- try:
- return HandoffBatch(results=run_due(budget_seconds=SYNC_BUDGET_SECONDS))
- finally:
- _local.running = False
-
-
-def _remaining(deadline: float) -> float:
- return deadline - time.monotonic()
-
-
-def _retryable(record: dict[str, Any]) -> bool:
- """A record a run may still attempt: active, or Failed on a code that is not final (an older
- build closed transient failures after 8 attempts; those re-arm here, on any run: a sign-in,
- ``hermes auth status``, ``hermes auth upgrade``, the retry worker). The retry window is checked
- when the attempt is reserved, so a record past it is closed, not silently skipped."""
- state = record.get("state")
- return state in _ACTIVE or (state == FAILED and record.get("error") not in _FINAL_CODES
- and bool(record.get("anon_token")))
-
-
def _due(record: dict[str, Any], now: float) -> bool:
- return _retryable(record) and float(record.get("next_attempt_at") or 0) <= now
-
-
-def _window_ended(record: dict[str, Any], now: float) -> bool:
- try:
- created = datetime.fromisoformat(str(record.get("created_at"))).timestamp()
- except ValueError:
- return True
- return now >= created + RETRY_WINDOW_SECONDS
-
-
-# --- The worker: retries in a long-lived process, for every profile -------------------------------
-#
-# A move queued by a short process (a CLI sign-in during an outage) is finished by whichever long-lived
-# Nous process runs next (Desktop backend, gateway, CLI agent), whatever its own profile or identity.
-_WORKER_FIRST_TICK_SECONDS = 15.0
-_WORKER_INTERVAL_SECONDS = 60.0
-_worker_lock = threading.Lock()
-_worker_stop = threading.Event()
-_worker_thread: Optional[threading.Thread] = None
-
-
-def start_worker() -> threading.Thread:
- """Start the process-wide retry worker (idempotent)."""
- global _worker_thread
- with _worker_lock:
- if _worker_thread is not None and _worker_thread.is_alive():
- return _worker_thread
- _worker_stop.clear()
- # health: allow HX012 -- process-wide worker that binds each record's own profile scope per run; it must not inherit the starter's
- _worker_thread = threading.Thread(target=_worker_loop, daemon=True, name="nous-guest-handoff")
- _worker_thread.start()
- return _worker_thread
-
-
-def stop_worker(timeout: float = 5.0) -> None:
- global _worker_thread
- with _worker_lock:
- thread = _worker_thread
- _worker_stop.set()
- if thread is not None and thread.is_alive():
- thread.join(timeout=timeout)
- with _worker_lock:
- if _worker_thread is thread:
- _worker_thread = None
-
-
-def _worker_loop() -> None:
- wait = _WORKER_FIRST_TICK_SECONDS
- while not _worker_stop.wait(wait):
- try:
- retry_all_profiles()
- except Exception:
- logger.warning("Free-tier handoff retry tick failed; the records stay for the next one", exc_info=True)
- wait = _WORKER_INTERVAL_SECONDS
-
-
-def retry_all_profiles() -> list[dict[str, Any]]:
- """Run every due record under its owning profile's scope (home + secrets), so a named profile's
- move retries from a process launched as another profile. The bound-account check and the Bearer
- proof in ``_reserve`` still decide whether anything is sent."""
- try:
- records = _load(_records_path())["records"].values()
- except RuntimeError:
- return []
- now = _now()
- homes = sorted({home for record in records if _due(record, now) for home in record.get("profiles", ())})
- results: list[dict[str, Any]] = []
- for home in homes:
- if not Path(home).is_dir():
- continue # a deleted profile: nothing there holds the destination account
- with _profile_scope(home):
- batch = drain()
- results.extend(batch.results if batch else [])
- return results
-
-
-@contextmanager
-def _profile_scope(home: str) -> Iterator[None]:
- """The owning profile's home and secrets for one drain (the cron ticker binds a profile the same
- way); no terminal scope: nothing here runs a command."""
- from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope
- from hermes_constants import get_routing_process_hermes_home, hermes_home_key
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
- foreign = hermes_home_key(get_routing_process_hermes_home()) != home
- home_token = set_hermes_home_override(home)
- secret_token = set_secret_scope(build_profile_secret_scope(Path(home)), profile_home=home if foreign else None)
- try:
- yield
- finally:
- reset_secret_scope(secret_token)
- reset_hermes_home_override(home_token)
+ return record.get("state") in _ACTIVE and float(record.get("next_attempt_at") or 0) <= now
-def run_due(*, budget_seconds: float = SYNC_BUDGET_SECONDS) -> list[dict[str, Any]]:
- """Attempt every active, due record of this profile within *budget_seconds*. Returns their public
- views; a record the budget did not reach stays as it is for a later run."""
- try:
- path = _records_path()
- except RuntimeError:
- return []
+def drain() -> list[dict[str, Any]]:
+ """One attempt for each of this profile's due records; returns their public views. Call it only
+ outside the auth-store locks: it sends a request."""
home, now = _home_key(), _now()
- due = [key for key, record in _load(path)["records"].items()
- if home in record.get("profiles", ()) and _due(record, now)]
- deadline = time.monotonic() + budget_seconds
- results = []
- for key in due:
- if _remaining(deadline) <= 0:
- break
- if (view := _run_one(path, key, deadline)) is not None:
- results.append(view)
- return results
-
-
-def _account_bound_to(record: dict[str, Any]) -> Optional[dict[str, Any]]:
- """The profile's account when it is the record's destination; None while the profile still holds
- a guest (the save never landed) or holds another account (retries bind to the destination)."""
- from hermes_cli.anon_auth import is_guest_state
- from hermes_cli.auth import get_provider_auth_state
- account = get_provider_auth_state("nous")
- if not isinstance(account, dict) or is_guest_state(account) or not account.get("access_token"):
- return None
- destination = record.get("destination")
- return account if destination and _subject(account["access_token"]) == destination else None
+ due = [key for key, record in _records().items() if home in record.get("profiles", ()) and _due(record, now)]
+ return [view for key in due if (view := _run_one(_records_path(), key)) is not None]
-def _run_one(path: Path, key: str, deadline: float) -> Optional[dict[str, Any]]:
- record = _load(path)["records"].get(key)
- if record is None or _account_bound_to(record) is None:
- return None # a cheap skip; the binding that counts is proven in ``_reserve``
- # The claim lock spans read -> claim -> write so two processes never claim one record twice.
- # Order: claim lock, then the auth-store locks (token refresh), then the records lock. A lock
- # timeout anywhere in here is contention, not a verdict: the record stays as it is for a later run.
+def _run_one(path: Path, key: str) -> Optional[dict[str, Any]]:
+ from hermes_cli.auth import get_provider_auth_state
+ from hermes_cli.auth_constants import AuthError
try:
- with _lock(path.with_name(HANDOFF_FILENAME + ".claim.lock"), _claim_lock_holder,
- max(0.1, _remaining(deadline))):
- return _claim_locked(path, key, deadline)
- except TimeoutError:
+ bearer = _bearer()
+ except AuthError as exc:
+ logger.info("Free-tier handoff (%s): account token unavailable (%s)", key[:8], exc.code)
return None
+ record = _update(path, key, _reserve)
+ if record is None:
+ return None # another run holds it, or it settled meanwhile
+ prior = record["attempts"] - 1
+ outcome, payload, retry_after = _post(record["anon_token"], bearer, get_provider_auth_state("nous") or {})
+ logger.info("Free-tier handoff attempt %d (%s): %s", prior + 1, key[:8], payload.get("error") or outcome)
+ record = _update(path, key, lambda r: _apply(r, outcome, payload, retry_after, prior))
+ if outcome == _CLAIMED and payload.get("cohort_carried") is True:
+ _refresh_account_token()
+ return public_view(record) if record else None
+
+
+def _reserve(record: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
+ """Count the attempt and lease the record before the request leaves: a lost answer still counts,
+ and no other run sends it meanwhile."""
+ now = _now()
+ if record is None or not _due(record, now):
+ return None
+ return {**record, "attempts": int(record.get("attempts") or 0) + 1, "last_attempt_at": _iso(now),
+ "next_attempt_at": now + _LEASE_SECONDS}
-def _reserve(path: Path, key: str, bearer_subject: Optional[str]) -> Optional[tuple[dict[str, Any], int]]:
- """Reserve one attempt in a single locked read-modify-write: the record is still retryable and
- due, inside its retry window, and bound to the very account whose Bearer is about to be sent.
- Returns ``(record, attempts before this one)``, or None when nothing may be sent now. A record
- past its window is closed as Failed instead; one an older build failed is re-armed."""
- reserved: list[int] = []
-
- def change(record: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
- now = _now()
- if (record is None or not _due(record, now)
- or not bearer_subject or record.get("destination") != bearer_subject):
- return None
- if _window_ended(record, now):
- return {**record, "state": FAILED, "error": "retry_window_ended"}
- prior = int(record.get("attempts") or 0)
- reserved.append(prior)
- # Counted before the request leaves: an answer lost to a crash still counts as an attempt.
- return {**record, "state": RETRYING if record["state"] == FAILED else record["state"],
- "attempts": prior + 1, "last_attempt_at": _iso(now)}
-
- record = _update(path, key, change)
- return (record, reserved[0]) if reserved else None
-
-
-def _claim_locked(path: Path, key: str, deadline: float) -> Optional[dict[str, Any]]:
- from hermes_cli.auth import get_provider_auth_state
- from hermes_cli.auth_constants import AuthError
- force = False
- while True:
- current = _load(path)["records"].get(key)
- if current is None or _remaining(deadline) <= 0:
- return public_view(current) if current else None
- try:
- bearer = _bearer(force=force, timeout=_remaining(deadline))
- except AuthError as exc:
- logger.info("Free-tier handoff (%s): account token unavailable (%s)", key[:8], exc.code)
- return public_view(current)
- if _remaining(deadline) <= 0:
- return public_view(current)
- reservation = _reserve(path, key, _subject(bearer))
- if reservation is None:
- return public_view(_load(path)["records"].get(key) or current)
- record, prior = reservation
- outcome, payload, retry_after = _post(
- record["anon_token"], bearer, get_provider_auth_state("nous") or {},
- timeout=min(CLAIM_TIMEOUT_SECONDS, max(0.1, _remaining(deadline))))
- logger.info("Free-tier handoff attempt %d (%s): %s", prior + 1, key[:8], payload.get("error") or outcome)
- if outcome == _REAUTH and not force:
- # A refused bearer never reached the claim, so it is not an attempt.
- _update(path, key, lambda r: {**r, "attempts": prior} if r.get("attempts") == prior + 1 else None)
- force = True
- continue
- record = _update(path, key, lambda r: _apply(r, outcome, payload, retry_after, prior))
- if outcome == _CLAIMED and payload.get("cohort_carried") is True:
- _refresh_account_token(timeout=max(1.0, _remaining(deadline)))
- wait = max(0.0, float(record.get("next_attempt_at") or 0) - _now())
- if record["state"] != RETRYING or wait >= _remaining(deadline):
- return public_view(record)
- _sleep(wait)
-
-
-def _bearer(*, force: bool, timeout: float) -> str:
+def _bearer(*, force: bool = False) -> str:
from hermes_cli import auth
- from hermes_cli.auth_nous import _nous_shared_store_lock
# The resolver's 5 s memo can still hold the guest's token from just before the save.
with auth._RESOLVE_TOKEN_CACHE_LOCK:
auth._RESOLVE_TOKEN_CACHE.pop(_home_key(), None)
- # The resolver waits its own, longer floors for these locks. Taking them first within the
- # budget (same order: auth, then shared) makes its acquisitions reentrant, so a held lock costs
- # the budget, not 15 s; a timeout leaves the record for a later run.
- with auth._auth_store_lock(timeout), _nous_shared_store_lock(timeout_seconds=timeout):
- if force:
- return auth.resolve_nous_access_token(timeout_seconds=timeout, refresh_skew_seconds=_FORCE_REFRESH_SKEW)
- return auth.resolve_nous_access_token(timeout_seconds=timeout)
+ if force:
+ return auth.resolve_nous_access_token(timeout_seconds=CLAIM_TIMEOUT_SECONDS,
+ refresh_skew_seconds=_FORCE_REFRESH_SKEW)
+ return auth.resolve_nous_access_token(timeout_seconds=CLAIM_TIMEOUT_SECONDS)
-def _refresh_account_token(*, timeout: float) -> None:
+def _refresh_account_token() -> None:
"""The account's token picks up the carried cohort only on its next mint, so mint it now."""
from hermes_cli.auth_constants import AuthError
try:
- _bearer(force=True, timeout=timeout)
+ _bearer(force=True)
except AuthError as exc:
logger.info("Free-tier handoff: account token refresh after the move failed: %s", exc)
-def _post(anon_token: str, bearer: str, account: dict[str, Any], *,
- timeout: float) -> tuple[str, dict[str, Any], Optional[float]]:
+def _post(anon_token: str, bearer: str, account: dict[str, Any]) -> tuple[str, dict[str, Any], Optional[float]]:
from agent.retry_utils import parse_retry_after_seconds
from hermes_cli.anon_auth import _anon_headers
from hermes_cli.auth import _nous_portal_base_url, _resolve_verify
@@ -486,7 +219,7 @@ def _post(anon_token: str, bearer: str, account: dict[str, Any], *,
from hermes_cli.auth_nous import _nous_http_client
verify = _resolve_verify(insecure=None, ca_bundle=None, auth_state=account)
try:
- with _nous_http_client(timeout, verify) as client:
+ with _nous_http_client(CLAIM_TIMEOUT_SECONDS, verify) as client:
response = client.post(
f"{_nous_portal_base_url(account).rstrip('/')}/api/anonymous/claim",
headers={**_anon_headers(), "authorization": f"Bearer {bearer}"}, json={"token": anon_token})
@@ -503,8 +236,6 @@ def _post(anon_token: str, bearer: str, account: dict[str, Any], *,
def _classify(status: int, payload: dict[str, Any]) -> str:
if status == 200:
return _CLAIMED if payload.get("status") == "claimed" else _RETRY
- if status == 401:
- return _REAUTH
return _REFUSALS.get(str(payload.get("error") or ""), _RETRY)
@@ -526,16 +257,59 @@ def _apply(record: dict[str, Any], outcome: str, payload: dict[str, Any], retry_
elif outcome == _GONE:
# Gone after an earlier attempt is most likely that attempt's lost success.
record.update(state=GONE, probably_moved=payload.get("error") == "already_retired" or prior_attempts > 0)
- elif outcome == _FAIL:
+ elif outcome == _FAIL or prior_attempts >= len(_RETRY_DELAYS_SECONDS):
record.update(state=FAILED)
else:
- ladder = _BACKOFF_SECONDS[min(prior_attempts, len(_BACKOFF_SECONDS) - 1)]
- record.update(state=RETRYING, next_attempt_at=_now() + (retry_after if retry_after else ladder))
+ record.update(state=RETRYING, next_attempt_at=_now() + (retry_after or _RETRY_DELAYS_SECONDS[prior_attempts]))
if record["state"] in (CLAIMED, GONE):
record.pop("anon_token", None) # retired credential: nothing left to retry with
return record
+# --- The worker: retries a transient failure in a long-lived process ------------------------------
+
+_WORKER_FIRST_TICK_SECONDS = 15.0
+_WORKER_INTERVAL_SECONDS = 60.0
+_worker_lock = threading.Lock()
+_worker_stop = threading.Event()
+_worker_thread: Optional[threading.Thread] = None
+
+
+def start_worker() -> threading.Thread:
+ """Start the process-wide retry worker (idempotent)."""
+ global _worker_thread
+ with _worker_lock:
+ if _worker_thread is not None and _worker_thread.is_alive():
+ return _worker_thread
+ _worker_stop.clear()
+ # health: allow HX012 -- process-wide worker for the process's own profile; it must not inherit the starter's scope
+ _worker_thread = threading.Thread(target=_worker_loop, daemon=True, name="nous-guest-handoff")
+ _worker_thread.start()
+ return _worker_thread
+
+
+def stop_worker(timeout: float = 5.0) -> None:
+ global _worker_thread
+ with _worker_lock:
+ thread = _worker_thread
+ _worker_stop.set()
+ if thread is not None and thread.is_alive():
+ thread.join(timeout=timeout)
+ with _worker_lock:
+ if _worker_thread is thread:
+ _worker_thread = None
+
+
+def _worker_loop() -> None:
+ wait = _WORKER_FIRST_TICK_SECONDS
+ while not _worker_stop.wait(wait):
+ try:
+ drain()
+ except Exception:
+ logger.warning("Free-tier handoff retry tick failed; the records stay for the next one", exc_info=True)
+ wait = _WORKER_INTERVAL_SECONDS
+
+
# --- Read side: status for the surfaces -----------------------------------------------------------
def public_view(record: dict[str, Any]) -> dict[str, Any]:
@@ -551,36 +325,20 @@ def public_view(record: dict[str, Any]) -> dict[str, Any]:
"updated_at": record.get("updated_at")}
-def _status_of(record: dict[str, Any]) -> dict[str, Any]:
- view = public_view(record)
- if _retryable(record):
- view["state"] = RETRYING if _account_bound_to(record) else PAUSED
- return view
-
-
def handoff_status() -> dict[str, Any]:
- """This profile's latest handoff, or ``{"state": "idle"}``. A pure read (no lock, no network). An
- active move bound to an account this profile no longer holds reads as ``paused``."""
- try:
- records = _load(_records_path())["records"].values()
- except RuntimeError:
- return {"state": IDLE}
+ """This profile's latest handoff, or ``{"state": "idle"}``. A pure read (no lock, no network)."""
home = _home_key()
- mine = [r for r in records if home in r.get("profiles", ())]
+ mine = [r for r in _records().values() if home in r.get("profiles", ())]
if not mine:
return {"state": IDLE}
- return _status_of(max(mine, key=lambda r: str(r.get("updated_at") or "")))
+ return public_view(max(mine, key=lambda r: str(r.get("updated_at") or "")))
def record_status(anon_token: str) -> Optional[dict[str, Any]]:
- """The handoff of one free-tier credential (as :func:`handoff_status` reads it), or None when no
- record exists. A pure read: what a sign-in reports when its own run attempted nothing (another
- process held the claim, or the budget ran out first)."""
- try:
- record = _load(_records_path())["records"].get(_token_key(anon_token))
- except RuntimeError:
- return None
- return _status_of(record) if record else None
+ """The handoff of one free-tier credential, or None when no record exists. A pure read: what a
+ sign-in reports when its own run attempted nothing (another process held the record)."""
+ record = _records().get(_token_key(anon_token))
+ return public_view(record) if record else None
def wire_status(status: dict[str, Any]) -> dict[str, Any]:
@@ -601,14 +359,13 @@ def status_lines(status: dict[str, Any]) -> list[str]:
def result_lines(status: dict[str, Any]) -> list[str]:
"""What a handoff did, for the line after "Signed in as ..." (every sign-in surface) and for
:func:`status_lines`."""
+ from tools.tool_labels import app_title
state = status.get("state")
where = status.get("account_email") or "your account"
- moved, dropped = status.get("moved_toolkits") or [], status.get("dropped_toolkits") or []
+ moved = [app_title(slug) for slug in status.get("moved_toolkits") or []]
+ dropped = [app_title(slug) for slug in status.get("dropped_toolkits") or []]
if state in _ACTIVE:
return ["Moving your free-tier apps to this account; Hermes keeps trying in the background."]
- if state == PAUSED:
- return ["Your free-tier apps are set to move to another Nous account. Sign in to that account "
- "to finish moving them."]
if state == FAILED:
reason = _FAILURE_COPY.get(str(status.get("error") or ""))
return ["Your free-tier apps could not be moved." + (f" {reason}" if reason else "")]
diff --git a/hermes_cli/nous_subscription.py b/hermes_cli/nous_subscription.py
index 91c49397667..b830cf6c8dd 100644
--- a/hermes_cli/nous_subscription.py
+++ b/hermes_cli/nous_subscription.py
@@ -699,21 +699,21 @@ def _run_nous_portal_login_only(*, capability: str) -> bool:
if auth_state is None:
auth_state = auth._nous_device_code_login()
from hermes_cli.anon_auth import settle_after_upgrade
- from hermes_cli.guest_handoff import deferred, result_lines
- with deferred() as handoff: # a replaced free tier hands its apps over once both saves land
- with auth._auth_store_lock():
- auth_store = auth._load_auth_store()
- auth._save_provider_state(auth_store, "nous", auth_state)
- if prior_active_provider:
- auth_store["active_provider"] = prior_active_provider
- else:
- auth_store.pop("active_provider", None)
- auth._save_auth_store(auth_store)
- auth._write_shared_nous_state(auth_state, renewal=False)
+ from hermes_cli.guest_handoff import drain, result_lines
+ with auth._auth_store_lock():
+ auth_store = auth._load_auth_store()
+ auth._save_provider_state(auth_store, "nous", auth_state)
+ if prior_active_provider:
+ auth_store["active_provider"] = prior_active_provider
+ else:
+ auth_store.pop("active_provider", None)
+ auth._save_auth_store(auth_store)
+ auth._write_shared_nous_state(auth_state, renewal=False)
+ handoff = drain() # a replaced free tier hands its apps over once both saves land
auth._sync_nous_pool_from_auth_store()
settle_after_upgrade(auth_state) # a config left on the free tier's route moves to the account
print(" Nous Portal login successful.")
- for line in (line for view in handoff.results for line in result_lines(view)):
+ for line in (line for view in handoff for line in result_lines(view)):
print(f" {line}")
return True
except KeyboardInterrupt:
diff --git a/tests/hermes_cli/test_anon_desktop_signin.py b/tests/hermes_cli/test_anon_desktop_signin.py
index 63502bc5ef9..5f86f79bd40 100644
--- a/tests/hermes_cli/test_anon_desktop_signin.py
+++ b/tests/hermes_cli/test_anon_desktop_signin.py
@@ -50,7 +50,7 @@ def test_start_shows_the_device_code_and_completion_reports_what_moved(portal, f
assert body["status"] == "approved"
assert body["account_email"] == EMAIL
assert body["model"] == FREE_PICK
- assert body["handoff"] == [f"Your apps moved to {EMAIL}: gmail."]
+ assert body["handoff"] == [f"Your apps moved to {EMAIL}: Gmail."]
assert not [p for _, p in portal.calls if "promotion" in p]
state = _load_auth_store()["providers"]["nous"]
assert "anon_token" not in state and not anon_auth.is_guest_state(state)
diff --git a/tests/hermes_cli/test_anon_sign_in_flow.py b/tests/hermes_cli/test_anon_sign_in_flow.py
index 774d108377f..7b45850186c 100644
--- a/tests/hermes_cli/test_anon_sign_in_flow.py
+++ b/tests/hermes_cli/test_anon_sign_in_flow.py
@@ -73,7 +73,7 @@ def test_the_handoff_result_rides_the_completed_state(portal, free_account):
completed = _drain()[-1]
- assert completed.handoff == (f"Your apps moved to {EMAIL}: gmail.", f"Reconnect in {EMAIL}: slack.")
+ assert completed.handoff == (f"Your apps moved to {EMAIL}: Gmail.", f"Reconnect in {EMAIL}: Slack.")
assert completed.copy.splitlines()[:3] == [f"Signed in as {EMAIL}.", *completed.handoff]
diff --git a/tests/hermes_cli/test_anon_upgrade.py b/tests/hermes_cli/test_anon_upgrade.py
index f12b63853bc..135b4fb7240 100644
--- a/tests/hermes_cli/test_anon_upgrade.py
+++ b/tests/hermes_cli/test_anon_upgrade.py
@@ -154,7 +154,7 @@ class TestUpgrade:
out = capsys.readouterr().out
assert code == 0
assert f"Signed in as {EMAIL}." in out
- assert f"Your apps moved to {EMAIL}: gmail." in out
+ assert f"Your apps moved to {EMAIL}: Gmail." in out
lowered = out.lower()
for banned in ("guest", "anonymous", "claim"):
assert banned not in lowered, f"{banned!r} leaked into user-facing output:\n{out}"
@@ -196,7 +196,7 @@ class TestUpgrade:
auth_nous._login_nous(argparse.Namespace(no_browser=True, timeout=15.0), PROVIDER_REGISTRY["nous"])
- assert f"Your apps moved to {EMAIL}: gmail." in capsys.readouterr().out
+ assert f"Your apps moved to {EMAIL}: Gmail." in capsys.readouterr().out
assert len(portal.claims) == 1
diff --git a/tests/hermes_cli/test_desktop_signin_long_poll.py b/tests/hermes_cli/test_desktop_signin_long_poll.py
index 2c6e2eb22f3..16415147fc0 100644
--- a/tests/hermes_cli/test_desktop_signin_long_poll.py
+++ b/tests/hermes_cli/test_desktop_signin_long_poll.py
@@ -53,7 +53,7 @@ def test_a_sign_in_that_replaced_no_free_tier_reports_no_handoff(portal, free_ac
def test_a_move_no_attempt_reached_still_reports_the_waiting_record(portal, free_account, monkeypatch):
- """Another process holds the claim, so this sign-in's own run attempts nothing: the poll still
+ """Another process holds the record, so this sign-in's own run attempts nothing: the poll still
reports the replaced free tier's record (still moving) instead of no handoff at all."""
anon_auth.ensure_portal_identity(explicit=True)
monkeypatch.setattr(guest_handoff, "_run_one", lambda *a, **kw: None)
@@ -62,9 +62,8 @@ def test_a_move_no_attempt_reached_still_reports_the_waiting_record(portal, free
body = _poll(start["session_id"], wait=25)
assert body["status"] == "approved"
- # A move bound to this account and not yet attempted reads as retrying (handoff_status's rule).
- assert body["handoff_status"]["state"] == "retrying"
- assert body["handoff_status"]["lines"] == guest_handoff.result_lines({"state": "retrying"})
+ assert body["handoff_status"]["state"] == "pending"
+ assert body["handoff_status"]["lines"] == guest_handoff.result_lines({"state": "pending"})
assert not portal.claims
@@ -92,7 +91,7 @@ def test_the_handoff_route_reads_the_record_the_sign_in_left(portal, free_accoun
status = _handoff()
assert status["state"] == "claimed" and status["moved_toolkits"] == ["gmail"]
assert status["updated_at"] == signed_in["updated_at"]
- assert status["lines"] == [f"Your apps moved to {EMAIL}: gmail."]
+ assert status["lines"] == [f"Your apps moved to {EMAIL}: Gmail."]
def test_the_handoff_long_poll_answers_when_the_record_changes(monkeypatch):
@@ -105,7 +104,7 @@ def test_the_handoff_long_poll_answers_when_the_record_changes(monkeypatch):
status = _handoff(since="t1", wait=25)
assert status["state"] == "claimed" and status["updated_at"] == "t2"
- assert status["lines"] == [f"Your apps moved to {EMAIL}: gmail."]
+ assert status["lines"] == [f"Your apps moved to {EMAIL}: Gmail."]
def test_the_handoff_long_poll_returns_the_unchanged_record_after_its_wait(monkeypatch):
diff --git a/tests/hermes_cli/test_guest_handoff.py b/tests/hermes_cli/test_guest_handoff.py
index a45d54c2516..ada1e8f47c8 100644
--- a/tests/hermes_cli/test_guest_handoff.py
+++ b/tests/hermes_cli/test_guest_handoff.py
@@ -7,7 +7,6 @@ service (``anon_portal.FakePortal`` plus the claim and token-refresh routes).
from __future__ import annotations
import json
-import threading
import time
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
@@ -48,8 +47,7 @@ class ClaimPortal(FakePortal):
def handler(self, request: httpx.Request) -> httpx.Response:
if request.url.path == "/api/anonymous/claim":
- from hermes_cli import guest_handoff
- self.locks_held_during_claim.append(guest_handoff._holds_auth_locks())
+ self.locks_held_during_claim.append(holds_auth_locks())
self.claims.append({"body": json.loads(request.content),
"authorization": request.headers.get("authorization")})
if self.on_claim:
@@ -67,15 +65,18 @@ class ClaimPortal(FakePortal):
return super().handler(request)
+def holds_auth_locks() -> bool:
+ from hermes_cli import auth, auth_nous
+ if getattr(auth_nous._nous_shared_lock_holder, "depth", 0):
+ return True
+ with auth._auth_target_lock_holders_guard:
+ holders = list(auth._auth_target_lock_holders.values())
+ return any(getattr(holder, "depth", 0) for holder in holders)
+
+
@pytest.fixture
def portal(monkeypatch, tmp_path):
- from hermes_cli import guest_handoff
fake = install_portal(monkeypatch, tmp_path, ClaimPortal())
- # A runner's backoff sleep moves the handoff's own clock instead of the wall clock.
- skew = [0.0]
- monkeypatch.setattr(guest_handoff, "_now", lambda: time.time() + skew[0])
- monkeypatch.setattr(guest_handoff, "_sleep", lambda s: skew.__setitem__(0, skew[0] + s))
- monkeypatch.setattr(guest_handoff, "_local", threading.local())
# The settle reads the recommended default from the Portal; that is not under test here.
monkeypatch.setattr("hermes_cli.anon_auth.settle_after_upgrade", lambda _s: {"model": "", "changed": False})
return fake
@@ -99,13 +100,20 @@ def _only_record() -> dict:
return next(iter(records.values()))
-# --- Writer coverage: every way an account replaces the guest fires the hook ----------------------
+# --- Writer coverage: every way an account replaces the guest records the move -------------------
-def _persist(account):
+def _save(account):
from hermes_cli.auth import persist_nous_credentials
persist_nous_credentials(account)
+def _persist(account):
+ """A surface's save: the account, then the handoff outside the locks."""
+ from hermes_cli import guest_handoff
+ _save(account)
+ guest_handoff.drain()
+
+
def _step_up(account, monkeypatch):
from hermes_cli import auth
monkeypatch.setattr(auth, "_nous_device_code_login", lambda **_kw: account)
@@ -129,13 +137,11 @@ def _subscription_login(account, monkeypatch):
def _sibling_adoption(account, monkeypatch, tmp_path):
"""Another profile signed in (account in the shared store); this one adopts it on next use."""
import os
- from hermes_cli import anon_auth, auth_nous, guest_handoff
+ from hermes_cli import anon_auth, auth_nous
mine, sibling = os.environ["HERMES_HOME"], tmp_path / "sibling-profile"
sibling.mkdir()
monkeypatch.setenv("HERMES_HOME", str(sibling))
- monkeypatch.setattr(auth_nous, "drain", lambda: None) # the sibling's own run is not this test
auth_nous._write_shared_nous_state(account, renewal=False)
- monkeypatch.setattr(auth_nous, "drain", guest_handoff.drain)
monkeypatch.setenv("HERMES_HOME", mine)
anon_auth.ensure_portal_identity(explicit=True)
@@ -158,8 +164,7 @@ def test_every_writer_that_replaces_the_guest_hands_it_over(portal, monkeypatch,
assert portal.claims[0]["authorization"].startswith("Bearer ")
assert portal.locks_held_during_claim == [False]
record = _only_record()
- assert record["state"] == "claimed" and record["destination"] == DESTINATION
- assert "anon_token" not in record
+ assert record["state"] == "claimed" and "anon_token" not in record
from hermes_cli import guest_handoff
assert guest_handoff.handoff_status()["moved_toolkits"] == ["gmail"]
@@ -180,6 +185,7 @@ def _err(status, code, **headers):
(httpx.Response(200, json=CLAIMED), "claimed", False),
(_err(404, "unknown_token"), "gone", False),
(_err(410, "already_retired"), "gone", True),
+ (_err(401, "invalid_token"), "retrying", False),
(_err(409, "account_busy"), "retrying", False),
(_err(429, "rate_limited", **{"Retry-After": "120"}), "retrying", False),
(_err(404, "not_found"), "retrying", False),
@@ -192,37 +198,35 @@ def _err(status, code, **headers):
(_err(403, "client_not_allowed"), "failed", False),
(_err(403, "account_locked"), "failed", False),
], ids=lambda v: v if isinstance(v, str) else None)
-def test_each_claim_answer_lands_in_its_state(portal, monkeypatch, answer, state, probably_moved):
- from hermes_cli import guest_handoff
- monkeypatch.setattr(guest_handoff, "SYNC_BUDGET_SECONDS", 3.0) # one attempt: every retry waits longer
- monkeypatch.setattr(guest_handoff, "_BACKOFF_SECONDS", (60.0,))
+def test_each_claim_answer_lands_in_its_state(portal, answer, state, probably_moved):
anon = _mint_guest()
portal.claim_answers = [answer]
_persist(_account())
+ assert len(portal.claims) == 1
record = _only_record()
assert record["state"] == state
assert bool(record.get("probably_moved")) is probably_moved
# A retrying or failed record keeps the credential; a finished one drops it.
assert (record.get("anon_token") == anon) is (state in ("retrying", "failed"))
- if state == "retrying": # honours Retry-After, else the first backoff step
+ if state == "retrying": # honours Retry-After, else the first retry delay
wait = float(record["next_attempt_at"]) - time.time()
- assert wait >= float(answer.headers.get("Retry-After", 1)) - 1
+ assert wait >= float(answer.headers.get("Retry-After", 60)) - 1
-def test_a_refused_account_token_is_refreshed_once_then_retried(portal):
- portal.claim_answers = [_err(401, "invalid_token"), httpx.Response(200, json=CLAIMED)]
- _mint_guest()
- _persist(_account())
- assert len(portal.claims) == 2 and portal.refreshes == 1
- assert portal.claims[0]["authorization"] != portal.claims[1]["authorization"]
- assert _only_record()["state"] == "claimed" and _only_record()["attempts"] == 1
+def _later(monkeypatch, seconds: float) -> None:
+ from hermes_cli import guest_handoff
+ now = guest_handoff._now() + seconds
+ monkeypatch.setattr(guest_handoff, "_now", lambda: now)
-def test_lost_success_then_unknown_token_reads_as_probably_moved(portal):
+def test_lost_success_then_unknown_token_reads_as_probably_moved(portal, monkeypatch):
+ from hermes_cli import guest_handoff
portal.claim_answers = [httpx.ReadTimeout("lost"), _err(404, "unknown_token")]
_mint_guest()
_persist(_account())
+ _later(monkeypatch, 120)
+ guest_handoff.drain()
record = _only_record()
assert len(portal.claims) == 2
assert record["state"] == "gone" and record["probably_moved"] is True and record["attempts"] == 2
@@ -237,47 +241,28 @@ def test_account_token_refreshes_only_when_the_cohort_carried(portal, carried, r
assert portal.refreshes == refreshes
-def test_transient_failures_keep_retrying_past_the_old_attempt_cap(portal, monkeypatch):
+def test_transient_failures_retry_a_few_times_then_stop(portal, monkeypatch):
from hermes_cli import guest_handoff
- portal.claim_answers = [_err(503, "temporarily_disabled")] * 12 # the ops breaker: no Retry-After
- monkeypatch.setattr(guest_handoff, "_BACKOFF_SECONDS", (0.0,))
+ attempts = len(guest_handoff._RETRY_DELAYS_SECONDS) + 1
+ portal.claim_answers = [_err(503, "temporarily_disabled")] * (attempts + 1)
_mint_guest()
_persist(_account())
- assert len(portal.claims) == 13 and _only_record()["state"] == "claimed"
+ for _ in range(attempts):
+ _later(monkeypatch, 7 * 3600)
+ guest_handoff.drain()
+ assert len(portal.claims) == attempts
+ assert _only_record()["state"] == "failed" and _only_record()["anon_token"]
-def test_a_long_outage_retries_on_the_slowest_rung(portal, monkeypatch):
+def test_a_retry_not_yet_due_sends_nothing(portal):
from hermes_cli import guest_handoff
- _pending_for(monkeypatch, _account())
- guest_handoff._update(guest_handoff._records_path(), next(iter(_records())),
- lambda r: {**r, "state": "retrying", "attempts": 40})
portal.claim_answers = [_err(503, "temporarily_disabled")]
- guest_handoff.drain()
- record = _only_record()
- assert record["state"] == "retrying" and record["anon_token"]
- assert float(record["next_attempt_at"]) - guest_handoff._now() >= guest_handoff._BACKOFF_SECONDS[-1] - 5
-
-
-# --- Binding, sharing, durability -----------------------------------------------------------------
-
-def test_a_retry_only_claims_into_the_destination_account(portal, monkeypatch):
- from hermes_cli import guest_handoff
- monkeypatch.setattr(guest_handoff, "_BACKOFF_SECONDS", (60.0,))
- portal.claim_answers = [_err(409, "account_busy")]
_mint_guest()
_persist(_account())
- assert _only_record()["state"] == "retrying"
+ assert guest_handoff.drain() == [] and len(portal.claims) == 1
- # The profile now holds another account: the record is not claimed into it.
- _persist(_account(sub="someone_else", refresh="rt_other"))
- monkeypatch.setattr(guest_handoff, "_now", lambda: time.time() + 10_000)
- guest_handoff.drain()
- assert len(portal.claims) == 1 and _only_record()["destination"] == DESTINATION
-
- _persist(_account(refresh="rt_back"))
- guest_handoff.drain()
- assert len(portal.claims) == 2 and _only_record()["state"] == "claimed"
+# --- Sharing, durability --------------------------------------------------------------------------
def test_two_profiles_sharing_one_guest_claim_once(portal, monkeypatch, tmp_path):
from hermes_cli import anon_auth, guest_handoff
@@ -299,17 +284,13 @@ def test_two_profiles_sharing_one_guest_claim_once(portal, monkeypatch, tmp_path
assert len(_only_record()["profiles"]) == 2
-def test_a_crash_between_save_and_claim_is_claimed_on_next_boot(portal, monkeypatch):
- from hermes_cli import auth_nous, guest_handoff
+def test_a_crash_between_save_and_claim_is_claimed_on_the_next_run(portal):
+ from hermes_cli import guest_handoff
anon = _mint_guest()
- monkeypatch.setattr(auth_nous, "drain", lambda: None) # the process dies before the claim
- _persist(_account())
+ _save(_account()) # the process dies before the claim
assert portal.claims == [] and _only_record()["state"] == "pending"
- monkeypatch.setattr(auth_nous, "drain", guest_handoff.drain)
- monkeypatch.setattr(guest_handoff, "_local", threading.local()) # a fresh process
- guest_handoff.retry_all_profiles() # its retry worker's first tick
-
+ guest_handoff.drain() # the next process's retry worker tick
assert [c["body"] for c in portal.claims] == [{"token": anon}]
assert _only_record()["state"] == "claimed"
@@ -324,108 +305,16 @@ def test_a_claimed_record_is_never_reopened(portal):
assert len(portal.claims) == 1 and _only_record()["state"] == record["state"] == "claimed"
-def test_a_surface_lock_defers_the_claim_until_it_is_released(portal):
+def test_a_run_while_an_attempt_is_in_flight_sends_nothing(portal):
from hermes_cli import guest_handoff
_mint_guest()
- with guest_handoff.deferred() as batch:
- _persist(_account())
- assert portal.claims == [] and _only_record()["state"] == "pending"
- assert len(portal.claims) == 1
- assert batch.account_email == "[email protected]"
-
-
-# --- Review round 1: the apps never land in an account the record is not bound to ----------------
-
-def _pending_for(monkeypatch, account) -> None:
- """A saved account and its pending record, the claim not yet run."""
- _mint_guest()
- _pending_for_current_guest(monkeypatch, account)
-
-
-def _pending_for_current_guest(monkeypatch, account) -> None:
- from hermes_cli import auth_nous, guest_handoff
- monkeypatch.setattr(auth_nous, "drain", lambda: None)
- _persist(account)
- monkeypatch.setattr(auth_nous, "drain", guest_handoff.drain)
- assert _only_record()["state"] == "pending"
-
-
-def test_a_sign_in_racing_the_claim_never_moves_apps_into_it(portal, monkeypatch):
- from hermes_cli import auth_nous, guest_handoff
- _pending_for(monkeypatch, _account())
- real_bearer = guest_handoff._bearer
-
- def bearer_after_another_sign_in(**kw):
- monkeypatch.setattr(auth_nous, "drain", lambda: None)
- _persist(_account(sub="intruder", refresh="rt_intruder")) # lands after the bound check
- return real_bearer(**kw)
-
- monkeypatch.setattr(guest_handoff, "_bearer", bearer_after_another_sign_in)
- guest_handoff.drain()
- assert portal.claims == []
- assert _only_record()["state"] == "pending" and _only_record()["attempts"] == 0
-
-
-def test_a_destination_rebound_before_the_attempt_is_not_claimed_into_the_old_account(portal, monkeypatch):
- from hermes_cli import guest_handoff
- _pending_for(monkeypatch, _account())
- real_update, fired = guest_handoff._update, []
-
- def sibling_wins_the_records_lock_first(path, key, change):
- if not fired: # the runner's first locked write; a sibling's rebind lands just before it
- fired.append(True)
- guest_handoff.note_replacement(
- {"auth_method": "anonymous", "anon_token": "anon_0001"}, _account(sub="sibling_acct"))
- return real_update(path, key, change)
-
- monkeypatch.setattr(guest_handoff, "_update", sibling_wins_the_records_lock_first)
+ _save(_account())
+ portal.on_claim = lambda: portal.__dict__.setdefault("inner", guest_handoff.drain())
guest_handoff.drain()
- assert portal.claims == []
- assert _only_record()["destination"] == "sibling_acct" and _only_record()["state"] == "pending"
+ assert len(portal.claims) == 1 and portal.inner == [] and _only_record()["state"] == "claimed"
-def _age_record(days: float, **fields) -> None:
- from hermes_cli import guest_handoff
- created = guest_handoff._iso(guest_handoff._now() - days * 86400)
- guest_handoff._update(guest_handoff._records_path(), next(iter(_records())),
- lambda r: {**r, "created_at": created, **fields})
-
-
-def test_retries_stop_safely_before_the_free_tier_is_reaped(portal, monkeypatch):
- from hermes_cli import guest_handoff
- _pending_for(monkeypatch, _account())
- _age_record(13.5, state="retrying", attempts=300)
- guest_handoff.drain()
- assert portal.claims == []
- assert _only_record()["state"] == "failed" and _only_record()["error"] == "retry_window_ended"
-
-
[email protected]("trigger", ["auth_status", "auth_upgrade", "sign_in"])
-def test_a_record_an_older_build_failed_on_a_transient_error_is_rearmed(portal, monkeypatch, capsys, trigger):
- from hermes_cli import anon_auth, auth_commands
- anon = _mint_guest()
- _pending_for_current_guest(monkeypatch, _account())
- _age_record(2, state="failed", error="retries_exhausted", attempts=8)
- if trigger == "auth_status":
- auth_commands.auth_status_command(SimpleNamespace(provider="nous"))
- elif trigger == "auth_upgrade":
- anon_auth.upgrade_guest(SimpleNamespace(no_browser=True, timeout=None))
- else:
- _persist(_account(refresh="rt_again")) # the account saved again (re-login)
- assert [c["body"] for c in portal.claims] == [{"token": anon}]
- assert _only_record()["state"] == "claimed"
-
-
-def test_a_final_refusal_is_not_rearmed(portal, monkeypatch):
- from hermes_cli import auth_commands
- _pending_for(monkeypatch, _account())
- _age_record(1, state="failed", error="account_locked", attempts=1)
- auth_commands.auth_status_command(SimpleNamespace(provider="nous"))
- assert portal.claims == [] and _only_record()["state"] == "failed"
-
-
[email protected]("code", ["client_not_allowed", "account_locked", "invalid_request",
- "retry_window_ended", "some_new_code", None])
[email protected]("code", ["client_not_allowed", "account_locked", "invalid_request", "some_new_code", None])
def test_failure_copy_never_prints_a_server_code(code):
from hermes_cli import guest_handoff
lines = guest_handoff.status_lines({"state": "failed", "error": code})
@@ -451,46 +340,6 @@ def test_gone_on_a_first_attempt_reads_as_neutral(portal):
assert guest_handoff.status_lines(guest_handoff.handoff_status()) == ["Nothing left to move from the free tier."]
-def test_a_slow_refusal_at_the_budget_edge_starts_no_refresh_or_second_claim(portal, monkeypatch):
- from hermes_cli import guest_handoff
- clock = [1000.0]
- monkeypatch.setattr(guest_handoff.time, "monotonic", lambda: clock[0])
- portal.claim_answers = [_err(401, "invalid_token")]
- portal.on_claim = lambda: clock.__setitem__(0, clock[0] + guest_handoff.SYNC_BUDGET_SECONDS + 5)
- _mint_guest()
- _persist(_account())
- assert len(portal.claims) == 1 and portal.refreshes == 0
- assert _only_record()["state"] == "pending" and _only_record()["attempts"] == 0
-
-
-def test_corrupt_records_neither_block_a_sign_in_nor_stop_the_retry_worker(portal, monkeypatch):
- from hermes_cli import guest_handoff
- path = guest_handoff._records_path()
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text("{not json", encoding="utf-8")
- assert guest_handoff.retry_all_profiles() == []
-
- _mint_guest()
- _persist(_account())
- assert _only_record()["state"] == "claimed"
- assert path.with_suffix(".json.corrupt").read_text(encoding="utf-8") == "{not json"
-
-
-def test_a_move_bound_to_another_account_reads_as_paused(portal, monkeypatch):
- from hermes_cli import guest_handoff
- portal.claim_answers = [_err(409, "account_busy")]
- monkeypatch.setattr(guest_handoff, "_BACKOFF_SECONDS", (60.0,))
- _mint_guest()
- _persist(_account())
- assert guest_handoff.handoff_status()["state"] == "retrying"
- _persist(_account(sub="someone_else", refresh="rt_other"))
- status = guest_handoff.handoff_status()
- assert status["state"] == "paused"
- assert "another Nous account" in guest_handoff.status_lines(status)[0]
-
-
-# --- Review round 2: retries reach every profile; the first attempt is not lost -------------------
-
def test_a_long_lived_process_with_a_guest_still_runs_the_handoff_worker(portal, monkeypatch):
from hermes_cli import guest_handoff, nous_auth_keepalive
monkeypatch.setattr(nous_auth_keepalive, "get_provider_auth_state",
@@ -503,21 +352,6 @@ def test_a_long_lived_process_with_a_guest_still_runs_the_handoff_worker(portal,
assert guest_handoff._worker_thread is None
-def test_the_worker_retries_a_named_profiles_move_from_the_launch_profile(portal, monkeypatch, tmp_path):
- import os
- from hermes_cli import guest_handoff
- anon = _mint_guest()
- _pending_for_current_guest(monkeypatch, _account())
- launch = tmp_path / "launch-profile"
- launch.mkdir()
- named_home = os.environ["HERMES_HOME"]
- monkeypatch.setenv("HERMES_HOME", str(launch)) # the long-lived process runs as another profile
- guest_handoff.retry_all_profiles()
- assert [c["body"] for c in portal.claims] == [{"token": anon}]
- monkeypatch.setenv("HERMES_HOME", named_home)
- assert _only_record()["state"] == "claimed"
-
-
def test_a_guest_token_still_cached_from_a_connector_call_does_not_skip_the_move(portal):
from hermes_cli import auth
from hermes_constants import hermes_home_key
@@ -527,30 +361,6 @@ def test_a_guest_token_still_cached_from_a_connector_call_does_not_skip_the_move
assert len(portal.claims) == 1 and _only_record()["state"] == "claimed"
-def test_a_held_auth_lock_cannot_stretch_the_sync_budget(portal, monkeypatch):
- from hermes_cli import auth, guest_handoff
- _pending_for(monkeypatch, _account())
- monkeypatch.setattr(guest_handoff, "SYNC_BUDGET_SECONDS", 1.0)
- held, release = threading.Event(), threading.Event()
-
- def hold_auth_lock():
- with auth._auth_store_lock():
- held.set()
- release.wait(30)
-
- holder = threading.Thread(target=hold_auth_lock, daemon=True)
- holder.start()
- held.wait(5)
- started = time.monotonic()
- try:
- guest_handoff.drain()
- finally:
- release.set()
- holder.join(5)
- assert time.monotonic() - started < 6
- assert portal.claims == [] and _only_record()["state"] == "pending" and _only_record()["attempts"] == 0
-
-
def test_auth_status_shows_what_moved(portal, capsys):
from hermes_cli import auth_commands
_mint_guest()
@@ -558,7 +368,7 @@ def test_auth_status_shows_what_moved(portal, capsys):
capsys.readouterr()
auth_commands.auth_status_command(SimpleNamespace(provider="nous"))
out = capsys.readouterr().out
- assert "nous: logged in" in out and "Your apps moved to [email protected]: gmail." in out
+ assert "nous: logged in" in out and "Your apps moved to [email protected]: Gmail." in out
@pytest.mark.parametrize("kind", ["moved", "swapped"])
@@ -583,6 +393,6 @@ def test_status_copy_never_names_the_mechanism(portal):
):
text = " ".join(guest_handoff.status_lines(status)).lower()
assert text and not any(word in text for word in ("guest", "anonymous", "claim"))
- moved = guest_handoff.status_lines(
- {"state": "claimed", "connectors_kind": "moved", "moved_toolkits": ["gmail"], "account_email": "[email protected]"})
- assert moved == ["Your apps moved to [email protected]: gmail."]
+ moved = guest_handoff.status_lines({"state": "claimed", "connectors_kind": "moved", "account_email": "[email protected]",
+ "moved_toolkits": ["gmail", "googlecalendar"], "dropped_toolkits": ["linear"]})
+ assert moved == ["Your apps moved to [email protected]: Gmail, Google Calendar.", "Reconnect in [email protected]: Linear."]
diff --git a/tests/hermes_cli/test_login_cli_command.py b/tests/hermes_cli/test_login_cli_command.py
index 2e77efb3ec2..92ea3ab3605 100644
--- a/tests/hermes_cli/test_login_cli_command.py
+++ b/tests/hermes_cli/test_login_cli_command.py
@@ -41,7 +41,7 @@ def test_the_cli_handler_prints_the_code_then_drains_off_thread(monkeypatch):
states = iter([
anon_auth.Code("https://example.test/sign-in", "CODE-1", 900, 5),
anon_auth.Completed(email="[email protected]", model="model-1", model_changed=True,
- handoff=("Your apps moved to [email protected]: gmail.",)),
+ handoff=("Your apps moved to [email protected]: Gmail.",)),
])
monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: states)
monkeypatch.setattr(
@@ -58,7 +58,7 @@ def test_the_cli_handler_prints_the_code_then_drains_off_thread(monkeypatch):
]
assert workers[0][0].started is True
assert workers[0][0].target() == (
- "Signed in as [email protected].\nYour apps moved to [email protected]: gmail.\n"
+ "Signed in as [email protected].\nYour apps moved to [email protected]: Gmail.\n"
"Default model is now model-1.")
@pytest.mark.parametrize(
diff --git a/tests/hermes_cli/test_plain_login_settle.py b/tests/hermes_cli/test_plain_login_settle.py
index 14be35c9956..11abb78e758 100644
--- a/tests/hermes_cli/test_plain_login_settle.py
+++ b/tests/hermes_cli/test_plain_login_settle.py
@@ -13,7 +13,8 @@ from types import SimpleNamespace
import pytest
-from hermes_cli import anon_auth, auth_nous, guest_handoff
+from hermes_cli import anon_auth, auth_nous
+from tests.hermes_cli.test_guest_handoff import holds_auth_locks
from tests.hermes_cli.test_anon_upgrade import (
EMAIL, FREE_PICK, INFERENCE, PORTAL, REFRESH_TOKEN, WELCOME, _jwt, _model_config, _write_model_config,
free_account, portal)
@@ -63,7 +64,7 @@ def test_the_sign_in_settles_the_config_once_after_its_locks_are_released(
real_settle = anon_auth.settle_after_upgrade
def _recording(state):
- settles.append(guest_handoff._holds_auth_locks())
+ settles.append(holds_auth_locks())
return real_settle(state)
monkeypatch.setattr(anon_auth, "settle_after_upgrade", _recording)
@@ -88,5 +89,5 @@ def test_the_terminal_sign_in_prints_what_moved(portal, free_account, monkeypatc
surface(monkeypatch)
out = capsys.readouterr().out
- assert f"Your apps moved to {EMAIL}: gmail." in out
- assert f"Reconnect in {EMAIL}: slack." in out
+ assert f"Your apps moved to {EMAIL}: Gmail." in out
+ assert f"Reconnect in {EMAIL}: Slack." in out
diff --git a/website/docs/developer-guide/cli-internals.md b/website/docs/developer-guide/cli-internals.md
index e3bfe64c37a..510507aa2bf 100644
--- a/website/docs/developer-guide/cli-internals.md
+++ b/website/docs/developer-guide/cli-internals.md
@@ -156,43 +156,37 @@ that identity's connected apps to the account: `POST /api/anonymous/claim {"toke
with the account's own Bearer token. Nothing asks the user first; the result is shown afterwards
(`hermes auth status nous`; the desktop reads it from the sign-in poll's `handoff_status` and, while a
move is still retrying, from the `GET /api/providers/oauth/nous/handoff?since=&wait=` long-poll, which
-answers once the record's `updated_at` changes). Sign-in code does not
-call it:
+answers once the record's `updated_at` changes). Two halves:
- `note_replacement` runs at the two lowest write seams (`auth._store_provider_state` and
`auth_nous._write_shared_nous_state`) under the caller's auth-store locks and only writes a pending
record. Records live in `guest_handoff.json` beside the shared Nous store, keyed by a hash of the
- `anon_` credential and bound to the destination account, so profiles sharing one free-tier
- identity share one record and one claim.
+ `anon_` credential, so profiles sharing one free-tier identity share one record and one claim.
- Only a sign-in changes which identity the shared store holds. Every `_write_shared_nous_state`
caller declares `renewal`: a token refresh (`renewal=True`) never replaces another identity there
(identity = the guest's `anon_` credential, or the account's JWT `sub`), so a refresh of one
profile's account never replaces a guest another profile minted. That refresh is kept beside the
held identity under `renewal`, where sibling profiles on the same account read their next
single-use refresh token.
-- `drain` runs the claim outside every lock, bounded to about 10 s (each record, lock wait, token
- read and request counts against the budget): after a shared-store write, when a
- `guest_handoff.deferred()` block exits (a surface that saves under its own lock, such as the desktop
- poller, wraps the save in it), and after a free-tier reconcile. It only moves apps; config
- completion (`settle_after_upgrade`) stays with the sign-in that saved the account.
-- Retries left by any process are finished by a retry worker that every long-lived Nous process
- starts (`start_nous_auth_keepalive` starts it, guest or not). Each tick runs every due record
- under its owning profile's home and secrets, so a named profile's move retries from a process
- launched as another profile.
-- Every attempt is reserved in one locked read-modify-write that checks the record is still due,
- inside its retry window, and bound to the account whose Bearer is about to be sent (the token's
- `sub` must equal the record's destination). Apps never go to any other account.
+- `drain` makes one attempt per due record of this profile and returns what each did. It sends a
+ request, so it runs only outside the auth-store locks: every sign-in surface calls it right after
+ its save (`run_sign_in` after its `persist_guard` is released), and so do a free-tier reconcile,
+ `hermes auth status` and `hermes auth upgrade`. It only moves apps; config completion
+ (`settle_after_upgrade`) stays with the sign-in that saved the account.
+- A move a transient error left retrying is finished by a retry worker that every long-lived Nous
+ process starts (`start_nous_auth_keepalive` starts it, guest or not); each tick drains the
+ process's own profile.
+- Each attempt is counted and the record leased (not due for about 30 s) in one locked write before
+ the request leaves, so a lost answer still counts and two runs never send the same record.
Answers: `claimed` records what moved (and refreshes the account token only when
`cohort_carried`; an answer without `connectors` reads as unknown, never "nothing moved");
`unknown_token` is Gone, read as "probably moved" after an earlier attempt (a lost success);
-`already_retired` is Gone too; a 401 refreshes the account token once. Only codes no later attempt
-can change are final (`client_not_allowed`, `account_locked`, `invalid_request`). Every other refusal,
-unknown codes included, and every transport failure retries with backoff (Retry-After honoured), the
-slowest rung repeating, until 13 days after the record was made: the service reaps an idle free-tier
-identity, apps included, after 14. A record an older build failed on a transient code re-arms on the
-next run (a sign-in, `hermes auth status`, `hermes auth upgrade`, the retry worker). A Claimed record
-is never reopened, and user copy never shows a server code.
+`already_retired` is Gone too. Only codes no later attempt can change are final
+(`client_not_allowed`, `account_locked`, `invalid_request`). Every other answer, 401 and unknown
+codes included, and every transport failure retries after 1 minute, 10 minutes, 1 hour and 6 hours
+(Retry-After honoured), then the record is Failed. A Claimed record is never reopened, and user copy
+never shows a server code; app slugs show as display names (`tools.tool_labels.app_title`).
## Process identity: never infer it from argv substrings