suggestions.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """Suggested cron jobs — proposed automations the user accepts with one tap.
  2. A suggestion is a ready-to-run cron job spec the user accepts (creates the real job) or dismisses
  3. (latched by ``dedup_key`` so it is never re-offered). Every proposal flows through here regardless
  4. of source: ``catalog`` (curated starters), ``blueprint`` (skill ``blueprint:`` blocks, see
  5. ``tools/blueprints.py``), ``usage`` (self-improvement review), ``integration`` (connected account).
  6. Accepting calls ``cron.jobs.create_job`` with the stored ``job_spec`` — no second job engine;
  7. nothing auto-creates (consent-first). Storage mirrors ``cron/jobs.py`` (atomic replace, 0600).
  8. """
  9. from __future__ import annotations
  10. import json
  11. import logging
  12. import threading
  13. import uuid
  14. from pathlib import Path
  15. from typing import Any, Dict, List, Optional
  16. from hermes_constants import get_hermes_home
  17. from hermes_time import now as _hermes_now
  18. from utils import atomic_json_write
  19. logger = logging.getLogger(__name__)
  20. # Per-profile by design (anchored on get_hermes_home(), see cron/jobs.py). Optional test override;
  21. # production resolves the path at CALL time so multiplexed profile ticks (set_hermes_home_override)
  22. # cannot leak one profile's suggestions into the import-time home.
  23. # Per-profile by design (issue #4707): suggestions live alongside the active profile's cron store. Anchor on
  24. # get_hermes_home() (profile home), not the shared default root. Same pattern as cron/executions.py.
  25. SUGGESTIONS_FILE: Optional[Path] = None
  26. # Protects load->modify->save cycles (the background review fork and the main agent can both write).
  27. _suggestions_lock = threading.Lock()
  28. # Cap pending suggestions so the list never becomes a nag wall; when full, new ones are dropped.
  29. MAX_PENDING = 5
  30. VALID_SOURCES = frozenset({"catalog", "blueprint", "usage", "integration"})
  31. _STATUS_PENDING = "pending"
  32. _STATUS_ACCEPTED = "accepted"
  33. _STATUS_DISMISSED = "dismissed"
  34. def _current_suggestions_file() -> Path:
  35. return SUGGESTIONS_FILE or (get_hermes_home().resolve() / "cron" / "suggestions.json")
  36. def _ensure_dir() -> None:
  37. from cron.jobs import _ensure_cron_dir
  38. _ensure_cron_dir(_current_suggestions_file().parent)
  39. def _load_raw() -> dict[str, Any]:
  40. suggestions_file = _current_suggestions_file()
  41. if not suggestions_file.exists():
  42. return {"suggestions": []}
  43. try:
  44. with open(suggestions_file, "r", encoding="utf-8-sig") as f:
  45. data = json.load(f)
  46. except (json.JSONDecodeError, OSError) as e:
  47. logger.warning("suggestions.json unreadable (%s); starting empty", e)
  48. return {"suggestions": []}
  49. if isinstance(data, dict) and isinstance(data.get("suggestions"), list):
  50. return data
  51. if isinstance(data, list):
  52. return {"suggestions": data}
  53. logger.warning("suggestions.json malformed; starting empty")
  54. return {"suggestions": []}
  55. def _save_raw(suggestions: list[dict[str, Any]]) -> None:
  56. _ensure_dir()
  57. payload = {"suggestions": suggestions, "updated_at": _hermes_now().isoformat()}
  58. atomic_json_write(_current_suggestions_file(), payload, mode=0o600)
  59. def load_suggestions() -> list[dict[str, Any]]:
  60. """Return all suggestion records (any status)."""
  61. return _load_raw().get("suggestions", [])
  62. def _pending(suggestions: list[dict[str, Any]]) -> list[dict[str, Any]]:
  63. return [s for s in suggestions if s.get("status") == _STATUS_PENDING]
  64. def list_pending() -> list[dict[str, Any]]:
  65. """Return pending suggestions in creation order (oldest first)."""
  66. return _pending(load_suggestions())
  67. def add_suggestion(
  68. *, title: str, description: str, source: str, job_spec: dict[str, Any], dedup_key: str,
  69. ) -> Optional[dict[str, Any]]:
  70. """Register a pending suggestion. Returns the record, or None when skipped: the same
  71. ``dedup_key`` was already decided on or is still pending (never re-offer, never duplicate), or
  72. the pending list is full (``MAX_PENDING``). ``job_spec`` is passed straight to
  73. ``cron.jobs.create_job`` on accept."""
  74. if source not in VALID_SOURCES:
  75. raise ValueError(f"unknown suggestion source: {source!r}")
  76. if not title.strip() or not dedup_key.strip():
  77. raise ValueError("title and dedup_key are required")
  78. with _suggestions_lock:
  79. suggestions = _load_raw().get("suggestions", [])
  80. if any(
  81. existing.get("dedup_key") == dedup_key
  82. and existing.get("status") in (_STATUS_DISMISSED, _STATUS_ACCEPTED, _STATUS_PENDING)
  83. for existing in suggestions
  84. ):
  85. return None
  86. if len(_pending(suggestions)) >= MAX_PENDING:
  87. logger.info("Suggestion backlog full (%d); dropping %r", MAX_PENDING, title)
  88. return None
  89. record = {
  90. "id": uuid.uuid4().hex[:12],
  91. "title": title.strip(),
  92. "description": description.strip(),
  93. "source": source,
  94. "job_spec": job_spec,
  95. "dedup_key": dedup_key.strip(),
  96. "status": _STATUS_PENDING,
  97. "created_at": _hermes_now().isoformat(),
  98. }
  99. suggestions.append(record)
  100. _save_raw(suggestions)
  101. return record
  102. def get_suggestion(ref: str) -> Optional[dict[str, Any]]:
  103. """Resolve a suggestion by id, 1-based pending index, or exact (case-insensitive) title."""
  104. suggestions = load_suggestions()
  105. for s in suggestions:
  106. if s.get("id") == ref:
  107. return s
  108. if ref.isdigit():
  109. pending = _pending(suggestions)
  110. idx = int(ref) - 1
  111. if 0 <= idx < len(pending):
  112. return pending[idx]
  113. for s in suggestions:
  114. if s.get("title", "").lower() == ref.lower():
  115. return s
  116. return None
  117. def _set_status(suggestion_id: str, status: str) -> bool:
  118. with _suggestions_lock:
  119. suggestions = _load_raw().get("suggestions", [])
  120. for s in suggestions:
  121. if s.get("id") == suggestion_id:
  122. s["status"] = status
  123. s["resolved_at"] = _hermes_now().isoformat()
  124. _save_raw(suggestions)
  125. return True
  126. return False
  127. def dismiss_suggestion(ref: str) -> bool:
  128. """Dismiss a suggestion (latched — never re-offered for its dedup_key)."""
  129. s = get_suggestion(ref)
  130. return bool(s) and _set_status(s["id"], _STATUS_DISMISSED)
  131. def accept_suggestion(ref: str, *, origin: Optional[dict[str, Any]] = None) -> Optional[dict[str, Any]]:
  132. """Accept a suggestion: create the real cron job from its ``job_spec``. Returns the job dict, or
  133. None if not found / not pending. ``origin`` (platform/chat) is merged so "origin" delivery
  134. routes back to the chat where the user accepted."""
  135. s = get_suggestion(ref)
  136. if not s or s.get("status") != _STATUS_PENDING:
  137. return None
  138. from cron.scheduler import (
  139. CronSchedulerRegistrationError, create_job_with_scheduler_registration,
  140. )
  141. spec = dict(s.get("job_spec") or {})
  142. if origin is not None and "origin" not in spec:
  143. spec["origin"] = origin
  144. try:
  145. job = create_job_with_scheduler_registration(**spec)
  146. except CronSchedulerRegistrationError:
  147. # The job is already durable: resolve the suggestion so a retry cannot create a second copy.
  148. _set_status(s["id"], _STATUS_ACCEPTED)
  149. raise
  150. _set_status(s["id"], _STATUS_ACCEPTED)
  151. return job
  152. def clear_resolved() -> int:
  153. """Drop ACCEPTED records from disk (they served their purpose once the job exists); dismissed
  154. records are RETAINED for their dedup_key. Returns the count removed."""
  155. with _suggestions_lock:
  156. suggestions = _load_raw().get("suggestions", [])
  157. kept = [s for s in suggestions if s.get("status") != _STATUS_ACCEPTED]
  158. removed = len(suggestions) - len(kept)
  159. if removed:
  160. _save_raw(kept)
  161. return removed