Skip to content

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

fix: 统一存储 URI 规范化并兼容中文路径 (#5328)

hezhang-1216d8f675445b2e
diff --git a/openviking/parse/parsers/directory.py b/openviking/parse/parsers/directory.py
index 532eb9461..f7efbdd72 100644
--- a/openviking/parse/parsers/directory.py
+++ b/openviking/parse/parsers/directory.py
@@ -42,6 +42,10 @@ from openviking.parse.parsers.base_parser import BaseParser
from openviking.parse.parsers.media.constants import MEDIA_EXTENSIONS
from openviking.parse.parsers.upload_utils import detect_and_convert_encoding, is_text_file
from openviking.storage.viking_fs import LS_ALL_NODES
+from openviking.utils.path_safety import (
+ _normalize_storage_segments,
+ normalize_storage_target_uri,
+)
from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.utils.logger import get_logger
@@ -63,6 +67,17 @@ _UNDERSTANDING_LIMITERS: WeakKeyDictionary[
] = WeakKeyDictionary()
+def _normalize_output_target(path: str, writer: Optional[ParseArtifactWriter]) -> str:
+ """Normalize a parser output path without assuming its artifact backend."""
+ if path.startswith("viking://"):
+ return normalize_storage_target_uri(path)
+ if writer is None:
+ raise ValueError("non-Viking output paths require an artifact writer")
+ root = writer.ref.root.rstrip("/")
+ relative_path = _normalize_storage_segments(writer.relative_path(path))
+ return f"{root}/{relative_path}" if relative_path else root
+
+
def _get_understanding_limiter(max_concurrent: int) -> asyncio.Semaphore:
"""Return the shared directory Understanding limiter for this event loop."""
loop = asyncio.get_running_loop()
@@ -322,9 +337,10 @@ class DirectoryParser(BaseParser):
writer = await create_parse_artifact_writer(output_store, viking_fs=viking_fs)
output_store = writer.store
temp_uri = writer.ref.root
- target_uri = f"{temp_uri}/{dir_name}"
+ target_uri = _normalize_output_target(f"{temp_uri}/{dir_name}", writer)
+ target_rel = writer.relative_path(target_uri)
await writer.mkdir()
- await writer.mkdir(dir_name)
+ await writer.mkdir(target_rel)
if not processable_files:
root = ResourceNode(
@@ -341,7 +357,7 @@ class DirectoryParser(BaseParser):
warnings=warnings,
)
result.temp_dir_path = temp_uri
- result.artifact_ref = await writer.finalize(resource_rel=dir_name)
+ result.artifact_ref = await writer.finalize(resource_rel=target_rel)
result.meta["file_count"] = 0
result.meta["dir_name"] = dir_name
result.meta["total_processable"] = 0
@@ -506,7 +522,7 @@ class DirectoryParser(BaseParser):
warnings=warnings,
)
result.temp_dir_path = temp_uri
- result.artifact_ref = await writer.finalize(resource_rel=dir_name)
+ result.artifact_ref = await writer.finalize(resource_rel=target_rel)
result.meta["file_count"] = file_count
result.meta["dir_name"] = dir_name
result.meta["total_processable"] = len(processable_files)
@@ -876,7 +892,11 @@ class DirectoryParser(BaseParser):
if preserve_structure:
parent = str(PurePosixPath(classified_file.rel_path).parent)
- dest = f"{target_uri}/{parent}" if parent != "." else target_uri
+ dest = (
+ _normalize_output_target(f"{target_uri}/{parent}", target_writer)
+ if parent != "."
+ else target_uri
+ )
else:
dest = target_uri
source_ref = getattr(sub_result, "artifact_ref", None)
@@ -990,9 +1010,14 @@ class DirectoryParser(BaseParser):
try:
content = detect_and_convert_encoding(src_file.read_bytes(), src_file)
if preserve_structure:
- dst_uri = f"{target_uri}/{rel_path}"
+ dst_uri = _normalize_output_target(
+ f"{target_uri}/{rel_path}", target_writer
+ )
else:
- dst_uri = f"{target_uri}/{PurePosixPath(rel_path).name}"
+ dst_uri = _normalize_output_target(
+ f"{target_uri}/{PurePosixPath(rel_path).name}",
+ target_writer,
+ )
if target_writer is not None:
await target_writer.write_bytes(dst_uri, content)
else:
@@ -1029,9 +1054,12 @@ class DirectoryParser(BaseParser):
try:
content = detect_and_convert_encoding(src_file.read_bytes(), src_file)
if preserve_structure:
- dst_uri = f"{target_uri}/{rel_path}"
+ dst_uri = _normalize_output_target(f"{target_uri}/{rel_path}", target_writer)
else:
- dst_uri = f"{target_uri}/{PurePosixPath(rel_path).name}"
+ dst_uri = _normalize_output_target(
+ f"{target_uri}/{PurePosixPath(rel_path).name}",
+ target_writer,
+ )
if target_writer is not None:
await target_writer.write_bytes(dst_uri, content)
else:
@@ -1138,15 +1166,16 @@ class DirectoryParser(BaseParser):
for entry in destination_entries
if entry.get("name") not in ("", ".", "..")
}
- if payload.get("name") not in destination_names:
+ destination_uri = normalize_storage_target_uri(
+ f"{dest_uri.rstrip('/')}/{payload['name']}"
+ )
+ destination_name = destination_uri.rsplit("/", 1)[-1]
+ if destination_name not in destination_names:
src = payload.get(
"uri",
f"{wrapper_uri.rstrip('/')}/{payload['name']}",
)
- await viking_fs.move_file(
- src,
- f"{dest_uri.rstrip('/')}/{payload['name']}",
- )
+ await viking_fs.move_file(src, destination_uri)
try:
await viking_fs.delete_temp(src_temp_uri)
except Exception:
@@ -1163,7 +1192,7 @@ class DirectoryParser(BaseParser):
):
continue
src = entry.get("uri", f"{src_temp_uri.rstrip('/')}/{name}")
- dst = f"{dest_uri.rstrip('/')}/{name}"
+ dst = normalize_storage_target_uri(f"{dest_uri.rstrip('/')}/{name}")
if DirectoryParser._is_dir_entry(entry):
await DirectoryParser._recursive_move(viking_fs, src, dst)
else:
@@ -1240,7 +1269,7 @@ class DirectoryParser(BaseParser):
):
continue
s = f"{src_uri.rstrip('/')}/{name}"
- d = f"{dst_uri.rstrip('/')}/{name}"
+ d = normalize_storage_target_uri(f"{dst_uri.rstrip('/')}/{name}")
if DirectoryParser._is_dir_entry(entry):
await DirectoryParser._recursive_move(viking_fs, s, d)
else:
diff --git a/openviking/parse/tree_builder.py b/openviking/parse/tree_builder.py
index 765ce3300..02ab9b4b1 100644
--- a/openviking/parse/tree_builder.py
+++ b/openviking/parse/tree_builder.py
@@ -30,6 +30,7 @@ from openviking.parse.parsers.media.utils import get_media_base_uri, get_media_t
from openviking.server.identity import RequestContext
from openviking.storage.viking_fs import get_viking_fs
from openviking.utils import parse_code_hosting_url
+from openviking.utils.path_safety import normalize_storage_target_uri
from openviking_cli.utils import get_logger
from openviking_cli.utils.uri import VikingURI
@@ -93,6 +94,11 @@ class TreeBuilder:
) -> tuple[str, Optional[str]]:
"""Resolve the final target URI and optional unique-name candidate."""
+ if to_uri:
+ to_uri = normalize_storage_target_uri(to_uri)
+ if parent_uri:
+ parent_uri = normalize_storage_target_uri(parent_uri)
+
final_doc_name = VikingURI.sanitize_segment(doc_name)
if source_path and source_format == "repository":
parsed_org_repo = parse_code_hosting_url(source_path)
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 5a1443e63..fb8f14420 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -48,10 +48,12 @@ 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.ingest_options import IngestOptions
+from openviking.utils.path_safety import validate_safe_viking_uri_path
from openviking.utils.tags import normalize_search_tags
from openviking_cli.exceptions import (
DeadlineExceededError,
InvalidArgumentError,
+ NotFoundError,
NotInitializedError,
)
from openviking_cli.utils import VikingURI, get_logger
@@ -1014,7 +1016,14 @@ class FSService:
# always see a real viking:// URI. VikingFS.read_file also resolves, which
# is harmless defense-in-depth when the input was already a URI.
resolved_uri = await self._resolve_uri(uri, ctx)
- content = await viking_fs.read_file(resolved_uri, ctx=ctx)
+ try:
+ content = await viking_fs.read_file(resolved_uri, ctx=ctx)
+ except NotFoundError:
+ if "%20" not in resolved_uri:
+ raise
+ legacy_uri = validate_safe_viking_uri_path(resolved_uri.replace("%20", " "))
+ content = await viking_fs.read_file(legacy_uri, ctx=ctx)
+ resolved_uri = legacy_uri
skill_name = get_skill_name_from_uri(resolved_uri)
if skill_name and self._privacy_config_service:
current = await self._privacy_config_service.get_current(
diff --git a/openviking/storage/abstract_overview.py b/openviking/storage/abstract_overview.py
index 46e663e5f..07a166491 100644
--- a/openviking/storage/abstract_overview.py
+++ b/openviking/storage/abstract_overview.py
@@ -12,7 +12,7 @@ import hashlib
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, Optional, Sequence, TypeVar
-from urllib.parse import quote
+from urllib.parse import quote, unquote
import yaml
@@ -29,9 +29,14 @@ logger = get_logger(__name__)
ABSTRACT_OVERVIEW_FILENAMES = frozenset({".abstract.md", ".overview.md"})
EMBEDDING_METADATA_FIELDS = ("directory",)
_METADATA_ORDER = ("directory", "source", "generated_by", "freshness")
+_MARKDOWN_URI_SAFE_ASCII = frozenset(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~/:"
+)
_MAX_SOURCE_URI_CHARS = 4096
_MAX_LABEL_CHARS = 128
_T = TypeVar("_T")
+_VIKING_URI_BODY_DELIMITERS = frozenset(" \t\r\n)]}>,'\"`")
+_VIKING_URI_TRAILING_PUNCTUATION = frozenset(".,;:!?")
class AbstractOverviewFormatError(ValueError):
@@ -250,6 +255,41 @@ def render_abstract_overview(
return f"---\n{frontmatter}\n---\n\n{body.strip()}\n"
+def markdown_safe_viking_uri(uri: str) -> str:
+ """Encode ASCII-only URI syntax hazards while preserving Unicode path text."""
+
+ if not isinstance(uri, str):
+ raise TypeError("URI must be a string")
+ return "".join(
+ char if ord(char) > 127 or char in _MARKDOWN_URI_SAFE_ASCII else f"%{ord(char):02X}"
+ for char in uri
+ )
+
+
+def _normalize_markdown_viking_uris(text: str) -> str:
+ """Normalize embedded Viking URIs to the canonical Markdown-safe form."""
+
+ normalized: list[str] = []
+ cursor = 0
+ while True:
+ start = text.find("viking://", cursor)
+ if start < 0:
+ normalized.append(text[cursor:])
+ return "".join(normalized)
+ normalized.append(text[cursor:start])
+ end = start + len("viking://")
+ while end < len(text) and text[end] not in _VIKING_URI_BODY_DELIMITERS:
+ end += 1
+ raw_uri = text[start:end]
+ trailing = ""
+ while raw_uri and raw_uri[-1] in _VIKING_URI_TRAILING_PUNCTUATION:
+ trailing = raw_uri[-1] + trailing
+ raw_uri = raw_uri[:-1]
+ normalized.append(markdown_safe_viking_uri(unquote(raw_uri)))
+ normalized.append(trailing)
+ cursor = end
+
+
def rewrite_viking_uri_references(text: str, source_uri: str, target_uri: str) -> str:
"""Rewrite generated raw or URL-encoded URI references within one transfer scope."""
@@ -260,9 +300,11 @@ def rewrite_viking_uri_references(text: str, source_uri: str, target_uri: str) -
if not source or source == target:
return text
+ markdown_safe_target = markdown_safe_viking_uri(target)
variants = (
- (quote(source, safe=":/"), quote(target, safe=":/")),
- (source, target),
+ (quote(source, safe=":/"), markdown_safe_target),
+ (markdown_safe_viking_uri(source), markdown_safe_target),
+ (source, markdown_safe_target),
)
rewritten = text
seen: set[str] = set()
@@ -278,7 +320,7 @@ def rewrite_viking_uri_references(text: str, source_uri: str, target_uri: str) -
lambda _match, replacement=new: replacement,
rewritten,
)
- return rewritten
+ return _normalize_markdown_viking_uris(rewritten)
def rewrite_abstract_overview_for_transfer(
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index 3d0409a97..7572af63d 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -50,7 +50,10 @@ from openviking.telemetry.resource_summary import build_queue_status_payload
from openviking.utils.content_hash import content_md5
from openviking.utils.embedding_utils import vectorize_directory_meta, vectorize_file
from openviking.utils.ingest_options import IngestOptions
-from openviking.utils.path_safety import validate_safe_viking_uri_path
+from openviking.utils.path_safety import (
+ normalize_storage_target_uri,
+ validate_safe_viking_uri_path,
+)
from openviking.utils.tags import normalize_search_tags
from openviking_cli.exceptions import (
AlreadyExistsError,
@@ -136,7 +139,9 @@ class ContentWriteCoordinator:
) -> Dict[str, Any]:
self._validate_mode(mode)
processing_mode = normalize_processing_mode(processing_mode)
- normalized_uri = self._validate_uri_path(uri, field_name="uri")
+ normalized_uri = normalize_storage_target_uri(
+ self._validate_uri_path(uri, field_name="uri")
+ )
self._ensure_content_write_policy(normalized_uri)
await self._viking_fs._ensure_access(normalized_uri, ctx, action=AclAction.WRITE)
ingest_options = IngestOptions.from_search_tags(tags, mode=tag_mode)
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index ea4ec4b7f..97c4fe535 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -8,7 +8,7 @@ import threading
import time
from contextlib import nullcontext
from typing import Any, Awaitable, Callable, Dict, List, Optional, Set, Tuple
-from urllib.parse import quote, unquote, urlsplit
+from urllib.parse import unquote, urlsplit
from openviking.core.namespace import classify_uri
from openviking.observability.context import (
@@ -44,6 +44,7 @@ from openviking.storage.abstract_overview import (
body_for_preview,
deterministic_sample,
freshness_metadata,
+ markdown_safe_viking_uri,
plan_abstract_overview_refresh,
write_abstract_overview,
)
@@ -1334,7 +1335,7 @@ class SemanticProcessor(DequeueHandlerBase):
def _markdown_link_target(dir_uri: str, entry_name: str) -> str:
"""Build a Markdown-safe target without changing the stored Viking URI."""
entry_uri = VikingURI(dir_uri).join(entry_name).uri
- return quote(entry_uri, safe=":/")
+ return markdown_safe_viking_uri(entry_uri)
def _replace_link_references(self, generated_content: str, link_map: Dict[str, str]) -> str:
"""Resolve link placeholders (viking://input_sample_fN / cN) to real URIs.
diff --git a/openviking/utils/path_safety.py b/openviking/utils/path_safety.py
index bcb1733c4..b897da28a 100644
--- a/openviking/utils/path_safety.py
+++ b/openviking/utils/path_safety.py
@@ -42,6 +42,15 @@ def sanitize_relative_viking_path(rel_path: str) -> str:
return rel_path.replace("\\", "/")
+def _normalize_storage_segments(path: str) -> str:
+ return "/".join(
+ VikingURI.sanitize_segment(segment)
+ if any(character.isspace() for character in segment)
+ else segment
+ for segment in path.split("/")
+ )
+
+
def validate_safe_viking_uri_path(uri: str) -> str:
"""Validate a literal storage path, where ``#`` is part of the filename."""
normalized = VikingURI(uri.strip()).uri.rstrip("/")
@@ -56,6 +65,14 @@ def validate_safe_viking_uri_path(uri: str) -> str:
return normalized
+def normalize_storage_target_uri(uri: str) -> str:
+ """Return a safe Viking URI with whitespace-bearing path segments sanitized."""
+ normalized = validate_safe_viking_uri_path(uri)
+ prefix = f"{VikingURI.SCHEME}://"
+ path = normalized[len(prefix) :]
+ return f"{prefix}{_normalize_storage_segments(path)}"
+
+
def safe_join_viking_uri(base_uri: str, rel_path: str) -> str:
"""Join a Viking URI base with a sanitized relative child path."""
safe_rel_path = sanitize_relative_viking_path(rel_path)
diff --git a/tests/misc/test_tree_builder_dedup.py b/tests/misc/test_tree_builder_dedup.py
index 4f1412b86..f94e74ee1 100644
--- a/tests/misc/test_tree_builder_dedup.py
+++ b/tests/misc/test_tree_builder_dedup.py
@@ -112,7 +112,7 @@ class TestFinalizeFromTemp:
assert tree._root_is_file is True
@pytest.mark.asyncio
- async def test_explicit_to_is_preserved_for_single_no_split_file(self):
+ async def test_explicit_to_is_normalized_for_single_no_split_file(self):
from openviking.parse.tree_builder import TreeBuilder
from openviking.server.identity import RequestContext, Role
from openviking_cli.session.user_id import UserIdentifier
@@ -128,11 +128,11 @@ class TestFinalizeFromTemp:
tree = await TreeBuilder().finalize_from_temp(
temp_dir_path="viking://temp/import",
ctx=ctx,
- to_uri="viking://resources/custom-name",
+ to_uri="viking://resources/reports 2026/final draft",
flatten_single_file=True,
)
- assert tree.root.uri == "viking://resources/custom-name"
+ assert tree.root.uri == "viking://resources/reports_2026/final_draft"
assert tree.root.temp_uri == "viking://temp/import/aa/aa.md"
assert tree._root_is_file is True
diff --git a/tests/parse/test_add_directory.py b/tests/parse/test_add_directory.py
index cc8153e3e..af8c1d014 100644
--- a/tests/parse/test_add_directory.py
+++ b/tests/parse/test_add_directory.py
@@ -351,23 +351,25 @@ class TestDirectWriteFiles:
@pytest.mark.asyncio
async def test_local_store_merges_parsed_and_direct_files(self, tmp_path: Path) -> None:
- source = tmp_path / "source"
+ source = tmp_path / "source folder"
source.mkdir()
(source / "guide.md").write_text("# Guide\n\nbody", encoding="utf-8")
- (source / "main.py").write_text("print('ok')", encoding="utf-8")
+ nested = source / "team notes"
+ nested.mkdir()
+ (nested / "main file.py").write_text("print('ok')", encoding="utf-8")
store = LocalParseOutputStore(str(tmp_path / "artifacts"))
result = await DirectoryParser().parse(source, parse_output_store=store)
assert result.artifact_ref is not None
assert result.artifact_ref.backend == "local"
- assert result.artifact_ref.resource_rel == "source"
- root = Path(result.artifact_ref.root) / "source"
- assert (root / "main.py").read_text() == "print('ok')"
+ assert result.artifact_ref.resource_rel == "source_folder"
+ root = Path(result.artifact_ref.root) / "source_folder"
+ assert (root / "team_notes" / "main_file.py").read_text() == "print('ok')"
assert (root / "guide" / "guide.md").read_text() == "# Guide\n\nbody"
assert set(await read_artifact_manifest(store, result.artifact_ref)) == {
- "source/main.py",
- "source/guide/guide.md",
+ "source_folder/team_notes/main_file.py",
+ "source_folder/guide/guide.md",
}
diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py
index 80e6f5fc9..b6369207e 100644
--- a/tests/server/test_api_content.py
+++ b/tests/server/test_api_content.py
@@ -4,12 +4,14 @@
"""Tests for content endpoints: read, abstract, overview, reindex."""
from types import SimpleNamespace
+from unittest.mock import AsyncMock
import pytest
from openviking.server.identity import RequestContext, Role
from openviking.server.routers import content as content_router
from openviking.server.routers.content import ReindexRequest, WriteContentRequest, reindex
+from openviking_cli.exceptions import PermissionDeniedError
from openviking_cli.session.user_id import UserIdentifier
@@ -125,26 +127,38 @@ async def test_write_forwards_clear_without_tags_to_service(monkeypatch):
assert seen["tag_mode"] == "clear"
-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 = 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)
+async def test_read_content(client, service, monkeypatch):
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+ legacy_uri = "viking://resources/业务 域/章节 一.md"
+ encoded_uri = "viking://resources/业务%20域/章节%20一.md"
+ await service.viking_fs.write_file(legacy_uri, "legacy content", ctx=ctx)
- resp = await client.get("/api/v1/content/read", params={"uri": file_uri})
+ resp = await client.get("/api/v1/content/read", params={"uri": encoded_uri})
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "ok"
- assert body["result"] is not None
+ assert body["result"] == "legacy content"
+
+ await service.viking_fs.write_file(encoded_uri, "literal percent20 content", ctx=ctx)
+ resp = await client.get("/api/v1/content/read", params={"uri": encoded_uri})
+ assert resp.status_code == 200
+ assert resp.json()["result"] == "literal percent20 content"
+
+ resp = await client.get(
+ "/api/v1/content/read",
+ params={"uri": "viking://resources/业务%2520域/章节%2520一.md"},
+ )
+ assert resp.status_code == 404
+ assert resp.json()["error"]["code"] == "NOT_FOUND"
+
+ monkeypatch.setattr(
+ service.viking_fs,
+ "read_file",
+ AsyncMock(side_effect=[PermissionDeniedError("denied"), "legacy content"]),
+ )
+ resp = await client.get("/api/v1/content/read", params={"uri": encoded_uri})
+ assert resp.status_code == 403
+ assert resp.json()["error"]["code"] == "PERMISSION_DENIED"
async def test_read_memory_uses_visible_projection_and_raw_bypasses_it(monkeypatch):
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index fb2c88b11..3cbf6dd57 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -1229,8 +1229,8 @@ async def test_create_mode_memory_scope(monkeypatch):
@pytest.mark.asyncio
async def test_create_mode_resource_scope(monkeypatch):
- file_uri = "viking://resources/demo/test.md"
- root_uri = "viking://resources/demo"
+ file_uri = "viking://resources/team_notes/final_draft.md"
+ root_uri = "viking://resources/team_notes"
ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)
viking_fs = _FakeVikingFSForCreate(file_uri=file_uri, root_uri=root_uri, file_exists=False)
coordinator = ContentWriteCoordinator(viking_fs=viking_fs)
@@ -1252,10 +1252,15 @@ async def test_create_mode_resource_scope(monkeypatch):
monkeypatch.setattr(coordinator, "_wait_for_queues", _fake_wait_for_queues)
result = await coordinator.write(
- uri=file_uri, content="content", mode="create", ctx=ctx, wait=True
+ uri="viking://resources/team notes/final draft.md",
+ content="content",
+ mode="create",
+ ctx=ctx,
+ wait=True,
)
assert result["context_type"] == "resource"
- assert viking_fs.content[file_uri] == "content"
+ assert result["uri"] == file_uri
+ assert viking_fs.content == {file_uri: "content"}
class _AnyDirVikingFS:
diff --git a/tests/storage/test_semantic_processor_overview_batching.py b/tests/storage/test_semantic_processor_overview_batching.py
index 8b5212e3b..4b1239ab6 100644
--- a/tests/storage/test_semantic_processor_overview_batching.py
+++ b/tests/storage/test_semantic_processor_overview_batching.py
@@ -133,16 +133,16 @@ async def test_batched_merge_resolves_placeholders_from_merge_output(monkeypatch
)
overview = await SemanticProcessor()._generate_overview(
- "viking://resources/product docs",
+ "viking://resources/业务 docs",
file_summaries=[
{"name": "first file.md", "summary": "first summary"},
- {"name": "second#file.md", "summary": "second summary"},
+ {"name": "第二章#file.md", "summary": "second summary"},
],
children_abstracts=[],
)
assert overview == (
- "[first](viking://resources/product%20docs/first%20file.md) and "
- "[second](viking://resources/product%20docs/second%23file.md)"
+ "[first](viking://resources/业务%20docs/first%20file.md) and "
+ "[second](viking://resources/业务%20docs/第二章%23file.md)"
)
assert "viking://input_sample_" not in overview
diff --git a/tests/storage/test_vector_migration.py b/tests/storage/test_vector_migration.py
index a9b256551..508bb0bfe 100644
--- a/tests/storage/test_vector_migration.py
+++ b/tests/storage/test_vector_migration.py
@@ -99,15 +99,15 @@ def test_rewrite_vector_record_for_move_preserves_metadata(level):
def test_rewrite_vector_record_updates_generated_l1_uri_references(mode):
record = {
"id": "old-id",
- "uri": "viking://resources/source",
+ "uri": "viking://resources/业务域",
"level": 1,
"vector": [0.1],
- "abstract": "[chapter](viking://resources/source/chapter.md)",
+ "abstract": "[chapter](viking://resources/业务域/章节.md)",
"content": """---
-directory: viking://resources/source/
+directory: viking://resources/业务域/
---
-[chapter](viking://resources/source/chapter.md)
+[chapter](viking://resources/%E4%B8%9A%E5%8A%A1%E5%9F%9F/%E7%AB%A0%E8%8A%82.md)
""",
"created_at": 10,
"updated_at": 11,
@@ -116,17 +116,17 @@ directory: viking://resources/source/
result = vector_migration.rewrite_vector_record(
record,
- source_uri="viking://resources/source",
- target_uri="viking://resources/target",
+ source_uri="viking://resources/业务域",
+ target_uri="viking://resources/归档域",
ctx=_ctx(),
mode=mode,
timestamp=123,
)
- assert result["abstract"] == "[chapter](viking://resources/target/chapter.md)"
+ assert result["abstract"] == "[chapter](viking://resources/归档域/章节.md)"
content_doc = parse_abstract_overview(result["content"])
- assert content_doc.metadata["directory"] == "viking://resources/target/"
- assert content_doc.body.strip() == "[chapter](viking://resources/target/chapter.md)"
+ assert content_doc.metadata["directory"] == "viking://resources/归档域/"
+ assert content_doc.body.strip() == "[chapter](viking://resources/归档域/章节.md)"
class FakeVectorStore:
diff --git a/tests/storage/test_viking_fs_cp.py b/tests/storage/test_viking_fs_cp.py
index d8338c04e..c8542cd36 100644
--- a/tests/storage/test_viking_fs_cp.py
+++ b/tests/storage/test_viking_fs_cp.py
@@ -440,7 +440,7 @@ Back to viking://resources/source/data.bin.
"kind": "url",
"uri": "https://example.com/original",
}
- assert "[chapter](viking://resources/target/%E7%AB%A0%E8%8A%82.md)" in overview_doc.body
+ assert "[chapter](viking://resources/target/章节.md)" in overview_doc.body
assert "viking://resources/source" not in target_overview.decode()
target_abstract = agfs.files["/local/acct/resources/target/.abstract.md"]