The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): explain an old or locked store instead of crashing adopt
emozilla2107ee8b68b7
diff --git a/hermes_cli/sessions_adopt.py b/hermes_cli/sessions_adopt.pyindex 325e0f385d7..96ad0b0f3fa 100644--- a/hermes_cli/sessions_adopt.py+++ b/hermes_cli/sessions_adopt.py@@ -11,6 +11,7 @@ shared operator access.from __future__ import annotationsfrom collections import Counter+import sqlite3import sys_PROGRESS_EVERY = 25@@ -94,6 +95,20 @@ def _refusal(exc) -> str:return f'{reason} ({why})'+def _unreadable_store(exc: sqlite3.Error, store: str) -> str:+ """One line for a store adopt cannot read: what is wrong and what to run. Adopt opens the store+ read-only, so it neither upgrades a store from an older release nor waits out another writer."""+ from hermes_state_errors import is_sqlite_lock_error+ from hermes_state_repair import _schema_not_built++ if is_sqlite_lock_error(exc):+ return f'Error: {store} is locked by another program. Close that program, then run this command again.'+ if _schema_not_built(exc):+ return (f'Error: {store} is from an older Hermes and has not been upgraded ({exc}). Run '+ '`hermes sessions repair` to upgrade it (it makes a backup first), then run this command again.')+ return f'Error: could not read {store} ({exc}). Run `hermes sessions repair` to check it.'++def cmd_adopt(args) -> int:import asynciofrom websockets.exceptions import WebSocketException@@ -104,7 +119,11 @@ def cmd_adopt(args) -> int:if not path.exists():print(f'No session database at {display_hermes_home()}/state.db (nothing to adopt).')return 0- rows = adoptable_sessions(path)+ try:+ rows = adoptable_sessions(path)+ except sqlite3.Error as exc:+ print(_unreadable_store(exc, f'{display_hermes_home()}/state.db'), file=sys.stderr)+ return 1if not rows:print('Nothing to adopt: every local chat in this profile already belongs to its gateway.')return 0diff --git a/tests/hermes_cli/test_sessions_adopt.py b/tests/hermes_cli/test_sessions_adopt.pyindex bef126b3dfb..2a3c06eaae1 100644--- a/tests/hermes_cli/test_sessions_adopt.py+++ b/tests/hermes_cli/test_sessions_adopt.py@@ -7,7 +7,9 @@ adopts them in one pass, after which the browser login continues each."""import argparseimport asyncio+from contextlib import closingimport json+import sqlite3import pytest@@ -35,14 +37,19 @@ def _seed(home):db.close()-def _adopt(capsys, *argv):+def _run_adopt(capsys, *argv):from hermes_cli import sessions_cmdfrom hermes_cli.subcommands.sessions import build_sessions_parserparser = argparse.ArgumentParser()build_sessions_parser(parser.add_subparsers(dest='command'), cmd_sessions=sessions_cmd.cmd_sessions)args = parser.parse_args(['sessions', 'adopt', *argv])status = args.func(args)- return status, capsys.readouterr().out+ return status, capsys.readouterr()+++def _adopt(capsys, *argv):+ status, captured = _run_adopt(capsys, *argv)+ return status, captured.outasync def _rpc(socket, method, **params):@@ -113,3 +120,67 @@ def test_adopt_survives_a_long_history_and_names_what_the_owner_refused(tmp_pathassert 'Skipped 1: invalid_params (cwd: must be an absolute path to an existing directory).' in out, outresumed = asyncio.run(_browser_resume(home, descriptor, 'long-desktop'))assert resumed.get('result', {}).get('session_id') == 'long-desktop', str(resumed)[:300]+++def _rollback_journal_store(home):+ """A seeded store in rollback-journal mode, where a writer's exclusive lock also blocks readers."""+ home.mkdir(parents=True)+ _seed(home)+ with closing(sqlite3.connect(home / 'state.db', isolation_level=None)) as conn:+ assert conn.execute('PRAGMA journal_mode=DELETE').fetchone()[0] == 'delete'+ return home / 'state.db'+++def _store_files(home):+ return {path.name: path.read_bytes() for path in sorted(home.glob('state.db*'))}+++def _refused_adopt(capsys, monkeypatch, home, *argv):+ """Runs adopt where no gateway is reachable: the store has to answer before any connection."""+ from hermes_cli import gateway_client++ def no_gateway(**_kwargs):+ raise AssertionError('adopt connected to the gateway')++ monkeypatch.setattr(gateway_client, 'connect_gateway', no_gateway)+ monkeypatch.setenv('HERMES_HOME', str(home))+ status, captured = _run_adopt(capsys, *argv)+ return status, captured.out, captured.err++[email protected]('argv', [(), ('--dry-run',)])+def test_adopt_names_the_upgrade_for_a_store_no_newer_hermes_has_opened(tmp_path, monkeypatch, capsys, argv):+ """Adopt reads the store without upgrading it, so a store from an older release that lacks this+ release's tables gets one line naming the command that upgrades it, and stays as it was."""+ home = tmp_path / 'home'+ db = _rollback_journal_store(home)+ with closing(sqlite3.connect(db)) as conn:+ conn.execute('DROP TABLE state_meta')+ conn.commit()+ before = _store_files(home)++ status, out, err = _refused_adopt(capsys, monkeypatch, home, *argv)++ assert status == 1 and out == '', out+ assert len(err.splitlines()) == 1 and 'older' in err and '`hermes sessions repair`' in err, err+ assert _store_files(home) == before++[email protected]('argv', [(), ('--dry-run',)])+def test_adopt_says_to_close_the_holder_of_a_locked_store(tmp_path, monkeypatch, capsys, argv):+ """Another process's exclusive lock on a rollback-journal store blocks the read. Adopt says the+ store is locked and to retry once what holds it is closed, and changes nothing."""+ import hermes_state++ home = tmp_path / 'home'+ db = _rollback_journal_store(home)+ before = _store_files(home)+ monkeypatch.setattr(hermes_state, '_READ_BUSY_TIMEOUT_S', 0.1)+ with closing(sqlite3.connect(db, isolation_level=None)) as holder:+ holder.execute('BEGIN EXCLUSIVE')+ status, out, err = _refused_adopt(capsys, monkeypatch, home, *argv)+ holder.execute('ROLLBACK')++ assert status == 1 and out == '', out+ assert len(err.splitlines()) == 1 and 'locked' in err and 'close' in err.lower(), err+ assert _store_files(home) == before