Skip to content

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

fix(chat): let rag coexist with an exclusive knowledge capability (#650)

Bingxi Zhao (Frank)27a094748616
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py
index ab863dc3c..6b1b2adc7 100644
--- a/deeptutor/agents/_shared/tool_composition.py
+++ b/deeptutor/agents/_shared/tool_composition.py
@@ -125,8 +125,12 @@ def compose_enabled_tools(
``exclusive=True`` flips that for the *knowledge* category (an active
:class:`~deeptutor.capabilities.protocol.KnowledgeCapability`): the turn
- runs only on ``capability_owned`` plus the ``ask_user`` floor — no built-ins,
- no composer toggles, no conditional mounts. The capability owns the surface.
+ runs on ``capability_owned`` plus the ``ask_user`` floor — no other
+ built-ins, no composer toggles. The one exception is ``rag`` when
+ ``mount_flags.has_kb`` is set: it serves co-selected KBs the capability does
+ not own (e.g. LlamaIndex KBs alongside an Obsidian vault), so it coexists
+ with the owned surface instead of being dropped (issue #650). The capability
+ otherwise owns the surface.
``builtin_whitelist`` gates the *built-in* auto-mounts (steps 2 and 4 —
the :data:`AUTO_MOUNTED_TOOLS` members). ``None`` (the product-chat default)
@@ -150,7 +154,17 @@ def compose_enabled_tools(
"""
if exclusive:
owned = [str(name) for name in capability_owned if str(name).strip()]
- return _finalize([*owned, "ask_user"], forced, suppressed)
+ # ``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
+ # 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)
+ else []
+ )
+ return _finalize([*owned, *extra, "ask_user"], forced, suppressed)
def _builtin_allowed(name: str) -> bool:
return builtin_whitelist is None or name in builtin_whitelist
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 953069708..e3a2b046d 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -566,7 +566,10 @@ class AgenticChatPipeline:
mount_flags=ToolMountFlags(
# PageIndex KBs are read via the preloaded MCP tools, not rag —
# a conversation with only PageIndex KBs doesn't mount rag at all.
- has_kb=bool(self._rag_kbs(context)),
+ # Excludes KBs owned by an exclusive capability (an Obsidian vault
+ # is read via its own tools, never rag) so a pure-vault turn still
+ # doesn't mount rag, while co-selected LlamaIndex KBs do (#650).
+ has_kb=bool(self._coexisting_rag_kbs(context)),
# read_source is owned by the explore_context pre-pass (it runs
# the investigation over attached sources), not the answer loop.
# Keep it off the answer surface even when sources are present.
@@ -601,8 +604,9 @@ class AgenticChatPipeline:
def _exclusive_capability_active(context: UnifiedContext) -> bool:
"""True when a knowledge capability owns the turn (replaces the surface).
- Suppresses rag scaffolding (KB seed / kb note) too — rag isn't mounted,
- so seeding or advertising it would be wrong.
+ The capability's own tools replace chat's built-ins. rag scaffolding
+ (mount / KB seed / kb note) is still provided for any co-selected KBs the
+ capability does NOT own — see ``_coexisting_rag_kbs`` (issue #650).
"""
return any_exclusive_capability_active(context)
@@ -672,7 +676,7 @@ class AgenticChatPipeline:
context: UnifiedContext,
) -> list[dict[str, Any]]:
schemas = self.registry.build_openai_schemas(enabled_tools)
- kb_choices = self._rag_kbs(context)
+ kb_choices = self._coexisting_rag_kbs(context)
notebook_choices = self._notebook_choices()
for schema in schemas:
function = schema.get("function") if isinstance(schema, dict) else None
@@ -1043,9 +1047,12 @@ class AgenticChatPipeline:
context: UnifiedContext,
stream: StreamBus,
) -> str:
- if self._exclusive_capability_active(context):
- return ""
- kbs = self._selected_kbs(context)
+ # Seed every selected KB except those owned by an exclusive capability
+ # (an Obsidian vault is read agentically via its own tools, not seeded).
+ # Co-selected LlamaIndex KBs are still seeded so their context reaches
+ # the model even when a vault owns the turn (issue #650).
+ owned = self._capability_owned_kbs(context)
+ kbs = [kb for kb in self._selected_kbs(context) if kb not in owned]
query = (context.user_message or "").strip()
if not kbs or not query:
return ""
@@ -1264,6 +1271,31 @@ class AgenticChatPipeline:
pageindex = getattr(self, "_pageindex_docs", None) or {}
return [kb for kb in self._selected_kbs(context) if kb not in pageindex]
+ def _capability_owned_kbs(self, context: UnifiedContext) -> set[str]:
+ """Selected KBs consumed by an active capability's own tools (not rag).
+
+ An exclusive knowledge capability (Obsidian) reads its vault through its
+ own tools; those KB refs must be excluded from the rag surface. Read via
+ ``getattr`` so plain capabilities without the seam are unaffected.
+ """
+ owned: set[str] = set()
+ for cap in self._active_loop_capabilities(context):
+ hook = getattr(cap, "owned_kbs", None)
+ if callable(hook):
+ owned |= set(hook(context))
+ return owned
+
+ def _coexisting_rag_kbs(self, context: UnifiedContext) -> list[str]:
+ """rag-served KBs that coexist with an exclusive knowledge capability.
+
+ When an Obsidian vault owns the turn, co-selected LlamaIndex KBs would
+ otherwise be silently dropped (issue #650). These stay reachable via
+ rag; vault KBs (which have no rag index) are excluded. Equals
+ ``_rag_kbs`` for a plain chat turn (no capability owns any KB).
+ """
+ owned = self._capability_owned_kbs(context)
+ return [kb for kb in self._rag_kbs(context) if kb not in owned]
+
@staticmethod
def _workspace_key(context: UnifiedContext) -> str:
raw = str(
@@ -1276,12 +1308,14 @@ class AgenticChatPipeline:
return cleaned.strip("_") or "direct"
def _kb_system_note(self, context: UnifiedContext) -> str:
- if self._exclusive_capability_active(context):
- return ""
if not self._selected_kbs(context):
return ""
rag_note = ""
- rag_kbs = self._rag_kbs(context)
+ # Coexisting rag KBs only: when an Obsidian vault owns the turn, its own
+ # system block covers the vault, and this note tells the model the
+ # co-selected LlamaIndex KBs are reachable via rag (issue #650). A
+ # pure-vault turn yields no coexisting KBs, so the note stays empty.
+ rag_kbs = self._coexisting_rag_kbs(context)
if rag_kbs:
joined = ", ".join(rag_kbs)
rag_note = (
diff --git a/deeptutor/capabilities/obsidian/binding.py b/deeptutor/capabilities/obsidian/binding.py
index 741db6db9..e07fcff65 100644
--- a/deeptutor/capabilities/obsidian/binding.py
+++ b/deeptutor/capabilities/obsidian/binding.py
@@ -45,6 +45,26 @@ def _resolve(context: UnifiedContext) -> dict[str, str] | None:
return None
+def obsidian_vault_refs(context: UnifiedContext) -> set[str]:
+ """Return every selected KB ref that resolves to a connected Obsidian vault.
+
+ The capability only *operates* on the first vault (see :func:`vault_for_turn`),
+ but all vault refs are reported here so the chat pipeline can exclude them
+ from the ``rag`` surface — ``rag`` has no index for a live vault (issue #650).
+ """
+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata
+
+ refs: set[str] = set()
+ for ref in context.knowledge_bases or []:
+ ref = str(ref).strip()
+ if not ref:
+ continue
+ meta = resolve_kb_metadata(ref)
+ if meta and meta.get("type") == OBSIDIAN_KB_TYPE and str(meta.get("vault_path") or "").strip():
+ refs.add(ref)
+ return refs
+
+
_UNSET = object()
-__all__ = ["vault_for_turn"]
+__all__ = ["obsidian_vault_refs", "vault_for_turn"]
diff --git a/deeptutor/capabilities/obsidian/capability.py b/deeptutor/capabilities/obsidian/capability.py
index 4b5a04b66..8956ff8d4 100644
--- a/deeptutor/capabilities/obsidian/capability.py
+++ b/deeptutor/capabilities/obsidian/capability.py
@@ -15,7 +15,7 @@ from __future__ import annotations
from importlib import resources
from typing import Any
-from deeptutor.capabilities.obsidian.binding import vault_for_turn
+from deeptutor.capabilities.obsidian.binding import obsidian_vault_refs, vault_for_turn
from deeptutor.capabilities.obsidian.tools import OBSIDIAN_TOOL_NAMES
from deeptutor.capabilities.protocol import KnowledgeCapability, PromptBlock
from deeptutor.core.context import UnifiedContext
@@ -30,6 +30,12 @@ class ObsidianCapability(KnowledgeCapability):
def is_active(self, context: UnifiedContext) -> bool:
return vault_for_turn(context) is not None
+ def owned_kbs(self, context: UnifiedContext) -> set[str]:
+ # The selected vault KB(s) are read/authored through the Obsidian tools,
+ # never through rag — exclude them so co-selected LlamaIndex KBs keep
+ # their rag surface (issue #650).
+ return obsidian_vault_refs(context)
+
def system_block(
self,
context: UnifiedContext,
diff --git a/deeptutor/capabilities/protocol.py b/deeptutor/capabilities/protocol.py
index 991743012..166b19c47 100644
--- a/deeptutor/capabilities/protocol.py
+++ b/deeptutor/capabilities/protocol.py
@@ -101,5 +101,16 @@ class KnowledgeCapability:
exclusive_tools: bool = True
+ def owned_kbs(self, context: UnifiedContext) -> set[str]:
+ """Selected KB refs this capability consumes through its own tools.
+
+ Returned refs are excluded from the ``rag`` surface so that co-selected
+ KBs the capability does NOT own (e.g. plain LlamaIndex KBs alongside an
+ Obsidian vault) stay reachable via ``rag`` instead of being silently
+ dropped when the capability owns the turn (issue #650). Default: none.
+ """
+ _ = context
+ return set()
+
__all__ = ["KnowledgeCapability", "LoopCapability", "PromptBlock"]
diff --git a/deeptutor/capabilities/subagent/binding.py b/deeptutor/capabilities/subagent/binding.py
index cb8207a9d..4ee32e5d7 100644
--- a/deeptutor/capabilities/subagent/binding.py
+++ b/deeptutor/capabilities/subagent/binding.py
@@ -52,4 +52,24 @@ def _resolve(context: UnifiedContext) -> dict[str, str] | None:
return None
-__all__ = ["connection_for_turn"]
+def subagent_refs(context: UnifiedContext) -> set[str]:
+ """Return every selected KB ref that resolves to a connected subagent.
+
+ A subagent "KB" is a delegate consulted via ``consult_subagent``, not a rag
+ index — exclude these refs from the rag surface so a co-selected real KB
+ stays reachable (issue #650) and the agent ref never appears as a rag choice.
+ """
+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata
+
+ refs: set[str] = set()
+ for ref in context.knowledge_bases or []:
+ ref = str(ref).strip()
+ if not ref:
+ continue
+ meta = resolve_kb_metadata(ref)
+ if meta and meta.get("type") == SUBAGENT_KB_TYPE and str(meta.get("agent_kind") or "").strip():
+ refs.add(ref)
+ return refs
+
+
+__all__ = ["connection_for_turn", "subagent_refs"]
diff --git a/deeptutor/capabilities/subagent/capability.py b/deeptutor/capabilities/subagent/capability.py
index 9a49b658f..0ce8f5397 100644
--- a/deeptutor/capabilities/subagent/capability.py
+++ b/deeptutor/capabilities/subagent/capability.py
@@ -17,7 +17,7 @@ from __future__ import annotations
from typing import Any
from deeptutor.capabilities.protocol import KnowledgeCapability, PromptBlock
-from deeptutor.capabilities.subagent.binding import connection_for_turn
+from deeptutor.capabilities.subagent.binding import connection_for_turn, subagent_refs
from deeptutor.capabilities.subagent.tools import SUBAGENT_TOOL_NAMES
from deeptutor.core.context import UnifiedContext
@@ -38,6 +38,11 @@ class SubagentCapability(KnowledgeCapability):
def is_active(self, context: UnifiedContext) -> bool:
return connection_for_turn(context) is not None
+ def owned_kbs(self, context: UnifiedContext) -> set[str]:
+ # The selected subagent ref(s) are consulted via consult_subagent, never
+ # rag — exclude them so co-selected LlamaIndex KBs keep rag (issue #650).
+ return subagent_refs(context)
+
def system_block(
self,
context: UnifiedContext,
diff --git a/tests/agents/chat/test_kb_seed_context.py b/tests/agents/chat/test_kb_seed_context.py
index defec0e27..61085fe01 100644
--- a/tests/agents/chat/test_kb_seed_context.py
+++ b/tests/agents/chat/test_kb_seed_context.py
@@ -210,6 +210,41 @@ async def test_run_seeds_each_attached_kb(monkeypatch: pytest.MonkeyPatch) -> No
assert "## kb-b" in turn_context
+async def test_run_seeds_coexisting_kb_but_not_owned_vault(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Issue #650: an Obsidian vault owning the turn must NOT suppress seeding of
+ # a co-selected LlamaIndex KB. The vault itself is read via its own tools,
+ # so it is excluded from rag seeding.
+ def _fake_meta(ref: str):
+ if ref == "myvault":
+ return {"name": ref, "type": "obsidian", "vault_path": "/tmp/vault"}
+ return {"name": ref, "type": None}
+
+ monkeypatch.setattr(
+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata", _fake_meta
+ )
+ registry = _SeedRegistry()
+ client = _ScriptedChatClient([[_llm_chunk(content="Done.")]])
+ pipeline = _make_pipeline(monkeypatch, registry, client)
+
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="Intended Audience",
+ knowledge_bases=["myvault", "kb-plain"],
+ language="en",
+ metadata={"turn_id": "t1"},
+ )
+ await _run(pipeline, context)
+
+ seeded = {e["kwargs"]["kb_name"] for e in registry.executed if e["name"] == "rag"}
+ assert seeded == {"kb-plain"} # vault excluded, LlamaIndex KB seeded
+ turn_context = client.calls[0]["messages"][-1]["content"]
+ assert "## kb-plain" in turn_context
+ assert "## myvault" not in turn_context
+
+
@pytest.mark.asyncio
async def test_run_skips_seed_without_kb(monkeypatch: pytest.MonkeyPatch) -> None:
registry = _SeedRegistry()
diff --git a/tests/capabilities/test_obsidian_capability.py b/tests/capabilities/test_obsidian_capability.py
index a82394ed8..2364210d7 100644
--- a/tests/capabilities/test_obsidian_capability.py
+++ b/tests/capabilities/test_obsidian_capability.py
@@ -176,7 +176,10 @@ async def test_read_missing_note_is_graceful(tmp_path: Path) -> None:
# ---- exclusivity & registry --------------------------------------------------
-def test_exclusive_compose_drops_everything_but_owned_and_ask_user() -> 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.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search", "reason"],
@@ -185,6 +188,19 @@ def test_exclusive_compose_drops_everything_but_owned_and_ask_user() -> None:
capability_owned=["obsidian_search", "obsidian_read"],
exclusive=True,
)
+ assert set(composed) == {"obsidian_search", "obsidian_read", "rag", "ask_user"}
+
+
+def test_exclusive_compose_pure_vault_mounts_no_rag() -> None:
+ # No coexisting KBs (has_kb=False) → pure vault turn, rag stays off.
+ composed = compose_enabled_tools(
+ registry=get_tool_registry(),
+ requested_tools=["web_search"],
+ optional_whitelist=["web_search"],
+ mount_flags=ToolMountFlags(has_kb=False),
+ capability_owned=["obsidian_search", "obsidian_read"],
+ exclusive=True,
+ )
assert set(composed) == {"obsidian_search", "obsidian_read", "ask_user"}
@@ -194,3 +210,23 @@ def test_registry_flags_obsidian_turn_as_exclusive(monkeypatch, tmp_path: Path)
plain_turn = UnifiedContext(user_message="hi", knowledge_bases=["plain-kb"])
assert any_exclusive_capability_active(obsidian_turn) is True
assert any_exclusive_capability_active(plain_turn) is False
+
+
+def test_owned_kbs_reports_only_vault_refs(monkeypatch, tmp_path: Path) -> None:
+ # Issue #650: the capability owns only the vault; a co-selected LlamaIndex KB
+ # must NOT be reported as owned (so it keeps its rag surface).
+ _bind(monkeypatch, str(tmp_path)) # only "myvault" resolves as obsidian
+ cap = ObsidianCapability()
+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["myvault", "kb-plain"])
+ assert cap.owned_kbs(ctx) == {"myvault"}
+
+
+def test_obsidian_vault_refs_enumerates_every_selected_vault(monkeypatch, tmp_path: Path) -> None:
+ def fake(ref):
+ if ref in {"vaultA", "vaultB"}:
+ return {"name": ref, "type": "obsidian", "vault_path": str(tmp_path)}
+ return {"name": ref, "type": None}
+
+ monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_kb_metadata", fake)
+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["vaultA", "kb1", "vaultB"])
+ assert obsidian_binding.obsidian_vault_refs(ctx) == {"vaultA", "vaultB"}
diff --git a/tests/capabilities/test_subagent_capability.py b/tests/capabilities/test_subagent_capability.py
index cfb5c202e..9d5ecc900 100644
--- a/tests/capabilities/test_subagent_capability.py
+++ b/tests/capabilities/test_subagent_capability.py
@@ -113,7 +113,9 @@ def test_binding_cached(monkeypatch) -> None:
# ---- exclusivity -------------------------------------------------------------
-def test_exclusive_compose_drops_everything_but_consult_and_ask_user() -> 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.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search", "rag"],
@@ -122,6 +124,18 @@ def test_exclusive_compose_drops_everything_but_consult_and_ask_user() -> None:
capability_owned=["consult_subagent"],
exclusive=True,
)
+ assert set(composed) == {"consult_subagent", "rag", "ask_user"}
+
+
+def test_exclusive_compose_pure_subagent_mounts_no_rag() -> None:
+ composed = compose_enabled_tools(
+ registry=get_tool_registry(),
+ requested_tools=["web_search"],
+ optional_whitelist=["web_search"],
+ mount_flags=ToolMountFlags(has_kb=False),
+ capability_owned=["consult_subagent"],
+ exclusive=True,
+ )
assert set(composed) == {"consult_subagent", "ask_user"}
@@ -133,6 +147,16 @@ def test_registry_flags_subagent_turn_as_exclusive(monkeypatch) -> None:
assert any_exclusive_capability_active(plain_turn) is False
+def test_owned_kbs_reports_only_agent_ref(monkeypatch) -> None:
+ # Issue #650: the agent ref is owned (consulted, not rag'd); a co-selected
+ # LlamaIndex KB is not owned, so it keeps its rag surface.
+ _bind(monkeypatch) # only "myagent" resolves as a subagent
+ cap = SubagentCapability()
+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["myagent", "kb-plain"])
+ assert cap.owned_kbs(ctx) == {"myagent"}
+ assert subagent_binding.subagent_refs(ctx) == {"myagent"}
+
+
# ---- consult tool ------------------------------------------------------------