Skip to content

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

fix(storage): 保留名规则对齐:用户目录 tasks/_system 可列出,multi-write 元数据名统一隐藏并拒写 (#5170)

Zayn Jarvis525d1684b249
diff --git a/crates/ragfs/src/core/internal_names.rs b/crates/ragfs/src/core/internal_names.rs
index 8205164c3..dadfc36cd 100644
--- a/crates/ragfs/src/core/internal_names.rs
+++ b/crates/ragfs/src/core/internal_names.rs
@@ -4,21 +4,12 @@
//! or `.sync_log.json` must import these constants from this single source of truth.
//! There is no dynamic extension mechanism.
-use std::sync::LazyLock;
-
-use regex::Regex;
-
/// Path-lock marker for directory-level locks.
pub const PATH_LOCK_FILE: &str = ".path.ovlock";
/// Prefix for exact (sidecar) lock files: `.exact.ovlock.<safe_name>.<sha1-prefix>`.
pub const EXACT_LOCK_FILE_PREFIX: &str = ".exact.ovlock.";
-static EXACT_LOCK_FILE_RE: LazyLock<Regex> = LazyLock::new(|| {
- Regex::new(r"^\.exact\.ovlock\..+\.[0-9a-f]{16}$")
- .expect("exact lock filename regex must compile")
-});
-
/// Multi-write redirect metadata file.
pub const REDIRECT_FILE: &str = ".redirect.json";
@@ -27,10 +18,37 @@ pub const SYNC_LOG_FILE: &str = ".sync_log.json";
/// Returns `true` when `name` is a runtime path-lock file (`.path.ovlock` or `.exact.ovlock.*`).
pub fn is_hidden_runtime_lock_name(name: &str) -> bool {
- name == PATH_LOCK_FILE || EXACT_LOCK_FILE_RE.is_match(name)
+ // Reserve the whole prefix, including names not produced by the lock resolver.
+ name == PATH_LOCK_FILE || name.starts_with(EXACT_LOCK_FILE_PREFIX)
}
/// Returns `true` when `name` is any hidden internal name (lock files, redirect, sync-log).
pub fn is_hidden_internal_name(name: &str) -> bool {
is_hidden_runtime_lock_name(name) || name == REDIRECT_FILE || name == SYNC_LOG_FILE
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reserves_entire_exact_lock_prefix() {
+ for name in [
+ ".exact.ovlock.",
+ ".exact.ovlock.probe.md",
+ ".exact.ovlock.probe.md.0123456789abcdef",
+ ] {
+ assert!(is_hidden_runtime_lock_name(name));
+ assert!(is_hidden_internal_name(name));
+ }
+ for name in [
+ "probe.md",
+ "tasks",
+ "_system",
+ ".exact.ovlock",
+ "x.exact.ovlock.foo",
+ ] {
+ assert!(!is_hidden_internal_name(name));
+ }
+ }
+}
diff --git a/openviking/server/routers/webdav.py b/openviking/server/routers/webdav.py
index 44678399d..5a695bed9 100644
--- a/openviking/server/routers/webdav.py
+++ b/openviking/server/routers/webdav.py
@@ -18,7 +18,7 @@ from fastapi.responses import Response as FastAPIResponse
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
-from openviking.storage.internal_names import WEBDAV_RESERVED_FILENAMES
+from openviking.storage.internal_names import WEBDAV_RESERVED_FILENAMES, is_storage_internal_name
from openviking.utils.time_utils import parse_iso_datetime
from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
from openviking_cli.utils.uri import VikingURI
@@ -65,7 +65,7 @@ def _ensure_exposed_path(resource_path: str) -> None:
if not resource_path:
return
parts = resource_path.split("/")
- if any(part in WEBDAV_RESERVED_FILENAMES for part in parts):
+ if any(part in WEBDAV_RESERVED_FILENAMES or is_storage_internal_name(part) for part in parts):
raise NotFoundError(resource_path, "resource")
@@ -199,7 +199,7 @@ def _exposed_child_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]
name = str(entry.get("name", "") or "")
if not name or name in {".", ".."}:
continue
- if name in WEBDAV_RESERVED_FILENAMES:
+ if name in WEBDAV_RESERVED_FILENAMES or is_storage_internal_name(name):
continue
exposed.append(entry)
return exposed
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 119f45f81..da2723986 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -11,7 +11,7 @@ from collections.abc import Coroutine
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Literal, Optional
from openviking.core.context import ContextLevel
-from openviking.core.namespace import classify_uri, context_type_for_uri, uri_leaf_name
+from openviking.core.namespace import classify_uri, context_type_for_uri, uri_leaf_name, uri_parts
from openviking.privacy import (
UserPrivacyConfigService,
get_skill_name_from_uri,
@@ -30,6 +30,7 @@ from openviking.storage.abstract_overview import (
from openviking.storage.acl import AclAction, AclMode, CreatorAclGrant
from openviking.storage.content_write import ContentWriteCoordinator
from openviking.storage.expr import And, Eq, In, Or
+from openviking.storage.internal_names import is_storage_internal_name
from openviking.storage.queuefs import SemanticMsg, get_queue_manager
from openviking.storage.queuefs.semantic_msg import build_semantic_coalesce_key
from openviking.storage.queuefs.semantic_ops.freshness_policy import FreshnessAction
@@ -41,7 +42,11 @@ from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
from openviking.telemetry.resource_summary import build_queue_status_payload
from openviking.utils.embedding_utils import vectorize_directory_meta
from openviking.utils.tags import normalize_search_tags
-from openviking_cli.exceptions import DeadlineExceededError, NotInitializedError
+from openviking_cli.exceptions import (
+ DeadlineExceededError,
+ InvalidArgumentError,
+ NotInitializedError,
+)
from openviking_cli.utils import VikingURI, get_logger
from openviking_cli.utils.config import get_openviking_config
@@ -316,6 +321,12 @@ class FSService:
)
return entries
+ @staticmethod
+ def _reject_storage_internal_target(uri: str) -> None:
+ """Reject reserved names in targets and implicitly created parent directories."""
+ if any(is_storage_internal_name(part) for part in uri_parts(uri)):
+ raise InvalidArgumentError(f"cannot create storage internal name: {uri}")
+
async def mkdir(
self,
uri: str,
@@ -324,6 +335,7 @@ class FSService:
) -> None:
"""Create directory."""
viking_fs = self._ensure_initialized()
+ self._reject_storage_internal_target(uri)
directory_uri, abstract_uri = self._resolve_directory_uris(uri)
directory_preexisting = await viking_fs.exists(directory_uri, ctx=ctx)
await viking_fs.mkdir(uri, ctx=ctx)
@@ -671,6 +683,7 @@ class FSService:
"""Copy a resource without exposing a cancellable partial transaction."""
from_uri = VikingFS._normalize_transfer_uri(from_uri)
to_uri = VikingFS._normalize_transfer_uri(to_uri)
+ self._reject_storage_internal_target(to_uri)
return await self._finish_transfer_after_caller_cancel(
self._cp_and_refresh(from_uri, to_uri, recursive=recursive, ctx=ctx),
operation="copy",
@@ -729,6 +742,7 @@ class FSService:
"""Move a resource without exposing a cancellable partial transaction."""
from_uri = VikingFS._normalize_transfer_uri(from_uri)
to_uri = VikingFS._normalize_transfer_uri(to_uri)
+ self._reject_storage_internal_target(to_uri)
await self._finish_transfer_after_caller_cancel(
self._mv_and_refresh(from_uri, to_uri, ctx=ctx),
operation="move",
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index 56ae89ce6..42bd75ab4 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -39,6 +39,7 @@ from openviking.storage.abstract_overview import (
)
from openviking.storage.acl import AclAction, CreatorAclGrant
from openviking.storage.errors import LockAcquisitionError, ResourceBusyError
+from openviking.storage.internal_names import is_storage_internal_name
from openviking.storage.queuefs import SemanticMsg, get_queue_manager
from openviking.storage.queuefs.semantic_msg import build_semantic_coalesce_key
from openviking.storage.queuefs.semantic_ops.freshness_policy import FreshnessAction
@@ -1077,6 +1078,10 @@ class ContentWriteCoordinator:
name = uri.rstrip("/").split("/")[-1]
if name in _DERIVED_FILENAMES:
raise InvalidArgumentError(f"cannot write derived semantic file directly: {uri}")
+ if any(is_storage_internal_name(part) for part in uri_parts(uri)):
+ # Ancestors must also be checked: creating parents could otherwise
+ # create hidden directories using storage metadata names.
+ raise InvalidArgumentError(f"cannot write storage internal file directly: {uri}")
if is_watch_task_control_uri(uri):
raise InvalidArgumentError(f"cannot write watch task control file directly: {uri}")
diff --git a/openviking/storage/internal_names.py b/openviking/storage/internal_names.py
index db020d28d..fe75568c4 100644
--- a/openviking/storage/internal_names.py
+++ b/openviking/storage/internal_names.py
@@ -15,13 +15,25 @@ MULTIWRITE_INTERNAL_FILE_NAMES = frozenset(
}
)
-STORAGE_INTERNAL_ENTRY_NAMES = frozenset(
- {
- "_system",
- "tasks",
- *MULTIWRITE_INTERNAL_FILE_NAMES,
- }
-)
+
+def is_storage_internal_name(name: str) -> bool:
+ """Return whether ``name`` is multi-write metadata owned by the storage layer.
+
+ Mirrors ``is_hidden_internal_name`` in ``crates/ragfs/src/core/internal_names.rs``:
+ the directory lock, exact (sidecar) locks, redirect and sync-log files that RAGFS
+ keeps next to user content in any directory. Such an entry is hidden from every
+ listing and must never be created, written, copied or moved by a user.
+
+ The account-root internal directories (``/local/{account}/_system`` and
+ ``/local/{account}/tasks``) are deliberately not part of this predicate: root
+ listings use ``VikingURI.LISTABLE_SCOPES`` as a whitelist, and below the root a
+ user directory that happens to be called ``tasks`` or ``_system`` is ordinary
+ content.
+ """
+ return name in MULTIWRITE_INTERNAL_FILE_NAMES or name.startswith(
+ MULTIWRITE_EXACT_LOCK_FILE_PREFIX
+ )
+
WEBDAV_RESERVED_FILENAMES = frozenset(
{
diff --git a/openviking/storage/resource_diff.py b/openviking/storage/resource_diff.py
index 3045c38e9..a60b5a23f 100644
--- a/openviking/storage/resource_diff.py
+++ b/openviking/storage/resource_diff.py
@@ -32,7 +32,7 @@ from enum import Enum
from typing import Any, Dict, Mapping, Tuple
from openviking.concurrency import bounded_map
-from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
+from openviking.storage.internal_names import is_storage_internal_name
from openviking.storage.resource_rnfv import (
CONTROL_BASENAMES,
FormalEntry,
@@ -364,7 +364,7 @@ def _is_excluded_rel_path(rel_path: str) -> bool:
if not rel_path:
return True
for segment in rel_path.split("/"):
- if segment in STORAGE_INTERNAL_ENTRY_NAMES or segment in CONTROL_BASENAMES:
+ if is_storage_internal_name(segment) or segment in CONTROL_BASENAMES:
return True
return False
diff --git a/openviking/storage/viking_fs/__init__.py b/openviking/storage/viking_fs/__init__.py
index ccbda0cb9..5118395d6 100644
--- a/openviking/storage/viking_fs/__init__.py
+++ b/openviking/storage/viking_fs/__init__.py
@@ -52,7 +52,6 @@ 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.storage.expr import And, PathScope, RawDSL
-from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
# Import mixins
from openviking.storage.viking_fs import _base as _base_mod
diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.py
index 126193b31..3c81007c9 100644
--- a/openviking/storage/viking_fs/_access.py
+++ b/openviking/storage/viking_fs/_access.py
@@ -31,7 +31,7 @@ from openviking.storage.acl import (
normalize_acl_level,
normalize_acl_principal,
)
-from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
+from openviking.storage.internal_names import is_storage_internal_name
from openviking_cli.exceptions import (
FailedPreconditionError,
NotFoundError,
@@ -53,7 +53,7 @@ class _AccessMixin:
# First path segments that the Rust git enumerate.rs prunes from snapshots,
# plus the runtime lock name. Mirrors INTERNAL_FIRST_SEGMENTS in
- # crates/ragfs/src/git/enumerate.rs and VikingFS._INTERNAL_NAMES so that
+ # crates/ragfs/src/git/enumerate.rs so that
# callers fail fast in Python with a clear error rather than passing a
# path that the Rust side will silently drop.
_GIT_INTERNAL_FIRST_SEGMENTS = frozenset(
@@ -445,7 +445,7 @@ class _AccessMixin:
parts = [p for p in parent_path.strip("/").split("/") if p]
if len(parts) == 2 and parts[0] == "local":
return name in VikingURI.LISTABLE_SCOPES
- return name not in STORAGE_INTERNAL_ENTRY_NAMES
+ return not is_storage_internal_name(name)
def _ancestor_is_filtered(self, entry_path: str, base_path: str) -> bool:
"""Check if any ancestor directory of entry_path would be filtered by _ls_entries.
diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py
index 6cde8f26c..5b4d48ad7 100644
--- a/openviking/storage/viking_fs/_ops.py
+++ b/openviking/storage/viking_fs/_ops.py
@@ -29,7 +29,7 @@ from openviking.storage.abstract_overview import (
)
from openviking.storage.acl import AclAction, is_acl_uri
from openviking.storage.expr import And, PathScope, RawDSL
-from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
+from openviking.storage.internal_names import is_storage_internal_name
from openviking.storage.vector_ids import is_vector_record_id, vector_record_id
from openviking.storage.viking_fs._base import (
_ABSTRACT_WORKER_COUNT,
@@ -1542,9 +1542,9 @@ class _OpsMixin:
relative_parts = entry_parts[len(root_parts) :]
if not is_dir and name.startswith("."):
return False
- if name in STORAGE_INTERNAL_ENTRY_NAMES:
+ if is_storage_internal_name(name):
return False
- return all(part not in STORAGE_INTERNAL_ENTRY_NAMES for part in relative_parts)
+ return not any(is_storage_internal_name(part) for part in relative_parts)
async def _fill_remote_glob_entry_fields(
self,
@@ -2566,7 +2566,7 @@ class _OpsMixin:
parts = [p for p in path.strip("/").split("/") if p]
if len(parts) == 2 and parts[0] == "local":
return [e for e in entries if e.get("name") in VikingURI.LISTABLE_SCOPES]
- return [e for e in entries if e.get("name") not in STORAGE_INTERNAL_ENTRY_NAMES]
+ return [e for e in entries if not is_storage_internal_name(str(e.get("name", "")))]
async def _ls_entries(
self,
diff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.py
index d3df8e8d1..84da449fd 100644
--- a/openviking/utils/resource_processor.py
+++ b/openviking/utils/resource_processor.py
@@ -30,7 +30,7 @@ from openviking.storage.acl import AclAction, CreatorAclGrant
from openviking.storage.errors import LockAcquisitionError
from openviking.storage.expr import And, Eq, PathScope
from openviking.storage.index_action import FieldPatch
-from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES
+from openviking.storage.internal_names import is_storage_internal_name
from openviking.storage.queuefs.semantic_processor import SemanticProcessor
from openviking.storage.resource_rnfv import RequestIntent
from openviking.storage.viking_fs import LS_ALL_NODES, get_viking_fs
@@ -917,7 +917,7 @@ class ResourceProcessor:
if not name or name in {".", ".."}:
continue
names.append(str(name))
- if all(name in STORAGE_INTERNAL_ENTRY_NAMES for name in names):
+ if all(is_storage_internal_name(name) for name in names):
target_preexisting = False
except Exception:
pass
diff --git a/tests/misc/test_vikingfs_uri_guard.py b/tests/misc/test_vikingfs_uri_guard.py
index 5dd2ec144..25e3c8f01 100644
--- a/tests/misc/test_vikingfs_uri_guard.py
+++ b/tests/misc/test_vikingfs_uri_guard.py
@@ -120,9 +120,7 @@ class TestVikingFSURITraversalGuard:
"viking://agent/",
],
)
- async def test_rm_rejects_protected_namespace_roots_before_side_effects(
- self, uri: str
- ) -> None:
+ async def test_rm_rejects_protected_namespace_roots_before_side_effects(self, uri: str) -> None:
fs = _make_viking_fs()
fs._collect_uris = AsyncMock(return_value=[])
fs._delete_from_vector_store = AsyncMock()
@@ -161,9 +159,7 @@ class TestVikingFSURITraversalGuard:
fs.agfs.stat.assert_not_called()
fs.agfs.rm.assert_not_called()
- @pytest.mark.parametrize(
- "uri", ["viking://user/alice", "viking://resources"]
- )
+ @pytest.mark.parametrize("uri", ["viking://user/alice", "viking://resources"])
@pytest.mark.asyncio
async def test_rm_allows_maintenance_scope_roots_for_root(self, uri: str) -> None:
fs = _make_viking_fs()
@@ -388,3 +384,21 @@ class TestVikingFSURITraversalGuard:
entries = await fs._ls_entries("/local/default")
assert [entry["name"] for entry in entries] == ["resources"]
+
+ @pytest.mark.asyncio
+ async def test_ls_entries_below_root_keeps_reserved_root_names(self) -> None:
+ """A directory a user created and can stat must also show up in ls."""
+ fs = _make_viking_fs()
+ fs.agfs.ls.return_value = [
+ {"name": "tasks", "isDir": True},
+ {"name": "_system", "isDir": True},
+ {"name": "notes.md", "isDir": False},
+ {"name": ".path.ovlock", "isDir": False},
+ {"name": ".exact.ovlock.notes.md.0123abcd", "isDir": False},
+ {"name": ".redirect.json", "isDir": False},
+ {"name": ".sync_log.json", "isDir": False},
+ ]
+
+ entries = await fs._ls_entries("/local/default/resources/project")
+
+ assert [entry["name"] for entry in entries] == ["tasks", "_system", "notes.md"]
diff --git a/tests/server/test_api_fs_ls_sort.py b/tests/server/test_api_fs_ls_sort.py
index 1372c0e13..f9ac15a3e 100644
--- a/tests/server/test_api_fs_ls_sort.py
+++ b/tests/server/test_api_fs_ls_sort.py
@@ -67,7 +67,7 @@ async def test_ls_sorts_before_applying_offset_and_node_limit(client, service):
assert mtime_response.json()["result"][0]["name"] == "zz-newest"
assert response.status_code == 200
entries = response.json()["result"]
- assert [entry["name"] for entry in entries] == ["a-299", "a-298"]
+ assert [entry["name"] for entry in entries] == ["tasks", "a-299"]
filtered_page = await client.get(
"/api/v1/fs/ls",
@@ -81,7 +81,8 @@ async def test_ls_sorts_before_applying_offset_and_node_limit(client, service):
)
filtered_entries = filtered_page.json()["result"]
assert len(filtered_entries) == 256
- assert all(entry["name"] != "tasks" for entry in filtered_entries)
+ # A user directory named "tasks" below the account root is ordinary content.
+ assert any(entry["name"] == "tasks" for entry in filtered_entries)
invalid_offset = await client.get(
"/api/v1/fs/ls",
diff --git a/tests/server/test_api_webdav.py b/tests/server/test_api_webdav.py
index 2da34222e..6638e18d2 100644
--- a/tests/server/test_api_webdav.py
+++ b/tests/server/test_api_webdav.py
@@ -114,7 +114,12 @@ async def test_webdav_rejects_direct_access_to_multiwrite_internal_files(client_
def test_webdav_unit_rejects_direct_access_to_multiwrite_internal_files():
- for hidden_name in (".path.ovlock", ".sync_log.json", ".redirect.json"):
+ for hidden_name in (
+ ".path.ovlock",
+ ".exact.ovlock.notes.md.0123abcd",
+ ".sync_log.json",
+ ".redirect.json",
+ ):
try:
_ensure_exposed_path(f"workspace/{hidden_name}")
except NotFoundError:
@@ -126,6 +131,7 @@ def test_webdav_unit_filters_multiwrite_internal_files_from_children():
entries = [
{"name": ".obsidian"},
{"name": ".path.ovlock"},
+ {"name": ".exact.ovlock.notes.md.0123abcd"},
{"name": ".sync_log.json"},
{"name": ".redirect.json"},
{"name": "notes.md"},
diff --git a/tests/server/test_watch_task_acl.py b/tests/server/test_watch_task_acl.py
index 2312f4166..4ca684340 100644
--- a/tests/server/test_watch_task_acl.py
+++ b/tests/server/test_watch_task_acl.py
@@ -139,6 +139,54 @@ async def test_content_write_rejects_watch_task_control_files(user_ctx, uri):
await coordinator.write(uri=uri, content="x", ctx=user_ctx)
+ "uri",
+ [
+ "viking://resources/project/.path.ovlock",
+ "viking://resources/project/.exact.ovlock.",
+ "viking://resources/project/.exact.ovlock.probe.md",
+ "viking://resources/project/.exact.ovlock.notes.md.0123abcd",
+ "viking://resources/project/.redirect.json",
+ "viking://resources/project/.sync_log.json",
+ ],
+)
[email protected]("suffix", ["", "/child.md", "/nested/child.md"])
[email protected]("mode", ["create", "replace", "append"])
+async def test_content_write_rejects_storage_internal_files(user_ctx, uri, suffix, mode):
+ coordinator = ContentWriteCoordinator(_NoWriteVikingFS())
+
+ with pytest.raises(InvalidArgumentError, match="storage internal file"):
+ await coordinator.write(uri=uri + suffix, content="x", mode=mode, ctx=user_ctx)
+
+
+async def test_batch_write_rejects_storage_internal_parent_before_writing(user_ctx):
+ from unittest.mock import AsyncMock
+
+ coordinator = ContentWriteCoordinator(_NoWriteVikingFS())
+ coordinator._validate_batch_root = AsyncMock()
+ with pytest.raises(InvalidArgumentError, match="storage internal file"):
+ await coordinator.batch_write(
+ root_uri="viking://resources/project",
+ operations=[
+ {
+ "uri": "viking://resources/project/.exact.ovlock.probe.md/child.md",
+ "content": "x",
+ "mode": "create",
+ }
+ ],
+ ctx=user_ctx,
+ )
+
+
[email protected]("name", ["tasks", "_system", ".exact.ovlock", "x.exact.ovlock.foo"])
+def test_storage_name_policy_allows_user_directories(name):
+ from openviking.service.fs_service import FSService
+
+ uri = f"viking://resources/project/{name}/notes.md"
+ FSService._reject_storage_internal_target(uri)
+ ContentWriteCoordinator(_NoWriteVikingFS())._ensure_content_write_policy(uri)
+
+
@pytest.mark.parametrize(
"uri",
[
diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.py
index a09ed956e..da6da48ac 100644
--- a/tests/service/test_fs_service.py
+++ b/tests/service/test_fs_service.py
@@ -11,6 +11,7 @@ import pytest
from openviking.server.identity import RequestContext, Role
from openviking.service.fs_service import FSService
+from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.session.user_id import UserIdentifier
@@ -928,6 +929,37 @@ async def test_resource_mv_conflict_fails_before_resource_move(request_context):
@pytest.mark.asyncio
+ "name",
+ [
+ ".path.ovlock",
+ ".exact.ovlock.",
+ ".exact.ovlock.probe.md",
+ ".exact.ovlock.notes.md.0123abcd",
+ ".redirect.json",
+ ".sync_log.json",
+ ],
+)
[email protected]("suffix", ["", "/", "/child", "/child/notes.md"])
+async def test_mkdir_cp_mv_reject_storage_internal_names(request_context, name, suffix):
+ viking_fs = _FakeVikingFS(events=[])
+ service = FSService(viking_fs=viking_fs)
+ target = f"viking://resources/project/{name}{suffix}"
+ viking_fs.exists = AsyncMock()
+ viking_fs.mkdir = AsyncMock()
+
+ with pytest.raises(InvalidArgumentError, match="storage internal name"):
+ await service.mkdir(target, ctx=request_context)
+ with pytest.raises(InvalidArgumentError, match="storage internal name"):
+ await service.cp("viking://resources/project/a.md", target, False, ctx=request_context)
+ with pytest.raises(InvalidArgumentError, match="storage internal name"):
+ await service.mv("viking://resources/project/a.md", target, ctx=request_context)
+ assert viking_fs.mv_calls == []
+ assert viking_fs.cp_calls == []
+ viking_fs.exists.assert_not_called()
+ viking_fs.mkdir.assert_not_called()
+
+
async def test_resource_mv_without_watch_scheduler_moves_resource_directly(request_context):
events = []
viking_fs = _FakeVikingFS(events=events)
diff --git a/tests/storage/test_resource_diff_snapshot.py b/tests/storage/test_resource_diff_snapshot.py
index 7020700ac..00e516b82 100644
--- a/tests/storage/test_resource_diff_snapshot.py
+++ b/tests/storage/test_resource_diff_snapshot.py
@@ -148,11 +148,31 @@ class TestReadFormalTreeSnapshot:
"isDir": False,
"uri": "viking://resources/x/.abstract.md",
},
- {"rel_path": "_system", "isDir": True, "uri": "viking://resources/x/_system"},
+ {
+ "rel_path": ".path.ovlock",
+ "isDir": False,
+ "uri": "viking://resources/x/.path.ovlock",
+ },
+ {
+ "rel_path": "tasks/.exact.ovlock.t.md.0123abcd",
+ "isDir": False,
+ "uri": "viking://resources/x/tasks/.exact.ovlock.t.md.0123abcd",
+ },
+ # A user directory named tasks or _system is ordinary business content.
+ {
+ "rel_path": "tasks/t.md",
+ "isDir": False,
+ "uri": "viking://resources/x/tasks/t.md",
+ },
+ {
+ "rel_path": "_system/s.md",
+ "isDir": False,
+ "uri": "viking://resources/x/_system/s.md",
+ },
]
)
files, complete = await read_target_file_snapshot(vfs, "viking://resources/x", ctx=_Ctx())
- assert set(files) == {"a.py"}
+ assert set(files) == {"a.py", "tasks/t.md", "_system/s.md"}
assert complete is True
diff --git a/tests/storage/test_viking_fs_glob.py b/tests/storage/test_viking_fs_glob.py
index 60fc08d69..5adac94ff 100644
--- a/tests/storage/test_viking_fs_glob.py
+++ b/tests/storage/test_viking_fs_glob.py
@@ -658,9 +658,17 @@ async def test_glob_delegates_to_agfs_with_paging_and_visibility(monkeypatch, fs
"is_dir": False,
},
{
- "path": "/local/test_account/resources/_system/secret.md",
- "rel_path": "_system/secret.md",
- "name": "secret.md",
+ # Multi-write internal file: hidden at every level.
+ "path": "/local/test_account/resources/group/.path.ovlock",
+ "rel_path": "group/.path.ovlock",
+ "name": ".path.ovlock",
+ "is_dir": False,
+ },
+ {
+ # A user directory named "_system" below the root stays visible.
+ "path": "/local/test_account/resources/_system/notes.md",
+ "rel_path": "_system/notes.md",
+ "name": "notes.md",
"is_dir": False,
},
],
@@ -685,17 +693,18 @@ async def test_glob_delegates_to_agfs_with_paging_and_visibility(monkeypatch, fs
monkeypatch.setattr(fs._async_agfs, "glob_directory", fake_glob_directory)
- result = await fs.glob("**/*.md", uri="viking://resources", node_limit=2, ctx=_default_ctx())
+ result = await fs.glob("**/*.md", uri="viking://resources", node_limit=3, ctx=_default_ctx())
assert result == {
"matches": [
"viking://resources/group/a.md",
+ "viking://resources/_system/notes.md",
"viking://resources/group/b.md",
],
- "count": 2,
+ "count": 3,
}
assert [call["continuation_token"] for call in calls] == [None, "tok-1"]
- assert all(call["page_size"] == 2 for call in calls)
+ assert all(call["page_size"] == 3 for call in calls)
@pytest.mark.asyncio
diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.py
index b45b9bd42..63407cd32 100644
--- a/tests/storage/test_viking_fs_tree.py
+++ b/tests/storage/test_viking_fs_tree.py
@@ -220,15 +220,17 @@ def test_is_name_visible_at_account_root(fs, name, parent_path, expected):
[
("my_dir", "/local/test_account/resources", True),
("normal_dir", "/local/test_account/resources/foo", True),
- ("_system", "/local/test_account/resources", False),
- ("tasks", "/local/test_account/resources/bar", False),
+ ("_system", "/local/test_account/resources", True),
+ ("tasks", "/local/test_account/resources/bar", True),
+ ("tasks", "/local/test_account/agent", True),
(".path.ovlock", "/local/test_account/resources", False),
+ (".exact.ovlock.notes.md.0123abcd", "/local/test_account/resources", False),
(".sync_log.json", "/local/test_account/resources", False),
(".redirect.json", "/local/test_account/resources", False),
],
)
def test_is_name_visible_at_non_root(fs, name, parent_path, expected):
- """PY-FLT-004: Non-root internal-name blacklist."""
+ """PY-FLT-004: Below the account root only multi-write internal files are hidden."""
assert fs._is_name_visible_at_path(name, parent_path) == expected
@@ -238,7 +240,9 @@ def test_is_name_visible_at_non_root(fs, name, parent_path, expected):
("/local/test_account/resources/a", "/local/test_account", False),
("/local/test_account/tasks/foo", "/local/test_account", True),
("/local/test_account/tasks/foo/bar.txt", "/local/test_account", True),
- ("/local/test_account/resources/_system/secret.txt", "/local/test_account", True),
+ ("/local/test_account/resources/_system/secret.txt", "/local/test_account", False),
+ ("/local/test_account/resources/tasks/demo/t.md", "/local/test_account", False),
+ ("/local/test_account/resources/.path.ovlock/x", "/local/test_account", True),
("/local/test_account/resources/normal/file.txt", "/local/test_account", False),
("/local/test_account/resources/a/b/c", "/local/test_account", False),
],