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.

feat(library): per-collection 'available to the research agent' toggle (#4453)

LearningCircuit28dacaaf19dc
diff --git a/changelog.d/+collection-exclude-from-agent.feature.md b/changelog.d/+collection-exclude-from-agent.feature.md
new file mode 100644
index 0000000000..0bf101ff77
--- /dev/null
+++ b/changelog.d/+collection-exclude-from-agent.feature.md
@@ -0,0 +1 @@
+Collections now have an **"Available to the research agent"** toggle (default on). Turn it off to keep a collection out of the LangGraph research agent's tool list when it isn't needed for agentic research — without deleting it or changing its privacy/egress classification. The flag is exposed on the collection create form and the collection details page, persists via the collections API, and is enforced where the agent builds its specialized search tools (a disabled collection's name never reaches the agent).
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 79d262c389..4d018d6dfc 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
@@ -635,6 +635,19 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
if name in ("auto", "meta") or name == current:
continue
+ # Per-collection usability switch (independent of egress): a
+ # collection the user marked "not for the research agent" is
+ # skipped here so it never appears in the agent's tool list.
+ # Non-collection engines and NULL/missing flags default to
+ # available, so existing behaviour is unchanged.
+ if not config.get("agent_enabled", True):
+ logger.debug(
+ "specialized tool skipped: collection disabled for "
+ "the research agent",
+ engine=name,
+ )
+ continue
+
# Under STRICT, register no specialized engines at all —
# the agent gets only the primary web_search tool.
if (
diff --git a/src/local_deep_research/database/migrations/versions/0012_add_collection_agent_enabled.py b/src/local_deep_research/database/migrations/versions/0012_add_collection_agent_enabled.py
new file mode 100644
index 0000000000..1cc2c36d5f
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0012_add_collection_agent_enabled.py
@@ -0,0 +1,99 @@
+"""Add agent_enabled column to collections
+
+Gives each RAG collection a usability switch: should it be offered to the
+research agent (LangGraph) as a specialized search tool? Defaults to True
+(available) so existing collections keep their current behaviour. Flip it off
+to declutter the agent's tool list when a collection isn't needed for agentic
+research. This is independent of is_public / egress scope — a usability flag,
+NOT a security control.
+
+Revision ID: 0012
+Revises: 0011
+Create Date: 2026-06-07
+
+Column Added:
+=============
+- agent_enabled (BOOLEAN, nullable): Whether the collection is exposed to the
+ LangGraph research agent as a search tool. The column is nullable, but
+ effectively non-null for new rows via server_default=1 (available); any
+ legacy NULL is treated as available at the loader (NULL → True), so
+ pre-existing collections stay available — behaviour-preserving.
+
+Migration Notes:
+===============
+- Uses SQLite batch mode (table recreation) for ALTER TABLE operations.
+- Idempotent: skips the column if it already exists (fresh databases created
+ after the model change will already have it).
+
+Downgrade Behavior:
+==================
+The downgrade() function removes the agent_enabled column. Any per-collection
+agent-availability choice will be LOST on downgrade.
+"""
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy import inspect
+
+# revision identifiers, used by Alembic.
+revision = "0012"
+down_revision = "0011"
+branch_labels = None
+depends_on = None
+
+
+def column_exists(table_name: str, column_name: str) -> bool:
+ """Check if a column exists in a table."""
+ bind = op.get_bind()
+ inspector = inspect(bind)
+
+ if not inspector.has_table(table_name):
+ return False
+
+ columns = {col["name"] for col in inspector.get_columns(table_name)}
+ return column_name in columns
+
+
+def upgrade():
+ """Add agent_enabled column to collections if it doesn't exist."""
+ bind = op.get_bind()
+ inspector = inspect(bind)
+
+ if not inspector.has_table("collections"):
+ # Table doesn't exist yet, will be created by initial migration
+ return
+
+ if column_exists("collections", "agent_enabled"):
+ # Column already exists (fresh database created after model change)
+ return
+
+ # Use batch mode for SQLite compatibility. server_default 1 so existing
+ # collections stay available to the agent (behaviour-preserving) without a
+ # separate backfill UPDATE. nullable=True to match the ORM model column
+ # (Collection.agent_enabled, like its sibling is_public, is nullable) so the
+ # schema-drift autogenerate check stays clean; the loader treats NULL as
+ # available (True) anyway.
+ with op.batch_alter_table("collections") as batch_op:
+ batch_op.add_column(
+ sa.Column(
+ "agent_enabled",
+ sa.Boolean(),
+ nullable=True,
+ server_default=sa.true(),
+ )
+ )
+
+
+def downgrade():
+ """Remove agent_enabled column from collections."""
+ bind = op.get_bind()
+ inspector = inspect(bind)
+
+ if not inspector.has_table("collections"):
+ return
+
+ if not column_exists("collections", "agent_enabled"):
+ return
+
+ with op.batch_alter_table("collections") as batch_op:
+ batch_op.drop_column("agent_enabled")
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index 0f814d6d8e..0b7ae9cd88 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -390,6 +390,14 @@ class Collection(Base):
# never reach a cloud model. Operators flip it per-collection.
is_public = Column(Boolean, default=False)
+ # Whether this collection is offered to the research agent (LangGraph) as a
+ # specialized search tool. Defaults to True (available) so existing
+ # collections keep their current behaviour; flip it off to declutter the
+ # agent's tool list when a collection isn't needed for agentic research.
+ # Independent of is_public / egress scope — this is a usability switch, not
+ # a security control.
+ agent_enabled = Column(Boolean, default=True)
+
# Embedding model used for this collection (stored when first indexed)
embedding_model = Column(
String(100), nullable=True
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 17b9658f34..a5710c3174 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -66,6 +66,20 @@ rag_bp = Blueprint("rag", __name__, url_prefix="/library")
# @login_required guarantees the key exists; direct access fails fast
# if the decorator is ever removed.
+
+def _agent_enabled_default_on(collection) -> bool:
+ """Read a collection's ``agent_enabled`` flag with NULL → available.
+
+ A missing attribute (pre-migration object) or a stored NULL both mean
+ "available to the research agent" (default-on); only an explicit ``False``
+ disables. Used by every serializer so the four read sites can't drift on
+ null-handling. ``is not False`` is safe here because the source is a
+ Boolean column (only ever None/True/False) — NOT raw JSON input, where a
+ falsy ``0`` must still mean disabled (handled separately at the input edge).
+ """
+ return getattr(collection, "agent_enabled", True) is not False
+
+
# Global ThreadPoolExecutor for auto-indexing to prevent thread proliferation
_auto_index_executor: ThreadPoolExecutor | None = None
_auto_index_executor_lock = threading.Lock()
@@ -1238,6 +1252,7 @@ def get_collections():
if hasattr(coll, "is_default")
else False,
"is_public": bool(getattr(coll, "is_public", False)),
+ "agent_enabled": _agent_enabled_default_on(coll),
"document_count": len(coll.document_links)
if hasattr(coll, "document_links")
else 0,
@@ -1282,6 +1297,14 @@ def create_collection():
# Egress classification, default private (the safe choice). A public
# collection counts as a public engine and may use cloud inference.
is_public = bool(data.get("is_public", False))
+ # Usability switch (NOT egress): offer this collection to the research
+ # agent? Default True (available) — behaviour-preserving. An explicit
+ # JSON null normalizes to True so it matches how NULL is read back
+ # everywhere else (NULL → available); only an explicit false disables.
+ agent_enabled_raw = data.get("agent_enabled", True)
+ agent_enabled = (
+ True if agent_enabled_raw is None else bool(agent_enabled_raw)
+ )
if not name:
return jsonify({"success": False, "error": "Name is required"}), 400
@@ -1307,6 +1330,7 @@ def create_collection():
description=description,
collection_type=collection_type,
is_public=is_public,
+ agent_enabled=agent_enabled,
)
db_session.add(collection)
@@ -1322,6 +1346,7 @@ def create_collection():
"created_at": collection.created_at.isoformat(),
"collection_type": collection.collection_type,
"is_public": bool(collection.is_public),
+ "agent_enabled": _agent_enabled_default_on(collection),
},
}
)
@@ -1381,6 +1406,13 @@ def update_collection(collection_id):
if "is_public" in data:
collection.is_public = bool(data.get("is_public"))
+ # Research-agent availability toggle (only when the caller sends it).
+ # Explicit null normalizes to True (available) for parity with how
+ # NULL is read back elsewhere; only an explicit false disables.
+ if "agent_enabled" in data:
+ raw = data.get("agent_enabled")
+ collection.agent_enabled = True if raw is None else bool(raw)
+
db_session.commit()
return jsonify(
@@ -1395,6 +1427,7 @@ def update_collection(collection_id):
else None,
"collection_type": collection.collection_type,
"is_public": bool(collection.is_public),
+ "agent_enabled": _agent_enabled_default_on(collection),
},
}
)
@@ -1910,6 +1943,7 @@ def get_collection_documents(collection_id):
"is_public": bool(
getattr(collection, "is_public", False)
),
+ "agent_enabled": _agent_enabled_default_on(collection),
"embedding_model": collection.embedding_model,
"embedding_model_type": collection.embedding_model_type.value
if collection.embedding_model_type
diff --git a/src/local_deep_research/web/static/js/collection_create.js b/src/local_deep_research/web/static/js/collection_create.js
index 10281f5d10..0d52fdc28e 100644
--- a/src/local_deep_research/web/static/js/collection_create.js
+++ b/src/local_deep_research/web/static/js/collection_create.js
@@ -74,11 +74,14 @@ async function handleCreateCollection(e) {
// Prepare JSON data
const isPublicEl = document.getElementById('collection-is-public');
+ const agentEnabledEl = document.getElementById('collection-agent-enabled');
const jsonData = {
name: name.trim(),
description: description ? description.trim() : '',
type: 'user_uploads',
- is_public: isPublicEl ? isPublicEl.checked : false
+ is_public: isPublicEl ? isPublicEl.checked : false,
+ // Default available to the agent when the control is absent.
+ agent_enabled: agentEnabledEl ? agentEnabledEl.checked : true
};
const response = await safeFetch(URLS.LIBRARY_API.COLLECTION_CREATE, {
diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.js
index 959380e246..d36eae9a37 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -27,6 +27,11 @@ document.addEventListener('DOMContentLoaded', function() {
publicToggle.addEventListener('change', () => updateCollectionIsPublic(publicToggle.checked));
}
+ const agentToggle = document.getElementById('collection-agent-enabled');
+ if (agentToggle) {
+ agentToggle.addEventListener('change', () => updateCollectionAgentEnabled(agentToggle.checked));
+ }
+
// Check if there's an active indexing task
checkAndResumeIndexing();
});
@@ -60,6 +65,36 @@ async function updateCollectionIsPublic(isPublic) {
}
}
+/**
+ * Persist the collection's research-agent availability flag (usability, not
+ * egress): whether the LangGraph agent offers this collection as a tool.
+ */
+async function updateCollectionAgentEnabled(agentEnabled) {
+ const toggle = document.getElementById('collection-agent-enabled');
+ try {
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
+ const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ agent_enabled: agentEnabled })
+ });
+ const data = await response.json();
+ if (data.success) {
+ if (collectionData) collectionData.agent_enabled = !!data.collection.agent_enabled;
+ showSuccess(agentEnabled ? 'Collection available to the research agent.' : 'Collection hidden from the research agent.');
+ } else {
+ if (toggle) toggle.checked = !agentEnabled; // revert on failure
+ showError('Failed to update collection: ' + (data.error || 'unknown error'));
+ }
+ } catch (e) {
+ if (toggle) toggle.checked = !agentEnabled; // revert on failure
+ showError('Failed to update research-agent setting.');
+ }
+}
+
/**
* Load collection details and documents
*/
@@ -82,6 +117,12 @@ async function loadCollectionDetails() {
publicToggle.checked = !!collectionData.is_public;
}
+ // Reflect the research-agent availability flag (default available).
+ const agentToggle = document.getElementById('collection-agent-enabled');
+ if (agentToggle) {
+ agentToggle.checked = collectionData.agent_enabled !== false;
+ }
+
// Update statistics
updateStatistics();
diff --git a/src/local_deep_research/web/templates/pages/collection_create.html b/src/local_deep_research/web/templates/pages/collection_create.html
index 4219f40aee..798db4992b 100644
--- a/src/local_deep_research/web/templates/pages/collection_create.html
+++ b/src/local_deep_research/web/templates/pages/collection_create.html
@@ -56,6 +56,19 @@
</div>
</div>
+ <div class="ldr-form-group">
+ <label class="ldr-collection-public-label">
+ <input type="checkbox" id="collection-agent-enabled" name="agent_enabled" checked>
+ Available to the research agent
+ </label>
+ <div class="ldr-form-help">
+ Checked (default): the LangGraph research agent can search this
+ collection as one of its tools. Uncheck to keep the collection out
+ of the agent's tool list when you don't need it for agentic research.
+ This is a usability switch only — it does not change privacy or egress.
+ </div>
+ </div>
+
<div class="ldr-form-actions">
<button type="button" class="ldr-btn-collections ldr-btn-collections-secondary" onclick="window.location.href='/library/collections'">
<i aria-hidden="true" class="fas fa-times"></i> Cancel
diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.html
index 52a9952a71..6ab7f0cb06 100644
--- a/src/local_deep_research/web/templates/pages/collection_details.html
+++ b/src/local_deep_research/web/templates/pages/collection_details.html
@@ -61,6 +61,18 @@
<a href="https://github.com/LearningCircuit/local-deep-research/blob/main/docs/egress-modes.md#per-collection-publicprivate" target="_blank" rel="noopener noreferrer">Learn more &#8599;</a>
</div>
</div>
+ <div class="ldr-form-group">
+ <label class="ldr-collection-public-label">
+ <input type="checkbox" id="collection-agent-enabled">
+ Available to the research agent
+ </label>
+ <div class="ldr-form-help" id="collection-agent-enabled-help">
+ Checked (default): the LangGraph research agent can search this collection
+ as one of its tools. Uncheck to keep it out of the agent's tool list when
+ it isn't needed for agentic research. Usability switch only — it does not
+ change privacy or egress.
+ </div>
+ </div>
</div>
<!-- Statistics -->
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 fd94a5c54d..9bea0aabc7 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
@@ -231,12 +231,23 @@ def search_config(
collection_is_public = bool(
getattr(collection, "is_public", False)
)
+ # Usability flag (NOT egress): whether the LangGraph
+ # research agent offers this collection as a tool. NULL
+ # (pre-migration rows) reads as available (True). Uses
+ # the same `is not False` idiom as the rag_routes
+ # serializers so all call sites share one NULL→available
+ # default and can't drift.
+ collection_agent_enabled = (
+ getattr(collection, "agent_enabled", True)
+ is not False
+ )
search_engines[engine_id] = {
"module_path": ".engines.search_engine_collection",
"class_name": "CollectionSearchEngine",
"requires_llm": True,
"is_local": not collection_is_public,
"is_public": collection_is_public,
+ "agent_enabled": collection_agent_enabled,
"display_name": display_name,
"default_params": {
"collection_id": collection.id,
diff --git a/tests/research_library/routes/test_rag_routes_gaps_coverage.py b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
index d7bc364eb5..3c6febc337 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
@@ -853,3 +853,123 @@ class TestRagServiceCloseLifecycle:
# And close still ran despite the exception.
mock_rag.close.assert_called_once()
+
+
+# ===========================================================================
+# get_collections — agent_enabled serialization
+# ===========================================================================
+
+
+class TestGetCollectionsAgentEnabled:
+ """GET /api/collections must serialize the agent_enabled flag default-on.
+
+ Guards the get_collections() expression against regression: a stored NULL
+ or a missing attribute must serialize to True (default-on), while an
+ explicit False survives. Drives the real route via the auth client.
+ """
+
+ def _collection(self, **attrs):
+ from types import SimpleNamespace
+
+ base = dict(
+ id="c1",
+ name="C1",
+ description="d",
+ created_at=None,
+ collection_type="user_uploads",
+ is_default=False,
+ is_public=False,
+ document_links=[],
+ linked_folders=[],
+ embedding_model=None,
+ )
+ base.update(attrs)
+ return SimpleNamespace(**base)
+
+ def _list(self, app, collections):
+ db_session = _make_db_session()
+ db_session.query.return_value = _build_mock_query(
+ all_result=collections
+ )
+ with _auth_client(app, mock_db_session=db_session) as (client, _ctx):
+ resp = client.get("/library/api/collections")
+ assert resp.status_code == 200
+ body = resp.get_json()
+ assert body["success"] is True
+ return {c["name"]: c for c in body["collections"]}
+
+ def test_true_false_null_and_missing(self, app):
+ cols = self._list(
+ app,
+ [
+ self._collection(name="on", agent_enabled=True),
+ self._collection(name="off", agent_enabled=False),
+ self._collection(name="null", agent_enabled=None),
+ self._collection(name="missing"), # attribute absent entirely
+ ],
+ )
+ assert cols["on"]["agent_enabled"] is True
+ assert cols["off"]["agent_enabled"] is False
+ # NULL in the DB → default-on (matches get_collection_documents()).
+ assert cols["null"]["agent_enabled"] is True
+ # Pre-migration row with no column → default-on.
+ assert cols["missing"]["agent_enabled"] is True
+
+
+class TestUpdateCollectionAgentEnabled:
+ """PUT /api/collections/<id> serializes agent_enabled consistently with GET.
+
+ Guards the create/update response serializers (which used a bare
+ ``bool(collection.agent_enabled)`` that mis-rendered a legacy NULL row as
+ False) and the explicit-null input normalization (None → available).
+ """
+
+ def _collection(self, **attrs):
+ from types import SimpleNamespace
+
+ base = dict(
+ id="c1",
+ name="C1",
+ description="d",
+ created_at=None,
+ collection_type="user_uploads",
+ is_public=False,
+ agent_enabled=None, # legacy NULL row by default
+ )
+ base.update(attrs)
+ return SimpleNamespace(**base)
+
+ def _update(self, app, collection, body):
+ db_session = _make_db_session()
+ db_session.query.return_value = _build_mock_query(
+ first_result=collection
+ )
+ with _auth_client(app, mock_db_session=db_session) as (client, _ctx):
+ resp = client.put(
+ f"/library/api/collections/{collection.id}", json=body
+ )
+ assert resp.status_code == 200
+ return resp.get_json()["collection"], collection
+
+ def test_legacy_null_row_untouched_serializes_true(self, app):
+ # A pre-migration NULL row updated without agent_enabled in the body
+ # must serialize as available (True) — the same value GET returns.
+ # (Touch description, not name, to avoid the duplicate-name path the
+ # shared mock query would otherwise trip.)
+ coll = self._collection(agent_enabled=None)
+ payload, stored = self._update(app, coll, {"description": "updated"})
+ assert payload["agent_enabled"] is True
+ assert stored.agent_enabled is None # storage left untouched
+
+ def test_explicit_null_normalizes_to_available(self, app):
+ # {"agent_enabled": null} → stored True (available), serialized True.
+ coll = self._collection(agent_enabled=None)
+ payload, stored = self._update(app, coll, {"agent_enabled": None})
+ assert stored.agent_enabled is True
+ assert payload["agent_enabled"] is True
+
+ def test_explicit_false_disables(self, app):
+ coll = self._collection(agent_enabled=True)
+ payload, stored = self._update(app, coll, {"agent_enabled": False})
+ assert stored.agent_enabled is False
+ assert payload["agent_enabled"] is False
diff --git a/tests/security/test_collection_agent_enabled.py b/tests/security/test_collection_agent_enabled.py
new file mode 100644
index 0000000000..ec055b22f9
--- /dev/null
+++ b/tests/security/test_collection_agent_enabled.py
@@ -0,0 +1,120 @@
+"""Per-collection "Available to the research agent" flag (agent_enabled).
+
+A collection a user marked as NOT available to the research agent must be
+excluded from the LangGraph agent's specialized tool list — its name never
+reaches ``create_agent()`` — while agent-enabled collections survive. This is a
+usability switch, independent of egress scope: it filters even a collection
+that egress would otherwise allow.
+
+Drives the REAL ``LangGraphAgentStrategy._build_tools`` loop; only the leaf tool
+factories and engine discovery are mocked, so the assertion is the filter
+decision (which collection names survive into the built tool list).
+"""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+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
+from local_deep_research.security import clear_active_context
+
+
[email protected](autouse=True)
+def _clear_ctx():
+ clear_active_context()
+ yield
+ clear_active_context()
+
+
+@contextmanager
+def _patched_factories():
+ spec = MagicMock(
+ side_effect=lambda name, *a, **k: SimpleNamespace(name=name)
+ )
+ with (
+ patch.object(
+ strat,
+ "_make_web_search_tool",
+ lambda *a, **k: SimpleNamespace(name="web_search"),
+ ),
+ patch.object(strat, "build_fetch_tool", lambda *a, **k: None),
+ patch.object(strat, "_make_specialized_search_tool", spec),
+ ):
+ yield spec
+
+
+def _build(available):
+ # BOTH scope: a collection is allowed by egress regardless of is_public, so
+ # the ONLY differentiator left is the agent_enabled flag.
+ snapshot = {"policy.egress_scope": "both", "search.fetch.mode": "disabled"}
+ reg = MagicMock()
+ reg.get_metadata.return_value = None
+ with _patched_factories() as spec:
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engines_config"
+ ".get_available_engines",
+ return_value=available,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.retriever_registry"
+ ".retriever_registry",
+ reg,
+ ),
+ ):
+ strategy = strat.LangGraphAgentStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ citation_handler=object(),
+ include_sub_research=False,
+ settings_snapshot=snapshot,
+ )
+ tools = strategy._build_tools("overall query")
+ return {t.name for t in tools}, spec
+
+
+def _coll(is_public=True, agent_enabled=True):
+ cfg = {
+ "is_public": is_public,
+ "is_local": not is_public,
+ "is_retriever": False,
+ "description": "a collection",
+ "strengths": [],
+ }
+ if agent_enabled is not None:
+ cfg["agent_enabled"] = agent_enabled
+ return cfg
+
+
+def test_agent_disabled_collection_excluded_from_tools():
+ names, spec = _build(
+ {
+ "collection_enabled": _coll(agent_enabled=True),
+ "collection_disabled": _coll(agent_enabled=False),
+ }
+ )
+ assert "collection_enabled" in names
+ assert "collection_disabled" not in names
+ # The disabled collection's tool factory was never even called (the loop
+ # `continue`s before construction).
+ built = {c.args[0] for c in spec.call_args_list}
+ assert "collection_disabled" not in built
+ assert "collection_enabled" in built
+
+
+def test_missing_flag_defaults_to_available():
+ names, _ = _build({"collection_x": _coll(agent_enabled=None)})
+ assert "collection_x" in names
+
+
+def test_agent_flag_independent_of_egress():
+ # A PUBLIC collection that egress would allow under BOTH is still excluded
+ # when agent_enabled is False — proving the switch is orthogonal to scope.
+ names, _ = _build(
+ {"collection_pub_disabled": _coll(is_public=True, agent_enabled=False)}
+ )
+ assert "collection_pub_disabled" not in names