Skip to content

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

feat(knowledge): add KB frontier discovery tool (#1292) (#1293)

evan188199-tech271e4f7865db
diff --git a/README.md b/README.md
index 5e484cfd7..a1121d1ef 100644
--- a/README.md
+++ b/README.md
@@ -647,7 +647,7 @@ The loop is deliberately simple: the model thinks in rounds, calls tools when us
<img src="assets/figs/system/chat-agent-loop.png" alt="DeepTutor chat agent loop" width="900">
</div>
-User-toggleable tools are `brainstorm`, `web_search`, `paper_search`, `reason`, and `geogebra_analysis` — plus `imagegen` and `videogen` once you configure the matching generation model. Contextual tools such as `rag`, `kb_files`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `question_bank`, `github`, `consult_subagent`, `workspace_list`, `workspace_read`, `workspace_search`, `workspace_present`, and `workspace_export` mount automatically when the turn has the right context.
+User-toggleable tools are `brainstorm`, `web_search`, `paper_search`, `reason`, and `geogebra_analysis` — plus `imagegen` and `videogen` once you configure the matching generation model. Contextual tools such as `rag`, `kb_files`, `knowledge_frontier`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `question_bank`, `github`, `consult_subagent`, `workspace_list`, `workspace_read`, `workspace_search`, `workspace_present`, and `workspace_export` mount automatically when the turn has the right context.
Context comes in two kinds: **sticky session context** (capability, workspace or course, tools, knowledge bases, persona, model, and Reading / Mastery state) persists across turns; **one-time references** (files, chat history, books, reading sections, notebooks, question bank, imported agents) come from the `+` menu for a single turn. The voice button only transcribes the current message.
@@ -866,6 +866,7 @@ One `deeptutor` binary, two ways in: an interactive **REPL** for people who live
deeptutor chat # interactive REPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
+deeptutor run chat "Find recent work beyond this material" --kb textbook --tool knowledge_frontier
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py
index 7e1a03831..109b2e61a 100644
--- a/deeptutor/agents/_shared/tool_composition.py
+++ b/deeptutor/agents/_shared/tool_composition.py
@@ -47,6 +47,7 @@ AUTO_MOUNTED_TOOLS: frozenset[str] = frozenset(CONFIGURABLE_BUILTIN_TOOL_NAMES)
_CONDITIONAL_MOUNT_FLAGS: dict[str, str] = {
"rag": "has_kb",
"kb_files": "has_kb",
+ "knowledge_frontier": "has_kb",
"read_source": "has_sources",
"read_memory": "has_memory",
"list_notebook": "has_notebooks",
@@ -64,7 +65,7 @@ _CONDITIONAL_MOUNT_FLAGS: dict[str, str] = {
# 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")
+_KB_COEXISTING_TOOLS: tuple[str, ...] = ("rag", "kb_files", "knowledge_frontier")
# The workspace is the user's shared content surface, not a capability or an
# optional enhancement. These tools therefore survive exclusive capability
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index e0b9b6afd..5aedf8e07 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -221,6 +221,89 @@ def _kb_files_limit(raw: Any) -> int:
return min(requested, KB_FILES_MAX_LIMIT)
+class KnowledgeFrontierTool(_PromptHintsMixin, BaseTool):
+ """Discover recent research that extends an attached knowledge base."""
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="knowledge_frontier",
+ description=(
+ "Summarize the themes and gaps in one attached knowledge base, "
+ "then search arXiv for recent work that may extend it. Use when "
+ "the learner asks for frontier papers, new research, or what to "
+ "study next; the tool recommends but never imports sources."
+ ),
+ parameters=[
+ ToolParameter(
+ name="kb_name",
+ type="string",
+ description="Knowledge base to inspect. Must be one of the attached knowledge bases.",
+ ),
+ ToolParameter(
+ name="focus",
+ type="string",
+ description=(
+ "Optional narrower research goal, method, or topic. "
+ "Omit to cover the knowledge base broadly."
+ ),
+ required=False,
+ ),
+ ToolParameter(
+ name="max_papers",
+ type="integer",
+ description="Maximum recommendations to return (default 5, max 10).",
+ required=False,
+ default=5,
+ ),
+ ToolParameter(
+ name="years_limit",
+ type="integer",
+ description="Only include preprints from the last N years (default 3, max 10).",
+ required=False,
+ default=3,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.multi_user.knowledge_access import resolve_kb_manifest
+ from deeptutor.tools.knowledge_frontier import discover_frontier
+
+ kb_name = str(kwargs.get("kb_name") or "").strip()
+ if not kb_name:
+ raise ValueError("knowledge_frontier requires an explicit kb_name.")
+
+ manifest = await asyncio.to_thread(resolve_kb_manifest, kb_name, limit=20)
+ if manifest is None:
+ raise ValueError(f"Knowledge base '{kb_name}' is not accessible.")
+
+ result = await discover_frontier(
+ kb_name=kb_name,
+ manifest=manifest,
+ focus=kwargs.get("focus", ""),
+ max_papers=kwargs.get("max_papers", 5),
+ years_limit=kwargs.get("years_limit", 3),
+ api_key=kwargs.get("api_key"),
+ base_url=kwargs.get("base_url"),
+ model=kwargs.get("model"),
+ )
+ paper_sources = [
+ {
+ "type": "paper",
+ "provider": "arxiv",
+ "url": paper.get("url", ""),
+ "title": paper.get("title", ""),
+ "arxiv_id": paper.get("arxiv_id", ""),
+ }
+ for paper in result["metadata"]["papers"]
+ ]
+ return ToolResult(
+ content=result["content"],
+ sources=[*result["kb_sources"], *paper_sources],
+ metadata=result["metadata"],
+ )
+
+
class WebSearchTool(_PromptHintsMixin, BaseTool):
def get_definition(self) -> ToolDefinition:
return ToolDefinition(
@@ -1572,6 +1655,7 @@ USER_TOGGLEABLE_TOOL_NAMES: tuple[str, ...] = (
CONFIGURABLE_BUILTIN_TOOL_NAMES: tuple[str, ...] = (
"rag",
"kb_files",
+ "knowledge_frontier",
"read_source",
"read_memory",
"write_memory",
@@ -1630,6 +1714,7 @@ __all__ = [
"GithubTool",
"KbFilesTool",
"ImagegenTool",
+ "KnowledgeFrontierTool",
"VideogenTool",
"ListNotebookTool",
"PaperSearchToolWrapper",
diff --git a/deeptutor/tools/builtin_specs.py b/deeptutor/tools/builtin_specs.py
index cd458504f..61d2f9f7d 100644
--- a/deeptutor/tools/builtin_specs.py
+++ b/deeptutor/tools/builtin_specs.py
@@ -50,6 +50,7 @@ BUILTIN_TOOL_SPECS: tuple[BuiltinToolSpec, ...] = (
("brainstorm", "BrainstormTool"),
("rag", "RAGTool"),
("kb_files", "KbFilesTool"),
+ ("knowledge_frontier", "KnowledgeFrontierTool"),
("web_search", "WebSearchTool"),
("reason", "ReasonTool"),
("paper_search", "PaperSearchToolWrapper"),
diff --git a/deeptutor/tools/knowledge_frontier.py b/deeptutor/tools/knowledge_frontier.py
new file mode 100644
index 000000000..68f93e288
--- /dev/null
+++ b/deeptutor/tools/knowledge_frontier.py
@@ -0,0 +1,321 @@
+"""AI-assisted frontier discovery for an existing knowledge base.
+
+``rag`` answers questions about material the learner already collected. This
+service closes the next loop in the workflow: use that material to identify the
+topics worth following, then search arXiv for recent work. Discovery is
+read-only — adding a result to a KB remains an explicit user action.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+import json
+import re
+from typing import Any
+
+from deeptutor.tools.paper_search_tool import ArxivSearchTool
+
+DEFAULT_MAX_PAPERS = 5
+MAX_PAPERS_LIMIT = 10
+DEFAULT_YEARS_LIMIT = 3
+MAX_YEARS_LIMIT = 10
+MAX_SEARCH_QUERIES = 3
+_CONTEXT_CHARS = 3500
+
+
+async def discover_frontier(
+ *,
+ kb_name: str,
+ manifest: Any,
+ focus: str = "",
+ max_papers: int = DEFAULT_MAX_PAPERS,
+ years_limit: int | None = DEFAULT_YEARS_LIMIT,
+ **llm_kwargs: Any,
+) -> dict[str, Any]:
+ """Summarise a KB, derive arXiv queries, and collect deduplicated papers.
+
+ The caller performs the KB access check and supplies its manifest. The
+ method is deliberately resilient: if query generation fails, document names
+ and the user's focus still produce useful fallback searches.
+ """
+ requested_papers = _clamped_int(max_papers, DEFAULT_MAX_PAPERS, 1, MAX_PAPERS_LIMIT)
+ requested_years = (
+ None
+ if years_limit is None
+ else _clamped_int(years_limit, DEFAULT_YEARS_LIMIT, 0, MAX_YEARS_LIMIT)
+ )
+ focus_text = _one_line(focus, limit=240)
+ document_names = [
+ str(document.name)
+ for document in getattr(manifest, "documents", ())
+ if str(getattr(document, "name", "")).strip()
+ ]
+
+ rag_result = await _search_kb(kb_name=kb_name, focus=focus_text)
+ kb_summary = str(rag_result.get("answer") or rag_result.get("content") or "").strip()
+ query_result, queries = await _derive_queries(
+ kb_name=kb_name,
+ focus=focus_text,
+ kb_summary=kb_summary,
+ document_names=document_names,
+ **llm_kwargs,
+ )
+
+ papers, query_errors = await _search_papers(
+ queries=queries,
+ max_results=requested_papers,
+ years_limit=requested_years,
+ )
+ deduped = _deduplicate(papers)[:requested_papers]
+ status = "papers_found" if deduped else "papers_not_found"
+ content = _render_report(
+ kb_name=kb_name,
+ focus=focus_text,
+ document_count=getattr(manifest, "total", 0),
+ kb_summary=kb_summary,
+ queries=queries,
+ papers=deduped,
+ query_errors=query_errors,
+ )
+
+ return {
+ "content": content,
+ "metadata": {
+ "kb_name": str(getattr(manifest, "name", "") or kb_name),
+ "kb_documents": getattr(manifest, "total", 0),
+ "focus": focus_text,
+ "status": status,
+ "kb_summary": kb_summary,
+ "queries": queries,
+ "query_errors": query_errors,
+ "papers": deduped,
+ "query_plan": query_result,
+ "years_limit": requested_years,
+ },
+ "kb_sources": _kb_sources(rag_result, kb_name=kb_name, focus=focus_text),
+ }
+
+
+async def _search_kb(*, kb_name: str, focus: str) -> dict[str, Any]:
+ from deeptutor.tools.rag_tool import rag_search
+
+ query_parts = [
+ part
+ for part in (
+ focus,
+ "key concepts, current methods, limitations, open questions, "
+ "and future research directions",
+ )
+ if part
+ ]
+ return await rag_search(query=" ".join(query_parts), kb_name=kb_name)
+
+
+async def _derive_queries(
+ *,
+ kb_name: str,
+ focus: str,
+ kb_summary: str,
+ document_names: list[str],
+ **llm_kwargs: Any,
+) -> tuple[dict[str, Any], list[str]]:
+ """Ask the reasoning model for arXiv queries, with deterministic fallback."""
+ context = [
+ f"Knowledge base: {kb_name}",
+ f"Learner focus: {focus}" if focus else "",
+ f"Documents: {', '.join(document_names[:20])}" if document_names else "",
+ "Summary of the existing material:",
+ kb_summary[:_CONTEXT_CHARS] if kb_summary else "(retrieval returned no summary)",
+ ]
+ prompt = (
+ 'Return only a JSON object shaped as {"queries": [string, string, string]}. '
+ "Each value must be a concise English arXiv keyword query that follows from the "
+ "knowledge base, explores a distinct research direction, and contains no quotes "
+ "or Boolean operators."
+ )
+ from deeptutor.tools.reason import reason
+
+ try:
+ result = await reason(
+ query=prompt,
+ context="\n".join(part for part in context if part),
+ **llm_kwargs,
+ )
+ queries = _parse_queries(str(result.get("answer", "")))
+ if not queries:
+ return {"source": "fallback", "error": "No valid JSON queries"}, _fallback_queries(
+ focus=focus, document_names=document_names
+ )
+ return {"source": "llm", "model": result.get("model", "")}, queries
+ except Exception as exc:
+ return (
+ {"source": "fallback", "error": str(exc)},
+ _fallback_queries(focus=focus, document_names=document_names),
+ )
+
+
+def _parse_queries(answer: str) -> list[str]:
+ match = re.search(r"\[[\s\S]*\]", answer)
+ if not match:
+ return []
+ try:
+ payload = json.loads(match.group(0))
+ except json.JSONDecodeError:
+ return []
+ if isinstance(payload, dict):
+ payload = payload.get("queries")
+ if not isinstance(payload, list):
+ return []
+ return _clean_queries(payload)
+
+
+def _fallback_queries(*, focus: str, document_names: list[str]) -> list[str]:
+ seed = focus
+ if not seed and document_names:
+ first_name = document_names[0].rsplit("/", 1)[-1]
+ first_name = re.sub(r"\.[A-Za-z0-9]{1,5}$", "", first_name)
+ seed = re.sub(r"[-_.]+", " ", first_name)
+ seed = _one_line(seed, limit=120)
+ if not seed:
+ return ["recent research frontiers"]
+ return [
+ seed,
+ f"recent advances {seed}",
+ f"open challenges {seed}",
+ ]
+
+
+def _clean_queries(raw_values: Iterable[Any]) -> list[str]:
+ cleaned: list[str] = []
+ for value in raw_values:
+ if not isinstance(value, str):
+ continue
+ query = _one_line(value, limit=200)
+ if len(query.split()) >= 2 and query.lower() not in {item.lower() for item in cleaned}:
+ cleaned.append(query)
+ if len(cleaned) >= MAX_SEARCH_QUERIES:
+ break
+ return cleaned
+
+
+async def _search_papers(
+ *, queries: list[str], max_results: int, years_limit: int | None
+) -> tuple[list[dict[str, Any]], list[str]]:
+ searcher = ArxivSearchTool()
+ papers: list[dict[str, Any]] = []
+ errors: list[str] = []
+ for query in queries:
+ try:
+ results = await searcher.search_papers(
+ query=query,
+ max_results=max_results,
+ years_limit=years_limit,
+ sort_by="relevance",
+ )
+ except Exception as exc:
+ errors.append(f"{query}: {exc}")
+ continue
+ papers.extend({**paper, "source_query": query} for paper in results)
+ return _deduplicate(papers), errors
+
+
+def _deduplicate(papers: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ seen: set[tuple[str, str]] = set()
+ unique: list[dict[str, Any]] = []
+ for paper in papers:
+ if not isinstance(paper, dict):
+ continue
+ key = (
+ str(paper.get("arxiv_id", "")).strip().lower(),
+ str(paper.get("title", "")).strip().lower(),
+ )
+ if key in seen:
+ continue
+ seen.add(key)
+ unique.append(paper)
+ return unique
+
+
+def _kb_sources(rag_result: dict[str, Any], *, kb_name: str, focus: str) -> list[dict[str, Any]]:
+ retrieved = [item for item in (rag_result.get("sources") or []) if isinstance(item, dict)]
+ if not retrieved:
+ return [
+ {
+ "type": "rag",
+ "query": focus or "knowledge frontier",
+ "kb_name": kb_name,
+ }
+ ]
+ return [{"type": "rag", "kb_name": kb_name, **item} for item in retrieved]
+
+
+def _render_report(
+ *,
+ kb_name: str,
+ focus: str,
+ document_count: int,
+ kb_summary: str,
+ queries: list[str],
+ papers: list[dict[str, Any]],
+ query_errors: list[str],
+) -> str:
+ lines = [
+ f"**Knowledge frontier for `{kb_name}`**",
+ f"Grounded in {document_count} document(s).",
+ ]
+ if focus:
+ lines.append(f"Focus: {focus}")
+ if kb_summary:
+ lines.extend(["", "Existing material summary:", kb_summary[:1600]])
+
+ lines.extend(["", "arXiv queries used:"])
+ lines.extend(f"- {query}" for query in queries)
+ if query_errors:
+ lines.extend(["", "Query errors:"])
+ lines.extend(f"- {error}" for error in query_errors)
+
+ if not papers:
+ lines.extend(
+ [
+ "",
+ "No recent arXiv preprints were found for these queries. "
+ "Try a narrower focus or a longer year range.",
+ ]
+ )
+ return "\n".join(lines)
+
+ lines.extend(["", "Recent work to consider:"])
+ for index, paper in enumerate(papers, start=1):
+ authors = ", ".join(str(author) for author in (paper.get("authors") or [])[:4])
+ abstract = " ".join(str(paper.get("abstract", "")).split())[:320]
+ lines.extend(
+ [
+ "",
+ f"{index}. **{paper.get('title', 'Untitled')}** ({paper.get('year', 'unknown')})",
+ f" Authors: {authors or 'Unknown'}",
+ f" arXiv: {paper.get('arxiv_id', 'unknown')} | URL: {paper.get('url', '')}",
+ f" Matched query: {paper.get('source_query', '')}",
+ ]
+ )
+ if abstract:
+ lines.append(f" Abstract: {abstract}")
+ lines.extend(
+ [
+ "",
+ "These papers are recommendations, not knowledge-base contents. "
+ "Review them before adding any source.",
+ ]
+ )
+ return "\n".join(lines)
+
+
+def _one_line(value: Any, *, limit: int) -> str:
+ return re.sub(r"\s+", " ", str(value or "").strip())[:limit].strip()
+
+
+def _clamped_int(value: Any, default: int, minimum: int, maximum: int) -> int:
+ try:
+ number = int(value)
+ except (TypeError, ValueError):
+ return default
+ return max(minimum, min(number, maximum))
diff --git a/deeptutor/tools/prompting/hints/en/knowledge_frontier.yaml b/deeptutor/tools/prompting/hints/en/knowledge_frontier.yaml
new file mode 100644
index 000000000..5f987af48
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/knowledge_frontier.yaml
@@ -0,0 +1,5 @@
+short_description: "Turn an attached knowledge base into grounded recent arXiv recommendations."
+when_to_use: "The learner asks for frontier papers, research trends, gaps to explore, or what to study next based on an attached knowledge base."
+input_format: "kb_name; optional focus, max_papers, and years_limit"
+guideline: "Use after the knowledge base is attached; call once per knowledge base. Treat results as suggestions for explicit review, not imported material."
+phase: expansion
diff --git a/deeptutor/tools/prompting/hints/zh/knowledge_frontier.yaml b/deeptutor/tools/prompting/hints/zh/knowledge_frontier.yaml
new file mode 100644
index 000000000..06df2cca6
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/knowledge_frontier.yaml
@@ -0,0 +1,5 @@
+short_description: "把已选知识库转化为有依据的近期 arXiv 研究推荐。"
+when_to_use: "学习者希望基于知识库寻找前沿论文、研究趋势、空白方向或下一步学习内容时。"
+input_format: "kb_name;可选 focus、max_papers、years_limit"
+guideline: "知识库已附加后按库调用一次。结果只是待审阅的推荐,不是已导入知识库的资料。"
+phase: expansion
diff --git a/tests/capabilities/test_obsidian_capability.py b/tests/capabilities/test_obsidian_capability.py
index d11edd6e7..e5ae92ba2 100644
--- a/tests/capabilities/test_obsidian_capability.py
+++ b/tests/capabilities/test_obsidian_capability.py
@@ -215,8 +215,8 @@ async def test_read_note_with_date_frontmatter(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 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.
+ # LlamaIndex KBs the capability does not own stay searchable, enumerable,
+ # and frontier-expandable. Other flags (code/memory) stay dropped.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search", "reason"],
@@ -234,6 +234,7 @@ def test_exclusive_compose_drops_builtins_but_keeps_coexisting_rag() -> None:
"obsidian_read",
"rag",
"kb_files",
+ "knowledge_frontier",
"ask_user",
}
diff --git a/tests/capabilities/test_subagent_capability.py b/tests/capabilities/test_subagent_capability.py
index b66d7c9e0..859266fdd 100644
--- a/tests/capabilities/test_subagent_capability.py
+++ b/tests/capabilities/test_subagent_capability.py
@@ -115,7 +115,7 @@ def test_binding_cached(monkeypatch) -> None:
def test_exclusive_compose_drops_builtins_but_keeps_coexisting_rag() -> None:
# 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);
+ # real KB the capability does not own is searchable and enumerable);
# other built-ins/toggles stay dropped.
composed = compose_enabled_tools(
registry=get_tool_registry(),
@@ -133,6 +133,7 @@ def test_exclusive_compose_drops_builtins_but_keeps_coexisting_rag() -> None:
"consult_subagent",
"rag",
"kb_files",
+ "knowledge_frontier",
"ask_user",
}
diff --git a/tests/tools/test_kb_files_tool.py b/tests/tools/test_kb_files_tool.py
index 8bde48016..f3fabfef0 100644
--- a/tests/tools/test_kb_files_tool.py
+++ b/tests/tools/test_kb_files_tool.py
@@ -106,6 +106,7 @@ class TestMountGate:
"obsidian_read",
"rag",
"kb_files",
+ "knowledge_frontier",
"ask_user",
]
diff --git a/tests/tools/test_knowledge_frontier_tool.py b/tests/tools/test_knowledge_frontier_tool.py
new file mode 100644
index 000000000..9194e6616
--- /dev/null
+++ b/tests/tools/test_knowledge_frontier_tool.py
@@ -0,0 +1,175 @@
+"""``knowledge_frontier`` — grounded read-only extension of an existing KB."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from deeptutor.agents._shared.tool_composition import (
+ AUTO_MOUNTED_TOOLS,
+ ToolMountFlags,
+ compose_enabled_tools,
+)
+from deeptutor.tools.builtin import (
+ BUILTIN_TOOL_NAMES,
+ KnowledgeFrontierTool,
+)
+from deeptutor.tools.builtin_specs import BUILTIN_TOOL_SPEC_BY_NAME
+
+_PAPER = {
+ "title": "Grounded Frontier Learning",
+ "authors": ["Ada Lovelace"],
+ "year": 2026,
+ "abstract": "A recent direction.",
+ "url": "https://arxiv.org/abs/2601.0001",
+ "arxiv_id": "2601.0001",
+}
+
+
+class _EmptyRegistry:
+ @staticmethod
+ def get_enabled(_selected: list[str]) -> list[Any]:
+ return []
+
+
+class FakeArxivSearchTool:
+ calls: list[dict[str, Any]] = []
+ results: list[dict[str, Any]] = []
+
+ async def search_papers(self, **kwargs: Any) -> list[dict[str, Any]]:
+ FakeArxivSearchTool.calls.append(kwargs)
+ return list(FakeArxivSearchTool.results)
+
+
+def _stub_runtime(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ accessible: bool = True,
+ reason_answer: str = 'Here are queries: ["knowledge graphs", "causal tutoring"]',
+ reason_error: Exception | None = None,
+ rag_sources: list[dict[str, Any]] | None = None,
+) -> None:
+ FakeArxivSearchTool.calls = []
+ FakeArxivSearchTool.results = [_PAPER]
+
+ manifest = (
+ SimpleNamespace(
+ name="Course",
+ total=2,
+ documents=(
+ SimpleNamespace(name="attention-basics.pdf"),
+ SimpleNamespace(name="curriculum.md"),
+ ),
+ )
+ if accessible
+ else None
+ )
+ monkeypatch.setattr(
+ "deeptutor.multi_user.knowledge_access.resolve_kb_manifest",
+ lambda kb_name, **_kwargs: manifest,
+ raising=False,
+ )
+
+ async def fake_rag_search(query: str, kb_name: str) -> dict[str, Any]:
+ return {
+ "answer": "The KB covers attention basics and curriculum design.",
+ "sources": [] if rag_sources is None else rag_sources,
+ }
+
+ async def fake_reason(**kwargs: Any) -> dict[str, Any]:
+ if reason_error:
+ raise reason_error
+ return {"answer": reason_answer, "model": "test-model"}
+
+ import deeptutor.tools.reason as reason_module
+
+ monkeypatch.setattr("deeptutor.tools.rag_tool.rag_search", fake_rag_search)
+ monkeypatch.setattr(reason_module, "reason", fake_reason)
+ monkeypatch.setattr("deeptutor.tools.knowledge_frontier.ArxivSearchTool", FakeArxivSearchTool)
+
+
+class TestRegistration:
+ def test_tool_is_registered(self) -> None:
+ assert "knowledge_frontier" in BUILTIN_TOOL_NAMES
+ assert (
+ BUILTIN_TOOL_SPEC_BY_NAME["knowledge_frontier"].class_path
+ == "deeptutor.tools.builtin:KnowledgeFrontierTool"
+ )
+
+ def test_mounting_is_kb_owned_not_a_user_toggle(self) -> None:
+ assert "knowledge_frontier" in AUTO_MOUNTED_TOOLS
+ assert "knowledge_frontier" not in compose_enabled_tools(
+ registry=_EmptyRegistry(),
+ requested_tools=[],
+ optional_whitelist=["knowledge_frontier"],
+ mount_flags=ToolMountFlags(has_kb=False),
+ )
+
+ def test_mounts_with_the_same_gate_as_rag(self) -> None:
+ tools = compose_enabled_tools(
+ registry=_EmptyRegistry(),
+ requested_tools=[],
+ optional_whitelist=[],
+ mount_flags=ToolMountFlags(has_kb=True),
+ )
+ assert {"rag", "kb_files", "knowledge_frontier"} <= set(tools)
+
+
+class TestExecute:
+ @pytest.mark.asyncio
+ async def test_returns_grounded_deduplicated_papers(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_runtime(monkeypatch, rag_sources=[{"title": "Attention notes", "content": "..."}])
+
+ result = await KnowledgeFrontierTool().execute(
+ kb_name="Course",
+ focus="curriculum design",
+ max_papers=1,
+ years_limit=2,
+ )
+
+ assert result.success
+ assert "Knowledge frontier for `Course`" in result.content
+ assert "Grounded Frontier Learning" in result.content
+ assert "recommendations, not knowledge-base contents" in result.content
+ assert result.metadata["status"] == "papers_found"
+ assert result.metadata["queries"] == ["knowledge graphs", "causal tutoring"]
+ assert result.sources[0]["type"] == "rag"
+ assert result.sources[-1]["type"] == "paper"
+ assert FakeArxivSearchTool.calls[0]["max_results"] == 1
+ assert FakeArxivSearchTool.calls[0]["years_limit"] == 2
+
+ @pytest.mark.asyncio
+ async def test_inaccessible_kb_is_an_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_runtime(monkeypatch, accessible=False)
+
+ with pytest.raises(ValueError, match="not accessible"):
+ await KnowledgeFrontierTool().execute(kb_name="secret")
+
+ @pytest.mark.asyncio
+ async def test_query_generation_failure_still_searches_from_document_names(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_runtime(monkeypatch, reason_error=RuntimeError("LLM unavailable"))
+ FakeArxivSearchTool.results = []
+
+ result = await KnowledgeFrontierTool().execute(kb_name="Course")
+
+ assert "No recent arXiv preprints" in result.content
+ assert result.metadata["status"] == "papers_not_found"
+ assert result.metadata["query_plan"]["source"] == "fallback"
+ assert result.metadata["queries"][0] == "attention basics"
+
+ @pytest.mark.asyncio
+ async def test_a_partner_can_deny_the_tool(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 "knowledge_frontier" not in tools