Skip to content

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

27.5 KB
Raw Blame
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0

from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock

import pytest

from openviking.server.identity import RequestContext, Role
from openviking.storage import viking_fs as viking_fs_module
from openviking.storage.viking_fs import VikingFS
from openviking_cli.session.user_id import UserIdentifier


class _DummyAgfs:
    def stat(self, _path, ctx=None):
        """Return a minimal stat payload for paths assumed to exist in tree tests."""
        return {}


class _FixedDatetime(datetime):
    @classmethod
    def now(cls, tz=None):
        return cls(2026, 6, 11, 1, 0, 0, tzinfo=timezone.utc)


def _default_ctx() -> RequestContext:
    return RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)


@pytest.mark.asyncio
async def test_stat_queries_lock_status_only_when_requested(monkeypatch, fs):
    path = "/local/default/resources/example.md"
    lock_queries = []

    async def resolve_uri(uri, _ctx):
        return uri

    async def ensure_access(_uri, _ctx):
        return None

    async def stat_path(_path):
        return {"name": "example.md", "isDir": False}

    async def is_path_locked(queried_path):
        lock_queries.append(queried_path)
        return True

    monkeypatch.setattr(fs, "resolve_uri", resolve_uri)
    monkeypatch.setattr(fs, "_ensure_access", ensure_access)
    monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: path)
    monkeypatch.setattr(fs._async_agfs, "stat", stat_path)
    monkeypatch.setattr(fs, "_is_path_locked_async", is_path_locked)

    result = await fs.stat("viking://resources/example.md", ctx=_default_ctx())

    assert "isLocked" not in result
    assert lock_queries == []

    result = await fs.stat(
        "viking://resources/example.md",
        ctx=_default_ctx(),
        include_lock_status=True,
    )

    assert result["isLocked"] is True
    assert lock_queries == [path]


def test_viking_fs_no_longer_exposes_python_encryption_api(fs: VikingFS):
    """VikingFS should not expose Python-side encryption helpers after ragfs migration."""
    assert not hasattr(fs, "_encrypt_content")
    assert not hasattr(fs, "_decrypt_content")
    assert not hasattr(fs, "encrypt_bytes")
    assert not hasattr(fs, "decrypt_bytes")


# ── Shared fixtures / builders ──────────────────────────────────────────────


@pytest.fixture
def fs() -> VikingFS:
    """Fresh VikingFS backed by a dummy AGFS client."""
    return VikingFS(agfs=_DummyAgfs())


def _std_path_to_uri(path, **_kwargs):
    """Map account-isolated path back to a viking:// URI (test convention)."""
    return path.replace("/local/test_account/", "viking://")


def make_entry(
    path,
    name=None,
    *,
    size=0,
    mode=0o755,
    mod_time="2026-01-01T00:00:00Z",
    is_dir=True,
    extra=None,
):
    """Build a Rust-shaped TreeEntry dict for tests.

    ``rel_path`` is normalized by ``patch_tree_env`` for tree traversal tests,
    matching the binding contract where it is relative to the query root.
    ``name`` defaults to the last path component when not given.
    """
    if name is None:
        name = path.rstrip("/").rsplit("/", 1)[-1]
    return {
        "path": path,
        "rel_path": path.replace("/local/test_account/", ""),
        "info": {
            "name": name,
            "size": size,
            "mode": mode,
            "modTime": mod_time,
            "isDir": is_dir,
        },
        "extra": extra or {},
    }


def _query_relative_path(path: str, query_root: str) -> str:
    base = query_root.rstrip("/")
    normalized = path.rstrip("/")
    if normalized == base:
        return ""
    if normalized.startswith(f"{base}/"):
        return normalized[len(base) + 1 :]
    return path.replace("/local/test_account/", "")


def _with_query_relative_paths(entries, query_root: str):
    normalized_entries = []
    for entry in entries:
        normalized = dict(entry)
        normalized["rel_path"] = _query_relative_path(str(entry["path"]), query_root)
        normalized_entries.append(normalized)
    return normalized_entries


def patch_visibility(monkeypatch, fs, *, is_accessible=True):
    """Patch ACL + URI mapping used by visibility checks."""
    monkeypatch.setattr(
        fs,
        "_is_accessible",
        is_accessible if callable(is_accessible) else (lambda _uri, _ctx: is_accessible),
    )
    monkeypatch.setattr(fs, "_path_to_uri", _std_path_to_uri)


