"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add scheduled research job data model and CRUD API (#272)
Matt Van Hornf3bdc3b9ad46
diff --git a/agent/api_server.py b/agent/api_server.pyindex f6d766205..17cddb116 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -3268,6 +3268,112 @@ from src.api.alpha_routes import register_alpha_routes # noqa: E402register_alpha_routes(app)+# ============================================================================+# Scheduled Research Routes+# ============================================================================+#+# Three lightweight CRUD endpoints backed by ScheduledResearchJobStore.+# Execution wiring is intentionally deferred: these endpoints only record+# and expose scheduled-research jobs; no run is triggered here.+++_scheduled_research_store: Optional["ScheduledResearchJobStore"] = None+++def _get_scheduled_research_store() -> "ScheduledResearchJobStore":+ """Return the singleton ScheduledResearchJobStore, creating it on first call."""+ global _scheduled_research_store+ if _scheduled_research_store is None:+ from src.scheduled_research.store import ScheduledResearchJobStore++ _scheduled_research_store = ScheduledResearchJobStore()+ return _scheduled_research_store+++class CreateScheduledRunRequest(BaseModel):+ """Request body for POST /scheduled-runs."""++ id: Optional[str] = Field(None, description="Job id; auto-generated UUID when omitted")+ prompt: str = Field(..., min_length=1, description="Research prompt or backtest description")+ schedule: str = Field(..., min_length=1, description="Interval-ms or 5-field cron expression")+ next_run_at: Optional[int] = Field(None, description="Epoch-ms for next run; defaults to now")+ config: Dict[str, Any] = Field(default_factory=dict, description="Optional backtest parameters")+++class ScheduledRunResponse(BaseModel):+ """API response for a single scheduled job."""++ id: str+ prompt: str+ schedule: str+ next_run_at: int+ status: str+ created_at: int+ config: Dict[str, Any] = Field(default_factory=dict)+++ "/scheduled-runs",+ response_model=ScheduledRunResponse,+ status_code=status.HTTP_201_CREATED,+ dependencies=[Depends(require_auth)],+)+async def create_scheduled_run(request: CreateScheduledRunRequest) -> ScheduledRunResponse:+ """Create (or replace) a scheduled research job.++ The job is persisted immediately. No execution is triggered.+ """+ import time++ from src.scheduled_research.models import JobStatus, ScheduledResearchJob+ from src.scheduled_research.models import validate_schedule++ try:+ validate_schedule(request.schedule)+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc++ now_ms = int(time.time() * 1000)+ job = ScheduledResearchJob(+ id=request.id or str(uuid.uuid4()),+ prompt=request.prompt,+ schedule=request.schedule,+ next_run_at=request.next_run_at if request.next_run_at is not None else now_ms,+ status=JobStatus.PENDING,+ created_at=now_ms,+ config=request.config,+ )+ _get_scheduled_research_store().upsert(job)+ return ScheduledRunResponse(**job.to_dict())+++ "/scheduled-runs",+ response_model=List[ScheduledRunResponse],+ dependencies=[Depends(require_auth)],+)+async def list_scheduled_runs(+ status_filter: Optional[str] = Query(None, alias="status"),+ limit: int = Query(50, ge=1, le=200),+) -> List[ScheduledRunResponse]:+ """List scheduled research jobs, optionally filtered by status."""+ jobs = _get_scheduled_research_store().list_jobs(status=status_filter, limit=limit)+ return [ScheduledRunResponse(**j.to_dict()) for j in jobs]+++ "/scheduled-runs/{job_id}",+ status_code=status.HTTP_204_NO_CONTENT,+ dependencies=[Depends(require_auth)],+)+async def delete_scheduled_run(job_id: str) -> None:+ """Cancel (delete) a scheduled research job by id."""+ _validate_path_param(job_id, "job_id")+ removed = _get_scheduled_research_store().delete(job_id)+ if not removed:+ raise HTTPException(status_code=404, detail=f"scheduled run {job_id} not found")++# ============================================================================# Main Entry Point# ============================================================================diff --git a/agent/src/scheduled_research/__init__.py b/agent/src/scheduled_research/__init__.pynew file mode 100644index 000000000..6b2de7a3b--- /dev/null+++ b/agent/src/scheduled_research/__init__.py@@ -0,0 +1,16 @@+"""Scheduled research job data model and durable store.++This package provides the data model (``ScheduledResearchJob``) and+crash-safe persistence (``ScheduledResearchJobStore``) for scheduled+research / backtest jobs. It intentionally does NOT wire execution --+recording and exposing jobs is the only responsibility here.+"""++from src.scheduled_research.models import JobStatus, ScheduledResearchJob+from src.scheduled_research.store import ScheduledResearchJobStore++__all__ = [+ "JobStatus",+ "ScheduledResearchJob",+ "ScheduledResearchJobStore",+]diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.pynew file mode 100644index 000000000..26baeafd5--- /dev/null+++ b/agent/src/scheduled_research/models.py@@ -0,0 +1,159 @@+"""Data model for scheduled research jobs.++A ``ScheduledResearchJob`` records everything needed to describe a deferred+research or backtest run: the prompt/query, when to run it, and an opaque+``config`` dict for future backtest parameters. Execution wiring is deferred+to a follow-up PR once the product shape is confirmed.+"""++from __future__ import annotations++import re+import time+from dataclasses import dataclass, field+from enum import Enum+from typing import Any, Dict++# ---------------------------------------------------------------------------+# Schedule validation+# ---------------------------------------------------------------------------++# Accept either:+# * a bare positive integer (interval in milliseconds), e.g. "60000"+# * a simplified cron expression with 5 fields, e.g. "0 */6 * * *"+# Fields: minute hour day-of-month month day-of-week+# Each field may be: number, *, or */n+_INTERVAL_MS_RE = re.compile(r"^[1-9][0-9]*$")+_CRON_FIELD_RE = re.compile(r"^(\*|\*/[1-9][0-9]*|[0-9]+)$")+_CRON_PARTS = 5+# Inclusive (low, high) bounds per cron field: minute hour day-of-month month+# day-of-week. A bare number and a ``*/n`` step are both validated against the+# field's high bound so out-of-range values (e.g. minute ``99``) are rejected.+_CRON_BOUNDS = ((0, 59), (0, 23), (1, 31), (1, 12), (0, 6))+++def validate_schedule(schedule: str) -> None:+ """Raise ``ValueError`` when *schedule* is malformed.++ Args:+ schedule: Either a positive integer string (interval-ms) or a+ simplified 5-field cron expression.++ Raises:+ ValueError: When the schedule does not match either accepted form.+ """+ if not schedule or not isinstance(schedule, str):+ raise ValueError("schedule must be a non-empty string")++ if _INTERVAL_MS_RE.fullmatch(schedule.strip()):+ return # valid interval++ parts = schedule.strip().split()+ if len(parts) != _CRON_PARTS:+ raise ValueError(f"schedule must be a positive integer (ms) or a 5-field cron string; got: {schedule!r}")+ for part, (low, high) in zip(parts, _CRON_BOUNDS):+ if not _CRON_FIELD_RE.fullmatch(part):+ raise ValueError(f"cron field {part!r} is not valid; each field must be *, */n, or a number")+ if part == "*":+ continue+ value = int(part[2:]) if part.startswith("*/") else int(part)+ if not low <= value <= high:+ raise ValueError(f"cron field {part!r} is out of range; expected {low}-{high}")+++# ---------------------------------------------------------------------------+# Status enum+# ---------------------------------------------------------------------------+++class JobStatus(str, Enum):+ """Lifecycle status of a scheduled research job."""++ PENDING = "pending"+ RUNNING = "running"+ COMPLETED = "completed"+ FAILED = "failed"+ CANCELLED = "cancelled"+++# ---------------------------------------------------------------------------+# Data model+# ---------------------------------------------------------------------------+++@dataclass+class ScheduledResearchJob:+ """Immutable record describing a scheduled research / backtest job.++ Attributes:+ id: Unique job identifier (caller-supplied UUID or slug).+ prompt: Research prompt or backtest description.+ schedule: Interval-ms string or 5-field cron expression.+ next_run_at: Epoch-millisecond timestamp for the next intended+ execution. Defaults to the current time when the job is created.+ status: Current lifecycle status.+ created_at: Epoch-millisecond timestamp of job creation.+ config: Opaque dict for future backtest parameters.+ """++ id: str+ prompt: str+ schedule: str+ next_run_at: int = field(default_factory=lambda: int(time.time() * 1000))+ status: JobStatus = JobStatus.PENDING+ created_at: int = field(default_factory=lambda: int(time.time() * 1000))+ config: Dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> Dict[str, Any]:+ """Serialize to a plain JSON-serializable dict.++ Returns:+ A dict containing all job fields, with ``status`` as its string+ value.+ """+ return {+ "id": self.id,+ "prompt": self.prompt,+ "schedule": self.schedule,+ "next_run_at": self.next_run_at,+ "status": self.status.value,+ "created_at": self.created_at,+ "config": self.config,+ }++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "ScheduledResearchJob":+ """Reconstruct a job from a plain dict.++ Args:+ data: A raw dict as produced by :meth:`to_dict`.++ Returns:+ The reconstructed ``ScheduledResearchJob``.++ Raises:+ KeyError: If a required field is missing.+ TypeError: If a field has the wrong type.+ ValueError: If ``status`` is not a recognized ``JobStatus`` value.+ """+ job_id = data["id"]+ prompt = data["prompt"]+ schedule = data["schedule"]+ if not isinstance(job_id, str) or not isinstance(prompt, str) or not isinstance(schedule, str):+ raise TypeError("'id', 'prompt', and 'schedule' must be strings")+ next_run_at = data["next_run_at"]+ created_at = data["created_at"]+ if not isinstance(next_run_at, int) or not isinstance(created_at, int):+ raise TypeError("'next_run_at' and 'created_at' must be integers (epoch ms)")+ status = JobStatus(data["status"])+ raw_config = data.get("config")+ config: Dict[str, Any] = raw_config if isinstance(raw_config, dict) else {}+ return cls(+ id=job_id,+ prompt=prompt,+ schedule=schedule,+ next_run_at=next_run_at,+ status=status,+ created_at=created_at,+ config=config,+ )diff --git a/agent/src/scheduled_research/store.py b/agent/src/scheduled_research/store.pynew file mode 100644index 000000000..4b13a749c--- /dev/null+++ b/agent/src/scheduled_research/store.py@@ -0,0 +1,258 @@+"""Crash-safe store for scheduled research jobs.++Uses the same atomic write pattern as ``src.live.runtime.jobstore`` (write a+temp file in the same directory, fsync, replace, fsync the parent dir) so the+store survives a SIGKILL at any point without corruption.++A missing store file is the only clean empty result. A file that exists but+fails to parse is quarantined and ``load`` raises ``CorruptStoreError`` instead+of silently returning an empty list.+"""++from __future__ import annotations++import json+import logging+import os+from datetime import datetime, timezone+from pathlib import Path+from typing import Dict, List, Optional++from src.config.paths import get_runtime_root+from src.scheduled_research.models import ScheduledResearchJob, validate_schedule++logger = logging.getLogger(__name__)++_STORE_FILENAME = "scheduled_research_jobs.json"+_SCHEMA_VERSION = 1+++def _default_store_path() -> Path:+ """Return the default path for the scheduled-research store.++ Roots job state under the user runtime dir (``~/.vibe-trading`` by+ default), never inside the repo working tree — the same root the live+ runtime, swarm config, and persistent memory resolve via+ :func:`src.config.paths.get_runtime_root`.+ """+ return get_runtime_root() / "scheduled_research" / _STORE_FILENAME+++class CorruptStoreError(RuntimeError):+ """Raised when the store exists but cannot be parsed.++ The corrupt file is renamed aside (quarantined) before this is raised.++ Attributes:+ original: Path that failed to parse.+ quarantined: Path the corrupt file was moved to.+ cause: Short description of the parse failure.+ """++ def __init__(self, original: Path, quarantined: Path, cause: str) -> None:+ super().__init__(f"scheduled-research store {original} is corrupt ({cause}); quarantined to {quarantined}")+ self.original = original+ self.quarantined = quarantined+ self.cause = cause+++class ScheduledResearchJobStore:+ """Durable, crash-safe persistence for scheduled research jobs.++ The store is a thin envelope around a dict of+ :class:`~src.scheduled_research.models.ScheduledResearchJob` keyed by+ job id. It owns only serialization and atomic I/O; scheduling decisions+ live elsewhere.++ Attributes:+ path: Absolute path of the backing JSON file.+ """++ def __init__(self, path: Optional[Path] = None) -> None:+ """Initialize the store.++ Args:+ path: Explicit path. Defaults to+ ``agent/data/scheduled_research_jobs.json``.+ """+ self.path: Path = path if path is not None else _default_store_path()++ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------++ def load(self) -> Dict[str, ScheduledResearchJob]:+ """Load all persisted jobs.++ Returns:+ A dict mapping job id to job. Empty when the store has never been+ written.++ Raises:+ CorruptStoreError: When the file exists but cannot be parsed.+ """+ if not self.path.exists():+ return {}+ try:+ raw = self.path.read_text(encoding="utf-8")+ envelope = json.loads(raw)+ jobs_raw = self._extract_jobs(envelope)+ result: Dict[str, ScheduledResearchJob] = {}+ for item in jobs_raw:+ job = ScheduledResearchJob.from_dict(item)+ result[job.id] = job+ return result+ except (OSError, ValueError, KeyError, TypeError) as exc:+ quarantined = self._quarantine(str(exc))+ raise CorruptStoreError(self.path, quarantined, str(exc)) from exc++ def save(self, jobs: Dict[str, ScheduledResearchJob]) -> None:+ """Atomically persist the full job set.++ Write sequence: temp file in same dir -> fsync -> os.replace -> fsync+ parent dir. A SIGKILL at any step leaves either the old complete store+ or the new one, never a partial write.++ Args:+ jobs: Mapping of job id to job (the full set, not a delta).++ Raises:+ OSError: When the directory cannot be created or the write fails.+ """+ target = self.path+ target.parent.mkdir(parents=True, exist_ok=True)+ payload = json.dumps(self._envelope(jobs), ensure_ascii=False, indent=2)++ tmp = target.with_name(f".{target.name}.{os.getpid()}.tmp")+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ try:+ os.write(fd, payload.encode("utf-8"))+ os.fsync(fd)+ finally:+ os.close(fd)++ os.replace(tmp, target)+ self._fsync_dir(target.parent)++ def upsert(self, job: ScheduledResearchJob) -> None:+ """Insert or replace a job by id.++ Validates the schedule string before persisting.++ Args:+ job: The job to store.++ Raises:+ ValueError: When ``job.schedule`` is malformed.+ CorruptStoreError: When the existing store cannot be parsed.+ """+ validate_schedule(job.schedule)+ jobs = self.load()+ jobs[job.id] = job+ self.save(jobs)++ def get(self, job_id: str) -> Optional[ScheduledResearchJob]:+ """Return a job by id, or ``None`` when it does not exist.++ Args:+ job_id: Job identifier.++ Returns:+ The matching job or ``None``.+ """+ return self.load().get(job_id)++ def list_jobs(+ self,+ status: Optional[str] = None,+ limit: int = 50,+ ) -> List[ScheduledResearchJob]:+ """Return jobs, optionally filtered by status.++ Args:+ status: When provided, include only jobs whose status matches this+ string (e.g. ``"pending"``).+ limit: Maximum number of jobs to return (newest first by+ ``created_at``).++ Returns:+ A list of at most *limit* jobs sorted descending by ``created_at``.+ """+ jobs = list(self.load().values())+ if status is not None:+ jobs = [j for j in jobs if j.status.value == status]+ jobs.sort(key=lambda j: j.created_at, reverse=True)+ return jobs[:limit]++ def delete(self, job_id: str) -> bool:+ """Remove a job by id.++ Args:+ job_id: Identifier of the job to remove.++ Returns:+ ``True`` when the job was found and removed; ``False`` when it was+ not in the store.+ """+ jobs = self.load()+ if job_id not in jobs:+ return False+ del jobs[job_id]+ self.save(jobs)+ return True++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ def _quarantine(self, cause: str) -> Path:+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")+ quarantined = self.path.with_name(f"{self.path.name}.corrupt-{ts}")+ try:+ os.replace(self.path, quarantined)+ logger.error(+ "scheduled-research store %s corrupt (%s) — quarantined to %s",+ self.path,+ cause,+ quarantined,+ )+ except OSError:+ logger.error(+ "scheduled-research store %s corrupt (%s) — quarantine rename failed",+ self.path,+ cause,+ exc_info=True,+ )+ return self.path+ return quarantined++ @staticmethod+ def _fsync_dir(directory: Path) -> None:+ try:+ dir_fd = os.open(directory, os.O_RDONLY)+ except OSError:+ return+ try:+ os.fsync(dir_fd)+ except OSError:+ logger.debug("parent-dir fsync unsupported on %s", directory, exc_info=True)+ finally:+ os.close(dir_fd)++ @staticmethod+ def _envelope(jobs: Dict[str, ScheduledResearchJob]) -> dict:+ return {+ "schema_version": _SCHEMA_VERSION,+ "jobs": [j.to_dict() for j in jobs.values()],+ }++ @staticmethod+ def _extract_jobs(envelope: object) -> List[dict]:+ if not isinstance(envelope, dict):+ raise ValueError("store root is not a JSON object")+ jobs = envelope.get("jobs")+ if not isinstance(jobs, list):+ raise ValueError("store 'jobs' is missing or not a list")+ if not all(isinstance(item, dict) for item in jobs):+ raise ValueError("store 'jobs' contains a non-object entry")+ return jobsdiff --git a/agent/tests/test_scheduled_research_store.py b/agent/tests/test_scheduled_research_store.pynew file mode 100644index 000000000..7cac6b976--- /dev/null+++ b/agent/tests/test_scheduled_research_store.py@@ -0,0 +1,231 @@+"""Tests for the scheduled research job store.++Covers: happy-path CRUD, atomic persistence, invalid schedule rejection,+idempotent upsert, and empty-store behaviour.+"""++from __future__ import annotations++import time+from pathlib import Path++import pytest++from src.scheduled_research.models import JobStatus, ScheduledResearchJob, validate_schedule+from src.scheduled_research.store import CorruptStoreError, ScheduledResearchJobStore+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_job(+ job_id: str = "job-001",+ prompt: str = "analyse AAPL momentum",+ schedule: str = "60000",+) -> ScheduledResearchJob:+ now = int(time.time() * 1000)+ return ScheduledResearchJob(+ id=job_id,+ prompt=prompt,+ schedule=schedule,+ next_run_at=now + 60_000,+ status=JobStatus.PENDING,+ created_at=now,+ )+++# ---------------------------------------------------------------------------+# validate_schedule unit tests+# ---------------------------------------------------------------------------+++class TestValidateSchedule:+ def test_accepts_interval_ms(self) -> None:+ validate_schedule("60000")++ def test_accepts_cron_string(self) -> None:+ validate_schedule("0 */6 * * *")++ def test_accepts_cron_with_plain_numbers(self) -> None:+ validate_schedule("30 8 * * 1")++ def test_rejects_empty_string(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("")++ def test_rejects_zero_interval(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("0")++ def test_rejects_negative_interval(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("-1000")++ def test_rejects_malformed_cron(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("* * * *") # only 4 fields++ def test_rejects_non_numeric_cron_field(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("abc * * * *")++ def test_rejects_cron_with_invalid_step(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("*/0 * * * *") # step of 0 is not allowed++ def test_rejects_out_of_range_minute(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("99 * * * *") # minute > 59++ def test_rejects_out_of_range_hour(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("0 25 * * *") # hour > 23++ def test_rejects_zero_day_of_month(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("0 0 0 * *") # day-of-month is 1-31++ def test_rejects_out_of_range_step(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("*/99 * * * *") # minute step > 59++ def test_accepts_boundary_values(self) -> None:+ validate_schedule("59 23 31 12 6") # all field maxima+++# ---------------------------------------------------------------------------+# Store CRUD tests+# ---------------------------------------------------------------------------+++class TestScheduledResearchJobStore:+ def test_empty_store_returns_empty_list(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ assert store.list_jobs() == []++ def test_load_missing_file_returns_empty_dict(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ assert store.load() == {}++ def test_upsert_then_list(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job()+ store.upsert(job)+ result = store.list_jobs()+ assert len(result) == 1+ assert result[0].id == job.id+ assert result[0].status == JobStatus.PENDING++ def test_get_returns_job(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job()+ store.upsert(job)+ fetched = store.get(job.id)+ assert fetched is not None+ assert fetched.id == job.id+ assert fetched.prompt == job.prompt++ def test_get_missing_returns_none(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ assert store.get("nonexistent") is None++ def test_delete_removes_job(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job()+ store.upsert(job)+ removed = store.delete(job.id)+ assert removed is True+ assert store.get(job.id) is None++ def test_delete_missing_returns_false(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ assert store.delete("ghost") is False++ def test_idempotent_upsert_replaces_not_duplicates(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job()+ store.upsert(job)+ updated = ScheduledResearchJob(+ id=job.id,+ prompt="updated prompt",+ schedule=job.schedule,+ next_run_at=job.next_run_at,+ status=JobStatus.COMPLETED,+ created_at=job.created_at,+ )+ store.upsert(updated)+ jobs = store.list_jobs()+ assert len(jobs) == 1+ assert jobs[0].prompt == "updated prompt"+ assert jobs[0].status == JobStatus.COMPLETED++ def test_filter_by_status(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ pending = _make_job("p1")+ completed = ScheduledResearchJob(+ id="c1",+ prompt="done",+ schedule="60000",+ status=JobStatus.COMPLETED,+ next_run_at=int(time.time() * 1000),+ created_at=int(time.time() * 1000),+ )+ store.upsert(pending)+ store.upsert(completed)+ pending_only = store.list_jobs(status="pending")+ assert len(pending_only) == 1+ assert pending_only[0].id == "p1"++ def test_list_honours_limit(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ for i in range(5):+ store.upsert(_make_job(f"job-{i:03d}"))+ assert len(store.list_jobs(limit=3)) == 3++ def test_upsert_rejects_malformed_schedule(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ bad_job = ScheduledResearchJob(+ id="bad",+ prompt="x",+ schedule="not-a-schedule",+ next_run_at=int(time.time() * 1000),+ created_at=int(time.time() * 1000),+ )+ with pytest.raises(ValueError):+ store.upsert(bad_job)++ def test_corrupt_store_raises_and_quarantines(self, tmp_path: Path) -> None:+ store_path = tmp_path / "jobs.json"+ store_path.write_text("{{not valid json}}", encoding="utf-8")+ store = ScheduledResearchJobStore(path=store_path)+ with pytest.raises(CorruptStoreError) as exc_info:+ store.load()+ assert not store_path.exists(), "original corrupt file should be gone"+ assert exc_info.value.quarantined.exists(), "quarantined file must exist"++ def test_atomic_write_cleans_up_temp_on_success(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ store.upsert(_make_job())+ # Verify no leftover .tmp files after a successful write+ tmp_files = list(tmp_path.glob("*.tmp"))+ assert tmp_files == [], f"unexpected temp files: {tmp_files}"++ def test_persisted_data_round_trips(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job("rt-001", schedule="0 */4 * * *")+ store.upsert(job)++ # Open a fresh store instance to simulate restart+ store2 = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ fetched = store2.get("rt-001")+ assert fetched is not None+ assert fetched.prompt == job.prompt+ assert fetched.schedule == "0 */4 * * *"++ def test_cron_schedule_accepted(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ cron_job = _make_job("cron-1", schedule="*/30 * * * *")+ store.upsert(cron_job)+ assert store.get("cron-1") is not None