Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: Watch Management API — REST + ov CLI + MCP (RFC #2104) (#2110)

t0saki74414c946414
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rs
index 4c093506a..15d6d9e1b 100644
--- a/crates/ov_cli/src/base_client.rs
+++ b/crates/ov_cli/src/base_client.rs
@@ -405,6 +405,46 @@ impl BaseClient {
self.handle_response(response).await
}
+
+ pub async fn patch<B: serde::Serialize, T: DeserializeOwned>(
+ &self,
+ path: &str,
+ body: &B,
+ params: &[(String, String)],
+ ) -> Result<T> {
+ let url = format!("{}{}", self.base_url, path);
+ let response = self
+ .http
+ .patch(&url)
+ .headers(self.build_headers())
+ .query(params)
+ .json(body)
+ .send()
+ .await
+ .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
+
+ self.handle_response(response).await
+ }
+
+ pub async fn post_with_query<B: serde::Serialize, T: DeserializeOwned>(
+ &self,
+ path: &str,
+ body: &B,
+ params: &[(String, String)],
+ ) -> Result<T> {
+ let url = format!("{}{}", self.base_url, path);
+ let response = self
+ .http
+ .post(&url)
+ .headers(self.build_headers())
+ .query(params)
+ .json(body)
+ .send()
+ .await
+ .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
+
+ self.handle_response(response).await
+ }
}
// ============ FileUploader ============
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 7aefc8570..e0aef9ca2 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -106,6 +106,24 @@ impl HttpClient {
self.base.delete_with_body(path, body).await
}
+ pub async fn patch<B: serde::Serialize, T: DeserializeOwned>(
+ &self,
+ path: &str,
+ body: &B,
+ params: &[(String, String)],
+ ) -> Result<T> {
+ self.base.patch(path, body, params).await
+ }
+
+ pub async fn post_with_query<B: serde::Serialize, T: DeserializeOwned>(
+ &self,
+ path: &str,
+ body: &B,
+ params: &[(String, String)],
+ ) -> Result<T> {
+ self.base.post_with_query(path, body, params).await
+ }
+
// ============ File Helper Methods ============
fn create_uploader(&self) -> FileUploader {
@@ -1059,6 +1077,66 @@ impl HttpClient {
let body = serde_json::json!({ "version": version });
self.post(&path, &body).await
}
+
+ // ============ Watch Management (RFC #2104) ============
+
+ pub async fn list_watches(&self, active_only: bool) -> Result<serde_json::Value> {
+ let mut params = vec![];
+ if active_only {
+ params.push(("active_only".to_string(), "true".to_string()));
+ }
+ self.get("/api/v1/watches", &params).await
+ }
+
+ pub async fn get_watch_by_id(&self, task_id: &str) -> Result<serde_json::Value> {
+ let path = format!("/api/v1/watches/{}", task_id);
+ self.get(&path, &[]).await
+ }
+
+ pub async fn get_watch_by_uri(&self, to_uri: &str) -> Result<serde_json::Value> {
+ let params = vec![("to_uri".to_string(), to_uri.to_string())];
+ self.get("/api/v1/watches", &params).await
+ }
+
+ pub async fn patch_watch_by_id(
+ &self,
+ task_id: &str,
+ body: &serde_json::Value,
+ ) -> Result<serde_json::Value> {
+ let path = format!("/api/v1/watches/{}", task_id);
+ self.patch(&path, body, &[]).await
+ }
+
+ pub async fn patch_watch_by_uri(
+ &self,
+ to_uri: &str,
+ body: &serde_json::Value,
+ ) -> Result<serde_json::Value> {
+ let params = vec![("to_uri".to_string(), to_uri.to_string())];
+ self.patch("/api/v1/watches", body, &params).await
+ }
+
+ pub async fn delete_watch_by_id(&self, task_id: &str) -> Result<serde_json::Value> {
+ let path = format!("/api/v1/watches/{}", task_id);
+ self.delete(&path, &[]).await
+ }
+
+ pub async fn delete_watch_by_uri(&self, to_uri: &str) -> Result<serde_json::Value> {
+ let params = vec![("to_uri".to_string(), to_uri.to_string())];
+ self.delete("/api/v1/watches", &params).await
+ }
+
+ pub async fn trigger_watch_by_id(&self, task_id: &str) -> Result<serde_json::Value> {
+ let path = format!("/api/v1/watches/{}/trigger", task_id);
+ let empty = serde_json::json!({});
+ self.post(&path, &empty).await
+ }
+
+ pub async fn trigger_watch_by_uri(&self, to_uri: &str) -> Result<serde_json::Value> {
+ let params = vec![("to_uri".to_string(), to_uri.to_string())];
+ let empty = serde_json::json!({});
+ self.post_with_query("/api/v1/watches/trigger", &empty, &params).await
+ }
}
#[cfg(test)]
diff --git a/crates/ov_cli/src/commands/mod.rs b/crates/ov_cli/src/commands/mod.rs
index 90ebb9c72..678546561 100644
--- a/crates/ov_cli/src/commands/mod.rs
+++ b/crates/ov_cli/src/commands/mod.rs
@@ -12,3 +12,4 @@ pub mod search;
pub mod session;
pub mod system;
pub mod task;
+pub mod watch;
diff --git a/crates/ov_cli/src/commands/watch.rs b/crates/ov_cli/src/commands/watch.rs
new file mode 100644
index 000000000..5ae698a37
--- /dev/null
+++ b/crates/ov_cli/src/commands/watch.rs
@@ -0,0 +1,288 @@
+// Watch management subcommand handlers (RFC #2104).
+//
+// Mirrors the REST `/watches` endpoints with full parity. Each handler
+// auto-detects whether `key` is a viking:// URI or a task_id and routes to
+// the appropriate `*_by_uri` or `*_by_id` HTTP client method.
+
+use crate::client::HttpClient;
+use crate::error::{Error, Result};
+use crate::output::{OutputFormat, output_success};
+use serde_json::json;
+
+/// How a positional `<key>` arg should be routed.
+#[derive(Debug, PartialEq, Eq)]
+enum KeyKind {
+ /// Routes to `*_by_uri` HTTP method.
+ Uri,
+ /// Routes to `*_by_id` HTTP method (treated as opaque task_id).
+ TaskId,
+}
+
+/// Classify a positional key. Case-insensitive `viking://` matches as a URI;
+/// any other `://`-bearing string is rejected as a likely typo (avoids the
+/// silent "task_id not found" experience when the user meant a URI but used
+/// the wrong scheme / capitalization / single-slash).
+fn classify_key(key: &str) -> Result<KeyKind> {
+ if key.starts_with("viking://") {
+ return Ok(KeyKind::Uri);
+ }
+ if key.to_ascii_lowercase().starts_with("viking://") {
+ return Err(Error::Parse(format!(
+ "URI scheme is case-sensitive — use lowercase `viking://` (got {key:?})"
+ )));
+ }
+ if key.contains("://") {
+ return Err(Error::Parse(format!(
+ "Key {key:?} looks like a URI but does not start with `viking://`. \
+ If you meant a task_id, drop the scheme."
+ )));
+ }
+ Ok(KeyKind::TaskId)
+}
+
+/// Validate the `--interval` value of `ov task watch update`. Rejects 0,
+/// negatives, and NaN.
+fn validate_interval_minutes(minutes: f64) -> Result<()> {
+ if !(minutes > 0.0) {
+ return Err(Error::Parse(format!(
+ "minutes must be > 0 (got {minutes}). To pause a watch task, use `ov task watch pause`."
+ )));
+ }
+ Ok(())
+}
+
+pub async fn ls(
+ client: &HttpClient,
+ active_only: bool,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let response = client.list_watches(active_only).await?;
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+pub async fn show(
+ client: &HttpClient,
+ key: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let response = match classify_key(key)? {
+ KeyKind::Uri => client.get_watch_by_uri(key).await?,
+ KeyKind::TaskId => client.get_watch_by_id(key).await?,
+ };
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+pub async fn rm(
+ client: &HttpClient,
+ key: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let response = match classify_key(key)? {
+ KeyKind::Uri => client.delete_watch_by_uri(key).await?,
+ KeyKind::TaskId => client.delete_watch_by_id(key).await?,
+ };
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+pub async fn pause(
+ client: &HttpClient,
+ key: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let body = json!({"is_active": false});
+ let response = match classify_key(key)? {
+ KeyKind::Uri => client.patch_watch_by_uri(key, &body).await?,
+ KeyKind::TaskId => client.patch_watch_by_id(key, &body).await?,
+ };
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+pub async fn resume(
+ client: &HttpClient,
+ key: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let body = json!({"is_active": true});
+ let response = match classify_key(key)? {
+ KeyKind::Uri => client.patch_watch_by_uri(key, &body).await?,
+ KeyKind::TaskId => client.patch_watch_by_id(key, &body).await?,
+ };
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+/// Build the PATCH body for `ov task watch update`. Validates each field and
+/// guards against the no-op case (caller passed no flags). Exposed as a
+/// standalone helper so the validation paths can be unit-tested without an
+/// HTTP client.
+fn build_update_body(
+ interval: Option<f64>,
+ active: Option<bool>,
+ reason: Option<&str>,
+ instruction: Option<&str>,
+) -> Result<serde_json::Value> {
+ let mut body = serde_json::Map::new();
+ if let Some(i) = interval {
+ validate_interval_minutes(i)?;
+ body.insert("watch_interval".into(), json!(i));
+ }
+ if let Some(a) = active {
+ body.insert("is_active".into(), json!(a));
+ }
+ if let Some(r) = reason {
+ body.insert("reason".into(), json!(r));
+ }
+ if let Some(ins) = instruction {
+ body.insert("instruction".into(), json!(ins));
+ }
+ if body.is_empty() {
+ return Err(Error::Parse(
+ "At least one of --interval, --active, --reason, --instruction is required".into(),
+ ));
+ }
+ Ok(serde_json::Value::Object(body))
+}
+
+pub async fn update(
+ client: &HttpClient,
+ key: &str,
+ interval: Option<f64>,
+ active: Option<bool>,
+ reason: Option<String>,
+ instruction: Option<String>,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let body = build_update_body(interval, active, reason.as_deref(), instruction.as_deref())?;
+ let response = match classify_key(key)? {
+ KeyKind::Uri => client.patch_watch_by_uri(key, &body).await?,
+ KeyKind::TaskId => client.patch_watch_by_id(key, &body).await?,
+ };
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+pub async fn trigger(
+ client: &HttpClient,
+ key: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let response = match classify_key(key)? {
+ KeyKind::Uri => client.trigger_watch_by_uri(key).await?,
+ KeyKind::TaskId => client.trigger_watch_by_id(key).await?,
+ };
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{KeyKind, build_update_body, classify_key, validate_interval_minutes};
+ use crate::error::Error;
+
+ #[test]
+ fn classify_viking_uri_as_uri() {
+ assert_eq!(
+ classify_key("viking://resources/foo/bar").unwrap(),
+ KeyKind::Uri
+ );
+ assert_eq!(classify_key("viking://resources").unwrap(), KeyKind::Uri);
+ }
+
+ #[test]
+ fn classify_plain_id_as_task_id() {
+ assert_eq!(
+ classify_key("550e8400-e29b-41d4-a716-446655440000").unwrap(),
+ KeyKind::TaskId
+ );
+ assert_eq!(classify_key("abc-123").unwrap(), KeyKind::TaskId);
+ assert_eq!(classify_key("").unwrap(), KeyKind::TaskId);
+ }
+
+ #[test]
+ fn classify_rejects_uppercase_viking_scheme() {
+ let err = classify_key("Viking://resources/foo").expect_err("should reject");
+ match err {
+ Error::Parse(msg) => assert!(msg.contains("case-sensitive"), "got: {msg}"),
+ other => panic!("expected Parse error, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn classify_rejects_other_schemes() {
+ for bad in ["http://example.com", "https://example.com", "file:///etc"] {
+ let err = classify_key(bad).expect_err("should reject");
+ match err {
+ Error::Parse(msg) => assert!(msg.contains("looks like a URI"), "got: {msg}"),
+ other => panic!("expected Parse error, got {other:?}"),
+ }
+ }
+ }
+
+ #[test]
+ fn validate_interval_accepts_positive() {
+ for ok in [0.0001_f64, 1.0, 60.0, 1440.0, 1e9] {
+ assert!(validate_interval_minutes(ok).is_ok(), "should accept: {ok}");
+ }
+ }
+
+ #[test]
+ fn validate_interval_rejects_zero_negative_nan() {
+ for bad in [0.0_f64, -1.0, -42.5, f64::NAN] {
+ let err = validate_interval_minutes(bad).expect_err("should reject");
+ match err {
+ Error::Parse(msg) => assert!(msg.contains("minutes must be > 0"), "got: {msg}"),
+ other => panic!("expected Parse error, got {other:?}"),
+ }
+ }
+ }
+
+ #[test]
+ fn update_body_requires_at_least_one_flag() {
+ let err = build_update_body(None, None, None, None).expect_err("should reject");
+ match err {
+ Error::Parse(msg) => assert!(msg.contains("At least one"), "got: {msg}"),
+ other => panic!("expected Parse error, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn update_body_includes_each_field_when_set() {
+ let body = build_update_body(Some(120.0), Some(false), Some("r"), Some("i")).unwrap();
+ let obj = body.as_object().unwrap();
+ assert_eq!(obj["watch_interval"], 120.0);
+ assert_eq!(obj["is_active"], false);
+ assert_eq!(obj["reason"], "r");
+ assert_eq!(obj["instruction"], "i");
+ assert_eq!(obj.len(), 4);
+ }
+
+ #[test]
+ fn update_body_omits_unset_fields() {
+ // Only --active=true given — only is_active should appear in the body
+ let body = build_update_body(None, Some(true), None, None).unwrap();
+ let obj = body.as_object().unwrap();
+ assert_eq!(obj["is_active"], true);
+ assert_eq!(obj.len(), 1);
+ assert!(!obj.contains_key("watch_interval"));
+ }
+
+ #[test]
+ fn update_body_validates_interval() {
+ let err = build_update_body(Some(0.0), None, None, None).expect_err("should reject");
+ match err {
+ Error::Parse(msg) => assert!(msg.contains("minutes must be > 0"), "got: {msg}"),
+ other => panic!("expected Parse error, got {other:?}"),
+ }
+ }
+}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index cd1ef832e..362a7522a 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -715,6 +715,11 @@ enum TaskCommands {
#[arg(long)]
status: Option<String>,
},
+ /// Watch task management (auto-refresh subscriptions)
+ Watch {
+ #[command(subcommand)]
+ action: WatchCommands,
+ },
}
#[derive(Subcommand)]
@@ -808,6 +813,59 @@ enum SessionCommands {
},
}
+#[derive(Subcommand)]
+enum WatchCommands {
+ /// List watch tasks (auto-refresh subscriptions)
+ Ls {
+ /// Only show active (non-paused) tasks
+ #[arg(long, default_value_t = false)]
+ active_only: bool,
+ },
+ /// Show details of a single watch task
+ Show {
+ /// task_id (UUID) or to_uri (viking:// URI)
+ key: String,
+ },
+ /// Delete a watch task
+ Rm {
+ /// task_id (UUID) or to_uri (viking:// URI)
+ key: String,
+ },
+ /// Pause a watch task (preserves cadence, stops scheduling)
+ Pause {
+ /// task_id (UUID) or to_uri (viking:// URI)
+ key: String,
+ },
+ /// Resume a paused watch task
+ Resume {
+ /// task_id (UUID) or to_uri (viking:// URI)
+ key: String,
+ },
+ /// Update one or more mutable fields of a watch task.
+ /// At least one flag is required.
+ Update {
+ /// task_id (UUID) or to_uri (viking:// URI)
+ key: String,
+ /// New refresh interval in minutes (must be > 0)
+ #[arg(long)]
+ interval: Option<f64>,
+ /// Set active (true) / paused (false) — alternative to pause/resume shortcuts
+ #[arg(long)]
+ active: Option<bool>,
+ /// Human-readable reason for the watch task
+ #[arg(long)]
+ reason: Option<String>,
+ /// Processing instruction forwarded to the refresh handler
+ #[arg(long)]
+ instruction: Option<String>,
+ },
+ /// Trigger an immediate refresh, bypassing the schedule
+ Trigger {
+ /// task_id (UUID) or to_uri (viking:// URI)
+ key: String,
+ },
+}
+
#[derive(Subcommand)]
enum PrivacyCommands {
/// List privacy config categories
@@ -1216,6 +1274,63 @@ async fn main() {
)
.await
}
+ TaskCommands::Watch { action } => {
+ let client = ctx.get_client();
+ match action {
+ WatchCommands::Ls { active_only } => {
+ commands::watch::ls(
+ &client,
+ active_only,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ WatchCommands::Show { key } => {
+ commands::watch::show(&client, &key, ctx.output_format, ctx.compact)
+ .await
+ }
+ WatchCommands::Rm { key } => {
+ commands::watch::rm(&client, &key, ctx.output_format, ctx.compact).await
+ }
+ WatchCommands::Pause { key } => {
+ commands::watch::pause(&client, &key, ctx.output_format, ctx.compact)
+ .await
+ }
+ WatchCommands::Resume { key } => {
+ commands::watch::resume(&client, &key, ctx.output_format, ctx.compact)
+ .await
+ }
+ WatchCommands::Update {
+ key,
+ interval,
+ active,
+ reason,
+ instruction,
+ } => {
+ commands::watch::update(
+ &client,
+ &key,
+ interval,
+ active,
+ reason,
+ instruction,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ WatchCommands::Trigger { key } => {
+ commands::watch::trigger(
+ &client,
+ &key,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
+ }
+ }
},
Commands::Status => {
let client = ctx.get_client();
diff --git a/openviking/server/app.py b/openviking/server/app.py
index bdbd99aec..47656cc1c 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -45,6 +45,7 @@ from openviking.server.routers import (
stats_router,
system_router,
tasks_router,
+ watches_router,
webdav_router,
)
from openviking.service.core import OpenVikingService
@@ -511,6 +512,7 @@ def create_app(
app.include_router(observer_router)
app.include_router(metrics_router)
app.include_router(tasks_router)
+ app.include_router(watches_router)
app.include_router(webdav_router)
app.include_router(bot_router, prefix="/bot/v1")
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index bc038c2bd..156cae9e6 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -355,10 +355,31 @@ _LOCAL_FILE_HINT = (
' {"url": "https://your-host", "api_key": "your-key"}'
)
+_WATCH_REQUIRES_TO_HINT = (
+ "watch_interval > 0 requires `to` to be specified (the stable target URI to refresh into). "
+ "Pick a deterministic URI under viking://resources/. For example:\n"
+ " - https://github.com/<org>/<repo> -> to='viking://resources/<org>/<repo>'\n"
+ " - https://example.com/docs/api -> to='viking://resources/example.com/docs/api'\n"
+ "Tip: call add_resource without watch_interval first, observe the returned URI, "
+ "then call again with watch_interval=<minutes> and to=<that URI>."
+)
+
@mcp.tool()
-async def add_resource(path: str, description: str = "") -> str:
- """Add a remote resource (HTTP/HTTPS URL or git URL) to OpenViking. Asynchronous — processed in the background. Local file paths are not supported here; use the `ov add-resource` CLI for local files."""
+async def add_resource(
+ path: str,
+ description: str = "",
+ watch_interval: float = 0,
+ to: str = "",
+) -> str:
+ """Add a remote resource (HTTP/HTTPS URL or git URL) to OpenViking. Asynchronous — processed in the background. Local file paths are not supported here; use the `ov add-resource` CLI for local files.
+
+ Args:
+ path: Remote URL (http(s):// or git URL).
+ description: Optional human-readable reason for adding the resource.
+ watch_interval: Auto-refresh cadence in minutes. 0 (default) = no watch. >0 = periodically re-fetch the resource at that cadence (full re-ingest each time). Prefer >=1440 (24h) unless the source genuinely changes faster — every refresh re-embeds the entire resource. Requires `to`.
+ to: Target URI under viking://resources/ (e.g. "viking://resources/volcengine/OpenViking"). Required when watch_interval > 0. Leave empty for one-shot adds — the system will auto-derive a URI from the source.
+ """
from openviking.server.local_input_guard import require_remote_resource_source
service = get_service()
@@ -367,24 +388,127 @@ async def add_resource(path: str, description: str = "") -> str:
path = require_remote_resource_source(path)
except PermissionDeniedError:
return f"Error: {_LOCAL_FILE_HINT}"
+ if watch_interval < 0:
+ return (
+ "Error: watch_interval must be >= 0. Use 0 for one-shot add (no watch); "
+ "use a positive number of minutes (>=1440 recommended) to subscribe to auto-refresh."
+ )
+ if watch_interval > 0 and not to:
+ return f"Error: {_WATCH_REQUIRES_TO_HINT}"
try:
result = await service.resources.add_resource(
path=path,
ctx=ctx,
+ to=to or None,
reason=description,
wait=False,
+ watch_interval=watch_interval,
enforce_public_remote_targets=True,
)
root_uri = result.get("root_uri", "")
+ if watch_interval > 0:
+ watch_suffix = f" (watch enabled, refresh every {watch_interval:g} minute(s))"
+ else:
+ watch_suffix = ""
return (
- f"Resource added: {root_uri}"
+ f"Resource added: {root_uri}{watch_suffix}"
if root_uri
- else "Resource added (processing in background)."
+ else f"Resource added (processing in background){watch_suffix}."
)
except Exception as e:
return f"Error adding resource: {e}"
+# -- watch management ------------------------------------------------------
+# MCP exposes the minimum closure: list + cancel. Pause/resume/trigger and
+# the unified `update` verb are intentionally NOT exposed — they're either
+# low-value for agents or invite unwanted autonomous decisions. Power users
+# should reach for the REST API or the `ov task watch *` CLI (`pause`,
+# `resume`, `trigger`, `update --interval`, etc.) for those operations.
+
+
+async def list_watches() -> str:
+ """List watch tasks (auto-refresh subscriptions) visible to the current agent.
+
+ Each line shows: target URI, refresh interval (minutes), active/paused status,
+ and the next scheduled execution time. Returns "No watch tasks." when empty.
+ """
+ service = get_service()
+ ctx = _get_ctx()
+ scheduler = getattr(service, "watch_scheduler", None)
+ if scheduler is None or not scheduler.is_running:
+ return "Error: Watch scheduler not running"
+ wm = scheduler.watch_manager
+ if wm is None:
+ return "Error: Watch scheduler not running"
+ # get_all_tasks does not raise PermissionDeniedError — it silently filters
+ # tasks the caller cannot see (watch_manager.py:596-624), so we just
+ # accept the filtered list.
+ tasks = await wm.get_all_tasks(
+ ctx.account_id,
+ ctx.user.user_id,
+ ctx.role.value,
+ active_only=False,
+ agent_id=ctx.user.agent_id,
+ )
+ if not tasks:
+ return "No watch tasks."
+ lines = []
+ for t in tasks:
+ status = "active" if t.is_active else "paused"
+ nxt = t.next_execution_time.isoformat() if t.next_execution_time else "n/a"
+ lines.append(
+ f"- {t.to_uri or '(no uri)'} interval={t.watch_interval:g}m {status} next={nxt}"
+ )
+ return "\n".join(lines)
+
+
+async def cancel_watch(to_uri: str) -> str:
+ """Cancel (delete) a watch task by its target URI.
+
+ The URI must match the watch task's `to` value (e.g. "viking://resources/volcengine/OpenViking").
+ To change the cadence or pause temporarily, cancel and re-add with a new watch_interval.
+ """
+ from openviking.resource import watch_manager as _wm_mod
+
+ service = get_service()
+ ctx = _get_ctx()
+ scheduler = getattr(service, "watch_scheduler", None)
+ if scheduler is None or not scheduler.is_running:
+ return "Error: Watch scheduler not running"
+ wm = scheduler.watch_manager
+ if wm is None:
+ return "Error: Watch scheduler not running"
+ task = await wm.get_task_by_uri(
+ to_uri,
+ ctx.account_id,
+ ctx.user.user_id,
+ ctx.role.value,
+ ctx.user.agent_id,
+ )
+ if task is None:
+ return f"No watch task found for {to_uri}"
+ try:
+ # Return value (bool) is intentionally ignored: delete_task returns
+ # False only when the task was removed between our lookup and the
+ # delete call (a concurrent cancel from another caller). In that case
+ # the post-condition the caller wanted ("no watch on this URI") still
+ # holds, so we report the same success message either way. Permission
+ # errors still surface via the explicit except below.
+ _ = await wm.delete_task(
+ task.task_id,
+ ctx.account_id,
+ ctx.user.user_id,
+ ctx.role.value,
+ ctx.user.agent_id,
+ )
+ except _wm_mod.PermissionDeniedError:
+ return f"Permission denied for {to_uri}"
+ return f"Watch cancelled: {to_uri}"
+
+
# -- grep ------------------------------------------------------------------
diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.py
index 11a2a0f49..5f18b4a5a 100644
--- a/openviking/server/routers/__init__.py
+++ b/openviking/server/routers/__init__.py
@@ -19,6 +19,7 @@ from openviking.server.routers.sessions import router as sessions_router
from openviking.server.routers.stats import router as stats_router
from openviking.server.routers.system import router as system_router
from openviking.server.routers.tasks import router as tasks_router
+from openviking.server.routers.watches import router as watches_router
from openviking.server.routers.webdav import router as webdav_router
__all__ = [
@@ -39,5 +40,6 @@ __all__ = [
"metrics_router",
"observer_router",
"tasks_router",
+ "watches_router",
"webdav_router",
]
diff --git a/openviking/server/routers/watches.py b/openviking/server/routers/watches.py
new file mode 100644
index 000000000..27dcdeb05
--- /dev/null
+++ b/openviking/server/routers/watches.py
@@ -0,0 +1,358 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Watch management endpoints for OpenViking HTTP Server.
+
+Implements RFC #2104 (Watch Management API) on the REST control plane.
+Routes mirror WatchManager primitives with dual-key support: every
+single-resource endpoint accepts either path parameter ``{task_id}`` or
+query parameter ``?to_uri=``. Cross-key conflict returns 400.
+"""
+
+import asyncio
+from typing import Optional
+
+from fastapi import APIRouter, Body, Depends, Path, Query
+from pydantic import BaseModel, ConfigDict, field_validator
+
+from openviking.resource import watch_manager as wm_mod
+from openviking.resource.watch_manager import WatchManager, WatchTask
+from openviking.server.auth import get_request_context
+from openviking.server.dependencies import get_service
+from openviking.server.identity import RequestContext
+from openviking.server.models import Response
+from openviking_cli.exceptions import (
+ FailedPreconditionError,
+ InvalidArgumentError,
+ NotFoundError,
+ PermissionDeniedError,
+)
+
+router = APIRouter(prefix="/api/v1", tags=["watches"])
+
+# Strong refs for in-flight fire-and-forget trigger tasks. Python asyncio
+# only keeps weak references to tasks created via asyncio.create_task, so a
+# task without an external strong reference can be garbage-collected
+# mid-execution and silently aborted. We hold each task here until it
+# completes and discard via done_callback. See
+# https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
+_BACKGROUND_TRIGGER_TASKS: set[asyncio.Task] = set()
+
+
+class UpdateWatchRequest(BaseModel):
+ """Partial-update body for PATCH /watches.
+
+ Any field left unset is preserved on the underlying task. ``is_active``
+ and ``watch_interval`` are orthogonal: flip ``is_active`` to pause/resume
+ without losing the configured cadence.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ watch_interval: Optional[float] = None
+ is_active: Optional[bool] = None
+ reason: Optional[str] = None
+ instruction: Optional[str] = None
+
+ @field_validator("watch_interval")
+ @classmethod
+ def _interval_must_be_positive(cls, value: Optional[float]) -> Optional[float]:
+ # `None` means "leave unchanged" — only validate when the caller
+ # actually supplied a value. Mirrors the CLI/MCP boundary checks so
+ # the three control planes agree on "non-positive is invalid".
+ # Without this, PATCH would persist `watch_interval <= 0`, which then
+ # makes a later `is_active=true` resume fail inside update_task with
+ # ValueError and surface as 404.
+ if value is not None and value <= 0:
+ raise ValueError(
+ "watch_interval must be > 0 (use is_active=false to pause "
+ "without losing the cadence)"
+ )
+ return value
+
+
+def _wm() -> WatchManager:
+ svc = get_service()
+ scheduler = getattr(svc, "watch_scheduler", None)
+ if scheduler is None or not scheduler.is_running:
+ raise FailedPreconditionError("Watch scheduler not running")
+ wm = scheduler.watch_manager
+ if wm is None:
+ raise FailedPreconditionError("Watch scheduler not running")
+ return wm
+
+
+def _scheduler():
+ svc = get_service()
+ scheduler = getattr(svc, "watch_scheduler", None)
+ if scheduler is None or not scheduler.is_running:
+ raise FailedPreconditionError("Watch scheduler not running")
+ return scheduler
+
+
+def _identity(ctx: RequestContext):
+ return (ctx.account_id, ctx.user.user_id, ctx.role.value, ctx.user.agent_id)
+
+
+async def _resolve_task(
+ task_id: Optional[str],
+ to_uri: Optional[str],
+ ctx: RequestContext,
+) -> WatchTask:
+ """Return the task identified by either task_id (path) or to_uri (query).
+
+ When both keys are given they must refer to the same task — this enables
+ callers to double-key cross-validate. Rejection happens only when the
+ two keys disagree, not just because both are present.
+
+ Raises:
+ InvalidArgumentError: neither key supplied, or both supplied but they
+ resolve to different tasks.
+ NotFoundError: no task matches (or caller lacks visibility).
+ """
+ if not task_id and not to_uri:
+ raise InvalidArgumentError("Either {task_id} or ?to_uri= is required")
+
+ wm = _wm()
+ account_id, user_id, role, agent_id = _identity(ctx)
+ if task_id:
+ task = await wm.get_task(task_id, account_id, user_id, role, agent_id)
+ else:
+ task = await wm.get_task_by_uri(to_uri, account_id, user_id, role, agent_id)
+ # `wm.get_task*` return None for both "task does not exist" and "task
+ # exists but the caller fails the permission check" (watch_manager.py
+ # `_check_permission`). Collapsing both into 404 is deliberate: it avoids
+ # leaking the existence of another tenant's task to an unauthorized
+ # caller. The trade-off is that callers see 404 instead of 403 on a
+ # cross-tenant access attempt, which matches the security-first stance
+ # used elsewhere in OpenViking.
+ if task is None:
+ raise NotFoundError(task_id or to_uri or "", "watch_task")
+ if task_id and to_uri and task.to_uri != to_uri:
+ raise InvalidArgumentError(
+ f"task_id {task_id} maps to to_uri={task.to_uri!r}, not {to_uri!r}"
+ )
+ return task
+
+
+def _translate_perm(exc: wm_mod.PermissionDeniedError, target: str) -> PermissionDeniedError:
+ """Convert watch_manager's own PermissionDeniedError (plain Exception)
+ into the OpenVikingError-rooted one so the global handler renders 403.
+ """
+ return PermissionDeniedError(str(exc) or "Permission denied", resource=target)
+
+
[email protected]("/watches")
+async def list_or_get_watch(
+ active_only: bool = Query(False, description="Only return tasks with is_active=true"),
+ to_uri: Optional[str] = Query(None, description="If set, return the single task with this URI"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """List watch tasks, or look one up by ``to_uri``.
+
+ Without ``to_uri`` returns ``{tasks: [...], total: N}``. With ``to_uri``
+ returns the single matching task object (404 if missing). When both
+ ``to_uri`` and ``active_only=true`` are supplied, a paused task at that
+ URI still 404s — the active-only filter stays consistent in both modes.
+ """
+ wm = _wm()
+ account_id, user_id, role, agent_id = _identity(_ctx)
+ if to_uri:
+ task = await wm.get_task_by_uri(to_uri, account_id, user_id, role, agent_id)
+ if task is None or (active_only and not task.is_active):
+ raise NotFoundError(to_uri, "watch_task")
+ return Response(status="ok", result=task.to_dict())
+ tasks = await wm.get_all_tasks(
+ account_id, user_id, role, active_only=active_only, agent_id=agent_id
+ )
+ return Response(
+ status="ok", result={"tasks": [t.to_dict() for t in tasks], "total": len(tasks)}
+ )
+
+
[email protected]("/watches/{task_id}")
+async def get_watch(
+ task_id: str = Path(..., description="Watch task ID"),
+ to_uri: Optional[str] = Query(
+ None,
+ description=(
+ "Optional cross-key sanity check. If supplied, must equal the "
+ "task's current `to_uri`; otherwise the request is rejected with "
+ "400. Useful when the caller has both pieces of information and "
+ "wants to guard against acting on a stale task_id."
+ ),
+ ),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Get a single watch task by ID."""
+ task = await _resolve_task(task_id, to_uri, _ctx)
+ return Response(status="ok", result=task.to_dict())
+
+
+async def _patch_impl(target: WatchTask, body: UpdateWatchRequest, ctx: RequestContext):
+ """Forward to WatchManager.update_task.
+
+ Exception translation: `watch_manager.PermissionDeniedError` is a plain
+ Exception (not an OpenVikingError) so the global handler would not turn it
+ into a 403 — we translate it explicitly. Any other watch_manager exception
+ that already inherits from OpenVikingError (e.g. ConflictError) bubbles
+ untouched and the global handler maps it to the right HTTP status.
+
+ `ValueError` from update_task is currently only used for "task not found"
+ after the inner lock acquires, which is a race window past the
+ `_resolve_task` pre-check (e.g. another caller deleted the task). We map
+ it to 404 to stay consistent with the pre-check behavior.
+ """
+ wm = _wm()
+ account_id, user_id, role, agent_id = _identity(ctx)
+ try:
+ updated = await wm.update_task(
+ target.task_id,
+ account_id,
+ user_id,
+ role,
+ agent_id=agent_id,
+ watch_interval=body.watch_interval,
+ is_active=body.is_active,
+ reason=body.reason,
+ instruction=body.instruction,
+ )
+ except wm_mod.PermissionDeniedError as e:
+ raise _translate_perm(e, target.to_uri or target.task_id) from e
+ except ValueError as e:
+ raise NotFoundError(target.task_id, "watch_task") from e
+ return Response(status="ok", result=updated.to_dict())
+
+
[email protected]("/watches/{task_id}")
+async def patch_watch_by_id(
+ task_id: str = Path(..., description="Watch task ID"),
+ to_uri: Optional[str] = Query(
+ None,
+ description=(
+ "Optional cross-key sanity check. If supplied, must equal the "
+ "task's current `to_uri`; otherwise the request is rejected with "
+ "400. Useful when the caller has both pieces of information and "
+ "wants to guard against acting on a stale task_id — but a wrong "
+ "value here will block DELETE/PATCH/trigger on an otherwise valid "
+ "task, so omit it unless the cross-check is desired."
+ ),
+ ),
+ body: UpdateWatchRequest = Body(...),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Partial update by task_id. Fields left null are preserved."""
+ task = await _resolve_task(task_id, to_uri, _ctx)
+ return await _patch_impl(task, body, _ctx)
+
+
[email protected]("/watches")
+async def patch_watch_by_uri(
+ to_uri: str = Query(..., description="Target URI of the watch task"),
+ body: UpdateWatchRequest = Body(...),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Partial update by to_uri (query parameter)."""
+ task = await _resolve_task(None, to_uri, _ctx)
+ return await _patch_impl(task, body, _ctx)
+
+
+async def _delete_impl(target: WatchTask, ctx: RequestContext):
+ wm = _wm()
+ account_id, user_id, role, agent_id = _identity(ctx)
+ try:
+ ok = await wm.delete_task(target.task_id, account_id, user_id, role, agent_id)
+ except wm_mod.PermissionDeniedError as e:
+ raise _translate_perm(e, target.to_uri or target.task_id) from e
+ if not ok:
+ raise NotFoundError(target.task_id, "watch_task")
+ return Response(
+ status="ok",
+ result={"task_id": target.task_id, "to_uri": target.to_uri, "deleted": True},
+ )
+
+
[email protected]("/watches/{task_id}")
+async def delete_watch_by_id(
+ task_id: str = Path(..., description="Watch task ID"),
+ to_uri: Optional[str] = Query(
+ None,
+ description=(
+ "Optional cross-key sanity check. If supplied, must equal the "
+ "task's current `to_uri`; otherwise the request is rejected with "
+ "400. Useful when the caller has both pieces of information and "
+ "wants to guard against acting on a stale task_id — but a wrong "
+ "value here will block DELETE/PATCH/trigger on an otherwise valid "
+ "task, so omit it unless the cross-check is desired."
+ ),
+ ),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Delete a watch task by ID."""
+ task = await _resolve_task(task_id, to_uri, _ctx)
+ return await _delete_impl(task, _ctx)
+
+
[email protected]("/watches")
+async def delete_watch_by_uri(
+ to_uri: str = Query(..., description="Target URI of the watch task"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Delete a watch task by to_uri."""
+ task = await _resolve_task(None, to_uri, _ctx)
+ return await _delete_impl(task, _ctx)
+
+
+async def _trigger_impl(target: WatchTask):
+ """Dispatch a scheduling request without waiting for execution.
+
+ `WatchScheduler.schedule_task` awaits `_execute_task` inline, which runs
+ the full re-ingest (re-fetch + re-parse + re-embed) and can take many
+ seconds. We don't want HTTP requests blocked for that long, so the call
+ is fired off via `asyncio.create_task` and the response returns
+ immediately with ``scheduled=true``. Actual success/failure is observable
+ via subsequent `GET /watches/{task_id}` (last_execution_time updates).
+ """
+ scheduler = _scheduler()
+ task = asyncio.create_task(scheduler.schedule_task(target.task_id))
+ _BACKGROUND_TRIGGER_TASKS.add(task)
+ task.add_done_callback(_BACKGROUND_TRIGGER_TASKS.discard)
+ return Response(
+ status="ok",
+ result={"task_id": target.task_id, "to_uri": target.to_uri, "scheduled": True},
+ )
+
+
[email protected]("/watches/{task_id}/trigger")
+async def trigger_watch_by_id(
+ task_id: str = Path(..., description="Watch task ID"),
+ to_uri: Optional[str] = Query(
+ None,
+ description=(
+ "Optional cross-key sanity check. If supplied, must equal the "
+ "task's current `to_uri`; otherwise the request is rejected with "
+ "400. Useful when the caller has both pieces of information and "
+ "wants to guard against acting on a stale task_id — but a wrong "
+ "value here will block DELETE/PATCH/trigger on an otherwise valid "
+ "task, so omit it unless the cross-check is desired."
+ ),
+ ),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Immediately schedule the watch task for execution (fire-and-forget).
+
+ Dispatches the scheduling request asynchronously and returns right away;
+ the actual re-fetch runs in the background. Poll
+ ``GET /watches/{task_id}.last_execution_time`` to confirm completion.
+ """
+ task = await _resolve_task(task_id, to_uri, _ctx)
+ return await _trigger_impl(task)
+
+
[email protected]("/watches/trigger")
+async def trigger_watch_by_uri(
+ to_uri: str = Query(..., description="Target URI of the watch task"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Trigger by to_uri (fire-and-forget; see by-id variant for semantics)."""
+ task = await _resolve_task(None, to_uri, _ctx)
+ return await _trigger_impl(task)
diff --git a/tests/server/test_api_watches.py b/tests/server/test_api_watches.py
new file mode 100644
index 000000000..96f2a7a4b
--- /dev/null
+++ b/tests/server/test_api_watches.py
@@ -0,0 +1,249 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Tests for watch management endpoints (RFC #2104)."""
+
+import asyncio
+
+import httpx
+import pytest
+
+
+def watch_manager(service):
+ wm = service.watch_scheduler.watch_manager
+ assert wm is not None, "WatchScheduler must be running for these tests"
+ return wm
+
+
+async def _seed(
+ wm,
+ *,
+ to_uri="viking://resources/test/foo",
+ account="default",
+ user="default",
+ agent="default",
+ role="user",
+ interval=60.0,
+ path="https://example.com/foo",
+):
+ return await wm.create_task(
+ path=path,
+ account_id=account,
+ user_id=user,
+ agent_id=agent,
+ original_role=role,
+ to_uri=to_uri,
+ watch_interval=interval,
+ )
+
+
+async def test_list_empty(client: httpx.AsyncClient):
+ resp = await client.get("/api/v1/watches")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ assert body["result"] == {"tasks": [], "total": 0}
+
+
+async def test_full_lifecycle(client: httpx.AsyncClient, watch_manager, monkeypatch):
+ task = await _seed(watch_manager)
+
+ # List
+ resp = await client.get("/api/v1/watches")
+ body = resp.json()
+ assert body["status"] == "ok"
+ assert body["result"]["total"] == 1
+ assert body["result"]["tasks"][0]["task_id"] == task.task_id
+ assert body["result"]["tasks"][0]["to_uri"] == task.to_uri
+
+ # Get by ID
+ resp = await client.get(f"/api/v1/watches/{task.task_id}")
+ assert resp.status_code == 200
+ assert resp.json()["result"]["task_id"] == task.task_id
+
+ # Get by URI (via list endpoint with ?to_uri=)
+ resp = await client.get("/api/v1/watches", params={"to_uri": task.to_uri})
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["result"]["task_id"] == task.task_id
+
+ # PATCH watch_interval
+ resp = await client.patch(
+ f"/api/v1/watches/{task.task_id}",
+ json={"watch_interval": 4320},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["result"]["watch_interval"] == 4320
+
+ # PATCH is_active=false (pause)
+ resp = await client.patch(
+ f"/api/v1/watches/{task.task_id}",
+ json={"is_active": False},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["result"]["is_active"] is False
+ assert resp.json()["result"]["next_execution_time"] is None
+
+ # POST trigger — monkeypatch scheduler so we don't actually run a fetch.
+ # Class-level setattr means the function is bound as a method, so the
+ # fake must accept `self` (the WatchScheduler instance) as first arg.
+ triggered = []
+ schedule_started = asyncio.Event()
+
+ async def fake_schedule(_self, task_id):
+ triggered.append(task_id)
+ schedule_started.set()
+ return True
+
+ monkeypatch.setattr(
+ "openviking.resource.watch_scheduler.WatchScheduler.schedule_task",
+ fake_schedule,
+ )
+ resp = await client.post(f"/api/v1/watches/{task.task_id}/trigger")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["result"]["scheduled"] is True
+ # Trigger is fire-and-forget — wait briefly for the background task to run.
+ await asyncio.wait_for(schedule_started.wait(), timeout=2.0)
+ assert triggered == [task.task_id]
+
+ # DELETE
+ resp = await client.delete(f"/api/v1/watches/{task.task_id}")
+ assert resp.status_code == 200
+ assert resp.json()["result"]["deleted"] is True
+
+ # Subsequent GET → 404
+ resp = await client.get(f"/api/v1/watches/{task.task_id}")
+ assert resp.status_code == 404
+
+
+async def test_get_by_uri_returns_single_object(client: httpx.AsyncClient, watch_manager):
+ task = await _seed(watch_manager, to_uri="viking://resources/test/uri-keyed")
+ resp = await client.get("/api/v1/watches", params={"to_uri": task.to_uri})
+ assert resp.status_code == 200
+ body = resp.json()
+ # When to_uri is given, result is single object (not the {tasks, total} envelope)
+ assert "task_id" in body["result"]
+ assert "tasks" not in body["result"]
+
+
+async def test_active_only_filter(client: httpx.AsyncClient, watch_manager):
+ active = await _seed(watch_manager, to_uri="viking://resources/test/active")
+ paused = await _seed(watch_manager, to_uri="viking://resources/test/paused")
+ await watch_manager.update_task(paused.task_id, "default", "default", "root", is_active=False)
+
+ resp = await client.get("/api/v1/watches", params={"active_only": "true"})
+ ids = {t["task_id"] for t in resp.json()["result"]["tasks"]}
+ assert active.task_id in ids
+ assert paused.task_id not in ids
+
+ resp = await client.get("/api/v1/watches", params={"active_only": "false"})
+ ids = {t["task_id"] for t in resp.json()["result"]["tasks"]}
+ assert active.task_id in ids
+ assert paused.task_id in ids
+
+
+async def test_dual_key_matching_accepted(client: httpx.AsyncClient, watch_manager):
+ """When both {task_id} and ?to_uri= are supplied and resolve to the SAME task,
+ the request succeeds (useful as a cross-key sanity check from clients that
+ have both pieces of information)."""
+ task = await _seed(watch_manager, to_uri="viking://resources/test/dual-ok")
+ resp = await client.get(f"/api/v1/watches/{task.task_id}", params={"to_uri": task.to_uri})
+ assert resp.status_code == 200
+ assert resp.json()["result"]["task_id"] == task.task_id
+
+
+async def test_dual_key_mismatch_returns_400(client: httpx.AsyncClient, watch_manager):
+ """When {task_id} and ?to_uri= refer to DIFFERENT tasks, return 400."""
+ a = await _seed(watch_manager, to_uri="viking://resources/test/dual-a")
+ b = await _seed(watch_manager, to_uri="viking://resources/test/dual-b")
+ # Use a's task_id but b's to_uri — they disagree.
+ resp = await client.get(f"/api/v1/watches/{a.task_id}", params={"to_uri": b.to_uri})
+ assert resp.status_code == 400
+
+
+async def test_delete_missing_key_400(client: httpx.AsyncClient):
+ """DELETE /watches without {task_id} path and without ?to_uri= must 400."""
+ resp = await client.delete("/api/v1/watches")
+ # The by-uri route requires to_uri as a Query(...) so FastAPI will 422 it.
+ assert resp.status_code == 422
+
+
+async def test_not_found_404(client: httpx.AsyncClient):
+ resp = await client.delete("/api/v1/watches/no-such-task-id")
+ assert resp.status_code == 404
+ resp = await client.get("/api/v1/watches/no-such-task-id")
+ assert resp.status_code == 404
+ resp = await client.patch("/api/v1/watches/no-such-task-id", json={"is_active": False})
+ assert resp.status_code == 404
+
+
+async def test_patch_rejects_non_positive_watch_interval(client: httpx.AsyncClient, watch_manager):
+ """REST PATCH must reject `watch_interval <= 0` at the request boundary.
+
+ Without the field_validator, a negative or zero value would be forwarded
+ to WatchManager.update_task, which deactivates the task and stores the
+ bad cadence. A later resume (`is_active=true`) then fails inside
+ update_task with ValueError → 404, misleading callers about the root
+ cause. Reject upfront with 422 instead, matching CLI/MCP semantics.
+ """
+ task = await _seed(watch_manager, to_uri="viking://resources/test/nonpos")
+ for bad in [-1, 0, -42.5]:
+ resp = await client.patch(
+ f"/api/v1/watches/{task.task_id}",
+ json={"watch_interval": bad},
+ )
+ assert resp.status_code == 422, (
+ f"watch_interval={bad} should be 422, got {resp.status_code}: {resp.text[:200]}"
+ )
+
+
+async def test_patch_rejects_unknown_field(client: httpx.AsyncClient, watch_manager):
+ """UpdateWatchRequest has extra='forbid'; passing a field outside the allowed
+ set (watch_interval / is_active / reason / instruction) returns 422.
+
+ Note: `to_uri` is intentionally NOT exposed via PATCH. WatchManager's
+ update_task supports rebinding to_uri (which is the only mutation that can
+ raise ConflictError on the watch side), but we want to-uri assignment to
+ be a delete-and-recreate operation for clarity, not an in-place mutation.
+ """
+ task = await _seed(watch_manager, to_uri="viking://resources/test/forbid")
+ resp = await client.patch(
+ f"/api/v1/watches/{task.task_id}",
+ json={"to_uri": "viking://resources/test/other"},
+ )
+ assert resp.status_code == 422
+
+
+async def test_trigger_by_uri(client: httpx.AsyncClient, watch_manager, monkeypatch):
+ task = await _seed(watch_manager, to_uri="viking://resources/test/trig")
+
+ triggered = []
+ schedule_started = asyncio.Event()
+
+ async def fake_schedule(_self, task_id):
+ triggered.append(task_id)
+ schedule_started.set()
+ return True
+
+ monkeypatch.setattr(
+ "openviking.resource.watch_scheduler.WatchScheduler.schedule_task",
+ fake_schedule,
+ )
+ resp = await client.post("/api/v1/watches/trigger", params={"to_uri": task.to_uri})
+ assert resp.status_code == 200
+ await asyncio.wait_for(schedule_started.wait(), timeout=2.0)
+ assert triggered == [task.task_id]
+
+
+async def test_patch_partial_preserves_unset_fields(client: httpx.AsyncClient, watch_manager):
+ task = await _seed(watch_manager, to_uri="viking://resources/test/partial")
+ original_interval = task.watch_interval
+
+ # PATCH only is_active — interval should not change
+ resp = await client.patch(f"/api/v1/watches/{task.task_id}", json={"is_active": False})
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["result"]["watch_interval"] == original_interval
+ assert body["result"]["is_active"] is False
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 5977d29cf..f1f4a3263 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -20,10 +20,12 @@ from openviking.server.mcp_endpoint import (
_get_ctx,
_mcp_ctx,
add_resource,
+ cancel_watch,
forget,
glob,
grep,
health,
+ list_watches,
read,
remember,
search,
@@ -323,6 +325,77 @@ async def test_add_resource_rejects_bare_filename_with_cli_hint(service):
assert "ov add-resource" in result
+async def test_add_resource_watch_requires_to(service):
+ """watch_interval > 0 without `to` returns hint about deterministic URI."""
+ result = await add_resource(
+ path="https://example.com/foo",
+ watch_interval=1440,
+ )
+ assert "error" in result.lower()
+ assert "watch_interval > 0 requires `to`" in result
+
+
+async def test_add_resource_rejects_negative_watch_interval(service):
+ """watch_interval < 0 is rejected at the MCP boundary, even when `to` is given.
+
+ Without this guard, a negative value would bypass the `> 0 requires to`
+ check (passing the `> 0` comparison as false) and be forwarded into
+ the service layer with undefined semantics.
+ """
+ result = await add_resource(
+ path="https://example.com/foo",
+ watch_interval=-1,
+ to="viking://resources/test/neg",
+ )
+ assert "error" in result.lower()
+ assert "watch_interval must be >= 0" in result
+
+
+# ---------------------------------------------------------------------------
+# list_watches / cancel_watch tools
+# ---------------------------------------------------------------------------
+
+
+async def _seed_watch(service, to_uri="viking://resources/test/foo"):
+ wm = service.watch_scheduler.watch_manager
+ return await wm.create_task(
+ path="https://example.com/foo",
+ account_id=DEFAULT_CTX.account_id,
+ user_id=DEFAULT_CTX.user.user_id,
+ agent_id=DEFAULT_CTX.user.agent_id,
+ original_role="root",
+ to_uri=to_uri,
+ watch_interval=1440.0,
+ )
+
+
+async def test_list_watches_empty(service):
+ result = await list_watches()
+ assert "no watch" in result.lower()
+
+
+async def test_list_watches_with_seed(service):
+ task = await _seed_watch(service, to_uri="viking://resources/test/list")
+ result = await list_watches()
+ assert task.to_uri in result
+ assert "active" in result.lower()
+ assert "1440" in result
+
+
+async def test_cancel_watch_by_uri(service):
+ task = await _seed_watch(service, to_uri="viking://resources/test/cancel")
+ result = await cancel_watch(to_uri=task.to_uri)
+ assert "cancelled" in result.lower()
+ # Verify it's actually gone
+ follow_up = await list_watches()
+ assert task.to_uri not in follow_up
+
+
+async def test_cancel_watch_not_found(service):
+ result = await cancel_watch(to_uri="viking://resources/never/existed")
+ assert "no watch task found" in result.lower()
+
+
# ---------------------------------------------------------------------------
# forget tool
# ---------------------------------------------------------------------------