def patch_tree_env(
    monkeypatch,
    fs,
    entries_or_fn,
    *,
    is_accessible=True,
    uri_to_path="/local/test_account/resources",
):
    """Install the standard monkeypatch set for tree traversal tests.

    ``entries_or_fn`` may be a list of entries (returned by a generated fake
    ``tree_directory``) or a custom async ``tree_directory`` callable when a
    test needs to capture the arguments passed to Rust.
    """
    if callable(entries_or_fn):
        fake_tree = entries_or_fn
    else:

        async def fake_tree(path, **_kwargs):
            return _with_query_relative_paths(entries_or_fn, path)

    monkeypatch.setattr(fs._async_agfs, "tree_directory", fake_tree)
    monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: uri_to_path)
    monkeypatch.setattr(fs, "_ctx_or_default", lambda _ctx=None: _default_ctx())
    patch_visibility(monkeypatch, fs, is_accessible=is_accessible)


# ── _is_name_visible_at_path / _ancestor_is_filtered tests ──


@pytest.mark.parametrize(
    "name,parent_path,expected",
    [
        ("resources", "/local/test_account", True),
        ("user", "/local/test_account", True),
        ("agent", "/local/test_account", True),
        ("system", "/local/test_account", True),
        ("session", "/local/test_account", False),
        ("tasks", "/local/test_account", False),
        ("_system", "/local/test_account", False),
        ("temp", "/local/test_account", False),
    ],
)
def test_is_name_visible_at_account_root(fs, name, parent_path, expected):
    """PY-FLT-001, PY-FLT-002: Account root LISTABLE_SCOPES whitelist."""
    assert fs._is_name_visible_at_path(name, parent_path) == expected


