Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
Watch sync followup (#2962)
yepper4c1ff1190b84
diff --git a/openviking/resource/watch_manager.py b/openviking/resource/watch_manager.pyindex 758d5d2cb..1a0e88063 100644--- a/openviking/resource/watch_manager.py+++ b/openviking/resource/watch_manager.py@@ -7,10 +7,11 @@ Provides task creation, update, deletion, query, and persistence storage."""import asyncio+import inspectimport jsonimport uuidfrom datetime import datetime, timedelta-from typing import Any, Dict, List, Optional+from typing import Any, Awaitable, Callable, Dict, List, Optionalfrom pydantic import BaseModel, Field@@ -27,6 +28,31 @@ logger = get_logger(__name__)_UNSET = object()+def _uri_matches_prefix(uri: Optional[str], prefix: str) -> bool:+ if not uri:+ return False+ normalized = prefix.rstrip("/")+ return uri == normalized or uri.startswith(normalized + "/")+++def _rewrite_uri_prefix(uri: str, old_prefix: str, new_prefix: str) -> str:+ old_normalized = old_prefix.rstrip("/")+ new_normalized = new_prefix.rstrip("/")+ if uri == old_normalized:+ return new_normalized+ return new_normalized + uri[len(old_normalized) :]+++def _parent_uri(uri: str) -> Optional[str]:+ normalized = uri.rstrip("/")+ if "/" not in normalized:+ return None+ parent = normalized.rsplit("/", 1)[0]+ if parent in {"viking:/", "viking://"}:+ return None+ return parent++class WatchTask(BaseModel):"""Resource monitoring task data model."""@@ -545,6 +571,155 @@ class WatchManager:task.auth_state = auth_stateawait self._save_tasks()+ def _plan_move_tasks_under_uri_unlocked(+ self,+ old_uri: str,+ new_uri: str,+ ) -> Dict[str, str]:+ old_prefix = old_uri.rstrip("/")+ new_prefix = new_uri.rstrip("/")+ plan: Dict[str, str] = {}+ for task_id, task in self._tasks.items():+ if _uri_matches_prefix(task.to_uri, old_prefix):+ plan[task_id] = _rewrite_uri_prefix(task.to_uri or "", old_prefix, new_prefix)++ moving_task_ids = set(plan)+ for task_id, target_uri in plan.items():+ existing_task_id = self._uri_to_task.get(target_uri)+ if existing_task_id and existing_task_id not in moving_task_ids:+ raise ConflictError(+ f"Target URI '{target_uri}' is already used by another task",+ resource=target_uri,+ )+ if existing_task_id in moving_task_ids and existing_task_id != task_id:+ raise ConflictError(+ f"Target URI '{target_uri}' is already used by another moved task",+ resource=target_uri,+ )+ return plan++ async def plan_move_tasks_under_uri_internal(+ self,+ old_uri: str,+ new_uri: str,+ ) -> Dict[str, str]:+ """Return the watch-task URI rewrite plan for a resource move.++ This is an internal lifecycle hook used before moving resources so URI+ conflicts can fail the move before any resource state is changed.+ """+ async with self._lock:+ return self._plan_move_tasks_under_uri_unlocked(old_uri, new_uri)++ async def move_tasks_under_uri_internal(+ self,+ old_uri: str,+ new_uri: str,+ ) -> List[WatchTask]:+ """Rewrite watch-task target URIs after a resource move."""+ async with self._lock:+ plan = self._plan_move_tasks_under_uri_unlocked(old_uri, new_uri)+ if not plan:+ return []++ for task_id in plan:+ task = self._tasks[task_id]+ if task.to_uri:+ self._uri_to_task.pop(task.to_uri, None)++ updated: List[WatchTask] = []+ for task_id, target_uri in plan.items():+ task = self._tasks[task_id]+ old_parent = _parent_uri(task.to_uri or "")+ task.to_uri = target_uri+ if task.parent_uri is not None and task.parent_uri == old_parent:+ task.parent_uri = _parent_uri(target_uri)+ self._uri_to_task[target_uri] = task_id+ updated.append(task)++ await self._save_tasks()+ logger.info(+ f"[WatchManager] Rewrote {len(updated)} watch task target URI(s) "+ f"under {old_uri} to {new_uri}"+ )+ return updated++ async def sync_tasks_with_resource_move_internal(+ self,+ old_uri: str,+ new_uri: str,+ move_resource: Callable[[], Awaitable[None]],+ rollback_resource: Optional[Callable[[], Awaitable[None]]] = None,+ ) -> List[WatchTask]:+ """Move a resource and keep watch-task target URIs in sync under one lock."""+ async with self._lock:+ plan = self._plan_move_tasks_under_uri_unlocked(old_uri, new_uri)+ move_result = move_resource()+ if inspect.isawaitable(move_result):+ await move_result+ if not plan:+ return []++ original_targets = {+ task_id: (task.to_uri, task.parent_uri)+ for task_id, task in self._tasks.items()+ if task_id in plan+ }+ original_uri_to_task = dict(self._uri_to_task)++ try:+ for task_id in plan:+ task = self._tasks[task_id]+ if task.to_uri:+ self._uri_to_task.pop(task.to_uri, None)++ updated: List[WatchTask] = []+ for task_id, target_uri in plan.items():+ task = self._tasks[task_id]+ old_parent = _parent_uri(task.to_uri or "")+ task.to_uri = target_uri+ if task.parent_uri is not None and task.parent_uri == old_parent:+ task.parent_uri = _parent_uri(target_uri)+ self._uri_to_task[target_uri] = task_id+ updated.append(task)++ await self._save_tasks()+ logger.info(+ f"[WatchManager] Rewrote {len(updated)} watch task target URI(s) "+ f"under {old_uri} to {new_uri}"+ )+ return updated+ except Exception:+ for task_id, (original_to_uri, original_parent_uri) in original_targets.items():+ task = self._tasks[task_id]+ task.to_uri = original_to_uri+ task.parent_uri = original_parent_uri+ self._uri_to_task = original_uri_to_task+ if rollback_resource is not None:+ rollback_result = rollback_resource()+ if inspect.isawaitable(rollback_result):+ await rollback_result+ raise++ async def deactivate_tasks_under_uri_internal(self, uri: str) -> List[WatchTask]:+ """Deactivate watch tasks whose target URI is deleted."""+ async with self._lock:+ matched = [+ task+ for task in self._tasks.values()+ if _uri_matches_prefix(task.to_uri, uri)+ ]+ if not matched:+ return []++ for task in matched:+ task.is_active = False+ task.next_execution_time = None++ await self._save_tasks()+ logger.info(f"[WatchManager] Deactivated {len(matched)} watch task(s) under {uri}")+ return matched+async def delete_task(self,task_id: str,diff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.pyindex d3aa26fdd..6b37d8cfd 100644--- a/openviking/resource/watch_scheduler.py+++ b/openviking/resource/watch_scheduler.py@@ -18,8 +18,10 @@ from openviking.resource.feishu_watch_auth import (is_feishu_auth_state,)from openviking.resource.watch_manager import WatchManager+from openviking.server.error_mapping import is_not_found_errorfrom openviking.server.identity import RequestContext, Rolefrom openviking.service.resource_service import ResourceService+from openviking_cli.exceptions import NotFoundErrorfrom openviking_cli.utils import get_loggerlogger = get_logger(__name__)@@ -249,24 +251,35 @@ class WatchScheduler:role=role,)- processor_kwargs = dict(getattr(task, "processor_kwargs", {}) or {})- processor_kwargs.pop("build_index", None)- processor_kwargs.pop("summarize", None)- auth_state = getattr(task, "auth_state", None)- if is_feishu_auth_state(auth_state):- try:- auth_state = await self._prepare_feishu_auth_state(task, auth_state)- processor_kwargs["feishu_access_token"] = auth_state["access_token"]- except FeishuTokenRefreshError as e:- if e.permanent:- should_deactivate = True- deactivation_reason = str(e)- logger.error(- f"[WatchScheduler] Task {task.task_id} permanent Feishu "- f"token refresh failure: {e}. Deactivating task."- )- else:- raise+ if task.to_uri:+ target_exists = await self._check_target_uri_exists(task.to_uri, ctx)+ if target_exists is False:+ should_deactivate = True+ deactivation_reason = f"Watched target URI does not exist: {task.to_uri}"+ logger.warning(+ f"[WatchScheduler] Task {task.task_id}: {deactivation_reason}. "+ "Deactivating task."+ )++ if not should_deactivate:+ processor_kwargs = dict(getattr(task, "processor_kwargs", {}) or {})+ processor_kwargs.pop("build_index", None)+ processor_kwargs.pop("summarize", None)+ auth_state = getattr(task, "auth_state", None)+ if is_feishu_auth_state(auth_state):+ try:+ auth_state = await self._prepare_feishu_auth_state(task, auth_state)+ processor_kwargs["feishu_access_token"] = auth_state["access_token"]+ except FeishuTokenRefreshError as e:+ if e.permanent:+ should_deactivate = True+ deactivation_reason = str(e)+ logger.error(+ f"[WatchScheduler] Task {task.task_id} permanent Feishu "+ f"token refresh failure: {e}. Deactivating task."+ )+ else:+ raiseif not should_deactivate:result = await self._resource_service.add_resource(@@ -383,6 +396,20 @@ class WatchScheduler:logger.warning(f"[WatchScheduler] Failed to check path existence {path}: {e}")return False+ async def _check_target_uri_exists(self, uri: str, ctx: RequestContext) -> Optional[bool]:+ if self._viking_fs is None:+ return True+ try:+ await self._viking_fs.stat(uri, ctx=ctx)+ return True+ except NotFoundError:+ return False+ except Exception as e:+ if is_not_found_error(e):+ return False+ logger.warning(f"[WatchScheduler] Failed to check target URI existence {uri}: {e}")+ return None+@propertydef is_running(self) -> bool:"""Check if the scheduler is running."""diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 827bc8bbb..e55679c6d 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -380,6 +380,7 @@ class OpenVikingService:vikingdb=self._vikingdb_manager,privacy_config_service=self._privacy_config_service,resource_memory_link_service=self._resource_memory_link_service,+ watch_scheduler=self._watch_scheduler,)self._relation_service.set_viking_fs(self._viking_fs)self._pack_service.set_dependencies(diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex 76846f390..2189efc86 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -15,6 +15,7 @@ from openviking.privacy import (get_skill_name_from_uri,restore_skill_content,)+from openviking.resource.watch_storage import is_watch_task_control_urifrom openviking.server.identity import RequestContextfrom openviking.session.memory.memory_updater import MemoryUpdaterfrom openviking.storage.content_write import ContentWriteCoordinator@@ -31,6 +32,8 @@ from openviking_cli.utils import VikingURI, get_loggerlogger = get_logger(__name__)if TYPE_CHECKING:+ from openviking.resource.watch_manager import WatchManager+ from openviking.resource.watch_scheduler import WatchSchedulerfrom openviking.service.resource_memory_link_service import ResourceMemoryLinkServicefrom openviking.storage import VikingDBManager@@ -44,11 +47,13 @@ class FSService:vikingdb: Optional["VikingDBManager"] = None,privacy_config_service: Optional[UserPrivacyConfigService] = None,resource_memory_link_service: Optional["ResourceMemoryLinkService"] = None,+ watch_scheduler: Optional["WatchScheduler"] = None,):self._viking_fs = viking_fsself._vikingdb = vikingdbself._privacy_config_service = privacy_config_serviceself._resource_memory_link_service = resource_memory_link_service+ self._watch_scheduler = watch_schedulerdef set_dependencies(self,@@ -56,12 +61,14 @@ class FSService:vikingdb: Optional["VikingDBManager"] = None,privacy_config_service: Optional[UserPrivacyConfigService] = None,resource_memory_link_service: Optional["ResourceMemoryLinkService"] = None,+ watch_scheduler: Optional["WatchScheduler"] = None,) -> None:"""Set service dependencies (for deferred initialization)."""self._viking_fs = viking_fsself._vikingdb = vikingdbself._privacy_config_service = privacy_config_serviceself._resource_memory_link_service = resource_memory_link_service+ self._watch_scheduler = watch_schedulerdef _ensure_initialized(self) -> VikingFS:"""Ensure VikingFS is initialized."""@@ -69,6 +76,11 @@ class FSService:raise NotInitializedError("VikingFS")return self._viking_fs+ def _get_watch_manager(self) -> Optional["WatchManager"]:+ if not self._watch_scheduler:+ return None+ return self._watch_scheduler.watch_manager+async def ls(self,uri: str,@@ -191,6 +203,7 @@ class FSService:refresh_parent_uri = self._semantic_refresh_parent_uri(uri, context_type)memory_overview_uri = self._memory_overview_parent_uri(uri, context_type)result = await viking_fs.rm(uri, recursive=recursive, ctx=ctx)+ await self._sync_watch_after_rm(uri, context_type=context_type)queue_status = Nonerequest_registered = Falsetelemetry_id = get_current_telemetry().telemetry_id@@ -372,7 +385,70 @@ class FSService:from_uri = validate_viking_uri(from_uri, field_name="from_uri")to_uri = validate_viking_uri(to_uri, field_name="to_uri")viking_fs = self._ensure_initialized()- await viking_fs.mv(from_uri, to_uri, ctx=ctx)+ watch_manager = self._get_watch_manager()+ if not watch_manager or context_type_for_uri(from_uri) != "resource":+ await viking_fs.mv(from_uri, to_uri, ctx=ctx)+ return+ if context_type_for_uri(to_uri) != "resource":+ await viking_fs.mv(from_uri, to_uri, ctx=ctx)+ return+ if is_watch_task_control_uri(from_uri) or is_watch_task_control_uri(to_uri):+ await viking_fs.mv(from_uri, to_uri, ctx=ctx)+ return++ await watch_manager.sync_tasks_with_resource_move_internal(+ from_uri,+ to_uri,+ move_resource=lambda: viking_fs.mv(from_uri, to_uri, ctx=ctx),+ rollback_resource=lambda: viking_fs.mv(to_uri, from_uri, ctx=ctx),+ )++ async def _plan_watch_before_mv(self, from_uri: str, to_uri: str) -> None:+ if context_type_for_uri(from_uri) != "resource":+ return+ if context_type_for_uri(to_uri) != "resource":+ return+ if is_watch_task_control_uri(from_uri) or is_watch_task_control_uri(to_uri):+ return+ watch_manager = self._get_watch_manager()+ if not watch_manager:+ return+ await watch_manager.plan_move_tasks_under_uri_internal(from_uri, to_uri)++ async def _sync_watch_after_mv(self, from_uri: str, to_uri: str) -> None:+ if context_type_for_uri(from_uri) != "resource":+ return+ if context_type_for_uri(to_uri) != "resource":+ return+ if is_watch_task_control_uri(from_uri) or is_watch_task_control_uri(to_uri):+ return+ watch_manager = self._get_watch_manager()+ if not watch_manager:+ return+ updated = await watch_manager.move_tasks_under_uri_internal(from_uri, to_uri)+ if updated:+ logger.info(+ "Updated %d watch task target URI(s) after moving %s to %s",+ len(updated),+ from_uri,+ to_uri,+ )++ async def _sync_watch_after_rm(self, uri: str, *, context_type: str) -> None:+ if context_type != "resource":+ return+ if is_watch_task_control_uri(uri):+ return+ watch_manager = self._get_watch_manager()+ if not watch_manager:+ return+ deactivated = await watch_manager.deactivate_tasks_under_uri_internal(uri)+ if deactivated:+ logger.info(+ "Deactivated %d watch task(s) after deleting %s",+ len(deactivated),+ uri,+ )async def tree(self,@@ -638,4 +714,3 @@ class FSService:.ovgitignore; missing is success."""viking_fs = self._ensure_initialized()await viking_fs.delete_gitignore(ctx=ctx)-diff --git a/tests/resource/test_watch_manager.py b/tests/resource/test_watch_manager.pyindex 253c09182..9b7c2ff24 100644--- a/tests/resource/test_watch_manager.py+++ b/tests/resource/test_watch_manager.py@@ -7,6 +7,7 @@ import jsonfrom datetime import datetime, timedeltafrom pathlib import Pathfrom typing import AsyncGenerator+from unittest.mock import AsyncMockimport pytestimport pytest_asyncio@@ -229,6 +230,155 @@ class TestWatchManager:assert task.is_active is Trueassert task.next_execution_time is not None+ @pytest.mark.asyncio+ async def test_deactivate_tasks_under_uri_internal_matches_subtree(+ self, watch_manager_no_fs: WatchManager+ ):+ root = await watch_manager_no_fs.create_task(+ path="/test/root",+ to_uri="viking://resources/codeask/wiki",+ watch_interval=30.0,+ )+ child = await watch_manager_no_fs.create_task(+ path="/test/child",+ to_uri="viking://resources/codeask/wiki/page",+ watch_interval=30.0,+ )+ sibling = await watch_manager_no_fs.create_task(+ path="/test/sibling",+ to_uri="viking://resources/codeask/wiki-renamed",+ watch_interval=30.0,+ )++ deactivated = await watch_manager_no_fs.deactivate_tasks_under_uri_internal(+ "viking://resources/codeask/wiki"+ )++ assert {task.task_id for task in deactivated} == {root.task_id, child.task_id}+ assert (await watch_manager_no_fs.get_task(root.task_id)).is_active is False+ assert (await watch_manager_no_fs.get_task(child.task_id)).is_active is False+ assert (await watch_manager_no_fs.get_task(sibling.task_id)).is_active is True++ @pytest.mark.asyncio+ async def test_move_tasks_under_uri_internal_rewrites_subtree(+ self, watch_manager_no_fs: WatchManager+ ):+ root = await watch_manager_no_fs.create_task(+ path="/test/root",+ to_uri="viking://resources/codeask/wiki",+ parent_uri="viking://resources/codeask",+ watch_interval=30.0,+ )+ child = await watch_manager_no_fs.create_task(+ path="/test/child",+ to_uri="viking://resources/codeask/wiki/page",+ parent_uri="viking://resources/codeask/wiki",+ watch_interval=30.0,+ )++ plan = await watch_manager_no_fs.plan_move_tasks_under_uri_internal(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ )+ updated = await watch_manager_no_fs.move_tasks_under_uri_internal(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ )++ assert plan == {+ root.task_id: "viking://resources/codeask/wiki-renamed",+ child.task_id: "viking://resources/codeask/wiki-renamed/page",+ }+ assert {task.task_id for task in updated} == {root.task_id, child.task_id}+ moved_root = await watch_manager_no_fs.get_task_by_uri(+ "viking://resources/codeask/wiki-renamed",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ moved_child = await watch_manager_no_fs.get_task_by_uri(+ "viking://resources/codeask/wiki-renamed/page",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert moved_root is not None+ assert moved_root.parent_uri == "viking://resources/codeask"+ assert moved_child is not None+ assert moved_child.parent_uri == "viking://resources/codeask/wiki-renamed"++ @pytest.mark.asyncio+ async def test_move_tasks_under_uri_internal_preserves_none_parent(+ self, watch_manager_no_fs: WatchManager+ ):+ root = await watch_manager_no_fs.create_task(+ path="/test/root",+ to_uri="viking://resources/codeask/wiki",+ parent_uri=None,+ watch_interval=30.0,+ )++ updated = await watch_manager_no_fs.move_tasks_under_uri_internal(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ )++ assert [task.task_id for task in updated] == [root.task_id]+ moved_root = await watch_manager_no_fs.get_task(root.task_id)+ assert moved_root is not None+ assert moved_root.to_uri == "viking://resources/codeask/wiki-renamed"+ assert moved_root.parent_uri is None++ @pytest.mark.asyncio+ async def test_plan_move_tasks_under_uri_internal_detects_conflict(+ self, watch_manager_no_fs: WatchManager+ ):+ await watch_manager_no_fs.create_task(+ path="/test/root",+ to_uri="viking://resources/codeask/wiki",+ watch_interval=30.0,+ )+ await watch_manager_no_fs.create_task(+ path="/test/existing",+ to_uri="viking://resources/codeask/wiki-renamed",+ watch_interval=30.0,+ )++ with pytest.raises(ConflictError):+ await watch_manager_no_fs.plan_move_tasks_under_uri_internal(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ )++ @pytest.mark.asyncio+ async def test_sync_tasks_with_resource_move_internal_rolls_back_task_state_on_save_failure(+ self, watch_manager_no_fs: WatchManager+ ):+ root = await watch_manager_no_fs.create_task(+ path="/test/root",+ to_uri="viking://resources/codeask/wiki",+ parent_uri=None,+ watch_interval=30.0,+ )+ watch_manager_no_fs._save_tasks = AsyncMock(side_effect=RuntimeError("save failed"))+ move_resource = AsyncMock()+ rollback_resource = AsyncMock()++ with pytest.raises(RuntimeError, match="save failed"):+ await watch_manager_no_fs.sync_tasks_with_resource_move_internal(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ move_resource=move_resource,+ rollback_resource=rollback_resource,+ )++ move_resource.assert_awaited_once()+ rollback_resource.assert_awaited_once()+ restored = await watch_manager_no_fs.get_task(root.task_id)+ assert restored is not None+ assert restored.to_uri == "viking://resources/codeask/wiki"+ assert restored.parent_uri is None+@pytest.mark.asyncioasync def test_auth_state_persisted_and_hidden_from_public_dict(self, mock_viking_fs: MockVikingFSdiff --git a/tests/resource/test_watch_scheduler.py b/tests/resource/test_watch_scheduler.pyindex 89f17f5cd..ee49727ed 100644--- a/tests/resource/test_watch_scheduler.py+++ b/tests/resource/test_watch_scheduler.py@@ -1,5 +1,8 @@+from unittest.mock import AsyncMock+import pytest+from openviking.resource.watch_manager import WatchManagerfrom openviking.resource.watch_scheduler import WatchSchedulerfrom openviking.service.resource_service import ResourceService@@ -25,3 +28,85 @@ class TestWatchSchedulerResourceExistence:assert scheduler._check_resource_exists("[email protected]:org/repo.git") is Trueassert scheduler._check_resource_exists("ssh://[email protected]/org/repo.git") is Trueassert scheduler._check_resource_exists("git://github.com/org/repo.git") is True++ @pytest.mark.asyncio+ async def test_missing_target_uri_deactivates_without_add_resource(self, tmp_path):+ from openviking_cli.exceptions import NotFoundError++ class FakeVikingFS:+ async def stat(self, uri, ctx=None):+ raise NotFoundError(uri, "resource")++ class FakeResourceService(ResourceService):+ def __init__(self):+ super().__init__()+ self.calls = []++ async def add_resource(self, **kwargs):+ self.calls.append(kwargs)+ return {"root_uri": kwargs.get("to")}++ source = tmp_path / "source.txt"+ source.write_text("ok")+ resource_service = FakeResourceService()+ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=FakeVikingFS(),+ check_interval=1,+ )+ manager = WatchManager(viking_fs=None)+ await manager.initialize()+ scheduler._watch_manager = manager+ task = await manager.create_task(+ path=str(source),+ to_uri="viking://resources/codeask/wiki",+ watch_interval=30.0,+ )++ await scheduler._execute_task(task)++ updated = await manager.get_task(task.task_id)+ assert updated is not None+ assert updated.is_active is False+ assert resource_service.calls == []++ @pytest.mark.asyncio+ async def test_target_uri_check_error_does_not_deactivate_task(self, tmp_path):+ class FakeVikingFS:+ async def stat(self, uri, ctx=None):+ raise RuntimeError("temporary stat failure")++ class FakeResourceService(ResourceService):+ def __init__(self):+ super().__init__()+ self.calls = []++ async def add_resource(self, **kwargs):+ self.calls.append(kwargs)+ return {"root_uri": kwargs.get("to")}++ source = tmp_path / "source.txt"+ source.write_text("ok")+ resource_service = FakeResourceService()+ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=FakeVikingFS(),+ check_interval=1,+ )+ manager = WatchManager(viking_fs=None)+ await manager.initialize()+ scheduler._watch_manager = manager+ manager.update_execution_time = AsyncMock()+ task = await manager.create_task(+ path=str(source),+ to_uri="viking://resources/codeask/wiki",+ watch_interval=30.0,+ )++ await scheduler._execute_task(task)++ updated = await manager.get_task(task.task_id)+ assert updated is not None+ assert updated.is_active is True+ assert resource_service.calls and resource_service.calls[0]["to"] == task.to_uri+ manager.update_execution_time.assert_awaited_once_with(task.task_id)diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.pyindex acdb136b9..3d61a4657 100644--- a/tests/service/test_fs_service.py+++ b/tests/service/test_fs_service.py@@ -15,6 +15,7 @@ from openviking_cli.session.user_id import UserIdentifierclass _FakeVikingFS:def __init__(self, *, rm_error=None):self.rm_calls = []+ self.mv_calls = []self.rm_error = rm_errorasync def rm(self, uri, recursive=False, ctx=None):@@ -23,6 +24,45 @@ class _FakeVikingFS:raise self.rm_errorreturn {"estimated_deleted_count": 3}+ async def mv(self, from_uri, to_uri, ctx=None):+ self.mv_calls.append({"from_uri": from_uri, "to_uri": to_uri, "ctx": ctx})+++class _FakeWatchManager:+ def __init__(self):+ self.plan_calls = []+ self.move_calls = []+ self.sync_calls = []+ self.deactivate_calls = []+ self.plan_error = None++ async def plan_move_tasks_under_uri_internal(self, from_uri, to_uri):+ self.plan_calls.append({"from_uri": from_uri, "to_uri": to_uri})+ if self.plan_error:+ raise self.plan_error+ return {}++ async def move_tasks_under_uri_internal(self, from_uri, to_uri):+ self.move_calls.append({"from_uri": from_uri, "to_uri": to_uri})+ return [SimpleNamespace(task_id="watch-1")]++ async def sync_tasks_with_resource_move_internal(+ self,+ from_uri,+ to_uri,+ move_resource,+ rollback_resource=None,+ ):+ self.sync_calls.append({"from_uri": from_uri, "to_uri": to_uri})+ if self.plan_error:+ raise self.plan_error+ await move_resource()+ return [SimpleNamespace(task_id="watch-1")]++ async def deactivate_tasks_under_uri_internal(self, uri):+ self.deactivate_calls.append(uri)+ return [SimpleNamespace(task_id="watch-1")]+class _FakeResourceMemoryLinkService:def __init__(self, result):@@ -34,6 +74,11 @@ class _FakeResourceMemoryLinkService:return self.result+class _FakeWatchScheduler:+ def __init__(self, watch_manager):+ self.watch_manager = watch_manager++class _FakeWaitTracker:def __init__(self):self.registered_requests = []@@ -163,6 +208,108 @@ async def test_resource_rm_without_wait_only_queues_refresh(request_context):assert result["semantic_status"] == "queued"+async def test_resource_rm_deactivates_watch_tasks(request_context):+ viking_fs = _FakeVikingFS()+ watch_manager = _FakeWatchManager()+ service = FSService(+ viking_fs=viking_fs,+ watch_scheduler=_FakeWatchScheduler(watch_manager),+ )+ service._enqueue_delete_refresh = AsyncMock()++ await service.rm("viking://resources/codeask/wiki", ctx=request_context, recursive=True)++ assert watch_manager.deactivate_calls == ["viking://resources/codeask/wiki"]+++async def test_resource_rm_does_not_deactivate_watch_task_control_uri(request_context):+ viking_fs = _FakeVikingFS()+ watch_manager = _FakeWatchManager()+ service = FSService(+ viking_fs=viking_fs,+ watch_scheduler=_FakeWatchScheduler(watch_manager),+ )++ await service.rm("viking://resources/.watch_tasks.json", ctx=request_context)++ assert watch_manager.deactivate_calls == []+++async def test_resource_mv_plans_then_moves_then_rewrites_watch_tasks(request_context):+ viking_fs = _FakeVikingFS()+ watch_manager = _FakeWatchManager()+ service = FSService(+ viking_fs=viking_fs,+ watch_scheduler=_FakeWatchScheduler(watch_manager),+ )++ await service.mv(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ ctx=request_context,+ )++ assert watch_manager.sync_calls == [+ {+ "from_uri": "viking://resources/codeask/wiki",+ "to_uri": "viking://resources/codeask/wiki-renamed",+ }+ ]+ assert viking_fs.mv_calls == [+ {+ "from_uri": "viking://resources/codeask/wiki",+ "to_uri": "viking://resources/codeask/wiki-renamed",+ "ctx": request_context,+ }+ ]+ assert watch_manager.plan_calls == []+ assert watch_manager.move_calls == []+++async def test_resource_mv_conflict_fails_before_resource_move(request_context):+ viking_fs = _FakeVikingFS()+ watch_manager = _FakeWatchManager()+ watch_manager.plan_error = RuntimeError("watch conflict")+ service = FSService(+ viking_fs=viking_fs,+ watch_scheduler=_FakeWatchScheduler(watch_manager),+ )++ with pytest.raises(RuntimeError, match="watch conflict"):+ await service.mv(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ ctx=request_context,+ )++ assert viking_fs.mv_calls == []+ assert watch_manager.move_calls == []+++async def test_resource_mv_without_watch_scheduler_moves_resource_directly(request_context):+ viking_fs = _FakeVikingFS()+ service = FSService(viking_fs=viking_fs)++ await service.mv(+ "viking://resources/codeask/wiki",+ "viking://resources/codeask/wiki-renamed",+ ctx=request_context,+ )++ assert viking_fs.mv_calls == [+ {+ "from_uri": "viking://resources/codeask/wiki",+ "to_uri": "viking://resources/codeask/wiki-renamed",+ "ctx": request_context,+ }+ ]++@pytest.mark.asyncioasync def test_resource_rm_wait_registers_request_before_semantic_root(request_context,diff --git a/uv.lock b/uv.lockindex 2c5d46aa0..ecf327a3a 100644--- a/uv.lock+++ b/uv.lock@@ -1038,6 +1038,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl", hash = "sha256:d316bb415a2d9e2d2b3abcc4084c6502fc09240e292cd76a76afc106a1c8e04a", size = 9190, upload-time = "2025-02-24T04:41:32.565Z" },]+[[package]]+name = "defusedxml"+version = "0.7.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" },+]+[[package]]name = "diff-match-patch"version = "20241021"@@ -1267,6 +1276,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/1f/f6/da4db31001e854025ffd26bc9ba0740a9cbba2c3259695f7c5834908b336/fastuuid-0.14.0-cp314-cp314-win_amd64.whl", hash = "sha256:df61342889d0f5e7a32f7284e55ef95103f2110fee433c2ae7c2c0956d76ac8a", size = 156457, upload-time = "2025-10-19T22:33:44.579Z" },]+[[package]]+name = "feedparser"+version = "6.0.12"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "sgmllib3k" },+]+sdist = { url = "https://files.pythonhosted.org/packages/dc/79/db7edb5e77d6dfbc54d7d9df72828be4318275b2e580549ff45a962f6461/feedparser-6.0.12.tar.gz", hash = "sha256:64f76ce90ae3e8ef5d1ede0f8d3b50ce26bcce71dd8ae5e82b1cd2d4a5f94228", size = 286579, upload-time = "2025-09-10T13:33:59.486Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/4e/eb/c96d64137e29ae17d83ad2552470bafe3a7a915e85434d9942077d7fd011/feedparser-6.0.12-py3-none-any.whl", hash = "sha256:6bbff10f5a52662c00a2e3f86a38928c37c48f77b3c511aedcd51de933549324", size = 81480, upload-time = "2025-09-10T13:33:58.022Z" },+]+[[package]]name = "ffmpy"version = "1.0.0"@@ -3502,8 +3523,10 @@ dependencies = [{ name = "argon2-cffi" },{ name = "charset-normalizer" },{ name = "cryptography" },+ { name = "defusedxml" },{ name = "ebooklib" },{ name = "fastapi" },+ { name = "feedparser" },{ name = "httpx" },{ name = "jinja2" },{ name = "json-repair" },@@ -3734,10 +3757,12 @@ requires-dist = [{ name = "datasets", marker = "extra == 'eval'", specifier = ">=2.0.0" },{ name = "datasets", marker = "extra == 'test'", specifier = ">=2.0.0" },{ name = "ddgs", marker = "extra == 'bot'", specifier = ">=9.0.0" },+ { name = "defusedxml", specifier = ">=0.7.1" },{ name = "diff-match-patch", marker = "extra == 'test'", specifier = ">=20200713" },{ name = "dingtalk-stream", marker = "extra == 'bot-dingtalk'", specifier = ">=0.4.0" },{ name = "ebooklib", specifier = ">=0.18.0" },{ name = "fastapi", specifier = ">=0.128.0" },+ { name = "feedparser", specifier = ">=6.0.0" },{ name = "fusepy", marker = "extra == 'bot-fuse'", specifier = ">=3.0.1" },{ name = "google-genai", marker = "extra == 'gemini'", specifier = ">=1.0.0" },{ name = "google-genai", marker = "extra == 'gemini-async'", specifier = ">=1.0.0" },@@ -3758,7 +3783,7 @@ requires-dist = [{ name = "langgraph", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },{ name = "lark-oapi", specifier = ">=1.5.3" },{ name = "lark-oapi", marker = "extra == 'bot-feishu'", specifier = ">=1.0.0" },- { name = "litellm", specifier = ">=1.83.7,<1.86.3" },+ { name = "litellm", specifier = ">=1.83.7,<1.89.3" },{ name = "llama-cpp-python", marker = "extra == 'local-embed'", specifier = ">=0.3.0" },{ name = "loguru", specifier = ">=0.7.3" },{ name = "markdownify", specifier = ">=0.11.0" },@@ -5662,6 +5687,12 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/5c/e1/342c4434df56aa537f6ce7647eefee521d96fbb828b08acd709865767652/setuptools_scm-10.0.5-py3-none-any.whl", hash = "sha256:f611037d8aae618221503b8fa89319f073438252ae3420e01c9ceec249131a0a", size = 21695, upload-time = "2026-03-27T15:57:03.969Z" },]+[[package]]+name = "sgmllib3k"+version = "1.0.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/9e/bd/3704a8c3e0942d711c1299ebf7b9091930adae6675d7c8f476a7ce48653c/sgmllib3k-1.0.0.tar.gz", hash = "sha256:7868fb1c8bfa764c1ac563d3cf369c381d1325d36124933a726f29fcdaa812e9", size = 5750, upload-time = "2010-08-24T14:33:52.445Z" }+[[package]]name = "shellingham"version = "1.5.4"