sessions_repair_profiles.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. """``hermes sessions repair-profiles`` — settle crossed-profile durable state across every store.
  2. The per-profile store model (#88734) and the identity fences that followed are forward-only: they
  3. put NEW rows in the right place and refuse to widen existing damage, but nothing walks the stores
  4. and settles what an earlier release left crossed. This does, for six kinds of crossing:
  5. 1. ``sessions.profile_name`` disagreeing with the profile in the row's own ``session_key``;
  6. 2. rows physically in the wrong store (a named profile's keys in the root ``state.db``, another
  7. profile's keys in ``profiles/<p>/state.db``) — moved to the owning profile's store;
  8. 3. ``parent_session_id`` crossing namespaces — severed (the child's own identity is untouched);
  9. 4. ``gateway_routing`` rows in a named profile's store (the routing index lives in the gateway's
  10. home; #66887 copied every profile's rows into whichever store was scoped) — moved to the routing
  11. store when absent there, dropped otherwise — and root rows for a namespace no profile claims;
  12. 5. profile-less Telegram topic bindings and ``gateway_voice_mode.json`` entries owned by a
  13. non-default bot — relabelled from the evidence of the rows themselves;
  14. 6. ``sessions.json`` mirror entries whose key namespace no served profile claims — dropped, since
  15. the legacy import re-injects any key the routing DB lacks on every boot.
  16. Legacy ``agent:main:`` rows inside a named profile's store are reported but NOT repaired unless
  17. ``--legacy-main`` says how: they are either a standalone (pre-multiplex) gateway's own history that
  18. must be rekeyed to ``agent:<p>:`` (the #113884 incident), or a default-profile chat that leaked in
  19. under a scoped write (#102157) and must move to the root store. The row carries no evidence that
  20. tells the two apart, and guessing wrong hands a conversation to the other bot.
  21. Report-only by default. ``--apply`` refuses while a gateway owning any touched store is live (it
  22. holds the routing index in memory and writes it back), takes a quick snapshot of every store it
  23. will mutate, and is idempotent: a second run finds nothing.
  24. """
  25. from __future__ import annotations
  26. import contextlib
  27. import json
  28. import logging
  29. from dataclasses import dataclass, field
  30. from pathlib import Path
  31. from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple
  32. logger = logging.getLogger(__name__)
  33. _LEGACY_MAIN_CHOICES = ("report", "rekey", "move")
  34. _VOICE_MODE_FILE = "gateway_voice_mode.json"
  35. @dataclass(frozen=True)
  36. class Store:
  37. """One profile's ``state.db``; ``routing`` marks the store that owns the multiplexer's index."""
  38. profile: str
  39. home: Path
  40. routing: bool = False
  41. @property
  42. def db_path(self) -> Path:
  43. return self.home / "state.db"
  44. @dataclass
  45. class Finding:
  46. kind: str
  47. store: str
  48. subject: str
  49. detail: str
  50. action: Optional[str] = None # what --apply does; None = report only
  51. reason: Optional[str] = None # why it is report only
  52. _fix: Optional[Callable[[_Session], dict[str, int]]] = field(default=None, repr=False, compare=False)
  53. @property
  54. def repairable(self) -> bool:
  55. return self._fix is not None
  56. def as_dict(self) -> dict[str, Any]:
  57. return {"kind": self.kind, "store": self.store, "subject": self.subject, "detail": self.detail,
  58. "action": self.action, "reason": self.reason}
  59. class _Session:
  60. """Open store handles for one run; every store opened at most once, all released at the end."""
  61. def __init__(self, *, read_only: bool) -> None:
  62. self.read_only = read_only
  63. self._dbs: dict[Path, Any] = {}
  64. def db(self, store: Store):
  65. """The store's SessionDB. Read-only runs never create a file: a live profile that has no
  66. ``state.db`` yet reads as empty; an apply run opens it for real when a move lands there."""
  67. path = store.db_path
  68. if path not in self._dbs:
  69. if self.read_only:
  70. from hermes_state import SessionDB
  71. self._dbs[path] = SessionDB(path, read_only=True) if path.exists() else _EMPTY_STORE
  72. else:
  73. from hermes_state_registry import acquire
  74. self._dbs[path] = acquire(path)
  75. return self._dbs[path]
  76. def close(self) -> None:
  77. from hermes_state_registry import release_or_close
  78. for db in self._dbs.values():
  79. if db is _EMPTY_STORE:
  80. continue
  81. with contextlib.suppress(Exception):
  82. release_or_close(db) if not self.read_only else db.close()
  83. self._dbs.clear()
  84. class _EmptyStore:
  85. """Stand-in for a live profile whose ``state.db`` does not exist yet: nothing to find."""
  86. def find_crossed_profile_sessions(self, owner):
  87. return {"mislabelled": [], "foreign": [], "crossed_parents": []}
  88. def find_profile_less_telegram_topic_rows(self):
  89. return []
  90. def list_gateway_routing_rows(self):
  91. return []
  92. def key_profiles_for_chat(self, platform, chat_id):
  93. return set()
  94. _EMPTY_STORE = _EmptyStore()
  95. # ── enumeration ───────────────────────────────────────────────────────────────
  96. def enumerate_stores() -> list[Store]:
  97. """Default root plus every live named profile (a live profile claims its namespace whether or not
  98. it has written a ``state.db`` yet). The root store owns the routing index: the multiplexer's
  99. ``_routing_home`` is its launch home, the root."""
  100. from hermes_cli.profiles import _get_default_hermes_home, _iter_named_profile_dirs
  101. root = _get_default_hermes_home()
  102. stores = [Store("default", root, routing=True)]
  103. stores.extend(Store(entry.name, entry) for entry in _iter_named_profile_dirs())
  104. return stores
  105. def _gateway_multiplexes(root: Path) -> bool:
  106. """Does the default gateway serve every profile? Same reader as every other CLI surface: the live
  107. record, else the explicit flag, else False — an unset flag is a verdict only the gateway reaches,
  108. and guessing "yes" would uproot a standalone gateway's own routing index."""
  109. from hermes_cli.gateway_multiplex_mode import default_gateway_multiplexes
  110. try:
  111. return default_gateway_multiplexes(root)
  112. except Exception:
  113. return False
  114. def live_gateway_homes(stores: Iterable[Store]) -> list[tuple[str, int]]:
  115. from gateway.status import live_gateway_pid_for_home
  116. live = []
  117. for store in stores:
  118. pid = live_gateway_pid_for_home(store.home)
  119. if pid is not None:
  120. live.append((store.profile, pid))
  121. return live
  122. # ── scan ──────────────────────────────────────────────────────────────────────
  123. class RepairPlan:
  124. def __init__(self, stores: list[Store], *, legacy_main: str = "report") -> None:
  125. if legacy_main not in _LEGACY_MAIN_CHOICES:
  126. raise ValueError(f"legacy_main must be one of {_LEGACY_MAIN_CHOICES}")
  127. self.stores = stores
  128. self.by_profile = {s.profile: s for s in stores}
  129. self.claimed: set[str] = set(self.by_profile)
  130. self.routing_store = next((s for s in stores if s.routing), None)
  131. self.legacy_main = legacy_main
  132. self.multiplexes = _gateway_multiplexes(self.routing_store.home) if self.routing_store else False
  133. self.findings: list[Finding] = []
  134. self._moves: dict[tuple[Path, Path], _MoveBatch] = {}
  135. # -- helpers --
  136. def _add(self, finding: Finding) -> None:
  137. self.findings.append(finding)
  138. @property
  139. def repairable(self) -> list[Finding]:
  140. return [f for f in self.findings if f.repairable]
  141. # -- scan --
  142. def scan(self, session: _Session) -> RepairPlan:
  143. for store in self.stores:
  144. self._scan_sessions(session, store)
  145. self._scan_topics(session, store)
  146. for store in self.stores:
  147. self._scan_routing(session, store)
  148. if self.routing_store is not None:
  149. self._scan_voice_modes(session, self.routing_store)
  150. self._scan_sessions_json(self.routing_store)
  151. return self
  152. def _scan_sessions(self, session: _Session, store: Store) -> None:
  153. db = session.db(store)
  154. crossed = db.find_crossed_profile_sessions(store.profile)
  155. moving: set[str] = set()
  156. held = _ledgered_lineages([r for r in crossed["foreign"] if self._would_move(store, r)])
  157. for row in crossed["foreign"]:
  158. if row["id"] in held:
  159. moving.add(row["id"]) # neither relabelled nor severed in place: it is a stray
  160. self._add(Finding(
  161. "wrong_store", store.profile, row["id"],
  162. f"key {row['session_key']!r} ({row['message_count']} messages) sits in the "
  163. f"{store.profile} store", reason=held[row["id"]]))
  164. continue
  165. self._plan_foreign_row(store, row, moving)
  166. for row in crossed["mislabelled"]:
  167. if row["id"] in moving:
  168. continue # the move stamps the right label
  169. self._add(Finding(
  170. "mislabelled", store.profile, row["id"],
  171. f"profile_name={row['profile_name']!r} but key {row['session_key']!r} belongs to "
  172. f"{row['key_profile']!r}", action=f"relabel to {row['key_profile']!r}",
  173. _fix=lambda s, st=store, sid=row["id"]: {
  174. "relabelled": s.db(st).relabel_sessions_to_key_profile([sid])}))
  175. for row in crossed["crossed_parents"]:
  176. if row["id"] in moving:
  177. continue # the import drops a parent that is not in the target store
  178. self._add(Finding(
  179. "crossed_parent", store.profile, row["id"],
  180. f"{row['key_profile']!r} row inherits from parent {row['parent_session_id']} keyed under "
  181. f"{row['parent_profile']!r}", action="sever parent_session_id",
  182. _fix=lambda s, st=store, sid=row["id"]: {"severed": s.db(st).sever_crossed_parents([sid])}))
  183. def _would_move(self, store: Store, row: dict[str, Any]) -> bool:
  184. """Mirror of :meth:`_plan_foreign_row`: does the plan copy this row to another store?"""
  185. if row["key_profile"] == "default" and store.profile != "default":
  186. return self.legacy_main == "move" and self.routing_store is not None
  187. return row["key_profile"] in self.claimed
  188. def _plan_foreign_row(self, store: Store, row: dict[str, Any], moving: set[str]) -> None:
  189. key_profile, sid = row["key_profile"], row["id"]
  190. detail = f"key {row['session_key']!r} ({row['message_count']} messages) sits in the {store.profile} store"
  191. if key_profile == "default" and store.profile != "default":
  192. self._plan_legacy_main_row(store, row, moving)
  193. return
  194. if key_profile not in self.claimed:
  195. self._add(Finding(
  196. "unclaimed_namespace", store.profile, sid, detail,
  197. reason=f"no live profile named {key_profile!r}; create it, then rerun, or "
  198. f"`hermes profile migrate-identity {key_profile} <target>`"))
  199. return
  200. moving.add(sid)
  201. self._add(Finding(
  202. "wrong_store", store.profile, sid, detail, action=f"move to the {key_profile} store",
  203. _fix=self._move_batch(store, self.by_profile[key_profile]).fix_for(sid)))
  204. def _plan_legacy_main_row(self, store: Store, row: dict[str, Any], moving: set[str]) -> None:
  205. sid = row["id"]
  206. detail = (f"legacy default-namespace key {row['session_key']!r} ({row['message_count']} messages) "
  207. f"in the {store.profile} store")
  208. if self.legacy_main == "rekey":
  209. self._add(Finding(
  210. "legacy_main", store.profile, sid, detail, action=f"rekey to agent:{store.profile}:",
  211. _fix=lambda s, st=store, i=sid: {"rekeyed": s.db(st).rekey_legacy_main_sessions([i], st.profile)}))
  212. elif self.legacy_main == "move" and self.routing_store is not None:
  213. moving.add(sid)
  214. self._add(Finding(
  215. "legacy_main", store.profile, sid, detail, action="move to the default store",
  216. _fix=self._move_batch(store, self.routing_store).fix_for(sid)))
  217. else:
  218. self._add(Finding(
  219. "legacy_main", store.profile, sid, detail,
  220. reason="either a standalone gateway's own history (--legacy-main rekey) or a default "
  221. "chat that leaked in (--legacy-main move); the row cannot say which"))
  222. def _move_batch(self, src: Store, dst: Store) -> _MoveBatch:
  223. return self._moves.setdefault((src.db_path, dst.db_path), _MoveBatch(src, dst))
  224. def _scan_topics(self, session: _Session, store: Store) -> None:
  225. rows = session.db(store).find_profile_less_telegram_topic_rows()
  226. for row in rows:
  227. self._add(Finding(
  228. "topic_profile_less", store.profile, f"chat {row['chat_id']} thread {row['thread_id']}",
  229. f"telegram topic binding labelled 'default' but keyed {row['session_key']!r}",
  230. action=f"relabel to {row['key_profile']!r}",
  231. _fix=lambda s, st=store, r=row: s.db(st).relabel_telegram_topic_rows([r])))
  232. def _scan_routing(self, session: _Session, store: Store) -> None:
  233. from hermes_state_profile_repair import session_key_profile
  234. rows = session.db(store).list_gateway_routing_rows()
  235. for row in rows:
  236. key_profile = session_key_profile(row["session_key"])
  237. if key_profile is None:
  238. continue
  239. subject = f"{row['session_key']} (scope {row['scope']!r})"
  240. if store.routing:
  241. if key_profile not in self.claimed:
  242. self._add(Finding(
  243. "routing_unclaimed", store.profile, subject,
  244. f"routing row for a namespace no live profile claims ({key_profile!r}); every "
  245. "inbound event on it logs a missing-profile error", action="delete",
  246. _fix=lambda s, st=store, r=row: {
  247. "routing_deleted": s.db(st).delete_gateway_routing_rows([(r["scope"], r["session_key"])])}))
  248. continue
  249. if key_profile == store.profile and not self.multiplexes:
  250. continue # a standalone gateway's own index lives in its own store
  251. routing_store = self.routing_store
  252. if routing_store is None:
  253. continue
  254. self._add(Finding(
  255. "routing_stray", store.profile, subject,
  256. f"routing row in the {store.profile} store; the index lives in the default store",
  257. action="move to the default store (existing row there wins)",
  258. _fix=lambda s, st=store, r=row, rs=routing_store: self._move_routing_row(s, st, rs, r)))
  259. def _move_routing_row(self, session: _Session, store: Store, routing_store: Store,
  260. row: dict[str, Any]) -> dict[str, int]:
  261. adopted = session.db(routing_store).insert_gateway_routing_rows_if_absent(
  262. [(row["scope"], row["session_key"], row["entry_json"], row["updated_at"])])
  263. deleted = session.db(store).delete_gateway_routing_rows([(row["scope"], row["session_key"])])
  264. return {"routing_adopted": adopted, "routing_deleted": deleted}
  265. def _scan_voice_modes(self, session: _Session, store: Store) -> None:
  266. path = store.home / _VOICE_MODE_FILE
  267. try:
  268. data = json.loads(path.read_text(encoding="utf-8-sig"))
  269. except (FileNotFoundError, json.JSONDecodeError, OSError):
  270. return
  271. if not isinstance(data, dict):
  272. return
  273. for key in sorted(k for k in data if isinstance(k, str) and k.count(":") == 1):
  274. platform, chat_id = key.split(":", 1)
  275. owners: set[str] = set()
  276. for st in self.stores:
  277. owners |= session.db(st).key_profiles_for_chat(platform, chat_id)
  278. if not owners or "default" in owners:
  279. continue # the default bot speaks there: the unprefixed key is its own
  280. if len(owners) > 1:
  281. self._add(Finding(
  282. "voice_profile_less", store.profile, key,
  283. f"voice mode entry without a profile; chat is held by {sorted(owners)}",
  284. reason="more than one non-default bot speaks in this chat"))
  285. continue
  286. owner = next(iter(owners))
  287. self._add(Finding(
  288. "voice_profile_less", store.profile, key,
  289. f"voice mode {data[key]!r} without a profile; chat is held only by {owner!r}",
  290. action=f"rekey to {owner}:{key}",
  291. _fix=lambda s, p=path, k=key, o=owner: _rekey_voice_mode_entry(p, k, o)))
  292. def _scan_sessions_json(self, store: Store) -> None:
  293. from hermes_state_profile_repair import session_key_profile
  294. path = store.home / "sessions" / "sessions.json"
  295. try:
  296. data = json.loads(path.read_text(encoding="utf-8-sig"))
  297. except (FileNotFoundError, json.JSONDecodeError, OSError):
  298. return
  299. if not isinstance(data, dict):
  300. return
  301. for key in sorted(k for k in data if isinstance(k, str) and not k.startswith("_")):
  302. key_profile = session_key_profile(key)
  303. if key_profile is None or key_profile in self.claimed:
  304. continue
  305. self._add(Finding(
  306. "sessions_json_unclaimed", store.profile, key,
  307. f"sessions.json mirror entry for a namespace no live profile claims ({key_profile!r}); "
  308. "the legacy import re-injects it into routing on every boot", action="delete entry",
  309. _fix=lambda s, p=path, k=key: _drop_sessions_json_entry(p, k)))
  310. # -- apply --
  311. def apply(self, session: _Session, *, snapshot: Callable[[Store], Optional[str]]) -> dict[str, Any]:
  312. """Run every repairable fix; snapshots every store first. Fixes are independent and each
  313. re-checks its precondition, so a partial run leaves a state the next run completes."""
  314. snapshots = {s.profile: snapshot(s) for s in self.stores if s.db_path.exists()}
  315. totals: dict[str, int] = {}
  316. failures: list[dict[str, str]] = []
  317. for finding in self.repairable:
  318. fix = finding._fix
  319. assert fix is not None
  320. try:
  321. for key, count in (fix(session) or {}).items():
  322. totals[key] = totals.get(key, 0) + int(count)
  323. except Exception as exc: # one bad row must not abandon the rest of the plan
  324. logger.warning("repair-profiles: %s on %s failed", finding.kind, finding.subject, exc_info=True)
  325. failures.append({"kind": finding.kind, "subject": finding.subject,
  326. "error": f"{type(exc).__name__}: {exc}"})
  327. return {"snapshots": snapshots, "totals": totals, "failures": failures}
  328. class _MoveBatch:
  329. """Every session moving from one store to another, moved together: export all, import all
  330. (parents before children, so a moved child keeps its moved parent), then delete from the source.
  331. Row by row, deleting a parent would detach the children still waiting in the source. Copy
  332. precedes delete, so a crash between the two leaves a duplicate the next run settles
  333. (``present`` on import, then the delete). A row that fails is that row's failure alone: the
  334. rest of the batch still moves, and only its lineage (descendants, and the parent it still
  335. points at in the source) waits with it for the next run."""
  336. def __init__(self, src: Store, dst: Store) -> None:
  337. self.src, self.dst = src, dst
  338. self.ids: list[str] = []
  339. self._result: Optional[dict[str, dict[str, int]]] = None
  340. self._errors: dict[str, Exception] = {}
  341. def fix_for(self, sid: str) -> Callable[[_Session], dict[str, int]]:
  342. self.ids.append(sid)
  343. return lambda session: self._outcome(session, sid)
  344. def _outcome(self, session: _Session, sid: str) -> dict[str, int]:
  345. result = self.run(session)
  346. if sid in self._errors:
  347. raise self._errors[sid]
  348. return result.get(sid, {"missing": 1})
  349. def run(self, session: _Session) -> dict[str, dict[str, int]]:
  350. if self._result is not None:
  351. return self._result
  352. src_db, dst_db = session.db(self.src), session.db(self.dst)
  353. from hermes_state_profile_repair import SessionLedgeredError
  354. payloads: dict[str, Optional[dict[str, Any]]] = {}
  355. for sid in self.ids:
  356. try:
  357. payloads[sid] = src_db.export_session_for_move(sid)
  358. except SessionLedgeredError as exc: # gained ledger rows since the scan: never copied
  359. self._errors[sid] = exc
  360. ordered = _parents_first([p for p in payloads.values() if p is not None])
  361. result: dict[str, dict[str, int]] = {sid: {"missing": 1} for sid, p in payloads.items()
  362. if p is None and sid not in self._errors}
  363. for payload in ordered:
  364. sid, parent = payload["session"]["id"], payload["session"].get("parent_session_id")
  365. if parent in self._errors:
  366. # Imported now, it would land without the parent and never regain the link.
  367. self._errors[sid] = RuntimeError(
  368. f"its parent {parent} did not move; kept in the {self.src.profile} store with it")
  369. continue
  370. try:
  371. outcome = dst_db.import_moved_session(payload, profile_name=self.dst.profile)
  372. except Exception as exc:
  373. self._errors[sid] = exc
  374. continue
  375. if dst_db.count_messages_all(sid) < len(payload["messages"]):
  376. logger.warning("repair-profiles: %s copied into %s with fewer messages than the source; "
  377. "source row kept", sid, self.dst.profile)
  378. result[sid] = {"copied_incomplete": 1}
  379. continue
  380. result[sid] = {outcome: 1}
  381. # Deleting a row detaches its children still in the source; a child that did not move
  382. # must find its parent there on the next run.
  383. awaited = {p["session"].get("parent_session_id") for p in ordered if p["session"]["id"] in self._errors}
  384. for payload in ordered:
  385. sid = payload["session"]["id"]
  386. if sid not in result or sid in awaited or "copied_incomplete" in result[sid]:
  387. continue
  388. try:
  389. if src_db.delete_moved_session(sid):
  390. result[sid]["moved"] = 1
  391. except Exception as exc:
  392. self._errors[sid] = exc
  393. self._result = result
  394. return result
  395. def _ledgered_lineages(foreign: list[dict[str, Any]]) -> dict[str, str]:
  396. """Stray rows that must stay put, each with the reason. A row the gateway ledger references
  397. (admissions/workers, ``ON DELETE RESTRICT``) cannot be deleted from its store, so copying it
  398. would leave the session in both; the stray rows linked to it by ``parent_session_id`` stay
  399. with it, since moving a parent detaches the child left behind and a moved child loses its
  400. parent. Whether a move should carry the ledger is a separate policy decision."""
  401. by_id = {row["id"]: row for row in foreign}
  402. groups: dict[str, set[str]] = {sid: {sid} for sid in by_id}
  403. for row in foreign:
  404. parent = row.get("parent_session_id")
  405. if parent in by_id and groups[parent] is not groups[row["id"]]:
  406. merged = groups[parent] | groups[row["id"]]
  407. for sid in merged:
  408. groups[sid] = merged
  409. held: dict[str, str] = {}
  410. for sid, row in by_id.items():
  411. anchors = sorted(m for m in groups[sid] if by_id[m].get("ledgered"))
  412. if row.get("ledgered"):
  413. held[sid] = "has gateway admission/worker history, which a move cannot carry"
  414. elif anchors:
  415. held[sid] = f"its lineage holds {anchors[0]}, which has gateway admission/worker history"
  416. return held
  417. def _parents_first(payloads: list[dict[str, Any]]) -> list[dict[str, Any]]:
  418. """Order moved sessions so every parent in the batch precedes its children (a cycle, impossible
  419. for a well-formed store, falls back to insertion order)."""
  420. pending = {p["session"]["id"]: p for p in payloads}
  421. ordered: list[dict[str, Any]] = []
  422. while pending:
  423. ready = [sid for sid, p in pending.items() if p["session"].get("parent_session_id") not in pending]
  424. if not ready:
  425. ready = list(pending)
  426. for sid in ready:
  427. ordered.append(pending.pop(sid))
  428. return ordered
  429. def _rekey_voice_mode_entry(path: Path, key: str, owner: str) -> dict[str, int]:
  430. from utils import atomic_json_write
  431. data = json.loads(path.read_text(encoding="utf-8-sig"))
  432. if key not in data:
  433. return {}
  434. data.setdefault(f"{owner}:{key}", data.pop(key))
  435. data.pop(key, None)
  436. atomic_json_write(path, data)
  437. return {"voice_rekeyed": 1}
  438. def _drop_sessions_json_entry(path: Path, key: str) -> dict[str, int]:
  439. from utils import atomic_json_write
  440. data = json.loads(path.read_text(encoding="utf-8-sig"))
  441. if key not in data:
  442. return {}
  443. del data[key]
  444. atomic_json_write(path, data, mode=0o600)
  445. return {"sessions_json_dropped": 1}
  446. # ── entry points ──────────────────────────────────────────────────────────────
  447. def scan_stores(stores: Optional[list[Store]] = None, *, legacy_main: str = "report",
  448. read_only: bool = True) -> tuple[RepairPlan, _Session]:
  449. """Open every store and build the plan. The caller owns the returned session (close it)."""
  450. stores = enumerate_stores() if stores is None else stores
  451. session = _Session(read_only=read_only)
  452. try:
  453. plan = RepairPlan(stores, legacy_main=legacy_main).scan(session)
  454. except Exception:
  455. session.close()
  456. raise
  457. return plan, session
  458. def default_snapshot(store: Store) -> Optional[str]:
  459. from hermes_cli.backup import create_quick_snapshot
  460. try:
  461. return create_quick_snapshot(label="repair-profiles", hermes_home=store.home)
  462. except Exception as exc:
  463. logger.warning("repair-profiles: snapshot of %s failed: %s", store.home, exc)
  464. return None