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
perf(acl): 减少列表和读取接口的重复权限查询 (#6763)
Qin Haojie68e54f1494e9
diff --git a/docs/en/concepts/15-acl.md b/docs/en/concepts/15-acl.mdindex 18654528f..fb37c2371 100644--- a/docs/en/concepts/15-acl.md+++ b/docs/en/concepts/15-acl.md@@ -113,6 +113,8 @@ Delete and move authorize the specified file or directory without checking desceFor a directory, `stat.count` uses the same path and ACL scalar filter and reports the number of context records visible to the caller.+Listing summaries reuse read authorization already completed for that page, without querying ACL again for each entry.+## Retrieval FilteringACL data exists only in the context collection. Each context record stores direct and inherited permissions in native scalar fields:diff --git a/docs/zh/concepts/15-acl.md b/docs/zh/concepts/15-acl.mdindex 84732ab91..9234093cb 100644--- a/docs/zh/concepts/15-acl.md+++ b/docs/zh/concepts/15-acl.md@@ -108,6 +108,8 @@ read user:carol on viking://resources/A/B/C/report.md目录 `stat` 的 `count` 使用相同的路径和 ACL 标量过滤,表示当前用户可见的 context 数量。+列表的摘要和概览复用本次已通过的读取授权,不再为每个条目重复查询 ACL。+## 检索过滤ACL 只保存在 context collection。每条 context 记录维护当前节点和继承权限两组原生标量字段:diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex afb074c39..ed43ca888 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -1474,18 +1474,27 @@ class FSService:viking_fs = self._ensure_initialized()await viking_fs._ensure_access(uri, ctx, action=AclAction.WRITE)- async def _read_content(self, uri: str, ctx: RequestContext) -> tuple[str, str]:+ async def _read_content(+ self, uri: str, ctx: RequestContext, *, max_bytes: int | None = None+ ) -> tuple[str, str]:"""Resolve the URI and read stored content without Privacy restoration."""viking_fs = self._ensure_initialized()resolved_uri = await self._resolve_uri(uri, ctx)+ reader = (+ viking_fs.read_file+ if max_bytes is None+ else partial(viking_fs.read_file_bytes, max_bytes=max_bytes)+ )try:- content = await viking_fs.read_file(resolved_uri, ctx=ctx)+ content = await reader(resolved_uri, ctx=ctx)except NotFoundError:if "%20" not in resolved_uri:raiselegacy_uri = validate_safe_viking_uri_path(resolved_uri.replace("%20", " "))- content = await viking_fs.read_file(legacy_uri, ctx=ctx)+ content = await reader(legacy_uri, ctx=ctx)resolved_uri = legacy_uri+ if max_bytes is not None:+ content = viking_fs._decode_bytes(content)return resolved_uri, contentasync def read(self, uri: str, ctx: RequestContext, offset: int = 0, limit: int = -1) -> str:@@ -1529,24 +1538,20 @@ class FSService:# Resolve id to URI before classify_uri / visible_content which expect# a real viking:// URI.resolved_uri = await self._resolve_uri(uri, ctx)- if self._privacy_sanitizer is not None:- stat = await self._ensure_initialized().stat(- resolved_uri,- ctx=ctx,- skip_count=True,- )- size = stat.get("size") if isinstance(stat, dict) else None- if isinstance(size, int) and size > self._privacy_sanitizer.max_content_bytes:- raise ResourceExhaustedError(- "File exceeds the Privacy visible-read size limit",- details={- "uri": resolved_uri,- "reason": "privacy_visible_read_limit_exceeded",- "size_bytes": size,- "max_bytes": self._privacy_sanitizer.max_content_bytes,- },- )- resolved_uri, content = await self._read_content(resolved_uri, ctx)+ max_bytes = (+ self._privacy_sanitizer.max_content_bytes+ if self._privacy_sanitizer is not None+ else None+ )+ try:+ resolved_uri, content = await self._read_content(resolved_uri, ctx, max_bytes=max_bytes)+ except ResourceExhaustedError as exc:+ if not exc.details or exc.details.get("reason") != "read_limit_exceeded":+ raise+ raise ResourceExhaustedError(+ "File exceeds the Privacy visible-read size limit",+ details={**exc.details, "reason": "privacy_visible_read_limit_exceeded"},+ ) from excif classify_uri(resolved_uri).is_memory:content = visible_content(content, uri=resolved_uri)if self._privacy_sanitizer is not None:diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.pyindex 942b24cfc..8152a37e0 100644--- a/openviking/storage/viking_fs/_access.py+++ b/openviking/storage/viking_fs/_access.py@@ -27,6 +27,7 @@ from openviking.storage.acl import (AclMode,AclSpec,AclUpdate,+ EffectiveAcl,acl_allows,acl_ancestors,has_implicit_manage,@@ -355,18 +356,21 @@ class _AccessMixin:real_ctx.account_id)- async def _ensure_acl_manage(self, uri: str, ctx: Optional[RequestContext]) -> RequestContext:+ async def _ensure_acl_manage(+ self, uri: str, ctx: Optional[RequestContext]+ ) -> tuple[RequestContext, EffectiveAcl | None]:+ """Authorize manage, returning its ACL snapshot unless authority is implicit."""if self.acl_manager is None:raise RuntimeError("ACL is not initialized")real_ctx = self._ctx_or_default(ctx)self._safe_uri_parts(uri)acl_ancestors(uri)if has_implicit_manage(real_ctx, uri):- return real_ctx+ return real_ctx, Noneif await self.acl_manager.is_enabled(real_ctx.account_id):effective = await self.acl_manager.resolve(uri, real_ctx)if acl_allows(effective, real_ctx, AclAction.MANAGE):- return real_ctx+ return real_ctx, effectiveraise PermissionDeniedError(f"ACL management denied for {uri}: manage permission required", resource=uri)@@ -397,9 +401,10 @@ class _AccessMixin:return await acquire(path)async def get_acl(self, uri: str, ctx: Optional[RequestContext] = None) -> Dict[str, Any]:- real_ctx = await self._ensure_acl_manage(uri, ctx)+ real_ctx, effective = await self._ensure_acl_manage(uri, ctx)await self._ensure_acl_target_exists(uri, real_ctx)- effective = await self.acl_manager.resolve(uri, real_ctx)+ if effective is None:+ effective = await self.acl_manager.resolve(uri, real_ctx)return self.acl_manager.to_report(uri, effective)async def prepare_acl_update(@@ -423,7 +428,7 @@ class _AccessMixin:*,acl_mode: AclMode | None = None,) -> Dict[str, Any]:- real_ctx = await self._ensure_acl_manage(uri, ctx)+ real_ctx, _ = await self._ensure_acl_manage(uri, ctx)lease = await self._acquire_acl_target_lock(uri, real_ctx)try:await self._ensure_acl_manage(uri, real_ctx)@@ -459,7 +464,7 @@ class _AccessMixin:) -> Dict[str, Any]:principal = normalize_acl_principal(principal)normalized_level = normalize_acl_level(level) if level is not None else None- real_ctx = await self._ensure_acl_manage(uri, ctx)+ real_ctx, _ = await self._ensure_acl_manage(uri, ctx)lease = await self._acquire_acl_target_lock(uri, real_ctx)try:await self._ensure_acl_manage(uri, real_ctx)diff --git a/openviking/storage/viking_fs/_grep.py b/openviking/storage/viking_fs/_grep.pyindex 8b60b646e..cd8ecad82 100644--- a/openviking/storage/viking_fs/_grep.py+++ b/openviking/storage/viking_fs/_grep.py@@ -70,7 +70,7 @@ class _GrepMixin:Returns:Dict with matches, count, match_count, files_scanned"""- await self._ensure_access(uri, ctx)+ # stat() authorizes the requested path.# Skip vector_store.count() — the count field is not needed for grep,# and avoiding it saves one VikingDB API call.await self.stat(uri, ctx=ctx, skip_count=True)diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.pyindex f19dd1a90..9dd3cc90a 100644--- a/openviking/storage/viking_fs/_ops.py+++ b/openviking/storage/viking_fs/_ops.py@@ -9,7 +9,7 @@ import timeimport uuidfrom dataclasses import replacefrom datetime import datetime, timezone-from typing import Any, Awaitable, Callable, Dict, List, Literal, Optional, Union+from typing import Any, Dict, List, Literal, Optional, Unionfrom openviking.core.context import ContextLevelfrom openviking.core.namespace import (@@ -1620,7 +1620,6 @@ class _OpsMixin:entries,field="abstract",limit=abs_limit,- reader=self._read_abstract_for_known_dir,fallback="[.abstract.md is not ready]",ctx=ctx,)@@ -1636,7 +1635,6 @@ class _OpsMixin:entries,field="overview",limit=overview_limit,- reader=self.overview,fallback="[.overview.md is not ready]",ctx=ctx,)@@ -1645,9 +1643,8 @@ class _OpsMixin:self,entries: List[Dict[str, Any]],*,- field: str,+ field: Literal["abstract", "overview"],limit: int,- reader: Callable[..., Awaitable[str]],fallback: str,ctx: Optional[RequestContext] = None,) -> None:@@ -1678,7 +1675,7 @@ class _OpsMixin:cursor += 1try:- summary = await reader(entry["uri"], ctx=ctx)+ summary = await self._read_directory_summary(entry["uri"], field, ctx=ctx)except Exception:summary = fallbackdiff --git a/openviking/storage/viking_fs/_semantic.py b/openviking/storage/viking_fs/_semantic.pyindex 2f31b1905..f970b082a 100644--- a/openviking/storage/viking_fs/_semantic.py+++ b/openviking/storage/viking_fs/_semantic.py@@ -4,7 +4,7 @@import asynciofrom datetime import datetime, timezone-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Literal, Optional, Unionfrom openviking.core.context import ContextLevelfrom openviking.core.retrieval_targets import resolve_retrieval_targets@@ -37,43 +37,25 @@ class _SemanticMixin:# ========== VikingFS Specific Capabilities ==========- async def _read_abstract_file(- self,- path: str,- uri: str,- ctx: Optional[RequestContext] = None,+ async def _read_directory_summary(+ self, uri: str, field: Literal["abstract", "overview"], ctx: Optional[RequestContext] = None) -> str:- """Read and decrypt/decode .abstract.md from a known directory path.-- Does NOT perform stat or isDir check -- caller is responsible for- ensuring the path points to a directory.- """- file_path = f"{path}/.abstract.md"+ """Read a fixed summary file from an already authorized, known directory."""+ path = self._uri_to_path(uri, ctx=ctx)try:- content_bytes = self._handle_agfs_read(await self._async_agfs.read(file_path))- return body_for_preview(self._decode_bytes(content_bytes))+ raw = self._handle_agfs_read(await self._async_agfs.read(f"{path}/.{field}.md"))+ return body_for_preview(self._decode_bytes(raw))except AbstractOverviewFormatError as exc:- logger.warning("Malformed directory abstract for %s: %s", uri, exc)+ logger.warning("Malformed directory %s for %s: %s", field, uri, exc)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 excraise- return f"# {uri} [Directory abstract is not ready]"-- async def _read_abstract_for_known_dir(- self,- uri: str,- ctx: Optional[RequestContext] = None,- ) -> str:- """Read .abstract.md for a directory that is already known to be a directory.-- Bypasses stat() and isDir check. Caller (i.e. _batch_fetch_abstracts)- must guarantee that the URI points to a directory.- """- await self._ensure_access(uri, ctx)- return await self._read_abstract_file(self._uri_to_path(uri, ctx=ctx), uri, ctx=ctx)+ if field == "abstract":+ return f"# {uri} [Directory abstract is not ready]"+ return f"# {uri}\n\n[Directory overview is not ready]"async def abstract(self,@@ -103,7 +85,7 @@ class _SemanticMixin:parent_uri,)return await self.abstract(parent_uri, ctx=ctx)- return await self._read_abstract_file(path, uri, ctx=ctx)+ return await self._read_directory_summary(uri, "abstract", ctx=ctx)async def overview(self,@@ -133,19 +115,7 @@ class _SemanticMixin:parent_uri,)return await self.overview(parent_uri, ctx=ctx)- file_path = f"{path}/.overview.md"- try:- content_bytes = self._handle_agfs_read(await self._async_agfs.read(file_path))- return body_for_preview(self._decode_bytes(content_bytes))- except AbstractOverviewFormatError as exc:- logger.warning("Malformed directory overview for %s: %s", uri, exc)- 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- return f"# {uri}\n\n[Directory overview is not ready]"+ return await self._read_directory_summary(uri, "overview", ctx=ctx)async def find(self,diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.pyindex b57c52d4d..81be2ae15 100644--- a/tests/service/test_fs_service.py+++ b/tests/service/test_fs_service.py@@ -6,7 +6,7 @@ import asynciofrom contextlib import asynccontextmanagerfrom dataclasses import replacefrom types import SimpleNamespace-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, callimport pytest@@ -18,7 +18,7 @@ from openviking.storage.abstract_overview import body_for_previewfrom openviking.storage.acl import AclActionfrom openviking.storage.errors import LockAcquisitionErrorfrom openviking.storage.viking_fs import VikingFS-from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.exceptions import InvalidArgumentError, ResourceExhaustedErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -324,8 +324,18 @@ async def test_read_visible_strips_supported_memory_metadata_trailers(@pytest.mark.asyncioasync def test_read_visible_preserves_non_memory_content(request_context):raw = 'visible\n<!-- MEMORY_FIELDS {"example":true} -->'- viking_fs = SimpleNamespace(read_file=AsyncMock(return_value=raw))- service = FSService(viking_fs=viking_fs)+ viking_fs = VikingFS(agfs=SimpleNamespace())+ viking_fs._async_agfs = SimpleNamespace(+ stat=AsyncMock(return_value={"isDir": False, "size": len(raw.encode())}),+ read=AsyncMock(return_value=raw.encode()),+ )+ service = FSService(+ viking_fs=viking_fs,+ privacy_sanitizer=SimpleNamespace(+ max_content_bytes=len(raw.encode()),+ sanitize=AsyncMock(return_value=SimpleNamespace(content=raw)),+ ),+ )assert (await service.read_visible(@@ -337,6 +347,13 @@ async def test_read_visible_preserves_non_memory_content(request_context):== '<!-- MEMORY_FIELDS {"example":true} -->')+ # A file that grows after stat must still be rejected by the bounded read.+ viking_fs._async_agfs.read.return_value = raw.encode() + b"extra"+ with pytest.raises(ResourceExhaustedError) as exc:+ await service.read_visible("viking://resources/example.md", ctx=request_context)+ assert exc.value.details["reason"] == "privacy_visible_read_limit_exceeded"+ service._privacy_sanitizer.sanitize.assert_awaited_once()+@pytest.mark.asyncioasync def test_grep_projects_memory_content_but_keeps_resource_fast_path(request_context):@@ -476,10 +493,10 @@ async def test_plain_listing_reads_only_requested_page_summaries(request_contextviking_fs, "_ls_original", AsyncMock(return_value=[dict(e) for e in entries]))monkeypatch.setattr(viking_fs, "_tree_original", AsyncMock(return_value=entries))- abstract = AsyncMock(return_value="L0 summary")- overview = AsyncMock(return_value="L1 overview")- monkeypatch.setattr(viking_fs, "_read_abstract_for_known_dir", abstract)- monkeypatch.setattr(viking_fs, "overview", overview)+ summary = AsyncMock(+ side_effect=lambda uri, field, ctx: "L0 summary" if field == "abstract" else "L1 overview"+ )+ monkeypatch.setattr(viking_fs, "_read_directory_summary", summary)class FakeVikingDB:async def filter(self, **_kwargs):@@ -500,8 +517,14 @@ async def test_plain_listing_reads_only_requested_page_summaries(request_contextassert await service.tree("viking://resources", ctx=request_context) == ListingPage(entries=entries, has_more=False)- abstract.assert_awaited_once_with(selected["uri"], ctx=request_context)- overview.assert_awaited_once_with(selected["uri"], ctx=request_context)+ summary.assert_has_awaits(+ [+ call(selected["uri"], "abstract", ctx=request_context),+ call(selected["uri"], "overview", ctx=request_context),+ ],+ any_order=True,+ )+ assert summary.await_count == 2@pytest.mark.asyncio@@ -705,10 +728,10 @@ async def test_ls_filters_and_paginates_before_reading_summaries(request_contextviking_fs = VikingFS(agfs=SimpleNamespace())monkeypatch.setattr(viking_fs, "_ensure_access", AsyncMock())monkeypatch.setattr(viking_fs, "_ls_original", AsyncMock(side_effect=fake_ls))- abstract = AsyncMock(return_value="L0 summary")- overview = AsyncMock(return_value="L1 overview")- monkeypatch.setattr(viking_fs, "_read_abstract_for_known_dir", abstract)- monkeypatch.setattr(viking_fs, "overview", overview)+ summary = AsyncMock(+ side_effect=lambda uri, field, ctx: "L0 summary" if field == "abstract" else "L1 overview"+ )+ monkeypatch.setattr(viking_fs, "_read_directory_summary", summary)class FakeVikingDB:async def filter(self, **_kwargs):@@ -758,8 +781,14 @@ async def test_ls_filters_and_paginates_before_reading_summaries(request_context],has_more=True,)- abstract.assert_awaited_once_with("viking://resources/docs", ctx=request_context)- overview.assert_awaited_once_with("viking://resources/docs", ctx=request_context)+ summary.assert_has_awaits(+ [+ call("viking://resources/docs", "abstract", ctx=request_context),+ call("viking://resources/docs", "overview", ctx=request_context),+ ],+ any_order=True,+ )+ assert summary.await_count == 2@pytest.mark.asyncio@@ -816,10 +845,10 @@ async def test_tree_projects_directory_tags_before_pagination_and_summaries(]viking_fs = VikingFS(agfs=SimpleNamespace())monkeypatch.setattr(viking_fs, "tree", AsyncMock(return_value=entries))- abstract = AsyncMock(return_value="L0 summary")- overview = AsyncMock(return_value="L1 overview")- monkeypatch.setattr(viking_fs, "_read_abstract_for_known_dir", abstract)- monkeypatch.setattr(viking_fs, "overview", overview)+ summary = AsyncMock(+ side_effect=lambda uri, field, ctx: "L0 summary" if field == "abstract" else "L1 overview"+ )+ monkeypatch.setattr(viking_fs, "_read_directory_summary", summary)class FakeVikingDB:async def filter(self, **_kwargs):@@ -865,8 +894,14 @@ async def test_tree_projects_directory_tags_before_pagination_and_summaries(assert fetch_options["output"] == "original"assert fetch_options["include_abstract"] is Noneassert fetch_options["include_overview"] is False- abstract.assert_awaited_once_with(directory["uri"], ctx=request_context)- overview.assert_awaited_once_with(directory["uri"], ctx=request_context)+ summary.assert_has_awaits(+ [+ call(directory["uri"], "abstract", ctx=request_context),+ call(directory["uri"], "overview", ctx=request_context),+ ],+ any_order=True,+ )+ assert summary.await_count == 2@pytest.mark.asynciodiff --git a/tests/storage/test_viking_fs_acl_locking.py b/tests/storage/test_viking_fs_acl_locking.pyindex 1275e4643..a73faf445 100644--- a/tests/storage/test_viking_fs_acl_locking.py+++ b/tests/storage/test_viking_fs_acl_locking.py@@ -41,7 +41,7 @@ def _fs(agfs):fs = VikingFS(agfs=SimpleNamespace())fs._async_agfs = agfs # type: ignore[assignment]ctx = RequestContext(user=UserIdentifier("default", "alice"), role=Role.ADMIN)- fs._ensure_acl_manage = AsyncMock(return_value=ctx) # type: ignore[method-assign]+ fs._ensure_acl_manage = AsyncMock(return_value=(ctx, None)) # type: ignore[method-assign]fs._uri_to_path = lambda uri, **_: "/local/default/resources/target" # type: ignore[method-assign]fs.acl_manager = SimpleNamespace(set_acl=AsyncMock(return_value="effective"),diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.pyindex c2d89f83b..6a1ede234 100644--- a/tests/storage/test_viking_fs_tree.py+++ b/tests/storage/test_viking_fs_tree.py@@ -659,10 +659,10 @@ async def test_tree_agent_structure(monkeypatch, fs):make_entry("/local/test_account/resources/sub", "sub", size=999, is_dir=True),]patch_tree_env(monkeypatch, fs, entries)- abstract = AsyncMock(return_value="L0 summary")- overview = AsyncMock(return_value="L1 overview")- monkeypatch.setattr(fs, "_read_abstract_for_known_dir", abstract)- monkeypatch.setattr(fs, "overview", overview)+ summary = AsyncMock(+ side_effect=lambda uri, field, ctx: "L0 summary" if field == "abstract" else "L1 overview"+ )+ monkeypatch.setattr(fs, "_read_directory_summary", summary)result = await fs.tree("viking://resources", output="agent", ctx=_default_ctx())@@ -684,9 +684,8 @@ async def test_tree_agent_structure(monkeypatch, fs):"abstract": "L0 summary",},]- abstract.assert_awaited_once_with("viking://resources/sub", ctx=_default_ctx())- overview.assert_not_awaited()- abstract.reset_mock()+ summary.assert_awaited_once_with("viking://resources/sub", "abstract", ctx=_default_ctx())+ summary.reset_mock()result = await fs.tree("viking://resources",@@ -698,8 +697,7 @@ async def test_tree_agent_structure(monkeypatch, fs):assert all("abstract" not in entry for entry in result)assert [entry["overview"] for entry in result] == ["", "L1 overview"]- abstract.assert_not_awaited()- overview.assert_awaited_once_with("viking://resources/sub", ctx=_default_ctx())+ summary.assert_awaited_once_with("viking://resources/sub", "overview", ctx=_default_ctx())@pytest.mark.asyncio@@ -764,10 +762,10 @@ async def test_ls_agent_preserves_metadata_acl_and_summary_controls(monkeypatch,return {uri: not uri.endswith("/restricted") for uri in uris}monkeypatch.setattr(fs, "_can_access_many", fake_can_access_many)- abstract = AsyncMock(return_value="L0 summary")- overview = AsyncMock(return_value="L1 overview")- monkeypatch.setattr(fs, "_read_abstract_for_known_dir", abstract)- monkeypatch.setattr(fs, "overview", overview)+ summary = AsyncMock(+ side_effect=lambda uri, field, ctx: "L0 summary" if field == "abstract" else "L1 overview"+ )+ monkeypatch.setattr(fs, "_read_directory_summary", summary)result = await fs.ls("viking://resources",@@ -786,9 +784,8 @@ async def test_ls_agent_preserves_metadata_acl_and_summary_controls(monkeypatch,"access": "denied",}assert result[2]["abstract"] == "L0 summary"- abstract.assert_awaited_once_with("viking://resources/docs", ctx=_default_ctx())- overview.assert_not_awaited()- abstract.reset_mock()+ summary.assert_awaited_once_with("viking://resources/docs", "abstract", ctx=_default_ctx())+ summary.reset_mock()result = await fs.ls("viking://resources",@@ -801,8 +798,7 @@ async def test_ls_agent_preserves_metadata_acl_and_summary_controls(monkeypatch,assert result[0]["overview"] == ""assert "overview" not in result[1]assert result[2]["overview"] == "L1 overview"- abstract.assert_not_awaited()- overview.assert_awaited_once_with("viking://resources/docs", ctx=_default_ctx())+ summary.assert_awaited_once_with("viking://resources/docs", "overview", ctx=_default_ctx())@pytest.mark.asyncioasync def test_tree_filters_and_paginates_before_summary_reads(monkeypatch, fs):@@ -831,10 +827,10 @@ async def test_tree_filters_and_paginates_before_summary_reads(monkeypatch, fs):return _with_query_relative_paths(page, path)patch_tree_env(monkeypatch, fs, fake_tree_directory)- abstract = AsyncMock(return_value="L0 summary")- overview = AsyncMock(return_value="L1 overview")- monkeypatch.setattr(fs, "_read_abstract_for_known_dir", abstract)- monkeypatch.setattr(fs, "overview", overview)+ summary = AsyncMock(+ side_effect=lambda uri, field, ctx: "L0 summary" if field == "abstract" else "L1 overview"+ )+ monkeypatch.setattr(fs, "_read_directory_summary", summary)result = await fs.tree("viking://resources",@@ -859,8 +855,10 @@ async def test_tree_filters_and_paginates_before_summary_reads(monkeypatch, fs):("L0...", "L1 o..."),("L0...", "L1 o..."),]- for reader in (abstract, overview):- assert sorted(call.args[0] for call in reader.await_args_list) == [+ for field in ("abstract", "overview"):+ assert sorted(+ item.args[0] for item in summary.await_args_list if item.args[1] == field+ ) == ["viking://resources/dir-b","viking://resources/dir-c",]