sessions_cmd_repair_profiles.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """``hermes sessions repair-profiles`` — the CLI face of :mod:`hermes_cli.sessions_repair_profiles`.
  2. Runs pre-DB (``_PRE_DB_HANDLERS``): it opens every profile's store itself rather than the one
  3. ambient ``SessionDB()``. Report-only unless ``--apply``; ``--json`` for automation.
  4. """
  5. from __future__ import annotations
  6. import json
  7. import sys
  8. from typing import Dict, List
  9. from hermes_cli.sessions_repair_profiles import (
  10. Finding, default_snapshot, enumerate_stores, live_gateway_homes, scan_stores,
  11. )
  12. _KIND_LABELS = {
  13. "mislabelled": "profile_name disagrees with the row's own session key",
  14. "wrong_store": "rows in another profile's store",
  15. "legacy_main": "legacy agent:main rows inside a named profile's store",
  16. "unclaimed_namespace": "rows keyed to a profile that does not exist",
  17. "crossed_parent": "parent_session_id crossing profile namespaces",
  18. "routing_stray": "routing rows outside the default store",
  19. "routing_unclaimed": "routing rows for a profile that does not exist",
  20. "topic_profile_less": "Telegram topic bindings without their bot's profile",
  21. "voice_profile_less": "voice-mode entries without their bot's profile",
  22. "sessions_json_unclaimed": "sessions.json entries for a profile that does not exist",
  23. }
  24. def _group(findings: list[Finding]) -> dict[str, list[Finding]]:
  25. grouped: dict[str, list[Finding]] = {}
  26. for finding in findings:
  27. grouped.setdefault(finding.kind, []).append(finding)
  28. return grouped
  29. def _print_report(findings: list[Finding]) -> None:
  30. for kind, rows in _group(findings).items():
  31. print(f"\n{_KIND_LABELS.get(kind, kind)} ({len(rows)}):")
  32. for finding in rows:
  33. print(f" [{finding.store}] {finding.subject}\n {finding.detail}")
  34. if finding.action:
  35. print(f" → {finding.action}")
  36. else:
  37. print(f" ✗ not repaired — {finding.reason}")
  38. def cmd_repair_profiles(args) -> int:
  39. stores = enumerate_stores()
  40. apply = bool(getattr(args, "apply", False))
  41. as_json = bool(getattr(args, "json", False))
  42. legacy_main = getattr(args, "legacy_main", None) or "report"
  43. if apply:
  44. # Before any store is opened for write: a writable open runs schema init, and a live
  45. # gateway holds the routing index in memory and would write it back over the repair.
  46. live = live_gateway_homes(stores)
  47. if live:
  48. names = ", ".join(f"{profile} (pid {pid})" for profile, pid in live)
  49. print(f"A gateway is running for: {names}. It holds the routing index in memory and would "
  50. "write it back over this repair. Stop it (`hermes gateway stop`), then re-run --apply.",
  51. file=sys.stderr)
  52. return 1
  53. plan, session = scan_stores(stores, legacy_main=legacy_main, read_only=not apply)
  54. try:
  55. findings = plan.findings
  56. repairable = plan.repairable
  57. if as_json and not apply:
  58. print(json.dumps({"stores": [s.profile for s in stores], "findings": [f.as_dict() for f in findings],
  59. "repairable": len(repairable)}, indent=2))
  60. return 0
  61. if not as_json:
  62. print(f"Scanned {len(stores)} profile store(s): {', '.join(s.profile for s in stores)}")
  63. if not findings:
  64. print("✓ No crossed-profile state found.")
  65. return 0
  66. _print_report(findings)
  67. if not apply:
  68. print(f"\n{len(repairable)} of {len(findings)} finding(s) can be repaired. "
  69. "Re-run with --apply to perform them.")
  70. return 0
  71. if not repairable:
  72. if as_json:
  73. print(json.dumps({"findings": [f.as_dict() for f in findings], "applied": {}}, indent=2))
  74. else:
  75. print("\nNothing to repair.")
  76. return 0
  77. if not getattr(args, "yes", False) and not as_json:
  78. from hermes_cli.sessions_cmd import _confirm_or_exit_code
  79. refused = _confirm_or_exit_code(
  80. f"\nApply {len(repairable)} repair(s)? A snapshot of every store is taken first. [y/N] ",
  81. declined="Aborted — nothing was changed.")
  82. if refused is not None:
  83. return refused
  84. result = plan.apply(session, snapshot=default_snapshot)
  85. finally:
  86. session.close()
  87. if as_json:
  88. print(json.dumps({"findings": [f.as_dict() for f in findings], "applied": result}, indent=2))
  89. else:
  90. for profile, snap in result["snapshots"].items():
  91. print(f" snapshot [{profile}]: {snap or 'FAILED'}")
  92. applied = ", ".join(f"{k}={v}" for k, v in sorted(result["totals"].items()) if v)
  93. print(f"\nApplied: {applied or 'nothing'}")
  94. for failure in result["failures"]:
  95. print(f" ✗ {failure['kind']} {failure['subject']}: {failure['error']}")
  96. print("Re-run without --apply to confirm the stores are clean.")
  97. return 1 if result["failures"] else 0