config_version_stamp.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """The config schema-version stamp: raw reads of ``_config_version`` from config.yaml.
  2. Split out of :mod:`hermes_cli.config` (code-health size ratchet); ``hermes_cli.config``
  3. late-imports these and re-exports them, and :mod:`scripts.docker_config_migrate` reads the
  4. raw stamp directly. ``_coerce_config_version`` stays module-private here.
  5. """
  6. from __future__ import annotations
  7. from typing import Optional, Tuple
  8. from hermes_cli.config_defaults import DEFAULT_CONFIG
  9. def _coerce_config_version(value) -> int:
  10. """Return a safe integer config version, treating invalid values as legacy."""
  11. if isinstance(value, bool):
  12. return 0
  13. try:
  14. version = int(value)
  15. except (TypeError, ValueError):
  16. return 0
  17. return max(version, 0)
  18. def read_config_version_stamp(*, raise_on_parse_error: bool = False) -> tuple[Optional[int], int]:
  19. """Single raw read behind ``check_config_version()``: ``(stamp, latest_version)`` where
  20. *stamp* is ``None`` when config.yaml parsed but carries no ``_config_version`` key (a
  21. never-stamped current-schema file, not an ancient install — ``migrate_config()`` gives it only
  22. the legacy-key steps). A missing file, or malformed YAML under a tolerant caller, reads as
  23. ``latest`` exactly as ``check_config_version()`` always reported it."""
  24. from hermes_cli.config import InvalidUserConfigError, _warn_config_parse_failure, get_config_path
  25. from hermes_cli.config_backend import config_exists, read_config_doc
  26. latest = _coerce_config_version(DEFAULT_CONFIG.get("_config_version", 1)) or 1
  27. config_path = get_config_path()
  28. if not config_exists(config_path):
  29. return latest, latest
  30. try:
  31. config = read_config_doc(config_path)
  32. except Exception as e:
  33. _warn_config_parse_failure(config_path, e)
  34. if raise_on_parse_error:
  35. raise InvalidUserConfigError(
  36. f"Cannot inspect {config_path}: config.yaml is not valid YAML ({e})"
  37. ) from e
  38. return latest, latest
  39. if config is None:
  40. config = {} # empty file / bare document: valid first-run state
  41. if not isinstance(config, dict):
  42. # A list/scalar root parses fine but is just as unusable as broken YAML: save_config()
  43. # would refuse it later, after .env was already rewritten. Strict callers see it up front.
  44. if raise_on_parse_error:
  45. raise InvalidUserConfigError(
  46. f"Cannot inspect {config_path}: config.yaml top-level value must be "
  47. f"a mapping, got {type(config).__name__}"
  48. )
  49. config = {}
  50. if "_config_version" not in config:
  51. return None, latest
  52. return _coerce_config_version(config.get("_config_version")), latest
  53. def check_config_version(*, raise_on_parse_error: bool = False) -> tuple[int, int]:
  54. """Return ``(current_version, latest_version)`` from the raw on-disk config.
  55. Reads the raw file rather than ``load_config()``: the deep-merge would make a file lacking
  56. ``_config_version`` inherit the latest version, hiding that the schema was never migrated.
  57. Invalid YAML gets a parse warning, not an automatic schema rewrite. Tolerant runtime status
  58. callers keep the historical latest/latest fallback for malformed YAML; mutation and explicit
  59. validation paths set ``raise_on_parse_error`` so a parse failure or a non-mapping root cannot
  60. be mistaken for an up-to-date config. A file with no version key reads as 0."""
  61. stamp, latest = read_config_version_stamp(raise_on_parse_error=raise_on_parse_error)
  62. return (0 if stamp is None else stamp), latest
  63. def note_first_stamp(home, on_disk: dict, to_write: dict) -> list[str]:
  64. """``save_config`` is about to give *home*'s config.yaml (*on_disk*: missing or never stamped) its first
  65. ``_config_version`` outside a migration, so the steps up to that version never see this home. Do into
  66. *to_write* what they would have done with the home's pre-split files: record the left-core rows in use
  67. (``left_core_migration.record_core_use``), or the stamp would make a home that ran the core feature look
  68. newer than the split, and move its AGENT_BROWSER_* settings (``config_migrations_browser``), which
  69. nothing reads any more. Returns those browser moves."""
  70. if "_config_version" in on_disk or "_config_version" not in to_write:
  71. return []
  72. from agent.safe_worker_policy import worker_config_snapshot
  73. if worker_config_snapshot() is not None:
  74. return [] # a frozen worker never reads the profile's files; its owner migrates the home
  75. from hermes_cli.config_migrations_browser import adopt_agent_browser_env
  76. from hermes_cli.left_core_migration import LEFT_CORE, record_core_use
  77. for version in sorted({feature.left_at for feature in LEFT_CORE if feature.left_at}):
  78. record_core_use(home, to_write, version)
  79. return adopt_agent_browser_env(home, to_write)
  80. def stamp_missing_config() -> bool:
  81. """A missing config.yaml reads as current (:func:`read_config_version_stamp`), so no config step ever
  82. runs on the home. When its .env still carries AGENT_BROWSER_* settings, create config.yaml with its
  83. first stamp (:func:`note_first_stamp`) now, before callers trust that shortcut, or the browser those
  84. settings chose is lost. A home without them stays without a config.yaml. Returns whether one was written."""
  85. from hermes_cli.config import _secure_file, atomic_config_write, get_config_path, is_managed
  86. from hermes_cli.config_backend import config_exists
  87. path = get_config_path()
  88. if config_exists(path) or is_managed():
  89. return False
  90. config = {"_config_version": _coerce_config_version(DEFAULT_CONFIG.get("_config_version", 1)) or 1}
  91. if not note_first_stamp(path.parent, {}, config):
  92. return False
  93. path.parent.mkdir(parents=True, exist_ok=True)
  94. atomic_config_write(path, config)
  95. _secure_file(path)
  96. return True