@pytest.mark.parametrize(
    "name,parent_path,expected",
    [
        ("my_dir", "/local/test_account/resources", True),
        ("normal_dir", "/local/test_account/resources/foo", True),
        ("_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: Below the account root only multi-write internal files are hidden."""
    assert fs._is_name_visible_at_path(name, parent_path) == expected


@pytest.mark.parametrize(
    "entry_path,base_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", 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),
    ],
)
def test_ancestor_is_filtered(fs, entry_path, base_path, expected):
    """PY-FLT-003, PY-FLT-006, PY-FLT-007: Ancestor chain filtering."""
    assert fs._ancestor_is_filtered(entry_path, base_path) == expected


# ── _is_tree_entry_visible tests ──


def test_is_tree_entry_visible_visible(monkeypatch, fs):
    """PY-FLT-005, PY-FLT-009: Normal visible entry."""
    patch_visibility(monkeypatch, fs, is_accessible=True)
    entry = make_entry("/local/test_account/resources/a", "a")
    assert (
        fs._is_tree_entry_visible(
            entry,
            "/local/test_account",
            _default_ctx(),
            acl_enabled=False,
        )
        is True
    )


def test_is_tree_entry_visible_acl_filtered(monkeypatch, fs):
    """PY-FLT-008: ACL filtering."""
    patch_visibility(monkeypatch, fs, is_accessible=False)
    entry = make_entry("/local/test_account/resources/secret", "secret")
    assert (
        fs._is_tree_entry_visible(
            entry,
            "/local/test_account",
            _default_ctx(),
            acl_enabled=False,
        )
        is False
    )


def test_is_tree_entry_visible_hidden_scope_filtered(monkeypatch, fs):
    """PY-FLT-007: tasks scope filtered at account root."""
    patch_visibility(monkeypatch, fs, is_accessible=True)
    entry = make_entry("/local/test_account/tasks/foo", "foo")
    assert (
        fs._is_tree_entry_visible(
            entry,
            "/local/test_account",
            _default_ctx(),
            acl_enabled=False,
        )
        is False
    )


def test_is_tree_entry_visible_path_ovlock_filtered(monkeypatch, fs):
    """PY-FLT-011: .path.ovlock is filtered."""
    patch_visibility(monkeypatch, fs, is_accessible=True)
    entry = make_entry("/local/test_account/resources/.path.ovlock", ".path.ovlock", is_dir=False)
    assert (
        fs._is_tree_entry_visible(
            entry,
            "/local/test_account",
            _default_ctx(),
            acl_enabled=False,
        )
        is False
    )


def test_is_tree_entry_visible_multiwrite_meta_filtered(monkeypatch, fs):
    """PY-FLT-012: multi-write metadata files are filtered."""
    patch_visibility(monkeypatch, fs, is_accessible=True)
    for hidden_name in (".sync_log.json", ".redirect.json"):
        entry = make_entry(
            f"/local/test_account/resources/{hidden_name}",
            hidden_name,
            is_dir=False,
        )
        assert (
            fs._is_tree_entry_visible(
                entry,
                "/local/test_account",
                _default_ctx(),
                acl_enabled=False,
            )
            is False
        )


def test_is_tree_entry_visible_default_ctx(monkeypatch, fs):
    """PY-FLT-010: ctx=None uses default context."""
    patch_visibility(monkeypatch, fs, is_accessible=True)
    entry = make_entry("/local/test_account/resources/a", "a")
    assert (
        fs._is_tree_entry_visible(
            entry,
            "/local/test_account",
            _default_ctx(),
            acl_enabled=False,
        )
        is True
    )


# ── _iter_visible_tree_entries tests ──


@pytest.mark.asyncio
async def test_iter_visible_tree_entries_uses_minimum_backend_page_size(monkeypatch, fs):
    """PY-ITER-001: bounded tree reads use the minimum backend page size."""
    captured = {}

    async def fake_tree_directory(_path, **kwargs):
        captured["node_limit"] = kwargs.get("node_limit")
        captured["offset"] = kwargs.get("offset")
        return []

    patch_tree_env(monkeypatch, fs, fake_tree_directory)

    async for _ in fs._iter_visible_tree_entries(
        "viking://resources", node_limit=10, ctx=_default_ctx()
    ):
        pass

    assert captured == {"node_limit": 256, "offset": 0}


@pytest.mark.asyncio
async def test_iter_visible_tree_entries_node_limit_none_not_pushed(monkeypatch, fs):
    """PY-ITER-001b: node_limit=None (full-tree callers) pushes no raw limit."""
    captured = {"set": False, "value": "unset"}

    async def fake_tree_directory(_path, **kwargs):
        captured["set"] = True
        captured["value"] = kwargs.get("node_limit")
        return []

    patch_tree_env(monkeypatch, fs, fake_tree_directory)

    async for _ in fs._iter_visible_tree_entries(
        "viking://resources", node_limit=None, ctx=_default_ctx()
    ):
        pass

    assert captured["set"] is True
    assert captured["value"] is None


@pytest.mark.asyncio
async def test_iter_visible_tree_entries_level_limit_passed_to_rust(monkeypatch, fs):
    """PY-ITER-003: level_limit IS passed to Rust layer."""
    captured = {}

    async def fake_tree_directory(_path, **kwargs):
        captured["level_limit"] = kwargs.get("level_limit")
        return []

    patch_tree_env(monkeypatch, fs, fake_tree_directory)

    async for _ in fs._iter_visible_tree_entries(
        "viking://resources", level_limit=3, ctx=_default_ctx()
    ):
        pass

    assert captured["level_limit"] == 3


@pytest.mark.asyncio
async def test_iter_visible_tree_entries_offset_and_node_limit_after_acl(monkeypatch, fs):
    """PY-ITER-002: offset and node_limit apply after ACL filtering."""
    visible_count = 0

    entries = [
        make_entry(f"/local/test_account/resources/{name}", name, is_dir=False)
        for name in ["a", "b", "c", "d", "e"]
    ]

    def fake_is_accessible(_uri, _ctx):
        nonlocal visible_count
        visible_count += 1
        return True

    patch_tree_env(monkeypatch, fs, entries, is_accessible=fake_is_accessible)

    results = []
    async for entry, _entry_uri in fs._iter_visible_tree_entries(
        "viking://resources", offset=1, node_limit=2, ctx=_default_ctx()
    ):
        results.append(entry)

    assert [entry["info"]["name"] for entry in results] == ["b", "c"]
    assert visible_count == 3, "only skipped and returned entries should be ACL checked"


@pytest.mark.asyncio
async def test_iter_visible_tree_entries_pushes_directory_filter_to_backend(monkeypatch, fs):
    entries = [
        make_entry(
            f"/local/test_account/resources/{name}",
            name,
            is_dir=is_dir,
        )
        for name, is_dir in [
            ("file-a.md", False),
            ("dir-a", True),
            ("file-b.md", False),
            ("dir-b", True),
            ("dir-c", True),
        ]
    ]
    captured = {}

    async def fake_tree_directory(_path, **kwargs):
        captured["directories_only"] = kwargs.get("directories_only")
        directories = [entry for entry in entries if entry["info"]["isDir"]]
        offset = kwargs.get("offset", 0)
        limit = kwargs.get("node_limit")
        return directories[offset : offset + limit]

    patch_tree_env(monkeypatch, fs, fake_tree_directory)

    results = []
    async for entry, _entry_uri in fs._iter_visible_tree_entries(
        "viking://resources",
        directories_only=True,
        offset=1,
        node_limit=2,
        ctx=_default_ctx(),
    ):
        results.append(entry)

    assert [entry["info"]["name"] for entry in results] == ["dir-b", "dir-c"]
    assert captured["directories_only"] is True


@pytest.mark.asyncio
async def test_iter_visible_tree_entries_reads_next_page_when_filtering_is_sparse(monkeypatch, fs):
    """PY-ITER-004: sparse visible results advance the RagFS offset."""
    node_limit = 2
    invisible = [
        make_entry(f"/local/test_account/resources/h{i}/x", "x", is_dir=False) for i in range(256)
    ]
    visible = [
        make_entry(f"/local/test_account/resources/v{i}", f"v{i}", is_dir=False)
        for i in range(node_limit)
    ]
    entries = invisible + visible
    captured_pages = []

    async def fake_tree_directory(_path, **kwargs):
        raw_offset = kwargs.get("offset")
        raw_limit = kwargs.get("node_limit")
        captured_pages.append((raw_offset, raw_limit))
        return entries[raw_offset : raw_offset + raw_limit]

    def fake_is_accessible(uri, _ctx):
        # Entries under an "hN" directory are invisible (ACL denied).
        return "/h" not in uri

    patch_tree_env(monkeypatch, fs, fake_tree_directory, is_accessible=fake_is_accessible)

    results = []
    async for entry, _uri in fs._iter_visible_tree_entries(
        "viking://resources", node_limit=node_limit, ctx=_default_ctx()
    ):
        results.append(entry)

    assert len(results) == node_limit
    assert captured_pages == [(0, 256), (256, 256)]


@pytest.mark.asyncio
async def test_iter_visible_tree_entries_show_hidden_passthrough(monkeypatch, fs):
    """PY-ITER-005: show_all_hidden passthrough."""
    captured = {}

    async def fake_tree_directory(_path, **kwargs):
        captured["show_hidden"] = kwargs.get("show_hidden")
        return []

    patch_tree_env(monkeypatch, fs, fake_tree_directory)

    async for _ in fs._iter_visible_tree_entries(
        "viking://resources", show_all_hidden=True, ctx=_default_ctx()
    ):
        pass

    assert captured["show_hidden"] is True


# ── _tree_original tests ──


@pytest.mark.asyncio
async def test_tree_original_structure(monkeypatch, fs):
    """PY-ORIG-001: Return structure contains expected fields."""
    entries = [
        make_entry(
            "/local/test_account/resources/a",
            "a",
            size=100,
            mode=0o644,
            is_dir=False,
            extra={"meta": {"Name": "s3fs"}},
        )
    ]
    patch_tree_env(monkeypatch, fs, entries)

    result = await fs.tree("viking://resources", output="original", ctx=_default_ctx())

    assert len(result) == 1
    e = result[0]
    assert e["name"] == "a"
    assert e["size"] == 100
    assert e["mode"] == 0o644
    assert e["modTime"] == "2026-01-01T00:00:00Z"
    assert e["isDir"] is False
    assert e["rel_path"] == "a"
    assert e["uri"] == "viking://resources/a"
    assert "abstract" not in e
    assert "overview" not in e


@pytest.mark.asyncio
async def test_tree_original_extra_fields_preserved(monkeypatch, fs):
    """PY-ORIG-002: extra fields preserved."""
    entries = [
        make_entry(
            "/local/test_account/resources/a",
            "a",
            size=100,
            mode=0o644,
            is_dir=False,
            extra={"meta": {"Name": "s3fs", "Type": "s3"}},
        )
    ]
    patch_tree_env(monkeypatch, fs, entries)

    result = await fs._tree_original("viking://resources", ctx=_default_ctx())
    assert result[0]["meta"] == {"Name": "s3fs", "Type": "s3"}


@pytest.mark.asyncio
async def test_extra_fields_do_not_enrich_acl_denied_entries(monkeypatch, fs):
    denied = {
        "name": "restricted",
        "isDir": True,
        "uri": "viking://resources/restricted",
        "access": "denied",
    }

    async def fail_locked(_path):
        raise AssertionError("denied entry must not query lock metadata")

    monkeypatch.setattr(fs, "_is_path_locked_async", fail_locked)
    monkeypatch.setattr(fs, "_get_vector_store", lambda: None)

    await fs._augment_entries_extra_fields(
        [denied],
        ["locked", "id", "count"],
        ctx=_default_ctx(),
    )

    assert denied == {
        "name": "restricted",
        "isDir": True,
        "uri": "viking://resources/restricted",
        "access": "denied",
    }


@pytest.mark.asyncio
async def test_tree_original_dfs_order(monkeypatch, fs):
    """PY-ORIG-006: DFS order preserved — directories before their children."""
    entries = [
        make_entry("/local/test_account/resources/sub", "sub", is_dir=True),
        make_entry(
            "/local/test_account/resources/sub/file.txt",
            "file.txt",
            size=100,
            mode=0o644,
            is_dir=False,
        ),
        make_entry("/local/test_account/resources/restricted", "restricted", is_dir=True),
        make_entry(
            "/local/test_account/resources/restricted/hidden.txt",
            "hidden.txt",
            is_dir=False,
        ),
    ]
    patch_tree_env(monkeypatch, fs, entries)

    async def acl_enabled(_account_id):
        return True

    fs.acl_manager = SimpleNamespace(is_enabled=acl_enabled)

    async def fake_can_access_many(uris, _ctx):
        return {uri: "/restricted" not in uri for uri in uris}

    monkeypatch.setattr(fs, "_can_access_many", fake_can_access_many)

    result = await fs._tree_original("viking://resources", ctx=_default_ctx())
    assert result[0]["name"] == "sub"
    assert result[0]["isDir"] is True
    assert result[0]["rel_path"] == "sub"
    assert result[1]["name"] == "file.txt"
    assert result[1]["rel_path"] == "sub/file.txt"
    assert result[2] == {
        "name": "restricted",
        "isDir": True,
        "rel_path": "restricted",
        "uri": "viking://resources/restricted",
        "access": "denied",
    }
    assert len(result) == 3


# ── tree agent output tests ──


@pytest.mark.asyncio
async def test_tree_agent_structure(monkeypatch, fs):
    """Agent defaults and explicit summary controls preserve the listing contract."""
    entries = [
        make_entry("/local/test_account/resources/a", "a", size=100, is_dir=False),
        make_entry("/local/test_account/resources/sub", "sub", size=999, is_dir=True),
    ]
    patch_tree_env(monkeypatch, fs, entries)
    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())

    assert result == [
        {
            "uri": "viking://resources/a",
            "size": 100,
            "isDir": False,
            "modTime": "2026-01-01T00:00:00.000Z",
            "rel_path": "a",
            "abstract": "",
        },
        {
            "uri": "viking://resources/sub",
            "size": 0,
            "isDir": True,
            "modTime": "2026-01-01T00:00:00.000Z",
            "rel_path": "sub",
            "abstract": "L0 summary",
        },
    ]
    summary.assert_awaited_once_with("viking://resources/sub", "abstract", ctx=_default_ctx())
    summary.reset_mock()

    result = await fs.tree(
        "viking://resources",
        output="agent",
        include_abstract=False,
        include_overview=True,
        ctx=_default_ctx(),
    )

    assert all("abstract" not in entry for entry in result)
    assert [entry["overview"] for entry in result] == ["", "L1 overview"]
    summary.assert_awaited_once_with("viking://resources/sub", "overview", ctx=_default_ctx())


