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
fix(resources): reject file target used as directory (#4936)
zhanggaoyuanfb26626616f3
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 899ced6dc..df5e80a90 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -80,6 +80,7 @@ from openviking.utils.skill_processor import SkillProcessingPreparation, SkillPrfrom openviking_cli.exceptions import (ConflictError,DeadlineExceededError,+ FailedPreconditionError,InternalError,InvalidArgumentError,NotInitializedError,@@ -1156,6 +1157,7 @@ class ResourceService:create_parent=create_parent,source_info=plan.source_identity,defer_candidate_resolution=defer_candidate_resolution,+ to_is_directory=planned_to_is_directory,)lock_handoff = await self._lock_to_handoff_payload(resource_lock)message_path = plan.path@@ -1270,6 +1272,7 @@ class ResourceService:create_parent: bool,source_info: _ResourceSourceInfo,defer_candidate_resolution: bool,+ to_is_directory: bool,) -> tuple[str, Optional[Dict[str, Any]], bool, bool]:"""Resolve the target and track ownership of a newly reserved empty path."""if not self._resource_processor or not self._viking_fs:@@ -1306,6 +1309,16 @@ class ResourceService:# lock still rejects compliant concurrent writers, and cleanup rechecks# that the target is empty before deleting it.target_preexisting = await self._viking_fs.exists(root_uri, ctx=ctx)+ if to_is_directory and target_preexisting:+ target_stat = await self._viking_fs.stat(root_uri, ctx=ctx, skip_count=True)+ if not target_stat.get("isDir"):+ raise FailedPreconditionError(+ "Target URI already exists as a file and cannot be used as a "+ f"resource directory: {root_uri}. Choose another URI, use "+ "'parent' to add a new resource under a directory, or use "+ "content/write to update the existing file.",+ details={"resource": root_uri, "type": "file"},+ )dst_path = self._viking_fs._uri_to_path(root_uri, ctx=ctx)resource_lock = await self._viking_fs._async_agfs.pathlock_acquire_tree(dst_path,diff --git a/tests/service/test_resource_service_reserved_target_cleanup.py b/tests/service/test_resource_service_reserved_target_cleanup.pyindex 754b2a83c..19748b17d 100644--- a/tests/service/test_resource_service_reserved_target_cleanup.py+++ b/tests/service/test_resource_service_reserved_target_cleanup.py@@ -6,6 +6,7 @@ import pytestfrom openviking.server.identity import RequestContext, Rolefrom openviking.service.resource_service import ResourceServicefrom openviking.storage.queuefs.add_resource_msg import AddResourceMsg+from openviking_cli.exceptions import FailedPreconditionErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -106,8 +107,13 @@ async def test_explicit_target_plan_tracks_reservation_ownership(async def ensure_access(*args, **kwargs):calls.append("acl")+ async def target_stat(*args, **kwargs):+ calls.append("stat")+ return {"isDir": True}+viking_fs = SimpleNamespace(exists=AsyncMock(side_effect=target_exists),+ stat=AsyncMock(side_effect=target_stat),_ensure_access=AsyncMock(side_effect=ensure_access),_uri_to_path=lambda uri, ctx: f"/agfs/{uri}",_async_agfs=SimpleNamespace(pathlock_acquire_tree=AsyncMock(side_effect=acquire_lock)),@@ -131,6 +137,7 @@ async def test_explicit_target_plan_tracks_reservation_ownership(source_format="zip",),defer_candidate_resolution=False,+ to_is_directory=True,)assert planned == (@@ -139,7 +146,61 @@ async def test_explicit_target_plan_tracks_reservation_ownership(False,cleanup_empty_target_on_failure,)- assert calls == ["acl", "exists", "lock", "acl"]+ expected_calls = ["acl", "exists"]+ if target_preexisting:+ expected_calls.append("stat")+ expected_calls.extend(["lock", "acl"])+ assert calls == expected_calls+++async def test_explicit_directory_target_rejects_existing_file():+ lock = {"lease_ref": "lock-1"}+ ctx = _ctx()+ async_agfs = SimpleNamespace(+ pathlock_acquire_tree=AsyncMock(return_value=lock),+ pathlock_release=AsyncMock(),+ )+ viking_fs = SimpleNamespace(+ exists=AsyncMock(return_value=True),+ stat=AsyncMock(return_value={"isDir": False}),+ _ensure_access=AsyncMock(),+ _uri_to_path=lambda uri, ctx: f"/agfs/{uri}",+ _async_agfs=async_agfs,+ )+ processor = SimpleNamespace(+ tree_builder=SimpleNamespace(+ resolve_target_uri=AsyncMock(return_value=("viking://resources/report.md", None))+ )+ )+ service = _service(viking_fs, processor)++ with pytest.raises(+ FailedPreconditionError,+ match="already exists as a file",+ ):+ await service._plan_source_job_target(+ path="report.md",+ ctx=ctx,+ to="viking://resources/report.md",+ parent="",+ create_parent=False,+ source_info=SimpleNamespace(+ source_path="report.md",+ source_name="report.md",+ source_format="markdown",+ ),+ defer_candidate_resolution=False,+ to_is_directory=True,+ )++ viking_fs.stat.assert_awaited_once_with(+ "viking://resources/report.md",+ ctx=ctx,+ skip_count=True,+ )+ async_agfs.pathlock_acquire_tree.assert_not_awaited()+ async_agfs.pathlock_release.assert_not_awaited()@pytest.mark.asyncio