Skip to content

The agent that grows with you

refactor(cron): share ledger connect/prepare/transaction across executions, incidents, notepad; compact suggestions

Tekniumb3d9b20a3b29
diff --git a/cron/executions.py b/cron/executions.py
index 9f9bc6fbeb7..054f995e1a9 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -1,8 +1,8 @@
"""Profile-local durable audit ledger for cron execution attempts.
-The ledger records what is known about each attempt; it is not a retry queue.
-Interrupted attempts become ``unknown`` only after their exact owner process is
-proved gone. Terminal states are immutable.
+The ledger records what is known about each attempt; it is not a retry queue. Interrupted attempts
+become ``unknown`` only after their exact owner process is proved gone. Terminal states are immutable.
+Also hosts the SQLite connection/transaction helpers shared with ``cron.incidents`` / ``cron.notepad``.
"""
from __future__ import annotations
@@ -12,14 +12,14 @@ import sqlite3
import threading
import uuid
from contextlib import contextmanager
-from typing import Any, Dict, Iterator, List, Optional
+from pathlib import Path
+from typing import Any, Callable, Dict, Iterator, List, Optional
from hermes_constants import get_hermes_home
from hermes_time import now as _hermes_now
-# Optional test override. Production resolves the path at transaction time so
-# dashboard operations that temporarily enter another profile cannot leak that
-# profile's execution records into the import-time home.
+# Optional test override. Production resolves the path at transaction time so dashboard operations
+# that temporarily enter another profile cannot leak that profile's records into the import-time home.
EXECUTIONS_FILE: Optional[Path] = None
MAX_TERMINAL_EXECUTIONS = 1000
_TERMINAL_STATES = ("completed", "failed", "unknown")
@@ -27,21 +27,54 @@ _lock = threading.RLock()
_PROCESS_ID = uuid.uuid4().hex
-def _connect() -> sqlite3.Connection:
+# --- shared SQLite ledger plumbing --------------------------------------------------------------
+
+def open_ledger(path: Path) -> sqlite3.Connection:
+ """Open a profile-local ledger DB, creating its ``cron/`` dir with the store's permissions."""
from cron.jobs import _ensure_cron_dir
- path = EXECUTIONS_FILE or (get_hermes_home().resolve() / "cron" / "executions.db")
_ensure_cron_dir(path.parent)
return sqlite3.connect(path, timeout=5)
-def _initialize_schema(conn: sqlite3.Connection) -> None:
+def prepare_ledger(conn: sqlite3.Connection, *, db_label: str, synchronous_full: bool = True) -> None:
+ """Row factory + busy timeout + WAL (with fallback) + optional ``synchronous=FULL``."""
from hermes_state import apply_wal_with_fallback
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA busy_timeout=5000")
- apply_wal_with_fallback(conn, db_label="cron/executions.db")
- conn.execute("PRAGMA synchronous=FULL")
+ apply_wal_with_fallback(conn, db_label=db_label)
+ if synchronous_full:
+ conn.execute("PRAGMA synchronous=FULL")
+
+
+@contextmanager
+def ledger_transaction(
+ lock: threading.RLock,
+ connect: Callable[[], sqlite3.Connection],
+ initialize_schema: Callable[[sqlite3.Connection], None],
+) -> Iterator[sqlite3.Connection]:
+ """Open a connection, commit/rollback on exit, always close. ``sqlite3.Connection``'s own context
+ manager does NOT close (leaks WAL/SHM fds until GC); schema init runs inside the ``try`` so a
+ PRAGMA/DDL failure after ``connect()`` still closes."""
+ with lock:
+ conn = connect()
+ try:
+ initialize_schema(conn)
+ with conn:
+ yield conn
+ finally:
+ conn.close()
+
+
+# --- executions ledger --------------------------------------------------------------------------
+
+def _connect() -> sqlite3.Connection:
+ return open_ledger(EXECUTIONS_FILE or (get_hermes_home().resolve() / "cron" / "executions.db"))
+
+
+def _initialize_schema(conn: sqlite3.Connection) -> None:
+ prepare_ledger(conn, db_label="cron/executions.db")
conn.execute(
"""CREATE TABLE IF NOT EXISTS executions (
id TEXT PRIMARY KEY,
@@ -70,20 +103,12 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
@contextmanager
def _transaction() -> Iterator[sqlite3.Connection]:
- """Open a connection, commit/rollback on exit, always close. ``sqlite3.Connection``'s own
- context manager does NOT close (leaks WAL/SHM fds until GC); schema init runs inside the ``try``
- so a PRAGMA/DDL failure after ``connect()`` still closes."""
- with _lock:
- conn = _connect()
- try:
- _initialize_schema(conn)
- with conn:
- yield conn
- finally:
- conn.close()
+ with ledger_transaction(_lock, _connect, _initialize_schema) as conn:
+ yield conn
-def _record(row: Optional[sqlite3.Row]) -> Optional[Dict[str, Any]]:
+def _fetch(conn: sqlite3.Connection, execution_id: str) -> Optional[Dict[str, Any]]:
+ row = conn.execute("SELECT * FROM executions WHERE id=?", (execution_id,)).fetchone()
return dict(row) if row is not None else None
@@ -121,14 +146,13 @@ def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:
def _prune_unlocked(conn: sqlite3.Connection) -> None:
- limit = max(0, int(MAX_TERMINAL_EXECUTIONS))
conn.execute(
"""DELETE FROM executions WHERE id IN (
SELECT id FROM executions
WHERE status IN ('completed','failed','unknown')
ORDER BY claimed_at DESC, id DESC LIMIT -1 OFFSET ?
)""",
- (limit,),
+ (max(0, int(MAX_TERMINAL_EXECUTIONS)),),
)
@@ -146,10 +170,7 @@ def create_execution(job_id: str, *, source: str) -> Dict[str, Any]:
(execution_id, str(job_id), str(source), _PROCESS_ID, pid,
_process_start_time(pid), now),
)
- row = conn.execute(
- "SELECT * FROM executions WHERE id=?", (execution_id,)
- ).fetchone()
- record = _record(row)
+ record = _fetch(conn, execution_id)
_emit_execution_state(record)
return record # type: ignore[return-value]
@@ -165,9 +186,7 @@ def mark_execution_running(execution_id: str) -> Optional[Dict[str, Any]]:
)
if cur.rowcount != 1:
return None
- record = _record(conn.execute(
- "SELECT * FROM executions WHERE id=?", (execution_id,)
- ).fetchone())
+ record = _fetch(conn, execution_id)
_emit_execution_state(record)
return record
@@ -189,9 +208,7 @@ def finish_execution(
if cur.rowcount != 1:
return None
_prune_unlocked(conn)
- record = _record(conn.execute(
- "SELECT * FROM executions WHERE id=?", (execution_id,)
- ).fetchone())
+ record = _fetch(conn, execution_id)
_emit_execution_state(record, delivery_outcome=delivery_outcome)
return record
@@ -221,9 +238,7 @@ def recover_interrupted_executions() -> int:
)
changed += cur.rowcount
if cur.rowcount:
- record = _record(conn.execute(
- "SELECT * FROM executions WHERE id=?", (row["id"],)
- ).fetchone())
+ record = _fetch(conn, row["id"])
if record is not None:
recovered.append(record)
if changed:
diff --git a/cron/incidents.py b/cron/incidents.py
index 6b62bd92796..b66f8c640b5 100644
--- a/cron/incidents.py
+++ b/cron/incidents.py
@@ -1,18 +1,11 @@
"""Durable cron failure incidents with signature dedup and ack.
-The executions ledger (``cron.executions``) records every attempt; this module groups the *failures*
-into durable incidents keyed by ``(job_id, error signature)`` so the same job failing with the same
-error does not re-ping the operator every run once they have acknowledged it.
-
-Lifecycle: ``detected`` → ``alerted`` → ``closed``. Closing (acking) an incident is per-signature:
-the same job + same normalized error keeps resolving to the SAME incident id, so a closed incident
-stays closed (no re-alert) until the error text changes, which mints a brand-new incident.
-``detected`` means the failure was recorded; ``alerted`` means at least one failure ping for the
-signature actually reached the operator. Other lifecycle words (e.g. ``reviewed``) are deliberately
-NOT reserved here.
-
-Incidents live in the SAME ``cron/executions.db`` as ``cron.executions`` (one ledger file, shared
-connection settings).
+The executions ledger records every attempt; this module groups the *failures* into incidents keyed
+by ``(job_id, error signature)`` so the same job failing with the same error does not re-ping the
+operator every run once acknowledged. Lifecycle: ``detected`` → ``alerted`` → ``closed``. The same
+job + same normalized error resolves to the SAME incident id, so a closed incident stays closed until
+the error text changes and mints a new one. ``alerted`` means a failure ping actually reached the
+operator. Incidents share ``cron/executions.db`` with ``cron.executions`` (one ledger file).
"""
from __future__ import annotations
@@ -25,6 +18,7 @@ from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional
+from cron.executions import ledger_transaction, open_ledger, prepare_ledger
from hermes_constants import get_hermes_home
from hermes_time import now as _hermes_now
@@ -47,21 +41,10 @@ _MAX_SIGNATURE_ERROR_CHARS = 200
_lock = threading.RLock()
-def _connect() -> sqlite3.Connection:
- from cron.jobs import _ensure_cron_dir
-
- path = _db_path()
- _ensure_cron_dir(path.parent)
- return sqlite3.connect(path, timeout=5)
-
-
def _db_path() -> Path:
- """Resolve the shared cron DB path.
-
- Prefer the ``cron.executions`` override when one is installed so an operator/test that redirects
- the executions ledger also redirects the incident table — they must stay in the SAME database.
- Falls back to this module's own override, then the canonical profile home.
- """
+ """Shared cron DB path. The ``cron.executions`` override wins when installed so redirecting the
+ executions ledger also redirects the incident table (they must stay in the SAME database); then
+ this module's own override, then the canonical profile home."""
try:
from cron.executions import EXECUTIONS_FILE as _EXEC_OVERRIDE
@@ -74,13 +57,12 @@ def _db_path() -> Path:
return get_hermes_home().resolve() / "cron" / "executions.db"
-def _initialize_schema(conn: sqlite3.Connection) -> None:
- from hermes_state import apply_wal_with_fallback
+def _connect() -> sqlite3.Connection:
+ return open_ledger(_db_path())
- conn.row_factory = sqlite3.Row
- conn.execute("PRAGMA busy_timeout=5000")
- apply_wal_with_fallback(conn, db_label="cron/executions.db")
- conn.execute("PRAGMA synchronous=FULL")
+
+def _initialize_schema(conn: sqlite3.Connection) -> None:
+ prepare_ledger(conn, db_label="cron/executions.db")
conn.execute(
"""CREATE TABLE IF NOT EXISTS cron_incidents (
id TEXT PRIMARY KEY,
@@ -108,19 +90,8 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
@contextmanager
def _transaction() -> Iterator[sqlite3.Connection]:
- """Open a connection, commit/rollback on exit, always close.
-
- Mirrors ``cron.executions._transaction``: schema init runs inside the ``try`` so a PRAGMA/DDL
- failure after a successful ``connect()`` still closes the connection instead of leaking it.
- """
- with _lock:
- conn = _connect()
- try:
- _initialize_schema(conn)
- with conn:
- yield conn
- finally:
- conn.close()
+ with ledger_transaction(_lock, _connect, _initialize_schema) as conn:
+ yield conn
def _normalize_error(error: str) -> str:
@@ -129,14 +100,13 @@ def _normalize_error(error: str) -> str:
def _redact_error(error: str) -> str:
- """Redact secrets then bound the stored error length."""
+ """Redact secrets (best-effort; the scheduler path never fails on it) then bound the length."""
text = str(error or "")
try:
from agent.redact import redact_sensitive_text
text = redact_sensitive_text(text)
except Exception:
- # Redaction is best-effort; the scheduler path never fails on it.
pass
return text[:MAX_ERROR_CHARS]
@@ -144,8 +114,7 @@ def _redact_error(error: str) -> str:
def _error_signature(job_id: str, error: str) -> str:
"""Dedup key: stable for same job + same normalized error prefix."""
normalized = _normalize_error(error)[:_MAX_SIGNATURE_ERROR_CHARS]
- digest = hashlib.sha256(job_id.encode() + normalized.encode()).hexdigest()
- return digest[:12]
+ return hashlib.sha256(job_id.encode() + normalized.encode()).hexdigest()[:12]
def _incident_id(job_id: str, error_sig: str) -> str:
@@ -175,13 +144,9 @@ def upsert_incident(
failure_type: Optional[str] = None,
output_file: Optional[str] = None,
) -> tuple[str, bool]:
- """Record (or refresh) the incident for ``job_id`` + ``error``.
-
- Returns ``(incident_id, is_new)``. A row for the same signature already
- existing refreshes ``last_seen_at``/``error``/``output_file`` and keeps its
- current state — a ``closed`` (acked) incident stays closed for the same
- signature. A changed error text mints a new incident automatically.
- """
+ """Record (or refresh) the incident for ``job_id`` + ``error``; returns ``(incident_id, is_new)``.
+ An existing row for the signature refreshes ``last_seen_at``/``error``/``output_file`` and keeps
+ its state — a ``closed`` incident stays closed. A changed error text mints a new incident."""
job_id = str(job_id or "")
sig = _error_signature(job_id, error)
stored_error = _redact_error(error)
@@ -214,12 +179,9 @@ def upsert_incident(
def set_incident_state(incident_id: str, state: str) -> bool:
- """Transition an incident's lifecycle state; return whether it changed.
-
- ``closed`` is terminal for that signature: no transition (including back
- to ``alerted``) leaves it — re-open happens by the error changing and
- minting a NEW incident. Unknown states are rejected (no-op, ``False``).
- """
+ """Transition an incident's lifecycle state; return whether it changed. ``closed`` is terminal for
+ that signature (re-open happens by a changed error minting a NEW incident). Unknown states are
+ rejected (no-op, ``False``)."""
if state not in INCIDENT_STATES:
return False
now = _hermes_now().isoformat()
@@ -227,9 +189,7 @@ def set_incident_state(incident_id: str, state: str) -> bool:
row = conn.execute(
"SELECT state FROM cron_incidents WHERE id=?", (incident_id,)
).fetchone()
- if row is None or row["state"] == state:
- return False
- if row["state"] == "closed":
+ if row is None or row["state"] in (state, "closed"):
return False
if state == "closed":
conn.execute(
@@ -247,29 +207,23 @@ def set_incident_state(incident_id: str, state: str) -> bool:
def ack_incident(incident_id: str) -> bool:
- """Acknowledge (close) an incident; return whether the state changed.
-
- A no-op (``False``) when the incident does not exist or is already closed.
- """
+ """Acknowledge (close) an incident; ``False`` when missing or already closed."""
return set_incident_state(incident_id, "closed")
+def _state_filter(state: Optional[str]) -> tuple[str, tuple]:
+ return ("", ()) if state is None else (" WHERE state=?", (state,))
+
+
def list_incidents(state: Optional[str] = None) -> List[Dict[str, Any]]:
"""Return incidents, newest-activity first, optionally filtered by state."""
if state is not None and state not in INCIDENT_STATES:
return []
+ where, params = _state_filter(state)
with _transaction() as conn:
- if state is None:
- rows = conn.execute(
- "SELECT * FROM cron_incidents "
- "ORDER BY last_seen_at DESC, id DESC"
- ).fetchall()
- else:
- rows = conn.execute(
- "SELECT * FROM cron_incidents WHERE state=? "
- "ORDER BY last_seen_at DESC, id DESC",
- (state,),
- ).fetchall()
+ rows = conn.execute(
+ "SELECT * FROM cron_incidents" + where + " ORDER BY last_seen_at DESC, id DESC", params
+ ).fetchall()
return [dict(row) for row in rows]
@@ -284,12 +238,7 @@ def get_incident(incident_id: str) -> Optional[Dict[str, Any]]:
def count_incidents(state: Optional[str] = None) -> int:
if state is not None and state not in INCIDENT_STATES:
return 0
+ where, params = _state_filter(state)
with _transaction() as conn:
- if state is None:
- row = conn.execute("SELECT COUNT(*) AS n FROM cron_incidents").fetchone()
- else:
- row = conn.execute(
- "SELECT COUNT(*) AS n FROM cron_incidents WHERE state=?",
- (state,),
- ).fetchone()
+ row = conn.execute("SELECT COUNT(*) AS n FROM cron_incidents" + where, params).fetchone()
return int(row["n"]) if row is not None else 0
diff --git a/cron/notepad.py b/cron/notepad.py
index d0d304b4daa..6c5a91ea3b8 100644
--- a/cron/notepad.py
+++ b/cron/notepad.py
@@ -15,13 +15,13 @@ from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional
+from cron.executions import ledger_transaction, open_ledger, prepare_ledger
from hermes_constants import get_hermes_home
from hermes_time import now as _hermes_now
# Optional test override. Production resolves the path at transaction time so multiplexed profile
# ticks (set_hermes_home_override) cannot leak one profile's notepad rows into the import-time home
-# — and remove_job's clear_notepad cannot wipe the wrong profile's DB. Same pattern as
-# cron/executions.py.
+# — and remove_job's clear_notepad cannot wipe the wrong profile's DB.
NOTEPAD_FILE: Optional[Path] = None
MAX_VALUE_BYTES = 16 * 1024
MAX_KEY_CHARS = 128
@@ -34,19 +34,11 @@ def _current_notepad_file() -> Path:
def _connect() -> sqlite3.Connection:
- from cron.jobs import _ensure_cron_dir
-
- path = _current_notepad_file()
- _ensure_cron_dir(path.parent)
- return sqlite3.connect(path, timeout=5)
+ return open_ledger(_current_notepad_file())
def _initialize_schema(conn: sqlite3.Connection) -> None:
- from hermes_state import apply_wal_with_fallback
-
- conn.row_factory = sqlite3.Row
- conn.execute("PRAGMA busy_timeout=5000")
- apply_wal_with_fallback(conn, db_label="cron/notepad.db")
+ prepare_ledger(conn, db_label="cron/notepad.db", synchronous_full=False)
conn.execute(
"""CREATE TABLE IF NOT EXISTS cron_notepad (
job_id TEXT NOT NULL,
@@ -60,19 +52,8 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
@contextmanager
def _transaction() -> Iterator[sqlite3.Connection]:
- """Open a connection, commit/rollback on exit, always close.
-
- Mirrors ``cron.executions._transaction``: schema init runs inside the ``try`` so a PRAGMA/DDL
- failure still closes the connection instead of leaking it.
- """
- with _lock:
- conn = _connect()
- try:
- _initialize_schema(conn)
- with conn:
- yield conn
- finally:
- conn.close()
+ with ledger_transaction(_lock, _connect, _initialize_schema) as conn:
+ yield conn
def _validate(job_id: str, key: str, value: str) -> None:
@@ -83,9 +64,7 @@ def _validate(job_id: str, key: str, value: str) -> None:
if len(key) > MAX_KEY_CHARS:
raise ValueError(f"key too long (max {MAX_KEY_CHARS} characters)")
if len(value.encode("utf-8")) > MAX_VALUE_BYTES:
- raise ValueError(
- f"value too large (max {MAX_VALUE_BYTES} bytes per key)"
- )
+ raise ValueError(f"value too large (max {MAX_VALUE_BYTES} bytes per key)")
def set_note(job_id: str, key: str, value: str) -> Dict[str, Any]:
@@ -147,11 +126,8 @@ def list_notes(job_id: str) -> List[Dict[str, Any]]:
def clear_notepad(job_id: str) -> int:
- """Delete every key for one job (e.g. on job removal). Returns row count.
-
- Called from ``cron.jobs.remove_job`` so deleted jobs don't orphan their
- rows. No-ops without creating the DB when no notepad file exists yet.
- """
+ """Delete every key for one job (called from ``cron.jobs.remove_job``). Returns row count; no-ops
+ without creating the DB when no notepad file exists yet."""
if not _current_notepad_file().exists():
return 0
with _transaction() as conn:
@@ -162,11 +138,8 @@ def clear_notepad(job_id: str) -> int:
def render_notepad_section(job_id: str) -> str:
- """Render a job's notepad as a prompt section, or '' when empty/unavailable.
-
- Empty notepad MUST return the empty string so jobs that never use the
- feature get a byte-identical prompt (prompt-cache + drift safety).
- """
+ """Render a job's notepad as a prompt section. An empty notepad MUST return '' so jobs that never
+ use the feature get a byte-identical prompt (prompt-cache + drift safety)."""
try:
notes = list_notes(job_id)
except Exception:
diff --git a/cron/suggestions.py b/cron/suggestions.py
index f88efeddc9c..52352dac950 100644
--- a/cron/suggestions.py
+++ b/cron/suggestions.py
@@ -1,25 +1,11 @@
"""Suggested cron jobs — proposed automations the user accepts with one tap.
-A *suggestion* is a ready-to-run cron job spec that Hermes surfaces to the user, who accepts it
-(creates the real cron job) or dismisses it (latched so it is never re-offered). This is the single
-surface every automation proposal flows through, regardless of where it came from:
-
- * ``catalog`` — a curated starter automation (daily briefing, important-mail
- monitor, weekly digest, ...).
- * ``blueprint`` — the user installed a skill that carries a ``blueprint:`` block
- (see ``tools/blueprints.py``); installing it registers a
- suggestion instead of auto-scheduling.
- * ``usage`` — the background self-improvement review noticed a recurring
- ask that a scheduled job would serve.
- * ``integration`` — the user connected an account (Gmail, GitHub, ...) and
- the obvious automations for that surface are offered.
-
-Accepting a suggestion just calls the existing ``cron.jobs.create_job`` with the stored ``job_spec``
-— there is NO second job engine. Suggestions never auto-create jobs; acceptance is always explicit
-(consent-first). Dismissed suggestions latch by a stable ``dedup_key`` so the same proposal is not
-re-offered after the user says no.
-
-Storage mirrors ``cron/jobs.py``: ``~/.hermes/cron/suggestions.json``, atomic replace, 0600.
+A suggestion is a ready-to-run cron job spec the user accepts (creates the real job) or dismisses
+(latched by ``dedup_key`` so it is never re-offered). Every proposal flows through here regardless
+of source: ``catalog`` (curated starters), ``blueprint`` (skill ``blueprint:`` blocks, see
+``tools/blueprints.py``), ``usage`` (self-improvement review), ``integration`` (connected account).
+Accepting calls ``cron.jobs.create_job`` with the stored ``job_spec`` — no second job engine; nothing
+auto-creates (consent-first). Storage mirrors ``cron/jobs.py``: ``suggestions.json``, atomic replace, 0600.
"""
from __future__ import annotations
@@ -39,23 +25,15 @@ from utils import atomic_replace
logger = logging.getLogger(__name__)
-# Per-profile by design: suggestions live alongside the active profile's cron store. Anchor on
-# get_hermes_home() (profile home), not the shared default root. See cron/jobs.py for the full
-# rationale. Optional test override; production resolves the path at CALL time so multiplexed
-# profile ticks (set_hermes_home_override) cannot leak one profile's suggestions into the
-# import-time home.
+# Per-profile by design (anchored on get_hermes_home(), see cron/jobs.py). Optional test override;
+# production resolves the path at CALL time so multiplexed profile ticks (set_hermes_home_override)
+# cannot leak one profile's suggestions into the import-time home.
SUGGESTIONS_FILE: Optional[Path] = None
-
-def _current_suggestions_file() -> Path:
- return SUGGESTIONS_FILE or (get_hermes_home().resolve() / "cron" / "suggestions.json")
-
-# In-process lock protecting load->modify->save cycles (the background review
-# fork and the main agent can both write).
+# Protects load->modify->save cycles (the background review fork and the main agent can both write).
_suggestions_lock = threading.Lock()
-# Cap pending suggestions so the list never becomes a nag wall. When full,
-# new suggestions are dropped (the user should clear the backlog first).
+# Cap pending suggestions so the list never becomes a nag wall; when full, new ones are dropped.
MAX_PENDING = 5
VALID_SOURCES = frozenset({"catalog", "blueprint", "usage", "integration"})
@@ -64,6 +42,10 @@ _STATUS_ACCEPTED = "accepted"
_STATUS_DISMISSED = "dismissed"
+def _current_suggestions_file() -> Path:
+ return SUGGESTIONS_FILE or (get_hermes_home().resolve() / "cron" / "suggestions.json")
+
+
def _secure_file(path: Path) -> None:
try:
os.chmod(path, 0o600)
@@ -101,11 +83,7 @@ def _save_raw(suggestions: List[Dict[str, Any]]) -> None:
fd, tmp_path = tempfile.mkstemp(dir=str(suggestions_file.parent), suffix=".tmp", prefix=".sugg_")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
- json.dump(
- {"suggestions": suggestions, "updated_at": _hermes_now().isoformat()},
- f,
- indent=2,
- )
+ json.dump({"suggestions": suggestions, "updated_at": _hermes_now().isoformat()}, f, indent=2)
f.flush()
os.fsync(f.fileno())
atomic_replace(tmp_path, suggestions_file)
@@ -123,9 +101,13 @@ def load_suggestions() -> List[Dict[str, Any]]:
return _load_raw().get("suggestions", [])
+def _pending(suggestions: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ return [s for s in suggestions if s.get("status") == _STATUS_PENDING]
+
+
def list_pending() -> List[Dict[str, Any]]:
"""Return pending suggestions in creation order (oldest first)."""
- return [s for s in load_suggestions() if s.get("status") == _STATUS_PENDING]
+ return _pending(load_suggestions())
def add_suggestion(
@@ -136,15 +118,9 @@ def add_suggestion(
job_spec: Dict[str, Any],
dedup_key: str,
) -> Optional[Dict[str, Any]]:
- """Register a pending suggestion. Returns the record, or None if skipped.
-
- Skipped when: the source is unknown, the same ``dedup_key`` was already dismissed or accepted
- (never re-offer), an identical pending suggestion exists, or the pending list is full
- (``MAX_PENDING``).
-
- ``job_spec`` is a dict of kwargs for ``cron.jobs.create_job`` — accepting the suggestion passes
- it straight through, so there is no second schema to keep in sync.
- """
+ """Register a pending suggestion. Returns the record, or None when skipped: the same ``dedup_key``
+ was already decided on or is still pending (never re-offer, never duplicate), or the pending list
+ is full (``MAX_PENDING``). ``job_spec`` is passed straight to ``cron.jobs.create_job`` on accept."""
if source not in VALID_SOURCES:
raise ValueError(f"unknown suggestion source: {source!r}")
if not title.strip() or not dedup_key.strip():
@@ -152,18 +128,13 @@ def add_suggestion(
with _suggestions_lock:
suggestions = _load_raw().get("suggestions", [])
-
- # Never re-offer something the user already saw and decided on, and
- # never duplicate a still-pending proposal.
- for existing in suggestions:
- if existing.get("dedup_key") == dedup_key:
- if existing.get("status") in (_STATUS_DISMISSED, _STATUS_ACCEPTED):
- return None
- if existing.get("status") == _STATUS_PENDING:
- return None
-
- pending_count = sum(1 for s in suggestions if s.get("status") == _STATUS_PENDING)
- if pending_count >= MAX_PENDING:
+ if any(
+ existing.get("dedup_key") == dedup_key
+ and existing.get("status") in (_STATUS_DISMISSED, _STATUS_ACCEPTED, _STATUS_PENDING)
+ for existing in suggestions
+ ):
+ return None
+ if len(_pending(suggestions)) >= MAX_PENDING:
logger.info("Suggestion backlog full (%d); dropping %r", MAX_PENDING, title)
return None
@@ -183,19 +154,16 @@ def add_suggestion(
def get_suggestion(ref: str) -> Optional[Dict[str, Any]]:
- """Resolve a suggestion by id, 1-based pending index, or title (exact)."""
+ """Resolve a suggestion by id, 1-based pending index, or exact (case-insensitive) title."""
suggestions = load_suggestions()
- # By id.
for s in suggestions:
if s.get("id") == ref:
return s
- # By 1-based pending index.
if ref.isdigit():
- pending = [s for s in suggestions if s.get("status") == _STATUS_PENDING]
+ pending = _pending(suggestions)
idx = int(ref) - 1
if 0 <= idx < len(pending):
return pending[idx]
- # By exact title (case-insensitive).
for s in suggestions:
if s.get("title", "").lower() == ref.lower():
return s
@@ -205,33 +173,25 @@ def get_suggestion(ref: str) -> Optional[Dict[str, Any]]:
def _set_status(suggestion_id: str, status: str) -> bool:
with _suggestions_lock:
suggestions = _load_raw().get("suggestions", [])
- changed = False
for s in suggestions:
if s.get("id") == suggestion_id:
s["status"] = status
s["resolved_at"] = _hermes_now().isoformat()
- changed = True
- break
- if changed:
- _save_raw(suggestions)
- return changed
+ _save_raw(suggestions)
+ return True
+ return False
def dismiss_suggestion(ref: str) -> bool:
"""Dismiss a suggestion (latched — never re-offered for its dedup_key)."""
s = get_suggestion(ref)
- if not s:
- return False
- return _set_status(s["id"], _STATUS_DISMISSED)
+ return bool(s) and _set_status(s["id"], _STATUS_DISMISSED)
def accept_suggestion(ref: str, *, origin: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
- """Accept a suggestion: create the real cron job from its ``job_spec``.
-
- Returns the created cron job dict, or None if the suggestion isn't found / not pending. The
- job_spec is passed straight to ``cron.jobs.create_job``; an ``origin`` (platform/chat) is merged
- so "origin" delivery routes back to the chat where the user accepted.
- """
+ """Accept a suggestion: create the real cron job from its ``job_spec``. Returns the job dict, or
+ None if not found / not pending. ``origin`` (platform/chat) is merged so "origin" delivery routes
+ back to the chat where the user accepted."""
s = get_suggestion(ref)
if not s or s.get("status") != _STATUS_PENDING:
return None
@@ -248,8 +208,7 @@ def accept_suggestion(ref: str, *, origin: Optional[Dict[str, Any]] = None) -> O
try:
job = create_job_with_scheduler_registration(**spec)
except CronSchedulerRegistrationError:
- # The job is already durable. Resolve the suggestion so retrying the
- # same acceptance cannot create another local copy.
+ # The job is already durable: resolve the suggestion so a retry cannot create another local copy.
_set_status(s["id"], _STATUS_ACCEPTED)
raise
_set_status(s["id"], _STATUS_ACCEPTED)
@@ -257,13 +216,8 @@ def accept_suggestion(ref: str, *, origin: Optional[Dict[str, Any]] = None) -> O
def clear_resolved() -> int:
- """Drop accepted/dismissed records from disk. Returns the count removed.
-
- Pending suggestions and the dedup memory of dismissed ones are the only
- things that matter long-term, but dismissed records must be RETAINED for
- their dedup_key (so they aren't re-offered). This only prunes ACCEPTED
- records, which have served their purpose once the job exists.
- """
+ """Drop ACCEPTED records from disk (they served their purpose once the job exists); dismissed
+ records are RETAINED for their dedup_key. Returns the count removed."""
with _suggestions_lock:
suggestions = _load_raw().get("suggestions", [])
kept = [s for s in suggestions if s.get("status") != _STATUS_ACCEPTED]