The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): offer and reopen a canonically reset ACP session by its retained owner
Tekniumc27aad5c873d
diff --git a/acp_adapter/catalog.py b/acp_adapter/catalog.pyindex c61445b43e0..e2237a9f06d 100644--- a/acp_adapter/catalog.py+++ b/acp_adapter/catalog.py@@ -1,4 +1,5 @@"""ACP historical catalog without storage initialization or an execution owner."""+import jsonfrom pathlib import Pathfrom hermes_state import SessionDB@@ -15,27 +16,64 @@ def read_catalog_rows(path):return {str(row["id"]): dict(row) for row in db.list_sessions_rich(source="acp", limit=1000)}+def _local_owners(db):+ """Physical id -> retained logical owner, from each private local creation receipt's lineage.+ A canonical reset or compression advances the receipt's physical target but keeps policy/FIFO+ on the creation id. Legacy reset histories have no receipt and stay independent chats."""+ from hermes_state_local import POLICY_PREFIX+ owners = {}+ with db._read_ctx() as conn:+ rows = conn.execute('SELECT value FROM state_meta WHERE key GLOB ?', (POLICY_PREFIX + '*',)).fetchall()+ for (raw,) in rows:+ try:+ receipt = json.loads(raw)+ except (TypeError, ValueError):+ continue+ owner = receipt.get('session_id') if isinstance(receipt, dict) else None+ lineage = receipt.get('lineage') if isinstance(owner, str) else None+ for physical in lineage if isinstance(lineage, list) else ():+ if isinstance(physical, str):+ owners[physical] = owner+ return owners+++def read_local_owners(path):+ path = Path(path)+ if not path.exists():+ return {}+ with SessionDB(db_path=path, read_only=True) as db:+ return _local_owners(db)++def logical_session_id(path, session_id):- """The authority's logical id for an id an editor already holds: compression advances the- physical transcript, never the session identity (``SessionAuthority.logical_owner``)."""+ """The authority's logical id for an id an editor already holds: compression and a canonical+ reset advance the physical transcript, never the session identity (the local receipt's owner,+ else ``SessionAuthority.logical_owner``'s compression root)."""path = Path(path)if not path.exists():return session_idwith SessionDB(db_path=path, read_only=True) as db:lineage = db.get_compression_lineage(session_id)- return lineage[0] if lineage else session_id+ root = lineage[0] if lineage else session_id+ return _local_owners(db).get(root, root)def catalog_sessions(path, cwd=None):normalized = _normalize_cwd_for_compare(cwd) if cwd else None- results = []+ owners = read_local_owners(path)+ results = {}for sid, row in read_catalog_rows(path).items():# The listing projects a compressed chat's tip; the editor must hold the logical id.sid = row.get("_lineage_root_id") or sid+ sid = owners.get(sid, sid)count = int(row.get("message_count") or 0)session_cwd = row.get('cwd') or _parse_model_config(row.get("model_config")).get("cwd", ".")if count <= 0 or (normalized and _normalize_cwd_for_compare(session_cwd) != normalized):continue- results.append(_session_info(sid, session_cwd, row.get("model") or "", count, row.get("title"),- row.get("preview"), row.get("last_active") or row.get("started_at")))- return sorted(results, key=lambda row: _updated_at_sort_key(row.get("updated_at")), reverse=True)+ info = _session_info(sid, session_cwd, row.get("model") or "", count, row.get("title"),+ row.get("preview"), row.get("last_active") or row.get("started_at"))+ # One row per logical conversation: its most recently active segment represents it.+ held = results.get(sid)+ if held is None or _updated_at_sort_key(info.get("updated_at")) > _updated_at_sort_key(held.get("updated_at")):+ results[sid] = info+ return sorted(results.values(), key=lambda row: _updated_at_sort_key(row.get("updated_at")), reverse=True)diff --git a/tests/acp_adapter/test_gateway_catalog_reset_owner.py b/tests/acp_adapter/test_gateway_catalog_reset_owner.pynew file mode 100644index 00000000000..46c03e5214b--- /dev/null+++ b/tests/acp_adapter/test_gateway_catalog_reset_owner.py@@ -0,0 +1,50 @@+"""An explicit canonical reset on an ACP session is offered and reopened by its retained owner."""+from contextlib import closing+from dataclasses import asdict++from acp_adapter.catalog import catalog_sessions, logical_session_id+from hermes_state import SessionDB+import hermes_state_runtime as rt+++def _acp_local_session(db, epoch, cwd):+ from hermes_state_local import commit_local_session+ from gateway.config import Platform+ from gateway.session import SessionEntry, SessionSource+ from gateway.session_lifecycle import _now+ from gateway.session_local_recovery import local_identity+ from gateway.session_policy import build_policy+ sid = local_identity('profile', 'human', 'editor')+ source = SessionSource(platform=Platform.LOCAL, chat_id=sid, user_id='human', chat_type='dm')+ entry = SessionEntry('local:' + sid, sid, _now(), _now(), origin=source, platform=Platform.LOCAL)+ policy = build_policy({'source': 'acp', 'cwd': str(cwd), 'model': 'm', 'toolsets': []},+ {'platform_toolsets': {'acp': []}}, private_secrets={})+ commit_local_session(db, epoch=epoch, receipt={+ 'profile_id': 'profile', 'principal_id': 'human', 'request_id': 'editor', 'session_id': sid,+ 'route': entry.session_key, 'entry': entry.to_dict(), 'policy': asdict(policy)})+ return sid+++def test_reset_child_maps_to_its_owner_while_legacy_reset_histories_stay_independent(tmp_path):+ path = tmp_path / 'state.db'+ with closing(SessionDB(path)) as db:+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ sid = _acp_local_session(db, epoch, tmp_path)+ db.append_message(sid, 'user', 'before reset')+ row = db.get_session(sid)+ child = rt.mutate_runtime_session(db, epoch=epoch, principal_id='human', session_id=sid,+ request_id='reset', operation='reset', expected_revision=row['runtime_revision'],+ expected_generation=row['runtime_generation'], payload={})['target_session_id']+ db.append_message(child, 'user', 'after reset')+ # A true legacy reset history (no local receipt) keeps two independent conversations.+ db.create_session('legacy-old', source='acp', cwd=str(tmp_path))+ db.append_message('legacy-old', 'user', 'legacy old')+ db.end_session('legacy-old', 'session_reset')+ db.create_session('legacy-new', source='acp', cwd=str(tmp_path), parent_session_id='legacy-old',+ model_config={'_reset_from': 'legacy-old'})+ db.append_message('legacy-new', 'user', 'legacy new')+ offered = [row['session_id'] for row in catalog_sessions(path, str(tmp_path))]+ assert sorted(offered) == sorted([sid, 'legacy-old', 'legacy-new']), offered+ assert logical_session_id(path, child) == sid+ assert logical_session_id(path, sid) == sid+ assert logical_session_id(path, 'legacy-new') == 'legacy-new'