Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
Gate idle watch and task database work (#777)
Call White0048c3c80af1
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex d494340f3..08490774d 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -761,6 +761,7 @@ class TaskExecutionStore:self.processing_dir = self.root / "processing"self.completed_dir = self.root / "completed"self._ensure_dirs()+ self._signature = self._state_signature()def _ensure_dirs(self) -> None:if self._sqlite is not None:@@ -769,6 +770,24 @@ class TaskExecutionStore:self.processing_dir.mkdir(parents=True, exist_ok=True)self.completed_dir.mkdir(parents=True, exist_ok=True)+ def _state_signature(self) -> tuple[Optional[tuple[int, int, int]], ...] | None:+ if self._sqlite is not None:+ return None+ return (+ _path_signature(self.pending_dir),+ _path_signature(self.processing_dir),+ _path_signature(self.completed_dir),+ )++ def maybe_reload(self) -> bool:+ if self._sqlite is not None:+ return self._sqlite.maybe_reload()+ signature = self._state_signature()+ if signature == self._signature:+ return False+ self._signature = signature+ return True+def _request_path(self, request_id: str, *, state: str) -> Path:directory = {"pending": self.pending_dir,@@ -1431,6 +1450,7 @@ class ScheduledTaskService:# Cache of session_id -> canonical lock key (resolution hits SQLite).self._session_lock_cache: Dict[str, str] = {}self._requires_service_lease = runtime.service_instance_lock_attached_to_process()+ self._drain_dirty = Trueself.request_store.recover_processing()def validate_platform(self, platform: str) -> None:@@ -1532,10 +1552,19 @@ class ScheduledTaskService:if not self._owns_service_instance():returntry:- if self.store.maybe_reload():+ store_changed = self.store.maybe_reload()+ request_store_changed = self.request_store.maybe_reload()+ should_drain = store_changed or request_store_changed or self._drain_dirty+ if store_changed:self.reconcile_jobs()- await self._drain_requests()- await self._drain_callbacks()+ if should_drain:+ self._drain_dirty = False+ try:+ await self._drain_requests()+ await self._drain_callbacks()+ except Exception:+ self._drain_dirty = True+ raiseawait asyncio.sleep(2)except asyncio.CancelledError:raise@@ -1664,11 +1693,14 @@ class ScheduledTaskService:except Exception as exc:logger.error("Agent run callback failed for %s: %s", run_id, exc, exc_info=True)self.request_store.update_callback_status(run_id, status="failed", error=str(exc))+ self._drain_dirty = Truecontinueif callback_run is None:self.request_store.update_callback_status(run_id, status="skipped")+ self._drain_dirty = Truecontinueself.request_store.update_callback_status(run_id, status="sent", callback_run_id=callback_run.id)+ self._drain_dirty = Truedef _enqueue_callback_run(self, run: dict[str, Any]) -> Optional[TaskExecutionRequest]:callback_session_id = str(run.get("callback_session_id") or "").strip()@@ -1795,6 +1827,7 @@ class ScheduledTaskService:self._inflight_executions.pop(request_id, None)if lock_key is not None:self._inflight_sessions.discard(lock_key)+ self._drain_dirty = True# ``_execute_claimed_request`` already records failures and requeues on# cancellation; this only surfaces unexpected crashes in the wrapper.if task.cancelled():diff --git a/core/watches.py b/core/watches.pyindex 5cd5f363f..ba83a6863 100644--- a/core/watches.py+++ b/core/watches.py@@ -413,6 +413,8 @@ class ManagedWatchService:self._store_error_fused = Falseself._store_reconcile_failures = 0self._requires_service_lease = runtime.service_instance_lock_attached_to_process()+ self._reconcile_dirty = True+ self._runtime_state_dirty = Truedef active_process_pids(self) -> set[int]:"""Return active waiter process roots owned by managed watches."""@@ -424,8 +426,12 @@ class ManagedWatchService:self._running = Trueself._reconcile_task = asyncio.create_task(self._watch_store())try:- self.reconcile_watches()+ if self.reconcile_watches():+ self._runtime_state_dirty = True+ self._write_runtime_state()+ self._reconcile_dirty = Falseexcept Exception as exc:+ self._reconcile_dirty = Trueself._handle_reconcile_store_error(exc)async def stop(self) -> None:@@ -442,6 +448,7 @@ class ManagedWatchService:self._active_tasks.clear()self._active_pids.clear()self._watch_started_at.clear()+ self._runtime_state_dirty = Trueself._write_runtime_state()async def _watch_store(self) -> None:@@ -452,41 +459,52 @@ class ManagedWatchService:await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)continuetry:- if self.store.maybe_reload():- self.reconcile_watches()- self.reconcile_watches()+ should_reconcile = self.store.maybe_reload() or self._reconcile_dirty+ if should_reconcile:+ if self.reconcile_watches():+ self._runtime_state_dirty = True+ if self._runtime_state_dirty:+ self._write_runtime_state()self._store_reconcile_failures = 0+ self._reconcile_dirty = Falseexcept asyncio.CancelledError:raiseexcept Exception as exc:+ self._reconcile_dirty = Trueself._handle_reconcile_store_error(exc)await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)- def reconcile_watches(self) -> None:+ def reconcile_watches(self) -> bool:if not self._owns_service_instance():- return+ return Falseif self._store_error_fused:- return- desired_ids = {watch.id for watch in self.store.list_watches() if watch.enabled}- for watch in self.store.list_watches():+ return False+ watches = self.store.list_watches()+ desired_ids = {watch.id for watch in watches if watch.enabled}+ changed = False+ for watch in watches:if not watch.enabled or watch.id in self._active_tasks or watch.id in self._fused_watch_ids:continuetask = asyncio.create_task(self._run_watch(watch.id))self._active_tasks[watch.id] = tasktask.add_done_callback(lambda _task, watch_id=watch.id: self._on_watch_done(watch_id))+ changed = Truefor watch_id, task in list(self._active_tasks.items()):if watch_id in desired_ids:continuetask.cancel()+ changed = True- self._write_runtime_state()+ return changeddef _on_watch_done(self, watch_id: str) -> None:self._active_tasks.pop(watch_id, None)self._active_pids.pop(watch_id, None)self._watch_started_at.pop(watch_id, None)+ self._runtime_state_dirty = Trueself._write_runtime_state()+ self._reconcile_dirty = Truedef _write_runtime_state(self) -> None:payload = {"watches": {}}@@ -500,7 +518,9 @@ class ManagedWatchService:}try:self.runtime_store.write(payload)+ self._runtime_state_dirty = Falseexcept Exception:+ self._runtime_state_dirty = Truelogger.exception("Failed to persist watch runtime state")def _fuse_store_after_error(self, operation: str, exc: Exception, *, watch_id: str | None = None) -> None:@@ -552,6 +572,7 @@ class ManagedWatchService:for task in list(self._active_tasks.values()):if task is not current_task:task.cancel()+ self._runtime_state_dirty = Trueself._write_runtime_state()def _owns_service_instance(self) -> bool:@@ -566,6 +587,7 @@ class ManagedWatchService:async def _run_watch(self, watch_id: str) -> None:lifetime_started = asyncio.get_running_loop().time()self._watch_started_at[watch_id] = _utc_now_iso()+ self._runtime_state_dirty = Trueself._write_runtime_state()while self._running:@@ -719,6 +741,7 @@ class ManagedWatchService:**isolated_subprocess_kwargs(),)self._active_pids[watch.id] = process.pid+ self._runtime_state_dirty = Trueself._write_runtime_state()try:if timeout_seconds > 0:@@ -734,6 +757,7 @@ class ManagedWatchService:return _CycleResult(exit_code=124, stdout="", stderr=stderr.decode("utf-8", errors="replace"), timed_out=True)finally:self._active_pids.pop(watch.id, None)+ self._runtime_state_dirty = Trueself._write_runtime_state()return _CycleResult(diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex cb6940900..f09119e89 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -901,6 +901,23 @@ def test_request_store_enqueue_claim_and_complete(tmp_path: Path) -> None:assert not (store.processing_dir / f"{request.id}.json").exists()+def test_request_store_file_backend_reload_detects_queue_changes(tmp_path: Path) -> None:+ root = tmp_path / "task_requests"+ reader = TaskExecutionStore(root)+ writer = TaskExecutionStore(root)++ assert reader.maybe_reload() is False+ request = writer.enqueue_hook_send(session_key="slack::channel::C123", prompt="hello")++ assert reader.maybe_reload() is True+ assert reader.maybe_reload() is False++ assert writer.claim(request.id) is not None++ assert reader.maybe_reload() is True+ assert reader.maybe_reload() is False++def test_request_store_file_backend_filters_public_run_statuses(tmp_path: Path) -> None:store = TaskExecutionStore(tmp_path / "task_requests")queued = store.enqueue_hook_send(session_key="slack::channel::C123", prompt="queued")@@ -2702,6 +2719,193 @@ def test_watch_store_does_not_respawn_after_stop(tmp_path: Path) -> None:asyncio.run(_exercise())+def test_scheduled_task_service_idle_tick_does_not_drain_empty_queues(tmp_path: Path, monkeypatch) -> None:+ original_sleep = asyncio.sleep++ class IdleTaskStore(ScheduledTaskStore):+ def __init__(self, path: Path):+ super().__init__(path)+ self.reloads = 0+ self.list_calls = 0++ def maybe_reload(self) -> bool:+ self.reloads += 1+ return False++ def list_tasks(self):+ self.list_calls += 1+ return super().list_tasks()++ class IdleRequestStore(TaskExecutionStore):+ def __init__(self, root: Path):+ super().__init__(root)+ self.reloads = 0+ self.pending_calls = 0+ self.callback_calls = 0++ def maybe_reload(self) -> bool:+ self.reloads += 1+ return False++ def list_pending(self):+ self.pending_calls += 1+ return super().list_pending()++ def list_pending_callbacks(self, *, limit: int = 20):+ self.callback_calls += 1+ return super().list_pending_callbacks(limit=limit)++ store = IdleTaskStore(tmp_path / "scheduled_tasks.json")+ request_store = IdleRequestStore(tmp_path / "task_requests")+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=request_store,+ )+ service.scheduler = _StubScheduler()+ service._running = True+ service._drain_dirty = False+ ticks = 0++ async def _stop_after_first_sleep(_seconds):+ nonlocal ticks+ ticks += 1+ service._running = False+ await original_sleep(0)++ monkeypatch.setattr("core.scheduled_tasks.asyncio.sleep", _stop_after_first_sleep)++ asyncio.run(service._watch_store())++ assert ticks == 1+ assert store.reloads == 1+ assert request_store.reloads == 1+ assert store.list_calls == 0+ assert request_store.pending_calls == 0+ assert request_store.callback_calls == 0+++def test_scheduled_task_service_dirty_tick_drains_without_store_reload(tmp_path: Path, monkeypatch) -> None:+ original_sleep = asyncio.sleep++ class IdleTaskStore(ScheduledTaskStore):+ def maybe_reload(self) -> bool:+ return False++ class IdleRequestStore(TaskExecutionStore):+ def maybe_reload(self) -> bool:+ return False++ store = IdleTaskStore(tmp_path / "scheduled_tasks.json")+ request_store = IdleRequestStore(tmp_path / "task_requests")+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=request_store,+ )+ service.scheduler = _StubScheduler()+ service._running = True+ service._drain_dirty = True+ request_drains = 0+ callback_drains = 0++ async def _drain_requests() -> None:+ nonlocal request_drains+ request_drains += 1++ async def _drain_callbacks() -> None:+ nonlocal callback_drains+ callback_drains += 1++ async def _stop_after_first_sleep(_seconds):+ service._running = False+ await original_sleep(0)++ service._drain_requests = _drain_requests+ service._drain_callbacks = _drain_callbacks+ monkeypatch.setattr("core.scheduled_tasks.asyncio.sleep", _stop_after_first_sleep)++ asyncio.run(service._watch_store())++ assert request_drains == 1+ assert callback_drains == 1+ assert service._drain_dirty is False+++def test_scheduled_task_service_rearms_after_skipped_and_failed_callback_batches(+ tmp_path: Path, monkeypatch+) -> None:+ original_sleep = asyncio.sleep++ class IdleTaskStore(ScheduledTaskStore):+ def maybe_reload(self) -> bool:+ return False++ class CallbackRequestStore(TaskExecutionStore):+ def __init__(self, root: Path):+ super().__init__(root)+ self.callback_calls = 0+ self.status_updates: list[tuple[str, str]] = []++ def maybe_reload(self) -> bool:+ return False++ def list_pending_callbacks(self, *, limit: int = 20):+ self.callback_calls += 1+ if self.callback_calls == 1:+ return [{"id": "run-1", "callback_session_id": "ses-callback"}]+ if self.callback_calls == 2:+ return [{"id": "run-2", "callback_session_id": "ses-callback"}]+ return []++ def update_callback_status(+ self,+ run_id: str,+ *,+ status: str,+ error: str | None = None,+ callback_run_id: str | None = None,+ ) -> None:+ self.status_updates.append((run_id, status))++ store = IdleTaskStore(tmp_path / "scheduled_tasks.json")+ request_store = CallbackRequestStore(tmp_path / "task_requests")+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=request_store,+ )+ service.scheduler = _StubScheduler()+ service._running = True+ service._drain_dirty = True+ ticks = 0++ async def _drain_requests() -> None:+ return None++ def _enqueue_callback_run(run: dict):+ if run["id"] == "run-1":+ return None+ raise RuntimeError("callback boom")++ async def _stop_after_two_sleeps(_seconds):+ nonlocal ticks+ ticks += 1+ if ticks >= 2:+ service._running = False+ await original_sleep(0)++ service._drain_requests = _drain_requests+ service._enqueue_callback_run = _enqueue_callback_run+ monkeypatch.setattr("core.scheduled_tasks.asyncio.sleep", _stop_after_two_sleeps)++ asyncio.run(service._watch_store())++ assert request_store.status_updates == [("run-1", "skipped"), ("run-2", "failed")]+ assert request_store.callback_calls == 2+ assert service._drain_dirty is True++def test_drain_does_not_block_on_hung_execution(tmp_path: Path) -> None:"""A turn that never returns must not stall delivery of other sessions.diff --git a/tests/test_watches.py b/tests/test_watches.pyindex d00e1861b..28ee6af57 100644--- a/tests/test_watches.py+++ b/tests/test_watches.py@@ -811,6 +811,94 @@ def test_managed_watch_service_fuses_reconcile_after_store_read_error(tmp_path:assert service._active_tasks == {}+def test_managed_watch_service_idle_tick_does_not_write_runtime_state(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)++ class IdleStore(ManagedWatchStore):+ def __init__(self, path: Path):+ super().__init__(path)+ self.reloads = 0+ self.lists = 0++ def maybe_reload(self) -> bool:+ self.reloads += 1+ return False++ def list_watches(self):+ self.lists += 1+ return super().list_watches()++ class CountingRuntimeStore(WatchRuntimeStateStore):+ def __init__(self) -> None:+ self.writes = 0++ def write(self, payload: dict) -> None:+ self.writes += 1++ def load(self) -> dict:+ return {"watches": {}}++ store = IdleStore(tmp_path / "watches.json")+ runtime_store = CountingRuntimeStore()+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=TaskExecutionStore(tmp_path / "task_requests"),+ runtime_store=runtime_store,+ )+ service._running = True+ service._reconcile_dirty = False+ service._runtime_state_dirty = False++ async def _run() -> None:+ task = asyncio.create_task(service._watch_store())+ await asyncio.sleep(0.05)+ service._running = False+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ asyncio.run(_run())++ assert store.reloads > 0+ assert store.lists == 0+ assert runtime_store.writes == 0+++def test_managed_watch_service_start_clears_stale_runtime_state(tmp_path: Path) -> None:+ store = ManagedWatchStore(tmp_path / "watches.json")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ runtime_store.write(+ {+ "watches": {+ "stale-watch": {+ "running": True,+ "pid": 1234,+ "started_at": "2026-05-15T00:00:00+00:00",+ "updated_at": "2026-05-15T00:00:01+00:00",+ }+ }+ }+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=TaskExecutionStore(tmp_path / "task_requests"),+ runtime_store=runtime_store,+ )++ async def _run() -> None:+ service.start()+ try:+ assert runtime_store.load()["watches"] == {}+ finally:+ await service.stop()++ asyncio.run(_run())++def test_managed_watch_service_retries_transient_reconcile_errors(tmp_path: Path, monkeypatch) -> None:monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)