Skip to content

The agent that grows with you

feat: add revision-fenced runtime rename and archive receipts

Teknium5878e5656ca6
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index ca3db002e23..9a896672b6b 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -171,6 +171,63 @@ def recover_session_inputs(db, *, epoch: int) -> int:
return db._execute_write(write)
+def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str,
+ request_id: str, expected_revision: int,
+ operation: str, payload: dict) -> dict:
+ """Commit a closed metadata edit and its retry receipt in the same transaction.
+
+ Caller authorizes the principal and resolves the canonical session. These
+ metadata edits do not stop execution. Existing direct writers must migrate
+ before this seam can provide universal revision fencing.
+ """
+ for value in (principal_id, session_id, request_id):
+ _text(value)
+ if type(expected_revision) is not int or expected_revision < 0:
+ raise RuntimeStoreError('invalid_params')
+ fields = {'rename': ('title', str), 'archive': ('archived', bool)}
+ if not isinstance(operation, str) or operation not in fields or not isinstance(payload, dict):
+ raise RuntimeStoreError('invalid_params')
+ field, value_type = fields[operation]
+ if set(payload) != {field} or type(payload[field]) is not value_type:
+ raise RuntimeStoreError('invalid_params')
+ # Snapshot caller data before waiting for the writer lock.
+ payload = json.loads(_json(payload))
+ key = 'gateway.session_mutation.v1.' + admission_fingerprint(
+ canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})
+ digest = admission_fingerprint(canonical_target=session_id, payload={
+ 'operation': operation, 'payload': payload, 'expected_revision': expected_revision})
+
+ def write(conn):
+ _epoch(conn, epoch)
+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
+ if old is not None:
+ receipt = json.loads(old[0])
+ if receipt['digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return receipt['result']
+ session = _session(conn, session_id)
+ if session['runtime_revision'] != expected_revision:
+ raise RuntimeStoreError('stale_revision')
+ if operation == 'rename':
+ db._set_session_title_in_transaction(
+ conn, session_id, payload['title'], source=db.TITLE_SOURCE_USER)
+ affected = [session_id]
+ else:
+ affected = db._set_lineage_column_in_transaction(
+ conn, 'archived', session_id, int(payload['archived']))
+ conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',
+ [(target,) for target in affected])
+ updated = _session(conn, session_id)
+ result = {'session_id': session_id, 'revision': updated['runtime_revision'],
+ 'operation': operation, field: updated[field]}
+ if operation == 'archive':
+ result[field] = bool(result[field])
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
+ (key, _json({'digest': digest, 'result': result})))
+ return result
+ return db._execute_write(write)
+
+
_IMPORT_KEY = 'gateway.prompt_admissions_import.v1'
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index a7039236bc5..cb49f39098c 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -795,7 +795,13 @@ class SessionSessionsMixin:
def _set_lineage_column(self, column: str, session_id: str, value: Any) -> bool:
"""Set one ``sessions`` column across a whole compression lineage: Desktop projects roots
forward to their tip, so updating only the tip would let the root resurrect it on refresh."""
- return self._write_rowcount(
+ return bool(self._execute_write(
+ lambda conn: self._set_lineage_column_in_transaction(conn, column, session_id, value)
+ ))
+
+ def _set_lineage_column_in_transaction(self, conn, column: str, session_id: str, value: Any):
+ """Return affected IDs so authority revisions share this exact lineage selector."""
+ return [row[0] for row in conn.execute(
f"""
WITH RECURSIVE
ancestors(id) AS (
@@ -824,9 +830,10 @@ class SessionSessionsMixin:
UPDATE sessions
SET {column} = ?
WHERE id IN (SELECT id FROM lineage)
+ RETURNING id
""",
(session_id, session_id, value),
- ) > 0
+ ).fetchall()]
def set_session_archived(self, session_id: str, archived: bool) -> bool:
"""Soft-hide (or unhide) a session and its compression lineage; messages are kept."""
diff --git a/hermes_state_titles.py b/hermes_state_titles.py
index 1305a2a22c3..58ef8883c51 100644
--- a/hermes_state_titles.py
+++ b/hermes_state_titles.py
@@ -72,49 +72,52 @@ class SessionTitlesMixin:
re-running the titler on an llm row is a no-op). No writer may move a hidden
canonical Bot Chat off its title. Read and write are one compare-and-swap
transaction, so a manual ``/title`` racing an in-flight generation is not clobbered."""
+ return self._execute_write(
+ lambda conn: self._set_session_title_in_transaction(conn, session_id, title, source=source)
+ ) > 0
+
+ def _set_session_title_in_transaction(self, conn, session_id: str, title: str, *, source: str):
+ """Reuse title rules within an authority-owned transaction; never commit here."""
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):
- current = conn.execute(
- "SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),
+ current = conn.execute(
+ "SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),
+ ).fetchone()
+ if current is None:
+ return 0
+ # The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by
+ # exact-title lookup on every open), so a rename orphans the conversation. Hidden
+ # is the discriminator: canonical chats are born hidden; a visible session merely
+ # named "Bot Chat" stays renameable. Provenance-blind.
+ if ((current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE and bool(current["hidden"])
+ and title != self.CANONICAL_BOT_CHAT_TITLE):
+ if is_user:
+ raise ValueError("This is the bot's canonical Bot Chat — its name is its "
+ "identity, and renaming it would orphan the conversation. "
+ "To start fresh, create a new bot instead.")
+ return 0
+ if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:
+ return 0
+ if title:
+ conflict = conn.execute(
+ "SELECT id FROM sessions WHERE title = ? AND id != ?", (title, session_id),
).fetchone()
- if current is None:
- return 0
- # The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by
- # exact-title lookup on every open), so a rename orphans the conversation. Hidden
- # is the discriminator: canonical chats are born hidden; a visible session merely
- # named "Bot Chat" stays renameable. Provenance-blind.
- if ((current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE and bool(current["hidden"])
- and title != self.CANONICAL_BOT_CHAT_TITLE):
- if is_user:
- raise ValueError("This is the bot's canonical Bot Chat — its name is its "
- "identity, and renaming it would orphan the conversation. "
- "To start fresh, create a new bot instead.")
- return 0
- if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:
- return 0
- if title:
- conflict = conn.execute(
- "SELECT id FROM sessions WHERE title = ? AND id != ?", (title, session_id),
- ).fetchone()
- if conflict:
- conflict_id = conflict["id"]
- # A hidden compressed ancestor holding the title cannot be freed by the
- # user, so transfer it onto the tip (uniqueness + lineage kept).
- if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):
- conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))
- else:
- raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")
- # CAS on the values just read (``IS`` is NULL-safe): a concurrent write between
- # the SELECT and here loses instead of being overwritten.
- return conn.execute(
- "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"]),
- ).rowcount
-
- return self._execute_write(_do) > 0
+ if conflict:
+ conflict_id = conflict["id"]
+ # A hidden compressed ancestor holding the title cannot be freed by the
+ # user, so transfer it onto the tip (uniqueness + lineage kept).
+ if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):
+ conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))
+ else:
+ raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")
+ # CAS on the values just read (``IS`` is NULL-safe): a concurrent write between
+ # the SELECT and here loses instead of being overwritten.
+ return conn.execute(
+ "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"]),
+ ).rowcount
def set_session_title(self, session_id: str, title: str) -> bool:
"""Set a title on the user's behalf (``user`` provenance). Empty clears it. Raises
diff --git a/tests/state/test_runtime_mutations.py b/tests/state/test_runtime_mutations.py
new file mode 100644
index 00000000000..124970a6d65
--- /dev/null
+++ b/tests/state/test_runtime_mutations.py
@@ -0,0 +1,75 @@
+"""Revision, replay and business-rule invariants on real isolated SQLite."""
+import sqlite3
+
+import pytest
+
+from hermes_state import SessionDB
+import hermes_state_runtime as rt
+
+
[email protected]('operation,payload', [('rename', {'title': ' New name '}), ('archive', {'archived': True})])
+def test_mutation_receipt_fences_replay_revision_and_epoch(tmp_path, operation, payload):
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ try:
+ db.create_session('s', source='test')
+ epoch = rt.begin_runtime_epoch(db, instance_id='boot')
+ mutate = getattr(rt, 'mutate_runtime_session', None)
+ assert callable(mutate), 'revision-fenced mutation operation missing'
+ args = dict(epoch=epoch, principal_id='human', session_id='s', request_id='edit', expected_revision=0, operation=operation, payload=payload)
+ result = mutate(db, **args)
+ assert result['revision'] == 1
+ assert mutate(db, **args) == result
+ assert db.get_session('s')['runtime_revision'] == 1
+ with pytest.raises(rt.RuntimeStoreError, match='admission_conflict'):
+ mutate(db, **{**args, 'expected_revision': 1})
+ with pytest.raises(rt.RuntimeStoreError, match='stale_revision'):
+ mutate(db, **{**args, 'request_id': 'other'})
+ new_epoch = rt.begin_runtime_epoch(db, instance_id='replacement')
+ with pytest.raises(rt.RuntimeStoreError, match='stale_epoch'):
+ mutate(db, **args)
+ assert mutate(db, **{**args, 'epoch': new_epoch}) == result
+ db.close()
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ assert mutate(db, **{**args, 'epoch': new_epoch}) == result
+ finally:
+ db.close()
+
+
[email protected]('operation,payload', [('rename', {'title': ' New name '}), ('archive', {'archived': True})])
+def test_mutation_rules_and_receipt_failure_are_atomic(tmp_path, operation, payload):
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ try:
+ db.create_session('s', source='test')
+ db.set_session_title('s', 'Original')
+ epoch = rt.begin_runtime_epoch(db, instance_id='boot')
+ mutate = getattr(rt, 'mutate_runtime_session', None)
+ assert callable(mutate), 'revision-fenced mutation operation missing'
+ args = dict(epoch=epoch, principal_id='human', session_id='s', request_id='edit', expected_revision=0, operation=operation, payload=payload)
+ before = db.get_session('s')
+ db._execute_write(lambda c: c.execute("CREATE TRIGGER refuse_receipt BEFORE INSERT ON state_meta WHEN NEW.key LIKE 'gateway.session_mutation.%' BEGIN SELECT RAISE(ABORT, 'receipt refused'); END"))
+ with pytest.raises(sqlite3.IntegrityError, match='receipt refused'):
+ mutate(db, **args)
+ assert db.get_session('s') == before
+ db._execute_write(lambda c: c.execute('DROP TRIGGER refuse_receipt'))
+ if operation == 'rename':
+ db.create_session('bot', source='test')
+ db.set_session_title('bot', db.CANONICAL_BOT_CHAT_TITLE)
+ db.set_session_hidden('bot', True)
+ with pytest.raises(ValueError, match='canonical Bot Chat'):
+ mutate(db, **{**args, 'session_id': 'bot'})
+ db.create_session('collision', source='test')
+ db.set_session_title('collision', 'New name')
+ with pytest.raises(ValueError, match='already in use'):
+ mutate(db, **args)
+ db.set_session_title('collision', '')
+ mutate(db, **args)
+ assert db.get_session_title('s') == 'New name'
+ assert db.get_session_title_source('s') == db.TITLE_SOURCE_USER
+ else:
+ db.create_session('child', source='test', parent_session_id='s')
+ db.end_session('s', end_reason='compression')
+ mutate(db, **args)
+ assert db.get_session('s')['archived'] == db.get_session('child')['archived'] == 1
+ assert db.get_session('child')['runtime_revision'] == 1
+ finally:
+ db.close()