@pytest.mark.asyncio
async def test_tree_agent_normalizes_modtime_to_utc(monkeypatch, fs):
    entries = [
        make_entry(
            "/local/test_account/resources/a",
            "a",
            size=100,
            mode=0o644,
            mod_time="2026-06-11T00:30:17+08:00",
            is_dir=False,
        )
    ]
    patch_tree_env(monkeypatch, fs, entries)
    monkeypatch.setattr(viking_fs_module, "datetime", _FixedDatetime)

    result = await fs.tree(
        "viking://resources",
        output="agent",
        abs_limit=256,
        ctx=_default_ctx(),
    )

    assert set(result[0].keys()) == {"uri", "size", "isDir", "modTime", "rel_path", "abstract"}
    assert result[0]["modTime"] == "2026-06-10T16:30:17.000Z"


@pytest.mark.asyncio
async def test_ls_agent_preserves_metadata_acl_and_summary_controls(monkeypatch, fs):
    async def fake_ls_entries(_path, **_kwargs):
        return [
            {
                "name": "a.md",
                "size": 100,
                "mode": 0o644,
                "modTime": "2026-06-11T00:30:17+08:00",
                "isDir": False,
            },
            {
                "name": "restricted",
                "size": 4096,
                "mode": 0o755,
                "modTime": "2026-06-11T00:30:18+08:00",
                "isDir": True,
            },
            {"name": "docs", "size": 4096, "mode": 0o755, "modTime": "", "isDir": True},
        ]

    monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account/resources")
    monkeypatch.setattr(fs, "_ls_entries", fake_ls_entries)
    monkeypatch.setattr(fs, "_path_to_uri", _std_path_to_uri)
    monkeypatch.setattr(fs, "_is_accessible", lambda _uri, _ctx: True)
    monkeypatch.setattr(viking_fs_module, "datetime", _FixedDatetime)

    async def acl_enabled(_account_id):
        return True

    fs.acl_manager = SimpleNamespace(is_enabled=acl_enabled)

    async def fake_can_access_many(uris, _ctx, **_kwargs):
        return {uri: not uri.endswith("/restricted") for uri in uris}

    monkeypatch.setattr(fs, "_can_access_many", fake_can_access_many)
    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",
        output="agent",
        abs_limit=256,
        show_all_hidden=False,
        ctx=_default_ctx(),
    )

    assert set(result[0].keys()) == {"uri", "size", "isDir", "modTime", "abstract"}
    assert result[0]["modTime"] == "2026-06-10T16:30:17.000Z"
    assert result[1] == {
        "name": "restricted",
        "uri": "viking://resources/restricted",
        "isDir": True,
        "access": "denied",
    }
    assert result[2]["abstract"] == "L0 summary"
    summary.assert_awaited_once_with("viking://resources/docs", "abstract", ctx=_default_ctx())
    summary.reset_mock()

    result = await fs.ls(
        "viking://resources",
        output="agent",
        include_abstract=False,
        include_overview=True,
        ctx=_default_ctx(),
    )
    assert all("abstract" not in entry for entry in result)
    assert result[0]["overview"] == ""
    assert "overview" not in result[1]
    assert result[2]["overview"] == "L1 overview"
    summary.assert_awaited_once_with("viking://resources/docs", "overview", ctx=_default_ctx())

