Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(langgraph-agent): describe selected primary source (#5274)

LearningCircuita8d7f7127a40
diff --git a/changelog.d/+langgraph-primary-search-metadata.bugfix.md b/changelog.d/+langgraph-primary-search-metadata.bugfix.md
new file mode 100644
index 0000000000..7738b1a068
--- /dev/null
+++ b/changelog.d/+langgraph-primary-search-metadata.bugfix.md
@@ -0,0 +1 @@
+LangGraph's primary search tool now identifies the selected source classification to agents.
diff --git a/docs/decisions/0007-egress-two-axis-data-classification.md b/docs/decisions/0007-egress-two-axis-data-classification.md
index e33e35c0b6..63565dd175 100644
--- a/docs/decisions/0007-egress-two-axis-data-classification.md
+++ b/docs/decisions/0007-egress-two-axis-data-classification.md
@@ -111,7 +111,7 @@ The classification is computed **per component**, and "component" means *every*
model the run touches: each search engine, each collection / store, the LLM, and
the embeddings model. A single function —
`classify(component, settings) -> (Sensitivity, Exposure)` — becomes the one
-home for logic scattered today across `_engine_bucket`, the
+home for logic shared today through `classify_engine`, the
`_CLOUD_LLM_PROVIDERS` set, the per-collection `is_public` lookup, and the URL
fail-up.
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 1de8e27f3d..9c03c52be5 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -23,6 +23,7 @@ from langgraph.errors import GraphRecursionError
from loguru import logger
from ...citation_handler import CitationHandler
+from ...security.egress import EngineClassification, classify_engine
from ...security import sanitize_error_for_client
from ...utilities.thread_context import get_search_context, search_context
from ..tools.fetch import FETCH_MODES, build_fetch_tool
@@ -32,6 +33,12 @@ from .base_strategy import (
CHECK_CONTEXT_ENTRY,
CHECK_CONTEXT_FALLBACK_SYNTHESIS,
)
+from .primary_search_metadata import (
+ NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,
+ PrimarySourceType,
+ classify_primary_source,
+ format_primary_search_description,
+)
# ---------------------------------------------------------------------------
# Constants
@@ -260,12 +267,13 @@ def _make_web_search_tool(
settings_snapshot: dict,
collector: SearchResultsCollector,
programmatic_mode: bool = False,
+ description: str = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,
):
"""Create a ``web_search`` tool that instantiates a fresh engine per call."""
@tool
def web_search(query: str) -> str:
- """Search the web for current information, facts, or news. Returns search result snippets with source indices."""
+ """Search the selected source and return result snippets with source indices."""
from local_deep_research.utilities.resource_utils import safe_close
from local_deep_research.web_search_engines.search_engine_factory import (
create_search_engine,
@@ -296,6 +304,7 @@ def _make_web_search_tool(
finally:
safe_close(engine, "web search engine")
+ web_search.description = description
return web_search
@@ -405,7 +414,15 @@ def _load_specialized_engine_tools(
egress_context=egress_context,
check_agent_enabled=True,
)
- for name, config in eligible.items():
+ except Exception:
+ logger.exception(
+ "Failed to discover specialized search engines",
+ skip_engine=skip_engine,
+ )
+ return tools
+
+ for name, config in eligible.items():
+ try:
if name == skip_engine:
continue
@@ -441,24 +458,32 @@ def _load_specialized_engine_tools(
# (engine-PDP returns engine_unknown for them); plain engines
# route to evaluate_engine.
if egress_context is not None:
- if config.get("is_retriever"):
- try:
- meta = retriever_registry.get_metadata(name)
- except AttributeError:
- meta = None
- decision = evaluate_retriever(
- name, egress_context, metadata=meta
- )
- else:
- # Pass the engine config as metadata so a per-collection
- # is_public classification is honored without a
- # redundant DB lookup per collection.
- decision = evaluate_engine(
- name,
- egress_context,
- settings_snapshot=settings_snapshot,
- metadata=config,
+ try:
+ if config.get("is_retriever"):
+ try:
+ meta = retriever_registry.get_metadata(name)
+ except AttributeError:
+ meta = None
+ decision = evaluate_retriever(
+ name, egress_context, metadata=meta
+ )
+ else:
+ # Pass the engine config as metadata so a per-collection
+ # is_public classification is honored without a
+ # redundant DB lookup per collection.
+ decision = evaluate_engine(
+ name,
+ egress_context,
+ settings_snapshot=settings_snapshot,
+ metadata=config,
+ )
+ except Exception:
+ logger.bind(policy_audit=True).exception(
+ "specialized tool skipped: policy evaluation failed",
+ engine=name,
+ scope=egress_context.scope.value,
)
+ continue
if not decision.allowed:
logger.bind(policy_audit=True).info(
"specialized tool filtered by egress policy",
@@ -482,11 +507,11 @@ def _load_specialized_engine_tools(
programmatic_mode=programmatic_mode,
)
)
- except Exception:
- logger.exception(
- "Failed to load specialized search engines",
- skip_engine=skip_engine,
- )
+ except Exception:
+ logger.exception(
+ "Failed to load specialized search engine",
+ engine=name,
+ )
return tools
@@ -503,6 +528,7 @@ def _make_research_subtopic_tool(
overall_query: str = "",
egress_context=None,
max_subagent_workers: int = MAX_SUBAGENT_WORKERS,
+ web_search_description: str = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,
):
"""Create the ``research_subtopic`` tool that spawns parallel subagents.
@@ -556,6 +582,7 @@ def _make_research_subtopic_tool(
settings_snapshot,
collector,
programmatic_mode=programmatic_mode,
+ description=web_search_description,
)
)
sub_fetch = build_fetch_tool(
@@ -1286,9 +1313,77 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# every tool builder so subagent threads — which don't inherit
# thread-local state — get the same context as the lead agent.
policy_ctx = self._build_egress_context()
+ primary_search_description = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION
# Web search (always present if we have a search engine)
if self.search is not None:
+ try:
+ from ...web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ primary_source_config = search_config(
+ settings_snapshot=self.settings_snapshot
+ ).get(self._search_engine_name)
+ primary_source_type = PrimarySourceType.SEARCH
+ primary_engine_classification: EngineClassification | None = (
+ None
+ )
+ if self._search_engine_name == "library":
+ primary_source_type = PrimarySourceType.LIBRARY
+ if self._search_engine_name.startswith("collection_"):
+ primary_source_type = PrimarySourceType.COLLECTION
+ if (
+ primary_source_config is not None
+ and primary_source_config.get("is_retriever") is True
+ ):
+ from ...web_search_engines.retriever_registry import (
+ retriever_registry,
+ )
+
+ primary_source_type = PrimarySourceType.RETRIEVER
+ retriever_metadata = retriever_registry.get_metadata(
+ self._search_engine_name
+ )
+ retriever_is_local = (
+ retriever_metadata.get("is_local")
+ if retriever_metadata is not None
+ else None
+ )
+ primary_engine_classification = EngineClassification(
+ is_public=(
+ not retriever_is_local
+ if isinstance(retriever_is_local, bool)
+ else None
+ ),
+ is_local=(
+ retriever_is_local
+ if isinstance(retriever_is_local, bool)
+ else None
+ ),
+ )
+ elif policy_ctx is not None:
+ primary_engine_classification = classify_engine(
+ self._search_engine_name,
+ policy_ctx,
+ settings_snapshot=self.settings_snapshot,
+ metadata=primary_source_config,
+ )
+ if primary_engine_classification is not None:
+ primary_source_classification = classify_primary_source(
+ primary_source_type,
+ primary_engine_classification,
+ )
+ primary_search_description = (
+ format_primary_search_description(
+ primary_source_classification
+ )
+ )
+ except Exception:
+ logger.debug(
+ "Could not resolve primary search metadata; using neutral "
+ "tool description"
+ )
tools.append(
_make_web_search_tool(
self._search_engine_name,
@@ -1296,6 +1391,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
self.settings_snapshot,
self.collector,
programmatic_mode=self.programmatic_mode,
+ description=primary_search_description,
)
)
@@ -1355,6 +1451,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
overall_query=overall_query,
egress_context=policy_ctx,
max_subagent_workers=self.max_subagent_workers,
+ web_search_description=primary_search_description,
)
)
@@ -1458,14 +1555,14 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
"given topic and produce a comprehensive, well-cited report.\n"
"Do NOT ask clarifying questions, do NOT ask the user anything, "
"do NOT offer to help further — just research and report.\n"
- "You MUST search the web before answering — never answer from memory alone.\n\n"
+ "You MUST search the selected source before answering — never answer from memory alone.\n\n"
"Strategy:\n"
- "1. Start with web_search for initial exploration.\n"
+ "1. Start with web_search — it queries your selected primary source — for initial exploration.\n"
"2. For complex multi-faceted questions, use research_subtopic to "
f"investigate specific aspects in parallel (pass 2-{MAX_SUBTOPICS} "
f"focused, non-overlapping questions — at most {MAX_SUBTOPICS}).\n"
f"{fetch_line}"
- "4. Use search_[engine] tools for domain-specific searches "
+ "4. When available, use specialized search_[engine] tools for domain-specific searches "
"(search_arxiv for science, search_pubmed for medical, etc.).\n"
"5. When you have enough information, provide a comprehensive answer "
"citing sources as [1], [2], etc.\n"
diff --git a/src/local_deep_research/advanced_search_system/strategies/primary_search_metadata.py b/src/local_deep_research/advanced_search_system/strategies/primary_search_metadata.py
new file mode 100644
index 0000000000..b252961633
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/primary_search_metadata.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import StrEnum, unique
+from typing import Final
+
+from ...security.egress import EngineClassification
+
+
+@unique
+class PrimarySourceType(StrEnum):
+ SEARCH = "configured search source"
+ LIBRARY = "document library"
+ COLLECTION = "selected document collection"
+ RETRIEVER = "registered retriever"
+
+
+@unique
+class PrimarySourceScope(StrEnum):
+ PUBLIC = "public"
+ LOCAL = "local"
+ PUBLIC_AND_LOCAL = "public and local"
+ UNSPECIFIED = "unspecified"
+
+
+@dataclass(frozen=True, slots=True)
+class PrimarySourceClassification:
+ source_type: PrimarySourceType
+ scope: PrimarySourceScope
+
+
+NEUTRAL_PRIMARY_SEARCH_DESCRIPTION: Final = (
+ "Search the primary source selected by the user. "
+ "Source classification: unavailable. "
+ "Returns search result snippets with source indices."
+)
+
+
+def format_primary_search_description(
+ classification: PrimarySourceClassification,
+) -> str:
+ """Format fixed prose from trusted structured classification."""
+ return (
+ "Search the primary source selected by the user. "
+ f"Source type: {classification.source_type.value}. "
+ f"Source scope: {classification.scope.value}. "
+ "Returns search result snippets with source indices."
+ )
+
+
+def classify_primary_source(
+ source_type: PrimarySourceType,
+ engine_classification: EngineClassification,
+) -> PrimarySourceClassification:
+ """Classify one source without retaining its engine key or config text."""
+ if (
+ engine_classification.is_public is True
+ and engine_classification.is_local is True
+ ):
+ scope = PrimarySourceScope.PUBLIC_AND_LOCAL
+ elif engine_classification.is_public is True:
+ scope = PrimarySourceScope.PUBLIC
+ elif engine_classification.is_local is True:
+ scope = PrimarySourceScope.LOCAL
+ else:
+ scope = PrimarySourceScope.UNSPECIFIED
+ return PrimarySourceClassification(source_type=source_type, scope=scope)
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.md
index ea22a57a9d..d7f1de05c1 100644
--- a/src/local_deep_research/security/egress/README.md
+++ b/src/local_deep_research/security/egress/README.md
@@ -75,7 +75,7 @@ Vocabulary borrowed from XACML / zero-trust:
| File | Role |
|---|---|
-| `policy.py` | The PDP. `EgressScope`, `EgressContext`, `Decision`, `PolicyDeniedError`, `context_from_snapshot()` (builds the frozen per-run context + resolves Adaptive), and the `evaluate_*()` decision functions. Also host classification (DNS + private-IP, NAT64 metadata, percent-decode), the run-scoped DNS cache, and the denied-fetch quota. |
+| `policy.py` | The PDP. `EgressScope`, `EgressContext`, `Decision`, `EngineClassification`, `PolicyDeniedError`, `classify_engine()`, `context_from_snapshot()` (builds the frozen per-run context + resolves Adaptive), and the `evaluate_*()` decision functions. Also host classification (DNS + private-IP, NAT64 metadata, percent-decode), the run-scoped DNS cache, and the denied-fetch quota. |
| `audit_hook.py` | A process-wide **PEP-578 `sys.audit` hook** on `socket.connect`. The *secondary* net: catches outbound connections from code paths the explicit PEPs don't cover (third-party libs, new contributors using raw `requests`). Inactive until a worker calls `set_active_context(ctx)`; only gates PRIVATE_ONLY / STRICT. |
| `fetch.py` | `policy_aware_validate_url()` — the egress-scope-aware SSRF wrapper (lets PRIVATE_ONLY reach private lab hosts without disabling SSRF globally; metadata IPs stay blocked). Depends on `../ssrf_validator.py`, not the other way around. |
| `warnings.py` | The three UI banner checks (`check_public_egress_enabled`, `check_cloud_llm_enabled`, `check_cloud_embeddings_enabled`), each with its own dismiss key. Pure functions; the `web/warning_checks` orchestrator calls them. |
@@ -86,7 +86,8 @@ Vocabulary borrowed from XACML / zero-trust:
```python
from local_deep_research.security.egress import (
- EgressScope, EgressContext, Decision, PolicyDeniedError,
+ EgressScope, EgressContext, Decision, EngineClassification, PolicyDeniedError,
+ classify_engine, # classify an engine as public and/or local
context_from_snapshot, # build the per-run context
evaluate_engine, # may engine X run under this scope?
evaluate_retriever, # … for a registered retriever
@@ -276,7 +277,7 @@ Each cell is the decision produced by the real `evaluate_*` logic / PEP for that
| **private_only blocks ALL external data egress** | engine selection (`evaluate_engine` → `scope_mismatch_private_only`), URL/library/webhook fetch (`evaluate_url` PRIVATE_ONLY branch), LLM (`require_local_llm` forced in `context_from_snapshot` → `provider_cloud_only`), embeddings (`require_local_embeddings` forced → `provider_cloud`), and the raw-socket audit-hook net armed for PRIVATE_ONLY (`audit_hook.py`). No vector permits a public destination. |
| **public_only stays open to public sources** | public engines pass `evaluate_engine` (private collections BLOCKED via `scope_mismatch_public_only`); `evaluate_url` allows public hosts, blocks private; inference is NOT scope-forced (toggles still apply); the audit hook stays INACTIVE (only PRIVATE_ONLY/STRICT arm it) so legitimate local infra traffic — local Ollama, settings DB — is never falsely blocked. |
| **adaptive just matches the primary engine** | `_resolve_adaptive_scope`: private primary → PRIVATE_ONLY, public primary → PUBLIC_ONLY, unknown → BOTH. A registered local retriever primary also resolves PRIVATE_ONLY. Uses the engine's **static class flags** (`is_public`/`is_local` on the Python class), not the network location of the engine's server — so a locally-hosted SearXNG (class `is_public=True`) resolves to PUBLIC_ONLY. Resolved once at run start; the stored `EgressContext` carries the concrete scope, not ADAPTIVE. |
-| **A private RAG collection as ADAPTIVE primary pulls the whole run local** | `_resolve_collection_is_public` defaults private → `_engine_bucket` returns local → adaptive resolves PRIVATE_ONLY → forces local LLM + embeddings. Mark the collection `is_public` to opt into cloud inference. |
+| **A private RAG collection as ADAPTIVE primary pulls the whole run local** | `_resolve_collection_is_public` defaults private → `classify_engine` returns local → adaptive resolves PRIVATE_ONLY → forces local LLM + embeddings. Mark the collection `is_public` to opt into cloud inference. |
| **Cloud-metadata is never reachable, under any scope** | `evaluate_url` runs `is_ip_blocked(..., allow_private_ips=True)` before scope logic; `_classify_host` applies the same metadata block on BOTH the literal-IP and DNS-resolved paths; NAT64-wrapped metadata is reclassified PUBLIC. |
| **An engine self-checks scope at run time, even off the factory path** | `BaseSearchEngine._verify_egress_scope()` runs at the top of `run()` (and inside `CollectionSearchEngine.search()` / `LibraryRAGSearchEngine.search()`, which bypass `run()`), re-evaluating `evaluate_engine` against the engine's stored snapshot and **raising `PolicyDeniedError`** on a mismatch. Memoized per snapshot identity + (scope, primary) values so the hot path pays the evaluation once. A defense-in-depth backstop behind the factory PEP for engines built by direct instantiation; it cannot deny anything the factory would have allowed. |
| **Direct MCP searches still arm the socket-level net** | `mcp/server.py::_egress_audit_net()` builds the run's `EgressContext` from the request snapshot and arms the PEP-578 audit hook around `engine.run()`, so a direct MCP search (which never goes through `AdvancedSearchSystem`) still gets the raw-socket backstop under PRIVATE_ONLY/STRICT. Fails open to a no-op when the policy is unevaluable — the factory PEP remains primary. |
diff --git a/src/local_deep_research/security/egress/__init__.py b/src/local_deep_research/security/egress/__init__.py
index 8d053f6314..7caf43dcd1 100644
--- a/src/local_deep_research/security/egress/__init__.py
+++ b/src/local_deep_research/security/egress/__init__.py
@@ -14,11 +14,13 @@ The implementation lives in:
from .policy import (
Decision,
+ EngineClassification,
EgressContext,
EgressScope,
MAX_DENIED_FETCHES_PER_RUN,
PolicyDeniedError,
context_from_snapshot,
+ classify_engine,
evaluate_embeddings,
evaluate_engine,
evaluate_llm_endpoint,
@@ -39,11 +41,13 @@ from .audit_hook import (
__all__ = [
# policy / PDP
"Decision",
+ "EngineClassification",
"EgressContext",
"EgressScope",
"MAX_DENIED_FETCHES_PER_RUN",
"PolicyDeniedError",
"context_from_snapshot",
+ "classify_engine",
"evaluate_embeddings",
"evaluate_engine",
"evaluate_llm_endpoint",
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index 6a7f60c3d8..ae9033100a 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -142,6 +142,14 @@ class Decision:
reason: str
+@dataclass(frozen=True, slots=True)
+class EngineClassification:
+ """Public/local classification for one search engine."""
+
+ is_public: bool | None
+ is_local: bool | None
+
+
class PolicyDeniedError(RuntimeError):
"""Raised by PEPs when a policy decision is hard-stop denial.
@@ -400,15 +408,15 @@ def _resolve_collection_is_public(
return False
-def _engine_bucket(
+def classify_engine(
engine_name: str,
ctx: EgressContext,
+ *,
settings_snapshot: dict,
metadata: Optional[dict] = None,
allow_dns: bool = True,
-):
- """Return the ``(is_public, is_local)`` classification for an engine based
- on its **Python class flags**, with a fail-up URL override.
+) -> EngineClassification:
+ """Classify an engine from its flags, collection metadata, and URL policy.
The class-level ``is_public`` / ``is_local`` flags express the engine's
*nature* — whether it queries the public internet or searches local data —
@@ -426,7 +434,7 @@ def _engine_bucket(
- ``library`` / ``collection_<uuid>``: per-collection ``is_public``
flag (from ``metadata`` when the caller has the engine config, else a
direct DB lookup), defaulting private.
- - Anything else (unknown): ``(None, None)``.
+ - Anything else (unknown): ``EngineClassification(None, None)``.
"""
engine_cls = _get_engine_class(engine_name)
if engine_cls is None:
@@ -447,8 +455,8 @@ def _engine_bucket(
# ``(is_public, is_local=True)`` rather than the old mutually-
# exclusive ``(is_public, not is_public)`` which wrongly hid a
# public collection from private runs.
- return is_public, True
- return None, None
+ return EngineClassification(is_public=is_public, is_local=True)
+ return EngineClassification(is_public=None, is_local=None)
is_public, is_local, url_setting = _engine_flags(engine_cls)
# Fail-up URL override (asymmetric, only ever MORE restrictive): a
# local-data engine (Elasticsearch, Paperless) whose configured URL
@@ -465,8 +473,8 @@ def _engine_bucket(
if host_classification is False:
# False from _classify_engine_url == "connect target is a
# PUBLIC host" -> fail up to public.
- return True, False
- return is_public, is_local
+ return EngineClassification(is_public=True, is_local=False)
+ return EngineClassification(is_public=is_public, is_local=is_local)
# Denial reasons that justify dropping an engine from an LLM candidate
@@ -600,25 +608,37 @@ def evaluate_engine(
# A truly unknown engine (not in the static registry and not a
# collection) fails closed as engine_unknown. ``library`` /
- # ``collection_*`` are classified by _engine_bucket below.
+ # ``collection_*`` are classified by classify_engine below.
is_collection = engine_name == "library" or engine_name.startswith(
"collection_"
)
if _get_engine_class(engine_name) is None and not is_collection:
return Decision(False, "engine_unknown")
- is_public, is_local = _engine_bucket(
- engine_name, ctx, settings_snapshot, metadata
+ classification = classify_engine(
+ engine_name,
+ ctx,
+ settings_snapshot=settings_snapshot,
+ metadata=metadata,
)
# Fail-closed for unclassified engines.
- if is_public is not True and is_local is not True:
+ if (
+ classification.is_public is not True
+ and classification.is_local is not True
+ ):
return Decision(False, "unclassified")
# Scope/bucket compatibility.
- if ctx.scope == EgressScope.PUBLIC_ONLY and is_public is not True:
+ if (
+ ctx.scope == EgressScope.PUBLIC_ONLY
+ and classification.is_public is not True
+ ):
return Decision(False, "scope_mismatch_public_only")
- if ctx.scope == EgressScope.PRIVATE_ONLY and is_local is not True:
+ if (
+ ctx.scope == EgressScope.PRIVATE_ONLY
+ and classification.is_local is not True
+ ):
return Decision(False, "scope_mismatch_private_only")
return Decision(True, "allowed")
@@ -1215,7 +1235,7 @@ def _resolve_adaptive_scope(
) -> EgressScope:
"""Map ADAPTIVE to a concrete scope by classifying the primary engine.
- Uses the engine's **static class flags** (plus ``_engine_bucket``'s
+ Uses the engine's **static class flags** (plus ``classify_engine``'s
fail-up URL override) so that e.g. a locally-hosted SearXNG is still
treated as a public engine, and a remote-hosted Elasticsearch resolves
public rather than pulling the run into PRIVATE_ONLY.
@@ -1226,7 +1246,7 @@ def _resolve_adaptive_scope(
classification hiccup never hard-fails the run).
A registered LangChain retriever (private KB) is not in ENGINE_REGISTRY,
- so ``_engine_bucket`` returns ``(None, None)`` for it; we then consult the
+ so ``classify_engine`` returns no classification for it; we then consult the
retriever registry so a local retriever primary resolves to PRIVATE_ONLY
(forcing local inference) rather than leaking the corpus to cloud models.
"""
@@ -1241,8 +1261,11 @@ def _resolve_adaptive_scope(
local_hostnames=local_hostnames,
username=username,
)
- is_public, is_local = _engine_bucket(
- primary_engine, probe_ctx, settings_snapshot, allow_dns=allow_dns
+ classification = classify_engine(
+ primary_engine,
+ probe_ctx,
+ settings_snapshot=settings_snapshot,
+ allow_dns=allow_dns,
)
except Exception: # noqa: silent-exception - adaptive falls back to BOTH
logger.bind(policy_audit=True).debug(
@@ -1251,14 +1274,14 @@ def _resolve_adaptive_scope(
)
return EgressScope.BOTH
- if is_local is True and is_public is not True:
+ if classification.is_local is True and classification.is_public is not True:
return EgressScope.PRIVATE_ONLY
- if is_public is True and is_local is not True:
+ if classification.is_public is True and classification.is_local is not True:
return EgressScope.PUBLIC_ONLY
- # Unknown to _engine_bucket — it may be a registered retriever (private
+ # Unknown to classify_engine — it may be a registered retriever (private
# KB). Classify via the retriever registry before falling back to BOTH.
- if is_public is None and is_local is None:
+ if classification.is_public is None and classification.is_local is None:
retriever_local = _retriever_is_local(primary_engine, username)
if retriever_local is True:
return EgressScope.PRIVATE_ONLY
@@ -1352,7 +1375,7 @@ def context_from_snapshot(
# engine: a concrete private primary => PRIVATE_ONLY, a concrete public
# primary => PUBLIC_ONLY, an unclassifiable primary => BOTH.
# The resolved scope is what the EgressContext stores and what
- # every downstream PEP enforces. Classification reuses _engine_bucket
+ # every downstream PEP enforces. Classification reuses classify_engine
# via a throwaway BOTH-scoped context (its DNS cache is discarded).
if scope == EgressScope.ADAPTIVE:
scope = _resolve_adaptive_scope(
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index 3dc2f61b15..20c4b5c18b 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -234,7 +234,7 @@ def search_config(
"module_path": ".engines.search_engine_collection",
"class_name": "CollectionSearchEngine",
"requires_llm": True,
- "is_local": not collection_is_public,
+ "is_local": True,
"is_public": collection_is_public,
"agent_enabled": collection_agent_enabled,
"display_name": display_name,
diff --git a/tests/mcp/test_additional_coverage.py b/tests/mcp/test_additional_coverage.py
index b1374176d8..5d1a385e21 100644
--- a/tests/mcp/test_additional_coverage.py
+++ b/tests/mcp/test_additional_coverage.py
@@ -517,6 +517,30 @@ class TestListSearchEnginesOutput:
assert engine["requires_api_key"] is True
assert engine["is_local"] is False
+ def test_public_collection_reports_is_local_true(self):
+ """A public collection's config now carries ``is_local: True``
+ (two-axis semantics: public and local are independent), and the
+ MCP listing must pass that through — a public collection is still
+ local data to API consumers."""
+ from local_deep_research.mcp.server import list_search_engines
+
+ mock_engines = {
+ "collection_abc123": {
+ "description": "Shared docs",
+ "is_public": True,
+ "is_local": True,
+ }
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engines_config.search_config",
+ return_value=mock_engines,
+ ):
+ result = list_search_engines()
+
+ assert result["status"] == "success"
+ assert result["engines"][0]["is_local"] is True
+
def test_engine_info_defaults(self):
"""Test that engine info defaults work for missing fields."""
from local_deep_research.mcp.server import list_search_engines
diff --git a/tests/routes/test_settings_routes.py b/tests/routes/test_settings_routes.py
index c42508f58c..49238d671e 100644
--- a/tests/routes/test_settings_routes.py
+++ b/tests/routes/test_settings_routes.py
@@ -520,6 +520,21 @@ class TestGetEngineIconAndCategory:
assert icon == "📁"
assert category == "Local RAG"
+ def test_public_collection_still_categorized_local_rag(self):
+ """A PUBLIC collection is still local data (two-axis semantics:
+ ``is_public`` and ``is_local`` are independent), so its config —
+ which now always carries ``is_local: True`` — must keep the
+ Local RAG icon/category rather than falling through to generic."""
+ from local_deep_research.web.routes.settings_routes import (
+ _get_engine_icon_and_category,
+ )
+
+ icon, category = _get_engine_icon_and_category(
+ {"is_local": True, "is_public": True}
+ )
+ assert icon == "📁"
+ assert category == "Local RAG"
+
def test_scientific_engine(self):
"""Test icon for scientific engine."""
from local_deep_research.web.routes.settings_routes import (
diff --git a/tests/security/test_egress_collection_semantics_followup.py b/tests/security/test_egress_collection_semantics_followup.py
index f96703f82a..860a3d7949 100644
--- a/tests/security/test_egress_collection_semantics_followup.py
+++ b/tests/security/test_egress_collection_semantics_followup.py
@@ -3,15 +3,15 @@
A collection (``collection_<uuid>`` or the aggregate ``library``) is ALWAYS a
local knowledge base, and its ``is_public`` flag is ADDITIVE — marking a
collection public ALSO makes it eligible under PUBLIC_ONLY/cloud inference, but
-NEVER removes its private (local) eligibility. Concretely, ``_engine_bucket``
-returns ``(is_public, is_local=True)`` for any collection.
+NEVER removes its private (local) eligibility. Concretely, ``classify_engine``
+returns ``EngineClassification(is_public, is_local=True)`` for any collection.
These tests pin that bucket shape directly, the DB-resolution fallback when no
metadata is supplied, and the ADAPTIVE-scope resolution when the PRIMARY engine
is a collection (public -> BOTH, private -> PRIVATE_ONLY forcing local
inference). They complement (do not duplicate) the metadata-driven evaluate_engine
cases already covered in tests/security/test_egress_policy.py by attacking the
-``_engine_bucket`` / ``_resolve_collection_is_public`` / ``_resolve_adaptive_scope``
+``classify_engine`` / ``_resolve_collection_is_public`` / ``_resolve_adaptive_scope``
functions directly and the DB-lookup path.
"""
@@ -19,10 +19,13 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
+from local_deep_research.security.egress import (
+ EngineClassification,
+ classify_engine,
+)
from local_deep_research.security.egress.policy import (
EgressContext,
EgressScope,
- _engine_bucket,
_resolve_adaptive_scope,
_resolve_collection_is_public,
context_from_snapshot,
@@ -57,60 +60,75 @@ _POLICY = "local_deep_research.security.egress.policy"
# ---------------------------------------------------------------------------
-# _engine_bucket — the (is_public, is_local=True) contract
+# classify_engine — the (is_public, is_local=True) contract
# ---------------------------------------------------------------------------
-def test_engine_bucket_public_collection_is_public_AND_local():
+def test_classify_engine_public_collection_is_public_and_local():
"""A public collection buckets as (True, True): the public flag is
ADDITIVE, it never strips the local-KB eligibility."""
ctx = make_ctx(primary="collection_pub")
- bucket = _engine_bucket(
- "collection_pub", ctx, {}, metadata={"is_public": True}
+ classification = classify_engine(
+ "collection_pub",
+ ctx,
+ settings_snapshot={},
+ metadata={"is_public": True},
)
- assert bucket == (True, True)
+ assert classification == EngineClassification(is_public=True, is_local=True)
-def test_engine_bucket_private_collection_is_local_only():
+def test_classify_engine_private_collection_is_local_only():
"""A private collection buckets as (False, True) — local, not public."""
ctx = make_ctx(primary="collection_priv")
- bucket = _engine_bucket(
- "collection_priv", ctx, {}, metadata={"is_public": False}
+ classification = classify_engine(
+ "collection_priv",
+ ctx,
+ settings_snapshot={},
+ metadata={"is_public": False},
+ )
+ assert classification == EngineClassification(
+ is_public=False, is_local=True
)
- assert bucket == (False, True)
-def test_engine_bucket_library_is_local_only_via_db_default():
+def test_classify_engine_library_is_local_only_via_db_default():
"""``library`` is the always-private aggregate; with no metadata it
resolves via the (always-False) collection resolver -> (False, True)."""
ctx = make_ctx(primary="library")
- bucket = _engine_bucket("library", ctx, {})
- assert bucket == (False, True)
+ classification = classify_engine("library", ctx, settings_snapshot={})
+ assert classification == EngineClassification(
+ is_public=False, is_local=True
+ )
-def test_engine_bucket_metadata_short_circuits_db_lookup():
- """When the caller supplies engine metadata, _engine_bucket must NOT
+def test_classify_engine_metadata_short_circuits_db_lookup():
+ """When the caller supplies engine metadata, classify_engine must NOT
fall back to the DB resolver — the metadata flag wins outright."""
ctx = make_ctx(primary="collection_x")
with patch(f"{_POLICY}._resolve_collection_is_public") as mock_resolve:
mock_resolve.return_value = False # would mis-classify if consulted
- bucket = _engine_bucket(
- "collection_x", ctx, {}, metadata={"is_public": True}
+ classification = classify_engine(
+ "collection_x",
+ ctx,
+ settings_snapshot={},
+ metadata={"is_public": True},
)
mock_resolve.assert_not_called()
- assert bucket == (True, True)
+ assert classification == EngineClassification(is_public=True, is_local=True)
-def test_engine_bucket_collection_no_metadata_consults_db_resolver():
- """Without metadata, _engine_bucket delegates classification to
+def test_classify_engine_collection_no_metadata_consults_db_resolver():
+ """Without metadata, classify_engine delegates classification to
_resolve_collection_is_public and threads is_local=True regardless."""
ctx = make_ctx(primary="collection_y", username="alice")
with patch(
f"{_POLICY}._resolve_collection_is_public", return_value=True
) as mock_resolve:
- bucket = _engine_bucket("collection_y", ctx, {})
+ classification = classify_engine(
+ "collection_y", ctx, settings_snapshot={}
+ )
mock_resolve.assert_called_once_with("collection_y", "alice")
- assert bucket == (True, True)
+ assert classification == EngineClassification(is_public=True, is_local=True)
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_egress_langgraph_tool_filter.py b/tests/security/test_egress_langgraph_tool_filter.py
index 8d9f9cd3d4..77ffb9ed14 100644
--- a/tests/security/test_egress_langgraph_tool_filter.py
+++ b/tests/security/test_egress_langgraph_tool_filter.py
@@ -96,6 +96,7 @@ def _build_tool_names(
retriever_meta=None,
snapshot_extra=None,
primary="searxng",
+ registry=None,
):
"""Construct a minimal strategy under ``scope`` and run the REAL
``_build_tools`` loop against the mocked engine discovery ``available``.
@@ -109,6 +110,10 @@ def _build_tool_names(
``primary`` sets ``search.tool`` (a real run always has one). Pass
``primary=None`` to omit it entirely and exercise the fail-closed path.
+
+ ``registry`` replaces the default MagicMock retriever registry entirely
+ (e.g. a ``SimpleNamespace()`` without ``get_metadata`` to exercise the
+ older-registry AttributeError degradation).
"""
snapshot = {
"policy.egress_scope": scope,
@@ -123,8 +128,11 @@ def _build_tool_names(
if snapshot_extra:
snapshot.update(snapshot_extra)
- reg = MagicMock()
- reg.get_metadata.return_value = retriever_meta
+ if registry is not None:
+ reg = registry
+ else:
+ reg = MagicMock()
+ reg.get_metadata.return_value = retriever_meta
with _patched_tool_factories() as spec:
with (
@@ -285,6 +293,53 @@ class TestRetrieverFilter:
assert spec.call_args_list[0].args[0] == self._RET
+class TestPolicyEvaluationFailureIsolation:
+ def test_failed_engine_is_not_constructed_and_later_engine_survives(self):
+ # Given: policy evaluation fails for one engine and allows its successor.
+ # When: the lead tool list is built from the ordered discovery result.
+ with patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ side_effect=[
+ RuntimeError("test policy evaluation failure"),
+ SimpleNamespace(allowed=True, reason="allowed"),
+ ],
+ ):
+ names, spec = _build_tool_names(
+ "public_only", {"broken": {}, "valid": {}}
+ )
+
+ # Then: the failed engine is neither exposed nor constructed; valid remains.
+ assert "broken" not in names
+ assert "valid" in names
+ assert [call.args[0] for call in spec.call_args_list] == ["valid"]
+
+ def test_registry_without_get_metadata_still_consults_pdp(self):
+ # Given: an older/minimal registry object with no ``get_metadata``
+ # attribute at all. The strategy-side lookup raises AttributeError,
+ # which must degrade to ``metadata=None`` — handing the decision to
+ # ``evaluate_retriever`` (whose own registry fallback fails closed) —
+ # NOT fall into the broad per-engine skip as "policy evaluation
+ # failed". Regression guard for the failure-isolation refactor
+ # accidentally swallowing this pre-existing degradation path.
+ with patch(
+ "local_deep_research.security.egress.policy.evaluate_retriever",
+ return_value=SimpleNamespace(allowed=True, reason="allowed"),
+ ) as evaluate_retriever:
+ names, spec = _build_tool_names(
+ "private_only",
+ {"my_kb": {"description": "kb", "is_retriever": True}},
+ registry=SimpleNamespace(),
+ )
+
+ # Then: the PDP was consulted with degraded metadata and its ALLOW
+ # decision was honored — the retriever tool was built, proving the
+ # AttributeError did not silently drop the engine.
+ evaluate_retriever.assert_called_once()
+ assert evaluate_retriever.call_args.kwargs["metadata"] is None
+ assert "my_kb" in names
+ assert spec.call_args_list[0].args[0] == "my_kb"
+
+
# ---------------------------------------------------------------------------
# ADAPTIVE (the DEFAULT scope): the concrete scope FOLLOWS the run's primary
# engine (search.tool) — the same value the factory PEP uses. These cover the
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index f220288939..b4e7518d8b 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -12,10 +12,19 @@ Tests cover:
"""
import threading
-from unittest.mock import MagicMock, patch
+from dataclasses import dataclass
+from types import SimpleNamespace
+from unittest.mock import ANY, MagicMock, patch
import pytest
+from local_deep_research.advanced_search_system.strategies.primary_search_metadata import (
+ PrimarySourceClassification,
+ PrimarySourceScope,
+ PrimarySourceType,
+)
+from local_deep_research.security.egress import EngineClassification
+
# ---------------------------------------------------------------------------
# SearchResultsCollector tests
@@ -390,6 +399,391 @@ class TestLangGraphAgentStrategy:
assert strategy._display_tool_name("fetch_content") == "the page"
+@dataclass(frozen=True, slots=True)
+class _PrimaryClassificationCase:
+ primary_engine: str
+ source_config: dict[str, bool] | None
+ retriever_metadata: dict[str, bool] | None
+ lookup_exception: RuntimeError | None
+ engine_classification: EngineClassification | None
+ expected_classification: PrimarySourceClassification | None
+
+
+class TestPrimaryWebSearchClassification:
+ @pytest.mark.parametrize(
+ "case",
+ [
+ _PrimaryClassificationCase(
+ primary_engine="searxng",
+ source_config=None,
+ retriever_metadata=None,
+ lookup_exception=None,
+ engine_classification=EngineClassification(
+ is_public=True, is_local=False
+ ),
+ expected_classification=PrimarySourceClassification(
+ source_type=PrimarySourceType.SEARCH,
+ scope=PrimarySourceScope.PUBLIC,
+ ),
+ ),
+ _PrimaryClassificationCase(
+ primary_engine="library",
+ source_config=None,
+ retriever_metadata=None,
+ lookup_exception=None,
+ engine_classification=EngineClassification(
+ is_public=False, is_local=True
+ ),
+ expected_classification=PrimarySourceClassification(
+ source_type=PrimarySourceType.LIBRARY,
+ scope=PrimarySourceScope.LOCAL,
+ ),
+ ),
+ _PrimaryClassificationCase(
+ primary_engine="collection_primary",
+ source_config={"is_public": True, "is_local": True},
+ retriever_metadata=None,
+ lookup_exception=None,
+ engine_classification=EngineClassification(
+ is_public=True, is_local=True
+ ),
+ expected_classification=PrimarySourceClassification(
+ source_type=PrimarySourceType.COLLECTION,
+ scope=PrimarySourceScope.PUBLIC_AND_LOCAL,
+ ),
+ ),
+ _PrimaryClassificationCase(
+ primary_engine="retriever_primary",
+ source_config={"is_retriever": True},
+ retriever_metadata={"is_local": True},
+ lookup_exception=None,
+ engine_classification=None,
+ expected_classification=PrimarySourceClassification(
+ source_type=PrimarySourceType.RETRIEVER,
+ scope=PrimarySourceScope.LOCAL,
+ ),
+ ),
+ _PrimaryClassificationCase(
+ primary_engine="retriever_remote",
+ source_config={"is_retriever": True},
+ retriever_metadata={"is_local": False},
+ lookup_exception=None,
+ engine_classification=None,
+ expected_classification=PrimarySourceClassification(
+ source_type=PrimarySourceType.RETRIEVER,
+ scope=PrimarySourceScope.PUBLIC,
+ ),
+ ),
+ _PrimaryClassificationCase(
+ primary_engine="retriever_unclassified",
+ source_config={"is_retriever": True},
+ retriever_metadata=None,
+ lookup_exception=None,
+ engine_classification=None,
+ expected_classification=PrimarySourceClassification(
+ source_type=PrimarySourceType.RETRIEVER,
+ scope=PrimarySourceScope.UNSPECIFIED,
+ ),
+ ),
+ _PrimaryClassificationCase(
+ primary_engine="unknown_primary",
+ source_config=None,
+ retriever_metadata=None,
+ lookup_exception=None,
+ engine_classification=EngineClassification(
+ is_public=None, is_local=None
+ ),
+ expected_classification=PrimarySourceClassification(
+ source_type=PrimarySourceType.SEARCH,
+ scope=PrimarySourceScope.UNSPECIFIED,
+ ),
+ ),
+ _PrimaryClassificationCase(
+ primary_engine="searxng",
+ source_config=None,
+ retriever_metadata=None,
+ lookup_exception=RuntimeError("metadata lookup failed"),
+ engine_classification=None,
+ expected_classification=None,
+ ),
+ ],
+ ids=(
+ "built_in_public",
+ "library_local",
+ "collection_override",
+ "retriever_local",
+ "retriever_remote",
+ "retriever_unclassified",
+ "missing_metadata",
+ "lookup_exception",
+ ),
+ )
+ def test_primary_web_search_routes_classification_to_lead_and_subagents(
+ self, case
+ ):
+ import local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy as mod
+ from local_deep_research.web_search_engines import search_engines_config
+ from local_deep_research.web_search_engines.retriever_registry import (
+ retriever_registry,
+ )
+
+ # Given a live search engine and optional classification metadata.
+ # (The classification under test comes from the mocked
+ # ``classify_engine`` / retriever metadata, never from attributes on
+ # the engine object itself — a bare stand-in keeps that unambiguous.)
+ strategy = mod.LangGraphAgentStrategy(
+ model=MagicMock(),
+ search=SimpleNamespace(),
+ all_links_of_system=[],
+ settings_snapshot={"search.tool": case.primary_engine},
+ )
+ agent = MagicMock()
+ agent.invoke.return_value = {
+ "messages": [MagicMock(content="subagent finding")]
+ }
+ configs = (
+ {case.primary_engine: case.source_config}
+ if case.source_config is not None
+ else {}
+ )
+ search_config_patch = (
+ patch.object(
+ search_engines_config,
+ "search_config",
+ side_effect=case.lookup_exception,
+ )
+ if case.lookup_exception is not None
+ else patch.object(
+ search_engines_config,
+ "search_config",
+ return_value=configs,
+ )
+ )
+
+ # When the lead builds its tools and delegates one subtopic.
+ with (
+ search_config_patch as search_config_mock,
+ patch.object(
+ mod,
+ "format_primary_search_description",
+ return_value="opaque-primary-classification-description",
+ ) as format_metadata,
+ patch.object(
+ mod,
+ "classify_engine",
+ return_value=case.engine_classification,
+ ) as classify_engine,
+ patch.object(
+ search_engines_config,
+ "list_eligible_engine_configs",
+ return_value={},
+ ),
+ patch.object(
+ retriever_registry,
+ "get_metadata",
+ return_value=case.retriever_metadata,
+ ) as get_metadata,
+ patch.object(mod, "build_fetch_tool", return_value=None),
+ patch(
+ "langchain.agents.create_agent", return_value=agent
+ ) as create_agent,
+ ):
+ tools = strategy._build_tools()
+ lead_search = next(
+ tool for tool in tools if tool.name == "web_search"
+ )
+ subtopic_tool = next(
+ tool for tool in tools if tool.name == "research_subtopic"
+ )
+ subtopic_tool.invoke({"subtopics": ["topic"]})
+
+ # Then the schema stays stable and both agents receive the same value.
+ schema = lead_search.args_schema.model_json_schema()
+ assert lead_search.name == "web_search"
+ assert schema["required"] == ["query"]
+ assert set(schema["properties"]) == {"query"}
+
+ subagent_search = create_agent.call_args.kwargs["tools"][0]
+ assert subagent_search.name == "web_search"
+ expected_description = (
+ "opaque-primary-classification-description"
+ if case.expected_classification is not None
+ else mod.NEUTRAL_PRIMARY_SEARCH_DESCRIPTION
+ )
+ assert lead_search.description == expected_description
+ assert subagent_search.description == expected_description
+ search_config_mock.assert_called_once_with(
+ settings_snapshot=strategy.settings_snapshot
+ )
+ if case.expected_classification is not None:
+ format_metadata.assert_called_once_with(
+ case.expected_classification
+ )
+ else:
+ format_metadata.assert_not_called()
+ if (
+ case.source_config is not None
+ and case.source_config.get("is_retriever") is True
+ ):
+ classify_engine.assert_not_called()
+ elif case.lookup_exception is not None:
+ classify_engine.assert_not_called()
+ else:
+ classify_engine.assert_called_once_with(
+ case.primary_engine,
+ ANY,
+ settings_snapshot=strategy.settings_snapshot,
+ metadata=case.source_config,
+ )
+ expected_primary_metadata_calls = (
+ [(case.primary_engine,)]
+ if case.source_config is not None
+ and case.source_config.get("is_retriever") is True
+ else []
+ )
+ assert [
+ metadata_call.args
+ for metadata_call in get_metadata.call_args_list
+ if not metadata_call.kwargs
+ ] == expected_primary_metadata_calls
+
+
+class TestPrimarySearchDescriptionText:
+ """Pin the literal LLM-facing description strings — UNMOCKED.
+
+ The routing test above patches ``format_primary_search_description``
+ out, so on its own it could not catch a regression that reintroduced a
+ raw engine key, collection UUID, or user-supplied config prose into the
+ model-visible string. These tests call the real formatter and assert the
+ exact fixed prose, then drive the real ``_build_tools`` path with an
+ identifier-laden primary and prove none of it leaks.
+ """
+
+ def test_neutral_description_is_fixed_prose(self):
+ from local_deep_research.advanced_search_system.strategies.primary_search_metadata import (
+ NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,
+ )
+
+ assert NEUTRAL_PRIMARY_SEARCH_DESCRIPTION == (
+ "Search the primary source selected by the user. "
+ "Source classification: unavailable. "
+ "Returns search result snippets with source indices."
+ )
+
+ @pytest.mark.parametrize(
+ ("source_type", "scope", "expected"),
+ [
+ (
+ PrimarySourceType.SEARCH,
+ PrimarySourceScope.PUBLIC,
+ "Search the primary source selected by the user. "
+ "Source type: configured search source. "
+ "Source scope: public. "
+ "Returns search result snippets with source indices.",
+ ),
+ (
+ PrimarySourceType.LIBRARY,
+ PrimarySourceScope.LOCAL,
+ "Search the primary source selected by the user. "
+ "Source type: document library. "
+ "Source scope: local. "
+ "Returns search result snippets with source indices.",
+ ),
+ (
+ PrimarySourceType.COLLECTION,
+ PrimarySourceScope.PUBLIC_AND_LOCAL,
+ "Search the primary source selected by the user. "
+ "Source type: selected document collection. "
+ "Source scope: public and local. "
+ "Returns search result snippets with source indices.",
+ ),
+ (
+ PrimarySourceType.RETRIEVER,
+ PrimarySourceScope.UNSPECIFIED,
+ "Search the primary source selected by the user. "
+ "Source type: registered retriever. "
+ "Source scope: unspecified. "
+ "Returns search result snippets with source indices.",
+ ),
+ ],
+ ids=(
+ "search_public",
+ "library_local",
+ "collection_both",
+ "retriever_unspecified",
+ ),
+ )
+ def test_format_produces_exact_fixed_prose(
+ self, source_type, scope, expected
+ ):
+ from local_deep_research.advanced_search_system.strategies.primary_search_metadata import (
+ format_primary_search_description,
+ )
+
+ description = format_primary_search_description(
+ PrimarySourceClassification(source_type=source_type, scope=scope)
+ )
+ assert description == expected
+
+ def test_built_description_leaks_no_engine_identifiers(self):
+ """End-to-end: an identifier-laden collection primary yields ONLY
+ the fixed prose — no engine key, UUID, display name, or config
+ description reaches the model-visible tool description."""
+ import local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy as mod
+ from local_deep_research.web_search_engines import search_engines_config
+
+ engine_key = "collection_8f3a9b2c-4e1d-4a7b-9c6f-1d2e3f4a5b6c"
+ source_config = {
+ "is_public": True,
+ "display_name": "Internal Compliance Corpus",
+ "description": "Scanned internal compliance PDFs",
+ }
+ strategy = mod.LangGraphAgentStrategy(
+ model=MagicMock(),
+ search=SimpleNamespace(),
+ all_links_of_system=[],
+ settings_snapshot={"search.tool": engine_key},
+ )
+ with (
+ patch.object(
+ search_engines_config,
+ "search_config",
+ return_value={engine_key: source_config},
+ ),
+ patch.object(
+ mod,
+ "classify_engine",
+ return_value=EngineClassification(
+ is_public=True, is_local=True
+ ),
+ ),
+ patch.object(
+ search_engines_config,
+ "list_eligible_engine_configs",
+ return_value={},
+ ),
+ patch.object(mod, "build_fetch_tool", return_value=None),
+ ):
+ tools = strategy._build_tools()
+
+ description = next(
+ tool for tool in tools if tool.name == "web_search"
+ ).description
+ assert description == (
+ "Search the primary source selected by the user. "
+ "Source type: selected document collection. "
+ "Source scope: public and local. "
+ "Returns search result snippets with source indices."
+ )
+ for identifier in (
+ engine_key,
+ "8f3a9b2c",
+ "Internal Compliance Corpus",
+ "Scanned internal compliance PDFs",
+ ):
+ assert identifier not in description
+
+
# ---------------------------------------------------------------------------
# Tool-call progress formatting
#
diff --git a/tests/strategies/test_langgraph_subagent_specialized_engines.py b/tests/strategies/test_langgraph_subagent_specialized_engines.py
index 99d36cb531..fddffaaf4c 100644
--- a/tests/strategies/test_langgraph_subagent_specialized_engines.py
+++ b/tests/strategies/test_langgraph_subagent_specialized_engines.py
@@ -20,6 +20,8 @@ subagents ``web_search`` + ``fetch_content``) did not satisfy:
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
+import pytest
+
import local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy as strat # noqa: E501
@@ -101,6 +103,79 @@ def _stop(ctx):
c.stop()
+class TestSpecializedEngineFailureIsolation:
+ @pytest.mark.parametrize(
+ ("broken_config", "factory_fails"),
+ [
+ (None, False),
+ ({"description": "broken", "strengths": []}, True),
+ ],
+ ids=["malformed_config", "tool_construction_failure"],
+ )
+ def test_later_engines_remain_available_when_prior_engine_fails(
+ self, broken_config, factory_fails
+ ):
+ # Given: discovery returns a broken engine before two valid engines.
+ engines = {
+ "broken": broken_config,
+ "valid_first": {"description": "first", "strengths": []},
+ "valid_second": {"description": "second", "strengths": []},
+ }
+
+ def make_specialized_tool(name, *_args, **_kwargs):
+ if factory_fails and name == "broken":
+ raise RuntimeError("test tool construction failure")
+ return SimpleNamespace(name=f"search_{name}")
+
+ # When: the shared specialized-engine helper loads the ordered engines.
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engines_config"
+ ".list_eligible_engine_configs",
+ return_value=engines,
+ ),
+ patch.object(
+ strat, "_make_specialized_search_tool", make_specialized_tool
+ ),
+ ):
+ tools = strat._load_specialized_engine_tools(
+ skip_engine=None,
+ model=MagicMock(),
+ settings_snapshot={},
+ collector=MagicMock(),
+ )
+
+ # Then: the bad engine is omitted and later engines preserve order.
+ assert [tool.name for tool in tools] == [
+ "search_valid_first",
+ "search_valid_second",
+ ]
+
+ def test_discovery_failure_returns_no_tools_without_construction(self):
+ # Given: engine discovery itself fails before yielding any configuration.
+ factory = MagicMock()
+
+ # When: the shared specialized-engine helper attempts discovery.
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engines_config"
+ ".list_eligible_engine_configs",
+ side_effect=RuntimeError("test discovery failure"),
+ ),
+ patch.object(strat, "_make_specialized_search_tool", factory),
+ ):
+ tools = strat._load_specialized_engine_tools(
+ skip_engine=None,
+ model=MagicMock(),
+ settings_snapshot={},
+ collector=MagicMock(),
+ )
+
+ # Then: no partial tools exist and no factory was invoked.
+ assert tools == []
+ factory.assert_not_called()
+
+
class TestSubagentSpecializedEngines:
def test_subagent_receives_specialized_engine_tools(self):
call_log, tool, ctx = _stub_subagent_internals(
diff --git a/tests/web_search_engines/test_search_engines_config.py b/tests/web_search_engines/test_search_engines_config.py
index f3c66911fb..5b002a3f5e 100644
--- a/tests/web_search_engines/test_search_engines_config.py
+++ b/tests/web_search_engines/test_search_engines_config.py
@@ -363,6 +363,45 @@ class TestSearchConfig:
result = search_config()
assert "library" not in result
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_public_collection_config_is_also_local(
+ self, mock_get_setting, mock_registry
+ ):
+ mock_get_setting.side_effect = lambda key, default, **_kwargs: (
+ True if key == "search.engine.library.enabled" else default
+ )
+ mock_registry.list_registered.return_value = []
+ collection = MagicMock(
+ id="public",
+ name="Public Papers",
+ description="",
+ is_public=True,
+ agent_enabled=True,
+ )
+ session = MagicMock()
+ session.query.return_value.all.return_value = [collection]
+ session_context = MagicMock()
+ session_context.__enter__.return_value = session
+ session_context.__exit__.return_value = False
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=session_context,
+ ):
+ result = search_config(settings_snapshot={"_username": "alice"})
+
+ assert result["collection_public"]["is_public"] is True
+ assert result["collection_public"]["is_local"] is True
+
class TestDefaultSearchEngine:
"""Tests for default_search_engine function."""