Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(scheduling): add protected system job definitions and registration

shadowinlife3ac55e68d0da
diff --git a/agent/src/scheduling/__init__.py b/agent/src/scheduling/__init__.py
index 4e4475caf..4f7d75774 100644
--- a/agent/src/scheduling/__init__.py
+++ b/agent/src/scheduling/__init__.py
@@ -19,8 +19,13 @@ in the repo can adopt:
sync/async callables, with exact-key resolution only (no dynamic import,
no string parsing, no shell).
-Later todos of the scheduler-unification plan add ``system_jobs.py``
-(protected system jobs) beside these modules.
+* :mod:`src.scheduling.system_jobs` — protected system jobs: the
+ ``SystemJobSpec`` surface (``system:`` id prefix, ``source_type="system"``,
+ ``executor_kind="internal"``, registry-key callable, per-spec enablement
+ predicate) and ``ensure_system_jobs`` — the idempotent startup
+ seed/repair pass (tamper correction, (α) status reset, (β) schedule-trust
+ boundary, repair-replay, flag-off halt) called from the lifespan before
+ the executor starts.
"""
from src.scheduling.kernel import (
@@ -71,6 +76,8 @@ from src.scheduling.types import (
__all__ = [
"CRON_BOUNDS",
+ "EnabledPredicate",
+ "EnsureSystemJobsReport",
"CRON_SEARCH_LIMIT_DAYS",
"DEFAULT_MAX_CONSECUTIVE_FAILURES",
"DEFAULT_RETRY_BASE_DELAY_MS",
@@ -89,10 +96,15 @@ __all__ = [
"JobLike",
"NowFn",
"OnTickFn",
+ "SYSTEM_JOB_ID_PREFIX",
"SchedulerKernel",
+ "SpecGate",
+ "SystemJobSpec",
"TriggerSpec",
"day_matches",
+ "ensure_system_jobs",
"is_executor_kind",
+ "is_system_job_id",
"is_interval_schedule",
"is_registered",
"list_internal",
@@ -103,8 +115,40 @@ __all__ = [
"parse_cron_field",
"register_internal",
"resolve_internal",
+ "system_job_specs",
"trigger_interval_ms",
"validate_schedule",
"validate_timezone",
"validate_timezone_shape",
]
+
+# --- lazy re-export: src.scheduling.system_jobs (PEP 562) -------------------
+# system_jobs imports src.scheduled_research.models/store, and models itself
+# imports src.scheduling.triggers — an eager import here would make that
+# re-enter this partially initialized __init__ (circular ImportError) whenever
+# src.scheduled_research is imported before src.scheduling. Deferring the
+# import to first attribute access keeps the export surface identical
+# (``from src.scheduling import ensure_system_jobs`` and friends all work)
+# while breaking the import-time cycle in every import order.
+_SYSTEM_JOBS_EXPORTS = frozenset(
+ {
+ "SYSTEM_JOB_ID_PREFIX",
+ "EnabledPredicate",
+ "EnsureSystemJobsReport",
+ "SpecGate",
+ "SystemJobSpec",
+ "ensure_system_jobs",
+ "is_system_job_id",
+ "system_job_specs",
+ }
+)
+
+
+def __getattr__(name: str):
+ """Lazily resolve the system-jobs exports (see the comment above)."""
+ if name in _SYSTEM_JOBS_EXPORTS:
+ from src.scheduling import system_jobs
+
+ return getattr(system_jobs, name)
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
diff --git a/agent/src/scheduling/system_jobs.py b/agent/src/scheduling/system_jobs.py
new file mode 100644
index 000000000..ae0e6104c
--- /dev/null
+++ b/agent/src/scheduling/system_jobs.py
@@ -0,0 +1,398 @@
+"""Protected system jobs: definitions and idempotent registration (T6).
+
+A *system job* is a built-in scheduled task the product owns end to end: its
+row in the scheduled-research store is seeded and repaired by this module at
+startup, it executes an in-process callable through the registry allowlist
+(:mod:`src.scheduling.registry`) — never a prompt dispatch — and, once T7
+lands its route/proposal/CLI guards, users cannot delete, rewrite or forge it
+through any API surface.
+
+Contracts implemented here (scheduler-unification plan todo 6, ③b):
+
+* **(i) Timing** — :func:`ensure_system_jobs` is called from the ``api_server``
+ lifespan startup BEFORE the executor's ``start()`` (T12 wires the call), so
+ every enabled system job is in the store before the first tick can run.
+* **(ii) Idempotence** — an existing row is never re-seeded: runtime fields
+ (``next_run_at`` / ``last_run_at`` / ``consecutive_failures`` /
+ ``last_error`` / ``failure_kind`` / ``created_at`` / ``config`` / ``title`` /
+ ``prompt`` / every ``delivery*`` field) and a live status (PENDING /
+ RUNNING / COMPLETED) are left exactly as they are; tampered spec-owned
+ fields ``source_type`` / ``executor_kind`` / ``internal_callable`` ARE
+ corrected back to the spec.
+* **(ii-c) schedule trust boundary — plan choice (β), local trust** — a
+ syntactically VALID user-edited ``schedule``/``timezone`` is LEFT ALONE:
+ whoever can edit the store file could equally flip the env flags off, so
+ local file tampering is not treated as a security boundary (same reasoning
+ as the documented win32 no-lock limitation). An INVALID schedule/timezone,
+ however, IS repaired to the spec default: repair writes go through
+ ``store.upsert(job, validate=False)`` (plan (ii-b)), which would otherwise
+ persist garbage the executor could only mark FAILED
+ (``failure_kind="schedule"``) — repairing keeps the "protected" claim
+ functional rather than merely nominal.
+* **(α) status reset** — a system row found in CANCELLED or EXPIRED is reset
+ to PENDING with ``end_at`` cleared. WHY this is safe: after T7, no API path
+ (REST DELETE/PATCH, proposals, playbook/CLI creation) can put a system job
+ into those states, so they can only originate from a manual store-file edit
+ (or from this module's own flag-off halt below) — resetting makes
+ "protected" true at the local-file layer too. An enabled row's ``end_at`` is
+ cleared even while PENDING: specs define no end boundary, and a manually
+ added future ``end_at`` would otherwise be honoured by
+ ``_expire_elapsed_jobs`` mid-life — the same tamper class α addresses.
+ (For CHANGELOG/T13: manual cancellation of a system job via file edit is
+ undone at the next startup.)
+* **(ii-b) repair writes** — every repair/halt write uses
+ ``store.upsert(job, validate=False)`` so a tampered row can never crash
+ startup; the fix is "correct + log", mirroring the executor's lifecycle-write
+ convention (``store.py`` upsert docstring).
+* **(iii) repair-replay** — a system job deleted from the store by hand is
+ re-seeded at the next startup, else "protected" would be vacuous.
+* **(iv) DOUBLE-gate enablement chain** — a system job actually executes only
+ when BOTH gates hold: the scheduler master switch
+ ``VIBE_TRADING_ENABLE_SCHEDULER`` (without it the executor never starts —
+ ``scheduled_routes`` early-return) AND the job's own flag, expressed here as
+ the spec's ``enabled_predicate`` (T8/T9 supply predicates reading the env
+ flags they declare; THIS MODULE READS NO ENVIRONMENT ITSELF — predicates are
+ injected, keeping the env surface owned by T8/T9 and the AST gate clean).
+ To make the chain true in the flag-off direction too, a DISABLED spec whose
+ row already exists (flag was on, then turned off) is halted: a runnable
+ status (PENDING/RUNNING/COMPLETED) becomes CANCELLED so the executor's
+ never-due set excludes it; terminal statuses are left untouched. Re-enabling
+ the flag undoes the halt through the (α) reset above. A disabled spec with
+ NO row writes nothing at all (plan QA (a)).
+* **Registry independence** — seeding does NOT require ``internal_callable``
+ to be registered (the registry dict is empty until T8/T9 append their
+ callables). A seeded job whose callable is unregistered fails at EXECUTION
+ time in the supervisor's resolve step, recorded as ``failure_kind="dispatch"``
+ with a readable ``last_error`` (plan QA (c)) — never silently skipped, never
+ prompt-dispatched.
+
+ID convention for T7: every system job id starts with ``system:`` — the
+colon is deliberately part of the convention because ``_SAFE_JOB_ID_RE``
+(``^[A-Za-z0-9_-]{1,128}$``, enforced on POST/playbook routes and in
+``_validate_path_param``) rejects ``:``, so forging or path-addressing a
+system id through those surfaces is structurally impossible.
+:func:`is_system_job_id` is the single prefix predicate T7's guards consume.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from dataclasses import dataclass, field
+from typing import Callable, Optional, Sequence
+
+from src.scheduled_research.models import (
+ JobStatus,
+ ScheduledResearchJob,
+ validate_schedule,
+ validate_timezone_shape,
+)
+from src.scheduled_research.store import ScheduledResearchJobStore
+from src.scheduling.triggers import is_interval_schedule, next_due
+
+logger = logging.getLogger(__name__)
+
+#: Mandatory id prefix. Contains ``:`` on purpose — see the ID-convention
+#: note in the module docstring (T7 relies on ``_SAFE_JOB_ID_RE`` rejecting
+#: every id that carries this prefix).
+SYSTEM_JOB_ID_PREFIX = "system:"
+
+#: Per-spec enablement gate (T8/T9 bind these to the env flags they declare).
+EnabledPredicate = Callable[[], bool]
+#: Caller-level override gate used by :func:`ensure_system_jobs`'s
+#: ``enabled_predicate`` parameter; receives the spec, returns enablement.
+SpecGate = Callable[["SystemJobSpec"], bool]
+#: Injectable wall clock returning epoch milliseconds.
+NowFn = Callable[[], int]
+
+#: Statuses that keep a row executable by the tick loop (``is_due``'s
+#: complement of the never-due set); a disabled spec halts exactly these.
+_RUNNABLE_STATUSES = frozenset({JobStatus.PENDING, JobStatus.RUNNING, JobStatus.COMPLETED})
+#: Statuses only reachable (post-T7) via manual file edits or this module's
+#: own flag-off halt; (α) resets them when the spec is enabled again.
+_TAMPER_TERMINAL_STATUSES = frozenset({JobStatus.CANCELLED, JobStatus.EXPIRED})
+
+
+def _always_enabled() -> bool:
+ """Default spec gate: enabled. T8/T9 replace it with env-flag readers."""
+ return True
+
+
+def _now_ms() -> int:
+ """Return current wall-clock time in epoch milliseconds."""
+ return int(time.time() * 1000)
+
+
+@dataclass(frozen=True)
+class SystemJobSpec:
+ """Declarative definition of one protected system job.
+
+ Attributes:
+ id: Stable, predictable job id; MUST start with
+ :data:`SYSTEM_JOB_ID_PREFIX` (the ``system:`` prefix convention
+ T7's guards and ``_SAFE_JOB_ID_RE`` interplay depend on).
+ schedule: Default schedule (interval-ms string or 5-field cron).
+ Seeded verbatim; on an existing row a VALID edited schedule is
+ trusted (β) and only an INVALID one is repaired back to this.
+ internal_callable: Registry KEY name (never an import path) resolved
+ through :mod:`src.scheduling.registry` at execution time.
+ title: Human-readable label seeded with the row.
+ timezone: IANA key for cron schedules, ``None`` for UTC/interval.
+ prompt: Always ``""`` — internal/system jobs carry no prompt
+ (plan ③b(i); ``from_dict`` accepts ``source_type="system"`` with
+ an empty prompt since T3).
+ source_type: Fixed ``"system"``.
+ executor_kind: Fixed ``"internal"``.
+ enabled_predicate: Zero-arg callable deciding the spec's own gate —
+ the second half of the double-gate chain (module docstring (iv)).
+ This dataclass never reads the environment itself.
+ """
+
+ id: str
+ schedule: str
+ internal_callable: str
+ title: str = ""
+ timezone: Optional[str] = None
+ prompt: str = ""
+ source_type: str = "system"
+ executor_kind: str = "internal"
+ enabled_predicate: EnabledPredicate = field(default=_always_enabled)
+
+ def __post_init__(self) -> None:
+ """Fail fast on spec-authoring bugs (T8/T9 append specs by hand)."""
+ if not isinstance(self.id, str) or not self.id.startswith(SYSTEM_JOB_ID_PREFIX):
+ raise ValueError(f"system job id {self.id!r} must start with {SYSTEM_JOB_ID_PREFIX!r}")
+ if len(self.id) <= len(SYSTEM_JOB_ID_PREFIX):
+ raise ValueError(f"system job id {self.id!r} needs a name after the prefix")
+ if self.source_type != "system":
+ raise ValueError(f"system job spec {self.id!r} must keep source_type='system'")
+ if self.executor_kind != "internal":
+ raise ValueError(f"system job spec {self.id!r} must keep executor_kind='internal'")
+ if not self.internal_callable:
+ raise ValueError(f"system job spec {self.id!r} requires an internal_callable registry key")
+ if not callable(self.enabled_predicate):
+ raise TypeError(f"system job spec {self.id!r} requires a callable enabled_predicate")
+ # Spec-owned defaults must be valid at authoring time; seeding uses
+ # validate=True so a bad spec surfaces in CI, never at a user startup.
+ validate_schedule(self.schedule)
+ validate_timezone_shape(self.timezone)
+
+
+# ---------------------------------------------------------------------------
+# Production spec surface
+# ---------------------------------------------------------------------------
+
+#: The production specs. EMPTY by design in T6 — the framework ships first;
+#: T8 (memory consolidation) and T9 (br_data sync) each append ONE literal
+#: here plus ONE registry entry in ``registry.py``'s ``_INTERNAL_CALLABLES``
+#: block, e.g.:
+#:
+#: SystemJobSpec(
+#: id="system:memory-consolidation",
+#: schedule="0 3 * * *",
+#: timezone="UTC",
+#: internal_callable="memory.consolidate",
+#: title="Memory consolidation",
+#: enabled_predicate=_memory_consolidation_enabled, # reads T8's flag
+#: ),
+#:
+#: Nothing else changes: ensure_system_jobs, the guards (T7) and the lifespan
+#: wiring (T12) all consume this tuple generically.
+_SYSTEM_JOB_SPECS: tuple[SystemJobSpec, ...] = ()
+
+
+def system_job_specs() -> tuple[SystemJobSpec, ...]:
+ """Return every declared production system-job spec (immutable tuple)."""
+ return _SYSTEM_JOB_SPECS
+
+
+def is_system_job_id(job_id: object) -> bool:
+ """Whether *job_id* carries the protected ``system:`` prefix.
+
+ The single predicate T7's route/proposal/CLI guards consume. Pure prefix
+ convention — never raises, non-strings are ``False``. Note the prefix
+ contains ``:``, which ``_SAFE_JOB_ID_RE`` rejects, so a user-facing
+ create path can never mint an id this function returns ``True`` for.
+ """
+ return isinstance(job_id, str) and job_id.startswith(SYSTEM_JOB_ID_PREFIX)
+
+
+@dataclass(frozen=True)
+class EnsureSystemJobsReport:
+ """Per-outcome id lists from one :func:`ensure_system_jobs` pass.
+
+ ``seeded``: missing rows created (enabled specs; repair-replay (iii) lands
+ here too). ``repaired``: enabled rows rewritten (tamper correction,
+ invalid-schedule repair, (α) reset, ``end_at`` clearing). ``unchanged``:
+ conformant enabled rows, NOT written. ``skipped_disabled``: disabled specs
+ with no row — nothing written. ``halted``: disabled specs with an existing
+ row (made non-runnable/corrected, or already terminal, no write needed).
+ """
+
+ seeded: tuple[str, ...] = ()
+ repaired: tuple[str, ...] = ()
+ unchanged: tuple[str, ...] = ()
+ skipped_disabled: tuple[str, ...] = ()
+ halted: tuple[str, ...] = ()
+
+
+def _seed_job(spec: SystemJobSpec, now_ms: int) -> ScheduledResearchJob:
+ """Build a fresh row for *spec* (mirrors ``build_job_from_draft``'s next-run
+ convention: cron-with-tz waits for its next slot; interval/UTC-cron due now)."""
+ next_run_at = now_ms
+ if spec.timezone is not None and not is_interval_schedule(spec.schedule):
+ next_run_at = next_due(spec.schedule, now_ms, spec.timezone)
+ return ScheduledResearchJob(
+ id=spec.id,
+ prompt=spec.prompt,
+ schedule=spec.schedule,
+ title=spec.title,
+ source_type=spec.source_type,
+ executor_kind=spec.executor_kind,
+ internal_callable=spec.internal_callable,
+ timezone=spec.timezone,
+ next_run_at=next_run_at,
+ created_at=now_ms,
+ status=JobStatus.PENDING,
+ )
+
+
+def _schedule_shape_ok(schedule: str, timezone: Optional[str]) -> bool:
+ """Whether *schedule*/*timezone* pass the store's syntactic validation —
+ exactly the check ``store.upsert(validate=True)`` applies, so the (β)
+ boundary uses the system-wide grammar: valid-but-different is trusted
+ local editing; invalid is garbage a ``validate=False`` write must not keep.
+ """
+ try:
+ validate_schedule(schedule)
+ validate_timezone_shape(timezone)
+ except ValueError:
+ return False
+ return True
+
+
+def _reconcile(job: ScheduledResearchJob, spec: SystemJobSpec, *, enabled: bool) -> list[str]:
+ """Mutate *job* toward *spec* in place; return human-readable change notes.
+
+ Touches ONLY spec-owned fields (source_type / executor_kind /
+ internal_callable, invalid schedule/timezone, the (α) status reset,
+ ``end_at``, and the flag-off halt). Runtime fields — next_run_at,
+ last_run_at, consecutive_failures, last_error, failure_kind, created_at,
+ config, title, prompt, delivery* — are never modified here.
+ """
+ notes: list[str] = []
+ if job.source_type != spec.source_type:
+ notes.append(f"source_type {job.source_type!r} -> {spec.source_type!r}")
+ job.source_type = spec.source_type
+ if job.executor_kind != spec.executor_kind:
+ notes.append(f"executor_kind {job.executor_kind!r} -> {spec.executor_kind!r}")
+ job.executor_kind = spec.executor_kind
+ if job.internal_callable != spec.internal_callable:
+ notes.append(f"internal_callable {job.internal_callable!r} -> {spec.internal_callable!r}")
+ job.internal_callable = spec.internal_callable
+ # (ii-c)/(β): a VALID edited schedule/timezone is trusted and left alone;
+ # an INVALID one is repaired to the spec default because the repair write
+ # below uses validate=False and would otherwise persist garbage.
+ if not _schedule_shape_ok(job.schedule, job.timezone):
+ notes.append(
+ f"invalid schedule/timezone ({job.schedule!r}, {job.timezone!r}) "
+ f"-> spec default ({spec.schedule!r}, {spec.timezone!r})"
+ )
+ job.schedule = spec.schedule
+ job.timezone = spec.timezone
+ if enabled:
+ # (α): post-T7 these statuses can only come from manual file edits (or
+ # our own flag-off halt), so resetting them is safe and keeps the
+ # "protected" claim true at the local-file layer.
+ if job.status in _TAMPER_TERMINAL_STATUSES:
+ notes.append(f"status {job.status.value!r} -> 'pending' (alpha reset), end_at cleared")
+ job.status = JobStatus.PENDING
+ job.end_at = None
+ elif job.end_at is not None:
+ # Specs define no end boundary; a hand-added future end_at would
+ # silently expire the job mid-life (same tamper class as alpha).
+ notes.append(f"end_at {job.end_at} -> None (system jobs do not expire)")
+ job.end_at = None
+ elif job.status in _RUNNABLE_STATUSES:
+ # (iv) enablement chain, flag-off direction: the row must not keep
+ # firing after its flag was turned off. CANCELLED is terminal in
+ # is_due, non-destructive (runtime fields preserved) and undone by
+ # the (alpha) reset when the flag comes back on.
+ notes.append(f"status {job.status.value!r} -> 'cancelled' (spec flag disabled)")
+ job.status = JobStatus.CANCELLED
+ return notes
+
+
+def ensure_system_jobs(
+ store: ScheduledResearchJobStore,
+ *,
+ enabled_predicate: Optional[SpecGate] = None,
+ specs: Optional[Sequence[SystemJobSpec]] = None,
+ now_fn: Optional[NowFn] = None,
+) -> EnsureSystemJobsReport:
+ """Seed/repair every enabled system job into *store* (idempotent).
+
+ Call at lifespan startup BEFORE ``executor.start()`` (contract (i), T12
+ wires it). Running it twice changes nothing the second time: conformant
+ rows are not rewritten at all, so runtime state and store bytes survive.
+
+ Args:
+ store: The scheduled-research job store to reconcile against.
+ enabled_predicate: Optional caller-level gate override receiving each
+ spec; production (T12) passes nothing so each spec's own
+ ``enabled_predicate`` decides (the double-gate chain (iv) — the
+ scheduler master switch still gates execution itself). Primarily
+ an injection seam for tests and uniform external gating.
+ specs: Optional explicit spec sequence; defaults to
+ :func:`system_job_specs`. Tests inject framework specs here while
+ the production tuple stays empty until T8/T9 append to it.
+ now_fn: Injectable wall clock (epoch ms) for seeded timestamps.
+
+ Returns:
+ An :class:`EnsureSystemJobsReport` of per-outcome job ids.
+
+ Raises:
+ ValueError: Only when a SEEDED spec default fails store validation —
+ a spec-authoring bug that must crash CI, not a user-tampered row
+ (repairs never raise; they use ``validate=False`` per (ii-b)).
+ """
+ active_specs = tuple(system_job_specs() if specs is None else specs)
+ now = _now_ms() if now_fn is None else int(now_fn())
+ gate: SpecGate = enabled_predicate if enabled_predicate is not None else (lambda s: s.enabled_predicate())
+ seeded: list[str] = []
+ repaired: list[str] = []
+ unchanged: list[str] = []
+ skipped: list[str] = []
+ halted: list[str] = []
+ for spec in active_specs:
+ enabled = bool(gate(spec))
+ existing = store.get(spec.id)
+ if existing is None:
+ if not enabled:
+ # QA (a): disabled + no row -> nothing is written at all.
+ skipped.append(spec.id)
+ continue
+ # (iii) repair-replay shares this path: a hand-deleted system job
+ # is re-seeded at the next startup. validate=True on purpose —
+ # the spec defaults are ours and were checked in __post_init__.
+ store.upsert(_seed_job(spec, now))
+ seeded.append(spec.id)
+ logger.info("system job %s seeded (schedule=%r)", spec.id, spec.schedule)
+ continue
+ notes = _reconcile(existing, spec, enabled=enabled)
+ if not notes:
+ (unchanged if enabled else halted).append(spec.id)
+ continue
+ # (ii-b): repair/halt writes must always land — a row whose schedule
+ # no longer validates must still be correctable without crashing
+ # startup.
+ store.upsert(existing, validate=False)
+ (repaired if enabled else halted).append(spec.id)
+ logger.info("system job %s reconciled at startup: %s", spec.id, "; ".join(notes))
+ return EnsureSystemJobsReport(
+ seeded=tuple(seeded),
+ repaired=tuple(repaired),
+ unchanged=tuple(unchanged),
+ skipped_disabled=tuple(skipped),
+ halted=tuple(halted),
+ )
diff --git a/agent/tests/scheduling/test_system_jobs.py b/agent/tests/scheduling/test_system_jobs.py
new file mode 100644
index 000000000..440931706
--- /dev/null
+++ b/agent/tests/scheduling/test_system_jobs.py
@@ -0,0 +1,567 @@
+"""Protected system jobs (scheduler unification T6).
+
+Covers the plan's acceptance criteria and QA trio mechanically:
+
+* idempotence — two ``ensure_system_jobs`` passes leave identical rows and
+ the second pass performs NO write (store bytes unchanged);
+* enabled/disabled branches — spec-level ``enabled_predicate`` and the
+ caller-level override; disabled with no row writes NOTHING (QA (a));
+ disabled with an existing runnable row halts it to CANCELLED so the
+ double-gate enablement chain (iv) holds in the flag-off direction too;
+* ``is_system_job_id`` — prefix convention, incl. the playbook-id false case;
+* tamper correction — ``executor_kind``/``source_type``/``internal_callable``
+ (QA (b)); valid edited schedule preserved (β local trust), invalid
+ schedule repaired to the spec default; (α) CANCELLED/EXPIRED reset to
+ PENDING with ``end_at`` cleared; manual deletion re-seeded (iii);
+ runtime fields preserved across re-ensure;
+* end-to-end through the executor — a seeded system job due → the registry
+ fake callable runs exactly once via the internal branch (T5 supervisor),
+ prompt dispatch never called; an unregistered callable FAILS with
+ ``failure_kind="dispatch"`` and a readable ``last_error`` (QA (c)) — not
+ silently skipped, not prompt-dispatched — while ``ensure_system_jobs``
+ itself seeds without requiring registry membership.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+from src.scheduled_research.executor import ScheduledResearchExecutor
+from src.scheduled_research.models import (
+ DeliveryRecord,
+ DeliveryStatus,
+ JobStatus,
+ ScheduledResearchJob,
+)
+from src.scheduled_research.store import ScheduledResearchJobStore
+from src.scheduling import system_jobs as sj
+from src.scheduling.registry import register_internal, resolve_internal
+from src.scheduling.system_jobs import (
+ SYSTEM_JOB_ID_PREFIX,
+ EnsureSystemJobsReport,
+ SystemJobSpec,
+ ensure_system_jobs,
+ is_system_job_id,
+ system_job_specs,
+)
+
+
+def _store(tmp_path: Path) -> ScheduledResearchJobStore:
+ return ScheduledResearchJobStore(path=tmp_path / "jobs.json")
+
+
+def _spec(**overrides: object) -> SystemJobSpec:
+ base: dict = {
+ "id": "system:test-job",
+ "schedule": "1000",
+ "internal_callable": "test.fake",
+ "title": "Test system job",
+ }
+ base.update(overrides)
+ return SystemJobSpec(**base) # type: ignore[arg-type]
+
+
+def _resolver(job: ScheduledResearchJob):
+ """Production-shaped dispatcher: exact-key registry lookup, may raise."""
+ return resolve_internal(job.internal_callable)
+
+
+async def _drain(executor: ScheduledResearchExecutor) -> None:
+ """Await every in-flight internal background task (test-only reach-in)."""
+ tasks = list(executor._internal._tasks)
+ if tasks:
+ await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=10)
+
+
+def _mutate_row(store: ScheduledResearchJobStore, job_id: str, **changes: object) -> None:
+ """Simulate a manual store-file edit (bypasses upsert validation)."""
+ jobs = store.load()
+ job = jobs[job_id]
+ for key, value in changes.items():
+ setattr(job, key, value)
+ store.save(jobs)
+
+
+# ---------------------------------------------------------------------------
+# is_system_job_id — the prefix predicate T7 consumes
+# ---------------------------------------------------------------------------
+
+
+ "job_id",
+ ["system:memory-consolidation", "system:br-data-sync", "system:", "system:x" * 30],
+)
+def test_is_system_job_id_true_for_prefix(job_id: str) -> None:
+ assert is_system_job_id(job_id) is True
+
+
+ "job_id",
+ [
+ "playbook-premarket-brief-abcd1234", # plan's named false case
+ "sr-0123456789ab",
+ "systemic-job", # 'system' without the colon is NOT the prefix
+ "System:memory-consolidation", # case-sensitive
+ "",
+ None,
+ 123,
+ ],
+)
+def test_is_system_job_id_false_for_everything_else(job_id: object) -> None:
+ assert is_system_job_id(job_id) is False
+
+
+def test_prefix_constant_contains_colon_for_safe_id_re_interplay() -> None:
+ """T7 ②b: the prefix MUST contain ':' so _SAFE_JOB_ID_RE (^[A-Za-z0-9_-]{1,128}$)
+ rejects every system id at POST/path-param level — structural anti-forgery."""
+ assert SYSTEM_JOB_ID_PREFIX == "system:"
+ assert ":" in SYSTEM_JOB_ID_PREFIX
+
+
+# ---------------------------------------------------------------------------
+# Spec surface + validation
+# ---------------------------------------------------------------------------
+
+
+def test_production_specs_are_a_tuple_of_wellformed_specs() -> None:
+ specs = system_job_specs()
+ assert isinstance(specs, tuple)
+ for spec in specs: # empty until T8/T9 append; the loop pins the invariant
+ assert is_system_job_id(spec.id)
+ assert spec.source_type == "system"
+ assert spec.executor_kind == "internal"
+ assert spec.prompt == ""
+ assert spec.internal_callable
+
+
+def test_ensure_consumes_system_job_specs_by_default(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """T8/T9 edit surface: appending to _SYSTEM_JOB_SPECS is enough — the
+ default ensure path (no specs kwarg, as T12 will call it) picks it up."""
+ store = _store(tmp_path)
+ spec = _spec()
+ monkeypatch.setattr(sj, "_SYSTEM_JOB_SPECS", (spec,))
+ report = ensure_system_jobs(store, now_fn=lambda: 1000)
+ assert report.seeded == (spec.id,)
+ assert store.get(spec.id) is not None
+
+
+def test_spec_defaults_are_system_and_internal() -> None:
+ spec = _spec()
+ assert spec.source_type == "system"
+ assert spec.executor_kind == "internal"
+ assert spec.prompt == ""
+ assert spec.timezone is None
+ assert spec.enabled_predicate() is True
+
+
+ "overrides",
+ [
+ {"id": "memory-consolidation"}, # missing prefix
+ {"id": "system:"}, # prefix only, no name
+ {"id": ""},
+ {"source_type": "prompt"},
+ {"executor_kind": "prompt"},
+ {"internal_callable": ""},
+ {"schedule": "not a schedule!!!"},
+ {"schedule": ""},
+ ],
+)
+def test_spec_rejects_malformed_definitions(overrides: dict) -> None:
+ with pytest.raises(ValueError):
+ _spec(**overrides)
+
+
+def test_spec_rejects_non_callable_predicate() -> None:
+ with pytest.raises(TypeError):
+ _spec(enabled_predicate="yes")
+
+
+# ---------------------------------------------------------------------------
+# Seeding: enabled / disabled branches (QA (a))
+# ---------------------------------------------------------------------------
+
+
+def test_enabled_spec_seeds_system_job(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ spec = _spec(schedule="2000")
+ report = ensure_system_jobs(store, specs=[spec], now_fn=lambda: 5000)
+ assert report.seeded == (spec.id,)
+ job = store.get(spec.id)
+ assert job is not None
+ assert job.source_type == "system"
+ assert job.executor_kind == "internal"
+ assert job.internal_callable == "test.fake"
+ assert job.prompt == ""
+ assert job.status == JobStatus.PENDING
+ assert job.schedule == "2000"
+ assert job.next_run_at == 5000 # interval schedule: due immediately
+ assert job.created_at == 5000
+ assert job.end_at is None
+ assert job.delivery_channel is None # no delivery for this batch (plan)
+
+
+def test_seeded_cron_with_timezone_waits_for_next_slot(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ spec = _spec(schedule="0 3 * * *", timezone="UTC")
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 0)
+ job = store.get(spec.id)
+ assert job is not None
+ assert job.next_run_at > 0 # next 03:00 UTC slot, not "now"
+ assert job.timezone == "UTC"
+
+
+def test_disabled_spec_writes_nothing(tmp_path: Path) -> None:
+ """QA (a): flag false → NO system job written — strongest sense: the
+ store file is never even created."""
+ store = _store(tmp_path)
+ spec = _spec()
+ report = ensure_system_jobs(store, specs=[spec], enabled_predicate=lambda _s: False)
+ assert report.skipped_disabled == (spec.id,)
+ assert report.seeded == ()
+ assert store.load() == {}
+ assert not store.path.exists()
+
+
+def test_spec_level_enabled_predicate_gates_seeding(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ off = _spec(id="system:off", enabled_predicate=lambda: False)
+ on = _spec(id="system:on", enabled_predicate=lambda: True)
+ report = ensure_system_jobs(store, specs=[off, on], now_fn=lambda: 1000)
+ assert report.seeded == ("system:on",)
+ assert report.skipped_disabled == ("system:off",)
+ assert store.get("system:on") is not None
+ assert store.get("system:off") is None
+
+
+# ---------------------------------------------------------------------------
+# Idempotence + runtime-field preservation
+# ---------------------------------------------------------------------------
+
+
+def test_two_passes_are_idempotent_with_zero_rewrite(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ first_bytes = store.path.read_bytes()
+ first = store.get(spec.id).to_dict()
+
+ report = ensure_system_jobs(store, specs=[spec], now_fn=lambda: 999_999)
+ assert report.unchanged == (spec.id,)
+ assert report.seeded == () and report.repaired == ()
+ assert store.path.read_bytes() == first_bytes # conformant row NOT written
+ assert store.get(spec.id).to_dict() == first
+ assert len(store.load()) == 1
+
+
+def test_runtime_fields_preserved_across_reensure(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ delivery = DeliveryRecord(status=DeliveryStatus.SENT, session_id="s-1", key="k")
+ _mutate_row(
+ store,
+ spec.id,
+ next_run_at=777,
+ last_run_at=555,
+ consecutive_failures=2,
+ last_error="earlier boom",
+ failure_kind="dispatch",
+ status=JobStatus.COMPLETED,
+ created_at=111,
+ config={"k": 1},
+ title="user-renamed",
+ prompt="user-typed text",
+ delivery_channel="email",
+ delivery=delivery,
+ )
+ before = store.get(spec.id).to_dict()
+
+ report = ensure_system_jobs(store, specs=[spec], now_fn=lambda: 888_888)
+ assert report.unchanged == (spec.id,)
+ after = store.get(spec.id).to_dict()
+ assert after == before # every field, byte for byte
+ job = store.get(spec.id)
+ assert job.status == JobStatus.COMPLETED # live status untouched
+ assert job.next_run_at == 777 and job.last_run_at == 555
+ assert job.consecutive_failures == 2 and job.failure_kind == "dispatch"
+ assert job.delivery.status == DeliveryStatus.SENT and job.delivery.session_id == "s-1"
+
+
+# ---------------------------------------------------------------------------
+# Tamper correction (QA (b)) + (β) schedule boundary + (α) status reset
+# ---------------------------------------------------------------------------
+
+
+def test_tampered_executor_kind_prompt_is_corrected(tmp_path: Path) -> None:
+ """QA (b): user hand-edits executor_kind to 'prompt' → corrected to
+ 'internal' (and the callable key restored), so the row can never be
+ prompt-dispatched again."""
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(
+ store,
+ spec.id,
+ source_type="prompt",
+ executor_kind="prompt",
+ internal_callable=None,
+ )
+
+ report = ensure_system_jobs(store, specs=[spec], now_fn=lambda: 2000)
+ assert report.repaired == (spec.id,)
+ job = store.get(spec.id)
+ assert job.executor_kind == "internal"
+ assert job.source_type == "system"
+ assert job.internal_callable == "test.fake"
+ assert job.next_run_at == 1000 # runtime fields still untouched
+
+
+def test_tampered_callable_key_is_corrected_to_spec(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, internal_callable="os.system")
+
+ ensure_system_jobs(store, specs=[spec])
+ assert store.get(spec.id).internal_callable == "test.fake"
+
+
+def test_valid_edited_schedule_is_preserved_beta_local_trust(tmp_path: Path) -> None:
+ """(ii-c) choice (β): a syntactically VALID user-edited schedule is
+ trusted local configuration and left alone — with its next_run_at."""
+ store = _store(tmp_path)
+ spec = _spec(schedule="1000")
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, schedule="5000", next_run_at=4242)
+
+ report = ensure_system_jobs(store, specs=[spec])
+ assert report.unchanged == (spec.id,)
+ job = store.get(spec.id)
+ assert job.schedule == "5000"
+ assert job.next_run_at == 4242
+
+
+def test_invalid_schedule_is_repaired_to_spec_default(tmp_path: Path) -> None:
+ """The other side of the (β) boundary: an INVALID schedule must be
+ repaired, else the validate=False repair write would persist garbage."""
+ store = _store(tmp_path)
+ spec = _spec(schedule="1000")
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, schedule="every tuesday maybe")
+
+ report = ensure_system_jobs(store, specs=[spec])
+ assert report.repaired == (spec.id,)
+ job = store.get(spec.id)
+ assert job.schedule == "1000"
+ assert job.next_run_at == 1000 # runtime field still preserved
+
+
[email protected]("status", [JobStatus.CANCELLED, JobStatus.EXPIRED])
+def test_alpha_reset_cancelled_and_expired_to_pending(tmp_path: Path, status: JobStatus) -> None:
+ """(α): CANCELLED/EXPIRED can only come from manual file edits (post-T7)
+ or our own flag-off halt — reset to PENDING and clear end_at."""
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, status=status, end_at=12345)
+
+ report = ensure_system_jobs(store, specs=[spec])
+ assert report.repaired == (spec.id,)
+ job = store.get(spec.id)
+ assert job.status == JobStatus.PENDING
+ assert job.end_at is None
+
+
+def test_hand_added_future_end_at_is_cleared_while_pending(tmp_path: Path) -> None:
+ """Same tamper class as (α): specs define no end boundary, so a manually
+ added end_at that would expire the job mid-life is removed."""
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, end_at=10**15)
+
+ ensure_system_jobs(store, specs=[spec])
+ assert store.get(spec.id).end_at is None
+
+
+def test_manual_deletion_is_reseeded(tmp_path: Path) -> None:
+ """(iii) repair-replay: hand-deleting the row does not stick."""
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ assert store.delete(spec.id) is True
+
+ report = ensure_system_jobs(store, specs=[spec], now_fn=lambda: 2000)
+ assert report.seeded == (spec.id,)
+ job = store.get(spec.id)
+ assert job is not None and job.source_type == "system"
+ assert job.created_at == 2000 # genuinely fresh row
+
+
+# ---------------------------------------------------------------------------
+# Flag-off halt + re-enable round trip (enablement chain (iv))
+# ---------------------------------------------------------------------------
+
+
+def test_disabled_flag_halts_existing_row_and_reenable_revives_it(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, last_run_at=900, consecutive_failures=1)
+
+ off = ensure_system_jobs(store, specs=[spec], enabled_predicate=lambda _s: False)
+ assert off.halted == (spec.id,)
+ job = store.get(spec.id)
+ assert job.status == JobStatus.CANCELLED # never due again while off
+ assert job.last_run_at == 900 and job.consecutive_failures == 1 # non-destructive
+ assert job.executor_kind == "internal" # spec-owned fields still correct
+
+ # Idempotent while still disabled: no further write.
+ halted_bytes = store.path.read_bytes()
+ off2 = ensure_system_jobs(store, specs=[spec], enabled_predicate=lambda _s: False)
+ assert off2.halted == (spec.id,)
+ assert store.path.read_bytes() == halted_bytes
+
+ # Flag back on: the (α) reset revives the row.
+ on = ensure_system_jobs(store, specs=[spec])
+ assert on.repaired == (spec.id,)
+ job = store.get(spec.id)
+ assert job.status == JobStatus.PENDING
+ assert job.last_run_at == 900 # history preserved across the round trip
+
+
+def test_disabled_flag_leaves_terminal_rows_untouched(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, status=JobStatus.FAILED, consecutive_failures=3)
+ before = store.path.read_bytes()
+
+ report = ensure_system_jobs(store, specs=[spec], enabled_predicate=lambda _s: False)
+ assert report.halted == (spec.id,)
+ assert store.path.read_bytes() == before # FAILED is already never-due
+
+
+def test_disabled_flag_still_corrects_tampered_fields(tmp_path: Path) -> None:
+ """A disabled row tampered to executor_kind='prompt' must not stay a
+ prompt-dispatchable row even while the feature flag is off."""
+ store = _store(tmp_path)
+ spec = _spec()
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ _mutate_row(store, spec.id, executor_kind="prompt", internal_callable=None)
+
+ ensure_system_jobs(store, specs=[spec], enabled_predicate=lambda _s: False)
+ job = store.get(spec.id)
+ assert job.executor_kind == "internal"
+ assert job.internal_callable == "test.fake"
+ assert job.status == JobStatus.CANCELLED
+
+
+# ---------------------------------------------------------------------------
+# End-to-end through the executor (QA happy + QA (c))
+# ---------------------------------------------------------------------------
+
+
+def test_seeded_system_job_runs_registry_callable_once_via_internal_branch(
+ tmp_path: Path, clean_registry
+) -> None:
+ """QA happy: enabled → seeded → due → the registry fake callable is
+ invoked exactly once through the T5 supervisor path; the prompt dispatch
+ callback is never called for it."""
+ store = _store(tmp_path)
+ calls: list[int] = []
+ register_internal("test.fake", lambda: calls.append(1))
+ spec = _spec(schedule="1000")
+ ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ prompt_calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ prompt_calls.append(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store, dispatch, internal_dispatcher=_resolver, now_fn=lambda: 1500
+ )
+ await executor.tick(1500)
+ await _drain(executor)
+
+ asyncio.run(scenario())
+
+ assert calls == [1]
+ assert prompt_calls == []
+ saved = store.get(spec.id)
+ assert saved is not None
+ assert saved.status == JobStatus.COMPLETED
+ assert saved.failure_kind is None
+ assert saved.last_run_at == 1500
+ assert saved.next_run_at == 2500 # advanced from completion time
+
+
+def test_unregistered_callable_seeds_then_fails_as_dispatch(
+ tmp_path: Path, clean_registry
+) -> None:
+ """QA (c): ensure seeds WITHOUT requiring registry membership; at
+ execution the unregistered key fails closed — failure_kind='dispatch',
+ readable last_error, retryable PENDING — never silently skipped, never
+ prompt-dispatched."""
+ store = _store(tmp_path)
+ spec = _spec(internal_callable="test.never.registered")
+ report = ensure_system_jobs(store, specs=[spec], now_fn=lambda: 1000)
+ assert report.seeded == (spec.id,) # registry empty, seeding still works
+ prompt_calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ prompt_calls.append(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store, dispatch, internal_dispatcher=_resolver, now_fn=lambda: 1500
+ )
+ await executor.tick(1500)
+ assert not executor._internal._tasks # resolve failed synchronously
+
+ asyncio.run(scenario())
+
+ saved = store.get(spec.id)
+ assert saved is not None
+ assert saved.status == JobStatus.PENDING # retryable first failure
+ assert saved.failure_kind == "dispatch"
+ assert saved.consecutive_failures == 1
+ assert "not registered" in (saved.last_error or "")
+ assert "test.never.registered" in (saved.last_error or "")
+ assert prompt_calls == []
+
+
+# ---------------------------------------------------------------------------
+# Report shape + module purity
+# ---------------------------------------------------------------------------
+
+
+def test_report_is_frozen_with_tuple_fields(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ report = ensure_system_jobs(store, specs=[])
+ assert isinstance(report, EnsureSystemJobsReport)
+ assert report == EnsureSystemJobsReport()
+ for value in (
+ report.seeded,
+ report.repaired,
+ report.unchanged,
+ report.skipped_disabled,
+ report.halted,
+ ):
+ assert isinstance(value, tuple)
+ with pytest.raises(Exception): # frozen dataclass
+ report.seeded = ("x",) # type: ignore[misc]
+
+
+def test_system_jobs_module_reads_no_environment() -> None:
+ """The env surface belongs to T8/T9: this module only consumes injected
+ predicates (the ci_env_var_gate AST walk backs this at CI level)."""
+ source = Path(sj.__file__).read_text(encoding="utf-8")
+ for token in ("os.environ", "getenv", "get_env_config", "environ["):
+ assert token not in source