diff --git a/dokimi/changelog.d/20261128_100000_doc-source-unlistable-dir.md b/dokimi/changelog.d/20261128_100000_doc-source-unlistable-dir.md new file mode 100644 index 000000000..7f59f47cc --- /dev/null +++ b/dokimi/changelog.d/20261128_100000_doc-source-unlistable-dir.md @@ -0,0 +1,3 @@ +### Fixed + +- **`local:` and `okf:` doc sources refuse a directory they cannot list instead of reading a smaller tree** — both clients listed the tree with `rglob("*")`, which skips a directory it cannot list without an error, so a source holding `a.md` and `sub/b.md` with `sub` at mode `0o111` gave `a.md` alone and `check_connection()` said `True` (a root at `0o111` gave no docs and a "no doc files found" warning). `get_library_docs` now raises `MCPConnectionError` naming the directory, as it does for a missing path, `check_connection()` returns `False` with a warning that names it, and `require_local_doc_source` (`eval questions generate`, `benchmark preflight`) exits 2 rather than falling back to default seed topics, with `cannot list ` for a directory below the root, and with the existing `cannot read : permission denied` for a root the user cannot read or search. A tree that can be listed gives the same files, a directory with no doc files still gives a warning and no docs, and a file that cannot be read is still skipped. `docs/adding-doc-source.md` says what each case does. diff --git a/dokimi/docs/adding-doc-source.md b/dokimi/docs/adding-doc-source.md index 373ef335f..804ffe317 100644 --- a/dokimi/docs/adding-doc-source.md +++ b/dokimi/docs/adding-doc-source.md @@ -22,6 +22,13 @@ With `--doc-source` you can point it at a local directory or any URL instead. | `okf:` | Google OKF (Open Knowledge Format) bundle — a directory of Markdown files with YAML frontmatter | | `mcp:` | Retrieve through a real MCP server (requires `pip install mcp`) | +### What `local:` and `okf:` do with a path they cannot read + +- A missing path is refused: `eval questions generate` and `benchmark preflight` exit 2, and retrieval raises `MCPConnectionError`. +- A directory that cannot be listed, the root or one below it, gets the same refusal and the message names that directory. A tree is never read as a smaller one: on a source holding `a.md` and `sub/b.md` with `sub` unlistable, `eval questions generate` exits 2 rather than using `a.md` alone. +- A directory with no doc files logs a warning and gives no docs. +- A file that cannot be read is skipped; the other files are still used. + ### Naming the library for `context7` and `mcp:` A Context7 library ID is not derivable from a product name, so nothing guesses diff --git a/dokimi/dokimi/mcp/factory.py b/dokimi/dokimi/mcp/factory.py index c2f9f38f4..4714bfb99 100644 --- a/dokimi/dokimi/mcp/factory.py +++ b/dokimi/dokimi/mcp/factory.py @@ -13,8 +13,22 @@ from . import MCPClient +def _require_listable(doc_source: str, path: Path) -> None: + """#1207: a directory of the tree that cannot be listed is an input error, not a smaller doc set.""" + from dokimi.digest_entries import listed_entries + + try: + listed_entries(path) + except OSError as exc: + raise InputError(f"doc source {doc_source}: cannot list {exc.filename or path}: {exc.strerror or exc}") from exc + + def require_local_doc_source(doc_source: str) -> None: - """#1086: a `local:` or `okf:` source whose path is missing is an input error, not default seed topics.""" + """#1086: a `local:` or `okf:` source whose path is missing is an input error, not default seed topics. + + #1207: so is a directory of its tree that cannot be listed (the root included once it passes the checks above), + which the message names. A directory with no doc files, or a file that cannot be read, is not refused here. + """ prefix = next((p for p in ("local:", "okf:") if doc_source.startswith(p)), None) if prefix is None: return @@ -33,6 +47,8 @@ def require_local_doc_source(doc_source: str) -> None: unreadable = os.access(path, os.F_OK) and not os.access(path, mode) except ValueError: # a name the OS cannot encode (lone surrogate): exists() already accepted it unreadable = False + if not unreadable and path.is_dir(): + _require_listable(doc_source, path) if unreadable: raise InputError(f"doc source {doc_source}: cannot read {local_path}: permission denied") diff --git a/dokimi/dokimi/mcp/local_markdown.py b/dokimi/dokimi/mcp/local_markdown.py index 3a57882c0..ebb122b91 100644 --- a/dokimi/dokimi/mcp/local_markdown.py +++ b/dokimi/dokimi/mcp/local_markdown.py @@ -8,7 +8,7 @@ from typing import List, Dict, Any from . import MCPClient, MCPConnectionError -from .utils import strip_html, score_chunk +from .utils import list_doc_tree, strip_html, score_chunk logger = logging.getLogger(__name__) @@ -73,6 +73,11 @@ def get_library_docs( Returns: List of dicts with keys: content, source, file, library_id, query. + + Raises: + MCPConnectionError: the path does not exist, or a directory under it (the root + included) cannot be listed; the message names that directory. A file that + cannot be read is skipped, and a directory with no doc files gives ``[]``. """ if not self.path.exists(): raise MCPConnectionError(f"LocalMarkdownClient: path does not exist: {self.path}") @@ -119,10 +124,17 @@ def get_library_docs( return results def check_connection(self) -> bool: - """Return True if the path exists and contains at least one doc file.""" + """Return True if the path exists, can be listed and contains at least one doc file. + + A directory that cannot be listed gives False and a warning that names it; this never raises for it. + """ if not self.path.exists(): return False - return len(self._collect_files()) > 0 + try: + return len(self._collect_files()) > 0 + except MCPConnectionError as exc: + logger.warning("%s", exc) + return False # ── Helpers ─────────────────────────────────────────────────────────── @@ -132,7 +144,7 @@ def _collect_files(self) -> List[Path]: return [self.path] if self.path.suffix.lower() in _DOC_EXTENSIONS else [] files = [] - for fp in self.path.rglob("*"): + for fp in list_doc_tree("LocalMarkdownClient", self.path): if fp.is_file() and fp.suffix.lower() in _DOC_EXTENSIONS: if fp.stat().st_size <= self.max_file_size_bytes: files.append(fp) diff --git a/dokimi/dokimi/mcp/okf_client.py b/dokimi/dokimi/mcp/okf_client.py index 8cce37fb8..1fb8a9407 100644 --- a/dokimi/dokimi/mcp/okf_client.py +++ b/dokimi/dokimi/mcp/okf_client.py @@ -24,7 +24,7 @@ import yaml from . import MCPClient, MCPConnectionError -from .utils import score_chunk +from .utils import list_doc_tree, score_chunk logger = logging.getLogger(__name__) @@ -128,6 +128,11 @@ def get_library_docs( Returns: List of dicts with keys: content, source, file, library_id, query, relevance_score, metadata (the parsed OKF frontmatter). + + Raises: + MCPConnectionError: the path does not exist, or a directory under it (the root + included) cannot be listed; the message names that directory. A file that + cannot be read is skipped, and a directory with no documents gives ``[]``. """ if not self.path.exists(): raise MCPConnectionError(f"OKFClient: path does not exist: {self.path}") @@ -193,10 +198,17 @@ def get_library_docs( return results def check_connection(self) -> bool: - """Return True if the path exists and holds at least one OKF document.""" + """Return True if the path exists, can be listed and holds at least one OKF document. + + A directory that cannot be listed gives False and a warning that names it; this never raises for it. + """ if not self.path.exists(): return False - return any(True for _ in self._iter_candidate_files()) + try: + return any(True for _ in self._iter_candidate_files()) + except MCPConnectionError as exc: + logger.warning("%s", exc) + return False # ── internals ────────────────────────────────────────────────────────── @@ -206,7 +218,7 @@ def _iter_candidate_files(self): if self.path.suffix.lower() in _OKF_EXTENSIONS: yield self.path return - for fp in self.path.rglob("*"): + for fp in list_doc_tree("OKFClient", self.path): if fp.is_file() and fp.suffix.lower() in _OKF_EXTENSIONS: yield fp diff --git a/dokimi/dokimi/mcp/utils.py b/dokimi/dokimi/mcp/utils.py index 52d5b351c..e890469ab 100644 --- a/dokimi/dokimi/mcp/utils.py +++ b/dokimi/dokimi/mcp/utils.py @@ -10,10 +10,22 @@ from typing import List, Optional from dokimi.atomic_write import write_text_atomic +from dokimi.digest_entries import listed_entries + +from . import MCPConnectionError logger = logging.getLogger(__name__) +def list_doc_tree(client: str, root: Path) -> List[Path]: + """Every entry under the directory ``root`` (``rglob("*")``'s, in no set order). A directory that cannot be + listed raises :class:`MCPConnectionError` naming it, so a doc source is never a smaller tree than the user's.""" + try: + return listed_entries(root) + except OSError as exc: + raise MCPConnectionError(f"{client}: cannot list {exc.filename or root}: {exc}") from exc + + class _TextExtractor(HTMLParser): """Collect the text of a page, dropping script/style bodies; every tag becomes a space.""" diff --git a/dokimi/tests/test_doc_source_unlistable.py b/dokimi/tests/test_doc_source_unlistable.py new file mode 100644 index 000000000..0d3763797 --- /dev/null +++ b/dokimi/tests/test_doc_source_unlistable.py @@ -0,0 +1,183 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1207: ``local:`` and ``okf:`` refuse a doc tree with a directory they cannot list, not a smaller doc set.""" + +from __future__ import annotations + +import argparse +import errno +import json +import logging +import os +import re +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from dokimi.mcp import MCPConnectionError +from dokimi.mcp.factory import require_local_doc_source +from dokimi.mcp.local_markdown import LocalMarkdownClient +from dokimi.mcp.okf_client import OKFClient +from dokimi.utils import InputError + +CLIENTS = [(LocalMarkdownClient, "local"), (OKFClient, "okf")] + +needs_modes = pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") + + +def _tree(tmp_path: Path) -> Path: + root = tmp_path / "docs" + (root / "sub").mkdir(parents=True) + (root / "a.md").write_text("alpha parallel_for\n", encoding="utf-8") + (root / "sub" / "b.md").write_text("beta parallel_for\n", encoding="utf-8") + return root + + +def _files(client) -> list[str]: + return [d["file"] for d in client.get_library_docs("x", "parallel_for")] + + +def _lock(directory: Path) -> None: + directory.chmod(0o111) + if os.access(directory, os.R_OK): + directory.chmod(0o700) + pytest.skip("this file system or user lists a mode 111 directory") + + +@pytest.mark.parametrize("cls,_prefix", CLIENTS) +def test_a_listable_nested_tree_gives_the_same_files(tmp_path: Path, cls, _prefix): + root = _tree(tmp_path) + (root / "sub" / "deep").mkdir() + (root / "sub" / "deep" / "c.md").write_text("gamma\n", encoding="utf-8") + (root / "sub" / "skip.bin").write_text("x\n", encoding="utf-8") + assert sorted(_files(cls(root))) == ["a.md", "sub/b.md", "sub/deep/c.md"] + + +@needs_modes +@pytest.mark.parametrize("cls,_prefix", CLIENTS) +def test_a_subdirectory_that_cannot_be_listed_is_refused(tmp_path: Path, caplog, cls, _prefix): + root = _tree(tmp_path) + client = cls(root) + _lock(root / "sub") + try: + with pytest.raises(MCPConnectionError, match=rf"cannot list {re.escape(str(root / 'sub'))}: "): + client.get_library_docs("x", "parallel_for") + with caplog.at_level(logging.WARNING): + assert client.check_connection() is False + assert any("sub" in r.getMessage() and r.levelno == logging.WARNING for r in caplog.records) + finally: + (root / "sub").chmod(0o700) + assert sorted(_files(client)) == ["a.md", "sub/b.md"] + assert client.check_connection() is True + + +@needs_modes +@pytest.mark.parametrize("cls,_prefix", CLIENTS) +def test_a_root_that_cannot_be_listed_is_refused(tmp_path: Path, cls, _prefix): + root = _tree(tmp_path) + _lock(root) + try: + with pytest.raises(MCPConnectionError, match="cannot list"): + cls(root).get_library_docs("x", "parallel_for") + finally: + root.chmod(0o700) + + +@needs_modes +@pytest.mark.parametrize("cls,_prefix", CLIENTS) +def test_a_file_that_cannot_be_read_is_still_skipped(tmp_path: Path, cls, _prefix): + root = _tree(tmp_path) + (root / "sub" / "b.md").chmod(0) + if os.access(root / "sub" / "b.md", os.R_OK): + pytest.skip("this user reads a mode 000 file") + try: + assert _files(cls(root)) == ["a.md"] + finally: + (root / "sub" / "b.md").chmod(0o600) + + +@needs_modes +@pytest.mark.parametrize("cls,prefix", CLIENTS) +def test_the_preflight_refuses_a_subdirectory_that_cannot_be_listed(tmp_path: Path, cls, prefix): + root = _tree(tmp_path) + require_local_doc_source(f"{prefix}:{root}") + _lock(root / "sub") + try: + with pytest.raises(InputError, match=rf"cannot list {re.escape(str(root / 'sub'))}: Permission denied$"): + require_local_doc_source(f"{prefix}:{root}") + finally: + (root / "sub").chmod(0o700) + + +@needs_modes +@pytest.mark.parametrize("cls,prefix", CLIENTS) +def test_the_preflight_keeps_permission_denied_for_a_root_that_cannot_be_listed(tmp_path: Path, cls, prefix): + """#1207 and docs/adding-doc-source.md: an unreadable root keeps the #1086 message, not ``cannot list``.""" + root = _tree(tmp_path) + _lock(root) + try: + with pytest.raises(InputError, match=rf"cannot read {re.escape(str(root))}: permission denied") as caught: + require_local_doc_source(f"{prefix}:{root}") + finally: + root.chmod(0o700) + assert "cannot list" not in str(caught.value) + + +LISTING_ERRORS = [ + (OSError(errno.EIO, "Input/output error"), "Input/output error"), + (OSError("boom"), "boom"), +] + + +def _failing(err: OSError): + def listing(_root): + raise err + + return listing + + +@pytest.mark.parametrize("err,_strerror", LISTING_ERRORS) +@pytest.mark.parametrize("cls,_prefix", CLIENTS) +def test_a_listing_error_without_a_filename_names_the_root(tmp_path: Path, monkeypatch, cls, _prefix, err, _strerror): + """#1207: an ``OSError`` that carries no filename is reported against the source directory.""" + root = _tree(tmp_path) + monkeypatch.setattr("dokimi.mcp.utils.listed_entries", _failing(err)) + with pytest.raises(MCPConnectionError) as caught: + cls(root).get_library_docs("x", "parallel_for") + assert str(caught.value) == f"{cls.__name__}: cannot list {root}: {err}" + + +@pytest.mark.parametrize("err,strerror", LISTING_ERRORS) +@pytest.mark.parametrize("cls,prefix", CLIENTS) +def test_the_preflight_names_the_root_for_a_listing_error_without_a_filename(tmp_path: Path, monkeypatch, cls, prefix, err, strerror): + """#1207 and docs/adding-doc-source.md: the preflight message ends with the strerror, or the error when it has none.""" + root = _tree(tmp_path) + monkeypatch.setattr("dokimi.digest_entries.listed_entries", _failing(err)) + with pytest.raises(InputError) as caught: + require_local_doc_source(f"{prefix}:{root}") + assert str(caught.value) == f"doc source {prefix}:{root}: cannot list {root}: {strerror}" + + +@needs_modes +def test_questions_generate_stops_before_any_seed_extraction(tmp_path: Path, monkeypatch): + from dokimi.commands import questions as cmd + from dokimi import questions as questions_pkg + + root = _tree(tmp_path) + reached = MagicMock(side_effect=AssertionError("reached the extractor or generator")) + monkeypatch.setattr(questions_pkg, "QuestionGenerator", reached) + monkeypatch.setattr(questions_pkg, "RagasSeedExtractor", reached) + personas = tmp_path / "personas.json" + personas.write_text(json.dumps({"personas": [{"id": "dev", "name": "dev", "skill_level": "expert"}]}), encoding="utf-8") + args = argparse.Namespace( + product="oneTBB", personas=str(personas), topics=None, doc_source=f"local:{root}", context7_id=None, + top_k=3, provider="openai", model="m", count=1, validate=False, output=None) + _lock(root / "sub") + try: + with pytest.raises(InputError, match="cannot list .*sub"): + cmd.cmd_questions_generate(args) + finally: + (root / "sub").chmod(0o700) + reached.assert_not_called()