config_home.py 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """Directory initialization and storage diagnostics for the active Hermes home."""
  2. import os
  3. from pathlib import Path
  4. from hermes_dir_acl import make_user_dir
  5. class HomeInitializationError(RuntimeError):
  6. """The home skeleton is unavailable, not an invalid YAML document."""
  7. def _directory_links(path: Path) -> list[Path]:
  8. return [part for part in (*reversed(path.parents), path) if part.is_symlink()]
  9. def _operator_owned_links(links: list[Path], home: Path) -> list[Path]:
  10. """Keep only the links that make the operator the owner of the home's permissions.
  11. That boundary is the home itself and anything under it. A link *above* the home
  12. (macOS ``/tmp`` -> ``/private/tmp``, ``/var`` -> ``/private/var``, or any aliased parent
  13. the user happens to live in) says nothing about who owns :data:`home`, and treating it as
  14. an operator-owned link left a fresh home and its ``cron``/``sessions``/``logs``/``memories``
  15. subdirectories at the default ``0o755`` instead of ``0o700``.
  16. """
  17. return [link for link in links if link == home or home in link.parents]
  18. def _ensure_directory(path: Path, *, create: bool, secure: bool, home: Path) -> None:
  19. from hermes_cli.config import _secure_dir
  20. detail = ""
  21. try:
  22. links = _directory_links(path)
  23. detail = "; ".join(f"{link} -> {link.readlink()}" for link in links)
  24. # Never materialize a missing mount's target on the underlying disk.
  25. for link in links:
  26. if not link.is_dir():
  27. raise FileNotFoundError(f"Directory link is unavailable: {link}")
  28. if create:
  29. make_user_dir(path, parents=True, exist_ok=True)
  30. elif not path.is_dir():
  31. raise FileNotFoundError(f"Required directory does not exist: {path}")
  32. # The operator owns permissions beyond a link, including logs/curator.
  33. if secure and not _operator_owned_links(links, home):
  34. _secure_dir(path)
  35. except OSError as exc:
  36. raise HomeInitializationError(
  37. f"Cannot initialize Hermes directory {path}: {exc}. "
  38. + (f"Directory links: {detail}. " if detail else "")
  39. + "Check the directory/link target, mount availability and access permissions; "
  40. "restore the mount or repair the link before retrying. "
  41. "Hermes has not replaced the link or created its missing target."
  42. ) from exc
  43. def initialize_home(home: Path, subdirs: tuple[str, ...], ensured: set[str]) -> None:
  44. from hermes_cli.config import _ensure_default_soul_md, is_managed
  45. managed = is_managed()
  46. old_umask = os.umask(0o007) if managed else None
  47. try:
  48. _ensure_directory(home, create=not managed, secure=not managed, home=home)
  49. required = ("cron", "sessions", "logs", "memories") if managed else subdirs
  50. for subdir in required:
  51. _ensure_directory(home / subdir, create=not managed, secure=not managed, home=home)
  52. if managed:
  53. _ensure_directory(home / "logs" / "curator", create=True, secure=False, home=home)
  54. try:
  55. _ensure_default_soul_md(home)
  56. except OSError as exc:
  57. raise HomeInitializationError(
  58. f"Cannot initialize Hermes home {home}: {exc}. "
  59. "Check storage availability and access permissions."
  60. ) from exc
  61. finally:
  62. if old_umask is not None:
  63. os.umask(old_umask)
  64. # Plugin discovery rebinds the resolved home. Do not repeat chmod through
  65. # that spelling after the operator-owned symlink boundary has been lost.
  66. ensured.update((str(home), str(home.resolve())))
  67. def config_load_issue(exc: Exception):
  68. from hermes_cli.config_issues import ConfigIssue
  69. if isinstance(exc, (HomeInitializationError, OSError)):
  70. return ConfigIssue(
  71. "error", f"Hermes storage is unavailable: {exc}",
  72. "Check the reported path, link target, mount and permissions; keep config.yaml unchanged.",
  73. )
  74. return ConfigIssue("error", "Could not load config.yaml", "Run 'hermes setup' to create a valid config")