@pytest.mark.asyncio
async def test_tree_filters_and_paginates_before_summary_reads(monkeypatch, fs):
    """Only selected directories consume node slots and summary reads."""
    entries = [
        make_entry(f"/local/test_account/resources/{name}", is_dir=is_dir)
        for name, is_dir in [
            ("file-a.md", False),
            ("dir-a", True),
            ("dir-a/.abstract.md", False),
            ("dir-a/.overview.md", False),
            ("file-b.md", False),
            ("dir-b", True),
            ("dir-c", True),
            ("dir-d", True),
        ]
    ]

    async def fake_tree_directory(path, **kwargs):
        filtered = entries
        if kwargs.get("directories_only"):
            filtered = [entry for entry in entries if entry["info"]["isDir"]]
        offset = kwargs.get("offset", 0)
        limit = kwargs.get("node_limit")
        page = filtered[offset : offset + limit if limit is not None else None]
        return _with_query_relative_paths(page, path)

    patch_tree_env(monkeypatch, fs, fake_tree_directory)
    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="original",
        directories_only=True,
        show_all_hidden=True,
        offset=1,
        node_limit=2,
        include_abstract=True,
        include_overview=True,
        abs_limit=5,
        overview_limit=7,
        ctx=_default_ctx(),
    )

    assert [entry["uri"] for entry in result] == [
        "viking://resources/dir-b",
        "viking://resources/dir-c",
    ]
    assert all(entry["isDir"] for entry in result)
    assert [(entry["abstract"], entry["overview"]) for entry in result] == [
        ("L0...", "L1 o..."),
        ("L0...", "L1 o..."),
    ]
    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",
        ]