Skip to content

The agent that grows with you

fix(sessions): give titles provenance so they stop overwriting themselves

Brooklyn Nicholson5566379f57ae
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 4eed5b44e21..8282bab2214 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3331,13 +3331,52 @@ def compress_context(
migrate_heartbeat_to_session(old_session_id, agent.session_id)
except Exception as _hb_err:
logger.debug("Could not migrate heartbeat on compression: %s", _hb_err)
- # Auto-number the title for the continuation session
+ # Carry the title across the compression boundary unchanged.
+ #
+ # This used to renumber ("Fix X" → "Fix X #2") on every
+ # rotation, which is why a long conversation ended up as
+ # "Smallville Map Architecture Plan #10" — ten forks of ONE
+ # session, each looking like a separate piece of work in the
+ # sidebar. Compression is an internal implementation detail;
+ # the user's conversation did not change topic, so its name
+ # must not change either. Uniqueness still holds because
+ # _set_session_title transfers the title off a hidden
+ # compression ancestor rather than raising on the conflict.
if old_title:
+ # Read provenance BEFORE the write: transferring the
+ # title off a hidden compression ancestor clears the
+ # ancestor's row, so reading afterwards always returns
+ # None and the child would be stamped "user" — freezing
+ # an auto-title that should still be upgradeable.
+ _src = None
+ try:
+ _src = agent._session_db.get_session_title_source(
+ old_session_id
+ )
+ except Exception as _src_err:
+ logger.debug(
+ "Could not read title provenance: %s", _src_err
+ )
try:
- new_title = agent._session_db.get_next_title_in_lineage(old_title)
- agent._session_db.set_session_title(agent.session_id, new_title)
+ agent._session_db.set_session_title(
+ agent.session_id, old_title
+ )
except (ValueError, Exception) as e:
logger.debug("Could not propagate title on compression: %s", e)
+ else:
+ # set_session_title() records "user"; restore the
+ # original authority so an inherited auto-title
+ # stays upgradeable and a manual one stays pinned.
+ if _src is not None:
+ try:
+ agent._session_db.set_session_title_source(
+ agent.session_id, _src
+ )
+ except Exception as _src_err:
+ logger.debug(
+ "Could not propagate title provenance: %s",
+ _src_err,
+ )
# In-place mode still updates/replaces the current row here.
# Rotation already published prompt + compacted handoff atomically.
diff --git a/hermes_state.py b/hermes_state.py
index 35c28c0117c..24e840c0364 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -5897,6 +5897,33 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# Maximum length for session titles
MAX_TITLE_LENGTH = 100
+ # Title provenance, lowest to highest authority. An auto-titling write may
+ # only replace a title of strictly lower authority, so the instant
+ # ``derived`` title upgrades to the model's ``llm`` title exactly once and
+ # nothing the agent generates can ever clobber a name the user typed.
+ TITLE_SOURCE_DERIVED = "derived"
+ TITLE_SOURCE_LLM = "llm"
+ TITLE_SOURCE_USER = "user"
+ _TITLE_SOURCE_RANK = {
+ TITLE_SOURCE_DERIVED: 0,
+ TITLE_SOURCE_LLM: 1,
+ TITLE_SOURCE_USER: 2,
+ }
+
+ @classmethod
+ def _title_rank(cls, source: Optional[str]) -> int:
+ """Rank a stored title_source. NULL means a pre-provenance row.
+
+ Rows written before this column existed carry NULL. They were almost
+ always set by the old auto-titler, but a manual ``/title`` from that
+ era is indistinguishable — so treat NULL as ``user`` and refuse to
+ overwrite it. Auto-titling only ever fills genuinely empty titles on
+ legacy rows, which is the conservative direction.
+ """
+ if source is None:
+ return cls._TITLE_SOURCE_RANK[cls.TITLE_SOURCE_USER]
+ return cls._TITLE_SOURCE_RANK.get(str(source), 0)
+
@staticmethod
def sanitize_title(title: Optional[str]) -> Optional[str]:
"""Validate and sanitize a session title.
@@ -5987,17 +6014,35 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
session_id: str,
title: str,
*,
- only_if_empty: bool,
+ source: str,
) -> bool:
+ """Write a title, enforcing provenance precedence.
+
+ ``source`` is one of ``TITLE_SOURCE_{DERIVED,LLM,USER}``. A ``user``
+ write always lands — an explicit rename is authoritative. An automatic
+ write (``derived``/``llm``) lands only when the row is untitled or the
+ stored title has strictly lower authority, so the instant ``derived``
+ title upgrades to ``llm`` exactly once and neither can ever overwrite a
+ name the user typed. Re-running the titler on an already-``llm`` row is
+ a no-op, which is what stops a session renaming itself.
+
+ The read and the write are one compare-and-swap inside a single
+ transaction, so a manual ``/title`` racing an in-flight generation
+ cannot be clobbered by the late arrival.
+ """
title = self.sanitize_title(title)
+ is_user = source == self.TITLE_SOURCE_USER
+ new_rank = self._title_rank(source) if not is_user else None
def _do(conn):
- if only_if_empty:
- current = conn.execute(
- "SELECT title FROM sessions WHERE id = ?",
- (session_id,),
- ).fetchone()
- if current is None or current["title"] is not None:
+ current = conn.execute(
+ "SELECT title, title_source FROM sessions WHERE id = ?",
+ (session_id,),
+ ).fetchone()
+ if current is None:
+ return 0
+ if not is_user and current["title"] is not None:
+ if self._title_rank(current["title_source"]) >= new_rank:
return 0
if title:
@@ -6031,10 +6076,19 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
raise ValueError(
f"Title '{title}' is already in use by session {conflict_id}"
)
- predicate = " AND title IS NULL" if only_if_empty else ""
+ # Compare-and-swap on the exact values we just read (``IS`` is
+ # NULL-safe in SQLite), so a concurrent write between the SELECT
+ # and here loses instead of being silently overwritten.
cursor = conn.execute(
- f"UPDATE sessions SET title = ? WHERE id = ?{predicate}",
- (title, session_id),
+ "UPDATE sessions SET title = ?, title_source = ? "
+ "WHERE id = ? AND title IS ? AND title_source IS ?",
+ (
+ title,
+ source if title else None,
+ session_id,
+ current["title"],
+ current["title_source"],
+ ),
)
return cursor.rowcount
@@ -6042,23 +6096,40 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return rowcount > 0
def set_session_title(self, session_id: str, title: str) -> bool:
- """Set or update a session's title.
+ """Set or update a session's title on the user's behalf.
Returns True if session was found and title was set.
Raises ValueError if title is already in use by another session,
or if the title fails validation (too long, invalid characters).
Empty/whitespace-only strings are normalized to None (clearing the title).
+
+ This records ``user`` provenance, so auto-titling will never replace
+ the result. Automatic callers must use :meth:`set_auto_title`.
"""
- return self._set_session_title(session_id, title, only_if_empty=False)
+ return self._set_session_title(
+ session_id, title, source=self.TITLE_SOURCE_USER
+ )
+
+ def set_auto_title(self, session_id: str, title: str, *, source: str) -> bool:
+ """Set an automatically generated title, honoring provenance precedence.
+
+ Returns True when the title was written, False when a higher-authority
+ title already holds the row (nothing is modified in that case).
+ """
+ if source not in (self.TITLE_SOURCE_DERIVED, self.TITLE_SOURCE_LLM):
+ raise ValueError(f"invalid automatic title source: {source!r}")
+ return self._set_session_title(session_id, title, source=source)
def set_auto_title_if_empty(self, session_id: str, title: str) -> bool:
- """Set an auto-generated title only when the current title is NULL.
+ """Back-compat shim: set an LLM title only if nothing better exists.
- The predicate and write run in one transaction so a concurrent manual
- rename cannot be overwritten. Validation and uniqueness behavior match
- :meth:`set_session_title`.
+ Retained because older callers (and third-party plugins) reference it
+ by name. New code should call :meth:`set_auto_title` with an explicit
+ source.
"""
- return self._set_session_title(session_id, title, only_if_empty=True)
+ return self.set_auto_title(
+ session_id, title, source=self.TITLE_SOURCE_LLM
+ )
def get_session_title(self, session_id: str) -> Optional[str]:
"""Get the title for a session, or None."""
@@ -6069,6 +6140,38 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
row = cursor.fetchone()
return row["title"] if row else None
+ def get_session_title_source(self, session_id: str) -> Optional[str]:
+ """Get the provenance of a session's title, or None when untitled."""
+ with self._lock:
+ cursor = self._conn.execute(
+ "SELECT title, title_source FROM sessions WHERE id = ?",
+ (session_id,),
+ )
+ row = cursor.fetchone()
+ if not row or row["title"] is None:
+ return None
+ return row["title_source"]
+
+ def set_session_title_source(self, session_id: str, source: str) -> bool:
+ """Overwrite a title's provenance without touching the title text.
+
+ Used when a title is carried across a session boundary (compression
+ rotation) and the copy must keep the original's authority rather than
+ the authority of whichever setter performed the copy.
+ """
+ if source not in self._TITLE_SOURCE_RANK:
+ raise ValueError(f"invalid title source: {source!r}")
+
+ def _do(conn):
+ cursor = conn.execute(
+ "UPDATE sessions SET title_source = ? "
+ "WHERE id = ? AND title IS NOT NULL",
+ (source, session_id),
+ )
+ return cursor.rowcount
+
+ return self._execute_write(_do) > 0
+
def set_session_archived(self, session_id: str, archived: bool) -> bool:
"""Archive or unarchive a session.
diff --git a/hermes_state_common.py b/hermes_state_common.py
index be24d8a1159..4fb7dc848c7 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -242,6 +242,7 @@ CREATE TABLE IF NOT EXISTS sessions (
cost_source TEXT,
pricing_version TEXT,
title TEXT,
+ title_source TEXT,
last_activity_at REAL,
last_activity_description TEXT,
last_activity_provenance TEXT,
diff --git a/tests/run_agent/test_in_place_compaction.py b/tests/run_agent/test_in_place_compaction.py
index d45964be8b6..2149a2d0c84 100644
--- a/tests/run_agent/test_in_place_compaction.py
+++ b/tests/run_agent/test_in_place_compaction.py
@@ -185,13 +185,16 @@ class TestRotationFallbackWhenFlagOff:
# Identity rotated to a fresh id.
assert agent.session_id != sid
- # Old session ended via compression; continuation forked + renamed.
+ # Old session ended via compression; continuation forked and
+ # carries the SAME name. Compression is an internal detail — the
+ # conversation didn't change topic, so it must not be renumbered
+ # into "my-research #2" and shown as a separate piece of work.
assert db.get_session(sid)["end_reason"] == "compression"
child = db._conn.execute(
"SELECT id, title FROM sessions WHERE parent_session_id = ?", (sid,)
).fetchall()
assert len(child) == 1
- assert child[0]["title"] == "my-research #2"
+ assert child[0]["title"] == "my-research"
# The compacted child is persisted atomically at the rotation
# boundary, so a headless process killed before finalization can
# still resume it without duplicating the two handoff messages.