hermes_state_titles.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """Session title mixin for SessionDB: sanitizing, auto/user provenance ranking, and
  2. lineage-aware lookups."""
  3. from __future__ import annotations
  4. import logging
  5. import re
  6. from typing import Any, Dict, Optional
  7. from agent.message_sanitization import _sanitize_surrogates
  8. from hermes_state_common import _COMPRESSION_CHILD_SQL, _non_continuation_child_sql, escape_like as _escape_like
  9. # caplog tests pin the "hermes_state" logger name.
  10. logger = logging.getLogger("hermes_state")
  11. # ASCII controls (keeping \t \n \r for the whitespace collapse), then zero-width,
  12. # bidi override, object-replacement and interlinear-annotation code points.
  13. _TITLE_CONTROL_RE = re.compile(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]')
  14. _TITLE_INVISIBLE_RE = re.compile(r'[\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff\ufffc\ufff9-\ufffb]')
  15. _NUMBERED_TITLE_RE = re.compile(r'^(.*?) #(\d+)$')
  16. def next_title_in_lineage(conn, base_title: str) -> str:
  17. """Next title in a lineage ("my session" -> "my session #2") as seen by *conn*: strip any
  18. " #N" suffix, then increment the highest existing number."""
  19. match = _NUMBERED_TITLE_RE.match(base_title)
  20. base = match.group(1) if match else base_title
  21. rows = conn.execute(
  22. "SELECT title FROM sessions WHERE title = ? OR title LIKE ? ESCAPE '\\'",
  23. (base, f"{_escape_like(base)} #%")).fetchall()
  24. if not rows:
  25. return base
  26. # The unnumbered original counts as #1.
  27. numbers = [int(m.group(2)) for m in (_NUMBERED_TITLE_RE.match(row[0]) for row in rows) if m]
  28. return f"{base} #{max([1, *numbers]) + 1}"
  29. class SessionTitlesMixin:
  30. """Sanitizing, ranking auto/user titles, lineage-aware lookups."""
  31. @classmethod
  32. def _title_rank(cls, source: Optional[str]) -> int:
  33. """Rank a stored title_source. NULL (pre-provenance rows) is indistinguishable from a
  34. manual ``/title`` of that era, so it ranks as ``user``."""
  35. rank = cls._TITLE_SOURCE_RANK
  36. return rank[cls.TITLE_SOURCE_USER] if source is None else rank.get(str(source), 0)
  37. @staticmethod
  38. def sanitize_title(title: Optional[str]) -> Optional[str]:
  39. """Strip control/zero-width/bidi chars (and lone surrogates sqlite3 cannot bind),
  40. collapse whitespace, normalize empty to None. ValueError past MAX_TITLE_LENGTH."""
  41. from hermes_state import SessionDB
  42. if not title:
  43. return None
  44. cleaned = _TITLE_INVISIBLE_RE.sub('', _TITLE_CONTROL_RE.sub('', _sanitize_surrogates(title)))
  45. cleaned = re.sub(r'\s+', ' ', cleaned).strip()
  46. if not cleaned:
  47. return None
  48. if len(cleaned) > SessionDB.MAX_TITLE_LENGTH:
  49. raise ValueError(f"Title too long ({len(cleaned)} chars, max {SessionDB.MAX_TITLE_LENGTH})")
  50. return cleaned
  51. def _is_compression_ancestor(self, conn, *, ancestor_id: str, descendant_id: str) -> bool:
  52. """True if *ancestor_id* is a compression predecessor of *descendant_id*, via the
  53. canonical continuation edge ``_COMPRESSION_CHILD_SQL`` (excludes delegate/branch
  54. children that also carry ``parent_session_id``, even under a compressed parent)."""
  55. if not ancestor_id or not descendant_id or ancestor_id == descendant_id:
  56. return False
  57. edge = _COMPRESSION_CHILD_SQL.format(a="child") + _non_continuation_child_sql("child.", "parent.id")
  58. return conn.execute(f"""
  59. WITH RECURSIVE ancestors(id) AS (
  60. SELECT ?
  61. UNION
  62. SELECT parent.id
  63. FROM ancestors a
  64. JOIN sessions child ON child.id = a.id
  65. JOIN sessions parent ON parent.id = child.parent_session_id
  66. WHERE {edge}
  67. )
  68. SELECT 1 FROM ancestors WHERE id = ? AND id != ? LIMIT 1
  69. """, (descendant_id, ancestor_id, descendant_id)).fetchone() is not None
  70. def _set_session_title(self, session_id: str, title: str, *, source: str) -> bool:
  71. """Write a title, enforcing provenance precedence. A ``user`` write always lands;
  72. ``derived``/``llm`` land only when the row is untitled or holds strictly lower
  73. authority (derived upgrades to llm exactly once, nothing overwrites a user name,
  74. re-running the titler on an llm row is a no-op). No writer may move a hidden
  75. canonical Bot Chat off its title. Read and write are one compare-and-swap
  76. transaction, so a manual ``/title`` racing an in-flight generation is not clobbered."""
  77. return bool(self._execute_write(
  78. lambda conn: self._set_session_title_in_transaction(conn, session_id, title, source=source)
  79. ))
  80. def _set_session_title_in_transaction(self, conn, session_id: str, title: str, *, source: str):
  81. """Reuse title rules within an authority-owned transaction; never commit here."""
  82. title = self.sanitize_title(title)
  83. is_user = source == self.TITLE_SOURCE_USER
  84. new_rank = self._title_rank(source) if not is_user else None
  85. affected = []
  86. current = conn.execute(
  87. "SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),
  88. ).fetchone()
  89. if current is None:
  90. return []
  91. # The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by
  92. # exact-title lookup on every open), so a rename orphans the conversation. Hidden
  93. # is the discriminator: canonical chats are born hidden; a visible session merely
  94. # named "Bot Chat" stays renameable. Provenance-blind.
  95. if ((current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE and bool(current["hidden"])
  96. and title != self.CANONICAL_BOT_CHAT_TITLE):
  97. if is_user:
  98. raise ValueError("This is the bot's canonical Bot Chat — its name is its "
  99. "identity, and renaming it would orphan the conversation. "
  100. "To start fresh, create a new bot instead.")
  101. return []
  102. if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:
  103. return []
  104. if title:
  105. cleared = self._resolve_title_conflict(conn, session_id, title)
  106. if cleared:
  107. affected.append(cleared)
  108. # CAS on the values just read (``IS`` is NULL-safe): a concurrent write between
  109. # the SELECT and here loses instead of being overwritten.
  110. changed = conn.execute(
  111. "UPDATE sessions SET title = ?, title_source = ? WHERE id = ? AND title IS ? AND title_source IS ?",
  112. (title, source if title else None, session_id, current["title"], current["title_source"]),
  113. ).rowcount
  114. return [*affected, session_id] if changed else affected
  115. def _resolve_title_conflict(self, conn, session_id: str, title: str) -> Optional[str]:
  116. """Free ``title`` for ``session_id`` inside the caller's write transaction, or raise
  117. ValueError when another session legitimately holds it. The one place the uniqueness
  118. rule lives, shared by renames and the API server's create-with-title. Returns the id
  119. whose title was cleared (an affected row for mutation receipts), else None."""
  120. conflict = conn.execute(
  121. f"SELECT id, archived, hidden, {self._EMPTY_SESSION_WHERE} AS ghost "
  122. "FROM sessions WHERE title = ? AND id != ?", (title, session_id),
  123. ).fetchone()
  124. if not conflict:
  125. return None
  126. conflict_id = conflict["id"]
  127. # A hidden compressed ancestor holding the title cannot be freed by the
  128. # user, so transfer it onto the tip (uniqueness + lineage kept).
  129. if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):
  130. conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))
  131. return conflict_id
  132. # A deliberately archived hidden Bot Chat is a retired registry
  133. # entry, not a live identity. Retire its name in the same title
  134. # transaction so a replacement can become the sole canonical row;
  135. # the old session remains archived and otherwise untouched.
  136. # An ended, empty, visible ghost (abandoned new chat that listings filter
  137. # out, so the user cannot find it to free the name) yields too (#81888).
  138. # The full index stays: a ``message_count > 0`` partial index would make
  139. # the ghost's first append_message fail with IntegrityError.
  140. if (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])
  141. and bool(conflict["hidden"])) or (conflict["ghost"] and not conflict["hidden"]):
  142. conn.execute(
  143. "UPDATE sessions SET title = NULL, title_source = NULL WHERE id = ?",
  144. (conflict_id,),
  145. )
  146. return conflict_id
  147. raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")
  148. def set_session_title(self, session_id: str, title: str) -> bool:
  149. """Set a title on the user's behalf (``user`` provenance). Empty clears it. Raises
  150. ValueError on conflict or validation failure."""
  151. return self._set_session_title(session_id, title, source=self.TITLE_SOURCE_USER)
  152. def set_auto_title(self, session_id: str, title: str, *, source: str) -> bool:
  153. """Set an automatic title; False (untouched) when a higher-authority title holds the row."""
  154. if source not in (self.TITLE_SOURCE_DERIVED, self.TITLE_SOURCE_LLM):
  155. raise ValueError(f"invalid automatic title source: {source!r}")
  156. return self._set_session_title(session_id, title, source=source)
  157. def get_session_title(self, session_id: str) -> Optional[str]:
  158. """Get the title for a session, or None."""
  159. row = self._read_one("SELECT title FROM sessions WHERE id = ?", (session_id,))
  160. return row["title"] if row else None
  161. def get_session_title_source(self, session_id: str) -> Optional[str]:
  162. """Get the provenance of a session's title, or None when untitled."""
  163. row = self._read_one("SELECT title, title_source FROM sessions WHERE id = ?", (session_id,))
  164. return row["title_source"] if row and row["title"] is not None else None
  165. def set_session_title_source(self, session_id: str, source: str) -> bool:
  166. """Overwrite a title's provenance without touching the text (a title copied across a
  167. compression rotation keeps the original's authority)."""
  168. if source not in self._TITLE_SOURCE_RANK:
  169. raise ValueError(f"invalid title source: {source!r}")
  170. return self._write_rowcount(
  171. "UPDATE sessions SET title_source = ? WHERE id = ? AND title IS NOT NULL", (source, session_id)
  172. ) > 0
  173. def get_session_by_title(self, title: str) -> Optional[dict[str, Any]]:
  174. """Look up a session by exact title. Returns session dict or None."""
  175. row = self._read_one(
  176. "SELECT s.*, COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved "
  177. "FROM sessions s LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash "
  178. "WHERE s.title = ?", (title,))
  179. return self._session_row_dict(row) if row else None
  180. def resolve_session_by_title(self, title: str) -> Optional[str]:
  181. """Resolve a title to a session ID, preferring the latest "title #N" continuation."""
  182. exact = self.get_session_by_title(title)
  183. # Exception to the "#N continuation" preference: the canonical Bot Chat's identity
  184. # IS its exact title (Bot Mode re-resolves it by name on every open, no id pointer).
  185. # A "<title> #N" sibling — a Desktop branch or a client-minted numbered row — is NOT
  186. # a Bot Mode session: it is visible, unmanaged, and the message_agent gate is off in
  187. # it. Every DM transport (``hermes -p <bot> chat --in ~ -c "Bot Chat"``: message_agent,
  188. # bot_relay, cron delivery) resolves through here, so letting the numbered row win
  189. # silently routes teammates' messages into a chat whose bot cannot answer back.
  190. if exact is not None and title == self.CANONICAL_BOT_CHAT_TITLE:
  191. return exact["id"]
  192. # Escape LIKE wildcards so "%"/"_" in titles cannot false-match.
  193. numbered = self._read_all(
  194. "SELECT id, title, started_at FROM sessions "
  195. "WHERE title LIKE ? ESCAPE '\\' ORDER BY started_at DESC",
  196. (f"{_escape_like(title)} #%",))
  197. return numbered[0]["id"] if numbered else (exact["id"] if exact else None)
  198. def get_next_title_in_lineage(self, base_title: str) -> str:
  199. """Next title in a lineage ("my session" -> "my session #2")."""
  200. return self._read_retrying_ioerr(lambda conn: next_title_in_lineage(conn, base_title))
  201. def lineage_title_on_conn(conn, base_title: str) -> str:
  202. """``get_next_title_in_lineage`` inside an authority-owned transaction (same connection, so a
  203. sibling branch committed in this transaction is counted)."""
  204. return next_title_in_lineage(conn, base_title)