def sync_heartbeat_and_routines(
scheduler: Any,
config: Any = None,
*,
workspace: str | None = None,
) -> dict[str, Any]:
"""Upsert heartbeat:tick + routine:{id} tasks. Returns summary."""
try:
from diapason.core.config import load_config
cfg = config or load_config()
except Exception:
cfg = config
hb = getattr(cfg, "heartbeat", None) if cfg is not None else None
rt = getattr(cfg, "routines", None) if cfg is not None else None
ws = workspace or (
str(getattr(hb, "workspace_dir", "") or "").strip() or None if hb else None
)
ensure_heartbeat_file(ws)
ensure_routines_file(ws)
summary: dict[str, Any] = {"heartbeat": None, "routines": []}
hb_enabled = bool(getattr(hb, "enabled", False)) if hb is not None else False
interval = int(getattr(hb, "interval_seconds", 1800) if hb is not None else 1800)
summary["heartbeat"] = _upsert_task(
scheduler,
task_id=HEARTBEAT_TASK_ID,
prompt=HEARTBEAT_PROMPT,
schedule_type="interval",
schedule_value=str(max(60, interval)),
metadata={"diapason_kind": "heartbeat"},
active=hb_enabled,
)
routines_enabled = bool(getattr(rt, "enabled", True)) if rt is not None else True
for routine in load_routines(ws):
task_id = f"routine:{routine.id}"
active = routines_enabled and routine.enabled
_upsert_task(
scheduler,
task_id=task_id,
prompt=f"[ROUTINE:{routine.id}]",
schedule_type="cron",
schedule_value=routine.cron,
metadata={
"diapason_kind": "routine",
"routine_id": routine.id,
"kind": routine.kind,
},
active=active,
)
summary["routines"].append(
{"id": routine.id, "active": active, "task_id": task_id}
)
logger.info(
"Synced heartbeat=%s routines=%d",
summary["heartbeat"],
len(summary["routines"]),
)
return summary