Skip to content

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

fix(cli): return actionable resource errors for fs commands (#1458)

Hao Zhed13bf58cb4b6
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 57eeedab1..3da6e3777 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -267,6 +267,10 @@ impl HttpClient {
// Handle HTTP errors
if !status.is_success() {
+ let error_code = json
+ .get("error")
+ .and_then(|e| e.get("code"))
+ .and_then(|c| c.as_str());
let error_msg = json
.get("error")
.and_then(|e| e.get("message"))
@@ -278,7 +282,10 @@ impl HttpClient {
.map(|s| s.to_string())
})
.unwrap_or_else(|| format!("HTTP error {}", status));
- return Err(Error::Api(error_msg));
+ return Err(Error::Api(match error_code {
+ Some(code) => format!("[{}] {}", code, error_msg),
+ None => error_msg,
+ }));
}
// Handle API errors (status == success but body has error)
diff --git a/crates/ov_cli/src/error.rs b/crates/ov_cli/src/error.rs
index d117d406b..287c348e8 100644
--- a/crates/ov_cli/src/error.rs
+++ b/crates/ov_cli/src/error.rs
@@ -75,7 +75,7 @@ impl From<Error> for CliError {
match err {
Error::Config(msg) => CliError::config(msg),
Error::Network(msg) => CliError::network(msg),
- Error::Api(msg) => CliError::new(format!("API error: {}", msg)),
+ Error::Api(msg) => CliError::new(msg),
Error::Client(msg) => CliError::new(format!("Client error: {}", msg)),
Error::Parse(msg) => CliError::new(format!("Parse error: {}", msg)),
Error::Output(msg) => CliError::new(format!("Output error: {}", msg)),
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index cbb15067f..2e085c699 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -316,12 +316,12 @@ enum Commands {
},
/// Read abstract content (L0)
Abstract {
- /// Viking URI
+ /// Directory URI
uri: String,
},
/// Read overview content (L1)
Overview {
- /// Viking URI
+ /// Directory URI
uri: String,
},
/// Write text content to an existing file
diff --git a/openviking/server/app.py b/openviking/server/app.py
index c96725c44..2f67d8cb9 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -14,6 +14,7 @@ from fastapi.responses import JSONResponse
from openviking.server.api_keys import APIKeyManager
from openviking.server.config import ServerConfig, load_server_config, validate_server_config
from openviking.server.dependencies import set_service
+from openviking.server.error_mapping import map_exception
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
from openviking.server.routers import (
admin_router,
@@ -198,6 +199,26 @@ def create_app(
# Catch-all for unhandled exceptions so clients always get JSON
@app.exception_handler(Exception)
async def general_error_handler(request: Request, exc: Exception):
+ mapped = map_exception(exc)
+ if mapped is not None:
+ http_status = ERROR_CODE_TO_HTTP_STATUS.get(mapped.code, 500)
+ logger.warning(
+ "Mapped unhandled exception to structured API error",
+ extra={"error_code": mapped.code, "error_message": mapped.message},
+ exc_info=exc,
+ )
+ return JSONResponse(
+ status_code=http_status,
+ content=Response(
+ status="error",
+ error=ErrorInfo(
+ code=mapped.code,
+ message=mapped.message,
+ details=mapped.details,
+ ),
+ ).model_dump(),
+ )
+
logger.exception("Unhandled exception")
return JSONResponse(
status_code=500,
diff --git a/openviking/server/error_mapping.py b/openviking/server/error_mapping.py
new file mode 100644
index 000000000..8df4d64e7
--- /dev/null
+++ b/openviking/server/error_mapping.py
@@ -0,0 +1,83 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from openviking.pyagfs.exceptions import (
+ AGFSClientError,
+ AGFSConnectionError,
+ AGFSHTTPError,
+ AGFSTimeoutError,
+)
+from openviking.storage.errors import ResourceBusyError
+from openviking_cli.exceptions import (
+ ConflictError,
+ FailedPreconditionError,
+ InvalidArgumentError,
+ NotFoundError,
+ OpenVikingError,
+ PermissionDeniedError,
+ UnavailableError,
+)
+
+
+def is_not_found_error(exc: Exception) -> bool:
+ if isinstance(exc, FileNotFoundError):
+ return True
+ if isinstance(exc, AGFSHTTPError) and exc.status_code == 404:
+ return True
+ message = str(exc).lower()
+ return "not found" in message or "no such file or directory" in message
+
+
+def map_exception(
+ exc: Exception,
+ *,
+ resource: str | None = None,
+ resource_type: str = "resource",
+) -> OpenVikingError | None:
+ if isinstance(exc, OpenVikingError):
+ return exc
+ if isinstance(exc, ResourceBusyError):
+ return ConflictError(str(exc), resource=resource)
+ if isinstance(exc, PermissionError):
+ return PermissionDeniedError(str(exc), resource=resource)
+ if isinstance(exc, FileNotFoundError):
+ return NotFoundError(resource or str(exc), resource_type)
+ if isinstance(exc, ValueError):
+ message = str(exc)
+ if "not a directory" in message.lower():
+ details = {"resource": resource} if resource else None
+ return FailedPreconditionError(message, details=details)
+ return InvalidArgumentError(message, details={"resource": resource} if resource else None)
+ if isinstance(exc, (AGFSConnectionError, AGFSTimeoutError)):
+ return UnavailableError("storage backend", reason=str(exc))
+ if isinstance(exc, AGFSHTTPError):
+ if exc.status_code == 404 or is_not_found_error(exc):
+ return NotFoundError(resource or str(exc), resource_type)
+ if exc.status_code == 403:
+ return PermissionDeniedError(str(exc), resource=resource)
+ if exc.status_code == 409:
+ return ConflictError(str(exc), resource=resource)
+ if exc.status_code == 400:
+ return InvalidArgumentError(str(exc), details={"resource": resource} if resource else None)
+ if exc.status_code in {500, 502, 503, 504}:
+ return UnavailableError("storage backend", reason=str(exc))
+ if isinstance(exc, AGFSClientError):
+ message = str(exc)
+ if is_not_found_error(exc):
+ return NotFoundError(resource or message, resource_type)
+ lowered = message.lower()
+ if "permission denied" in lowered:
+ return PermissionDeniedError(message, resource=resource)
+ if "already exists" in lowered:
+ return ConflictError(message, resource=resource)
+ if "timeout" in lowered or "connection refused" in lowered:
+ return UnavailableError("storage backend", reason=message)
+ message = str(exc)
+ lowered = message.lower()
+ if is_not_found_error(exc):
+ return NotFoundError(resource or message, resource_type)
+ if "permission denied" in lowered or "access denied" in lowered:
+ return PermissionDeniedError(message, resource=resource)
+ if "timeout" in lowered or "connection refused" in lowered:
+ return UnavailableError("storage backend", reason=message)
+ return None
diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.py
index 59fb6d36b..5ffc21507 100644
--- a/openviking/server/routers/filesystem.py
+++ b/openviking/server/routers/filesystem.py
@@ -10,6 +10,7 @@ from pydantic import BaseModel
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
+from openviking.server.error_mapping import map_exception
from openviking.server.identity import RequestContext
from openviking.server.models import Response
from openviking_cli.exceptions import NotFoundError
@@ -107,6 +108,11 @@ async def stat(
if "not found" in err_msg or "no such file or directory" in err_msg:
raise NotFoundError(uri, "file")
raise
+ except Exception as exc:
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
class MkdirRequest(BaseModel):
@@ -147,11 +153,15 @@ async def rm(
except AGFSNotFoundError:
raise NotFoundError(uri, "file")
except AGFSClientError as e:
- # Fallback for older versions without typed exceptions
err_msg = str(e).lower()
if "not found" in err_msg or "no such file or directory" in err_msg:
raise NotFoundError(uri, "file")
raise
+ except Exception as exc:
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
return Response(status="ok", result={"uri": uri})
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 5f3fdb959..6c99752dc 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -25,6 +25,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from openviking.pyagfs.exceptions import AGFSClientError, AGFSDirectoryNotEmptyError, AGFSHTTPError
from openviking.resource.watch_storage import is_watch_task_control_uri
+from openviking.server.error_mapping import is_not_found_error, map_exception
from openviking.server.identity import RequestContext, Role
from openviking.telemetry import get_current_telemetry
from openviking.utils.time_utils import format_simplified, get_current_timestamp, parse_iso_datetime
@@ -407,7 +408,12 @@ class VikingFS:
try:
stat = self.agfs.stat(path)
is_dir = stat.get("isDir", False) if isinstance(stat, dict) else False
- except Exception:
+ except Exception as exc:
+ if not is_not_found_error(exc):
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
# Path does not exist: clean up any orphan index records and return
uris_to_delete = await self._collect_uris(path, recursive, ctx=ctx)
uris_to_delete.append(target_uri)
@@ -416,6 +422,11 @@ class VikingFS:
return {}
if is_dir:
+ if not recursive:
+ raise FailedPreconditionError(
+ f"Cannot remove directory without --recursive: {uri}",
+ details={"resource": uri, "expected_flag": "recursive"},
+ )
lock_paths = [path]
lock_mode = "subtree"
else:
@@ -877,13 +888,27 @@ class VikingFS:
"""Read directory's L0 summary (.abstract.md)."""
self._ensure_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
- info = self.agfs.stat(path)
+ try:
+ info = self.agfs.stat(path)
+ except Exception as exc:
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
if not info.get("isDir", info.get("is_dir")):
- raise ValueError(f"{uri} is not a directory")
+ raise FailedPreconditionError(
+ f"{uri} is not a directory",
+ details={"resource": uri, "expected": "directory"},
+ )
file_path = f"{path}/.abstract.md"
try:
content_bytes = self._handle_agfs_read(self.agfs.read(file_path))
- except Exception:
+ except Exception as exc:
+ if not is_not_found_error(exc):
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
# Fallback to default if .abstract.md doesn't exist
return f"# {uri}\n\n[Directory abstract is not ready]"
@@ -901,13 +926,27 @@ class VikingFS:
"""Read directory's L1 overview (.overview.md)."""
self._ensure_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
- info = self.agfs.stat(path)
+ try:
+ info = self.agfs.stat(path)
+ except Exception as exc:
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
if not info.get("isDir", info.get("is_dir")):
- raise ValueError(f"{uri} is not a directory")
+ raise FailedPreconditionError(
+ f"{uri} is not a directory",
+ details={"resource": uri, "expected": "directory"},
+ )
file_path = f"{path}/.overview.md"
try:
content_bytes = self._handle_agfs_read(self.agfs.read(file_path))
- except Exception:
+ except Exception as exc:
+ if not is_not_found_error(exc):
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
# Fallback to default if .overview.md doesn't exist
return f"# {uri}\n\n[Directory overview is not ready]"
diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py
index babdcc7f0..e1edc4184 100644
--- a/tests/server/test_api_content.py
+++ b/tests/server/test_api_content.py
@@ -12,21 +12,20 @@ from openviking.server.routers.content import ReindexRequest, reindex
from openviking_cli.session.user_id import UserIdentifier
-async def test_read_content(client_with_resource):
- client, uri = client_with_resource
- # The resource URI may be a directory; list children to find the file
- ls_resp = await client.get(
+async def _first_child_uri(client, uri: str) -> str:
+ response = await client.get(
"/api/v1/fs/ls",
params={"uri": uri, "simple": True, "recursive": True, "output": "original"},
)
- children = ls_resp.json().get("result", [])
- # Find a file (non-directory) to read
- file_uri = None
- if children:
- # ls(simple=True) returns full URIs, use directly
- file_uri = children[0] if isinstance(children[0], str) else None
- if file_uri is None:
- file_uri = uri
+ children = response.json().get("result", [])
+ if children and isinstance(children[0], str):
+ return children[0]
+ return uri
+
+
+async def test_read_content(client_with_resource):
+ client, uri = client_with_resource
+ file_uri = await _first_child_uri(client, uri)
resp = await client.get("/api/v1/content/read", params={"uri": file_uri})
assert resp.status_code == 200
@@ -51,6 +50,28 @@ async def test_overview_content(client_with_resource):
assert body["status"] == "ok"
+async def test_abstract_file_uri_returns_failed_precondition(client_with_resource):
+ client, uri = client_with_resource
+ file_uri = await _first_child_uri(client, uri)
+ resp = await client.get("/api/v1/content/abstract", params={"uri": file_uri})
+ assert resp.status_code == 412
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "FAILED_PRECONDITION"
+ assert "not a directory" in body["error"]["message"]
+
+
+async def test_overview_missing_uri_returns_not_found(client):
+ resp = await client.get(
+ "/api/v1/content/overview",
+ params={"uri": "viking://resources/does-not-exist-for-overview"},
+ )
+ assert resp.status_code == 404
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "NOT_FOUND"
+
+
async def test_reindex_missing_uri(client):
"""Test reindex without uri field returns 422."""
resp = await client.post(
diff --git a/tests/server/test_api_filesystem.py b/tests/server/test_api_filesystem.py
index f034056f5..6d0c26571 100644
--- a/tests/server/test_api_filesystem.py
+++ b/tests/server/test_api_filesystem.py
@@ -5,6 +5,9 @@
import httpx
+from openviking.pyagfs.exceptions import AGFSHTTPError
+from openviking.storage.errors import ResourceBusyError
+
async def test_ls_root(client: httpx.AsyncClient):
resp = await client.get("/api/v1/fs/ls", params={"uri": "viking://"})
@@ -108,11 +111,27 @@ async def test_stat_not_found(client: httpx.AsyncClient):
"/api/v1/fs/stat",
params={"uri": "viking://nonexistent/xyz"},
)
- assert resp.status_code in (404, 500)
+ assert resp.status_code == 404
body = resp.json()
assert body["status"] == "error"
+async def test_rm_directory_without_recursive_returns_failed_precondition(client: httpx.AsyncClient):
+ await client.post(
+ "/api/v1/fs/mkdir",
+ json={"uri": "viking://resources/rm_dir_without_recursive/"},
+ )
+ resp = await client.request(
+ "DELETE",
+ "/api/v1/fs",
+ params={"uri": "viking://resources/rm_dir_without_recursive"},
+ )
+ assert resp.status_code == 412
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "FAILED_PRECONDITION"
+
+
async def test_resource_ops(client_with_resource):
"""Test stat, ls_recursive, mv, rm on a single shared resource."""
import uuid
@@ -148,3 +167,42 @@ async def test_resource_ops(client_with_resource):
resp = await client.request("DELETE", "/api/v1/fs", params={"uri": new_uri, "recursive": True})
assert resp.status_code == 200
assert resp.json()["status"] == "ok"
+
+
+async def test_rm_maps_resource_busy_to_conflict(client, service, monkeypatch):
+ async def fake_rm(uri, ctx=None, recursive=False):
+ raise ResourceBusyError(f"Resource is being processed: {uri}")
+
+ monkeypatch.setattr(service.fs, "rm", fake_rm)
+ resp = await client.request(
+ "DELETE",
+ "/api/v1/fs",
+ params={"uri": "viking://resources/locked", "recursive": True},
+ )
+ assert resp.status_code == 409
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "CONFLICT"
+
+
+async def test_rm_agfs_internal_error_does_not_look_successful(client, service, monkeypatch):
+ class FakeAGFS:
+ def __init__(self, wrapped):
+ self._wrapped = wrapped
+
+ def stat(self, path):
+ raise AGFSHTTPError("Internal server error", 500)
+
+ def __getattr__(self, name):
+ return getattr(self._wrapped, name)
+
+ monkeypatch.setattr(service.fs._viking_fs, "agfs", FakeAGFS(service.fs._viking_fs.agfs))
+ resp = await client.request(
+ "DELETE",
+ "/api/v1/fs",
+ params={"uri": "viking://resources/delete-failure", "recursive": True},
+ )
+ assert resp.status_code == 503
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "UNAVAILABLE"
diff --git a/tests/server/test_api_fs_content_endpoint_suite.py b/tests/server/test_api_fs_content_endpoint_suite.py
new file mode 100644
index 000000000..46445b5d1
--- /dev/null
+++ b/tests/server/test_api_fs_content_endpoint_suite.py
@@ -0,0 +1,288 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from types import SimpleNamespace
+
+import httpx
+
+from openviking.pyagfs.exceptions import AGFSHTTPError
+
+
+def _assert_error(
+ response: httpx.Response,
+ *,
+ status_code: int,
+ error_code: str,
+ message_fragment: str | None = None,
+) -> None:
+ assert response.status_code == status_code
+ body = response.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == error_code
+ if message_fragment is not None:
+ assert message_fragment in body["error"]["message"]
+
+
+async def _first_child_uri(client: httpx.AsyncClient, uri: str) -> str:
+ response = await client.get(
+ "/api/v1/fs/ls",
+ params={"uri": uri, "simple": True, "recursive": True, "output": "original"},
+ )
+ children = response.json().get("result", [])
+ if children and isinstance(children[0], str):
+ return children[0]
+ return uri
+
+
+async def _request_with_handler(app, method: str, url: str, **kwargs) -> httpx.Response:
+ transport = httpx.ASGITransport(app=app, raise_app_exceptions=False)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.request(method, url, **kwargs)
+
+
+class _FakeVikingFS:
+ def __init__(self, exists_result: bool):
+ self._exists_result = exists_result
+
+ async def exists(self, uri, ctx=None):
+ return self._exists_result
+
+
+class _FakeTracker:
+ def __init__(self, *, has_running: bool = False, task_id: str | None = None):
+ self._has_running = has_running
+ self._task_id = task_id
+
+ def has_running(self, *args, **kwargs):
+ return self._has_running
+
+ def create_if_no_running(self, *args, **kwargs):
+ if self._task_id is None:
+ return None
+ return SimpleNamespace(task_id=self._task_id)
+
+
+async def test_ls_permission_denied_returns_structured_error(app, service, monkeypatch):
+ async def fake_ls(*args, **kwargs):
+ raise PermissionError("Access denied for viking://resources")
+
+ monkeypatch.setattr(service.fs, "ls", fake_ls)
+ response = await _request_with_handler(
+ app,
+ "GET",
+ "/api/v1/fs/ls",
+ params={"uri": "viking://resources"},
+ )
+ _assert_error(
+ response,
+ status_code=403,
+ error_code="PERMISSION_DENIED",
+ message_fragment="Access denied",
+ )
+
+
+async def test_tree_missing_uri_returns_not_found(app, service, monkeypatch):
+ async def fake_tree(*args, **kwargs):
+ raise FileNotFoundError("tree target missing")
+
+ monkeypatch.setattr(service.fs, "tree", fake_tree)
+ response = await _request_with_handler(
+ app,
+ "GET",
+ "/api/v1/fs/tree",
+ params={"uri": "viking://resources/missing"},
+ )
+ _assert_error(response, status_code=404, error_code="NOT_FOUND")
+
+
+async def test_stat_backend_unavailable_returns_structured_error(app, service, monkeypatch):
+ async def fake_stat(*args, **kwargs):
+ raise AGFSHTTPError("Internal server error", 500)
+
+ monkeypatch.setattr(service.fs, "stat", fake_stat)
+ response = await _request_with_handler(
+ app,
+ "GET",
+ "/api/v1/fs/stat",
+ params={"uri": "viking://resources/unavailable"},
+ )
+ _assert_error(response, status_code=503, error_code="UNAVAILABLE")
+
+
+async def test_mkdir_permission_denied_returns_structured_error(app, service, monkeypatch):
+ async def fake_mkdir(*args, **kwargs):
+ raise PermissionError("Access denied for viking://resources/blocked")
+
+ monkeypatch.setattr(service.fs, "mkdir", fake_mkdir)
+ response = await _request_with_handler(
+ app,
+ "POST",
+ "/api/v1/fs/mkdir",
+ json={"uri": "viking://resources/blocked"},
+ )
+ _assert_error(response, status_code=403, error_code="PERMISSION_DENIED")
+
+
+async def test_mv_missing_source_returns_not_found(app, service, monkeypatch):
+ async def fake_mv(*args, **kwargs):
+ raise FileNotFoundError("mv source not found")
+
+ monkeypatch.setattr(service.fs, "mv", fake_mv)
+ response = await _request_with_handler(
+ app,
+ "POST",
+ "/api/v1/fs/mv",
+ json={
+ "from_uri": "viking://resources/missing",
+ "to_uri": "viking://resources/target",
+ },
+ )
+ _assert_error(response, status_code=404, error_code="NOT_FOUND")
+
+
+async def test_read_missing_uri_returns_not_found(app, service, monkeypatch):
+ async def fake_read(*args, **kwargs):
+ raise FileNotFoundError("read target missing")
+
+ monkeypatch.setattr(service.fs, "read", fake_read)
+ response = await _request_with_handler(
+ app,
+ "GET",
+ "/api/v1/content/read",
+ params={"uri": "viking://resources/missing.md"},
+ )
+ _assert_error(response, status_code=404, error_code="NOT_FOUND")
+
+
+async def test_download_returns_attachment_response(client_with_resource):
+ client, uri = client_with_resource
+ file_uri = await _first_child_uri(client, uri)
+ response = await client.get("/api/v1/content/download", params={"uri": file_uri})
+ assert response.status_code == 200
+ assert response.content
+ assert response.headers["content-type"] == "application/octet-stream"
+ assert "attachment;" in response.headers["content-disposition"]
+
+
+async def test_download_missing_uri_returns_not_found(app, service, monkeypatch):
+ async def fake_read_file_bytes(*args, **kwargs):
+ raise FileNotFoundError("download target missing")
+
+ monkeypatch.setattr(service.fs, "read_file_bytes", fake_read_file_bytes)
+ response = await _request_with_handler(
+ app,
+ "GET",
+ "/api/v1/content/download",
+ params={"uri": "viking://resources/missing.bin"},
+ )
+ _assert_error(response, status_code=404, error_code="NOT_FOUND")
+
+
+async def test_write_permission_denied_returns_structured_error(app, service, monkeypatch):
+ async def fake_write(*args, **kwargs):
+ raise PermissionError("Access denied for viking://resources/protected.md")
+
+ monkeypatch.setattr(service.fs, "write", fake_write)
+ response = await _request_with_handler(
+ app,
+ "POST",
+ "/api/v1/content/write",
+ json={
+ "uri": "viking://resources/protected.md",
+ "content": "hello",
+ "mode": "replace",
+ },
+ )
+ _assert_error(response, status_code=403, error_code="PERMISSION_DENIED")
+
+
+async def test_reindex_missing_uri_returns_not_found_error_payload(client, monkeypatch):
+ monkeypatch.setattr(
+ "openviking.storage.viking_fs.get_viking_fs",
+ lambda: _FakeVikingFS(False),
+ )
+ response = await client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://resources/missing", "wait": True},
+ )
+ _assert_error(response, status_code=200, error_code="NOT_FOUND")
+
+
+async def test_reindex_sync_conflict_returns_error_payload(client, monkeypatch):
+ monkeypatch.setattr(
+ "openviking.storage.viking_fs.get_viking_fs",
+ lambda: _FakeVikingFS(True),
+ )
+ monkeypatch.setattr(
+ "openviking.service.task_tracker.get_task_tracker",
+ lambda: _FakeTracker(has_running=True),
+ )
+ monkeypatch.setattr(
+ "openviking.server.routers.content.get_service",
+ lambda: SimpleNamespace(),
+ )
+ response = await client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://resources/conflict", "wait": True},
+ )
+ _assert_error(response, status_code=200, error_code="CONFLICT")
+
+
+async def test_reindex_sync_success_returns_ok_payload(client, monkeypatch):
+ async def fake_do_reindex(service, uri, regenerate, ctx):
+ return {"status": "success", "message": "Indexed 1 resources"}
+
+ monkeypatch.setattr(
+ "openviking.storage.viking_fs.get_viking_fs",
+ lambda: _FakeVikingFS(True),
+ )
+ monkeypatch.setattr(
+ "openviking.service.task_tracker.get_task_tracker",
+ lambda: _FakeTracker(has_running=False),
+ )
+ monkeypatch.setattr(
+ "openviking.server.routers.content.get_service",
+ lambda: SimpleNamespace(),
+ )
+ monkeypatch.setattr("openviking.server.routers.content._do_reindex", fake_do_reindex)
+ response = await client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://resources/demo", "wait": True},
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["status"] == "ok"
+ assert body["result"]["status"] == "success"
+
+
+async def test_reindex_async_returns_task_id(client, monkeypatch):
+ created = {"called": False}
+
+ def fake_create_task(coro):
+ created["called"] = True
+ coro.close()
+ return None
+
+ monkeypatch.setattr(
+ "openviking.storage.viking_fs.get_viking_fs",
+ lambda: _FakeVikingFS(True),
+ )
+ monkeypatch.setattr(
+ "openviking.service.task_tracker.get_task_tracker",
+ lambda: _FakeTracker(task_id="task-123"),
+ )
+ monkeypatch.setattr(
+ "openviking.server.routers.content.get_service",
+ lambda: SimpleNamespace(),
+ )
+ monkeypatch.setattr("openviking.server.routers.content.asyncio.create_task", fake_create_task)
+ response = await client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://resources/demo", "wait": False},
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["status"] == "ok"
+ assert body["result"]["status"] == "accepted"
+ assert body["result"]["task_id"] == "task-123"
+ assert created["called"] is True
diff --git a/tests/server/test_error_scenarios.py b/tests/server/test_error_scenarios.py
index a55ae336d..764a0631d 100644
--- a/tests/server/test_error_scenarios.py
+++ b/tests/server/test_error_scenarios.py
@@ -33,7 +33,7 @@ async def test_not_found_resource_returns_structured_error(
"/api/v1/fs/stat",
params={"uri": "viking://does_not_exist"},
)
- assert resp.status_code in (404, 500)
+ assert resp.status_code == 404
body = resp.json()
assert body["status"] == "error"
assert "code" in body["error"]
diff --git a/tests/server/test_server_health.py b/tests/server/test_server_health.py
index e6e076ad6..69445a485 100644
--- a/tests/server/test_server_health.py
+++ b/tests/server/test_server_health.py
@@ -36,7 +36,7 @@ async def test_process_time_header(client: httpx.AsyncClient):
async def test_openviking_error_handler(client: httpx.AsyncClient):
"""Requesting a non-existent resource should return structured error."""
resp = await client.get("/api/v1/fs/stat", params={"uri": "viking://nonexistent/path"})
- assert resp.status_code in (404, 500)
+ assert resp.status_code == 404
body = resp.json()
assert body["status"] == "error"
assert body["error"]["code"] is not None