Skip to content

The agent that grows with you

feat(cron): per-job durable notepad — KV scratchpad surviving scheduled runs

Teknium04e8a661f295
diff --git a/cron/notepad.py b/cron/notepad.py
new file mode 100644
index 00000000000..9b8864bb6d5
--- /dev/null
+++ b/cron/notepad.py
@@ -0,0 +1,181 @@
+"""Per-job durable notepad for cron jobs.
+
+A tiny KV scratchpad each cron job can use to carry state across scheduled
+wake-ups (cursors, watermarks, watchlists). Stored in its own profile-local
+SQLite file next to the executions ledger, following the same
+connection/pragma pattern as ``cron/executions.py``.
+
+Size caps (documented contract):
+
+- ``MAX_VALUE_BYTES`` (16 KB): per-key value cap, measured in UTF-8 bytes.
+- ``MAX_JOB_TOTAL_BYTES`` (64 KB): per-job cap over the sum of key+value
+ bytes. Oversized writes raise ``ValueError`` and leave the store
+ untouched — the notepad is prompt-injected each run, so unbounded growth
+ would bloat every wake-up's prompt.
+
+Write path is the CLI (``hermes cron notepad <job_id> set <key> <value>``),
+which the running agent invokes via its terminal tool; no model tool is
+added.
+
+Inspired by: Amp (Sourcegraph) cron notepad (idea-level, proprietary — zero
+code).
+"""
+
+from __future__ import annotations
+
+import sqlite3
+import threading
+from contextlib import contextmanager
+from typing import Any, Dict, Iterator, List, Optional
+
+from hermes_constants import get_hermes_home
+from hermes_time import now as _hermes_now
+
+NOTEPAD_FILE = get_hermes_home().resolve() / "cron" / "notepad.db"
+MAX_VALUE_BYTES = 16 * 1024
+MAX_KEY_CHARS = 128
+MAX_JOB_TOTAL_BYTES = 64 * 1024
+_lock = threading.RLock()
+
+
+def _connect() -> sqlite3.Connection:
+ NOTEPAD_FILE.parent.mkdir(parents=True, exist_ok=True)
+ return sqlite3.connect(NOTEPAD_FILE, timeout=5)
+
+
+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")
+ conn.execute(
+ """CREATE TABLE IF NOT EXISTS cron_notepad (
+ job_id TEXT NOT NULL,
+ key TEXT NOT NULL,
+ value TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (job_id, key)
+ )"""
+ )
+
+
+@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()
+
+
+def _validate(job_id: str, key: str, value: str) -> None:
+ if not str(job_id):
+ raise ValueError("job_id must be non-empty")
+ if not key:
+ raise ValueError("key must be non-empty")
+ 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)"
+ )
+
+
+def set_note(job_id: str, key: str, value: str) -> Dict[str, Any]:
+ """Upsert one key. Raises ValueError when a size cap would be exceeded."""
+ job_id, key, value = str(job_id), str(key), str(value)
+ _validate(job_id, key, value)
+ now = _hermes_now().isoformat()
+ with _transaction() as conn:
+ row = conn.execute(
+ """SELECT COALESCE(SUM(LENGTH(CAST(key AS BLOB))
+ + LENGTH(CAST(value AS BLOB))), 0)
+ FROM cron_notepad WHERE job_id=? AND key<>?""",
+ (job_id, key),
+ ).fetchone()
+ other_bytes = int(row[0])
+ entry_bytes = len(key.encode("utf-8")) + len(value.encode("utf-8"))
+ if other_bytes + entry_bytes > MAX_JOB_TOTAL_BYTES:
+ raise ValueError(
+ f"notepad full: job '{job_id}' would exceed "
+ f"{MAX_JOB_TOTAL_BYTES} bytes total; delete unused keys first"
+ )
+ conn.execute(
+ """INSERT INTO cron_notepad (job_id, key, value, updated_at)
+ VALUES (?, ?, ?, ?)
+ ON CONFLICT(job_id, key)
+ DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at""",
+ (job_id, key, value, now),
+ )
+ return {"job_id": job_id, "key": key, "value": value, "updated_at": now}
+
+
+def get_note(job_id: str, key: str) -> Optional[str]:
+ with _transaction() as conn:
+ row = conn.execute(
+ "SELECT value FROM cron_notepad WHERE job_id=? AND key=?",
+ (str(job_id), str(key)),
+ ).fetchone()
+ return None if row is None else row["value"]
+
+
+def delete_note(job_id: str, key: str) -> bool:
+ with _transaction() as conn:
+ cur = conn.execute(
+ "DELETE FROM cron_notepad WHERE job_id=? AND key=?",
+ (str(job_id), str(key)),
+ )
+ return cur.rowcount > 0
+
+
+def list_notes(job_id: str) -> List[Dict[str, Any]]:
+ """All entries for one job, sorted by key."""
+ with _transaction() as conn:
+ rows = conn.execute(
+ "SELECT job_id, key, value, updated_at FROM cron_notepad "
+ "WHERE job_id=? ORDER BY key",
+ (str(job_id),),
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+
+def clear_notepad(job_id: str) -> int:
+ """Delete every key for one job (e.g. on job removal). Returns row count."""
+ with _transaction() as conn:
+ cur = conn.execute(
+ "DELETE FROM cron_notepad WHERE job_id=?", (str(job_id),)
+ )
+ return cur.rowcount
+
+
+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).
+ """
+ try:
+ notes = list_notes(job_id)
+ except Exception:
+ return ""
+ if not notes:
+ return ""
+ lines = [f"- {note['key']}: {note['value']}" for note in notes]
+ return (
+ "## Job notepad (persistent across runs)\n"
+ "This durable scratchpad survives between scheduled runs of this "
+ "job. Update it via the CLI, e.g.:\n"
+ f"`hermes cron notepad {job_id} set <key> <value>` "
+ f"(also: get/delete/list; `hermes cron notepad {job_id} delete "
+ "<key>` removes an entry).\n\n" + "\n".join(lines) + "\n\n"
+ )
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 9378e92df7c..f9b7ff30df7 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2673,6 +2673,16 @@ def _build_job_prompt(
logger.warning("context_from: failed to read output for job %r: %s", source_job_id, e)
# silent skip — do not pollute the prompt with error messages
+ # Inject the job's durable notepad (per-job KV scratchpad surviving
+ # scheduled wake-ups). Empty notepad renders as "" so jobs that never
+ # use the feature get a byte-identical prompt.
+ from cron import notepad as cron_notepad
+
+ notepad_section = cron_notepad.render_notepad_section(str(job.get("id") or ""))
+ if notepad_section:
+ prompt = f"{notepad_section}{prompt}"
+ has_injected_data = True
+
# Always prepend cron execution guidance so the agent knows how
# delivery works and can suppress delivery when appropriate.
cron_hint = (
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index 6258dfd4a8f..aa3fad4437b 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -478,6 +478,69 @@ def _job_action(action: str, job_id: str, success_verb: str) -> int:
return 0
+def cron_notepad(args) -> int:
+ """Handle ``hermes cron notepad <job_id> [get|set|delete|list]``.
+
+ The per-job durable KV scratchpad (``cron/notepad.py``). This CLI is the
+ write path — a running cron agent updates its own notepad by invoking
+ these commands via its terminal tool; the scheduler injects non-empty
+ notepads into the job prompt on each run.
+ """
+ from cron import notepad
+
+ job_id = str(getattr(args, "job_id", "") or "")
+ action = getattr(args, "notepad_action", None) or "list"
+ key = getattr(args, "key", None)
+ value = getattr(args, "value", None)
+
+ if not job_id:
+ print(color("A job ID is required.", Colors.RED))
+ return 1
+
+ try:
+ if action == "set":
+ if key is None or value is None:
+ print(color("Usage: hermes cron notepad <job_id> set <key> <value>", Colors.RED))
+ return 1
+ notepad.set_note(job_id, key, value)
+ print(color(f"Set notepad key '{key}' for job {job_id}.", Colors.GREEN))
+ return 0
+
+ if action == "get":
+ if key is None:
+ print(color("Usage: hermes cron notepad <job_id> get <key>", Colors.RED))
+ return 1
+ stored = notepad.get_note(job_id, key)
+ if stored is None:
+ print(color(f"No notepad key '{key}' for job {job_id}.", Colors.YELLOW))
+ return 1
+ print(stored)
+ return 0
+
+ if action == "delete":
+ if key is None:
+ print(color("Usage: hermes cron notepad <job_id> delete <key>", Colors.RED))
+ return 1
+ if notepad.delete_note(job_id, key):
+ print(color(f"Deleted notepad key '{key}' for job {job_id}.", Colors.GREEN))
+ return 0
+ print(color(f"No notepad key '{key}' for job {job_id}.", Colors.YELLOW))
+ return 1
+
+ # list (default)
+ notes = notepad.list_notes(job_id)
+ if not notes:
+ print(color(f"Notepad for job {job_id} is empty.", Colors.DIM))
+ return 0
+ for note in notes:
+ print(f" {color(note['key'], Colors.YELLOW)} = {note['value']}")
+ print(f" {color('updated: ' + str(note['updated_at']), Colors.DIM)}")
+ return 0
+ except ValueError as exc:
+ print(color(f"Notepad error: {exc}", Colors.RED))
+ return 1
+
+
def cron_command(args):
"""Handle cron subcommands."""
subcmd = getattr(args, 'cron_command', None)
@@ -499,6 +562,9 @@ def cron_command(args):
cron_runs(getattr(args, "job_id", None), getattr(args, "limit", 20))
return 0
+ if subcmd == "notepad":
+ return cron_notepad(args)
+
if subcmd in {"create", "add"}:
return cron_create(args)
diff --git a/hermes_cli/subcommands/cron.py b/hermes_cli/subcommands/cron.py
index c9d6f6a4b40..8cc7d14ca63 100644
--- a/hermes_cli/subcommands/cron.py
+++ b/hermes_cli/subcommands/cron.py
@@ -225,6 +225,23 @@ def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:
cron_runs.add_argument("job_id", nargs="?", help="Optional job ID filter")
cron_runs.add_argument("--limit", type=int, default=20, help="Rows to show (1-500)")
+ # cron notepad — per-job durable KV scratchpad (injected into the job
+ # prompt each run; the running agent writes it via this CLI).
+ cron_notepad = cron_subparsers.add_parser(
+ "notepad",
+ help="Read/write a job's durable notepad (persistent KV across runs)",
+ )
+ cron_notepad.add_argument("job_id", help="Job ID the notepad belongs to")
+ cron_notepad.add_argument(
+ "notepad_action",
+ nargs="?",
+ default="list",
+ choices=["get", "set", "delete", "list"],
+ help="Action (default: list)",
+ )
+ cron_notepad.add_argument("key", nargs="?", help="Notepad key (get/set/delete)")
+ cron_notepad.add_argument("value", nargs="?", help="Value to store (set)")
+
# cron tick (mostly for debugging)
cron_tick = cron_subparsers.add_parser("tick", help="Run due jobs once and exit")
add_accept_hooks_flag(cron_tick)
diff --git a/tests/cron/test_notepad.py b/tests/cron/test_notepad.py
new file mode 100644
index 00000000000..8f2c7204ad1
--- /dev/null
+++ b/tests/cron/test_notepad.py
@@ -0,0 +1,229 @@
+"""Per-job durable cron notepad: KV scratchpad surviving scheduled wake-ups.
+
+Covers CRUD on the SQLite-backed store, size-cap enforcement, prompt
+injection of non-empty notepads, byte-stable prompts for jobs that don't
+use the notepad, and the `hermes cron notepad` CLI handler.
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+
+def notepad(monkeypatch, tmp_path):
+ import cron.notepad as notepad_mod
+
+ monkeypatch.setattr(
+ notepad_mod, "NOTEPAD_FILE", tmp_path / "cron" / "notepad.db"
+ )
+ return notepad_mod
+
+
+def cron_env(tmp_path, monkeypatch, notepad):
+ """Isolated cron environment with temp HERMES_HOME (mirrors test_cron_context_from)."""
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "cron").mkdir()
+ (hermes_home / "cron" / "output").mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+
+ import cron.jobs as jobs_mod
+
+ monkeypatch.setattr(jobs_mod, "HERMES_DIR", hermes_home)
+ monkeypatch.setattr(jobs_mod, "CRON_DIR", hermes_home / "cron")
+ monkeypatch.setattr(jobs_mod, "JOBS_FILE", hermes_home / "cron" / "jobs.json")
+ monkeypatch.setattr(jobs_mod, "OUTPUT_DIR", hermes_home / "cron" / "output")
+ return hermes_home
+
+
+class TestNotepadCrud:
+ def test_set_then_get_roundtrip(self, notepad):
+ notepad.set_note("job-1", "cursor", "page=7")
+ assert notepad.get_note("job-1", "cursor") == "page=7"
+
+ def test_get_missing_key_returns_none(self, notepad):
+ assert notepad.get_note("job-1", "nope") is None
+
+ def test_set_overwrites_existing_value(self, notepad):
+ notepad.set_note("job-1", "cursor", "page=1")
+ notepad.set_note("job-1", "cursor", "page=2")
+ assert notepad.get_note("job-1", "cursor") == "page=2"
+ assert len(notepad.list_notes("job-1")) == 1
+
+ def test_delete_removes_key(self, notepad):
+ notepad.set_note("job-1", "cursor", "page=1")
+ assert notepad.delete_note("job-1", "cursor") is True
+ assert notepad.get_note("job-1", "cursor") is None
+
+ def test_delete_missing_key_returns_false(self, notepad):
+ assert notepad.delete_note("job-1", "ghost") is False
+
+ def test_list_notes_sorted_by_key(self, notepad):
+ notepad.set_note("job-1", "beta", "2")
+ notepad.set_note("job-1", "alpha", "1")
+ notes = notepad.list_notes("job-1")
+ assert [n["key"] for n in notes] == ["alpha", "beta"]
+ assert all(n["updated_at"] for n in notes)
+
+ def test_jobs_are_isolated(self, notepad):
+ notepad.set_note("job-1", "k", "one")
+ notepad.set_note("job-2", "k", "two")
+ assert notepad.get_note("job-1", "k") == "one"
+ assert notepad.get_note("job-2", "k") == "two"
+ assert len(notepad.list_notes("job-1")) == 1
+
+ def test_survives_new_connection(self, notepad):
+ """Durability: values persist across independent calls (fresh connections)."""
+ notepad.set_note("job-1", "state", "persisted")
+ # Every public call opens its own connection, so a second read
+ # after the writer's connection closed proves on-disk durability.
+ assert notepad.get_note("job-1", "state") == "persisted"
+ assert notepad.list_notes("job-1")[0]["value"] == "persisted"
+
+ def test_clear_notepad_removes_all_keys_for_job_only(self, notepad):
+ notepad.set_note("job-1", "a", "1")
+ notepad.set_note("job-1", "b", "2")
+ notepad.set_note("job-2", "a", "keep")
+ assert notepad.clear_notepad("job-1") == 2
+ assert notepad.list_notes("job-1") == []
+ assert notepad.get_note("job-2", "a") == "keep"
+
+
+class TestNotepadCaps:
+ def test_value_over_per_key_cap_rejected(self, notepad):
+ big = "x" * (notepad.MAX_VALUE_BYTES + 1)
+ with pytest.raises(ValueError, match="value too large"):
+ notepad.set_note("job-1", "big", big)
+ assert notepad.get_note("job-1", "big") is None
+
+ def test_value_at_cap_accepted(self, notepad):
+ exact = "x" * notepad.MAX_VALUE_BYTES
+ notepad.set_note("job-1", "exact", exact)
+ assert notepad.get_note("job-1", "exact") == exact
+
+ def test_key_over_cap_rejected(self, notepad):
+ with pytest.raises(ValueError, match="key too long"):
+ notepad.set_note("job-1", "k" * (notepad.MAX_KEY_CHARS + 1), "v")
+
+ def test_empty_key_rejected(self, notepad):
+ with pytest.raises(ValueError, match="key must be non-empty"):
+ notepad.set_note("job-1", "", "v")
+
+ def test_per_job_total_cap_enforced(self, notepad, monkeypatch):
+ monkeypatch.setattr(notepad, "MAX_JOB_TOTAL_BYTES", 100)
+ notepad.set_note("job-1", "a", "x" * 60)
+ with pytest.raises(ValueError, match="notepad full"):
+ notepad.set_note("job-1", "b", "x" * 60)
+ # Overwriting the existing key within budget still works.
+ notepad.set_note("job-1", "a", "x" * 90)
+ assert notepad.get_note("job-1", "a") == "x" * 90
+
+ def test_total_cap_counts_only_this_job(self, notepad, monkeypatch):
+ monkeypatch.setattr(notepad, "MAX_JOB_TOTAL_BYTES", 100)
+ notepad.set_note("other-job", "a", "x" * 90)
+ notepad.set_note("job-1", "a", "x" * 90) # must not raise
+ assert notepad.get_note("job-1", "a") == "x" * 90
+
+
+class TestPromptInjection:
+ def test_nonempty_notepad_rendered_into_prompt(self, cron_env, notepad):
+ from cron.jobs import create_job
+ from cron.scheduler import _build_job_prompt
+
+ job = create_job(prompt="Check the feed", schedule="every 1h")
+ notepad.set_note(job["id"], "last_seen_id", "8842")
+ notepad.set_note(job["id"], "watchlist", "alpha, beta")
+
+ prompt = _build_job_prompt(job)
+ assert "Job notepad (persistent across runs)" in prompt
+ assert "last_seen_id" in prompt
+ assert "8842" in prompt
+ assert "watchlist" in prompt
+ # The injected section documents the CLI write path for this job.
+ assert f"hermes cron notepad {job['id']} set" in prompt
+
+ def test_empty_notepad_prompt_byte_stable(self, cron_env, notepad):
+ from cron.jobs import create_job
+ from cron.scheduler import _build_job_prompt
+
+ job = create_job(prompt="Check the feed", schedule="every 1h")
+ baseline = _build_job_prompt(job)
+
+ # A different job's notes must not leak in; a set+delete cycle on
+ # this job must leave the prompt byte-identical.
+ notepad.set_note("ffffffffffff", "k", "other job data")
+ notepad.set_note(job["id"], "tmp", "scratch")
+ notepad.delete_note(job["id"], "tmp")
+
+ assert _build_job_prompt(job) == baseline
+ assert "notepad" not in baseline.lower()
+
+ def test_notepad_read_failure_does_not_break_prompt(self, cron_env, notepad, monkeypatch):
+ from cron.jobs import create_job
+ from cron.scheduler import _build_job_prompt
+
+ job = create_job(prompt="Check the feed", schedule="every 1h")
+
+ def _boom(_job_id):
+ raise RuntimeError("db unavailable")
+
+ monkeypatch.setattr(notepad, "list_notes", _boom)
+ prompt = _build_job_prompt(job)
+ assert "Check the feed" in prompt
+ assert "notepad" not in prompt.lower()
+
+
+class TestNotepadCli:
+ def _ns(self, **kw):
+ base = dict(job_id=None, notepad_action="list", key=None, value=None)
+ base.update(kw)
+ return argparse.Namespace(**base)
+
+ def test_cli_set_get_list_delete(self, notepad, capsys):
+ from hermes_cli.cron import cron_notepad
+
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="set", key="cursor", value="42")) == 0
+ assert notepad.get_note("job-1", "cursor") == "42"
+
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="get", key="cursor")) == 0
+ assert "42" in capsys.readouterr().out
+
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="list")) == 0
+ assert "cursor" in capsys.readouterr().out
+
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="delete", key="cursor")) == 0
+ assert notepad.get_note("job-1", "cursor") is None
+
+ def test_cli_get_missing_key_exits_nonzero(self, notepad, capsys):
+ from hermes_cli.cron import cron_notepad
+
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="get", key="ghost")) == 1
+
+ def test_cli_set_requires_key_and_value(self, notepad, capsys):
+ from hermes_cli.cron import cron_notepad
+
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="set", key="k")) == 1
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="set")) == 1
+
+ def test_cli_set_oversized_value_reports_error(self, notepad, capsys):
+ from hermes_cli.cron import cron_notepad
+
+ big = "x" * (notepad.MAX_VALUE_BYTES + 1)
+ assert cron_notepad(self._ns(job_id="job-1", notepad_action="set", key="k", value=big)) == 1
+ assert "too large" in capsys.readouterr().out.lower()
+
+ def test_cron_command_dispatches_notepad(self, notepad):
+ from hermes_cli.cron import cron_command
+
+ ns = self._ns(job_id="job-9", notepad_action="set", key="k", value="v")
+ ns.cron_command = "notepad"
+ assert cron_command(ns) == 0
+ assert notepad.get_note("job-9", "k") == "v"