The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): order async session git metadata
embwl0xe89532d97eb2
diff --git a/hermes_state.py b/hermes_state.pyindex 3a4459f275f..325bd485c0e 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -5318,11 +5318,11 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)self,session_id: str,cwd: str,- git_branch: str = None,- git_repo_root: str = None,+ git_branch: Optional[str] = None,+ git_repo_root: Optional[str] = None,replace_git_meta: bool = False,- ) -> None:- """Persist the session working directory when a frontend knows it.+ ) -> Optional[int]:+ """Persist the authoritative cwd and claim a Git metadata generation.``git_branch`` records the git branch checked out in ``cwd`` at the timethe session started/resumed. The sidebar groups main-checkout sessions@@ -5340,27 +5340,100 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)MOVE (re-homing a session into another project) must overwrite the oldrepo identity even when the new cwd resolves to none — keeping the staleroot would leave the session grouped under the project it just left.++ Every call increments ``git_metadata_generation`` in the same write+ transaction. Async Git probes must publish through+ :meth:`publish_session_git_metadata` with the returned generation, so+ an older worker cannot overwrite a newer cwd claim even after an+ A -> B -> A transition or from another process sharing this database.+ Metadata from a different cwd is cleared atomically with the move."""if not session_id or not cwd:- return+ return None++ branch = (git_branch or "").strip()+ repo_root = (git_repo_root or "").strip()++ def _do(conn):+ current = conn.execute(+ "SELECT cwd FROM sessions WHERE id = ?", (session_id,)+ ).fetchone()+ if current is None:+ return None++ current_cwd = current["cwd"] if isinstance(current, sqlite3.Row) else current[0]+ sets = [+ "cwd = ?",+ "git_metadata_generation = COALESCE(git_metadata_generation, 0) + 1",+ ]+ params: List[Any] = [cwd]+ if current_cwd != cwd or replace_git_meta:+ sets.extend(("git_branch = ?", "git_repo_root = ?"))+ params.extend((branch or None, repo_root or None))+ elif branch:+ sets.append("git_branch = ?")+ params.append(branch)+ if repo_root and current_cwd == cwd and not replace_git_meta:+ sets.append("git_repo_root = ?")+ params.append(repo_root)+ params.append(session_id)+ conn.execute(+ f"UPDATE sessions SET {', '.join(sets)} WHERE id = ?", params+ )+ row = conn.execute(+ "SELECT git_metadata_generation FROM sessions WHERE id = ?",+ (session_id,),+ ).fetchone()+ if row is None:+ return None+ value = row["git_metadata_generation"] if isinstance(row, sqlite3.Row) else row[0]+ return int(value)++ return self._execute_write(_do)++ def publish_session_git_metadata(+ self,+ session_id: str,+ cwd: str,+ generation: int,+ git_branch: Optional[str] = None,+ git_repo_root: Optional[str] = None,+ ) -> bool:+ """Publish async Git enrichment only while its cwd claim is current."""+ if (+ not session_id+ or not cwd+ or isinstance(generation, bool)+ or not isinstance(generation, int)+ or generation < 1+ ):+ return Falsebranch = (git_branch or "").strip()repo_root = (git_repo_root or "").strip()+ if not branch and not repo_root:+ return False- sets = ["cwd = ?"]- params: List[Any] = [cwd]- if branch or replace_git_meta:+ sets: List[str] = []+ params: List[Any] = []+ if branch:sets.append("git_branch = ?")- params.append(branch or None)- if repo_root or replace_git_meta:+ params.append(branch)+ if repo_root:sets.append("git_repo_root = ?")- params.append(repo_root or None)- params.append(session_id)+ params.append(repo_root)+ params.extend((session_id, cwd, generation))def _do(conn):- conn.execute(f"UPDATE sessions SET {', '.join(sets)} WHERE id = ?", params)+ cursor = conn.execute(+ f"UPDATE sessions SET {', '.join(sets)} "+ "WHERE id = ? AND cwd = ? "+ "AND git_metadata_generation = ?",+ params,+ )+ return cursor.rowcount == 1- self._execute_write(_do)+ return bool(self._execute_write(_do))def backfill_repo_roots(self, cwd_to_root: Dict[str, str]) -> None:"""Persist resolved git repo roots for cwds that don't have one yet.@@ -7872,7 +7945,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)# declarative reconciliation are included automatically instead of# silently dropping out of list rows._SESSION_COMPACT_EXCLUDED = frozenset(- {"system_prompt", "system_prompt_hash"}+ {"system_prompt", "system_prompt_hash", "git_metadata_generation"})_session_compact_cols_sql: Optional[str] = Nonediff --git a/hermes_state_common.py b/hermes_state_common.pyindex 5a9e4893e6c..7186c8205db 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -216,7 +216,7 @@ def _sql_session_last_active_by_id(session_id_expr: str) -> str:)-SCHEMA_VERSION = 25+SCHEMA_VERSION = 26# FTS storage-layout version, tracked INDEPENDENTLY of SCHEMA_VERSION in the@@ -285,6 +285,7 @@ CREATE TABLE IF NOT EXISTS sessions (cwd TEXT,git_branch TEXT,git_repo_root TEXT,+ git_metadata_generation INTEGER NOT NULL DEFAULT 0,billing_provider TEXT,billing_base_url TEXT,billing_mode TEXT,diff --git a/tests/state/test_session_git_metadata_generation.py b/tests/state/test_session_git_metadata_generation.pynew file mode 100644index 00000000000..2e1cb309889--- /dev/null+++ b/tests/state/test_session_git_metadata_generation.py@@ -0,0 +1,257 @@+"""Cross-process ordering for asynchronous session Git metadata probes."""++from __future__ import annotations++import sqlite3+import threading++from hermes_state import SCHEMA_VERSION, SessionDB+++def _open_pair(tmp_path):+ path = tmp_path / "state.db"+ first = SessionDB(db_path=path)+ second = SessionDB(db_path=path)+ first.create_session("session", "desktop", cwd="/repo/A")+ return first, second+++def _require_generation(value: int | None) -> int:+ assert isinstance(value, int) and not isinstance(value, bool)+ return value+++def test_delayed_probe_cannot_overwrite_newer_a_b_a_claim(tmp_path):+ first, second = _open_pair(tmp_path)+ release_old = threading.Event()+ old_finished = threading.Event()+ old_result = []+ try:+ old_generation = _require_generation(+ first.update_session_cwd("session", "/repo/A")+ )++ def publish_old_probe():+ assert release_old.wait(5)+ old_result.append(+ first.publish_session_git_metadata(+ "session",+ "/repo/A",+ old_generation,+ "stale-branch",+ "/repo/stale-root",+ )+ )+ old_finished.set()++ worker = threading.Thread(target=publish_old_probe)+ worker.start()++ second.update_session_cwd("session", "/repo/B")+ new_generation = _require_generation(+ second.update_session_cwd("session", "/repo/A")+ )+ assert new_generation > old_generation+ assert second.publish_session_git_metadata(+ "session",+ "/repo/A",+ new_generation,+ "new-branch",+ "/repo/new-root",+ )++ release_old.set()+ assert old_finished.wait(5)+ worker.join(timeout=5)+ assert not worker.is_alive()+ assert old_result == [False]++ row = second.get_session("session")+ assert row is not None+ assert row["cwd"] == "/repo/A"+ assert row["git_branch"] == "new-branch"+ assert row["git_repo_root"] == "/repo/new-root"+ finally:+ release_old.set()+ first.close()+ second.close()+++def test_repeated_same_cwd_claim_invalidates_older_probe(tmp_path):+ first, second = _open_pair(tmp_path)+ try:+ old_generation = _require_generation(+ first.update_session_cwd("session", "/repo/A")+ )+ new_generation = _require_generation(+ second.update_session_cwd("session", "/repo/A")+ )++ assert new_generation > old_generation+ assert second.publish_session_git_metadata(+ "session", "/repo/A", new_generation, "new", "/repo/A"+ )+ assert not first.publish_session_git_metadata(+ "session", "/repo/A", old_generation, "old", "/repo/old"+ )+ row = second.get_session("session")+ assert row is not None+ assert row["git_branch"] == "new"+ finally:+ first.close()+ second.close()+++def test_cwd_move_clears_metadata_in_same_claim(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ db.create_session("session", "desktop", cwd="/repo/A")+ generation = _require_generation(+ db.update_session_cwd("session", "/repo/A")+ )+ assert db.publish_session_git_metadata(+ "session", "/repo/A", generation, "main", "/repo/A"+ )++ moved_generation = _require_generation(+ db.update_session_cwd("session", "/repo/B")+ )+ row = db.get_session("session")+ assert row is not None+ assert moved_generation > generation+ assert row["cwd"] == "/repo/B"+ assert row["git_branch"] is None+ assert row["git_repo_root"] is None+ finally:+ db.close()+++def test_explicit_move_replaces_metadata_and_claims_generation(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ db.create_session("session", "desktop", cwd="/repo/A")+ initial_generation = _require_generation(+ db.update_session_cwd(+ "session",+ "/repo/A",+ git_branch="main",+ git_repo_root="/repo/A",+ )+ )++ moved_generation = _require_generation(+ db.update_session_cwd(+ "session",+ "/outside-git",+ replace_git_meta=True,+ )+ )++ row = db.get_session("session")+ assert row is not None+ assert moved_generation > initial_generation+ assert row["cwd"] == "/outside-git"+ assert row["git_branch"] is None+ assert row["git_repo_root"] is None+ finally:+ db.close()+++def test_failed_new_probe_still_invalidates_older_worker(tmp_path):+ first, second = _open_pair(tmp_path)+ try:+ baseline = _require_generation(+ first.update_session_cwd("session", "/repo/A")+ )+ assert first.publish_session_git_metadata(+ "session", "/repo/A", baseline, "baseline", "/repo/A"+ )+ old_generation = _require_generation(+ first.update_session_cwd("session", "/repo/A")+ )+ second.update_session_cwd("session", "/repo/A")++ assert not first.publish_session_git_metadata(+ "session", "/repo/A", old_generation, "stale", "/repo/stale"+ )+ row = second.get_session("session")+ assert row is not None+ assert row["git_branch"] == "baseline"+ assert row["git_repo_root"] == "/repo/A"+ finally:+ first.close()+ second.close()+++def test_generation_authority_is_scoped_to_each_profile_database(tmp_path):+ first = SessionDB(db_path=tmp_path / "profile-a.db")+ second = SessionDB(db_path=tmp_path / "profile-b.db")+ try:+ first.create_session("same-id", "desktop", cwd="/a")+ second.create_session("same-id", "desktop", cwd="/b")+ first_generation = _require_generation(+ first.update_session_cwd("same-id", "/a")+ )+ second_generation = _require_generation(+ second.update_session_cwd("same-id", "/b")+ )++ assert first.publish_session_git_metadata(+ "same-id", "/a", first_generation, "a", "/a"+ )+ assert second.publish_session_git_metadata(+ "same-id", "/b", second_generation, "b", "/b"+ )+ first_row = first.get_session("same-id")+ second_row = second.get_session("same-id")+ assert first_row is not None+ assert second_row is not None+ assert first_row["git_branch"] == "a"+ assert second_row["git_branch"] == "b"+ finally:+ first.close()+ second.close()+++def test_legacy_sessions_table_reconciles_generation_column(tmp_path):+ path = tmp_path / "state.db"+ SessionDB(db_path=path).close()+ conn = sqlite3.connect(path)+ try:+ conn.execute("ALTER TABLE sessions DROP COLUMN git_metadata_generation")+ conn.execute("UPDATE schema_version SET version = 25")+ conn.commit()+ finally:+ conn.close()++ reopened = SessionDB(db_path=path)+ try:+ verify = sqlite3.connect(path)+ try:+ columns = {+ row[1]+ for row in verify.execute("PRAGMA table_info('sessions')")+ }+ finally:+ verify.close()+ assert "git_metadata_generation" in columns+ assert reopened._conn.execute(+ "SELECT version FROM schema_version"+ ).fetchone()[0] == SCHEMA_VERSION == 26+ reopened.create_session("session", "desktop", cwd="/repo")+ assert reopened.update_session_cwd("session", "/repo") == 1+ finally:+ reopened.close()+++def test_compact_session_rows_do_not_expose_internal_generation(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ db.create_session("session", "desktop", cwd="/repo")+ db.update_session_cwd("session", "/repo")++ rows = db.list_sessions_rich(compact_rows=True)+ assert len(rows) == 1+ assert "git_metadata_generation" not in rows[0]+ finally:+ db.close()diff --git a/tests/tui_gateway/test_session_git_metadata_generation.py b/tests/tui_gateway/test_session_git_metadata_generation.pynew file mode 100644index 00000000000..89dca812013--- /dev/null+++ b/tests/tui_gateway/test_session_git_metadata_generation.py@@ -0,0 +1,72 @@+"""Gateway wiring for generation-scoped Git metadata publication."""++from __future__ import annotations++import tui_gateway.server as server+++class _ImmediateThread:+ def __init__(self, *, target, **_kwargs):+ self._target = target++ def start(self):+ self._target()+++def test_cwd_claim_precedes_probe_and_generation_reaches_publish(monkeypatch):+ events = []++ class DB:+ def update_session_cwd(self, session_id, cwd):+ events.append(("claim", session_id, cwd))+ return 17++ def publish_session_git_metadata(+ self, session_id, cwd, generation, branch, root+ ):+ events.append(+ ("publish", session_id, cwd, generation, branch, root)+ )+ return True++ monkeypatch.setattr(server, "_get_db", lambda: DB())+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(+ server,+ "_git_branch_for_cwd",+ lambda cwd: events.append(("probe", cwd)) or "feature",+ )+ monkeypatch.setattr(server, "_git_common_repo_root_for_cwd", lambda _cwd: "/repo")++ generation = server._persist_session_cwd_and_schedule_git_meta(+ {"session_key": "session"}, "/repo/worktree"+ )++ assert generation == 17+ assert events == [+ ("claim", "session", "/repo/worktree"),+ ("probe", "/repo/worktree"),+ (+ "publish",+ "session",+ "/repo/worktree",+ 17,+ "feature",+ "/repo",+ ),+ ]+++def test_missing_db_claim_never_starts_git_probe(monkeypatch):+ probed = []+ monkeypatch.setattr(server, "_get_db", lambda: None)+ monkeypatch.setattr(+ server, "_git_branch_for_cwd", lambda cwd: probed.append(cwd)+ )++ generation = server._persist_session_cwd_and_schedule_git_meta(+ {"session_key": "session"}, "/repo"+ )++ assert generation is None+ assert probed == []diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 2375c91fccf..9638e887949 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2723,13 +2723,7 @@ def _display_session_cwd(session: dict | None) -> str:healed = _heal_dead_cwd(cwd)if healed and healed != cwd and session is not None:session["cwd"] = healed- try:- with _session_db(session) as db:- if db is not None:- db.update_session_cwd(session.get("session_key", ""), healed)- except Exception:- logger.debug("failed to persist healed session cwd", exc_info=True)- _persist_session_git_meta(session, healed)+ _persist_session_cwd_and_schedule_git_meta(session, healed)return healed@@ -2812,14 +2806,7 @@ def _reconcile_session_cwd_from_terminal(session: dict | None) -> bool:session["cwd_from_settle"] = True_register_session_cwd(session)- with _session_db(session) as db:- if db is not None:- try:- db.update_session_cwd(session.get("session_key", ""), resolved)- except Exception:- logger.debug("failed to persist settled session cwd", exc_info=True)-- _persist_session_git_meta(session, resolved)+ _persist_session_cwd_and_schedule_git_meta(session, resolved)return True@@ -3092,7 +3079,7 @@ def _session_db(session: dict):db.close()-def _persist_session_git_meta(session: dict, cwd: str) -> None:+def _persist_session_git_meta(session: dict, cwd: str, generation: int) -> None:"""Resolve + persist a session's git branch / repo root WITHOUT blocking.Branch and root come from ``git`` subprocess probes; running them inline on@@ -3106,7 +3093,13 @@ def _persist_session_git_meta(session: dict, cwd: str) -> None:probe never delays gateway shutdown."""session_key = session.get("session_key", "")- if not session_key or not cwd:+ if (+ not session_key+ or not cwd+ or isinstance(generation, bool)+ or not isinstance(generation, int)+ or generation < 1+ ):return# Snapshot the routing fields now; the live session dict may be gone by the# time the thread runs. `_session_db` reopens the profile-correct db inside.@@ -3120,13 +3113,52 @@ def _persist_session_git_meta(session: dict, cwd: str) -> None:returnwith _session_db(db_session) as db:if db is not None:- db.update_session_cwd(session_key, cwd, branch, root)+ db.publish_session_git_metadata(+ session_key,+ cwd,+ generation,+ branch,+ root,+ )except Exception:logger.debug("failed to persist session git metadata", exc_info=True)threading.Thread(target=_run, name="git-meta", daemon=True).start()+def _persist_session_cwd_and_schedule_git_meta(+ session: dict,+ cwd: str,+ *,+ db=None,+) -> int | None:+ """Claim a DB-backed probe generation, then start Git enrichment."""+ try:+ if db is not None:+ generation = db.update_session_cwd(+ session.get("session_key", ""), cwd+ )+ else:+ with _session_db(session) as owner_db:+ if owner_db is None:+ return None+ generation = owner_db.update_session_cwd(+ session.get("session_key", ""), cwd+ )+ except Exception:+ logger.debug("failed to persist session cwd", exc_info=True)+ return None++ if (+ isinstance(generation, bool)+ or not isinstance(generation, int)+ or generation < 1+ ):+ return None+ _persist_session_git_meta(session, cwd, generation)+ return generation++def _set_session_cwd(session: dict, cwd: str) -> str:from hermes_constants import translate_cwd_for_wsl_backend@@ -3142,14 +3174,9 @@ def _set_session_cwd(session: dict, cwd: str) -> str:# the terminal wandering must not move the workspace again.session["cwd_from_settle"] = False_register_session_cwd(session)- with _session_db(session) as db:- if db is not None:- try:- db.update_session_cwd(session.get("session_key", ""), resolved)- except Exception:- logger.debug("failed to persist session cwd", exc_info=True)- # Branch/repo-root probes are git subprocesses — capture them off the hot path.- _persist_session_git_meta(session, resolved)+ # The synchronous DB write claims ordering authority; Git subprocesses stay+ # off the hot path and may publish only for that exact generation.+ _persist_session_cwd_and_schedule_git_meta(session, resolved)try:from tools.terminal_tool import cleanup_vm@@ -6137,14 +6164,7 @@ def _apply_project_workspace(task_id: str, path: str, _name: str = "") -> None:session["cwd_from_settle"] = False_register_session_cwd(session)- with _session_db(session) as db:- if db is not None:- try:- db.update_session_cwd(session.get("session_key", ""), resolved)- except Exception:- logger.debug("failed to persist project workspace cwd", exc_info=True)-- _persist_session_git_meta(session, resolved)+ _persist_session_cwd_and_schedule_git_meta(session, resolved)try:agent = session.get("agent")@@ -6949,9 +6969,9 @@ def _init_session(try:_cwd = _sessions[sid]["cwd"]if hasattr(db, "update_session_cwd"):- db.update_session_cwd(key, _cwd)- # git branch/root probes run off the hot path (see _set_session_cwd).- _persist_session_git_meta(_sessions[sid], _cwd)+ _persist_session_cwd_and_schedule_git_meta(+ _sessions[sid], _cwd, db=db+ )except Exception:logger.debug("failed to persist resumed session cwd", exc_info=True