The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): low-disk prompt reaches Desktop/Ink sessions and reports each profile honestly
Teknium292457639cd2
diff --git a/gateway/run_housekeeping_disk.py b/gateway/run_housekeeping_disk.pyindex 2644226b04b..ffcc064a772 100644--- a/gateway/run_housekeeping_disk.py+++ b/gateway/run_housekeeping_disk.py@@ -2,7 +2,8 @@home-channel prompt for the low-disk auto-prune decision (see ``hermes_cli/prune_advisor.py``).A headless gateway on a small VPS is where a disk fills up, and its owner may never open the CLI,-so the question goes to each served profile's home channel. It is posted at most once per+so the question goes to each served profile's home channel; Desktop and Ink TUI viewers of local+sessions get it as a notice. It is posted at most once persnooze window per profile: posting records the snooze, and ``/autoprune on|off`` ends it for good.Runs from the housekeeping thread; the send is scheduled onto the gateway loop."""@@ -42,30 +43,67 @@ def housekeeping_media_caches() -> None:def maybe_post_auto_prune_prompt(runner, loop) -> None:- """One housekeeping tick: post the prompt to every served profile whose disk is low and who- has not decided. Cheap when nothing is due (two syscalls + a YAML read per profile)."""+ """One housekeeping tick: post the prompt to every served profile that has a home channel, a+ low disk and no decision yet. Cheap when nothing is due (two syscalls + a YAML read per+ profile); the database estimate runs only for a profile that can actually receive it."""if runner is None or loop is None:returnfrom agent.async_utils import safe_schedule_threadsafefrom hermes_cli import prune_advisorfrom hermes_constants import get_routing_process_hermes_home+ reachable = {profile for profile, *_rest in runner._served_home_channel_transports()}homes: dict = {None: get_routing_process_hermes_home()}homes.update(getattr(runner, "_served_profile_homes", None) or {})for profile, home in homes.items():- if prune_advisor.should_ask(Path(home)) is None:+ if profile not in reachable or prune_advisor.should_ask(Path(home)) is None:continueadvice = prune_advisor.advise(Path(home))if advice is None:continuefut = safe_schedule_threadsafe(_post(runner, profile, home, advice), loop, logger=logger,log_message="Auto-prune prompt scheduling error")- # Snooze only on a delivered post: a gateway with no home channel (the one a CLI- # auto-starts) must not swallow the question the CLI/TUI is about to ask.+ # Snooze only on a delivered post: a send that failed must not swallow the question.if fut is not None and fut.result(timeout=60):prune_advisor.snooze(Path(home))+_LOCAL_NOTIFIED: set[str] = set()+++async def publish_local_auto_prune_notice(authority, ref) -> None:+ """Desktop / Ink TUI sessions (``AuthorityConnection.resume``): one sticky ``notification.show``+ per profile per gateway process while the disk is low and auto-prune is undecided. The classic+ CLI asks at its own startup, so its sessions are skipped here."""+ import asyncio+ from gateway.config import Platform+ from gateway.session_policy import policy_for_source+ from hermes_cli import prune_advisor+ from hermes_state_runtime import RuntimeStoreError++ live = authority.sessions.get(ref.session_id)+ source = getattr(live, "source", None)+ if source is None or source.platform != Platform.LOCAL:+ return+ try:+ policy = policy_for_source(authority.runner, source)+ except RuntimeStoreError: # policy not restored yet: this viewer gets no notice, the next one may+ return+ if policy is None or policy.source not in {"tui", "gui"}:+ return+ home = Path(authority.db.db_path).parent+ if str(home) in _LOCAL_NOTIFIED or prune_advisor.should_ask(home) is None:+ return+ _LOCAL_NOTIFIED.add(str(home))+ advice = await asyncio.to_thread(prune_advisor.advise, home)+ if advice is None:+ return+ live.event_stream.publish(ref.session_id, {+ "text": "⚠ " + " ".join(prune_advisor.advice_lines(advice)), "level": "warn", "kind": "sticky",+ "ttl_ms": None, "key": "sessions.auto_prune", "id": "sessions.auto_prune"},+ event_type="notification.show")++async def _post(runner, profile, home, advice) -> bool:"""Send to the profile's home channels; True when at least one send was delivered."""from gateway.run import _async_profile_runtime_scopediff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex ba4e3060e51..98af790bea3 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -512,6 +512,7 @@ class AuthorityConnection:self.authority.authorize(self.actor, ref, 'session:read')snapshot = await self.authority.attach(self.actor, ref)self.subscriptions[ref.session_id] = snapshot.subscription_id+ self._spawn_notice(ref)# Only local routes have a frozen local launch policy to project; with it, main's banner and# status-bar inventory (tools, skills, MCP, version, branch) for that policy.info = {'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL}@@ -533,6 +534,14 @@ class AuthorityConnection:'pending': [asdict(r) for r in snapshot.pending],'prompts': list(snapshot.prompts), 'info': info}+ def _spawn_notice(self, ref):+ """Low-disk auto-prune question for this viewer, off the resume reply's path."""+ from gateway.run_housekeeping_disk import publish_local_auto_prune_notice+ task = asyncio.get_running_loop().create_task(publish_local_auto_prune_notice(self.authority, ref))+ tasks = self.__dict__.setdefault('_notice_tasks', set())+ tasks.add(task)+ task.add_done_callback(tasks.discard)+async def detach(self, ref, params):if set(params) - {'end_reason'} != {'session_id', 'subscription_id'}:raise RuntimeStoreError('invalid_params')diff --git a/hermes_cli/prune_advisor.py b/hermes_cli/prune_advisor.pyindex 487ad11c075..50ade9fcd7e 100644--- a/hermes_cli/prune_advisor.py+++ b/hermes_cli/prune_advisor.py@@ -56,6 +56,8 @@ class Advice:prunable_sessions: inttotal_sessions: intreclaim_bytes: int # estimate: the prunable share of messages times the file size+ estimate_ok: bool = True # False when state.db could not be read (counts are unknown, not zero)+ vacuum_after_prune: bool = True@propertydef helps(self) -> bool:@@ -86,15 +88,21 @@ def disk_snapshot(home: Optional[Path] = None) -> Optional[DiskSnapshot]:return DiskSnapshot(size, usage.free, usage.total)-def undecided(home: Optional[Path] = None) -> bool:- """True while the user's own config.yaml has no ``sessions.auto_prune`` (default not chosen)."""+def _user_sessions_config(home: Optional[Path]) -> Optional[dict]:+ """The ``sessions:`` block of *home*'s own config.yaml ({} when absent); None when unreadable."""import hermes_yaml as yamlfrom hermes_cli.config import read_user_config_rawtry:sessions = read_user_config_raw(_home(home) / "config.yaml").get("sessions")- except (OSError, ValueError, yaml.YAMLError): # unreadable/broken config: never nag on top of it- return False- return not (isinstance(sessions, dict) and "auto_prune" in sessions)+ except (OSError, ValueError, yaml.YAMLError):+ return None+ return sessions if isinstance(sessions, dict) else {}+++def undecided(home: Optional[Path] = None) -> bool:+ """True while the user's own config.yaml has no ``sessions.auto_prune`` (default not chosen)."""+ sessions = _user_sessions_config(home)+ return sessions is not None and "auto_prune" not in sessions # unreadable config: never nag on itdef _snooze_path(home: Optional[Path]) -> Path:@@ -131,9 +139,13 @@ def advise(home: Optional[Path] = None) -> Optional[Advice]:snap = should_ask(home)if snap is None:return None- from hermes_cli.config import load_config_readonly- retention = int(((load_config_readonly() or {}).get("sessions") or {}).get("retention_days", 90) or 90)+ # Read the settings from THIS home's config: gateway housekeeping calls this for every served+ # profile without entering its scope. Only an explicit key differs from the defaults here.+ sessions = _user_sessions_config(home) or {}+ retention = sessions.get("retention_days", 90)+ retention = retention if isinstance(retention, int) and retention >= 0 else 90prunable = total = prunable_msgs = total_msgs = 0+ estimate_ok = Truetry:from hermes_state import SessionDBdb = SessionDB(db_path=_home(home) / "state.db", read_only=True)@@ -147,8 +159,10 @@ def advise(home: Optional[Path] = None) -> Optional[Advice]:db.close()except (sqlite3.Error, OSError, RuntimeError, ValueError) as exc: # a busy/damaged store: no estimatelogger.debug("auto-prune advice: reclaim estimate unavailable: %s", exc)+ estimate_ok = Falsereclaim = int(snap.db_bytes * prunable_msgs / total_msgs) if total_msgs else 0- return Advice(snap, retention, int(prunable), int(total), reclaim)+ return Advice(snap, retention, int(prunable), int(total), reclaim, estimate_ok,+ bool(sessions.get("vacuum_after_prune", True)))def _gb(n: int) -> str:@@ -169,16 +183,22 @@ def advice_lines(advice: Advice, *, command_prefix: str = "/") -> list[str]:f"Auto-prune is off. Turning it on deletes ended sessions inactive for more than "f"{advice.retention_days} days, once a day (pinned and open sessions are kept).",]- if advice.prunable_sessions == 0:+ if not advice.estimate_ok:+ lines.append("Could not read state.db to estimate how much pruning would free.")+ elif advice.prunable_sessions == 0:held = (f"none of your {_sessions(advice.total_sessions)} is older than {advice.retention_days} days"if advice.total_sessions else "there is no session history to delete")lines.append(f"Pruning will not help right now: {held}. Something else is filling this disk.")elif not advice.helps:- lines.append(f"Pruning would free only about {_gb(advice.reclaim_bytes)} "+ lines.append(f"Pruning would remove only about {_gb(advice.reclaim_bytes)} of history "f"({_sessions(advice.prunable_sessions)}), which will not fix this disk on its own.")else:- lines.append(f"Pruning would free about {_gb(advice.reclaim_bytes)} "+ lines.append(f"Pruning would remove about {_gb(advice.reclaim_bytes)} of history "f"({advice.prunable_sessions} of {_sessions(advice.total_sessions)}).")+ if advice.estimate_ok and advice.prunable_sessions:+ lines.append("The file shrinks when state.db is next compacted (VACUUM), which needs other Hermes "+ "windows closed." if advice.vacuum_after_prune else+ "sessions.vacuum_after_prune is off, so state.db keeps its size until you run a VACUUM.")p = command_prefixlines.append(f"{p}autoprune on to enable, {p}autoprune off to keep everything (never asked again), "f"{p}autoprune later to be reminded in a week.")@@ -244,14 +264,14 @@ def offer_interactive(*, cprint, ask=input) -> Optional[bool]:print()return Noneanswer = answer.strip().lower()- if answer in {"y", "yes"}:- decide(True)- cprint(" ✓ sessions.auto_prune: true")- return True- if answer in {"n", "no"}:- decide(False)- cprint(" ✓ sessions.auto_prune: false. You won't be asked again.")- return False+ if answer in {"y", "yes", "n", "no"}:+ enable = answer.startswith("y")+ if not decide(enable):+ cprint(" Could not save sessions.auto_prune; check disk space and config.yaml permissions.")+ return None+ cprint(" ✓ sessions.auto_prune: true" if enable else+ " ✓ sessions.auto_prune: false. You won't be asked again.")+ return enablesnooze()cprint(" Later. /autoprune on|off decides it any time.")return Nonediff --git a/tests/hermes_cli/test_prune_advisor.py b/tests/hermes_cli/test_prune_advisor.pyindex f8fd21c00c4..69b488f3c1d 100644--- a/tests/hermes_cli/test_prune_advisor.py+++ b/tests/hermes_cli/test_prune_advisor.py@@ -60,3 +60,6 @@ def test_prompt_says_pruning_will_not_help_when_nothing_is_old_enough(home, monkadvice = prune_advisor.advise(home)assert advice.prunable_sessions == 1assert "will not help" not in "\n".join(prune_advisor.advice_lines(advice))+ # The estimate reads THIS home's settings; an explicit 0-day retention is kept, not defaulted.+ (home / "config.yaml").write_text("sessions:\n retention_days: 0\n", encoding="utf-8")+ assert prune_advisor.advise(home).retention_days == 0