The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(onboarding): run changes are one transaction; ended runs close the flag
alt-glitch1469522d1992
diff --git a/agent/onboarding_record.py b/agent/onboarding_record.pyindex b9aa3053760..98d9fef0773 100644--- a/agent/onboarding_record.py+++ b/agent/onboarding_record.py@@ -23,27 +23,55 @@ logger = logging.getLogger(__name__)KEY = "onboarding_run"+def _read(db, session_id: str) -> dict | None:+ record = db.get_session_model_config_value(session_id, KEY) if db is not None and session_id else None+ return record if isinstance(record, dict) else None++def load(db, session_id: str) -> dict | None:"""The run record, with the quiet-spell fallback applied (and saved) when it is due."""- record = db.get_session_model_config_value(session_id, KEY) if db is not None and session_id else None- if not isinstance(record, dict):- return None- expired = expire(record, now=time.time())- if expired is not record:- _save(db, session_id, record, expired)- return expired+ record = _read(db, session_id)+ if record is not None and expire(record, now=time.time()) is not record:+ step = _transition(db, session_id, None)+ return step.record if step is not None else None+ return record-def _save(db, session_id: str, before: Mapping[str, Any], after: dict) -> None:- db.patch_session_model_config(session_id, {KEY: after})- if is_active(before) and not is_active(after):+def _transition(db, session_id: str, event: Event | None) -> Step | None:+ """Expire, apply *event* and write the result in one database transaction, so Skip setup pressed+ while a card answer is being applied is never overwritten by the older copy. Every ended run+ then closes the install flag, so a Skip or Done retried after a failed config write repairs it."""+ holder: dict[str, Step] = {}++ def update(current: Any) -> Any:+ holder.pop("step", None)+ if not isinstance(current, dict):+ return current+ now = time.time()+ record = expire(current, now=now)+ holder["step"] = (apply(record, event, Facts.from_stored(record["facts"]), now=now)+ if event is not None else Step(record, {}))+ return holder["step"].record++ db.update_session_model_config_value(session_id, KEY, update)+ step = holder.get("step")+ if step is not None and not is_active(step.record):_close_install_flag()+ return stepdef _close_install_flag() -> None:+ from hermes_cli import config as config_modfrom hermes_cli.onboarding_run import set_run+ from hermes_constants import get_default_hermes_root++ from agent.onboarding import PROFILE_BUILD_FLAG- set_run(False, mark_profile_offered=True)+ section = config_mod.read_user_config_raw(get_default_hermes_root() / "config.yaml").get("onboarding")+ section = section if isinstance(section, dict) else {}+ seen = section.get("seen") if isinstance(section.get("seen"), dict) else {}+ if section.get("run") is not False or not seen.get(PROFILE_BUILD_FLAG):+ set_run(False, mark_profile_offered=True)def start(db, session_id: str, facts: Facts) -> dict:@@ -59,18 +87,23 @@ def start(db, session_id: str, facts: Facts) -> dict:def advance(db, session_id: str, event: Event) -> Step:"""Apply one event to the stored run; LookupError when this session has no run."""- record = load(db, session_id)- if record is None:+ step = _transition(db, session_id, event) if db is not None and session_id else None+ if step is None:raise LookupError(f"session {session_id} has no onboarding run")- step = apply(record, event, Facts.from_stored(record["facts"]), now=time.time())- if step.record != record:- _save(db, session_id, record, step.record)return stepdef active_session_id(db) -> str | None:- """The newest session whose run is still in progress."""- return next((sid for sid in db.session_ids_with_model_config_key(KEY) if is_active(load(db, sid))), None)+ """The newest chat whose run is still in progress. Rotation leaves the active copy on the+ compression parent, so each id is read at its compression tip."""+ tips: set[str] = set()+ for sid in db.session_ids_with_model_config_key(KEY):+ tip = db.resolve_resume_session_id(sid) or sid+ if tip not in tips:+ tips.add(tip)+ if is_active(load(db, tip)):+ return tip+ return Nonedef observe_tool_result(agent, name: str, args: Mapping[str, Any], result: Any) -> None:diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 816903a827e..25d657b4feb 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -832,6 +832,23 @@ class SessionSessionsMixin:session = self.get_session(session_id) or {}return _parse_model_config(session.get("model_config")).get(key, default)+ def update_session_model_config_value(self, session_id: str, key: str, update: Callable[[Any], Any]) -> bool:+ """Read ``key``, write ``update(value)`` back, in one write transaction, so a concurrent writer of+ the same key cannot be overwritten with a stale copy. ``update`` may run more than once (lock+ retry) and must be pure; returning None removes the key. False when the row does not exist."""+ def _do(conn) -> bool:+ row = conn.execute("SELECT model_config FROM sessions WHERE id = ?", (session_id,)).fetchone()+ if row is None:+ return False+ config = _parse_model_config(row[0])+ if (value := update(config.get(key))) is None:+ config.pop(key, None)+ else:+ config[key] = value+ conn.execute("UPDATE sessions SET model_config = ? WHERE id = ?", (json.dumps(config), session_id))+ return True+ return self._execute_write(_do)+def session_ids_with_model_config_key(self, key: str) -> list[str]:"""Ids of the sessions whose model_config carries ``key``, newest first."""with self._read_ctx() as conn:diff --git a/tests/tui_gateway/test_onboarding_session.py b/tests/tui_gateway/test_onboarding_session.pyindex b5bae076ed4..dc53a1c41d2 100644--- a/tests/tui_gateway/test_onboarding_session.py+++ b/tests/tui_gateway/test_onboarding_session.py@@ -11,7 +11,7 @@ from types import SimpleNamespaceimport pytestfrom agent import onboarding_record-from agent.onboarding_flow import Facts, Shown+from agent.onboarding_flow import Facts, Shown, SkipAllfrom agent.onboarding_text import GREETINGfrom tui_gateway import server, server_requests@@ -156,3 +156,29 @@ def test_a_compression_rotation_carries_the_run_record(root):assert onboarding_record.load(db, "child") == onboarding_record.load(db, "parent")assert db.get_session_model_config_value("child", "codex_thread_id") is None+ # The parent keeps its active copy; the run is read at the tip, so skipping the child ends it.+ assert onboarding_record.active_session_id(db) == "child"+ onboarding_record.advance(db, "child", SkipAll())+ assert onboarding_record.active_session_id(db) is None+++def test_a_skip_retried_after_a_failed_config_write_closes_the_install_flag(root, monkeypatch):+ from hermes_cli import onboarding_run+ from hermes_cli.config import read_user_config_raw+ db = server._get_db()+ db.create_session("onb", "desktop")+ onboarding_record.start(db, "onb", FACTS)+ real_set_run = onboarding_run.set_run++ def disk_full(value, **kw):+ raise OSError("disk full")++ monkeypatch.setattr(onboarding_run, "set_run", disk_full)+ with pytest.raises(OSError):+ onboarding_record.advance(db, "onb", SkipAll())+ monkeypatch.setattr(onboarding_run, "set_run", real_set_run)++ assert onboarding_record.load(db, "onb")["phase"] == "skipped"+ assert read_user_config_raw(root / "config.yaml")["onboarding"]["run"] is True+ onboarding_record.advance(db, "onb", SkipAll())+ assert read_user_config_raw(root / "config.yaml")["onboarding"]["run"] is False