The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): repair-profiles moves a session whose title the target store already holds
John Paul Soliva3dd848f263e0
diff --git a/hermes_cli/sessions_repair_profiles.py b/hermes_cli/sessions_repair_profiles.pyindex d93df3665c2..7a05c1d7d7c 100644--- a/hermes_cli/sessions_repair_profiles.py+++ b/hermes_cli/sessions_repair_profiles.py@@ -368,16 +368,25 @@ class _MoveBatch:(parents before children, so a moved child keeps its moved parent), then delete from the source.Row by row, deleting a parent would detach the children still waiting in the source. Copyprecedes delete, so a crash between the two leaves a duplicate the next run settles- (``present`` on import, then the delete)."""+ (``present`` on import, then the delete). A row that fails is that row's failure alone: the+ rest of the batch still moves, and only its lineage (descendants, and the parent it still+ points at in the source) waits with it for the next run."""def __init__(self, src: Store, dst: Store) -> None:self.src, self.dst = src, dstself.ids: List[str] = []self._result: Optional[Dict[str, Dict[str, int]]] = None+ self._errors: Dict[str, Exception] = {}def fix_for(self, sid: str) -> Callable[[_Session], Dict[str, int]]:self.ids.append(sid)- return lambda session: self.run(session).get(sid, {"missing": 1})+ return lambda session: self._outcome(session, sid)++ def _outcome(self, session: _Session, sid: str) -> Dict[str, int]:+ result = self.run(session)+ if sid in self._errors:+ raise self._errors[sid]+ return result.get(sid, {"missing": 1})def run(self, session: _Session) -> Dict[str, Dict[str, int]]:if self._result is not None:@@ -387,18 +396,35 @@ class _MoveBatch:ordered = _parents_first([p for p in payloads.values() if p is not None])result: Dict[str, Dict[str, int]] = {sid: {"missing": 1} for sid, p in payloads.items() if p is None}for payload in ordered:- sid = payload["session"]["id"]- outcome = dst_db.import_moved_session(payload, profile_name=self.dst.profile)+ sid, parent = payload["session"]["id"], payload["session"].get("parent_session_id")+ if parent in self._errors:+ # Imported now, it would land without the parent and never regain the link.+ self._errors[sid] = RuntimeError(+ f"its parent {parent} did not move; kept in the {self.src.profile} store with it")+ continue+ try:+ outcome = dst_db.import_moved_session(payload, profile_name=self.dst.profile)+ except Exception as exc:+ self._errors[sid] = exc+ continueif dst_db.count_messages_all(sid) < len(payload["messages"]):logger.warning("repair-profiles: %s copied into %s with fewer messages than the source; ""source row kept", sid, self.dst.profile)result[sid] = {"copied_incomplete": 1}continueresult[sid] = {outcome: 1}+ # Deleting a row detaches its children still in the source; a child that did not move+ # must find its parent there on the next run.+ awaited = {p["session"].get("parent_session_id") for p in ordered if p["session"]["id"] in self._errors}for payload in ordered:sid = payload["session"]["id"]- if "copied_incomplete" not in result[sid] and src_db.delete_moved_session(sid):- result[sid]["moved"] = 1+ if sid not in result or sid in awaited or "copied_incomplete" in result[sid]:+ continue+ try:+ if src_db.delete_moved_session(sid):+ result[sid]["moved"] = 1+ except Exception as exc:+ self._errors[sid] = excself._result = resultreturn resultdiff --git a/hermes_state_profile_repair.py b/hermes_state_profile_repair.pyindex 34d88cd7bef..2fca02c7315 100644--- a/hermes_state_profile_repair.py+++ b/hermes_state_profile_repair.py@@ -201,7 +201,10 @@ class SessionProfileRepairMixin:"""Insert a moved session into THIS store as *profile_name*'s. ``present`` when the id alreadyexists (an earlier run copied but did not delete), else ``imported``. The parent link survivesonly when the parent is already here — a moved row must never point across stores or at a- row of another profile. Columns the target schema lacks are dropped, never invented."""+ row of another profile. Columns the target schema lacks are dropped, never invented. Titles+ are unique per store only, so a title an unrelated row here already holds gets the moved+ row's id tail (the :meth:`import_foreign_history` convention); the resident row keeps its+ name, since it is the one this profile's clients resolve by title."""session = dict(payload["session"])session_id = session["id"]@@ -212,6 +215,10 @@ class SessionProfileRepairMixin:parent_id = session.get("parent_session_id")if parent_id and conn.execute("SELECT 1 FROM sessions WHERE id = ?", (parent_id,)).fetchone() is None:session["parent_session_id"] = None+ title = session.get("title")+ if title is not None and conn.execute("SELECT 1 FROM sessions WHERE title = ?", (title,)).fetchone():+ suffix = f" ({session_id[-12:]})"+ session["title"] = title[:self.MAX_TITLE_LENGTH - len(suffix)] + suffixsession["system_prompt_hash"] = self._store_system_prompt(conn, payload.get("system_prompt"))self._insert_row(conn, "sessions", session, skip=frozenset())for message in payload.get("messages") or []:diff --git a/tests/hermes_cli/test_sessions_repair_profiles.py b/tests/hermes_cli/test_sessions_repair_profiles.pyindex c26d7917eb3..d3202c2ef2a 100644--- a/tests/hermes_cli/test_sessions_repair_profiles.py+++ b/tests/hermes_cli/test_sessions_repair_profiles.py@@ -234,3 +234,103 @@ def test_legacy_main_rekey_adopts_a_standalone_gateways_history(homes, monkeypatfinally:acme.close()assert not any(f["kind"] == "legacy_main" for f in _report()["findings"])++[email protected]("colliding", ["first", "second"])[email protected]("title", ["Grocery list", "G" * SessionDB.MAX_TITLE_LENGTH])+def test_move_into_a_store_that_already_holds_the_title(homes, monkeypatch, colliding, title):+ """Titles are unique per store only. A stranded row whose title an unrelated session of the+ target profile already holds used to raise on the unique-title index, fail every row of the+ batch, and leave the rows copied before it in both stores, on every run."""+ monkeypatch.setattr("hermes_cli.sessions_cmd_repair_profiles.default_snapshot", lambda store: "snap")+ root = SessionDB(homes["default"] / "state.db")+ acme = SessionDB(homes["acme"] / "state.db")+ try:+ _session(root, "s-a", "agent:acme:telegram:dm:210", profile="acme")+ _session(root, "s-b", "agent:acme:telegram:dm:211", profile="acme", messages=3)+ _session(acme, "w-1", ACME_KEY, profile="acme")+ clash, other = ("s-a", "s-b") if colliding == "first" else ("s-b", "s-a")+ root.set_session_title(clash, title)+ root.set_session_title(other, "Weekend plans")+ acme.set_session_title("w-1", title)+ finally:+ root.close()+ acme.close()++ assert _run(apply=True) == 0++ root = SessionDB(homes["default"] / "state.db")+ acme = SessionDB(homes["acme"] / "state.db")+ try:+ assert root.get_session("s-a") is None and root.get_session("s-b") is None+ assert len(acme.get_messages("s-a")) == 2 and len(acme.get_messages("s-b")) == 3+ assert acme.get_session(other)["title"] == "Weekend plans"+ # the resident row keeps the name, so resolving it by title still finds it+ assert acme.get_session("w-1")["title"] == title+ assert acme.resolve_session_by_title(title) == "w-1"+ moved = acme.get_session(clash)["title"]+ assert moved not in (None, title) and len(moved) <= SessionDB.MAX_TITLE_LENGTH+ finally:+ root.close()+ acme.close()+ assert not any(f["kind"] == "wrong_store" for f in _report()["findings"])++[email protected]("stage", ["import", "delete"])+def test_a_failing_row_moves_alone_and_its_lineage_waits_with_it(homes, monkeypatch, capsys, stage):+ """One row that cannot move is that row's failure: an unrelated row of the same batch still+ moves, the batch is not re-run per finding, and the failed row's lineage stays linked so the+ next run moves it whole."""+ monkeypatch.setattr("hermes_cli.sessions_cmd_repair_profiles.default_snapshot", lambda store: "snap")+ root = SessionDB(homes["default"] / "state.db")+ try:+ _session(root, "gp", "agent:acme:telegram:dm:220", profile="acme")+ _session(root, "par", "agent:acme:telegram:dm:220", profile="acme", parent="gp")+ _session(root, "kid", "agent:acme:telegram:dm:220", profile="acme", parent="par")+ _session(root, "lone", "agent:acme:telegram:dm:221", profile="acme")+ finally:+ root.close()++ method = "import_moved_session" if stage == "import" else "delete_moved_session"+ real = getattr(SessionDB, method)+ calls = []++ def flaky(self, arg, **kw):+ sid = arg["session"]["id"] if stage == "import" else arg+ calls.append(sid)+ if sid == "par":+ raise sqlite3.OperationalError("disk I/O error")+ return real(self, arg, **kw)++ monkeypatch.setattr(SessionDB, method, flaky)+ assert _run(apply=True) == 1+ out = capsys.readouterr().out+ assert "wrong_store par: OperationalError: disk I/O error" in out+ assert sorted(calls) == sorted(set(calls)), "the batch was re-run for a later finding"++ root = SessionDB(homes["default"] / "state.db")+ acme = SessionDB(homes["acme"] / "state.db")+ try:+ assert root.get_session("lone") is None and acme.get_session("lone") is not None+ if stage == "import":+ assert "wrong_store kid:" in out+ # the child never lands parentless; the grandparent stays for the parent that points at it+ assert acme.get_session("kid") is None and acme.get_session("par") is None+ assert root.get_session("kid")["parent_session_id"] == "par"+ assert root.get_session("par")["parent_session_id"] == "gp"+ finally:+ root.close()+ acme.close()++ monkeypatch.setattr(SessionDB, method, real)+ assert _run(apply=True) == 0+ root = SessionDB(homes["default"] / "state.db")+ acme = SessionDB(homes["acme"] / "state.db")+ try:+ assert all(root.get_session(sid) is None for sid in ("gp", "par", "kid", "lone"))+ assert acme.get_session("par")["parent_session_id"] == "gp"+ assert acme.get_session("kid")["parent_session_id"] == "par"+ finally:+ root.close()+ acme.close()+ assert not any(f["kind"] == "wrong_store" for f in _report()["findings"])