Skip to content

The agent that grows with you

feat: commit sidebar edits with canonical mutation receipts

Teknium0b1b8e0f1d84
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
new file mode 100644
index 00000000000..6fd76b7f74a
--- /dev/null
+++ b/hermes_state_mutations.py
@@ -0,0 +1,33 @@
+"""Closed action handlers inside the runtime mutation receipt transaction."""
+import time
+from hermes_state_runtime import RuntimeStoreError
+
+METADATA_FIELDS = {'title': str, 'archived': bool, 'hidden': bool, 'pinned': bool, 'unread': bool}
+
+
+def validate_action(operation, payload):
+ if not isinstance(payload, dict) or not isinstance(operation, str):
+ raise RuntimeStoreError('invalid_params')
+ required = {'rename': {'title'}, 'archive': {'archived'}}
+ if operation == 'sidebar':
+ valid = bool(payload) and not set(payload) - METADATA_FIELDS.keys()
+ else:
+ valid = operation in required and set(payload) == required[operation]
+ if not valid or any(type(value) is not METADATA_FIELDS[key] for key, value in payload.items()):
+ raise RuntimeStoreError('invalid_params')
+
+
+def apply_action(db, conn, session_id, operation, payload):
+ affected = set()
+ result = {}
+ for key, value in payload.items():
+ if key == 'title':
+ affected.update(db._set_session_title_in_transaction(
+ conn, session_id, value, source=db.TITLE_SOURCE_USER))
+ result[key] = conn.execute('SELECT title FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
+ else:
+ column = 'last_read_at' if key == 'unread' else key
+ stored = (0.0 if value else time.time()) if key == 'unread' else int(value)
+ affected.update(db._set_lineage_column_in_transaction(conn, column, session_id, stored))
+ result[key] = value
+ return affected, result
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index b14d225b4a7..d2720ffd861 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -184,12 +184,8 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str
_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')
+ from hermes_state_mutations import validate_action, apply_action
+ validate_action(operation, payload)
# Snapshot caller data before waiting for the writer lock.
payload = json.loads(_json(payload))
key = 'gateway.mutation.v1.' + admission_fingerprint(
@@ -208,19 +204,12 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str
session = _session(conn, session_id)
if session['runtime_revision'] != expected_revision:
raise RuntimeStoreError('revision_conflict')
- if operation == 'rename':
- affected = db._set_session_title_in_transaction(
- conn, session_id, payload['title'], source=db.TITLE_SOURCE_USER)
- else:
- affected = db._set_lineage_column_in_transaction(
- conn, 'archived', session_id, int(payload['archived']))
+ affected, projection = apply_action(db, conn, session_id, operation, payload)
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])
+ 'operation': operation, **projection}
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
(key, _json({'digest': digest, 'result': result})))
return result
diff --git a/tests/state/test_runtime_mutation_actions.py b/tests/state/test_runtime_mutation_actions.py
new file mode 100644
index 00000000000..ed2fc36d3c3
--- /dev/null
+++ b/tests/state/test_runtime_mutation_actions.py
@@ -0,0 +1,28 @@
+"""Action-specific mutations share the canonical receipt transaction."""
+import sqlite3
+import pytest
+from hermes_state import SessionDB
+import hermes_state_runtime as rt
+
+
+def test_sidebar_edit_is_atomic_and_revision_fenced(tmp_path):
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('s', source='test')
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ args = dict(epoch=epoch, principal_id='human', session_id='s', request_id='edit',
+ expected_revision=0, operation='sidebar',
+ payload={'title': 'Title', 'pinned': True, 'hidden': True, 'unread': True})
+ db._execute_write(lambda c: c.execute("CREATE TRIGGER fail_receipt BEFORE INSERT ON state_meta WHEN NEW.key LIKE 'gateway.mutation.%' BEGIN SELECT RAISE(ABORT, 'receipt failed'); END"))
+ with pytest.raises(sqlite3.IntegrityError, match='receipt failed'):
+ rt.mutate_runtime_session(db, **args)
+ assert db.get_session('s')['title'] is None
+ assert not db.get_session('s')['pinned']
+ db._execute_write(lambda c: c.execute('DROP TRIGGER fail_receipt'))
+ receipt = rt.mutate_runtime_session(db, **args)
+ assert receipt['revision'] == 1
+ assert receipt['pinned'] and receipt['hidden'] and receipt['unread']
+ with SessionDB(db_path=tmp_path / 'state.db') as peer:
+ with pytest.raises(rt.RuntimeStoreError, match='revision_conflict'):
+ rt.mutate_runtime_session(peer, **(args | {'principal_id': 'peer'}))
+ assert rt.mutate_runtime_session(peer, **args) == receipt
+ assert db.get_session('s')['runtime_revision'] == 1