environment.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """Environment manifest for project verification.
  2. Ported from superagent-ai/grok-cli ``src/verify/environment.ts``. The manifest
  3. at ``<project>/.hermes/environment.json`` is the user-editable source of truth:
  4. when present and valid it wins over fresh static detection.
  5. """
  6. from __future__ import annotations
  7. import json
  8. from datetime import datetime, timezone, UTC
  9. from pathlib import Path
  10. from agent.verify.recipes import Recipe, detect_recipe
  11. MANIFEST_VERSION = 1
  12. _MANIFEST_RELPATH = Path(".hermes") / "environment.json"
  13. def manifest_path(root: Path) -> Path:
  14. """Path of the verify manifest for the project at ``root``."""
  15. return Path(root) / _MANIFEST_RELPATH
  16. def load_manifest(root: Path) -> Recipe | None:
  17. """Load the saved recipe; any read/parse/shape problem returns ``None`` so a
  18. corrupt manifest degrades to fresh detection. Accepts the wrapped
  19. ``{version, recipe}`` shape and a bare recipe."""
  20. try:
  21. manifest = json.loads(manifest_path(root).read_text(encoding="utf-8-sig"))
  22. except (OSError, ValueError): # ValueError includes JSONDecodeError
  23. return None
  24. return Recipe.from_dict(manifest.get("recipe", manifest)) if isinstance(manifest, dict) else None
  25. def save_manifest(root: Path, recipe: Recipe) -> Path:
  26. """Persist ``recipe`` in the versioned wrapper shape; returns the manifest path."""
  27. path = manifest_path(root)
  28. path.parent.mkdir(parents=True, exist_ok=True)
  29. payload = {"version": MANIFEST_VERSION, "recipe": recipe.to_dict(), "updatedAt": datetime.now(UTC).isoformat()}
  30. path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  31. return path
  32. def load_or_detect(root: Path) -> tuple[Recipe | None, str]:
  33. """Return ``(recipe, source)``; a saved manifest ('manifest') wins over 'detected'."""
  34. saved = load_manifest(root)
  35. return (saved, "manifest") if saved is not None else (detect_recipe(root), "detected")