catalog.py 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """ACP historical catalog without storage initialization or an execution owner."""
  2. import json
  3. from pathlib import Path
  4. from hermes_state import SessionDB
  5. from acp_adapter.session import (
  6. _normalize_cwd_for_compare, _parse_model_config, _session_info, _updated_at_sort_key,
  7. )
  8. def read_catalog_rows(path):
  9. path = Path(path)
  10. if not path.exists():
  11. return {}
  12. from hermes_cli.gateway_session_store import SurfaceLabelReader
  13. # The owner stores an editor thread as ``local`` with ``created_source='acp'``; the surface
  14. # reader matches both labels in SQL, before the LIMIT.
  15. with SessionDB(db_path=path, read_only=True) as db:
  16. rows = SurfaceLabelReader(db).list_sessions_rich(source="acp", limit=1000)
  17. return {str(row["id"]): dict(row) for row in rows}
  18. def _local_owners(db):
  19. """Physical id -> retained logical owner, from each private local creation receipt's lineage.
  20. A canonical reset or compression advances the receipt's physical target but keeps policy/FIFO
  21. on the creation id. Legacy reset histories have no receipt and stay independent chats."""
  22. from hermes_state_local import POLICY_PREFIX
  23. owners = {}
  24. with db._read_ctx() as conn:
  25. rows = conn.execute('SELECT value FROM state_meta WHERE key GLOB ?', (POLICY_PREFIX + '*',)).fetchall()
  26. for (raw,) in rows:
  27. try:
  28. receipt = json.loads(raw)
  29. except (TypeError, ValueError):
  30. continue
  31. owner = receipt.get('session_id') if isinstance(receipt, dict) else None
  32. lineage = receipt.get('lineage') if isinstance(owner, str) else None
  33. for physical in lineage if isinstance(lineage, list) else ():
  34. if isinstance(physical, str):
  35. owners[physical] = owner
  36. return owners
  37. def read_local_owners(path):
  38. path = Path(path)
  39. if not path.exists():
  40. return {}
  41. with SessionDB(db_path=path, read_only=True) as db:
  42. return _local_owners(db)
  43. def logical_session_id(path, session_id):
  44. """The authority's logical id for an id an editor already holds: compression and a canonical
  45. reset advance the physical transcript, never the session identity (the local receipt's owner,
  46. else ``SessionAuthority.logical_owner``'s compression root)."""
  47. path = Path(path)
  48. if not path.exists():
  49. return session_id
  50. with SessionDB(db_path=path, read_only=True) as db:
  51. lineage = db.get_compression_lineage(session_id)
  52. root = lineage[0] if lineage else session_id
  53. return _local_owners(db).get(root, root)
  54. def catalog_sessions(path, cwd=None):
  55. normalized = _normalize_cwd_for_compare(cwd) if cwd else None
  56. owners = read_local_owners(path)
  57. results = {}
  58. for sid, row in read_catalog_rows(path).items():
  59. # The listing projects a compressed chat's tip; the editor must hold the logical id.
  60. sid = row.get("_lineage_root_id") or sid
  61. sid = owners.get(sid, sid)
  62. count = int(row.get("message_count") or 0)
  63. session_cwd = row.get('cwd') or _parse_model_config(row.get("model_config")).get("cwd", ".")
  64. if count <= 0 or (normalized and _normalize_cwd_for_compare(session_cwd) != normalized):
  65. continue
  66. info = _session_info(sid, session_cwd, row.get("model") or "", count, row.get("title"),
  67. row.get("preview"), row.get("last_active") or row.get("started_at"))
  68. # One row per logical conversation: its most recently active segment represents it.
  69. held = results.get(sid)
  70. if held is None or _updated_at_sort_key(info.get("updated_at")) > _updated_at_sort_key(held.get("updated_at")):
  71. results[sid] = info
  72. return sorted(results.values(), key=lambda row: _updated_at_sort_key(row.get("updated_at")), reverse=True)