Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(knowledge): answer "how many files" from an inventory, not retrieval

Bingxi Zhao (Frank)a43f9fdf2aef
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py
index 6b1b2adc7..94e891f30 100644
--- a/deeptutor/agents/_shared/tool_composition.py
+++ b/deeptutor/agents/_shared/tool_composition.py
@@ -45,6 +45,7 @@ AUTO_MOUNTED_TOOLS: frozenset[str] = frozenset(CONFIGURABLE_BUILTIN_TOOL_NAMES)
# Insertion order fixes the default surface's conditional-tool order.
_CONDITIONAL_MOUNT_FLAGS: dict[str, str] = {
"rag": "has_kb",
+ "kb_files": "has_kb",
"read_source": "has_sources",
"read_memory": "has_memory",
"list_notebook": "has_notebooks",
@@ -55,6 +56,10 @@ _CONDITIONAL_MOUNT_FLAGS: dict[str, str] = {
"code_execution": "has_code",
}
+# Built-ins that survive an exclusive knowledge capability when other KBs are
+# co-selected: retrieval over them, and enumeration of what they hold.
+_KB_COEXISTING_TOOLS: tuple[str, ...] = ("rag", "kb_files")
+
def default_optional_tools(excluded: Iterable[str] = ()) -> list[str]:
"""Return the user-toggleable tool list (chat's default set).
@@ -154,14 +159,18 @@ def compose_enabled_tools(
"""
if exclusive:
owned = [str(name) for name in capability_owned if str(name).strip()]
- # ``rag`` is the one built-in that coexists with an exclusive knowledge
- # capability: it serves co-selected KBs the capability's own tools don't
+ # The KB built-ins are the ones that coexist with an exclusive knowledge
+ # capability: they serve co-selected KBs the capability's own tools don't
# touch (e.g. LlamaIndex KBs alongside an Obsidian vault). The caller
# sets ``has_kb`` only for those coexisting KBs, so a pure-capability
# turn still mounts nothing but ``owned`` + the ``ask_user`` floor (#650).
extra = (
- ["rag"]
- if mount_flags.has_kb and (builtin_whitelist is None or "rag" in builtin_whitelist)
+ [
+ name
+ for name in _KB_COEXISTING_TOOLS
+ if builtin_whitelist is None or name in builtin_whitelist
+ ]
+ if mount_flags.has_kb
else []
)
return _finalize([*owned, *extra, "ask_user"], forced, suppressed)
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index e3a2b046d..a784bbca7 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -38,6 +38,7 @@ from deeptutor.core.trace import (
merge_trace_metadata,
new_call_id,
)
+from deeptutor.knowledge.manifest import KbManifest, render_manifest_note
from deeptutor.runtime.registry.deferred_tools import (
DeferredToolLoader,
render_deferred_tools_manifest,
@@ -203,6 +204,7 @@ class AgenticChatPipeline:
self._deferred_loader: DeferredToolLoader | None = None
self._deferred_pool: list[Any] = []
self._exec_enabled = False
+ self._kb_manifests: list[KbManifest] = []
try:
chat_cfg = get_chat_params()
@@ -300,6 +302,7 @@ class AgenticChatPipeline:
async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
await self._prepare_deferred_tools(context)
+ await self._prepare_kb_manifests(context)
self._exec_enabled = await self._exec_allowed(context)
enabled_tools = self._compose_enabled_tools(context)
use_native_tools = bool(enabled_tools) and self._can_use_native_tool_calling()
@@ -904,6 +907,11 @@ class AgenticChatPipeline:
exec_dir = task_dir / "exec" if task_dir is not None else None
if tool_name == "rag":
kwargs.setdefault("mode", "hybrid")
+ elif tool_name == "kb_files":
+ # The report is read by the user as much as by the model, so it is
+ # written in the turn's language. Injected server-side; the tool
+ # exposes no ``language`` parameter for the model to get wrong.
+ kwargs["language"] = context.language or "en"
elif tool_name == "load_tools":
kwargs["_tool_loader"] = self._deferred_loader
elif tool_name == "exec":
@@ -1326,7 +1334,52 @@ class AgenticChatPipeline:
"must be one of these names."
)
)
- return rag_note + self._pageindex_system_note()
+ return rag_note + self._kb_manifest_system_note() + self._pageindex_system_note()
+
+ async def _prepare_kb_manifests(self, context: UnifiedContext) -> None:
+ """Read the attached KBs' document inventories once per turn.
+
+ Retrieval cannot answer "how many files are in here" — the passages it
+ returns say nothing about the size of the collection they came from. The
+ inventory is a filesystem fact, so it is read here (off the event loop,
+ one directory walk per KB) and rendered into the system prompt, which
+ keeps the prompt byte-stable for the whole turn and makes counts
+ answerable without a tool round-trip.
+
+ PageIndex KBs are excluded: ``_pageindex_system_note`` already lists
+ their documents, with the doc_ids its MCP tools need. Fails soft — a KB
+ whose files cannot be read costs the manifest, not the turn.
+ """
+ self._kb_manifests = []
+ kbs = self._rag_kbs(context)
+ if not kbs:
+ return
+ try:
+ self._kb_manifests = await asyncio.to_thread(self._collect_kb_manifests, kbs)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning("Failed to build knowledge base manifests: %s", exc)
+
+ @staticmethod
+ def _collect_kb_manifests(kbs: list[str]) -> list[KbManifest]:
+ from deeptutor.multi_user.knowledge_access import resolve_kb_manifest
+
+ manifests: list[KbManifest] = []
+ for kb in kbs:
+ try:
+ manifest = resolve_kb_manifest(kb)
+ except Exception as exc:
+ logger.warning("Failed to read documents of knowledge base '%s': %s", kb, exc)
+ continue
+ if manifest is not None:
+ manifests.append(manifest)
+ return manifests
+
+ def _kb_manifest_system_note(self) -> str:
+ """What the attached KBs contain, from :meth:`_prepare_kb_manifests`."""
+ if not self._kb_manifests:
+ return ""
+ note = render_manifest_note(self._kb_manifests, language=self.language)
+ return f"\n{note}" if note else ""
def _pageindex_system_note(self) -> str:
"""Doc list + retrieval instructions for attached PageIndex KBs.
diff --git a/deeptutor/i18n/metadata_i18n.py b/deeptutor/i18n/metadata_i18n.py
index 49d4409c7..15d743ce6 100644
--- a/deeptutor/i18n/metadata_i18n.py
+++ b/deeptutor/i18n/metadata_i18n.py
@@ -46,6 +46,10 @@ _TOOL_DESCRIPTIONS: dict[str, dict[str, str]] = {
"en": "Run shell commands inside an isolated sandbox workspace.",
"zh": "在隔离沙箱工作区中运行 shell 命令。",
},
+ "kb_files": {
+ "en": "List the documents a knowledge base holds, with the total count.",
+ "zh": "列出知识库中的文档清单与总数。",
+ },
"paper_search": {
"en": "Search arXiv preprints and return paper metadata.",
"zh": "搜索 arXiv 预印本并返回论文元数据。",
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index d212e1db0..e42da8860 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -25,6 +25,7 @@ from deeptutor.knowledge.kb_types import (
external_root_of,
is_connected_kb,
)
+from deeptutor.knowledge.manifest import iter_kb_documents
from deeptutor.services.file_io import atomic_write_json
from deeptutor.services.rag.factory import (
DEFAULT_PROVIDER,
@@ -485,6 +486,18 @@ class KnowledgeBaseManager:
self._save_config()
self._sync_kb_to_pb(name, kb_config)
+ def get_kb_entry(self, name: str) -> dict | None:
+ """The KB's raw ``kb_config.json`` record, or ``None`` if unregistered.
+
+ A cheap read for callers that need the registered facts (provider,
+ status, connected-KB pointers) without paying for :meth:`get_info`,
+ which additionally probes every index version on disk — and parses a
+ provider's docstore to do it.
+ """
+ self.config = self._load_config()
+ entry = self.config.get("knowledge_bases", {}).get(name)
+ return dict(entry) if isinstance(entry, dict) else None
+
def get_kb_status(self, name: str) -> dict | None:
"""Get status and progress for a knowledge base."""
self.config = self._load_config()
@@ -1168,11 +1181,10 @@ class KnowledgeBaseManager:
if dir_exists:
try:
- raw_count = (
- len([f for f in raw_dir.rglob("*") if f.is_file()])
- if raw_dir and raw_dir.is_dir()
- else 0
- )
+ # One definition of "a document in a KB", shared with the chat
+ # manifest / ``kb_files`` so a user is never told two different
+ # counts for the same KB (see :mod:`deeptutor.knowledge.manifest`).
+ raw_count = sum(1 for _ in iter_kb_documents(raw_dir)) if raw_dir else 0
except Exception:
pass
diff --git a/deeptutor/knowledge/manifest.py b/deeptutor/knowledge/manifest.py
new file mode 100644
index 000000000..aa648e3db
--- /dev/null
+++ b/deeptutor/knowledge/manifest.py
@@ -0,0 +1,427 @@
+"""Document inventory of a knowledge base — the facts retrieval cannot answer.
+
+Retrieval answers "what does the material say". It cannot answer "how many
+files are in this knowledge base", "did I upload X", or "list what's in here":
+those are questions about the KB's *inventory*, and no amount of passage
+similarity produces them. Asked one anyway, a model with only ``rag`` in hand
+either guesses from the passages it happened to retrieve or declines.
+
+This module owns the inventory as plain facts read off disk, so the two
+consumers can never disagree:
+
+* the chat system prompt embeds a manifest (:func:`render_manifest_note`), so
+ counts are answerable with no tool round-trip — the failure mode where a
+ weaker model simply never calls the tool;
+* the ``kb_files`` tool enumerates on demand (:func:`render_manifest_report`)
+ for the full list, which a system-prompt manifest deliberately truncates.
+
+Deliberately NOT reported: how many documents made it into the *index*. Every
+per-file index record available is unreliable — LlamaIndex's ``docstore.json``
+counts nodes (chunk-level, so it drifts with the chunking config and costs a
+multi-MB JSON parse to read), ``metadata.json``'s ``file_hashes`` is only
+written on the incremental-add path (KBs built by the create path have none),
+and ``last_indexed_count`` is the size of the last batch rather than a total. A
+confidently wrong count is worse than no count, so a manifest carries the
+document set plus the KB's index *status* and stops there.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator, Mapping, Sequence
+from dataclasses import dataclass
+import fnmatch
+import os
+from pathlib import Path
+from typing import Any
+
+from deeptutor.knowledge.kb_types import (
+ LIGHTRAG_SERVER_KB_TYPE,
+ SUBAGENT_KB_TYPE,
+ external_root_of,
+)
+
+# Documents listed per KB in the system-prompt manifest. Bounded because the
+# manifest rides in every turn's prompt prefix; ``kb_files`` serves the tail.
+MANIFEST_NOTE_LIMIT = 20
+
+# ``kb_files`` defaults: generous enough to enumerate an ordinary KB in one
+# call, capped so a pathological KB cannot flood the context window.
+KB_FILES_DEFAULT_LIMIT = 200
+KB_FILES_MAX_LIMIT = 1000
+
+# Why a KB's documents cannot be listed. Reason *codes* — the data layer never
+# produces user-facing copy; the renderers localise these.
+UNAVAILABLE_REMOTE = "remote"
+UNAVAILABLE_AGENT = "agent"
+UNAVAILABLE_MISSING = "missing"
+
+# KB types that hold no local document set at all: their content lives behind
+# an API. Reporting them as "0 documents" would be a lie, so they are reported
+# as non-enumerable instead.
+_NON_DOCUMENT_KB_TYPES: dict[str, str] = {
+ LIGHTRAG_SERVER_KB_TYPE: UNAVAILABLE_REMOTE,
+ SUBAGENT_KB_TYPE: UNAVAILABLE_AGENT,
+}
+
+
+@dataclass(frozen=True)
+class KbDocument:
+ """One document in a knowledge base."""
+
+ name: str
+ """POSIX path relative to the KB's document root (folders included)."""
+
+ size: int
+ """Size in bytes, or ``0`` when the file could not be stat'ed."""
+
+
+@dataclass(frozen=True)
+class KbManifest:
+ """What one knowledge base actually contains, as facts rather than passages."""
+
+ name: str
+ provider: str = ""
+ status: str = ""
+ kb_type: str = ""
+ total: int = 0
+ """Documents in the KB — always the full count, ignoring ``pattern``."""
+
+ matched: int = 0
+ """Documents matching ``pattern`` (equal to ``total`` when unfiltered)."""
+
+ documents: tuple[KbDocument, ...] = ()
+ """The matching documents, truncated to the caller's limit."""
+
+ pattern: str = ""
+ unavailable: str = ""
+ """Reason code from this module's ``UNAVAILABLE_*`` set; ``""`` when listable."""
+
+ @property
+ def enumerable(self) -> bool:
+ return not self.unavailable
+
+ @property
+ def omitted(self) -> int:
+ """Matching documents beyond the truncation limit."""
+ return max(0, self.matched - len(self.documents))
+
+
+def iter_kb_documents(root: Path) -> Iterator[Path]:
+ """Yield the documents under ``root``, recursing into folders.
+
+ Order is a depth-first walk with every level sorted — a folder's own files
+ before its subfolders — so a truncated listing always shows the top of the
+ tree and repeated calls agree.
+
+ A *document* is a non-hidden regular file. Hidden entries (``.DS_Store``,
+ ``.obsidian/``) are OS/editor bookkeeping rather than anything the user
+ added, and a manifest that counts ``.DS_Store`` as a document is simply
+ wrong — so they are skipped at every level. Symlinked directories are not
+ followed, so a linked folder pointing into itself cannot loop.
+
+ This is the canonical definition of "a document in a KB":
+ :meth:`KnowledgeBaseManager.get_info`'s ``raw_documents`` statistic reads it
+ too. The ``GET /knowledge/{kb}/files`` endpoint is a different thing — a
+ directory browser that also reports folders, for the KB file-manager UI.
+ """
+ if not root.is_dir():
+ return
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = sorted(name for name in dirnames if not name.startswith("."))
+ current = Path(dirpath)
+ for filename in sorted(filenames):
+ if filename.startswith("."):
+ continue
+ path = current / filename
+ if path.is_file():
+ yield path
+
+
+def document_root(kb_dir: Path, entry: Mapping[str, Any]) -> Path | None:
+ """Where ``entry``'s documents live on this machine, or ``None`` if nowhere.
+
+ Ordinary indexed KBs own ``<kb_dir>/raw``. A connected KB that points at a
+ real folder (``linked``, ``obsidian``) is enumerated in place. A remote
+ LightRAG server and a connected subagent have no local document set at all.
+ """
+ external = external_root_of(entry)
+ if external:
+ return Path(str(external)).expanduser()
+ if str(entry.get("type") or "").strip() in _NON_DOCUMENT_KB_TYPES:
+ return None
+ return kb_dir / "raw"
+
+
+def build_manifest(
+ *,
+ name: str,
+ kb_dir: Path,
+ entry: Mapping[str, Any] | None = None,
+ limit: int = MANIFEST_NOTE_LIMIT,
+ pattern: str = "",
+) -> KbManifest:
+ """Read ``name``'s document inventory off disk.
+
+ ``entry`` is the KB's ``kb_config.json`` record (provider / status / type);
+ it is read but never trusted for counts, which come from the filesystem.
+ ``pattern`` filters by name — a glob when it contains wildcards, otherwise a
+ case-insensitive substring. Only the retained documents are stat'ed, so a
+ large KB costs one directory walk rather than thousands of syscalls.
+ """
+ record: Mapping[str, Any] = entry or {}
+ kb_type = str(record.get("type") or "").strip()
+ manifest_fields: dict[str, Any] = {
+ "name": name,
+ "provider": str(record.get("rag_provider") or "").strip(),
+ "status": str(record.get("status") or "").strip(),
+ "kb_type": kb_type,
+ "pattern": pattern.strip(),
+ }
+
+ root = document_root(kb_dir, record)
+ if root is None:
+ return KbManifest(**manifest_fields, unavailable=_NON_DOCUMENT_KB_TYPES[kb_type])
+ if not root.is_dir():
+ # An external folder that moved, or a KB whose indexing never got as far
+ # as creating ``raw/``. Either way the document set is unknown, not empty.
+ return KbManifest(**manifest_fields, unavailable=UNAVAILABLE_MISSING)
+
+ all_names = [path.relative_to(root).as_posix() for path in iter_kb_documents(root)]
+ matched_names = _filter_names(all_names, manifest_fields["pattern"])
+ kept = matched_names[: max(0, limit)]
+ return KbManifest(
+ **manifest_fields,
+ total=len(all_names),
+ matched=len(matched_names),
+ documents=tuple(KbDocument(name=rel, size=_size_of(root / rel)) for rel in kept),
+ )
+
+
+def _filter_names(names: Sequence[str], pattern: str) -> list[str]:
+ if not pattern:
+ return list(names)
+ if any(char in pattern for char in "*?["):
+ lowered = pattern.lower()
+ return [
+ name
+ for name in names
+ if fnmatch.fnmatch(name.lower(), lowered)
+ or fnmatch.fnmatch(name.rsplit("/", 1)[-1].lower(), lowered)
+ ]
+ needle = pattern.lower()
+ return [name for name in names if needle in name.lower()]
+
+
+def _size_of(path: Path) -> int:
+ try:
+ return path.stat().st_size
+ except OSError:
+ return 0
+
+
+# ---------------------------------------------------------------------------
+# Rendering. Localised here (not by the caller) so the system-prompt manifest
+# and the tool report describe the same facts in the same words.
+# ---------------------------------------------------------------------------
+
+_STATUS_LABELS: dict[str, dict[str, str]] = {
+ "en": {
+ "ready": "index ready",
+ "needs_reindex": "needs reindexing, retrieval may be incomplete",
+ "processing": "still indexing, retrieval may be incomplete",
+ "initializing": "still indexing, retrieval may be incomplete",
+ "error": "indexing failed, retrieval may be unavailable",
+ },
+ "zh": {
+ "ready": "索引就绪",
+ "needs_reindex": "需要重建索引,检索结果可能不完整",
+ "processing": "正在索引,检索结果可能不完整",
+ "initializing": "正在索引,检索结果可能不完整",
+ "error": "索引失败,检索可能不可用",
+ },
+}
+
+# Complete sentences, so the manifest note and the tool report can share one
+# wording instead of each phrasing the same fact its own way.
+_UNAVAILABLE_LABELS: dict[str, dict[str, str]] = {
+ "en": {
+ UNAVAILABLE_REMOTE: "Hosted on a remote server; its document list cannot be read.",
+ UNAVAILABLE_AGENT: "A connected agent, not a document collection.",
+ UNAVAILABLE_MISSING: (
+ "Its document folder cannot be read right now — it may still be "
+ "under construction, or be an external folder that has moved."
+ ),
+ },
+ "zh": {
+ UNAVAILABLE_REMOTE: "由远端服务器托管,无法读取文档清单。",
+ UNAVAILABLE_AGENT: "是连接的智能体,不是文档集合。",
+ UNAVAILABLE_MISSING: "当前读不到它的文档目录——可能仍在创建中,也可能是外部文件夹已移动。",
+ },
+}
+
+_NOTE_TEXT: dict[str, dict[str, str]] = {
+ "en": {
+ "header": (
+ "[Knowledge Base Inventory]\n"
+ "What the attached knowledge bases actually contain, read from disk."
+ ),
+ "empty": "no documents yet",
+ "total": "{count} document{plural}",
+ "omitted": "and {count} more, use kb_files for the full list",
+ "authority": (
+ "Answer questions about document counts, file names, and whether a "
+ "given file is present from this inventory — it is authoritative. "
+ "Retrieved passages only show what a search happened to match and "
+ "must never be used to infer how many documents a knowledge base "
+ "holds or whether one exists in it. Call kb_files for the full list "
+ "or to filter by name."
+ ),
+ },
+ "zh": {
+ "header": "[知识库清单]\n以下是已挂载知识库的真实文档构成,直接读取自磁盘。",
+ "empty": "暂无文档",
+ "total": "共 {count} 个文档",
+ "omitted": "另有 {count} 个未列出,可用 kb_files 查看完整清单",
+ "authority": (
+ "回答文档数量、文件名、某个文件是否存在这类问题时,一律以本清单为准,"
+ "它是权威事实。检索到的片段只代表某次搜索命中的内容,"
+ "绝不能用来推断知识库有多少文档、或某个文档是否存在。"
+ "需要完整清单或按名称筛选时,调用 kb_files。"
+ ),
+ },
+}
+
+_REPORT_TEXT: dict[str, dict[str, str]] = {
+ "en": {
+ "heading": 'Knowledge base "{name}"{qualifier}: {total} document{plural}.',
+ "empty": 'Knowledge base "{name}"{qualifier} holds no documents.',
+ "unavailable": 'Knowledge base "{name}": {reason}',
+ "matched": 'Matching "{pattern}": {count}.',
+ "no_match": 'No document name matches "{pattern}".',
+ "omitted": "Showing the first {shown}; {omitted} more not listed "
+ "(narrow with pattern, or raise limit).",
+ },
+ "zh": {
+ "heading": "知识库「{name}」{qualifier}共 {total} 个文档。",
+ "empty": "知识库「{name}」{qualifier}暂无文档。",
+ "unavailable": "知识库「{name}」:{reason}",
+ "matched": "匹配「{pattern}」的有 {count} 个。",
+ "no_match": "没有文档名匹配「{pattern}」。",
+ "omitted": "以下列出前 {shown} 个,另有 {omitted} 个未列出(可用 pattern 缩小范围或提高 limit)。",
+ },
+}
+
+
+def _lang(language: str) -> str:
+ return "zh" if str(language or "en").lower().startswith("zh") else "en"
+
+
+def _colon(language: str) -> str:
+ return ":" if language == "zh" else ": "
+
+
+def _count(text: Mapping[str, str], key: str, count: int) -> str:
+ return text[key].format(count=count, plural="" if count == 1 else "s")
+
+
+def _qualifier(manifest: KbManifest, language: str) -> str:
+ """Parenthesised provider + index status, e.g. ``(llamaindex, index ready)``."""
+ parts = [part for part in (manifest.provider, _status_label(manifest, language)) if part]
+ if not parts:
+ return ""
+ return f"({','.join(parts)})" if language == "zh" else f" ({', '.join(parts)})"
+
+
+def _status_label(manifest: KbManifest, language: str) -> str:
+ return _STATUS_LABELS[language].get(manifest.status, "")
+
+
+def render_manifest_note(manifests: Sequence[KbManifest], *, language: str) -> str:
+ """The system-prompt block: one line per KB, plus the authority rule.
+
+ Empty when there is nothing to describe, so the caller can concatenate it
+ unconditionally.
+ """
+ if not manifests:
+ return ""
+ language = _lang(language)
+ text = _NOTE_TEXT[language]
+ lines = [f"- {_note_line(manifest, language)}" for manifest in manifests]
+ return "\n".join([text["header"], *lines, text["authority"]])
+
+
+def _note_line(manifest: KbManifest, language: str) -> str:
+ text = _NOTE_TEXT[language]
+ head = f"{manifest.name}{_qualifier(manifest, language)}{_colon(language)}"
+ if not manifest.enumerable:
+ return f"{head}{_UNAVAILABLE_LABELS[language][manifest.unavailable]}"
+ if not manifest.total:
+ return f"{head}{text['empty']}"
+ listed = "; ".join(document.name for document in manifest.documents)
+ if manifest.omitted:
+ tail = text["omitted"].format(count=manifest.omitted)
+ listed = f"{listed}({tail})" if language == "zh" else f"{listed} ({tail})"
+ return f"{head}{_count(text, 'total', manifest.total)} — {listed}"
+
+
+def render_manifest_report(manifest: KbManifest, *, language: str) -> str:
+ """The ``kb_files`` tool's answer for one knowledge base."""
+ language = _lang(language)
+ text = _REPORT_TEXT[language]
+ qualifier = _qualifier(manifest, language)
+ if not manifest.enumerable:
+ reason = _UNAVAILABLE_LABELS[language][manifest.unavailable]
+ return text["unavailable"].format(name=manifest.name, reason=reason)
+ if not manifest.total:
+ return text["empty"].format(name=manifest.name, qualifier=qualifier)
+
+ lines = [
+ text["heading"].format(
+ name=manifest.name,
+ qualifier=qualifier,
+ total=manifest.total,
+ plural="" if manifest.total == 1 else "s",
+ )
+ ]
+ if manifest.pattern:
+ if not manifest.matched:
+ lines.append(text["no_match"].format(pattern=manifest.pattern))
+ return "\n".join(lines)
+ lines.append(text["matched"].format(pattern=manifest.pattern, count=manifest.matched))
+ if manifest.omitted:
+ lines.append(
+ text["omitted"].format(shown=len(manifest.documents), omitted=manifest.omitted)
+ )
+ lines.extend(
+ f"{index}. {document.name} ({_human_size(document.size)})"
+ for index, document in enumerate(manifest.documents, start=1)
+ )
+ return "\n".join(lines)
+
+
+def _human_size(size: int) -> str:
+ if size < 1024:
+ return f"{size} B"
+ value = float(size)
+ for unit in ("KB", "MB", "GB"):
+ value /= 1024
+ if value < 1024:
+ return f"{value:.1f} {unit}"
+ return f"{value:.1f} TB"
+
+
+__all__ = [
+ "KB_FILES_DEFAULT_LIMIT",
+ "KB_FILES_MAX_LIMIT",
+ "MANIFEST_NOTE_LIMIT",
+ "UNAVAILABLE_AGENT",
+ "UNAVAILABLE_MISSING",
+ "UNAVAILABLE_REMOTE",
+ "KbDocument",
+ "KbManifest",
+ "build_manifest",
+ "document_root",
+ "iter_kb_documents",
+ "render_manifest_note",
+ "render_manifest_report",
+]
diff --git a/deeptutor/multi_user/knowledge_access.py b/deeptutor/multi_user/knowledge_access.py
index 00dbf04ce..41c3f7e5d 100644
--- a/deeptutor/multi_user/knowledge_access.py
+++ b/deeptutor/multi_user/knowledge_access.py
@@ -9,6 +9,7 @@ from typing import Any
from fastapi import HTTPException
from deeptutor.knowledge.manager import KnowledgeBaseManager
+from deeptutor.knowledge.manifest import MANIFEST_NOTE_LIMIT, KbManifest, build_manifest
from .context import get_current_user
from .grants import load_grant
@@ -245,3 +246,36 @@ def resolve_kb_metadata(kb_ref: str | None) -> dict[str, Any] | None:
return None
manager = _manager_for(str(resource.base_dir.resolve()))
return manager.get_metadata(resource.name)
+
+
+def resolve_kb_manifest(
+ kb_ref: str | None,
+ *,
+ limit: int = MANIFEST_NOTE_LIMIT,
+ pattern: str = "",
+) -> KbManifest | None:
+ """Access-checked document inventory for ``kb_ref`` (``None`` if inaccessible).
+
+ The one seam through which the chat manifest and the ``kb_files`` tool read
+ a KB's document set, so neither can bypass the per-user visibility rules
+ :func:`resolve_kb` enforces. A pure read with no usage audit, mirroring
+ :func:`resolve_kb_metadata`; it touches the filesystem, so async callers
+ should hand it to a worker thread.
+ """
+ if not kb_ref:
+ return None
+ try:
+ resource = resolve_kb(str(kb_ref), require_write=False)
+ except HTTPException:
+ return None
+ manager = _manager_for(str(resource.base_dir.resolve()))
+ entry = manager.get_kb_entry(resource.name)
+ if entry is None:
+ return None
+ return build_manifest(
+ name=resource.name,
+ kb_dir=resource.base_dir / resource.name,
+ entry=entry,
+ limit=limit,
+ pattern=pattern,
+ )
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index 1a0517b8d..824d7066b 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -12,6 +12,7 @@ from deeptutor.capabilities.obsidian import OBSIDIAN_TOOL_TYPES
from deeptutor.capabilities.solve import SOLVE_TOOL_TYPES
from deeptutor.capabilities.subagent import SUBAGENT_TOOL_TYPES
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
+from deeptutor.knowledge.manifest import KB_FILES_DEFAULT_LIMIT, KB_FILES_MAX_LIMIT
from deeptutor.tools.exec_tool import ExecTool
from deeptutor.tools.media_gen_tool import ImagegenTool, VideogenTool
from deeptutor.tools.partner_memory import (
@@ -140,6 +141,96 @@ class RAGTool(_PromptHintsMixin, BaseTool):
)
+class KbFilesTool(_PromptHintsMixin, BaseTool):
+ """Enumerate what a knowledge base holds — the query ``rag`` cannot serve.
+
+ Retrieval returns passages; it cannot report how many documents a KB holds
+ or whether a named file is in it. The chat system prompt carries a truncated
+ inventory for exactly this reason; this tool serves the full list and
+ name filtering.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="kb_files",
+ description=(
+ "List the documents stored in one of the knowledge bases attached "
+ "to this turn, with the total count. Use this — never rag — for "
+ "questions about how many files a knowledge base holds, what its "
+ "files are called, or whether a particular file is in it."
+ ),
+ parameters=[
+ ToolParameter(
+ name="kb_name",
+ type="string",
+ description="Knowledge base to inspect. Must be one of the attached knowledge bases.",
+ ),
+ ToolParameter(
+ name="pattern",
+ type="string",
+ description=(
+ "Optional name filter: a glob such as '*.pdf', or a "
+ "case-insensitive substring. Omit to list everything."
+ ),
+ required=False,
+ ),
+ ToolParameter(
+ name="limit",
+ type="integer",
+ description=(
+ f"Optional maximum number of documents to list "
+ f"(default {KB_FILES_DEFAULT_LIMIT}, max {KB_FILES_MAX_LIMIT})."
+ ),
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.knowledge.manifest import render_manifest_report
+ from deeptutor.multi_user.knowledge_access import resolve_kb_manifest
+
+ kb_name = str(kwargs.get("kb_name") or "").strip()
+ if not kb_name:
+ raise ValueError("kb_files requires an explicit kb_name.")
+ pattern = str(kwargs.get("pattern") or "").strip()
+ language = str(kwargs.get("language") or "en")
+
+ manifest = await asyncio.to_thread(
+ resolve_kb_manifest,
+ kb_name,
+ limit=_kb_files_limit(kwargs.get("limit")),
+ pattern=pattern,
+ )
+ if manifest is None:
+ raise ValueError(f"Knowledge base '{kb_name}' is not accessible.")
+
+ return ToolResult(
+ content=render_manifest_report(manifest, language=language),
+ metadata={
+ "kb_name": manifest.name,
+ "total": manifest.total,
+ "matched": manifest.matched,
+ "listed": [document.name for document in manifest.documents],
+ "omitted": manifest.omitted,
+ "pattern": manifest.pattern,
+ "status": manifest.status,
+ "unavailable": manifest.unavailable,
+ },
+ )
+
+
+def _kb_files_limit(raw: Any) -> int:
+ """Clamp a model-supplied ``limit`` into range; fall back on anything unusable."""
+ try:
+ requested = int(raw)
+ except (TypeError, ValueError):
+ return KB_FILES_DEFAULT_LIMIT
+ if requested <= 0:
+ return KB_FILES_DEFAULT_LIMIT
+ return min(requested, KB_FILES_MAX_LIMIT)
+
+
class WebSearchTool(_PromptHintsMixin, BaseTool):
def get_definition(self) -> ToolDefinition:
return ToolDefinition(
@@ -1471,6 +1562,7 @@ class CronTool(_PromptHintsMixin, BaseTool):
BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
BrainstormTool,
RAGTool,
+ KbFilesTool,
WebSearchTool,
CodeExecutionTool,
ReasonTool,
@@ -1554,6 +1646,7 @@ USER_TOGGLEABLE_TOOL_NAMES: tuple[str, ...] = (
# this surface.
CONFIGURABLE_BUILTIN_TOOL_NAMES: tuple[str, ...] = (
"rag",
+ "kb_files",
"code_execution",
"read_source",
"read_memory",
@@ -1592,6 +1685,7 @@ __all__ = [
"ExecTool",
"GeoGebraAnalysisTool",
"GithubTool",
+ "KbFilesTool",
"ImagegenTool",
"VideogenTool",
"ListNotebookTool",
diff --git a/deeptutor/tools/prompting/hints/en/kb_files.yaml b/deeptutor/tools/prompting/hints/en/kb_files.yaml
new file mode 100644
index 000000000..4e8b9dc8b
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/kb_files.yaml
@@ -0,0 +1,6 @@
+short_description: "List the documents an attached knowledge base holds, with the total count."
+when_to_use: "Use for questions about the knowledge base itself rather than its content — how many files it holds, what they are called, whether a particular document is in it, or what was uploaded."
+input_format: "{\"kb_name\": \"one of the attached knowledge base names\", \"pattern\": \"optional glob like '*.pdf' or a substring\", \"limit\": \"optional maximum to list\"}."
+guideline: "Never answer a counting or file-existence question from rag passages — retrieval only shows what a search matched and says nothing about the size of the collection. The system prompt's knowledge base inventory already covers the counts; call this tool for the full list or to filter by name."
+note: "Counts come from the files stored in the knowledge base. A knowledge base whose index is not ready still lists its documents, and a knowledge base hosted on a remote server cannot list them at all — report either fact as given."
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/kb_files.yaml b/deeptutor/tools/prompting/hints/zh/kb_files.yaml
new file mode 100644
index 000000000..915e5b4d0
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/kb_files.yaml
@@ -0,0 +1,6 @@
+short_description: "列出用户挂载的某个知识库中的文档清单与总数。"
+when_to_use: "当问题问的是知识库本身而不是其内容时使用——有多少个文件、文件都叫什么、某个文档在不在里面、上传了些什么。"
+input_format: "{\"kb_name\": \"挂载的某个知识库名称\", \"pattern\": \"可选,'*.pdf' 这样的通配符或一段文件名\", \"limit\": \"可选,最多列出多少个\"}。"
+guideline: "绝不能用 rag 检索到的片段回答数量或某文件是否存在的问题——检索只反映某次搜索命中的内容,说明不了整个知识库有多大。系统提示里的知识库清单已经给出了数量;需要完整清单或按名称筛选时才调用本工具。"
+note: "数量来自知识库中实际存放的文件。索引未就绪的知识库依然能列出文档;由远端服务器托管的知识库则无法列出——两种情况都据实说明。"
+phase: "exploration"
diff --git a/tests/agents/chat/test_kb_manifest_note.py b/tests/agents/chat/test_kb_manifest_note.py
new file mode 100644
index 000000000..32aa9c6d5
--- /dev/null
+++ b/tests/agents/chat/test_kb_manifest_note.py
@@ -0,0 +1,176 @@
+"""The system prompt states what the attached knowledge bases contain.
+
+Retrieval cannot answer "how many files are in this KB" — passages carry no
+information about the size of the collection they came from, so a model holding
+only ``rag`` guesses. The turn therefore reads the inventory off disk once and
+puts it in the system prompt, where a count is answerable with no tool call at
+all (the failure mode where a weaker model never calls the tool) and where the
+prompt stays byte-stable for the whole turn.
+
+These tests pin the wiring: the note reaches the prompt, PageIndex KBs are not
+described twice, and an unreadable KB costs the manifest rather than the turn.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
+from deeptutor.core.context import UnifiedContext
+from deeptutor.knowledge.manifest import KbDocument, KbManifest
+
+
+def _manifest(name: str, *documents: str, total: int | None = None) -> KbManifest:
+ docs = tuple(KbDocument(name=doc, size=1024) for doc in documents)
+ return KbManifest(
+ name=name,
+ provider="llamaindex",
+ status="ready",
+ total=total if total is not None else len(docs),
+ matched=total if total is not None else len(docs),
+ documents=docs,
+ )
+
+
+def _pipeline(monkeypatch: pytest.MonkeyPatch, *, language: str = "en") -> AgenticChatPipeline:
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ return AgenticChatPipeline(language=language)
+
+
+def _stub_resolver(
+ monkeypatch: pytest.MonkeyPatch, manifests: dict[str, KbManifest | None]
+) -> list[str]:
+ """Replace the access-checked resolver; record which KBs were asked for."""
+ asked: list[str] = []
+
+ def _resolve(kb_ref: str, **_kwargs: Any) -> KbManifest | None:
+ asked.append(kb_ref)
+ return manifests.get(kb_ref)
+
+ monkeypatch.setattr(
+ "deeptutor.multi_user.knowledge_access.resolve_kb_manifest", _resolve, raising=False
+ )
+ return asked
+
+
+async def test_manifest_reaches_the_system_prompt(monkeypatch: pytest.MonkeyPatch) -> None:
+ pipeline = _pipeline(monkeypatch)
+ _stub_resolver(monkeypatch, {"course": _manifest("course", "a.pdf", "notes/week3.md")})
+ context = UnifiedContext(
+ session_id="s1", user_message="how many files?", knowledge_bases=["course"]
+ )
+
+ await pipeline._prepare_kb_manifests(context)
+ prompt = pipeline._build_system_prompt(["rag", "kb_files"], context)
+
+ assert "[Knowledge Base Inventory]" in prompt
+ assert "2 documents" in prompt
+ assert "notes/week3.md" in prompt
+ # The authority rule (C): passages are not evidence about the collection.
+ assert "must never be used to infer how many documents" in prompt
+
+
+async def test_manifest_is_localised(monkeypatch: pytest.MonkeyPatch) -> None:
+ pipeline = _pipeline(monkeypatch, language="zh")
+ _stub_resolver(monkeypatch, {"course": _manifest("course", "a.pdf")})
+ context = UnifiedContext(session_id="s1", user_message="有几个文件", knowledge_bases=["course"])
+
+ await pipeline._prepare_kb_manifests(context)
+
+ assert "共 1 个文档" in pipeline._kb_system_note(context)
+
+
+async def test_every_attached_kb_is_described(monkeypatch: pytest.MonkeyPatch) -> None:
+ pipeline = _pipeline(monkeypatch)
+ asked = _stub_resolver(
+ monkeypatch,
+ {"course": _manifest("course", "a.pdf"), "papers": _manifest("papers", "p1.pdf", "p2.pdf")},
+ )
+ context = UnifiedContext(
+ session_id="s1", user_message="what's in there?", knowledge_bases=["course", "papers"]
+ )
+
+ await pipeline._prepare_kb_manifests(context)
+ note = pipeline._kb_system_note(context)
+
+ assert asked == ["course", "papers"]
+ assert "course" in note and "papers" in note
+
+
+async def test_pageindex_kbs_are_not_described_twice(monkeypatch: pytest.MonkeyPatch) -> None:
+ """PageIndex's own note already lists its documents, with their doc_ids."""
+ pipeline = _pipeline(monkeypatch)
+ pipeline._pageindex_docs = {"hosted": {"paper.pdf": "doc-1"}}
+ asked = _stub_resolver(monkeypatch, {"course": _manifest("course", "a.pdf")})
+ context = UnifiedContext(
+ session_id="s1", user_message="how many?", knowledge_bases=["course", "hosted"]
+ )
+
+ await pipeline._prepare_kb_manifests(context)
+
+ assert asked == ["course"]
+ assert [manifest.name for manifest in pipeline._kb_manifests] == ["course"]
+
+
+async def test_no_kb_attached_yields_no_inventory(monkeypatch: pytest.MonkeyPatch) -> None:
+ pipeline = _pipeline(monkeypatch)
+ asked = _stub_resolver(monkeypatch, {})
+ context = UnifiedContext(session_id="s1", user_message="hello", knowledge_bases=[])
+
+ await pipeline._prepare_kb_manifests(context)
+
+ assert asked == []
+ assert pipeline._kb_manifests == []
+ assert "[Knowledge Base Inventory]" not in pipeline._build_system_prompt(
+ ["web_search"], context
+ )
+
+
+async def test_inaccessible_kb_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A KB the user cannot see must not appear — resolution returns None."""
+ pipeline = _pipeline(monkeypatch)
+ _stub_resolver(monkeypatch, {"course": _manifest("course", "a.pdf"), "secret": None})
+ context = UnifiedContext(
+ session_id="s1", user_message="how many?", knowledge_bases=["course", "secret"]
+ )
+
+ await pipeline._prepare_kb_manifests(context)
+
+ assert [manifest.name for manifest in pipeline._kb_manifests] == ["course"]
+
+
+async def test_unreadable_kb_costs_the_manifest_not_the_turn(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pipeline = _pipeline(monkeypatch)
+
+ def _boom(kb_ref: str, **_kwargs: Any) -> KbManifest:
+ if kb_ref == "broken":
+ raise OSError("permission denied")
+ return _manifest(kb_ref, "a.pdf")
+
+ monkeypatch.setattr(
+ "deeptutor.multi_user.knowledge_access.resolve_kb_manifest", _boom, raising=False
+ )
+ context = UnifiedContext(
+ session_id="s1", user_message="how many?", knowledge_bases=["broken", "course"]
+ )
+
+ await pipeline._prepare_kb_manifests(context)
+
+ assert [manifest.name for manifest in pipeline._kb_manifests] == ["course"]
diff --git a/tests/capabilities/test_obsidian_capability.py b/tests/capabilities/test_obsidian_capability.py
index 2364210d7..9cb98be98 100644
--- a/tests/capabilities/test_obsidian_capability.py
+++ b/tests/capabilities/test_obsidian_capability.py
@@ -178,8 +178,9 @@ async def test_read_missing_note_is_graceful(tmp_path: Path) -> None:
def test_exclusive_compose_drops_builtins_but_keeps_coexisting_rag() -> None:
# Issue #650: an exclusive capability drops chat built-ins / composer
- # toggles, but rag coexists when has_kb is set (co-selected LlamaIndex KBs
- # the capability does not own). Other flags (code/memory) stay dropped.
+ # toggles, but the KB built-ins coexist when has_kb is set — co-selected
+ # LlamaIndex KBs the capability does not own stay both searchable (rag) and
+ # enumerable (kb_files). Other flags (code/memory) stay dropped.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search", "reason"],
@@ -188,7 +189,13 @@ def test_exclusive_compose_drops_builtins_but_keeps_coexisting_rag() -> None:
capability_owned=["obsidian_search", "obsidian_read"],
exclusive=True,
)
- assert set(composed) == {"obsidian_search", "obsidian_read", "rag", "ask_user"}
+ assert set(composed) == {
+ "obsidian_search",
+ "obsidian_read",
+ "rag",
+ "kb_files",
+ "ask_user",
+ }
def test_exclusive_compose_pure_vault_mounts_no_rag() -> None:
diff --git a/tests/capabilities/test_subagent_capability.py b/tests/capabilities/test_subagent_capability.py
index 9d5ecc900..1178e9333 100644
--- a/tests/capabilities/test_subagent_capability.py
+++ b/tests/capabilities/test_subagent_capability.py
@@ -114,8 +114,9 @@ def test_binding_cached(monkeypatch) -> None:
def test_exclusive_compose_drops_builtins_but_keeps_coexisting_rag() -> None:
- # Issue #650: rag coexists when has_kb is set (a co-selected real KB the
- # capability does not own); other built-ins/toggles stay dropped.
+ # Issue #650: the KB built-ins coexist when has_kb is set (a co-selected
+ # real KB the capability does not own is both searchable and enumerable);
+ # other built-ins/toggles stay dropped.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search", "rag"],
@@ -124,7 +125,7 @@ def test_exclusive_compose_drops_builtins_but_keeps_coexisting_rag() -> None:
capability_owned=["consult_subagent"],
exclusive=True,
)
- assert set(composed) == {"consult_subagent", "rag", "ask_user"}
+ assert set(composed) == {"consult_subagent", "rag", "kb_files", "ask_user"}
def test_exclusive_compose_pure_subagent_mounts_no_rag() -> None:
diff --git a/tests/knowledge/test_manifest.py b/tests/knowledge/test_manifest.py
new file mode 100644
index 000000000..0fe3e3f0d
--- /dev/null
+++ b/tests/knowledge/test_manifest.py
@@ -0,0 +1,236 @@
+"""KB document inventory — the facts retrieval cannot answer.
+
+"How many files are in this knowledge base?" is a question about the
+collection, not about passage similarity, so it is answered from disk. These
+tests pin the counting rules (what is and isn't a document), the degradations
+(remote / agent / unreadable KBs), and the wording contract both consumers —
+the chat system prompt and the ``kb_files`` tool — render from.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.knowledge.manifest import (
+ UNAVAILABLE_AGENT,
+ UNAVAILABLE_MISSING,
+ UNAVAILABLE_REMOTE,
+ build_manifest,
+ document_root,
+ iter_kb_documents,
+ render_manifest_note,
+ render_manifest_report,
+)
+
+_READY = {"rag_provider": "llamaindex", "status": "ready"}
+
+
+def _kb(tmp_path: Path, *files: str, name: str = "Course") -> Path:
+ kb_dir = tmp_path / name
+ raw = kb_dir / "raw"
+ raw.mkdir(parents=True, exist_ok=True)
+ for rel in files:
+ target = raw / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(b"x" * 2048)
+ return kb_dir
+
+
+class TestDocumentCounting:
+ def test_counts_documents_in_subfolders(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf", "notes/week3.md", "notes/deep/week4.md")
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ assert manifest.total == 3
+ # Folders are organizational only, so a document is identified by its
+ # path relative to raw/ — not by basename. Order is a depth-first walk
+ # with each level sorted: a folder's own files before its subfolders.
+ assert [doc.name for doc in manifest.documents] == [
+ "a.pdf",
+ "notes/week3.md",
+ "notes/deep/week4.md",
+ ]
+
+ def test_hidden_bookkeeping_is_not_a_document(self, tmp_path: Path) -> None:
+ """``.DS_Store`` is not something the user uploaded."""
+ kb_dir = _kb(tmp_path, "a.pdf", ".DS_Store", ".obsidian/workspace.json")
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ assert manifest.total == 1
+ assert [doc.name for doc in manifest.documents] == ["a.pdf"]
+
+ def test_empty_kb_reports_zero_rather_than_unavailable(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path)
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ assert manifest.enumerable
+ assert manifest.total == 0
+
+ def test_documents_are_truncated_but_total_is_not(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, *(f"doc{index:02d}.pdf" for index in range(10)))
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY, limit=3)
+
+ assert manifest.total == 10
+ assert len(manifest.documents) == 3
+ assert manifest.omitted == 7
+
+ def test_sizes_are_read_for_listed_documents(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf")
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ assert manifest.documents[0].size == 2048
+
+ def test_iter_skips_directories_and_sorts(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "b.pdf", "a.pdf", "sub/c.pdf")
+
+ names = [path.name for path in iter_kb_documents(kb_dir / "raw")]
+
+ assert names == ["a.pdf", "b.pdf", "c.pdf"]
+
+ def test_iter_of_missing_root_is_empty(self, tmp_path: Path) -> None:
+ assert list(iter_kb_documents(tmp_path / "nope")) == []
+
+
+class TestPatternFilter:
+ def test_glob_matches_full_path_or_basename(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf", "b.md", "notes/week3.md")
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY, pattern="*.md")
+
+ assert manifest.matched == 2
+ assert [doc.name for doc in manifest.documents] == ["b.md", "notes/week3.md"]
+
+ def test_plain_text_is_a_case_insensitive_substring(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "Lecture01.pdf", "lab.pdf")
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY, pattern="LECTURE")
+
+ assert [doc.name for doc in manifest.documents] == ["Lecture01.pdf"]
+
+ def test_total_stays_the_whole_kb_when_filtering(self, tmp_path: Path) -> None:
+ """A filtered view must not misreport how large the KB is."""
+ kb_dir = _kb(tmp_path, "a.pdf", "b.pdf", "c.md")
+
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY, pattern="*.md")
+
+ assert (manifest.total, manifest.matched) == (3, 1)
+
+
+class TestConnectedKbs:
+ def test_linked_kb_enumerates_the_external_folder(self, tmp_path: Path) -> None:
+ external = tmp_path / "elsewhere"
+ (external / "sub").mkdir(parents=True)
+ (external / "paper.pdf").write_text("x")
+ (external / "sub" / "notes.md").write_text("x")
+ entry = {"type": "linked", "external_path": str(external), "rag_provider": "llamaindex"}
+
+ manifest = build_manifest(name="Linked", kb_dir=tmp_path / "Linked", entry=entry)
+
+ assert manifest.total == 2
+ assert document_root(tmp_path / "Linked", entry) == external
+
+ def test_remote_server_kb_is_not_reported_as_empty(self, tmp_path: Path) -> None:
+ """A hosted KB has documents we simply cannot see — "0" would be a lie."""
+ entry = {"type": "lightrag_server", "server_url": "https://example.invalid"}
+
+ manifest = build_manifest(name="Remote", kb_dir=tmp_path / "Remote", entry=entry)
+
+ assert not manifest.enumerable
+ assert manifest.unavailable == UNAVAILABLE_REMOTE
+ assert manifest.total == 0
+ assert document_root(tmp_path / "Remote", entry) is None
+
+ def test_connected_agent_is_not_a_document_collection(self, tmp_path: Path) -> None:
+ entry = {"type": "subagent", "agent_kind": "claude_code"}
+
+ manifest = build_manifest(name="Agent", kb_dir=tmp_path / "Agent", entry=entry)
+
+ assert manifest.unavailable == UNAVAILABLE_AGENT
+
+ def test_missing_root_is_unavailable_not_empty(self, tmp_path: Path) -> None:
+ manifest = build_manifest(name="Fresh", kb_dir=tmp_path / "Fresh", entry=_READY)
+
+ assert manifest.unavailable == UNAVAILABLE_MISSING
+
+
+class TestManifestNote:
+ def test_note_carries_count_names_and_the_authority_rule(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf", "notes/week3.md")
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ note = render_manifest_note([manifest], language="en")
+
+ assert "2 documents" in note
+ assert "notes/week3.md" in note
+ # C: retrieval must never be the basis for a count.
+ assert "must never be used to infer how many documents" in note
+ assert "kb_files" in note
+
+ def test_note_is_localised(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf")
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ note = render_manifest_note([manifest], language="zh")
+
+ assert "共 1 个文档" in note
+ assert "以本清单为准" in note
+
+ def test_note_warns_when_the_index_is_not_ready(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf")
+ entry = {"rag_provider": "llamaindex", "status": "needs_reindex"}
+
+ note = render_manifest_note(
+ [build_manifest(name="Course", kb_dir=kb_dir, entry=entry)], language="en"
+ )
+
+ assert "needs reindexing" in note
+
+ def test_note_mentions_the_omitted_tail(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, *(f"doc{index:02d}.pdf" for index in range(5)))
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY, limit=2)
+
+ note = render_manifest_note([manifest], language="en")
+
+ assert "3 more" in note
+
+ def test_no_manifests_yields_no_block(self) -> None:
+ assert render_manifest_note([], language="en") == ""
+
+
+class TestManifestReport:
+ def test_report_lists_documents_with_sizes(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf")
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ report = render_manifest_report(manifest, language="en")
+
+ assert "1 document." in report
+ assert "1. a.pdf (2.0 KB)" in report
+
+ def test_report_states_a_pattern_matched_nothing(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path, "a.pdf")
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY, pattern="zzz")
+
+ report = render_manifest_report(manifest, language="en")
+
+ assert 'No document name matches "zzz"' in report
+
+ def test_report_declares_a_remote_kb_unlistable(self, tmp_path: Path) -> None:
+ entry = {"type": "lightrag_server"}
+ manifest = build_manifest(name="Remote", kb_dir=tmp_path / "Remote", entry=entry)
+
+ report = render_manifest_report(manifest, language="en")
+
+ assert "remote server" in report
+ assert "0" not in report
+
+ def test_report_of_an_empty_kb_says_so(self, tmp_path: Path) -> None:
+ kb_dir = _kb(tmp_path)
+ manifest = build_manifest(name="Course", kb_dir=kb_dir, entry=_READY)
+
+ assert "no documents" in render_manifest_report(manifest, language="en")
diff --git a/tests/multi_user/test_kb_manifest_access.py b/tests/multi_user/test_kb_manifest_access.py
new file mode 100644
index 000000000..4fa7482a5
--- /dev/null
+++ b/tests/multi_user/test_kb_manifest_access.py
@@ -0,0 +1,70 @@
+"""``resolve_kb_manifest`` is the one seam that reads a KB's document list.
+
+Both consumers (the chat system-prompt inventory and the ``kb_files`` tool) go
+through it, so per-user visibility has to hold here: a user's own KBs resolve,
+an admin KB resolves only while it is granted, and anything else yields
+``None`` rather than a listing.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+from deeptutor.multi_user.knowledge_access import resolve_kb_manifest
+
+
+def _make_kb(manager: KnowledgeBaseManager, name: str, *files: str) -> None:
+ """Register a KB and stage documents into it, as an upload would."""
+ raw = Path(manager.base_dir) / name / "raw"
+ raw.mkdir(parents=True, exist_ok=True)
+ for filename in files:
+ (raw / filename).write_bytes(b"x" * 512)
+ manager.register_knowledge_base(name, description=f"test KB {name}")
+
+
+def test_user_sees_their_own_kb(mu_isolated_root, as_user) -> None:
+ from deeptutor.multi_user.knowledge_access import current_kb_manager
+
+ with as_user("u_alice", role="user"):
+ _make_kb(current_kb_manager(), "alice-kb", "a.pdf", "b.pdf")
+
+ manifest = resolve_kb_manifest("alice-kb")
+
+ assert manifest is not None
+ assert manifest.total == 2
+ assert [document.name for document in manifest.documents] == ["a.pdf", "b.pdf"]
+
+
+def test_pattern_and_limit_reach_the_filesystem(mu_isolated_root, as_user) -> None:
+ from deeptutor.multi_user.knowledge_access import current_kb_manager
+
+ with as_user("u_alice", role="user"):
+ _make_kb(current_kb_manager(), "alice-kb", "a.pdf", "b.pdf", "notes.md")
+
+ manifest = resolve_kb_manifest("alice-kb", pattern="*.pdf", limit=1)
+
+ assert manifest is not None
+ assert (manifest.total, manifest.matched, manifest.omitted) == (3, 2, 1)
+
+
+def test_unknown_kb_yields_no_manifest(mu_isolated_root, as_user) -> None:
+ with as_user("u_alice", role="user"):
+ assert resolve_kb_manifest("does-not-exist") is None
+
+
+def test_ungranted_admin_kb_yields_no_manifest(mu_isolated_root, as_user) -> None:
+ """Naming an admin KB directly must not leak its file list (403 → None)."""
+ from deeptutor.multi_user.knowledge_access import admin_kb_manager
+
+ with as_user("u_admin", role="admin"):
+ _make_kb(admin_kb_manager(), "admin-kb", "secret.pdf")
+
+ with as_user("u_alice", role="user"):
+ assert resolve_kb_manifest("admin:kb:admin-kb") is None
+
+
+def test_empty_reference_yields_no_manifest(mu_isolated_root, as_user) -> None:
+ with as_user("u_alice", role="user"):
+ assert resolve_kb_manifest("") is None
+ assert resolve_kb_manifest(None) is None
diff --git a/tests/tools/test_kb_files_tool.py b/tests/tools/test_kb_files_tool.py
new file mode 100644
index 000000000..b4ea7f6f8
--- /dev/null
+++ b/tests/tools/test_kb_files_tool.py
@@ -0,0 +1,186 @@
+"""``kb_files`` — enumerate a knowledge base, the query ``rag`` cannot serve.
+
+``rag`` returns passages, so "how many files are in here" and "is X in this KB"
+have no answer on that path. This tool reads the inventory instead, through the
+same access-checked seam the chat manifest uses, and it mounts under the same
+gate as ``rag``: attached KB or nothing.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from deeptutor.agents._shared.tool_composition import (
+ AUTO_MOUNTED_TOOLS,
+ ToolMountFlags,
+ compose_enabled_tools,
+)
+from deeptutor.knowledge.manifest import (
+ KB_FILES_DEFAULT_LIMIT,
+ KB_FILES_MAX_LIMIT,
+ build_manifest,
+)
+from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES, KbFilesTool
+
+_READY = {"rag_provider": "llamaindex", "status": "ready"}
+
+
+def _kb(tmp_path: Path, *files: str) -> Path:
+ raw = tmp_path / "Course" / "raw"
+ raw.mkdir(parents=True, exist_ok=True)
+ for name in files:
+ (raw / name).write_bytes(b"x" * 1024)
+ return tmp_path / "Course"
+
+
+def _stub_resolver(monkeypatch: pytest.MonkeyPatch, kb_dir: Path | None) -> list[dict[str, Any]]:
+ """Stand in for the access-checked resolver, recording its arguments."""
+ calls: list[dict[str, Any]] = []
+
+ def _resolve(kb_ref: str, *, limit: int = KB_FILES_DEFAULT_LIMIT, pattern: str = ""):
+ calls.append({"kb_ref": kb_ref, "limit": limit, "pattern": pattern})
+ if kb_dir is None:
+ return None
+ return build_manifest(
+ name=kb_ref, kb_dir=kb_dir, entry=_READY, limit=limit, pattern=pattern
+ )
+
+ monkeypatch.setattr(
+ "deeptutor.multi_user.knowledge_access.resolve_kb_manifest", _resolve, raising=False
+ )
+ return calls
+
+
+class TestRegistration:
+ def test_tool_is_registered(self) -> None:
+ assert "kb_files" in BUILTIN_TOOL_NAMES
+
+ def test_mounting_is_pipeline_owned_like_rag(self) -> None:
+ assert "kb_files" in AUTO_MOUNTED_TOOLS
+
+ def test_definition_steers_counting_questions_away_from_rag(self) -> None:
+ definition = KbFilesTool().get_definition()
+ assert definition.name == "kb_files"
+ assert "never rag" in definition.description
+ assert {param.name for param in definition.parameters} == {"kb_name", "pattern", "limit"}
+ assert [param.name for param in definition.parameters if param.required] == ["kb_name"]
+
+
+class TestMountGate:
+ def test_mounts_with_a_knowledge_base_attached(self) -> None:
+ tools = compose_enabled_tools(
+ registry=_EmptyRegistry(),
+ requested_tools=[],
+ optional_whitelist=[],
+ mount_flags=ToolMountFlags(has_kb=True),
+ )
+ assert "kb_files" in tools and "rag" in tools
+
+ def test_absent_without_a_knowledge_base(self) -> None:
+ tools = compose_enabled_tools(
+ registry=_EmptyRegistry(),
+ requested_tools=[],
+ optional_whitelist=[],
+ mount_flags=ToolMountFlags(has_kb=False),
+ )
+ assert "kb_files" not in tools
+
+ def test_coexists_with_an_exclusive_knowledge_capability(self) -> None:
+ """An Obsidian vault owns the turn; co-selected KBs stay enumerable (#650)."""
+ tools = compose_enabled_tools(
+ registry=_EmptyRegistry(),
+ requested_tools=[],
+ optional_whitelist=[],
+ mount_flags=ToolMountFlags(has_kb=True),
+ capability_owned=["obsidian_read"],
+ exclusive=True,
+ )
+ assert tools == ["obsidian_read", "rag", "kb_files", "ask_user"]
+
+ def test_a_partner_can_deny_it(self) -> None:
+ tools = compose_enabled_tools(
+ registry=_EmptyRegistry(),
+ requested_tools=[],
+ optional_whitelist=[],
+ mount_flags=ToolMountFlags(has_kb=True),
+ builtin_whitelist={"rag"},
+ )
+ assert "rag" in tools and "kb_files" not in tools
+
+
+class _EmptyRegistry:
+ @staticmethod
+ def get_enabled(_selected: list[str]) -> list[Any]:
+ return []
+
+
+class TestExecute:
+ @pytest.mark.asyncio
+ async def test_reports_count_and_names(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ _stub_resolver(monkeypatch, _kb(tmp_path, "a.pdf", "b.pdf"))
+
+ result = await KbFilesTool().execute(kb_name="Course", language="en")
+
+ assert "2 documents." in result.content
+ assert "a.pdf" in result.content
+ assert result.metadata["total"] == 2
+ assert result.metadata["listed"] == ["a.pdf", "b.pdf"]
+
+ @pytest.mark.asyncio
+ async def test_pattern_is_forwarded(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ calls = _stub_resolver(monkeypatch, _kb(tmp_path, "a.pdf", "b.md"))
+
+ result = await KbFilesTool().execute(kb_name="Course", pattern="*.md", language="en")
+
+ assert calls[0]["pattern"] == "*.md"
+ assert result.metadata["matched"] == 1
+ assert result.metadata["total"] == 2
+
+ @pytest.mark.asyncio
+ async def test_limit_is_clamped(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ calls = _stub_resolver(monkeypatch, _kb(tmp_path, "a.pdf"))
+ tool = KbFilesTool()
+
+ await tool.execute(kb_name="Course", limit=999_999)
+ await tool.execute(kb_name="Course", limit=0)
+ await tool.execute(kb_name="Course", limit="not a number")
+
+ assert [call["limit"] for call in calls] == [
+ KB_FILES_MAX_LIMIT,
+ KB_FILES_DEFAULT_LIMIT,
+ KB_FILES_DEFAULT_LIMIT,
+ ]
+
+ @pytest.mark.asyncio
+ async def test_language_follows_the_turn(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ _stub_resolver(monkeypatch, _kb(tmp_path, "a.pdf"))
+
+ result = await KbFilesTool().execute(kb_name="Course", language="zh")
+
+ assert "共 1 个文档" in result.content
+
+ @pytest.mark.asyncio
+ async def test_missing_kb_name_is_rejected(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_resolver(monkeypatch, None)
+
+ with pytest.raises(ValueError, match="explicit kb_name"):
+ await KbFilesTool().execute(kb_name=" ")
+
+ @pytest.mark.asyncio
+ async def test_inaccessible_kb_is_an_error_not_an_empty_list(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Reporting "no documents" for a KB the user cannot reach would mislead."""
+ _stub_resolver(monkeypatch, None)
+
+ with pytest.raises(ValueError, match="not accessible"):
+ await KbFilesTool().execute(kb_name="secret")
diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsx
index 699c8fce8..1d8d0b3c3 100644
--- a/web/components/chat/home/TracePanels.tsx
+++ b/web/components/chat/home/TracePanels.tsx
@@ -195,6 +195,13 @@ function describeToolCall(
chip: clip(str(a.query)) || null,
mono: false,
};
+ case "kb_files":
+ return {
+ Icon: KnowledgeMark,
+ verb: t("Listing knowledge base files"),
+ chip: str(a.kb_name) || null,
+ mono: false,
+ };
case "web_search":
return {
Icon: GlobeMark,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 90627919c..c2863782b 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2300,6 +2300,7 @@
"Running command": "Running command",
"Running code": "Running code",
"Searching knowledge": "Searching knowledge",
+ "Listing knowledge base files": "Listing knowledge base files",
"Searching the web": "Searching the web",
"Searching papers": "Searching papers",
"Fetching page": "Fetching page",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 1a4275d56..e47152178 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2300,6 +2300,7 @@
"Running command": "运行命令",
"Running code": "运行代码",
"Searching knowledge": "检索知识库",
+ "Listing knowledge base files": "查看知识库文件清单",
"Searching the web": "联网搜索",
"Searching papers": "检索论文",
"Fetching page": "抓取网页",