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
feat(resources): add resource watch scheduling and status tracking (#709)
yepper834b8081832f
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex d9d9724b8..46166e666 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -480,6 +480,7 @@ impl HttpClient {include: Option<String>,exclude: Option<String>,directly_upload_media: bool,+ watch_interval: f64,) -> Result<serde_json::Value> {let path_obj = Path::new(path);@@ -501,6 +502,7 @@ impl HttpClient {"include": include,"exclude": exclude,"directly_upload_media": directly_upload_media,+ "watch_interval": watch_interval,});self.post("/api/v1/resources", &body).await@@ -520,6 +522,7 @@ impl HttpClient {"include": include,"exclude": exclude,"directly_upload_media": directly_upload_media,+ "watch_interval": watch_interval,});self.post("/api/v1/resources", &body).await@@ -537,6 +540,7 @@ impl HttpClient {"include": include,"exclude": exclude,"directly_upload_media": directly_upload_media,+ "watch_interval": watch_interval,});self.post("/api/v1/resources", &body).await@@ -555,6 +559,7 @@ impl HttpClient {"include": include,"exclude": exclude,"directly_upload_media": directly_upload_media,+ "watch_interval": watch_interval,});self.post("/api/v1/resources", &body).awaitdiff --git a/crates/ov_cli/src/commands/resources.rs b/crates/ov_cli/src/commands/resources.rsindex bc816bcf6..78ff6c63e 100644--- a/crates/ov_cli/src/commands/resources.rs+++ b/crates/ov_cli/src/commands/resources.rs@@ -16,6 +16,7 @@ pub async fn add_resource(include: Option<String>,exclude: Option<String>,directly_upload_media: bool,+ watch_interval: f64,format: OutputFormat,compact: bool,) -> Result<()> {@@ -33,6 +34,7 @@ pub async fn add_resource(include,exclude,directly_upload_media,+ watch_interval,).await?;output_success(&result, format, compact);diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex e20dd339a..cf444d759 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -96,6 +96,9 @@ enum Commands {/// Do not directly upload media files#[arg(long = "no-directly-upload-media", default_value_t = false)]no_directly_upload_media: bool,+ /// Watch interval in minutes for automatic resource monitoring (0 = no monitoring)+ #[arg(long, default_value = "0")]+ watch_interval: f64,},/// Add a skill into OpenVikingAddSkill {@@ -525,6 +528,7 @@ async fn main() {include,exclude,no_directly_upload_media,+ watch_interval,} => {handle_add_resource(path,@@ -539,6 +543,7 @@ async fn main() {include,exclude,no_directly_upload_media,+ watch_interval,ctx,).await@@ -655,6 +660,7 @@ async fn handle_add_resource(include: Option<String>,exclude: Option<String>,no_directly_upload_media: bool,+ watch_interval: f64,ctx: CliContext,) -> Result<()> {let is_url = path.starts_with("http://")@@ -722,6 +728,7 @@ async fn handle_add_resource(include,exclude,directly_upload_media,+ watch_interval,ctx.output_format,ctx.compact,).awaitdiff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex eff4d56f1..e7db29313 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -45,6 +45,7 @@ Add a resource to the knowledge base.| instruction | str | No | "" | Special processing instructions || wait | bool | No | False | Wait for semantic processing to complete || timeout | float | No | None | Timeout in seconds (only used when wait=True) |+| watch_interval | float | No | 0 | Watch interval (minutes). >0 enables/updates watch; <=0 disables watch. Only takes effect when target is provided |**Python SDK (Embedded / HTTP)**@@ -168,6 +169,48 @@ curl -X POST http://localhost:1933/api/v1/system/wait \openviking add-resource ./documents/guide.md --wait```+**Example: Watch for Updates (watch_interval)**++`watch_interval` is in minutes and periodically triggers re-processing for the specified target URI:++- `watch_interval > 0`: create (or reactivate and update) a watch task for the `target`+- `watch_interval <= 0`: disable (deactivate) the watch task for the `target`+- watch tasks are only managed when `target` / CLI `--to` is provided++If there is already an active watch task for the same `target`, submitting another request with `watch_interval > 0` returns a conflict error. Disable it first (`watch_interval = 0`) and then set a new interval.++**Python SDK (Embedded / HTTP)**++```python+client.add_resource(+ "./documents/guide.md",+ target="viking://resources/documents/guide.md",+ watch_interval=60,+)+```++**HTTP API**++```bash+curl -X POST http://localhost:1933/api/v1/resources \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "path": "./documents/guide.md",+ "target": "viking://resources/documents/guide.md",+ "watch_interval": 60+ }'+```++**CLI**++```bash+openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 60++# Disable watch+openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 0+```+---### export_ovpack()diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex 440e2fa30..fdcf201be 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -45,6 +45,7 @@ Input -> Parser -> TreeBuilder -> AGFS -> SemanticQueue -> Vector Index| instruction | str | 否 | "" | 特殊处理指令 || wait | bool | 否 | False | 等待语义处理完成 || timeout | float | 否 | None | 超时时间(秒),仅在 wait=True 时生效 |+| watch_interval | float | 否 | 0 | 定时更新间隔(分钟)。>0 开启/更新定时任务;<=0 关闭(停用)定时任务。仅在指定 target 时生效 |**Python SDK (Embedded / HTTP)**@@ -168,6 +169,48 @@ curl -X POST http://localhost:1933/api/v1/system/wait \openviking add-resource ./documents/guide.md --wait```+**示例:开启定时更新(watch_interval)**++`watch_interval` 的单位为分钟,用于对指定的目标 URI 定期触发更新处理:++- `watch_interval > 0`:创建(或重新激活并更新)该 `target` 的定时任务+- `watch_interval <= 0`:关闭(停用)该 `target` 的定时任务+- 只有在指定 `target` / CLI `--to` 时才会创建定时任务++如果同一个 `target` 已存在激活中的定时任务,再次以 `watch_interval > 0` 提交会返回冲突错误;需要先将 `watch_interval` 设为 `0`(取消/停用)后再重新设置新的间隔。++**Python SDK (Embedded / HTTP)**++```python+client.add_resource(+ "./documents/guide.md",+ target="viking://resources/documents/guide.md",+ watch_interval=60,+)+```++**HTTP API**++```bash+curl -X POST http://localhost:1933/api/v1/resources \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "path": "./documents/guide.md",+ "target": "viking://resources/documents/guide.md",+ "watch_interval": 60+ }'+```++**CLI**++```bash+openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 60++# 取消监控+openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 0+```+---### export_ovpack()diff --git a/examples/watch_resource_example.py b/examples/watch_resource_example.pynew file mode 100644index 000000000..fdf5c31b5--- /dev/null+++ b/examples/watch_resource_example.py@@ -0,0 +1,151 @@+#!/usr/bin/env python3+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""+Resource Watch Feature Example++This example demonstrates how to use the resource watch feature in OpenViking.+The watch feature allows you to automatically re-process resources at specified+intervals.++Key features:+- Create resources with watch enabled+- Update watch intervals (cancel then re-create)+- Cancel watch tasks+- Handle conflict errors+"""++import asyncio+from pathlib import Path++from openviking import AsyncOpenViking+from openviking_cli.exceptions import ConflictError+++async def example_basic_watch():+ client = AsyncOpenViking(path="./data_watch_example")+ await client.initialize()++ try:+ test_file = Path("./test_resource.md")+ test_file.write_text(+ """# Test Resource++## Content+This is a test resource for watch functionality.++## Version+Version: 1.0+"""+ )++ to_uri = "viking://resources/watched_resource"++ print("\nAdding resource with watch_interval=60.0 minutes...")+ result = await client.add_resource(+ path=str(test_file),+ to=to_uri,+ reason="Example: monitoring a document",+ instruction="Check for updates and re-index",+ watch_interval=60.0,+ )++ print("Resource added successfully!")+ print(f" Root URI: {result['root_uri']}")+ finally:+ await client.close()+++async def example_update_watch_interval():+ client = AsyncOpenViking(path="./data_watch_example")+ await client.initialize()++ try:+ test_file = Path("./test_resource.md")+ to_uri = "viking://resources/watched_resource"++ print("\nUpdating watch interval by canceling then re-creating...")+ await client.add_resource(+ path=str(test_file),+ to=to_uri,+ watch_interval=0,+ )+ await client.add_resource(+ path=str(test_file),+ to=to_uri,+ reason="Updated: more frequent monitoring",+ watch_interval=120.0,+ )+ print("Watch task updated successfully!")+ finally:+ await client.close()+++async def example_cancel_watch():+ client = AsyncOpenViking(path="./data_watch_example")+ await client.initialize()++ try:+ test_file = Path("./test_resource.md")+ to_uri = "viking://resources/watched_resource"++ print("\nCancelling watch by setting interval to 0...")+ await client.add_resource(+ path=str(test_file),+ to=to_uri,+ watch_interval=0,+ )+ print("Watch task cancelled successfully!")+ finally:+ await client.close()+++async def example_handle_conflict():+ client = AsyncOpenViking(path="./data_watch_example")+ await client.initialize()++ try:+ test_file = Path("./test_resource.md")+ to_uri = "viking://resources/conflict_example"++ print("\nCreating first watch task...")+ await client.add_resource(+ path=str(test_file),+ to=to_uri,+ watch_interval=30.0,+ )+ print(" First watch task created successfully")++ print("\nAttempting to create second watch task for same URI...")+ try:+ await client.add_resource(+ path=str(test_file),+ to=to_uri,+ watch_interval=60.0,+ )+ print(" ERROR: This should not happen!")+ except ConflictError as e:+ print(" ConflictError caught as expected!")+ print(f" Error message: {e}")+ finally:+ await client.close()+++async def main():+ print("\n" + "=" * 60)+ print("OpenViking Resource Watch Examples")+ print("=" * 60)++ await example_basic_watch()+ await example_update_watch_interval()+ await example_cancel_watch()+ await example_handle_conflict()++ print("\n" + "=" * 60)+ print("All examples completed!")+ print("=" * 60)+++if __name__ == "__main__":+ asyncio.run(main())+diff --git a/openviking/async_client.py b/openviking/async_client.pyindex b87b05ffb..655a717ea 100644--- a/openviking/async_client.py+++ b/openviking/async_client.py@@ -190,6 +190,7 @@ class AsyncOpenViking:timeout: float = None,build_index: bool = True,summarize: bool = False,+ watch_interval: float = 0,telemetry: TelemetryRequest = False,**kwargs,) -> Dict[str, Any]:@@ -223,9 +224,14 @@ class AsyncOpenViking:build_index=build_index,summarize=summarize,telemetry=telemetry,+ watch_interval=watch_interval,**kwargs,)+ @property+ def _service(self):+ return self._client.service+async def wait_processed(self, timeout: float = None) -> Dict[str, Any]:"""Wait for all queued processing to complete."""await self._ensure_initialized()diff --git a/openviking/client/local.py b/openviking/client/local.pyindex a6bcf061b..0c9183198 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -70,6 +70,7 @@ class LocalClient(BaseClient):build_index: bool = True,summarize: bool = False,telemetry: TelemetryRequest = False,+ watch_interval: float = 0,**kwargs,) -> Dict[str, Any]:"""Add resource to OpenViking."""@@ -90,6 +91,7 @@ class LocalClient(BaseClient):timeout=timeout,build_index=build_index,summarize=summarize,+ watch_interval=watch_interval,**kwargs,),)diff --git a/openviking/resource/__init__.py b/openviking/resource/__init__.pynew file mode 100644index 000000000..702b79059--- /dev/null+++ b/openviking/resource/__init__.py@@ -0,0 +1,7 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""Resource monitoring and management module."""++from openviking.resource.watch_manager import WatchManager, WatchTask++__all__ = ["WatchManager", "WatchTask"]diff --git a/openviking/resource/watch_manager.py b/openviking/resource/watch_manager.pynew file mode 100644index 000000000..4e475e570--- /dev/null+++ b/openviking/resource/watch_manager.py@@ -0,0 +1,717 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""+Resource monitoring task manager.++Provides task creation, update, deletion, query, and persistence storage.+"""++import asyncio+import json+import uuid+from datetime import datetime, timedelta+from typing import Any, Dict, List, Optional++from pydantic import BaseModel, Field++from openviking_cli.exceptions import ConflictError+from openviking_cli.utils.logger import get_logger++logger = get_logger(__name__)+++class WatchTask(BaseModel):+ """Resource monitoring task data model."""++ task_id: str = Field(+ default_factory=lambda: str(uuid.uuid4()), description="Unique task identifier"+ )+ path: str = Field(..., description="Resource path to monitor")+ to_uri: Optional[str] = Field(None, description="Target URI")+ parent_uri: Optional[str] = Field(None, description="Parent URI")+ reason: str = Field(default="", description="Reason for monitoring")+ instruction: str = Field(default="", description="Monitoring instruction")+ watch_interval: float = Field(default=60.0, description="Monitoring interval in minutes")+ build_index: bool = Field(default=True, description="Whether to build vector index")+ summarize: bool = Field(default=False, description="Whether to generate summary")+ processor_kwargs: Dict[str, Any] = Field(+ default_factory=dict, description="Extra kwargs forwarded to processor"+ )+ created_at: datetime = Field(default_factory=datetime.now, description="Task creation time")+ last_execution_time: Optional[datetime] = Field(None, description="Last execution time")+ next_execution_time: Optional[datetime] = Field(None, description="Next execution time")+ is_active: bool = Field(default=True, description="Whether the task is active")+ account_id: str = Field(default="default", description="Account ID (tenant)")+ user_id: str = Field(default="default", description="User ID who created this task")+ agent_id: str = Field(default="default", description="Agent ID who created this task")+ original_role: str = Field(default="user", description="Role used to execute this task")++ class Config:+ json_encoders = {datetime: lambda v: v.isoformat() if v else None}+ extra = "ignore"++ def to_dict(self) -> Dict[str, Any]:+ """Convert task to dictionary."""+ return {+ "task_id": self.task_id,+ "path": self.path,+ "to_uri": self.to_uri,+ "parent_uri": self.parent_uri,+ "reason": self.reason,+ "instruction": self.instruction,+ "watch_interval": self.watch_interval,+ "build_index": self.build_index,+ "summarize": self.summarize,+ "processor_kwargs": self.processor_kwargs,+ "created_at": self.created_at.isoformat() if self.created_at else None,+ "last_execution_time": self.last_execution_time.isoformat()+ if self.last_execution_time+ else None,+ "next_execution_time": self.next_execution_time.isoformat()+ if self.next_execution_time+ else None,+ "is_active": self.is_active,+ "account_id": self.account_id,+ "user_id": self.user_id,+ "agent_id": self.agent_id,+ "original_role": self.original_role,+ }++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "WatchTask":+ """Create task from dictionary."""+ if isinstance(data.get("created_at"), str):+ data["created_at"] = datetime.fromisoformat(data["created_at"])+ if isinstance(data.get("last_execution_time"), str):+ data["last_execution_time"] = datetime.fromisoformat(data["last_execution_time"])+ if isinstance(data.get("next_execution_time"), str):+ data["next_execution_time"] = datetime.fromisoformat(data["next_execution_time"])+ if data.get("processor_kwargs") is None:+ data["processor_kwargs"] = {}+ return cls(**data)++ def calculate_next_execution_time(self) -> datetime:+ """Calculate next execution time based on interval."""+ base_time = self.last_execution_time or self.created_at+ return base_time + timedelta(minutes=self.watch_interval)+++class PermissionDeniedError(Exception):+ """Permission denied error for watch operations."""++ pass+++class WatchManager:+ """Resource monitoring task manager.++ Provides task creation, update, deletion, query, and persistence storage.+ Thread-safe with async lock for concurrent access protection.+ Supports multi-tenant authorization.+ """++ STORAGE_URI = "viking://resources/.watch_tasks.json"+ STORAGE_BAK_URI = "viking://resources/.watch_tasks.json.bak"+ STORAGE_TMP_URI = "viking://resources/.watch_tasks.json.tmp"++ def __init__(self, viking_fs: Optional[Any] = None):+ """Initialize WatchManager.++ Args:+ viking_fs: VikingFS instance for persistence storage+ """+ self._tasks: Dict[str, WatchTask] = {}+ self._uri_to_task: Dict[str, str] = {}+ self._lock = asyncio.Lock()+ self._viking_fs = viking_fs+ self._initialized = False++ async def initialize(self) -> None:+ """Initialize the manager by loading tasks from storage."""+ if self._initialized:+ return++ async with self._lock:+ if self._initialized:+ return++ await self._load_tasks()+ self._initialized = True+ logger.info(f"[WatchManager] Initialized with {len(self._tasks)} tasks")++ async def _load_tasks(self) -> None:+ """Load tasks from VikingFS storage."""+ if not self._viking_fs:+ logger.debug("[WatchManager] No VikingFS provided, skipping load")+ return++ try:+ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)++ data = None+ try:+ content = await self._viking_fs.read_file(self.STORAGE_URI, ctx=ctx)+ if content and content.strip():+ data = json.loads(content)+ except FileNotFoundError:+ data = None+ except json.JSONDecodeError as e:+ logger.warning(f"[WatchManager] Invalid task storage JSON: {e}")+ except Exception as e:+ logger.warning(f"[WatchManager] Failed to read task storage: {e}")++ recovered_from_backup = False+ if data is None:+ try:+ bak_content = await self._viking_fs.read_file(self.STORAGE_BAK_URI, ctx=ctx)+ if bak_content and bak_content.strip():+ data = json.loads(bak_content)+ recovered_from_backup = True+ except FileNotFoundError:+ data = None+ except json.JSONDecodeError as e:+ logger.warning(f"[WatchManager] Invalid backup task storage JSON: {e}")+ data = None+ except Exception as e:+ logger.warning(f"[WatchManager] Failed to read backup task storage: {e}")++ if not isinstance(data, dict):+ data = {"tasks": []}++ normalized = False+ for task_data in data.get("tasks", []):+ try:+ task = WatchTask.from_dict(task_data)+ if not task.is_active:+ if task.next_execution_time is not None:+ task.next_execution_time = None+ normalized = True+ else:+ if task.watch_interval <= 0:+ task.is_active = False+ task.next_execution_time = None+ normalized = True+ elif task.next_execution_time is None:+ task.next_execution_time = task.calculate_next_execution_time()+ normalized = True+ self._tasks[task.task_id] = task+ if task.to_uri:+ self._uri_to_task[task.to_uri] = task.task_id+ except Exception as e:+ logger.warning(+ f"[WatchManager] Failed to load task {task_data.get('task_id')}: {e}"+ )++ logger.info(f"[WatchManager] Loaded {len(self._tasks)} tasks from storage")+ if recovered_from_backup:+ normalized = True+ if normalized:+ await self._save_tasks()+ except FileNotFoundError:+ logger.debug("[WatchManager] No existing task storage found, starting fresh")+ except Exception as e:+ logger.error(f"[WatchManager] Failed to load tasks: {e}")++ async def _save_tasks(self) -> None:+ """Save tasks to VikingFS storage."""+ if not self._viking_fs:+ logger.debug("[WatchManager] No VikingFS provided, skipping save")+ return++ try:+ from openviking.server.identity import RequestContext, Role+ from openviking_cli.session.user_id import UserIdentifier++ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)++ data = {+ "tasks": [task.to_dict() for task in self._tasks.values()],+ "updated_at": datetime.now().isoformat(),+ }++ content = json.dumps(data, ensure_ascii=False, indent=2)+ if not content.strip():+ raise ValueError("Refusing to write empty watch task storage")+ json.loads(content)++ supports_atomic = all(+ hasattr(self._viking_fs, name) for name in ("mv", "rm", "exists", "write_file")+ )+ if not supports_atomic:+ await self._viking_fs.write_file(self.STORAGE_URI, content, ctx=ctx)+ logger.debug(f"[WatchManager] Saved {len(self._tasks)} tasks to storage")+ return++ await self._viking_fs.write_file(self.STORAGE_TMP_URI, content, ctx=ctx)++ try:+ if await self._viking_fs.exists(self.STORAGE_BAK_URI, ctx=ctx):+ await self._viking_fs.rm(self.STORAGE_BAK_URI, ctx=ctx)+ except Exception:+ pass++ try:+ if await self._viking_fs.exists(self.STORAGE_URI, ctx=ctx):+ await self._viking_fs.mv(self.STORAGE_URI, self.STORAGE_BAK_URI, ctx=ctx)+ except Exception as e:+ logger.warning(f"[WatchManager] Failed to rotate task storage backup: {e}")++ await self._viking_fs.mv(self.STORAGE_TMP_URI, self.STORAGE_URI, ctx=ctx)+ logger.debug(f"[WatchManager] Saved {len(self._tasks)} tasks to storage")+ except Exception as e:+ logger.error(f"[WatchManager] Failed to save tasks: {e}")+ raise++ def _check_permission(+ self,+ task: WatchTask,+ account_id: str,+ user_id: str,+ role: str,+ ) -> bool:+ """Check if user has permission to access/modify a task.++ Args:+ task: The task to check permission for+ account_id: Requester's account ID+ user_id: Requester's user ID+ role: Requester's role (ROOT/ADMIN/USER)++ Returns:+ True if has permission, False otherwise++ Notes:+ - ROOT can access all tasks.+ - ADMIN can access tasks within the same account.+ - USER can only access tasks they created within the same account.+ """+ role_value = (role or "").lower()+ if role_value == "root":+ return True++ if task.account_id != account_id:+ return False++ if role_value == "admin":+ return True++ return task.user_id == user_id++ def _check_uri_conflict(+ self, to_uri: Optional[str], exclude_task_id: Optional[str] = None+ ) -> bool:+ """Check if target URI conflicts with existing tasks.++ Args:+ to_uri: Target URI to check+ exclude_task_id: Task ID to exclude from conflict check (for updates)++ Returns:+ True if there's a conflict, False otherwise+ """+ if not to_uri:+ return False++ existing_task_id = self._uri_to_task.get(to_uri)+ if not existing_task_id:+ return False++ if exclude_task_id and existing_task_id == exclude_task_id:+ return False++ return True++ async def create_task(+ self,+ path: str,+ account_id: str = "default",+ user_id: str = "default",+ agent_id: str = "default",+ original_role: str = "user",+ to_uri: Optional[str] = None,+ parent_uri: Optional[str] = None,+ reason: str = "",+ instruction: str = "",+ watch_interval: float = 60.0,+ build_index: bool = True,+ summarize: bool = False,+ processor_kwargs: Optional[Dict[str, Any]] = None,+ ) -> WatchTask:+ """Create a new monitoring task.++ Args:+ path: Resource path to monitor+ account_id: Account ID (tenant)+ user_id: User ID who creates this task+ agent_id: Agent ID who creates this task+ to_uri: Target URI+ parent_uri: Parent URI+ reason: Reason for monitoring+ instruction: Monitoring instruction+ watch_interval: Monitoring interval in minutes++ Returns:+ Created WatchTask++ Raises:+ ValueError: If required fields are missing+ ConflictError: If target URI conflicts with existing tasks+ """+ if not path:+ raise ValueError("Path is required")+ if watch_interval <= 0:+ raise ValueError("watch_interval must be > 0")++ async with self._lock:+ if self._check_uri_conflict(to_uri):+ raise ConflictError(+ f"Target URI '{to_uri}' is already used by another task",+ resource=to_uri,+ )++ task = WatchTask(+ path=path,+ to_uri=to_uri,+ parent_uri=parent_uri,+ reason=reason,+ instruction=instruction,+ watch_interval=watch_interval,+ build_index=build_index,+ summarize=summarize,+ processor_kwargs=processor_kwargs or {},+ account_id=account_id,+ user_id=user_id,+ agent_id=agent_id,+ original_role=original_role,+ )++ task.next_execution_time = task.calculate_next_execution_time()++ self._tasks[task.task_id] = task+ if to_uri:+ self._uri_to_task[to_uri] = task.task_id++ await self._save_tasks()++ logger.info(+ f"[WatchManager] Created task {task.task_id} for path {path} by user {account_id}/{user_id}"+ )+ return task++ async def update_task(+ self,+ task_id: str,+ account_id: str,+ user_id: str,+ role: str,+ path: Optional[str] = None,+ to_uri: Optional[str] = None,+ parent_uri: Optional[str] = None,+ reason: Optional[str] = None,+ instruction: Optional[str] = None,+ watch_interval: Optional[float] = None,+ build_index: Optional[bool] = None,+ summarize: Optional[bool] = None,+ processor_kwargs: Optional[Dict[str, Any]] = None,+ is_active: Optional[bool] = None,+ ) -> WatchTask:+ """Update an existing monitoring task.++ Args:+ task_id: Task ID to update+ account_id: Requester's account ID+ user_id: Requester's user ID+ role: Requester's role (ROOT/ADMIN/USER)+ path: New resource path+ to_uri: New target URI+ parent_uri: New parent URI+ reason: New reason+ instruction: New instruction+ watch_interval: New monitoring interval+ is_active: New active status++ Returns:+ Updated WatchTask++ Raises:+ ValueError: If task not found or invalid arguments+ ConflictError: If target URI conflicts with existing tasks+ PermissionDeniedError: If user doesn't have permission+ """+ async with self._lock:+ task = self._tasks.get(task_id)+ if not task:+ raise ValueError(f"Task {task_id} not found")++ if not self._check_permission(task, account_id, user_id, role):+ raise PermissionDeniedError(+ f"User {account_id}/{user_id} does not have permission to update task {task_id}"+ )++ if self._check_uri_conflict(to_uri, exclude_task_id=task_id):+ raise ConflictError(+ f"Target URI '{to_uri}' is already used by another task",+ resource=to_uri,+ )++ old_to_uri = task.to_uri++ if path is not None:+ task.path = path+ if to_uri is not None:+ task.to_uri = to_uri+ if parent_uri is not None:+ task.parent_uri = parent_uri+ if reason is not None:+ task.reason = reason+ if instruction is not None:+ task.instruction = instruction+ if watch_interval is not None:+ if watch_interval <= 0:+ if is_active is True:+ raise ValueError("watch_interval must be > 0 for active tasks")+ task.watch_interval = watch_interval+ task.is_active = False+ task.next_execution_time = None+ else:+ task.watch_interval = watch_interval+ if build_index is not None:+ task.build_index = build_index+ if summarize is not None:+ task.summarize = summarize+ if processor_kwargs is not None:+ task.processor_kwargs = processor_kwargs+ if is_active is not None:+ task.is_active = is_active++ if watch_interval is not None:+ if task.is_active and task.watch_interval > 0:+ task.next_execution_time = task.calculate_next_execution_time()+ else:+ task.next_execution_time = None+ if is_active is not None and watch_interval is None:+ if task.is_active:+ if task.watch_interval <= 0:+ raise ValueError("watch_interval must be > 0 for active tasks")+ if task.next_execution_time is None:+ task.next_execution_time = task.calculate_next_execution_time()+ else:+ task.next_execution_time = None++ if to_uri is not None:+ if old_to_uri and old_to_uri != to_uri:+ self._uri_to_task.pop(old_to_uri, None)+ if to_uri:+ self._uri_to_task[to_uri] = task_id++ await self._save_tasks()++ logger.info(f"[WatchManager] Updated task {task_id} by user {account_id}/{user_id}")+ return task++ async def delete_task(+ self,+ task_id: str,+ account_id: str,+ user_id: str,+ role: str,+ ) -> bool:+ """Delete a monitoring task.++ Args:+ task_id: Task ID to delete+ account_id: Requester's account ID+ user_id: Requester's user ID+ role: Requester's role (ROOT/ADMIN/USER)++ Returns:+ True if task was deleted, False if not found++ Raises:+ PermissionDeniedError: If user doesn't have permission+ """+ async with self._lock:+ task = self._tasks.get(task_id)+ if not task:+ return False++ if not self._check_permission(task, account_id, user_id, role):+ raise PermissionDeniedError(+ f"User {account_id}/{user_id} does not have permission to delete task {task_id}"+ )++ self._tasks.pop(task_id, None)+ if task.to_uri:+ self._uri_to_task.pop(task.to_uri, None)++ await self._save_tasks()++ logger.info(f"[WatchManager] Deleted task {task_id} by user {account_id}/{user_id}")+ return True++ async def get_task(+ self,+ task_id: str,+ account_id: str = "default",+ user_id: str = "default",+ role: str = "root",+ ) -> Optional[WatchTask]:+ """Get a monitoring task by ID.++ Args:+ task_id: Task ID to query+ account_id: Requester's account ID+ user_id: Requester's user ID+ role: Requester's role (ROOT/ADMIN/USER)++ Returns:+ WatchTask if found and accessible, None otherwise+ """+ async with self._lock:+ task = self._tasks.get(task_id)+ if not task:+ return None++ if not self._check_permission(task, account_id, user_id, role):+ return None++ return task++ async def get_all_tasks(+ self,+ account_id: str,+ user_id: str,+ role: str,+ active_only: bool = False,+ ) -> List[WatchTask]:+ """Get all monitoring tasks accessible by the user.++ Args:+ account_id: Requester's account ID+ user_id: Requester's user ID+ role: Requester's role (ROOT/ADMIN/USER)+ active_only: If True, only return active tasks++ Returns:+ List of accessible WatchTask objects+ """+ async with self._lock:+ tasks = []+ for task in self._tasks.values():+ if not self._check_permission(task, account_id, user_id, role):+ continue+ if active_only and not task.is_active:+ continue+ tasks.append(task)+ return tasks++ async def get_task_by_uri(+ self,+ to_uri: str,+ account_id: str,+ user_id: str,+ role: str,+ ) -> Optional[WatchTask]:+ """Get a monitoring task by target URI.++ Args:+ to_uri: Target URI to query+ account_id: Requester's account ID+ user_id: Requester's user ID+ role: Requester's role (ROOT/ADMIN/USER)++ Returns:+ WatchTask if found and accessible, None otherwise+ """+ async with self._lock:+ task_id = self._uri_to_task.get(to_uri)+ if not task_id:+ return None++ task = self._tasks.get(task_id)+ if not task:+ return None++ if not self._check_permission(task, account_id, user_id, role):+ return None++ return task++ async def update_execution_time(self, task_id: str) -> None:+ """Update task execution time after execution.++ Args:+ task_id: Task ID to update+ """+ async with self._lock:+ task = self._tasks.get(task_id)+ if not task:+ return++ if not task.is_active or task.watch_interval <= 0:+ task.is_active = False+ task.next_execution_time = None+ await self._save_tasks()+ return++ task.last_execution_time = datetime.now()+ task.next_execution_time = task.calculate_next_execution_time()++ await self._save_tasks()++ async def get_due_tasks(self, account_id: Optional[str] = None) -> List[WatchTask]:+ """Get all tasks that are due for execution.++ Args:+ account_id: Optional account ID filter (for scheduler)++ Returns:+ List of tasks that need to be executed+ """+ async with self._lock:+ now = datetime.now()+ due_tasks = []++ for task in self._tasks.values():+ if not task.is_active:+ continue++ if account_id and task.account_id != account_id:+ continue++ if task.next_execution_time and task.next_execution_time <= now:+ due_tasks.append(task)++ return due_tasks++ async def get_next_execution_time(self, account_id: Optional[str] = None) -> Optional[datetime]:+ async with self._lock:+ next_times: List[datetime] = []+ for task in self._tasks.values():+ if not task.is_active:+ continue+ if account_id and task.account_id != account_id:+ continue+ if task.next_execution_time is None:+ continue+ next_times.append(task.next_execution_time)+ return min(next_times) if next_times else None++ async def clear_all_tasks(self) -> int:+ """Clear all tasks (for testing purposes).++ Returns:+ Number of tasks cleared+ """+ async with self._lock:+ count = len(self._tasks)+ self._tasks.clear()+ self._uri_to_task.clear()++ await self._save_tasks()++ logger.info(f"[WatchManager] Cleared {count} tasks")+ return countdiff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.pynew file mode 100644index 000000000..7ea902377--- /dev/null+++ b/openviking/resource/watch_scheduler.py@@ -0,0 +1,350 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""+Resource watch scheduler.++Provides scheduled task execution for watch tasks.+"""++import asyncio+from datetime import datetime+from typing import Any, Optional, Set++from openviking.resource.watch_manager import WatchManager+from openviking.server.identity import RequestContext, Role+from openviking.service.resource_service import ResourceService+from openviking_cli.utils import get_logger++logger = get_logger(__name__)+++class WatchScheduler:+ """Scheduled task scheduler for resource watch tasks.++ Periodically checks for due tasks and executes them by calling ResourceService.+ Implements concurrency control to skip tasks that are already executing.+ Handles execution failures gracefully without affecting next scheduling.+ Manages the lifecycle of WatchManager internally.+ """++ DEFAULT_CHECK_INTERVAL = 60.0++ def __init__(+ self,+ resource_service: ResourceService,+ viking_fs: Optional[Any] = None,+ check_interval: float = DEFAULT_CHECK_INTERVAL,+ max_concurrency: int = 4,+ ):+ """Initialize WatchScheduler.++ Args:+ resource_service: ResourceService instance for executing tasks+ viking_fs: VikingFS instance for WatchManager persistence (optional)+ check_interval: Interval in seconds between scheduler checks (default: 60)+ """+ self._resource_service = resource_service+ self._viking_fs = viking_fs+ if check_interval <= 0:+ raise ValueError("check_interval must be > 0")+ if max_concurrency <= 0:+ raise ValueError("max_concurrency must be > 0")+ self._check_interval = check_interval+ self._max_concurrency = max_concurrency+ self._semaphore = asyncio.Semaphore(max_concurrency)++ self._watch_manager: Optional[WatchManager] = None+ self._running = False+ self._scheduler_task: Optional[asyncio.Task] = None+ self._executing_tasks: Set[str] = set()+ self._lock = asyncio.Lock()++ @property+ def watch_manager(self) -> Optional[WatchManager]:+ """Get the WatchManager instance."""+ return self._watch_manager++ async def start(self) -> None:+ """Start the scheduler.++ Creates a background task that periodically checks for due tasks.+ Initializes the WatchManager and loads persisted tasks.+ """+ if self._running:+ logger.warning("[WatchScheduler] Scheduler is already running")+ return++ # Initialize WatchManager+ self._watch_manager = WatchManager(viking_fs=self._viking_fs)+ await self._watch_manager.initialize()+ logger.info("[WatchScheduler] WatchManager initialized")++ self._running = True+ self._scheduler_task = asyncio.create_task(self._run_scheduler())+ logger.info(f"[WatchScheduler] Started with check interval {self._check_interval}s")++ async def stop(self) -> None:+ """Stop the scheduler.++ Cancels the background task and waits for it to complete.+ Cleans up the WatchManager.+ """+ if not self._running:+ logger.warning("[WatchScheduler] Scheduler is not running")+ return++ self._running = False++ if self._scheduler_task:+ self._scheduler_task.cancel()+ try:+ await self._scheduler_task+ except asyncio.CancelledError:+ pass+ self._scheduler_task = None++ # Clean up WatchManager+ if self._watch_manager:+ self._watch_manager = None+ logger.info("[WatchScheduler] WatchManager cleaned up")++ logger.info("[WatchScheduler] Stopped")++ async def schedule_task(self, task_id: str) -> bool:+ """Schedule a single task for immediate execution.++ Args:+ task_id: ID of the task to schedule++ Returns:+ True if task was scheduled, False if task is already executing or not found+ """+ if not self._watch_manager:+ logger.warning("[WatchScheduler] WatchManager is not initialized")+ return False++ task = await self._watch_manager.get_task(task_id)+ if not task:+ logger.warning(f"[WatchScheduler] Task {task_id} not found")+ return False++ if not await self._try_mark_executing(task_id):+ logger.info(f"[WatchScheduler] Task {task_id} is already executing, skipping")+ return False++ try:+ async with self._semaphore:+ await self._execute_task(task)+ return True+ finally:+ await asyncio.shield(self._discard_executing(task_id))++ async def _run_scheduler(self) -> None:+ """Background task loop that periodically checks and executes due tasks.++ This method runs continuously until the scheduler is stopped.+ """+ logger.info("[WatchScheduler] Scheduler loop started")++ while self._running:+ try:+ await self._check_and_execute_due_tasks()+ except Exception as e:+ logger.error(f"[WatchScheduler] Error in scheduler loop: {e}", exc_info=True)++ try:+ sleep_seconds = self._check_interval+ if self._watch_manager:+ next_time = await self._watch_manager.get_next_execution_time()+ if next_time is not None:+ now = datetime.now()+ sleep_seconds = min(+ self._check_interval,+ max(0.0, (next_time - now).total_seconds()),+ )+ await asyncio.sleep(sleep_seconds)+ except asyncio.CancelledError:+ break++ logger.info("[WatchScheduler] Scheduler loop ended")++ async def _check_and_execute_due_tasks(self) -> None:+ """Check for due tasks and execute them.++ This method is called periodically by the scheduler loop.+ """+ if not self._watch_manager:+ return++ due_tasks = await self._watch_manager.get_due_tasks()++ if not due_tasks:+ return++ logger.info(f"[WatchScheduler] Found {len(due_tasks)} due tasks")++ tasks_to_run = []+ for task in due_tasks:+ if not await self._try_mark_executing(task.task_id):+ logger.info(f"[WatchScheduler] Task {task.task_id} is already executing, skipping")+ continue+ tasks_to_run.append(task)++ async def run_one(t) -> None:+ try:+ async with self._semaphore:+ await self._execute_task(t)+ finally:+ await asyncio.shield(self._discard_executing(t.task_id))++ if tasks_to_run:+ await asyncio.gather(*(asyncio.create_task(run_one(t)) for t in tasks_to_run))++ async def _execute_task(self, task) -> None:+ """Execute a single watch task.++ Calls ResourceService.add_resource to process the resource.+ Handles errors gracefully and updates execution time regardless of success/failure.+ Deactivates tasks when resources no longer exist.++ Args:+ task: WatchTask to execute+ """+ logger.info(f"[WatchScheduler] Executing task {task.task_id} for path {task.path}")++ cancelled = False+ should_deactivate = False+ deactivation_reason = ""++ try:+ if not self._check_resource_exists(task.path):+ should_deactivate = True+ deactivation_reason = f"Resource path does not exist: {task.path}"+ logger.warning(+ f"[WatchScheduler] Task {task.task_id}: {deactivation_reason}. "+ "Deactivating task."+ )+ else:+ from openviking_cli.session.user_id import UserIdentifier++ user = UserIdentifier(+ account_id=task.account_id,+ user_id=task.user_id,+ agent_id=task.agent_id,+ )+ role_value = getattr(task, "original_role", None) or Role.USER.value+ try:+ role = Role(role_value)+ except Exception:+ role = Role.USER+ ctx = RequestContext(+ user=user,+ role=role,+ )++ processor_kwargs = dict(getattr(task, "processor_kwargs", {}) or {})+ processor_kwargs.pop("build_index", None)+ processor_kwargs.pop("summarize", None)+ result = await self._resource_service.add_resource(+ path=task.path,+ ctx=ctx,+ to=task.to_uri,+ parent=task.parent_uri,+ reason=task.reason,+ instruction=task.instruction,+ build_index=getattr(task, "build_index", True),+ summarize=getattr(task, "summarize", False),+ watch_interval=task.watch_interval,+ skip_watch_management=True,+ **processor_kwargs,+ )++ logger.info(+ f"[WatchScheduler] Task {task.task_id} executed successfully, "+ f"result: {result.get('root_uri', 'N/A')}"+ )++ except asyncio.CancelledError:+ cancelled = True+ raise+ except FileNotFoundError as e:+ should_deactivate = True+ deactivation_reason = f"Resource not found: {e}"+ logger.error(+ f"[WatchScheduler] Task {task.task_id} resource not found: {e}. Deactivating task."+ )+ except Exception as e:+ logger.error(+ f"[WatchScheduler] Task {task.task_id} execution failed: {e}",+ exc_info=True,+ )++ finally:+ try:+ if not cancelled:+ if should_deactivate:+ await asyncio.shield(+ self._watch_manager.update_task(+ task_id=task.task_id,+ account_id=task.account_id,+ user_id=task.user_id,+ role=getattr(task, "original_role", None) or Role.USER.value,+ is_active=False,+ )+ )+ logger.info(+ f"[WatchScheduler] Deactivated task {task.task_id}: {deactivation_reason}"+ )+ else:+ await asyncio.shield(+ self._watch_manager.update_execution_time(task.task_id)+ )+ logger.info(+ f"[WatchScheduler] Updated execution time for task {task.task_id}"+ )+ except Exception as e:+ logger.error(+ f"[WatchScheduler] Failed to update task {task.task_id}: {e}",+ exc_info=True,+ )++ async def _try_mark_executing(self, task_id: str) -> bool:+ async with self._lock:+ if task_id in self._executing_tasks:+ return False+ self._executing_tasks.add(task_id)+ return True++ async def _discard_executing(self, task_id: str) -> None:+ async with self._lock:+ self._executing_tasks.discard(task_id)++ def _check_resource_exists(self, path: str) -> bool:+ """Check if a resource path exists.++ Args:+ path: Resource path to check++ Returns:+ True if resource exists or is a URL, False otherwise+ """+ if path.startswith(("http://", "https://", "git@", "ssh://", "git://")):+ return True++ from pathlib import Path++ try:+ return Path(path).exists()+ except Exception as e:+ logger.warning(f"[WatchScheduler] Failed to check path existence {path}: {e}")+ return False++ @property+ def is_running(self) -> bool:+ """Check if the scheduler is running."""+ return self._running++ @property+ def executing_tasks(self) -> Set[str]:+ """Get the set of currently executing task IDs."""+ return self._executing_tasks.copy()diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.pyindex 254d291bd..c2fcccf64 100644--- a/openviking/server/routers/resources.py+++ b/openviking/server/routers/resources.py@@ -23,7 +23,39 @@ router = APIRouter(prefix="/api/v1", tags=["resources"])class AddResourceRequest(BaseModel):- """Request model for add_resource."""+ """Request model for add_resource.++ Attributes:+ path: Resource path (local file path or URL). Either path or temp_path must be provided.+ temp_path: Temporary file path for uploaded files. Either path or temp_path must be provided.+ to: Target URI for the resource (e.g., "viking://resources/my_resource").+ If not specified, an auto-generated URI will be used.+ parent: Parent URI under which the resource will be stored.+ Cannot be used together with 'to'.+ reason: Reason for adding the resource. Used for documentation and monitoring.+ instruction: Processing instruction for semantic extraction.+ Provides hints for how the resource should be processed.+ wait: Whether to wait for semantic extraction and vectorization to complete.+ Default is False (async processing).+ timeout: Timeout in seconds when wait=True. None means no timeout.+ strict: Whether to use strict mode for processing. Default is True.+ ignore_dirs: Comma-separated list of directory names to ignore during parsing.+ include: Glob pattern for files to include during parsing.+ exclude: Glob pattern for files to exclude during parsing.+ directly_upload_media: Whether to directly upload media files. Default is True.+ preserve_structure: Whether to preserve directory structure when adding directories.+ watch_interval: Watch interval in minutes for automatic resource monitoring.+ - watch_interval > 0: Creates or updates a watch task. The resource will be+ automatically re-processed at the specified interval.+ - watch_interval = 0: No watch task is created. If a watch task exists for+ this resource, it will be cancelled (deactivated).+ - watch_interval < 0: Same as watch_interval = 0, cancels any existing watch task.+ Default is 0 (no monitoring).++ Note: If the target URI already has an active watch task, a ConflictError will be+ raised. You must first cancel the existing watch (set watch_interval <= 0) before+ creating a new one.+ """path: Optional[str] = Nonetemp_path: Optional[str] = None@@ -40,6 +72,7 @@ class AddResourceRequest(BaseModel):directly_upload_media: bool = Truepreserve_structure: Optional[bool] = Nonetelemetry: TelemetryRequest = False+ watch_interval: float = 0@model_validator(mode="after")def check_path_or_temp_path(self):@@ -118,6 +151,7 @@ async def add_resource("include": request.include,"exclude": request.exclude,"directly_upload_media": request.directly_upload_media,+ "watch_interval": request.watch_interval,}if request.preserve_structure is not None:kwargs["preserve_structure"] = request.preserve_structurediff --git a/openviking/service/core.py b/openviking/service/core.pyindex d25830eaa..8a4ec618d 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -11,6 +11,7 @@ from typing import Any, Optionalfrom openviking.agfs_manager import AGFSManagerfrom openviking.core.directories import DirectoryInitializer+from openviking.resource.watch_scheduler import WatchSchedulerfrom openviking.server.identity import RequestContext, Rolefrom openviking.service.debug_service import DebugServicefrom openviking.service.fs_service import FSService@@ -77,6 +78,7 @@ class OpenVikingService:self._session_compressor: Optional[SessionCompressor] = Noneself._lock_manager: Optional[LockManager] = Noneself._directory_initializer: Optional[DirectoryInitializer] = None+ self._watch_scheduler: Optional[WatchScheduler] = None# Sub-servicesself._fs_service = FSService()@@ -177,6 +179,11 @@ class OpenVikingService:"""Get SessionCompressor instance."""return self._session_compressor+ @property+ def watch_scheduler(self) -> Optional[WatchScheduler]:+ """Get WatchScheduler instance."""+ return self._watch_scheduler+@propertydef fs(self) -> FSService:"""Get FSService instance."""@@ -296,6 +303,13 @@ class OpenVikingService:await self._lock_manager.start()logger.info("LockManager started")+ self._watch_scheduler = WatchScheduler(+ resource_service=self._resource_service,+ viking_fs=self._viking_fs,+ )+ await self._watch_scheduler.start()+ logger.info("WatchScheduler started")+# Wire up sub-servicesself._fs_service.set_viking_fs(self._viking_fs)self._relation_service.set_viking_fs(self._viking_fs)@@ -306,6 +320,7 @@ class OpenVikingService:viking_fs=self._viking_fs,resource_processor=self._resource_processor,skill_processor=self._skill_processor,+ watch_scheduler=self._watch_scheduler,)self._session_service.set_dependencies(vikingdb=self._vikingdb_manager,@@ -322,6 +337,11 @@ class OpenVikingService:async def close(self) -> None:"""Close OpenViking and release resources."""+ if self._watch_scheduler:+ await self._watch_scheduler.stop()+ self._watch_scheduler = None+ logger.info("WatchScheduler stopped")+if self._lock_manager:await self._lock_manager.stop()self._lock_manager = Nonediff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 44b0b6b82..d41942bcd 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -6,8 +6,9 @@ Resource Service for OpenViking.Provides resource management operations: add_resource, add_skill, wait_processed."""+import jsonimport time-from typing import Any, Dict, List, Optional+from typing import TYPE_CHECKING, Any, Dict, List, Optionalfrom openviking.server.identity import RequestContextfrom openviking.storage import VikingDBManager@@ -23,6 +24,7 @@ from openviking.telemetry.resource_summary import (from openviking.utils.resource_processor import ResourceProcessorfrom openviking.utils.skill_processor import SkillProcessorfrom openviking_cli.exceptions import (+ ConflictError,DeadlineExceededError,InvalidArgumentError,NotInitializedError,@@ -30,6 +32,10 @@ from openviking_cli.exceptions import (from openviking_cli.utils import get_loggerfrom openviking_cli.utils.uri import VikingURI+if TYPE_CHECKING:+ from openviking.resource.watch_manager import WatchManager+ from openviking.resource.watch_scheduler import WatchScheduler+logger = get_logger(__name__)@@ -42,11 +48,13 @@ class ResourceService:viking_fs: Optional[VikingFS] = None,resource_processor: Optional[ResourceProcessor] = None,skill_processor: Optional[SkillProcessor] = None,+ watch_scheduler: Optional["WatchScheduler"] = None,):self._vikingdb = vikingdbself._viking_fs = viking_fsself._resource_processor = resource_processorself._skill_processor = skill_processor+ self._watch_scheduler = watch_schedulerdef set_dependencies(self,@@ -54,12 +62,29 @@ class ResourceService:viking_fs: VikingFS,resource_processor: ResourceProcessor,skill_processor: SkillProcessor,+ watch_scheduler: Optional["WatchScheduler"] = None,) -> None:"""Set dependencies (for deferred initialization)."""self._vikingdb = vikingdbself._viking_fs = viking_fsself._resource_processor = resource_processorself._skill_processor = skill_processor+ self._watch_scheduler = watch_scheduler++ def _get_watch_manager(self) -> Optional["WatchManager"]:+ if not self._watch_scheduler:+ return None+ return self._watch_scheduler.watch_manager++ def _sanitize_watch_processor_kwargs(self, processor_kwargs: Dict[str, Any]) -> Dict[str, Any]:+ sanitized: Dict[str, Any] = {}+ for key, value in processor_kwargs.items():+ try:+ json.dumps(value, ensure_ascii=False)+ except TypeError:+ continue+ sanitized[key] = value+ return sanitizeddef _ensure_initialized(self) -> None:"""Ensure all dependencies are initialized."""@@ -82,23 +107,43 @@ class ResourceService:timeout: Optional[float] = None,build_index: bool = True,summarize: bool = False,+ watch_interval: float = 0,+ skip_watch_management: bool = False,**kwargs,) -> Dict[str, Any]:"""Add resource to OpenViking (only supports resources scope).Args:path: Resource path (local file or URL)- target: Target URI- reason: Reason for adding- instruction: Processing instruction+ to: Target URI (e.g., "viking://resources/my_resource")+ parent: Parent URI under which the resource will be stored+ reason: Reason for adding the resource+ instruction: Processing instruction for semantic extractionwait: Whether to wait for semantic extraction and vectorization to completetimeout: Wait timeout in seconds- build_index: Whether to build vector index immediately (default: True).- summarize: Whether to generate summary (default: False).- **kwargs: Extra options forwarded to the parser chain.+ build_index: Whether to build vector index immediately (default: True)+ summarize: Whether to generate summary (default: False)+ watch_interval: Watch interval in minutes for automatic resource monitoring.+ - watch_interval > 0: Creates or updates a watch task. The resource will be+ automatically re-processed at the specified interval by the scheduler.+ - watch_interval = 0: No watch task is created. If a watch task exists for+ this resource, it will be cancelled (deactivated).+ - watch_interval < 0: Same as watch_interval = 0, cancels any existing watch task.+ Default is 0 (no monitoring).++ Note: If the target URI already has an active watch task, a ConflictError will be+ raised. You must first cancel the existing watch (set watch_interval <= 0) before+ creating a new one.+ skip_watch_management: If True, skip watch task management (used by scheduler to+ avoid recursive watch task creation during scheduled execution)+ **kwargs: Extra options forwarded to the parser chainReturns:- Processing result+ Processing result containing 'root_uri' and other metadata++ Raises:+ ConflictError: If the target URI already has an active watch task+ InvalidArgumentError: If the URI scope is not 'resources'"""self._ensure_initialized()request_start = time.perf_counter()@@ -118,6 +163,11 @@ class ResourceService:raise InvalidArgumentError(f"add_resource only supports resources scope, use dedicated interface to add {parsed.scope} content")+ watch_manager = self._get_watch_manager()+ if watch_manager and not skip_watch_management and watch_interval > 0 and not to:+ raise InvalidArgumentError(+ "watch_interval > 0 requires 'to' to be specified (target URI to watch)"+ )result = await self._resource_processor.process_resource(path=path,@@ -152,6 +202,35 @@ class ResourceService:root_uri=result.get("root_uri"),)get_current_telemetry().set("queue.wait.duration_ms", queue_wait_duration_ms)+ if watch_manager and to and not skip_watch_management:+ if watch_interval > 0:+ try:+ processor_kwargs = self._sanitize_watch_processor_kwargs(kwargs)+ await self._handle_watch_task_creation(+ path=path,+ to_uri=to,+ parent_uri=parent,+ reason=reason,+ instruction=instruction,+ watch_interval=watch_interval,+ build_index=build_index,+ summarize=summarize,+ processor_kwargs=processor_kwargs,+ ctx=ctx,+ )+ except ConflictError:+ raise+ except Exception as e:+ logger.warning(+ f"[ResourceService] Failed to create watch task for {to}: {e}"+ )+ else:+ try:+ await self._handle_watch_task_cancellation(to_uri=to, ctx=ctx)+ except Exception as e:+ logger.warning(+ f"[ResourceService] Failed to cancel watch task for {to}: {e}"+ )get_current_telemetry().set("resource.request.duration_ms",@@ -168,6 +247,116 @@ class ResourceService:finally:unregister_wait_telemetry(telemetry_id)+ async def _handle_watch_task_creation(+ self,+ path: str,+ to_uri: str,+ parent_uri: Optional[str],+ reason: str,+ instruction: str,+ watch_interval: float,+ build_index: bool,+ summarize: bool,+ processor_kwargs: Dict[str, Any],+ ctx: RequestContext,+ ) -> None:+ """Handle creation or update of watch task.++ Args:+ path: Resource path to monitor+ to_uri: Target URI+ parent_uri: Parent URI+ reason: Reason for monitoring+ instruction: Monitoring instruction+ watch_interval: Monitoring interval in minutes+ ctx: Request context with user identity++ Raises:+ ConflictError: If target URI is already used by another active task+ """+ watch_manager = self._get_watch_manager()+ if not watch_manager:+ return++ existing_task = await watch_manager.get_task_by_uri(+ to_uri=to_uri,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ role=ctx.role.value,+ )+ if existing_task:+ if existing_task.is_active:+ raise ConflictError(+ f"Target URI '{to_uri}' is already being monitored by task {existing_task.task_id}. "+ f"Please cancel the existing task first.",+ resource=to_uri,+ )+ await watch_manager.update_task(+ task_id=existing_task.task_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ role=ctx.role.value,+ path=path,+ to_uri=to_uri,+ parent_uri=parent_uri,+ reason=reason,+ instruction=instruction,+ watch_interval=watch_interval,+ build_index=build_index,+ summarize=summarize,+ processor_kwargs=processor_kwargs,+ is_active=True,+ )+ logger.info(+ f"[ResourceService] Reactivated and updated watch task {existing_task.task_id} for {to_uri}"+ )+ else:+ task = await watch_manager.create_task(+ path=path,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ agent_id=ctx.user.agent_id,+ original_role=ctx.role.value,+ to_uri=to_uri,+ parent_uri=parent_uri,+ reason=reason,+ instruction=instruction,+ watch_interval=watch_interval,+ build_index=build_index,+ summarize=summarize,+ processor_kwargs=processor_kwargs,+ )+ logger.info(f"[ResourceService] Created watch task {task.task_id} for {to_uri}")++ async def _handle_watch_task_cancellation(self, to_uri: str, ctx: RequestContext) -> None:+ """Handle cancellation of watch task.++ Args:+ to_uri: Target URI to cancel watch for+ ctx: Request context with user identity+ """+ watch_manager = self._get_watch_manager()+ if not watch_manager:+ return++ existing_task = await watch_manager.get_task_by_uri(+ to_uri=to_uri,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ role=ctx.role.value,+ )+ if existing_task:+ await watch_manager.update_task(+ task_id=existing_task.task_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ role=ctx.role.value,+ is_active=False,+ )+ logger.info(+ f"[ResourceService] Deactivated watch task {existing_task.task_id} for {to_uri}"+ )+async def add_skill(self,data: Any,diff --git a/openviking/storage/queuefs/embedding_tracker.py b/openviking/storage/queuefs/embedding_tracker.pyindex bfee27b79..a51af6455 100644--- a/openviking/storage/queuefs/embedding_tracker.py+++ b/openviking/storage/queuefs/embedding_tracker.py@@ -127,53 +127,3 @@ class EmbeddingTaskTracker:exc_info=True,)return remaining-- async def get_status(self, semantic_msg_id: str) -> Optional[Dict[str, Any]]:- """Get the current status of a SemanticMsg's embedding tasks.-- Args:- semantic_msg_id: The ID of the SemanticMsg-- Returns:- Dict with 'remaining', 'total', 'metadata' or None if not found- """- async with self._lock:- if semantic_msg_id not in self._tasks:- return None- task_info = self._tasks[semantic_msg_id]- return {- "remaining": task_info["remaining"],- "total": task_info["total"],- "metadata": task_info.get("metadata", {}),- }-- async def remove(self, semantic_msg_id: str) -> bool:- """Remove a SemanticMsg from the tracker.-- Args:- semantic_msg_id: The ID of the SemanticMsg-- Returns:- True if removed, False if not found- """- async with self._lock:- if semantic_msg_id in self._tasks:- del self._tasks[semantic_msg_id]- return True- return False-- async def get_all_tracked(self) -> Dict[str, Dict[str, Any]]:- """Get all currently tracked SemanticMsgs.-- Returns:- Dict of semantic_msg_id -> task info- """- async with self._lock:- return {- msg_id: {- "remaining": info["remaining"],- "total": info["total"],- "metadata": info.get("metadata", {}),- }- for msg_id, info in self._tasks.items()- }diff --git a/openviking/storage/queuefs/semantic_dag.py b/openviking/storage/queuefs/semantic_dag.pyindex d626fa820..79213f718 100644--- a/openviking/storage/queuefs/semantic_dag.py+++ b/openviking/storage/queuefs/semantic_dag.py@@ -102,62 +102,44 @@ class SemanticDagExecutor:self._overview_cache_lock = asyncio.Lock()self._refresh_task: Optional[asyncio.Task] = None- def _create_on_complete_callback(self) -> Optional[Callable[[], Awaitable[None]]]:+ def _create_on_complete_callback(self) -> Callable[[], Awaitable[None]]:"""Create on_complete callback for incremental update or full update."""- if not self._target_uri or not self._root_uri:- return None- if self._incremental_update:+ async def noop_callback() -> None:+ return- async def sync_diff_callback() -> None:- try:- diff = await self._processor._sync_topdown_recursive(- self._root_uri,- self._target_uri,- ctx=self._ctx,- file_change_status=self._file_change_status,- )- logger.info(- f"[SyncDiff] Diff computed: "- f"added_files={len(diff.added_files)}, "- f"deleted_files={len(diff.deleted_files)}, "- f"updated_files={len(diff.updated_files)}, "- f"added_dirs={len(diff.added_dirs)}, "- f"deleted_dirs={len(diff.deleted_dirs)}"- )- except Exception as e:- logger.error(- f"[SyncDiff] Error in sync_diff_callback: "- f"root_uri={self._root_uri}, target_uri={self._target_uri} "- f"error={e}",- exc_info=True,- )+ if not self._target_uri or not self._root_uri:+ return noop_callback- return sync_diff_callback- else:+ # If full update, move temp uri to target uri has been handled in the processor+ if not self._incremental_update:+ return noop_callback- async def move_temp_to_target_callback() -> None:- try:- target_exists = await self._viking_fs.exists(self._target_uri, ctx=self._ctx)- if target_exists:- await self._viking_fs.rm(self._target_uri, recursive=True, ctx=self._ctx)- parent_uri = "/".join(self._target_uri.rsplit("/", 1)[:-1])- if parent_uri:- await self._viking_fs.mkdir(parent_uri, exist_ok=True, ctx=self._ctx)- await self._viking_fs.mv(self._root_uri, self._target_uri, ctx=self._ctx)- logger.info(- f"[MoveTemp] Moved temp uri to target uri: "- f"root_uri={self._root_uri}, target_uri={self._target_uri}"- )- except Exception as e:- logger.error(- f"[MoveTemp] Error moving temp uri to target uri: "- f"root_uri={self._root_uri}, target_uri={self._target_uri} "- f"error={e}",- exc_info=True,- )+ async def sync_diff_callback() -> None:+ try:+ diff = await self._processor._sync_topdown_recursive(+ self._root_uri,+ self._target_uri,+ ctx=self._ctx,+ file_change_status=self._file_change_status,+ )+ logger.info(+ f"[SyncDiff] Diff computed: "+ f"added_files={len(diff.added_files)}, "+ f"deleted_files={len(diff.deleted_files)}, "+ f"updated_files={len(diff.updated_files)}, "+ f"added_dirs={len(diff.added_dirs)}, "+ f"deleted_dirs={len(diff.deleted_dirs)}"+ )+ except Exception as e:+ logger.error(+ f"[SyncDiff] Error in sync_diff_callback: "+ f"root_uri={self._root_uri}, target_uri={self._target_uri} "+ f"error={e}",+ exc_info=True,+ )- return move_temp_to_target_callback+ return sync_diff_callbackasync def run(self, root_uri: str) -> None:"""Run DAG execution starting from root_uri."""@@ -327,6 +309,12 @@ class SemanticDagExecutor:if not target_path:return Truetry:+ current_stat = await self._viking_fs.stat(file_path, ctx=self._ctx)+ target_stat = await self._viking_fs.stat(target_path, ctx=self._ctx)+ current_size = current_stat.get("size") if isinstance(current_stat, dict) else None+ target_size = target_stat.get("size") if isinstance(target_stat, dict) else None+ if current_size is not None and target_size is not None and current_size != target_size:+ return Truecurrent_content = await self._viking_fs.read_file(file_path, ctx=self._ctx)target_content = await self._viking_fs.read_file(target_path, ctx=self._ctx)return current_content != target_contentdiff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.pyindex 98d32f7a1..2b92b73b9 100644--- a/openviking/storage/queuefs/semantic_processor.py+++ b/openviking/storage/queuefs/semantic_processor.py@@ -192,6 +192,12 @@ class SemanticProcessor(DequeueHandlerBase):"""Check if file content has changed compared to target file."""viking_fs = get_viking_fs()try:+ current_stat = await viking_fs.stat(file_path, ctx=ctx)+ target_stat = await viking_fs.stat(target_file, ctx=ctx)+ current_size = current_stat.get("size") if isinstance(current_stat, dict) else None+ target_size = target_stat.get("size") if isinstance(target_stat, dict) else None+ if current_size is not None and target_size is not None and current_size != target_size:+ return Truecurrent_content = await viking_fs.read_file(file_path, ctx=ctx)target_content = await viking_fs.read_file(target_file, ctx=ctx)return current_content != target_content@@ -233,7 +239,8 @@ class SemanticProcessor(DequeueHandlerBase):target_exists = await viking_fs.exists(msg.target_uri, ctx=self._current_ctx)- if target_exists:+ # Check if target URI exists and is not the same as the source URI(避免重复处理)+ if target_exists and msg.uri != msg.target_uri:is_incremental = Truelogger.info(f"Target URI exists, using incremental update: {msg.target_uri}"@@ -583,7 +590,7 @@ class SemanticProcessor(DequeueHandlerBase):await sync_dir(root_uri, target_uri)try:- await viking_fs.rm(root_uri, recursive=True, ctx=ctx)+ await viking_fs.delete_temp(root_uri, ctx=ctx)except Exception as e:logger.error(f"[SyncDiff] Failed to delete root directory {root_uri}: {e}")return diffdiff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.pyindex adcb4245f..172fcd332 100644--- a/openviking/utils/resource_processor.py+++ b/openviking/utils/resource_processor.py@@ -175,7 +175,6 @@ class ResourceProcessor:# - temp_dir_path: Temporary directory path (Parser wrote all files)# - source_path, source_format- # ============ Phase 2: Pass to and parent directly to TreeBuilder ============# ============ Phase 3: TreeBuilder finalizes from temp (scan + move to AGFS) ============try:finalize_start = time.perf_counter()diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.pyindex 8eb8e3f30..972072d41 100644--- a/openviking_cli/client/base.py+++ b/openviking_cli/client/base.py@@ -41,6 +41,7 @@ class BaseClient(ABC):instruction: str = "",wait: bool = False,timeout: Optional[float] = None,+ watch_interval: float = 0,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add resource to OpenViking."""diff --git a/tests/client/test_resource_management.py b/tests/client/test_resource_management.pyindex f42ce1324..818427fea 100644--- a/tests/client/test_resource_management.py+++ b/tests/client/test_resource_management.py@@ -4,6 +4,7 @@"""Resource management tests"""from pathlib import Path+from unittest.mock import AsyncMock, patchfrom openviking import AsyncOpenViking@@ -93,3 +94,91 @@ class TestWaitProcessed:status = await client.wait_processed()assert isinstance(status, dict)+++class TestWatchIntervalParameter:+ """Test watch_interval parameter propagation"""++ async def test_watch_interval_default_value(+ self, client: AsyncOpenViking, sample_markdown_file: Path+ ):+ """Test that watch_interval defaults to 0"""+ with patch.object(+ client._client, "add_resource", new_callable=AsyncMock+ ) as mock_add_resource:+ mock_add_resource.return_value = {"root_uri": "viking://test"}++ await client.add_resource(path=str(sample_markdown_file), reason="Test")++ call_kwargs = mock_add_resource.call_args[1]+ assert call_kwargs.get("watch_interval") == 0++ async def test_watch_interval_custom_value(+ self, client: AsyncOpenViking, sample_markdown_file: Path+ ):+ """Test that custom watch_interval value is propagated"""+ with patch.object(+ client._client, "add_resource", new_callable=AsyncMock+ ) as mock_add_resource:+ mock_add_resource.return_value = {"root_uri": "viking://test"}++ await client.add_resource(+ path=str(sample_markdown_file),+ reason="Test",+ watch_interval=5.0,+ )++ call_kwargs = mock_add_resource.call_args[1]+ assert call_kwargs.get("watch_interval") == 5.0++ async def test_watch_interval_propagates_to_local_client(+ self, sample_markdown_file: Path, test_data_dir: Path+ ):+ """Test that watch_interval propagates from AsyncOpenViking to LocalClient"""+ from openviking.client import LocalClient++ with patch.object(LocalClient, "add_resource", new_callable=AsyncMock) as mock_add_resource:+ mock_add_resource.return_value = {"root_uri": "viking://test"}++ from openviking import AsyncOpenViking++ await AsyncOpenViking.reset()+ client = AsyncOpenViking(path=str(test_data_dir))+ await client.initialize()++ try:+ await client.add_resource(+ path=str(sample_markdown_file),+ reason="Test",+ watch_interval=10.0,+ )++ call_kwargs = mock_add_resource.call_args[1]+ assert call_kwargs.get("watch_interval") == 10.0+ finally:+ await client.close()+ await AsyncOpenViking.reset()++ async def test_watch_interval_zero_means_disabled(+ self, client: AsyncOpenViking, sample_markdown_file: Path+ ):+ """Test that watch_interval=0 means monitoring is disabled"""+ result = await client.add_resource(+ path=str(sample_markdown_file),+ reason="Test",+ watch_interval=0,+ )++ assert "root_uri" in result++ async def test_watch_interval_positive_value(+ self, client: AsyncOpenViking, sample_markdown_file: Path+ ):+ """Test that positive watch_interval value is accepted"""+ result = await client.add_resource(+ path=str(sample_markdown_file),+ reason="Test",+ watch_interval=2.5,+ )++ assert "root_uri" in resultdiff --git a/tests/integration/test_watch_e2e.py b/tests/integration/test_watch_e2e.pynew file mode 100644index 000000000..0babfb66a--- /dev/null+++ b/tests/integration/test_watch_e2e.py@@ -0,0 +1,495 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""End-to-end tests for resource watch functionality."""++import asyncio+import shutil+from pathlib import Path++import pytest+import pytest_asyncio++from openviking import AsyncOpenViking+from openviking.resource.watch_scheduler import WatchScheduler+from openviking.server.identity import RequestContext, Role+from openviking.service.resource_service import ResourceService+from openviking_cli.exceptions import ConflictError+from openviking_cli.session.user_id import UserIdentifier+++async def get_watch_task(client: AsyncOpenViking, to_uri: str):+ watch_manager = client._service.resources._watch_scheduler.watch_manager+ return await watch_manager.get_task_by_uri(+ to_uri=to_uri,+ account_id=client._service.user.account_id,+ user_id=client._service.user.user_id,+ role=Role.USER.value,+ )+++@pytest_asyncio.fixture(scope="function")+async def e2e_client(test_data_dir: Path):+ """End-to-end test client with watch support."""+ await AsyncOpenViking.reset()++ shutil.rmtree(test_data_dir, ignore_errors=True)+ test_data_dir.mkdir(parents=True, exist_ok=True)++ client = AsyncOpenViking(path=str(test_data_dir))+ await client.initialize()++ yield client++ await client.close()+ await AsyncOpenViking.reset()+++@pytest_asyncio.fixture(scope="function")+async def watch_test_file(temp_dir: Path) -> Path:+ """Create a test file for watch testing."""+ file_path = temp_dir / "watch_test.md"+ file_path.write_text(+ """# Watch Test Document++## Initial Content+This is the initial content for watch testing.++## Version+Version: 1.0+Last Updated: Initial+"""+ )+ return file_path+++class TestWatchE2EBasicFlow:+ """End-to-end tests for basic watch flow."""++ @pytest.mark.asyncio+ async def test_create_resource_with_watch(+ self, e2e_client: AsyncOpenViking, watch_test_file: Path+ ):+ """Test creating a resource with watch enabled."""+ client = e2e_client++ to_uri = "viking://resources/watch_e2e_test"++ result = await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ reason="E2E watch test",+ instruction="Monitor for changes",+ watch_interval=60.0,+ )++ assert result is not None+ assert "root_uri" in result+ assert result["root_uri"] == to_uri++ task = await get_watch_task(client, to_uri)+ assert task is not None+ assert task.is_active is True+ assert task.watch_interval == 60.0+ assert task.task_id is not None+ assert task.next_execution_time is not None++ @pytest.mark.asyncio+ async def test_query_watch_status(self, e2e_client: AsyncOpenViking, watch_test_file: Path):+ """Test querying watch status for resources."""+ client = e2e_client++ watched_uri = "viking://resources/watched_resource"+ unwatched_uri = "viking://resources/unwatched_resource"++ await client.add_resource(+ path=str(watch_test_file),+ to=watched_uri,+ watch_interval=30.0,+ )++ await client.add_resource(+ path=str(watch_test_file),+ to=unwatched_uri,+ watch_interval=0,+ )++ watched_task = await get_watch_task(client, watched_uri)+ assert watched_task is not None+ assert watched_task.is_active is True+ assert watched_task.watch_interval == 30.0++ unwatched_task = await get_watch_task(client, unwatched_uri)+ assert unwatched_task is None++ @pytest.mark.asyncio+ async def test_update_watch_interval(self, e2e_client: AsyncOpenViking, watch_test_file: Path):+ """Test updating watch interval."""+ client = e2e_client++ to_uri = "viking://resources/update_interval_test"++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=30.0,+ )++ task = await get_watch_task(client, to_uri)+ assert task is not None+ assert task.watch_interval == 30.0+ task_id = task.task_id++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=0,+ )++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=120.0,+ )++ task = await get_watch_task(client, to_uri)+ assert task is not None+ assert task.is_active is True+ assert task.watch_interval == 120.0+ assert task.task_id == task_id++ @pytest.mark.asyncio+ async def test_cancel_watch(self, e2e_client: AsyncOpenViking, watch_test_file: Path):+ """Test cancelling watch by setting interval to 0 or negative."""+ client = e2e_client++ to_uri = "viking://resources/cancel_test"++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=30.0,+ )++ task = await get_watch_task(client, to_uri)+ assert task is not None+ assert task.is_active is True++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=0,+ )++ task = await get_watch_task(client, to_uri)+ assert task is not None+ assert task.is_active is False+++class TestWatchE2EConflictDetection:+ """End-to-end tests for conflict detection."""++ @pytest.mark.asyncio+ async def test_conflict_when_active_watch_exists(+ self, e2e_client: AsyncOpenViking, watch_test_file: Path+ ):+ """Test that conflict is raised when trying to watch an already watched URI."""+ client = e2e_client++ to_uri = "viking://resources/conflict_test"++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=30.0,+ )++ with pytest.raises(ConflictError) as exc_info:+ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=60.0,+ )++ assert "already being monitored" in str(exc_info.value)+ assert to_uri in str(exc_info.value)++ @pytest.mark.asyncio+ async def test_reactivate_inactive_watch(+ self, e2e_client: AsyncOpenViking, watch_test_file: Path+ ):+ """Test reactivating an inactive watch task."""+ client = e2e_client++ to_uri = "viking://resources/reactivate_test"++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ reason="Initial reason",+ watch_interval=30.0,+ )++ task = await get_watch_task(client, to_uri)+ assert task is not None+ task_id = task.task_id++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ watch_interval=0,+ )++ task = await get_watch_task(client, to_uri)+ assert task is not None+ assert task.is_active is False++ await client.add_resource(+ path=str(watch_test_file),+ to=to_uri,+ reason="Reactivated reason",+ watch_interval=45.0,+ )++ task = await get_watch_task(client, to_uri)+ assert task is not None+ assert task.is_active is True+ assert task.watch_interval == 45.0+ assert task.task_id == task_id+++class TestWatchE2ESchedulerExecution:+ """End-to-end tests for scheduler execution."""++ @pytest.mark.asyncio+ async def test_scheduler_executes_watch_task(self, temp_dir: Path, watch_test_file: Path):+ """Test that scheduler executes watch tasks on schedule."""+ execution_count = 0++ class MockResourceProcessor:+ async def process_resource(self, **kwargs):+ nonlocal execution_count+ execution_count += 1+ return {"root_uri": kwargs.get("to", "viking://resources/test")}++ class MockSkillProcessor:+ async def process_skill(self, **kwargs):+ return {"status": "ok"}++ class MockVikingDB:+ pass++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=object(),+ resource_processor=MockResourceProcessor(),+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )+ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ check_interval=0.1,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ task = await watch_manager.create_task(+ path=str(watch_test_file),+ to_uri="viking://resources/scheduler_test",+ reason="Scheduler test",+ watch_interval=0.002,+ )++ assert task.is_active is True++ await asyncio.sleep(0.3)++ await scheduler.stop()++ assert execution_count >= 1++ await watch_manager.clear_all_tasks()++ @pytest.mark.asyncio+ async def test_scheduler_updates_execution_time(self, temp_dir: Path, watch_test_file: Path):+ """Test that scheduler updates execution time after task execution."""++ class MockResourceProcessor:+ async def process_resource(self, **kwargs):+ return {"root_uri": kwargs.get("to", "viking://resources/test")}++ class MockSkillProcessor:+ async def process_skill(self, **kwargs):+ return {"status": "ok"}++ class MockVikingDB:+ pass++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=object(),+ resource_processor=MockResourceProcessor(),+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ check_interval=0.1,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ task = await watch_manager.create_task(+ path=str(watch_test_file),+ to_uri="viking://resources/execution_time_test",+ reason="Execution time test",+ watch_interval=0.002,+ )++ assert task.last_execution_time is None++ await asyncio.sleep(0.3)++ await scheduler.stop()++ updated_task = await watch_manager.get_task(task.task_id)+ assert updated_task is not None+ assert updated_task.last_execution_time is not None+ assert updated_task.next_execution_time is not None+ assert updated_task.next_execution_time > updated_task.last_execution_time++ await watch_manager.clear_all_tasks()+++class TestWatchE2EMultipleResources:+ """End-to-end tests for multiple resources."""++ @pytest.mark.asyncio+ async def test_multiple_watched_resources(+ self, e2e_client: AsyncOpenViking, watch_test_file: Path+ ):+ """Test managing multiple watched resources."""+ client = e2e_client++ uris = [+ "viking://resources/multi_test_1",+ "viking://resources/multi_test_2",+ "viking://resources/multi_test_3",+ ]++ intervals = [30.0, 60.0, 120.0]++ for uri, interval in zip(uris, intervals):+ await client.add_resource(+ path=str(watch_test_file),+ to=uri,+ watch_interval=interval,+ )++ for uri, expected_interval in zip(uris, intervals):+ task = await get_watch_task(client, uri)+ assert task is not None+ assert task.is_active is True+ assert task.watch_interval == expected_interval++ for uri in uris:+ await client.add_resource(+ path=str(watch_test_file),+ to=uri,+ watch_interval=0,+ )++ for uri in uris:+ task = await get_watch_task(client, uri)+ assert task is not None+ assert task.is_active is False++ @pytest.mark.asyncio+ async def test_independent_watch_tasks(+ self, e2e_client: AsyncOpenViking, watch_test_file: Path+ ):+ """Test that watch tasks are independent."""+ client = e2e_client++ uri1 = "viking://resources/independent_1"+ uri2 = "viking://resources/independent_2"++ await client.add_resource(+ path=str(watch_test_file),+ to=uri1,+ watch_interval=30.0,+ )++ await client.add_resource(+ path=str(watch_test_file),+ to=uri2,+ watch_interval=60.0,+ )++ task1 = await get_watch_task(client, uri1)+ task2 = await get_watch_task(client, uri2)+ assert task1 is not None+ assert task2 is not None+ assert task1.task_id != task2.task_id++ await client.add_resource(+ path=str(watch_test_file),+ to=uri1,+ watch_interval=0,+ )++ task1_after = await get_watch_task(client, uri1)+ task2_after = await get_watch_task(client, uri2)+ assert task1_after is not None+ assert task1_after.is_active is False+ assert task2_after is not None+ assert task2_after.is_active is True+++class TestWatchE2EErrorHandling:+ """End-to-end tests for error handling."""++ @pytest.mark.asyncio+ async def test_watch_without_watch_manager(self, temp_dir: Path, watch_test_file: Path):+ """Test that resource can be added without watch manager."""++ class MockResourceProcessor:+ async def process_resource(self, **kwargs):+ return {"root_uri": kwargs.get("to", "viking://resources/test")}++ class MockSkillProcessor:+ async def process_skill(self, **kwargs):+ return {"status": "ok"}++ resource_service = ResourceService(+ vikingdb=object(),+ viking_fs=object(),+ resource_processor=MockResourceProcessor(),+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ ctx = RequestContext(+ user=UserIdentifier("test_account", "test_user", "test_agent"),+ role=Role.USER,+ )++ result = await resource_service.add_resource(+ path=str(watch_test_file),+ ctx=ctx,+ to="viking://resources/no_watch_test",+ watch_interval=30.0,+ )++ assert result is not None+ assert "root_uri" in result++ @pytest.mark.asyncio+ async def test_watch_task_nonexistent_resource(self, e2e_client: AsyncOpenViking):+ client = e2e_client+ task = await get_watch_task(client, "viking://resources/nonexistent")+ assert task is Nonediff --git a/tests/misc/test_resource_processor_mv.py b/tests/misc/test_resource_processor_mv.pynew file mode 100644index 000000000..beb74029f--- /dev/null+++ b/tests/misc/test_resource_processor_mv.py@@ -0,0 +1,85 @@+import os+import sys+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+++class _DummyVikingDB:+ def get_embedder(self):+ return None+++class _DummyTelemetry:+ def set(self, *args, **kwargs):+ return None++ def set_error(self, *args, **kwargs):+ return None+++class _CtxMgr:+ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc, tb):+ return False+++class _FakeVikingFS:+ def __init__(self):+ self.agfs = SimpleNamespace(mv=MagicMock(return_value={"status": "ok"}))++ def bind_request_context(self, ctx):+ return _CtxMgr()++ async def exists(self, uri, ctx=None):+ return False++ async def mkdir(self, uri, exist_ok=False, ctx=None):+ return None++ async def delete_temp(self, temp_dir_path, ctx=None):+ return None++ def _uri_to_path(self, uri, ctx=None):+ return f"/mock/{uri.replace('viking://', '')}"+++async def test_resource_processor_first_add_persist_does_not_await_agfs_mv(monkeypatch):+ from openviking.utils.resource_processor import ResourceProcessor++ fake_fs = _FakeVikingFS()++ monkeypatch.setattr(+ "openviking.utils.resource_processor.get_current_telemetry",+ lambda: _DummyTelemetry(),+ )+ monkeypatch.setattr("openviking.utils.resource_processor.get_viking_fs", lambda: fake_fs)++ rp = ResourceProcessor(vikingdb=_DummyVikingDB(), media_storage=None)+ rp._get_media_processor = MagicMock()+ rp._get_media_processor.return_value.process = AsyncMock(+ return_value=SimpleNamespace(+ temp_dir_path="viking://temp/tmpdir",+ source_path="x",+ source_format="text",+ meta={},+ warnings=[],+ )+ )++ context_tree = SimpleNamespace(+ root=SimpleNamespace(uri="viking://resources/root", temp_uri="viking://temp/root_tmp")+ )+ rp.tree_builder.finalize_from_temp = AsyncMock(return_value=context_tree)++ result = await rp.process_resource(path="x", ctx=object(), build_index=False, summarize=False)++ assert result["status"] == "success"+ assert result["root_uri"] == "viking://resources/root"+ fake_fs.agfs.mv.assert_called_once()diff --git a/tests/resource/__init__.py b/tests/resource/__init__.pynew file mode 100644index 000000000..f05613572--- /dev/null+++ b/tests/resource/__init__.py@@ -0,0 +1,3 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""Tests for resource monitoring module."""diff --git a/tests/resource/test_watch_manager.py b/tests/resource/test_watch_manager.pynew file mode 100644index 000000000..f62520457--- /dev/null+++ b/tests/resource/test_watch_manager.py@@ -0,0 +1,689 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""Unit tests for WatchManager."""++import asyncio+import json+from datetime import datetime, timedelta+from pathlib import Path+from typing import AsyncGenerator++import pytest+import pytest_asyncio++from openviking.resource.watch_manager import WatchManager, WatchTask+from openviking_cli.exceptions import ConflictError+from tests.utils.mock_agfs import MockLocalAGFS++TEST_ACCOUNT_ID = "default"+TEST_USER_ID = "default"+TEST_ROLE = "ROOT"+++class MockVikingFS:+ """Mock VikingFS for testing."""++ def __init__(self, root_path: str):+ self.agfs = MockLocalAGFS(root_path=root_path)+ self._storage_data = {}++ async def read_file(self, uri: str, ctx=None) -> str:+ """Read file from storage."""+ path = self._uri_to_path(uri)+ content = self.agfs.read(path)+ if isinstance(content, bytes):+ return content.decode("utf-8")+ return content++ async def write_file(self, uri: str, content: str, ctx=None) -> None:+ """Write file to storage."""+ path = self._uri_to_path(uri)+ self.agfs.write(path, content.encode("utf-8"))++ def _uri_to_path(self, uri: str) -> str:+ """Convert URI to path."""+ if uri.startswith("viking://"):+ return uri.replace("viking://", "/local/default/")+ return uri+++@pytest_asyncio.fixture+async def temp_storage(tmp_path: Path) -> AsyncGenerator[Path, None]:+ """Create temporary storage directory."""+ storage_dir = tmp_path / "watch_storage"+ storage_dir.mkdir(parents=True, exist_ok=True)+ yield storage_dir+++@pytest_asyncio.fixture+async def mock_viking_fs(temp_storage: Path) -> MockVikingFS:+ """Create mock VikingFS instance."""+ return MockVikingFS(root_path=str(temp_storage))+++@pytest_asyncio.fixture+async def watch_manager(mock_viking_fs: MockVikingFS) -> AsyncGenerator[WatchManager, None]:+ """Create WatchManager instance with mock VikingFS."""+ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()+ yield manager+ await manager.clear_all_tasks()+++@pytest_asyncio.fixture+async def watch_manager_no_fs() -> AsyncGenerator[WatchManager, None]:+ """Create WatchManager instance without VikingFS."""+ manager = WatchManager(viking_fs=None)+ await manager.initialize()+ yield manager+ await manager.clear_all_tasks()+++class TestWatchTask:+ """Tests for WatchTask data model."""++ def test_create_task_with_defaults(self):+ """Test creating a task with default values."""+ task = WatchTask(path="/test/path")++ assert task.path == "/test/path"+ assert task.task_id is not None+ assert task.to_uri is None+ assert task.parent_uri is None+ assert task.reason == ""+ assert task.instruction == ""+ assert task.watch_interval == 60.0+ assert task.is_active is True+ assert task.created_at is not None+ assert task.last_execution_time is None+ assert task.next_execution_time is None++ def test_create_task_with_all_fields(self):+ """Test creating a task with all fields specified."""+ now = datetime.now()+ task = WatchTask(+ task_id="test-task-id",+ path="/test/path",+ to_uri="viking://resources/test",+ parent_uri="viking://resources",+ reason="Test reason",+ instruction="Test instruction",+ watch_interval=30.0,+ created_at=now,+ last_execution_time=now,+ next_execution_time=now + timedelta(minutes=30),+ is_active=False,+ )++ assert task.task_id == "test-task-id"+ assert task.path == "/test/path"+ assert task.to_uri == "viking://resources/test"+ assert task.parent_uri == "viking://resources"+ assert task.reason == "Test reason"+ assert task.instruction == "Test instruction"+ assert task.watch_interval == 30.0+ assert task.is_active is False+ assert task.created_at == now+ assert task.last_execution_time == now++ def test_to_dict(self):+ """Test converting task to dictionary."""+ now = datetime.now()+ task = WatchTask(+ task_id="test-id",+ path="/test/path",+ to_uri="viking://test",+ created_at=now,+ )++ data = task.to_dict()++ assert data["task_id"] == "test-id"+ assert data["path"] == "/test/path"+ assert data["to_uri"] == "viking://test"+ assert data["created_at"] == now.isoformat()+ assert data["is_active"] is True++ def test_from_dict(self):+ """Test creating task from dictionary."""+ now = datetime.now()+ data = {+ "task_id": "test-id",+ "path": "/test/path",+ "to_uri": "viking://test",+ "parent_uri": "viking://parent",+ "reason": "Test",+ "instruction": "Instruction",+ "watch_interval": 45.0,+ "created_at": now.isoformat(),+ "last_execution_time": now.isoformat(),+ "next_execution_time": (now + timedelta(minutes=45)).isoformat(),+ "is_active": False,+ }++ task = WatchTask.from_dict(data)++ assert task.task_id == "test-id"+ assert task.path == "/test/path"+ assert task.to_uri == "viking://test"+ assert task.watch_interval == 45.0+ assert task.is_active is False+ assert task.created_at == now+ assert task.last_execution_time == now++ def test_calculate_next_execution_time(self):+ """Test calculating next execution time."""+ now = datetime.now()+ task = WatchTask(+ path="/test",+ watch_interval=30.0,+ created_at=now,+ )++ next_time = task.calculate_next_execution_time()++ expected = now + timedelta(minutes=30.0)+ assert abs((next_time - expected).total_seconds()) < 1++ def test_calculate_next_execution_time_with_last_execution(self):+ """Test calculating next execution time based on last execution."""+ now = datetime.now()+ last_exec = now - timedelta(minutes=10)+ task = WatchTask(+ path="/test",+ watch_interval=30.0,+ created_at=now - timedelta(hours=1),+ last_execution_time=last_exec,+ )++ next_time = task.calculate_next_execution_time()++ expected = last_exec + timedelta(minutes=30.0)+ assert abs((next_time - expected).total_seconds()) < 1+++class TestWatchManager:+ """Tests for WatchManager."""++ @pytest.mark.asyncio+ async def test_create_task(self, watch_manager: WatchManager):+ """Test creating a task."""+ task = await watch_manager.create_task(+ path="/test/path",+ to_uri="viking://resources/test",+ reason="Test task",+ watch_interval=30.0,+ )++ assert task.path == "/test/path"+ assert task.to_uri == "viking://resources/test"+ assert task.reason == "Test task"+ assert task.watch_interval == 30.0+ assert task.is_active is True+ assert task.next_execution_time is not None++ @pytest.mark.asyncio+ async def test_create_task_without_path_raises(self, watch_manager: WatchManager):+ """Test that creating a task without path raises error."""+ with pytest.raises(ValueError, match="Path is required"):+ await watch_manager.create_task(path="")++ @pytest.mark.asyncio+ async def test_create_task_with_conflicting_uri(self, watch_manager: WatchManager):+ """Test that creating a task with conflicting URI raises error."""+ await watch_manager.create_task(+ path="/test/path1",+ to_uri="viking://resources/test",+ )++ with pytest.raises(ConflictError, match="already used by another task"):+ await watch_manager.create_task(+ path="/test/path2",+ to_uri="viking://resources/test",+ )++ @pytest.mark.asyncio+ async def test_update_task(self, watch_manager: WatchManager):+ """Test updating a task."""+ task = await watch_manager.create_task(+ path="/test/path",+ reason="Original reason",+ )++ updated = await watch_manager.update_task(+ task_id=task.task_id,+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ reason="Updated reason",+ watch_interval=45.0,+ is_active=False,+ )++ assert updated.reason == "Updated reason"+ assert updated.watch_interval == 45.0+ assert updated.is_active is False+ assert updated.next_execution_time is None++ @pytest.mark.asyncio+ async def test_update_task_not_found(self, watch_manager: WatchManager):+ """Test updating a non-existent task."""+ with pytest.raises(ValueError, match="not found"):+ await watch_manager.update_task(+ task_id="non-existent-id",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ reason="Updated",+ )++ @pytest.mark.asyncio+ async def test_update_task_with_conflicting_uri(self, watch_manager: WatchManager):+ """Test updating a task with conflicting URI."""+ await watch_manager.create_task(+ path="/test/path1",+ to_uri="viking://resources/test1",+ )+ task2 = await watch_manager.create_task(+ path="/test/path2",+ to_uri="viking://resources/test2",+ )++ with pytest.raises(ConflictError, match="already used by another task"):+ await watch_manager.update_task(+ task_id=task2.task_id,+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ to_uri="viking://resources/test1",+ )++ @pytest.mark.asyncio+ async def test_delete_task(self, watch_manager: WatchManager):+ """Test deleting a task."""+ task = await watch_manager.create_task(+ path="/test/path",+ to_uri="viking://resources/test",+ )++ result = await watch_manager.delete_task(+ task_id=task.task_id,+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )++ assert result is True++ retrieved = await watch_manager.get_task(task.task_id)+ assert retrieved is None++ uri_task = await watch_manager.get_task_by_uri(+ to_uri="viking://resources/test",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert uri_task is None++ @pytest.mark.asyncio+ async def test_delete_task_not_found(self, watch_manager: WatchManager):+ """Test deleting a non-existent task."""+ result = await watch_manager.delete_task(+ task_id="non-existent-id",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert result is False++ @pytest.mark.asyncio+ async def test_get_task(self, watch_manager: WatchManager):+ """Test getting a task by ID."""+ task = await watch_manager.create_task(path="/test/path")++ retrieved = await watch_manager.get_task(task.task_id)++ assert retrieved is not None+ assert retrieved.task_id == task.task_id+ assert retrieved.path == "/test/path"++ @pytest.mark.asyncio+ async def test_get_task_not_found(self, watch_manager: WatchManager):+ """Test getting a non-existent task."""+ retrieved = await watch_manager.get_task("non-existent-id")+ assert retrieved is None++ @pytest.mark.asyncio+ async def test_get_all_tasks(self, watch_manager: WatchManager):+ """Test getting all tasks."""+ await watch_manager.create_task(path="/test/path1")+ await watch_manager.create_task(path="/test/path2")+ await watch_manager.create_task(path="/test/path3")++ tasks = await watch_manager.get_all_tasks(+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )++ assert len(tasks) == 3++ @pytest.mark.asyncio+ async def test_get_all_tasks_active_only(self, watch_manager: WatchManager):+ """Test getting only active tasks."""+ task1 = await watch_manager.create_task(path="/test/path1")+ await watch_manager.create_task(path="/test/path2")++ await watch_manager.update_task(+ task_id=task1.task_id,+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ is_active=False,+ )++ tasks = await watch_manager.get_all_tasks(+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ active_only=True,+ )++ assert len(tasks) == 1+ assert tasks[0].is_active is True++ @pytest.mark.asyncio+ async def test_get_task_by_uri(self, watch_manager: WatchManager):+ """Test getting a task by URI."""+ task = await watch_manager.create_task(+ path="/test/path",+ to_uri="viking://resources/test",+ )++ retrieved = await watch_manager.get_task_by_uri(+ to_uri="viking://resources/test",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )++ assert retrieved is not None+ assert retrieved.task_id == task.task_id++ @pytest.mark.asyncio+ async def test_get_task_by_uri_not_found(self, watch_manager: WatchManager):+ """Test getting a task by non-existent URI."""+ retrieved = await watch_manager.get_task_by_uri(+ to_uri="viking://nonexistent",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert retrieved is None++ @pytest.mark.asyncio+ async def test_update_execution_time(self, watch_manager: WatchManager):+ """Test updating execution time."""+ task = await watch_manager.create_task(+ path="/test/path",+ watch_interval=30.0,+ )++ original_next_time = task.next_execution_time++ await asyncio.sleep(0.1)+ await watch_manager.update_execution_time(task.task_id)++ updated = await watch_manager.get_task(task.task_id)+ assert updated is not None+ assert updated.last_execution_time is not None+ assert updated.next_execution_time > original_next_time++ @pytest.mark.asyncio+ async def test_get_due_tasks(self, watch_manager: WatchManager):+ """Test getting due tasks."""+ task1 = await watch_manager.create_task(+ path="/test/path1",+ watch_interval=0.001,+ )+ await watch_manager.create_task(+ path="/test/path2",+ watch_interval=60.0,+ )++ await asyncio.sleep(0.1)++ due_tasks = await watch_manager.get_due_tasks()++ assert len(due_tasks) == 1+ assert due_tasks[0].task_id == task1.task_id++ @pytest.mark.asyncio+ async def test_clear_all_tasks(self, watch_manager: WatchManager):+ """Test clearing all tasks."""+ await watch_manager.create_task(path="/test/path1")+ await watch_manager.create_task(path="/test/path2")++ count = await watch_manager.clear_all_tasks()++ assert count == 2++ tasks = await watch_manager.get_all_tasks(+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert len(tasks) == 0++ @pytest.mark.asyncio+ async def test_create_task_with_non_positive_interval_raises(self, watch_manager: WatchManager):+ with pytest.raises(ValueError, match="watch_interval must be > 0"):+ await watch_manager.create_task(path="/test/path", watch_interval=0)++ @pytest.mark.asyncio+ async def test_get_next_execution_time(self, watch_manager: WatchManager):+ await watch_manager.create_task(path="/test/path1", watch_interval=60.0)+ await watch_manager.create_task(path="/test/path2", watch_interval=0.001)+ await asyncio.sleep(0.05)+ next_time = await watch_manager.get_next_execution_time()+ assert next_time is not None+++class TestWatchManagerPersistence:+ """Tests for WatchManager persistence."""++ @pytest.mark.asyncio+ async def test_persistence_save_and_load(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ """Test that tasks are saved and loaded correctly."""+ manager1 = WatchManager(viking_fs=mock_viking_fs)+ await manager1.initialize()++ task = await manager1.create_task(+ path="/test/path",+ to_uri="viking://resources/test",+ reason="Test task",+ watch_interval=45.0,+ )+ task_id = task.task_id++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ loaded_task = await manager2.get_task(task_id)++ assert loaded_task is not None+ assert loaded_task.path == "/test/path"+ assert loaded_task.to_uri == "viking://resources/test"+ assert loaded_task.reason == "Test task"+ assert loaded_task.watch_interval == 45.0++ @pytest.mark.asyncio+ async def test_persistence_without_vikingfs(self, watch_manager_no_fs: WatchManager):+ """Test that manager works without VikingFS (no persistence)."""+ task = await watch_manager_no_fs.create_task(+ path="/test/path",+ reason="Test task",+ )++ retrieved = await watch_manager_no_fs.get_task(task.task_id)+ assert retrieved is not None+ assert retrieved.path == "/test/path"++ @pytest.mark.asyncio+ async def test_persistence_after_delete(self, mock_viking_fs: MockVikingFS):+ """Test that deleted tasks are removed from persistence."""+ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ task = await manager.create_task(+ path="/test/path",+ to_uri="viking://resources/test",+ )++ await manager.delete_task(+ task_id=task.task_id,+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ loaded_task = await manager2.get_task(task.task_id)+ assert loaded_task is None++ uri_task = await manager2.get_task_by_uri(+ to_uri="viking://resources/test",+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert uri_task is None++ @pytest.mark.asyncio+ async def test_persistence_backfill_next_execution_time(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ manager1 = WatchManager(viking_fs=mock_viking_fs)+ await manager1.initialize()+ task = await manager1.create_task(+ path="/test/path",+ to_uri="viking://resources/test_backfill",+ watch_interval=30.0,+ )++ content = await mock_viking_fs.read_file(WatchManager.STORAGE_URI)+ data = json.loads(content)+ for t in data.get("tasks", []):+ if t.get("task_id") == task.task_id:+ t["next_execution_time"] = None+ break+ await mock_viking_fs.write_file(WatchManager.STORAGE_URI, json.dumps(data))++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()+ loaded = await manager2.get_task(task.task_id)+ assert loaded is not None+ assert loaded.is_active is True+ assert loaded.next_execution_time is not None++ @pytest.mark.asyncio+ async def test_persistence_empty_storage_file_is_ignored(self, mock_viking_fs: MockVikingFS):+ path = mock_viking_fs._uri_to_path(WatchManager.STORAGE_URI)+ mock_viking_fs.agfs.write(path, b"")++ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ tasks = await manager.get_all_tasks(+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert tasks == []++ @pytest.mark.asyncio+ async def test_persistence_recovers_from_backup_on_corrupt_storage(+ self, mock_viking_fs: MockVikingFS+ ):+ storage_path = mock_viking_fs._uri_to_path(WatchManager.STORAGE_URI)+ bak_path = mock_viking_fs._uri_to_path(WatchManager.STORAGE_BAK_URI)++ mock_viking_fs.agfs.write(storage_path, b"")++ task_data = {+ "task_id": "bak-task-id",+ "path": "/test/bak",+ "to_uri": "viking://resources/bak",+ "reason": "Backup task",+ "instruction": "",+ "watch_interval": 60.0,+ "created_at": datetime.now().isoformat(),+ "last_execution_time": None,+ "next_execution_time": None,+ "is_active": True,+ }+ data = {"tasks": [task_data], "updated_at": datetime.now().isoformat()}+ mock_viking_fs.agfs.write(bak_path, json.dumps(data).encode("utf-8"))++ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ loaded = await manager.get_task("bak-task-id")+ assert loaded is not None+ assert loaded.to_uri == "viking://resources/bak"+++class TestWatchManagerConcurrency:+ """Tests for WatchManager concurrent access."""++ @pytest.mark.asyncio+ async def test_concurrent_task_creation(self, watch_manager: WatchManager):+ """Test concurrent task creation."""++ async def create_task(index: int):+ return await watch_manager.create_task(+ path=f"/test/path{index}",+ to_uri=f"viking://resources/test{index}",+ )++ tasks = await asyncio.gather(*[create_task(i) for i in range(10)])++ assert len(tasks) == 10+ assert len({task.task_id for task in tasks}) == 10++ all_tasks = await watch_manager.get_all_tasks(+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ )+ assert len(all_tasks) == 10++ @pytest.mark.asyncio+ async def test_concurrent_read_write(self, watch_manager: WatchManager):+ """Test concurrent read and write operations."""+ task = await watch_manager.create_task(path="/test/path")++ async def update_task(index: int):+ await watch_manager.update_task(+ task_id=task.task_id,+ account_id=TEST_ACCOUNT_ID,+ user_id=TEST_USER_ID,+ role=TEST_ROLE,+ reason=f"Update {index}",+ )++ async def read_task():+ return await watch_manager.get_task(task.task_id)++ operations = [update_task(i) for i in range(5)] + [read_task() for _ in range(5)]+ results = await asyncio.gather(*operations, return_exceptions=True)++ assert all(not isinstance(r, Exception) for r in results)++ final_task = await watch_manager.get_task(task.task_id)+ assert final_task is not Nonediff --git a/tests/resource/test_watch_scheduler.py b/tests/resource/test_watch_scheduler.pynew file mode 100644index 000000000..89f17f5cd--- /dev/null+++ b/tests/resource/test_watch_scheduler.py@@ -0,0 +1,27 @@+import pytest++from openviking.resource.watch_scheduler import WatchScheduler+from openviking.service.resource_service import ResourceService+++class TestWatchSchedulerValidation:+ def test_check_interval_must_be_positive(self):+ rs = ResourceService()+ with pytest.raises(ValueError, match="check_interval must be > 0"):+ WatchScheduler(resource_service=rs, check_interval=0)++ def test_max_concurrency_must_be_positive(self):+ rs = ResourceService()+ with pytest.raises(ValueError, match="max_concurrency must be > 0"):+ WatchScheduler(resource_service=rs, max_concurrency=0)+++class TestWatchSchedulerResourceExistence:+ def test_url_like_sources_are_treated_as_existing(self):+ rs = ResourceService()+ scheduler = WatchScheduler(resource_service=rs, check_interval=1)+ assert scheduler._check_resource_exists("http://example.com") is True+ assert scheduler._check_resource_exists("https://example.com") is True+ assert scheduler._check_resource_exists("[email protected]:org/repo.git") is True+ assert scheduler._check_resource_exists("ssh://[email protected]/org/repo.git") is True+ assert scheduler._check_resource_exists("git://github.com/org/repo.git") is Truediff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.pyindex 6e5911273..b6d96785b 100644--- a/tests/server/test_api_resources.py+++ b/tests/server/test_api_resources.py@@ -151,3 +151,34 @@ async def test_wait_processed_after_add(client: httpx.AsyncClient, sample_markdo)assert resp.status_code == 200assert resp.json()["status"] == "ok"+++async def test_add_resource_with_watch_interval(client: httpx.AsyncClient, sample_markdown_file):+ resp = await client.post(+ "/api/v1/resources",+ json={+ "path": str(sample_markdown_file),+ "reason": "test resource with watch interval",+ "watch_interval": 5.0,+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert "root_uri" in body["result"]+++async def test_add_resource_with_default_watch_interval(+ client: httpx.AsyncClient, sample_markdown_file+):+ resp = await client.post(+ "/api/v1/resources",+ json={+ "path": str(sample_markdown_file),+ "reason": "test resource with default watch interval",+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "ok"+ assert "root_uri" in body["result"]diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.pynew file mode 100644index 000000000..6680de43c--- /dev/null+++ b/tests/service/test_resource_service_watch.py@@ -0,0 +1,482 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""Integration tests for ResourceService watch functionality."""++from typing import AsyncGenerator+from unittest.mock import AsyncMock, MagicMock++import pytest+import pytest_asyncio++from openviking.resource.watch_manager import WatchManager+from openviking.server.identity import RequestContext, Role+from openviking.service.resource_service import ResourceService+from openviking_cli.exceptions import ConflictError+from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.session.user_id import UserIdentifier+++async def get_task_by_uri(service: ResourceService, to_uri: str, ctx: RequestContext):+ return await service._watch_scheduler.watch_manager.get_task_by_uri(+ to_uri=to_uri,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ role=ctx.role.value,+ )+++class MockResourceProcessor:+ """Mock ResourceProcessor for testing."""++ async def process_resource(self, **kwargs):+ return {"root_uri": kwargs.get("to", "viking://resources/test")}+++class MockSkillProcessor:+ """Mock SkillProcessor for testing."""++ async def process_skill(self, **kwargs):+ return {"status": "ok"}+++class MockVikingFS:+ """Mock VikingFS for testing."""++ pass+++class MockVikingDB:+ """Mock VikingDBManager for testing."""++ pass+++@pytest_asyncio.fixture+async def watch_manager() -> AsyncGenerator[WatchManager, None]:+ """Create WatchManager instance without VikingFS for testing."""+ manager = WatchManager(viking_fs=None)+ await manager.initialize()+ yield manager+ await manager.clear_all_tasks()+++@pytest_asyncio.fixture+async def resource_service(watch_manager: WatchManager) -> AsyncGenerator[ResourceService, None]:+ """Create ResourceService instance with watch support."""+ scheduler = MagicMock()+ scheduler.watch_manager = watch_manager+ service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(),+ resource_processor=MockResourceProcessor(),+ skill_processor=MockSkillProcessor(),+ watch_scheduler=scheduler,+ )+ yield service+++@pytest_asyncio.fixture+def request_context() -> RequestContext:+ """Create request context for testing."""+ return RequestContext(+ user=UserIdentifier("test_account", "test_user", "test_agent"),+ role=Role.USER,+ )+++class TestWatchTaskCreation:+ """Tests for watch task creation in add_resource."""++ @pytest.mark.asyncio+ async def test_create_watch_task_with_positive_interval(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test creating a watch task when watch_interval > 0."""+ to_uri = "viking://resources/test_resource"++ result = await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ reason="Test monitoring",+ instruction="Monitor for changes",+ watch_interval=30.0,+ )++ assert result is not None+ assert "root_uri" in result++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.path == "/test/path"+ assert task.to_uri == to_uri+ assert task.reason == "Test monitoring"+ assert task.instruction == "Monitor for changes"+ assert task.watch_interval == 30.0+ assert task.is_active is True++ @pytest.mark.asyncio+ async def test_watch_interval_requires_to_when_watch_enabled(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ with pytest.raises(InvalidArgumentError, match="requires 'to'"):+ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=None,+ watch_interval=30.0,+ )++ @pytest.mark.asyncio+ async def test_watch_task_aligns_processor_params(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ to_uri = "viking://resources/align_processor_params"++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=30.0,+ build_index=False,+ summarize=True,+ custom_option="x",+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.build_index is False+ assert task.summarize is True+ assert task.processor_kwargs.get("custom_option") == "x"++ @pytest.mark.asyncio+ async def test_create_watch_task_with_default_interval(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test creating a watch task with default interval."""+ to_uri = "viking://resources/default_interval"++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=60.0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.watch_interval == 60.0++ @pytest.mark.asyncio+ async def test_no_watch_task_created_with_zero_interval(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test that no watch task is created when watch_interval is 0."""+ to_uri = "viking://resources/no_watch"++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is None++ @pytest.mark.asyncio+ async def test_no_watch_task_created_with_negative_interval(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test that no watch task is created when watch_interval is negative."""+ to_uri = "viking://resources/negative_watch"++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=-10,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is None+++class TestWatchTaskConflict:+ """Tests for watch task conflict detection."""++ @pytest.mark.asyncio+ async def test_conflict_when_active_task_exists(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test that ConflictError is raised when an active task already exists."""+ to_uri = "viking://resources/conflict_test"++ await resource_service.add_resource(+ path="/test/path1",+ ctx=request_context,+ to=to_uri,+ watch_interval=30.0,+ )++ with pytest.raises(ConflictError) as exc_info:+ await resource_service.add_resource(+ path="/test/path2",+ ctx=request_context,+ to=to_uri,+ watch_interval=45.0,+ )++ assert "already being monitored" in str(exc_info.value)+ assert to_uri in str(exc_info.value)++ @pytest.mark.asyncio+ async def test_conflict_when_task_exists_but_hidden_by_permission(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ to_uri = "viking://resources/cross_user_conflict"+ other_user_ctx = RequestContext(+ user=UserIdentifier("test_account", "other_user", "other_agent"),+ role=Role.USER,+ )++ await resource_service.add_resource(+ path="/test/path1",+ ctx=request_context,+ to=to_uri,+ watch_interval=30.0,+ )++ hidden_task = await get_task_by_uri(resource_service, to_uri, other_user_ctx)+ assert hidden_task is None++ with pytest.raises(ConflictError) as exc_info:+ await resource_service.add_resource(+ path="/test/path2",+ ctx=other_user_ctx,+ to=to_uri,+ watch_interval=45.0,+ )++ assert "already used by another task" in str(exc_info.value)+ assert to_uri in str(exc_info.value)++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None++ @pytest.mark.asyncio+ async def test_reactivate_inactive_task(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test reactivating an inactive task."""+ to_uri = "viking://resources/reactivate_test"++ await resource_service.add_resource(+ path="/test/path1",+ ctx=request_context,+ to=to_uri,+ watch_interval=30.0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ task_id = task.task_id++ await resource_service._watch_scheduler.watch_manager.update_task(+ task_id=task_id,+ account_id=request_context.account_id,+ user_id=request_context.user.user_id,+ role=request_context.role.value,+ is_active=False,+ )++ await resource_service.add_resource(+ path="/test/path2",+ ctx=request_context,+ to=to_uri,+ reason="Updated reason",+ watch_interval=45.0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.task_id == task_id+ assert task.path == "/test/path2"+ assert task.reason == "Updated reason"+ assert task.watch_interval == 45.0+ assert task.is_active is True+++class TestWatchTaskCancellation:+ """Tests for watch task cancellation."""++ @pytest.mark.asyncio+ async def test_cancel_watch_task_with_zero_interval(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test cancelling a watch task by setting watch_interval to 0."""+ to_uri = "viking://resources/cancel_test"++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=30.0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.is_active is True++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.is_active is False++ @pytest.mark.asyncio+ async def test_cancel_watch_task_with_negative_interval(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test cancelling a watch task by setting watch_interval to negative."""+ to_uri = "viking://resources/cancel_negative"++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=30.0,+ )++ await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=-5,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.is_active is False++ @pytest.mark.asyncio+ async def test_cancel_nonexistent_task_no_error(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test that cancelling a nonexistent task does not raise an error."""+ to_uri = "viking://resources/nonexistent"++ result = await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=to_uri,+ watch_interval=0,+ )++ assert result is not None+++class TestWatchTaskUpdate:+ """Tests for watch task update."""++ @pytest.mark.asyncio+ async def test_update_watch_task_parameters(+ self, resource_service: ResourceService, request_context: RequestContext+ ):+ """Test updating watch task parameters."""+ to_uri = "viking://resources/update_test"++ await resource_service.add_resource(+ path="/test/path1",+ ctx=request_context,+ to=to_uri,+ reason="Original reason",+ instruction="Original instruction",+ watch_interval=30.0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ original_task_id = task.task_id++ await resource_service._watch_scheduler.watch_manager.update_task(+ task_id=task.task_id,+ account_id=request_context.account_id,+ user_id=request_context.user.user_id,+ role=request_context.role.value,+ is_active=False,+ )++ await resource_service.add_resource(+ path="/test/path2",+ ctx=request_context,+ to=to_uri,+ reason="Updated reason",+ instruction="Updated instruction",+ watch_interval=60.0,+ )++ task = await get_task_by_uri(resource_service, to_uri, request_context)+ assert task is not None+ assert task.task_id == original_task_id+ assert task.path == "/test/path2"+ assert task.reason == "Updated reason"+ assert task.instruction == "Updated instruction"+ assert task.watch_interval == 60.0+ assert task.is_active is True+++class TestResourceProcessingIndependence:+ """Tests that resource processing is independent of watch task management."""++ @pytest.mark.asyncio+ async def test_resource_added_even_if_watch_fails(self, request_context: RequestContext):+ """Test that resource is added even if watch task creation fails."""+ failing_watch_manager = MagicMock(spec=WatchManager)+ failing_watch_manager.get_task_by_uri = AsyncMock(side_effect=Exception("DB error"))+ scheduler = MagicMock()+ scheduler.watch_manager = failing_watch_manager++ service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(),+ resource_processor=MockResourceProcessor(),+ skill_processor=MockSkillProcessor(),+ watch_scheduler=scheduler,+ )++ result = await service.add_resource(+ path="/test/path",+ ctx=request_context,+ to="viking://resources/test",+ watch_interval=30.0,+ )++ assert result is not None+ assert "root_uri" in result++ @pytest.mark.asyncio+ async def test_resource_added_without_watch_manager(self, request_context: RequestContext):+ """Test that resource is added when watch_manager is None."""+ service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(),+ resource_processor=MockResourceProcessor(),+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ result = await service.add_resource(+ path="/test/path",+ ctx=request_context,+ to="viking://resources/test",+ watch_interval=30.0,+ )++ assert result is not None+ assert "root_uri" in resultdiff --git a/tests/service/test_watch_recovery.py b/tests/service/test_watch_recovery.pynew file mode 100644index 000000000..b1bed7df9--- /dev/null+++ b/tests/service/test_watch_recovery.py@@ -0,0 +1,612 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""Integration tests for watch task recovery after service restart."""++import asyncio+import json+from datetime import datetime, timedelta+from pathlib import Path+from typing import AsyncGenerator++import pytest+import pytest_asyncio++from openviking.resource.watch_manager import WatchManager+from openviking.resource.watch_scheduler import WatchScheduler+from openviking.server.identity import RequestContext, Role+from openviking.service.resource_service import ResourceService+from openviking_cli.session.user_id import UserIdentifier+from tests.utils.mock_agfs import MockLocalAGFS+++class MockVikingFS:+ """Mock VikingFS for testing."""++ def __init__(self, root_path: str):+ self.agfs = MockLocalAGFS(root_path=root_path)++ async def read_file(self, uri: str, ctx=None) -> str:+ """Read file from storage."""+ path = self._uri_to_path(uri)+ content = self.agfs.read(path)+ if isinstance(content, bytes):+ return content.decode("utf-8")+ return content++ async def write_file(self, uri: str, content: str, ctx=None) -> None:+ """Write file to storage."""+ path = self._uri_to_path(uri)+ self.agfs.write(path, content.encode("utf-8"))++ def _uri_to_path(self, uri: str) -> str:+ """Convert URI to path."""+ if uri.startswith("viking://"):+ return uri.replace("viking://", "/local/default/")+ return uri+++class MockResourceProcessor:+ """Mock ResourceProcessor for testing."""++ def __init__(self):+ self.call_count = 0+ self.processed_paths = []++ async def process_resource(self, **kwargs):+ self.call_count += 1+ self.processed_paths.append(kwargs.get("path"))+ return {"root_uri": kwargs.get("to", "viking://resources/test")}+++class MockSkillProcessor:+ """Mock SkillProcessor for testing."""++ async def process_skill(self, **kwargs):+ return {"status": "ok"}+++class MockVikingDB:+ """Mock VikingDBManager for testing."""++ pass+++@pytest_asyncio.fixture+async def temp_storage(tmp_path: Path) -> AsyncGenerator[Path, None]:+ """Create temporary storage directory."""+ storage_dir = tmp_path / "watch_storage"+ storage_dir.mkdir(parents=True, exist_ok=True)+ yield storage_dir+++@pytest_asyncio.fixture+async def mock_viking_fs(temp_storage: Path) -> MockVikingFS:+ """Create mock VikingFS instance."""+ return MockVikingFS(root_path=str(temp_storage))+++@pytest_asyncio.fixture+async def request_context() -> RequestContext:+ """Create request context for testing."""+ return RequestContext(+ user=UserIdentifier.the_default_user(),+ role=Role.ROOT,+ )+++class TestServiceRestartRecovery:+ """Tests for watch task recovery after service restart."""++ @pytest.mark.asyncio+ async def test_tasks_persisted_and_reloaded_after_restart(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ """Test that tasks are persisted and correctly reloaded after service restart."""+ manager1 = WatchManager(viking_fs=mock_viking_fs)+ await manager1.initialize()++ task1 = await manager1.create_task(+ path="/test/path1",+ to_uri="viking://resources/test1",+ reason="Task 1",+ watch_interval=30.0,+ )+ task2 = await manager1.create_task(+ path="/test/path2",+ to_uri="viking://resources/test2",+ reason="Task 2",+ watch_interval=60.0,+ )++ task1_id = task1.task_id+ task2_id = task2.task_id++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ loaded_task1 = await manager2.get_task(task1_id)+ loaded_task2 = await manager2.get_task(task2_id)++ assert loaded_task1 is not None+ assert loaded_task1.path == "/test/path1"+ assert loaded_task1.to_uri == "viking://resources/test1"+ assert loaded_task1.reason == "Task 1"+ assert loaded_task1.watch_interval == 30.0+ assert loaded_task1.is_active is True++ assert loaded_task2 is not None+ assert loaded_task2.path == "/test/path2"+ assert loaded_task2.to_uri == "viking://resources/test2"+ assert loaded_task2.watch_interval == 60.0++ @pytest.mark.asyncio+ async def test_tasks_recovered_from_backup_when_primary_missing(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ """Test that tasks can be recovered from backup storage when primary is missing."""+ task_data = {+ "task_id": "backup-task-id",+ "path": "/test/backup",+ "to_uri": "viking://resources/backup",+ "reason": "Backup task",+ "instruction": "",+ "watch_interval": 60.0,+ "created_at": datetime.now().isoformat(),+ "last_execution_time": None,+ "next_execution_time": None,+ "is_active": True,+ }++ storage_uri = WatchManager.STORAGE_URI+ storage_path = mock_viking_fs._uri_to_path(storage_uri)+ assert mock_viking_fs.agfs.exists(storage_path) is False++ bak_uri = WatchManager.STORAGE_BAK_URI+ bak_path = mock_viking_fs._uri_to_path(bak_uri)+ data = {"tasks": [task_data], "updated_at": datetime.now().isoformat()}+ mock_viking_fs.agfs.write(bak_path, json.dumps(data).encode("utf-8"))++ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ loaded_task = await manager.get_task("backup-task-id")+ assert loaded_task is not None+ assert loaded_task.path == "/test/backup"+ assert loaded_task.to_uri == "viking://resources/backup"++ assert mock_viking_fs.agfs.exists(storage_path) is True++ @pytest.mark.asyncio+ async def test_expired_tasks_executed_on_startup(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path, request_context: RequestContext+ ):+ """Test that tasks with next_execution_time in the past are executed on startup."""+ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ past_time = datetime.now() - timedelta(minutes=10)+ task_data = {+ "task_id": "expired-task-id",+ "path": "/test/expired",+ "to_uri": "viking://resources/expired",+ "reason": "Expired task",+ "instruction": "",+ "watch_interval": 60.0,+ "created_at": (datetime.now() - timedelta(hours=1)).isoformat(),+ "last_execution_time": (datetime.now() - timedelta(hours=1)).isoformat(),+ "next_execution_time": past_time.isoformat(),+ "is_active": True,+ }++ storage_uri = WatchManager.STORAGE_URI+ path = mock_viking_fs._uri_to_path(storage_uri)+ data = {"tasks": [task_data], "updated_at": datetime.now().isoformat()}+ mock_viking_fs.agfs.write(path, json.dumps(data).encode("utf-8"))++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ due_tasks = await manager2.get_due_tasks()++ assert len(due_tasks) == 1+ assert due_tasks[0].task_id == "expired-task-id"++ @pytest.mark.asyncio+ async def test_future_tasks_not_executed_on_startup(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ """Test that tasks with future next_execution_time are not executed immediately."""+ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ future_time = datetime.now() + timedelta(hours=1)+ task_data = {+ "task_id": "future-task-id",+ "path": "/test/future",+ "to_uri": "viking://resources/future",+ "reason": "Future task",+ "instruction": "",+ "watch_interval": 60.0,+ "created_at": datetime.now().isoformat(),+ "last_execution_time": None,+ "next_execution_time": future_time.isoformat(),+ "is_active": True,+ }++ storage_uri = WatchManager.STORAGE_URI+ path = mock_viking_fs._uri_to_path(storage_uri)+ data = {"tasks": [task_data], "updated_at": datetime.now().isoformat()}+ mock_viking_fs.agfs.write(path, json.dumps(data).encode("utf-8"))++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ due_tasks = await manager2.get_due_tasks()++ assert len(due_tasks) == 0++ @pytest.mark.asyncio+ async def test_inactive_tasks_not_executed_after_restart(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ """Test that inactive tasks are not executed after restart."""+ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ past_time = datetime.now() - timedelta(minutes=10)+ task_data = {+ "task_id": "inactive-task-id",+ "path": "/test/inactive",+ "to_uri": "viking://resources/inactive",+ "reason": "Inactive task",+ "instruction": "",+ "watch_interval": 60.0,+ "created_at": (datetime.now() - timedelta(hours=1)).isoformat(),+ "last_execution_time": None,+ "next_execution_time": past_time.isoformat(),+ "is_active": False,+ }++ storage_uri = WatchManager.STORAGE_URI+ path = mock_viking_fs._uri_to_path(storage_uri)+ data = {"tasks": [task_data], "updated_at": datetime.now().isoformat()}+ mock_viking_fs.agfs.write(path, json.dumps(data).encode("utf-8"))++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ due_tasks = await manager2.get_due_tasks()++ assert len(due_tasks) == 0+++class TestResourceExistenceCheck:+ """Tests for resource existence checking during task execution."""++ @pytest.mark.asyncio+ async def test_task_deactivated_when_resource_deleted(+ self, temp_storage: Path, request_context: RequestContext+ ):+ """Test that task is deactivated when resource no longer exists."""+ resource_processor = MockResourceProcessor()++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(root_path=str(temp_storage)),+ resource_processor=resource_processor,+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ task = await watch_manager.create_task(+ path="/nonexistent/path/to/resource",+ to_uri="viking://resources/deleted",+ reason="Test deleted resource",+ watch_interval=30.0,+ )++ assert task.is_active is True++ await scheduler._execute_task(task)++ updated_task = await watch_manager.get_task(task.task_id)+ assert updated_task is not None+ assert updated_task.is_active is False++ @pytest.mark.asyncio+ async def test_task_continues_when_resource_exists(+ self, temp_storage: Path, request_context: RequestContext+ ):+ """Test that task continues normally when resource exists."""+ test_file = temp_storage / "test_resource.txt"+ test_file.write_text("test content")++ resource_processor = MockResourceProcessor()++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(root_path=str(temp_storage)),+ resource_processor=resource_processor,+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ task = await watch_manager.create_task(+ path=str(test_file),+ to_uri="viking://resources/existing",+ reason="Test existing resource",+ watch_interval=30.0,+ )++ await scheduler._execute_task(task)++ updated_task = await watch_manager.get_task(task.task_id)+ assert updated_task is not None+ assert updated_task.is_active is True+ assert updated_task.last_execution_time is not None++ @pytest.mark.asyncio+ async def test_url_resources_always_considered_existing(+ self, temp_storage: Path, request_context: RequestContext+ ):+ """Test that URL resources are always considered existing."""+ resource_processor = MockResourceProcessor()++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(root_path=str(temp_storage)),+ resource_processor=resource_processor,+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ task = await watch_manager.create_task(+ path="https://example.com/resource",+ to_uri="viking://resources/url",+ reason="Test URL resource",+ watch_interval=30.0,+ )++ await scheduler._execute_task(task)++ updated_task = await watch_manager.get_task(task.task_id)+ assert updated_task is not None+ assert updated_task.is_active is True+ assert resource_processor.call_count == 1+++class TestSchedulerIntegration:+ """Integration tests for WatchScheduler with WatchManager."""++ @pytest.mark.asyncio+ async def test_scheduler_processes_due_tasks_after_restart(+ self, temp_storage: Path, request_context: RequestContext+ ):+ """Test that scheduler processes due tasks after service restart."""+ test_file = temp_storage / "test.txt"+ test_file.write_text("test content")++ resource_processor = MockResourceProcessor()++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(root_path=str(temp_storage)),+ resource_processor=resource_processor,+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ check_interval=0.1,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ await watch_manager.create_task(+ path=str(test_file),+ to_uri="viking://resources/test",+ reason="Test task",+ watch_interval=0.001,+ )++ await asyncio.sleep(0.2)++ await scheduler.stop()++ assert resource_processor.call_count >= 1++ @pytest.mark.asyncio+ async def test_scheduler_handles_multiple_tasks_after_restart(+ self, temp_storage: Path, request_context: RequestContext+ ):+ """Test that scheduler handles multiple tasks after restart."""+ test_file1 = temp_storage / "test1.txt"+ test_file2 = temp_storage / "test2.txt"+ test_file1.write_text("test content 1")+ test_file2.write_text("test content 2")++ resource_processor = MockResourceProcessor()++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(root_path=str(temp_storage)),+ resource_processor=resource_processor,+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ check_interval=0.1,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ await watch_manager.create_task(+ path=str(test_file1),+ to_uri="viking://resources/test1",+ reason="Task 1",+ watch_interval=0.001,+ )+ await watch_manager.create_task(+ path=str(test_file2),+ to_uri="viking://resources/test2",+ reason="Task 2",+ watch_interval=0.001,+ )++ await asyncio.sleep(0.3)++ await scheduler.stop()++ assert resource_processor.call_count >= 2++ @pytest.mark.asyncio+ async def test_scheduler_skips_inactive_tasks_after_restart(+ self, temp_storage: Path, request_context: RequestContext+ ):+ """Test that scheduler skips inactive tasks after restart."""+ test_file = temp_storage / "test.txt"+ test_file.write_text("test content")++ resource_processor = MockResourceProcessor()++ resource_service = ResourceService(+ vikingdb=MockVikingDB(),+ viking_fs=MockVikingFS(root_path=str(temp_storage)),+ resource_processor=resource_processor,+ skill_processor=MockSkillProcessor(),+ watch_scheduler=None,+ )++ scheduler = WatchScheduler(+ resource_service=resource_service,+ viking_fs=None,+ check_interval=0.1,+ )+ await scheduler.start()++ watch_manager = scheduler.watch_manager++ task = await watch_manager.create_task(+ path=str(test_file),+ to_uri="viking://resources/test",+ reason="Inactive task",+ watch_interval=0.001,+ )++ await watch_manager.update_task(+ task_id=task.task_id,+ account_id=task.account_id,+ user_id=task.user_id,+ role="ROOT",+ is_active=False,+ )++ await asyncio.sleep(0.2)++ await scheduler.stop()++ assert resource_processor.call_count == 0+++class TestTaskExecutionTimeRecovery:+ """Tests for task execution time handling after restart."""++ @pytest.mark.asyncio+ async def test_execution_times_preserved_after_restart(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ """Test that execution times are preserved after restart."""+ manager1 = WatchManager(viking_fs=mock_viking_fs)+ await manager1.initialize()++ task = await manager1.create_task(+ path="/test/path",+ to_uri="viking://resources/test",+ watch_interval=30.0,+ )++ await manager1.update_execution_time(task.task_id)++ task_after_exec = await manager1.get_task(task.task_id)+ assert task_after_exec is not None+ original_last_exec = task_after_exec.last_execution_time+ original_next_exec = task_after_exec.next_execution_time++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ loaded_task = await manager2.get_task(task.task_id)+ assert loaded_task is not None+ assert loaded_task.last_execution_time is not None+ assert abs((loaded_task.last_execution_time - original_last_exec).total_seconds()) < 1+ assert loaded_task.next_execution_time is not None+ assert abs((loaded_task.next_execution_time - original_next_exec).total_seconds()) < 1++ @pytest.mark.asyncio+ async def test_next_execution_time_calculated_correctly_after_restart(+ self, mock_viking_fs: MockVikingFS, temp_storage: Path+ ):+ """Test that next execution time is calculated correctly for loaded tasks."""+ manager = WatchManager(viking_fs=mock_viking_fs)+ await manager.initialize()++ last_exec = datetime.now() - timedelta(minutes=15)+ task_data = {+ "task_id": "test-task-id",+ "path": "/test/path",+ "to_uri": "viking://resources/test",+ "reason": "Test",+ "instruction": "",+ "watch_interval": 30.0,+ "created_at": (datetime.now() - timedelta(hours=1)).isoformat(),+ "last_execution_time": last_exec.isoformat(),+ "next_execution_time": (last_exec + timedelta(minutes=30)).isoformat(),+ "is_active": True,+ }++ storage_uri = WatchManager.STORAGE_URI+ path = mock_viking_fs._uri_to_path(storage_uri)+ data = {"tasks": [task_data], "updated_at": datetime.now().isoformat()}+ mock_viking_fs.agfs.write(path, json.dumps(data).encode("utf-8"))++ manager2 = WatchManager(viking_fs=mock_viking_fs)+ await manager2.initialize()++ loaded_task = await manager2.get_task("test-task-id")+ assert loaded_task is not None+ assert loaded_task.watch_interval == 30.0+ assert loaded_task.last_execution_time is not None++ expected_next = loaded_task.last_execution_time + timedelta(minutes=30)+ assert abs((loaded_task.next_execution_time - expected_next).total_seconds()) < 1