update_cmd_validation.py 4.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """Source import-integrity checks for update and stash restoration."""
  2. import json
  3. import subprocess
  4. from pathlib import Path
  5. from hermes_cli._launchers import runtime_command
  6. # Modules imported on every startup. Unlike _UPDATE_CRITICAL_FILES (only parsed) these are
  7. # *imported*, catching cross-module breakage (a name pulled from a sibling no longer exists).
  8. _UPDATE_CRITICAL_MODULES = "hermes_cli.main", "run_agent", "model_tools", "toolsets"
  9. def _critical_module_import_failures(
  10. root, *, report_runtime_errors: bool = False) -> dict[str, tuple[str, str]]:
  11. """Import each ``_UPDATE_CRITICAL_MODULES`` entry in a subprocess; return failures in probe order.
  12. Syntax validation only *parses*: a partially-updated tree (Windows ZIP copy loop) parses yet
  13. dies with ``ImportError: cannot import name``. The boot-selected subprocess
  14. keeps import side effects out of the updater's ``sys.modules``.
  15. Generic import-time exceptions are tolerated unless ``report_runtime_errors=True``.
  16. """
  17. from hermes_cli.update_cmd import _UPDATE_CRITICAL_MODULES
  18. from hermes_constants import FIRST_PARTY_MODULE_ROOTS
  19. import secrets
  20. marker = f"__HERMES_IMPORT_HEALTH_{secrets.token_hex(16)}__"
  21. probe = (
  22. "import importlib, json, sys\n"
  23. # Importing hermes_cli.main runs the startup dotenv load, which pulls external secret
  24. # sources (op/bws/command helpers, up to 120s each) unless argv says ``update``. The
  25. # probe only checks importability, so it inherits the updater's own argv contract.
  26. "sys.argv = ['hermes', 'update']\n"
  27. "failures = []\n"
  28. f"for name in {_UPDATE_CRITICAL_MODULES!r}:\n"
  29. " try:\n"
  30. " importlib.import_module(name)\n"
  31. " except ModuleNotFoundError as exc:\n"
  32. # A missing *third-party* module means deps aren't installed, not a skewed checkout;
  33. # only our own packages count. Roots come from hermes_constants so the user hint can't drift.
  34. " missing = (getattr(exc, 'name', '') or '').split('.')[0]\n"
  35. f" if missing in {tuple(sorted(FIRST_PARTY_MODULE_ROOTS))!r} or missing.startswith('hermes_') or {report_runtime_errors!r}:\n"
  36. " failures.append((name, type(exc).__name__, str(exc)))\n"
  37. " except ImportError as exc:\n"
  38. " failures.append((name, type(exc).__name__, str(exc)))\n"
  39. " except Exception as exc:\n"
  40. f" if {report_runtime_errors!r}:\n"
  41. " failures.append((name, type(exc).__name__, str(exc)))\n"
  42. " except BaseException as exc:\n"
  43. " failures.append((name, type(exc).__name__, str(exc)))\n"
  44. f"sys.stdout.write('\\n{marker}' + json.dumps(failures))\n")
  45. try:
  46. result = subprocess.run(
  47. runtime_command(Path(root), code=probe), cwd=str(root), capture_output=True, text=True,
  48. encoding="utf-8", errors="replace", timeout=120, check=False)
  49. except subprocess.TimeoutExpired:
  50. return _probe_failure("TimeoutExpired", "timed out before reporting import health")
  51. except (OSError, subprocess.SubprocessError):
  52. # Can't run the probe — don't block the update on our own tooling.
  53. return {}
  54. output = result.stdout or ""
  55. if marker not in output:
  56. return _probe_failure(
  57. "ProbeTerminated",
  58. f"terminated before reporting import health (exit code {result.returncode})")
  59. try:
  60. failures = json.loads(output.rsplit(marker, 1)[1])
  61. if not isinstance(failures, list) or any(
  62. not isinstance(item, list) or len(item) != 3 or not all(isinstance(v, str) for v in item)
  63. for item in failures):
  64. raise ValueError("invalid import-health payload")
  65. return {str(module): (str(kind), str(detail)) for module, kind, detail in failures}
  66. except (TypeError, ValueError):
  67. return _probe_failure("MalformedPayload", "reported malformed import health data")
  68. def _probe_failure(kind: str, detail: str) -> dict[str, tuple[str, str]]:
  69. """Failure row for the probe itself (as opposed to a module it imported)."""
  70. return {"critical-module probe": (kind, detail)}
  71. def _validate_critical_modules_import(
  72. root, *, report_runtime_errors: bool = False) -> tuple[bool, str | None, str | None]:
  73. """Return the first critical-module import failure, if any."""
  74. failures = _critical_module_import_failures(root, report_runtime_errors=report_runtime_errors)
  75. if failures:
  76. module = next(iter(failures))
  77. return False, module, failures[module][1]
  78. return True, None, None