Skip to content

An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.

feat(cron): job store and schedule math

smixs019170462618
diff --git a/src/d_brain/services/cron_store.py b/src/d_brain/services/cron_store.py
new file mode 100644
index 0000000..d462347
--- /dev/null
+++ b/src/d_brain/services/cron_store.py
@@ -0,0 +1,181 @@
+"""Cron job store: jobs.json + schedule math. Pure file/data layer.
+
+The file is the API between the brain and the bot: the brain (Claude Code
+with Bash) edits jobs via the ``python -m d_brain.cron`` CLI, the in-bot
+ticker re-reads the file every tick. All writes go through ``mutate()``
+under a cross-process flock so CLI edits and runner state updates never
+lose each other.
+"""
+
+import fcntl
+import json
+import logging
+import os
+import time
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timedelta
+from pathlib import Path
+from zoneinfo import ZoneInfo
+
+from croniter import croniter
+
+logger = logging.getLogger(__name__)
+
+STORE_VERSION = 1
+
+
+@dataclass(frozen=True)
+class Schedule:
+ """Union: kind='at' (one-shot ISO) | 'every' (seconds) | 'cron' (expr+tz)."""
+
+ kind: str
+ at: str | None = None
+ every_seconds: int | None = None
+ expr: str | None = None
+ tz: str | None = None
+
+
+@dataclass
+class JobState:
+ next_run: str | None = None # aware ISO-8601
+ last_run: str | None = None
+ last_status: str | None = None
+ last_error: str | None = None
+ consecutive_errors: int = 0
+
+
+@dataclass
+class CronJob:
+ id: str
+ prompt: str
+ schedule: Schedule
+ chat_id: int | None = None
+ delete_after_run: bool = False
+ enabled: bool = True
+ created_at: str = ""
+ state: JobState = field(default_factory=JobState)
+
+
+def parse_schedule(
+ *,
+ at: str | None = None,
+ every: int | None = None,
+ cron: str | None = None,
+ tz: str | None = None,
+ default_tz: str,
+) -> Schedule:
+ """Validate flat CLI args into a Schedule. Exactly one kind required."""
+ given = [v is not None for v in (at, every, cron)]
+ if sum(given) != 1:
+ raise ValueError("exactly one of --at / --every / --cron is required")
+ if at is not None:
+ parsed = datetime.fromisoformat(at)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=ZoneInfo(tz or default_tz))
+ return Schedule(kind="at", at=parsed.isoformat())
+ if every is not None:
+ if every <= 0:
+ raise ValueError("--every must be a positive number of seconds")
+ return Schedule(kind="every", every_seconds=every)
+ assert cron is not None
+ if not croniter.is_valid(cron):
+ raise ValueError(f"invalid cron expression: {cron!r}")
+ zone = tz or default_tz
+ ZoneInfo(zone) # raises on unknown zone
+ return Schedule(kind="cron", expr=cron, tz=zone)
+
+
+def compute_next_run(schedule: Schedule, *, now: datetime) -> datetime | None:
+ """Next fire time. Anchored to ``now`` — missed slots are not replayed
+ (misfire policy: at most one catch-up, the caller fires due jobs once)."""
+ if schedule.kind == "at":
+ assert schedule.at is not None
+ return datetime.fromisoformat(schedule.at)
+ if schedule.kind == "every":
+ assert schedule.every_seconds is not None
+ return now + timedelta(seconds=schedule.every_seconds)
+ if schedule.kind == "cron":
+ assert schedule.expr is not None
+ local_now = now.astimezone(ZoneInfo(schedule.tz or "UTC"))
+ nxt: datetime = croniter(schedule.expr, local_now).get_next(datetime)
+ return nxt
+ raise ValueError(f"unknown schedule kind: {schedule.kind!r}")
+
+
+def _job_from_dict(raw: dict) -> CronJob:
+ sched = raw.get("schedule") or {}
+ state = raw.get("state") or {}
+ return CronJob(
+ id=raw["id"],
+ prompt=raw["prompt"],
+ schedule=Schedule(
+ kind=sched.get("kind", ""),
+ at=sched.get("at"),
+ every_seconds=sched.get("every_seconds"),
+ expr=sched.get("expr"),
+ tz=sched.get("tz"),
+ ),
+ chat_id=raw.get("chat_id"),
+ delete_after_run=raw.get("delete_after_run", False),
+ enabled=raw.get("enabled", True),
+ created_at=raw.get("created_at", ""),
+ state=JobState(
+ next_run=state.get("next_run"),
+ last_run=state.get("last_run"),
+ last_status=state.get("last_status"),
+ last_error=state.get("last_error"),
+ consecutive_errors=state.get("consecutive_errors", 0),
+ ),
+ )
+
+
+class CronStore:
+ """jobs.json with atomic writes and a cross-process write lock."""
+
+ def __init__(self, cron_dir: Path) -> None:
+ self.cron_dir = Path(cron_dir)
+ self.jobs_file = self.cron_dir / "jobs.json"
+ self.lock_file = self.cron_dir / "jobs.lock"
+
+ def load(self) -> list[CronJob]:
+ if not self.jobs_file.exists():
+ return []
+ try:
+ raw = json.loads(self.jobs_file.read_text())
+ return [_job_from_dict(j) for j in raw.get("jobs", [])]
+ except (json.JSONDecodeError, KeyError, TypeError) as exc:
+ # Keep the evidence, never wipe it: rename and start empty.
+ quarantine = self.jobs_file.with_name(
+ f"jobs.json.corrupt-{int(time.time())}"
+ )
+ self.jobs_file.rename(quarantine)
+ logger.error("corrupt jobs.json moved to %s: %s", quarantine, exc)
+ return []
+
+ def save(self, jobs: list[CronJob]) -> None:
+ self.cron_dir.mkdir(parents=True, exist_ok=True)
+ payload = {"version": STORE_VERSION, "jobs": [asdict(j) for j in jobs]}
+ tmp = self.jobs_file.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2))
+ os.replace(tmp, self.jobs_file)
+
+ @contextmanager
+ def locked(self) -> Iterator[None]:
+ self.cron_dir.mkdir(parents=True, exist_ok=True)
+ with open(self.lock_file, "w") as fh:
+ fcntl.flock(fh, fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(fh, fcntl.LOCK_UN)
+
+ def mutate(self, fn: Callable[[list[CronJob]], None]) -> list[CronJob]:
+ """Read-modify-write under the lock — the only write path for both
+ the CLI and the runner, so concurrent edits never get lost."""
+ with self.locked():
+ jobs = self.load()
+ fn(jobs)
+ self.save(jobs)
+ return jobs
diff --git a/tests/test_cron_store.py b/tests/test_cron_store.py
new file mode 100644
index 0000000..1c7abb0
--- /dev/null
+++ b/tests/test_cron_store.py
@@ -0,0 +1,170 @@
+"""Tests for the cron job store and schedule math (pure, no tmux)."""
+
+import json
+from datetime import datetime, timedelta, timezone
+from zoneinfo import ZoneInfo
+
+import pytest
+
+from d_brain.services.cron_store import (
+ CronJob,
+ CronStore,
+ Schedule,
+ compute_next_run,
+ parse_schedule,
+)
+
+NOW = datetime(2026, 6, 10, 12, 0, tzinfo=timezone.utc) # 17:00 in Tashkent
+
+
+# ── parse_schedule ───────────────────────────────────────────────────
+
+
+def test_parse_requires_exactly_one_kind():
+ with pytest.raises(ValueError):
+ parse_schedule(default_tz="UTC")
+ with pytest.raises(ValueError):
+ parse_schedule(at="2026-06-12T18:00:00+05:00", every=60, default_tz="UTC")
+
+
+def test_parse_rejects_invalid_cron_expr():
+ with pytest.raises(ValueError):
+ parse_schedule(cron="not a cron", default_tz="UTC")
+
+
+def test_parse_cron_defaults_tz():
+ s = parse_schedule(cron="0 9 * * *", default_tz="Asia/Tashkent")
+ assert s.kind == "cron"
+ assert s.expr == "0 9 * * *"
+ assert s.tz == "Asia/Tashkent"
+
+
+def test_parse_naive_at_gets_default_tz():
+ s = parse_schedule(at="2026-06-12T18:00:00", default_tz="Asia/Tashkent")
+ assert s.kind == "at"
+ parsed = datetime.fromisoformat(s.at)
+ assert parsed.utcoffset() == timedelta(hours=5)
+
+
+def test_parse_every_keeps_seconds():
+ s = parse_schedule(every=3600, default_tz="UTC")
+ assert s.kind == "every"
+ assert s.every_seconds == 3600
+
+
+def test_parse_rejects_nonpositive_every():
+ with pytest.raises(ValueError):
+ parse_schedule(every=0, default_tz="UTC")
+
+
+# ── compute_next_run ─────────────────────────────────────────────────
+
+
+def test_next_run_at_is_the_at_time_independent_of_now():
+ s = Schedule(kind="at", at="2026-06-12T18:00:00+05:00")
+ assert compute_next_run(s, now=NOW) == datetime.fromisoformat(
+ "2026-06-12T18:00:00+05:00"
+ )
+
+
+def test_next_run_every_anchors_to_now_not_missed_slots():
+ # Misfire policy: after downtime the next run is now+interval, no backlog.
+ s = Schedule(kind="every", every_seconds=3600)
+ assert compute_next_run(s, now=NOW) == NOW + timedelta(hours=1)
+
+
+def test_next_run_cron_respects_tz():
+ s = Schedule(kind="cron", expr="0 9 * * *", tz="Asia/Tashkent")
+ nxt = compute_next_run(s, now=NOW)
+ # 17:00 local → next 09:00 local is tomorrow
+ assert nxt == datetime(2026, 6, 11, 9, 0, tzinfo=ZoneInfo("Asia/Tashkent"))
+
+
+def test_next_run_cron_same_day_when_still_ahead():
+ early = datetime(2026, 6, 10, 2, 0, tzinfo=timezone.utc) # 07:00 local
+ s = Schedule(kind="cron", expr="0 9 * * *", tz="Asia/Tashkent")
+ nxt = compute_next_run(s, now=early)
+ assert nxt == datetime(2026, 6, 10, 9, 0, tzinfo=ZoneInfo("Asia/Tashkent"))
+
+
+# ── store ────────────────────────────────────────────────────────────
+
+
+def _job(job_id="j1", **over):
+ base = dict(
+ id=job_id,
+ prompt="do the thing",
+ schedule=Schedule(kind="every", every_seconds=60),
+ )
+ base.update(over)
+ return CronJob(**base)
+
+
+def test_load_missing_file_returns_empty(tmp_path):
+ assert CronStore(tmp_path / "cron").load() == []
+
+
+def test_save_load_roundtrip(tmp_path):
+ store = CronStore(tmp_path / "cron")
+ job = _job()
+ job.state.next_run = "2026-06-10T13:00:00+00:00"
+ store.save([job])
+ loaded = store.load()
+ assert len(loaded) == 1
+ assert loaded[0].id == "j1"
+ assert loaded[0].schedule.every_seconds == 60
+ assert loaded[0].state.next_run == "2026-06-10T13:00:00+00:00"
+ assert loaded[0].enabled is True
+
+
+def test_save_is_atomic_no_tmp_left(tmp_path):
+ store = CronStore(tmp_path / "cron")
+ store.save([_job()])
+ leftovers = [p for p in (tmp_path / "cron").iterdir() if "tmp" in p.name]
+ assert leftovers == []
+
+
+def test_corrupt_file_is_renamed_and_load_returns_empty(tmp_path):
+ cron_dir = tmp_path / "cron"
+ cron_dir.mkdir(parents=True)
+ (cron_dir / "jobs.json").write_text("{not json")
+ store = CronStore(cron_dir)
+ assert store.load() == []
+ corrupted = list(cron_dir.glob("jobs.json.corrupt-*"))
+ assert len(corrupted) == 1
+ assert not (cron_dir / "jobs.json").exists()
+
+
+def test_mutate_persists_changes_under_lock(tmp_path):
+ store = CronStore(tmp_path / "cron")
+ store.save([_job("a"), _job("b")])
+
+ def disable_b(jobs):
+ for j in jobs:
+ if j.id == "b":
+ j.enabled = False
+
+ result = store.mutate(disable_b)
+ assert [j.enabled for j in result] == [True, False]
+ assert [j.enabled for j in store.load()] == [True, False]
+
+
+def test_unknown_fields_in_file_are_ignored(tmp_path):
+ # Forward compatibility: a newer writer must not crash an older reader.
+ cron_dir = tmp_path / "cron"
+ cron_dir.mkdir(parents=True)
+ payload = {
+ "version": 1,
+ "jobs": [
+ {
+ "id": "x",
+ "prompt": "p",
+ "schedule": {"kind": "every", "every_seconds": 5, "novel": 1},
+ "state": {"consecutive_errors": 0, "novel": 2},
+ "novel": 3,
+ }
+ ],
+ }
+ (cron_dir / "jobs.json").write_text(json.dumps(payload))
+ jobs = CronStore(cron_dir).load()
+ assert jobs[0].id == "x"