deer-flow/backend/tests/test_memory_tools.py
qin-chenghan ad45f59d66
feat(memory): pluggable memory abstraction with self-contained DeerMem backend (#4122)
* feat(memory): pluggable + self-contained memory system (MemoryManager plan phases 1 & 2)

Phase 1 — Pluggable (steps 0-10):
- ABC MemoryManager (9 methods) + singleton factory + drop-in backend discovery
- DeerMem default backend with core/ (storage/queue/updater/prompt/message_processing)
- NoopMemoryManager backend (proves pluggability)
- All call sites (middleware/hook/prompt/gateway/client/app) routed through manager
- hasattr capability probing for DeerMem-internal methods (no hard imports)
- MemoryConfig gains manager_class field; shared vs DeerMem-private annotated

Phase 2 — Self-contained DeerMem (steps 11-18):
- backend_config passthrough + DeerMemConfig (all DeerMem-private fields moved off MemoryConfig)
- DI: DeerMem owns storage/queue/updater/llm as instance attributes (no global singletons)
- Storage independence: core/paths.py with own root (~/.deermem or ),
  factory auto-injects deer-flow's runtime_home() as absolute base_dir (zero-config)
- LLM independence: core/llm.py via langchain init_chat_model (no create_chat_model)
- Trace independence: optional tracing_callback replaces inject_langfuse_metadata/request_trace_context
- Message processing independence: hide_from_ui default-skip + optional should_keep_hidden_message hook
- Internal imports → relative (only deer_mem.py ABC import is host-relative)
- Carrier (deer_mem.py adapter) / portable (deermem/ config+core) split
- New tests: test_deermem_self_contained + test_memory_manager_pluggable; all memory tests migrated
- Other-agent demo: samples/other_agent_demo/ + automated portability test
- config.example.yaml memory section updated to phase-2 schema

* feat(memory): port consolidation + staleness fix into self-contained DeerMem; phase-2 host hooks

Port upstream #3996 (memory consolidation) and #3993 (staleness KeyError fix)
from origin/MemoryManager into the pluggable, self-contained DeerMem structure
(backends/deermem/deermem/), adapted to the DI MemoryUpdater (config injected,
not get_memory_config globals):

- DeerMemConfig: add consolidation_enabled (opt-in, default false) /
  consolidation_min_facts / consolidation_max_groups_per_cycle /
  consolidation_max_sources
- prompt.py: factsToConsolidate JSON field + {consolidation_section} placeholder
  + CONSOLIDATION_PROMPT constant
- updater.py: _coerce_source_confidence / _select_consolidation_candidates /
  _build_consolidation_section module helpers (matching the existing
  _select_stale_candidates style); consolidation normalization in
  _normalize_memory_update_data; consolidation apply in _apply_updates (after
  max_facts trim, with apply-time guardrails mirroring staleness); staleness
  KeyError fix (f["id"] -> f.get("id") is not None) applied to both the
  staleness guardrail and the consolidation allowed_source_ids comprehension
- config.example.yaml: consolidation section under memory.backend_config
- tests/test_memory_consolidation.py: 40 DI-adapted tests (running, not skipped)
  incl. the staleness KeyError regression

Also includes in-flight phase-2 host-integration work: storage_path semantics
(any absolute/relative value = root dir) and host-default tracing_callback /
should_keep_hidden_message hooks injected into backend_config by the factory.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(memory): add noop backend template and backends guide

- backends/noop/: complete drop-in template (config.py with zero deer-flow
  imports, noop_manager.py with a 6-step new-backend walkthrough in its
  docstring, commented optional fact-CRUD capabilities).
- backends/README.md: which files to touch when adding/swapping a backend,
  the 5-item backend contract, and common pitfalls.
- manager.py: generalize backend examples in comments (drop mem0-specific
  references).

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(frontend): guard formatTimeAgo against invalid timestamps

Return a neutral placeholder when the input date is invalid (e.g. an empty lastUpdated from a backend with no memories) instead of throwing 'Invalid time value' from date-fns.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(memory): wire tool-driven memory mode through the MemoryManager ABC

tools.py (memory_search/add/update/delete) now calls get_memory_manager()
instead of the removed host memory module, so tool mode (memory.mode: tool)
works for any backend. DeerMem.search is implemented (case-insensitive
substring match, ranked by confidence) as a stand-in for the planned
semantic retrieval; noop.search returns [] (unchanged). Fact-CRUD tools
use getattr+callable probing -- backends lacking those ops (noop) get a
clear JSON error instead of crashing.

Tests: test_memory_tools rewired to mock the manager (handler tests) +
TestModeGating retained; test_memory_search now covers DeerMem.search;
pluggable stubs test updated (search no longer a stub).

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: resolve lint errors (import sorting, type annotation quotes, E402 in skipped tests)

* docs: restore explanatory comments in config.example.yaml memory section

* fix(security): port html-escape memory facts fix (#4097) to vendored DeerMem prompt.py

* fix(memory): address review + port dropped upstream memory fixes

Review blockers (vendored DeerMem):
- #4044 restore _escape_memory_for_prompt (current_memory blob in
  MEMORY_UPDATE_PROMPT) - prevents </current_memory> breakout
- #4028 html.escape staleness-section cat/content in _build_staleness_section
- #4119 add _escape_summary for injection-path summaries (Work/Personal/
  Current Focus/Recent/Earlier/Background)
- default-model silent no-op: factory injects host default chat model via a
  new host_llm slot (create_chat_model(name=None)); DeerMem prefers host_llm
  over build_llm(model). Zero-config extraction works out of the box again
- MemoryConfigResponse: fix stale docstring (backend-agnostic shape; DeerMem
  knobs live under backend_config, not top-level - restoring flat would
  re-couple the API to DeerMem). Frontend audited: does not read /memory/config
- _host_default_tracing_callback: restore langfuse assistant_id/environment
- search: push category onto the ABC signature; DeerMem filters BEFORE the
  top_k slice (was filtered client-side after slicing -> starved results)
- _do_update_memory_sync: split into wrapper+impl; bind trace_id into the
  request-trace ContextVar on the Timer/executor worker via a new
  trace_context_manager host hook (None trace_id left unbound - no fabrication)
- client.py fact-CRUD now passes user_id (was writing to the global bucket
  while get_memory reads per-user)
- _resolve_manager_class: fail-fast (raise ValueError) on an unresolved
  explicit manager_class instead of silently falling back to DeerMem (memory is
  persistent state - a wrong store is a silent data-integrity footgun)

Upstream memory fixes dropped by the host->vendored rename conflict, re-ported
to backends/deermem/deermem/core/ (+ deer_mem.py):
- #4073 queue busy-timer-spin -> _reprocess_pending flag (core/queue.py)
- #4074 null source.confidence in staleness -> _coerce_source_confidence
  (core/updater.py: _build_staleness_section + _apply_updates stale sort)
- #4075 factsToRemove is optional (drop from _REQUIRED_MEMORY_UPDATE_TOP_LEVEL_KEYS)
- #4076 null confidence in search ranking -> _coerce_source_confidence
  (deer_mem.py DeerMem.search)

host_llm + trace_context_manager are host-injected via backend_config (factory
in manager.py), keeping backends/deermem/ at exactly one `from deerflow` line
(the ABC contract) - portability test preserved.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: resolve lint errors (F541 f-string without placeholders, E501 line too long)

* fix(memory): restore hide_from_ui clarification preservation, expose mode

Two memory-system fixes (F541/E501 lint was already fixed on this branch):

- filter_messages_for_memory: restore default preservation of well-formed
  human_input_response clarification answers (v2 regression). The
  self-containment refactor made the bare function skip ALL hide_from_ui when
  no hook was passed, but upstream preserves well-formed clarification
  responses by default (test_hide_from_ui_human_input_response_is_preserved).
  Inline a host-agnostic _is_human_clarification_response mirror of
  read_human_input_response as the default keep-decision; the host-injected
  should_keep_hidden_message hook still overrides (production path unchanged).
  Portable package stays zero `from deerflow`.

- /memory/config: expose `mode` (middleware|tool) in MemoryConfigResponse +
  the config/status endpoints + client.get_memory_config. mode is a host-
  shared, behavior-determining field missing from the response projection.
  Sync tests (mock .mode; e2e assert mode present).

- Align manager_class field docstring with fail-fast behavior.

Tests: filter/self-contained/portability (35) + memory-config (4) pass;
ruff clean.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): resolve ruff format failures in memory module + tests

`make lint` runs `ruff format --check` in addition to `ruff check`; 8 memory
files had pending format changes -- 7 pre-existing (deer_mem, updater, tools,
test_memory_queue/router/search/tools) + message_processing from the
hide_from_ui fix. Apply `ruff format`: whitespace/wrapping only, no logic
change. 109 memory tests pass; ruff check + format --check both clean.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): address PR review - legacy field migration, fact_id contract, path/docs

Address willem-bd's review on PR head bc8bf0d4 (risk:high, persistent state):

- config: auto-migrate pre-abstraction top-level memory.* DeerMem fields
  (storage_path, max_facts, debounce_seconds, model_name, token_counting,
  staleness_*, consolidation_*) into backend_config on load + warn, so an
  upgrade does NOT silently revert customized settings (was: silent
  extra='ignore' drop). model_name -> backend_config.model.model. Unknown
  top-level keys warned.
- factory: resolve a relative backend_config.storage_path against runtime_home()
  (base_dir-relative, CWD-independent) to preserve pre-abstraction semantics;
  paths.py stays portable (no runtime_home import).
- tools: memory_add uses the fact_id returned directly by create_fact instead of
  re-deriving it via content-key matching (coupled the tool to the backend's
  content normalization; could misreport a storage cap). create_fact now returns
  (memory_data, fact_id); gateway/client/tool updated. Fix terse
  {"error":"content"} -> {"error":"empty content"}.
- app.py: update stale token_counting=="char" warm-up comment to point at
  manager.warm (DeerMem.warm re-checks char and returns early).
- router: comment explaining reload_memory silent fallback vs fact 501 asymmetry
  (read-only degrade vs write fail-loud).
- CHANGELOG: document breaking changes (/memory/config + client.get_memory_config
  shape flat->backend_config; custom storage_class path moved + __init__ must
  accept config) and the legacy-field auto-migration.
- tests: add regression test pinning the per-user memory path
  ({storage_path}/users/{safe_user_id}/memory.json == host make_safe_user_id)
  across the abstraction; update create_fact mocks for (memory_data, fact_id).

Tests: 273 passed (memory suite); ruff check + format clean.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): address PR review - storage_path, max_facts, tracing, parsing

Six review findings (willem-bd), each verified against upstream:

- storage_path semantics (file -> root dir): migration drops file-style
  (.json) legacy values with a warning; factory raises if storage_path
  resolves to an existing file (avoid silent NotADirectoryError write
  failure). CHANGELOG + config.example.yaml comment updated.
- create_memory_fact enforces max_facts again (via _trim_facts_to_max) and
  returns (memory, None) when the cap evicts the new fact; memory_add tool
  reports "not stored", client raises ValueError, POST /memory/facts -> 409.
- max_facts trim uses _coerce_source_confidence (was raw f.get("confidence",
  0) -> TypeError on non-float imported/legacy confidence, swallowed as
  silent update failure).
- memory-tracing assistant_id restored to "memory_agent" (was "lead-agent"
  copy-paste; matches upstream + DeerMem run_name).
- _is_human_clarification_response cross-checked against
  read_human_input_response (drift guard test).
- empty-string legacy values skipped silently in migration (narrow fix, not
  broad "if not value" which would skip explicit bool False).

8 new regression tests. make lint + 406 memory tests pass.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): address internal review - storage fail-fast, build_llm degrade, config warn, noop template

Addresses 4 findings from the PR #4122 internal supplemental review
(parallel to willem-bd's review, no overlap):

- create_storage fail-fast: a misspelled/unimportable storage_class now
  raises ValueError instead of silently falling back to FileMemoryStorage.
  Memory is persistent state, so a wrong store is a data-integrity footgun;
  mirrors the existing manager_class resolution policy. (storage.py)

- noop template create_fact signature: the commented template used
  keyword-only `content` and returned a bare dict, while DeerMem's actual
  create_fact takes positional `content` and returns tuple[dict, str|None]
  (the memory_add tool passes content positionally; gateway/client/tools all
  tuple-unpack). A backend copied from the template would 500 on fact-CRUD.
  Template fixed; delete_fact/update_fact templates left (callers compatible).
  (noop_manager.py)

- build_llm graceful degrade: wrap init_chat_model in try/except, degrade to
  None + WARNING on failure (mirroring _host_default_llm) so a misconfigured
  explicit model does not crash app startup -- non-LLM memory ops still work
  and an update raises at runtime with the error logged. (llm.py)

- from_backend_config unknown-key warning: log a WARNING for unknown
  backend_config keys (mirrors the host layer's load_memory_config_from_dict)
  so a typo like `storage_pat` does not silently fall back to the default and
  write memory to an unintended location. (config.py)

Tests: rewrote 3 create_storage fallback tests to expect ValueError; added 4
tests (build_llm zero-config/degrade, from_backend_config warn/silent).
make lint green; full memory suite passes.

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: lllyfff <2281215061@qq.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: lllyfff <122260771+lllyfff@users.noreply.github.com>
2026-07-15 11:21:04 +08:00

552 lines
26 KiB
Python

"""Tests for memory tool functions (tool-driven memory mode).
The tools are backend-agnostic: they go through ``get_memory_manager()`` (the
MemoryManager ABC). These tests mock the manager to verify each tool calls the
right ABC method, returns the expected JSON, and handles errors / duplicates /
backends that lack fact-CRUD gracefully. Factory mode-gating (tool vs
middleware) is covered by ``TestModeGating`` at the bottom.
"""
import json
from types import SimpleNamespace
from deerflow.agents.memory.tools import (
get_memory_tools,
memory_add_tool,
memory_delete_tool,
memory_search_tool,
memory_update_tool,
)
class _NamedTool:
def __init__(self, name: str):
self.name = name
class _MockManager:
"""Configurable MemoryManager stand-in for tool-handler tests."""
def __init__(
self,
*,
facts=None,
search_results=None,
created_fact=None,
raise_on_create=None,
raise_on_update=None,
raise_on_delete=None,
raise_on_search=None,
supports_create=True,
supports_update=True,
supports_delete=True,
):
self._facts = facts if facts is not None else []
self._search_results = search_results if search_results is not None else []
self._created_fact = created_fact or {"id": "fact_new", "content": ""}
self._raise_on_create = raise_on_create
self._raise_on_update = raise_on_update
self._raise_on_delete = raise_on_delete
self._raise_on_search = raise_on_search
self._supports_create = supports_create
self._supports_update = supports_update
self._supports_delete = supports_delete
self.calls = []
def search(self, query, top_k=5, *, user_id=None, agent_name=None, category=None):
self.calls.append(("search", query, top_k, user_id, agent_name, category))
if self._raise_on_search:
raise self._raise_on_search
# Mirror the real backend: filter by category BEFORE returning, so the
# tool's category kwarg is honoured server-side (not client-side).
results = list(self._search_results)
if category is not None:
results = [f for f in results if f.get("category") == category]
return results
def get_memory(self, *, user_id=None, agent_name=None):
self.calls.append(("get_memory", user_id, agent_name))
return {"facts": list(self._facts)}
def create_fact(self, content, category="context", confidence=0.5, *, agent_name=None, user_id=None):
self.calls.append(("create_fact", content, category, confidence, agent_name, user_id))
if self._raise_on_create:
raise self._raise_on_create
# Mirrors the real backend: returns (memory_data, fact_id) so the tool uses
# the id directly instead of re-deriving it by content matching.
created = dict(self._created_fact)
created["content"] = content
created["category"] = category
created["confidence"] = confidence
return {"facts": [created] + list(self._facts)}, created.get("id")
def update_fact(self, fact_id, content=None, category=None, confidence=None, *, agent_name=None, user_id=None):
self.calls.append(("update_fact", fact_id, content, category, confidence, agent_name, user_id))
if self._raise_on_update:
raise self._raise_on_update
return {"facts": []}
def delete_fact(self, fact_id, *, agent_name=None, user_id=None):
self.calls.append(("delete_fact", fact_id, agent_name, user_id))
if self._raise_on_delete:
raise self._raise_on_delete
return {"facts": []}
# Tool uses getattr+callable to probe these; shadow with None to simulate a
# backend that does not expose fact CRUD (e.g. noop) -- getattr() returns
# None and the tool's callable() check fails gracefully.
def _drop_fact_ops(self):
if not self._supports_create:
self.create_fact = None
if not self._supports_update:
self.update_fact = None
if not self._supports_delete:
self.delete_fact = None
def _install_manager(monkeypatch, manager):
manager._drop_fact_ops()
monkeypatch.setattr("deerflow.agents.memory.tools.get_memory_manager", lambda: manager)
monkeypatch.setattr("deerflow.agents.memory.tools.resolve_runtime_user_id", lambda runtime: "test-user")
return manager
class TestGetMemoryTools:
"""Tests for get_memory_tools registry."""
def test_returns_four_tools(self):
"""Should return exactly 4 tools."""
tools = get_memory_tools()
assert len(tools) == 4
def test_tools_have_unique_names(self):
"""All tools should have unique names."""
tools = get_memory_tools()
names = [t.name for t in tools]
assert len(names) == len(set(names))
assert "memory_search" in names
assert "memory_add" in names
assert "memory_update" in names
assert "memory_delete" in names
class TestMemorySearchTool:
"""Tests for memory_search tool handler."""
def test_returns_json_with_results(self, monkeypatch):
"""Should return JSON with results and count."""
results = [
{"id": "fact_abc123", "content": "User likes Python", "category": "preference", "confidence": 0.9, "createdAt": "2026-01-01T00:00:00Z"},
]
mgr = _install_manager(monkeypatch, _MockManager(search_results=results))
result_json = memory_search_tool.func(SimpleNamespace(context={}), "Python")
result = json.loads(result_json)
assert result["count"] == 1
assert result["results"][0]["id"] == "fact_abc123"
# search forwards query + limit + scope to the manager.
assert mgr.calls[0][0] == "search"
assert mgr.calls[0][1] == "Python"
assert mgr.calls[0][2] == 10 # limit -> top_k
def test_empty_results(self, monkeypatch):
"""Should return empty results for no matches."""
_install_manager(monkeypatch, _MockManager(search_results=[]))
result_json = memory_search_tool.func(SimpleNamespace(context={}), "nothing")
result = json.loads(result_json)
assert result["count"] == 0
assert result["results"] == []
def test_category_filter_forwarded_to_backend(self, monkeypatch):
"""Category kwarg is forwarded to the backend, which filters before slicing."""
results = [
{"id": "f1", "content": "likes uv", "category": "preference", "confidence": 0.9},
{"id": "f2", "content": "uses uv", "category": "context", "confidence": 0.5},
]
mgr = _install_manager(monkeypatch, _MockManager(search_results=results))
result_json = memory_search_tool.func(SimpleNamespace(context={}), "uv", category="preference", limit=10)
result = json.loads(result_json)
assert result["count"] == 1
assert result["results"][0]["id"] == "f1"
# category is forwarded to the backend search call (not filtered client-side)
assert mgr.calls[0][0] == "search"
assert mgr.calls[0][5] == "preference" # category kwarg
def test_runtime_error_returns_error_json(self, monkeypatch):
"""Should return error JSON when search raises."""
_install_manager(monkeypatch, _MockManager(raise_on_search=RuntimeError("boom")))
result_json = memory_search_tool.func(SimpleNamespace(context={}), "anything")
result = json.loads(result_json)
assert result["error"] == "boom"
class TestMemoryAddTool:
"""Tests for memory_add tool handler."""
def test_adds_fact_and_returns_json(self, monkeypatch):
"""Should add a fact and return fact_id + status."""
mgr = _install_manager(monkeypatch, _MockManager(facts=[], created_fact={"id": "fact_new123"}))
result_json = memory_add_tool.func(SimpleNamespace(context={}), "User prefers dark mode", category="preference", confidence=0.9)
result = json.loads(result_json)
assert result["status"] == "added"
assert result["fact_id"] == "fact_new123"
# dup-checked via get_memory, then created via create_fact.
assert ("get_memory", "test-user", None) in mgr.calls
assert any(c[0] == "create_fact" and c[1] == "User prefers dark mode" for c in mgr.calls)
def test_add_returns_fact_id_when_storage_reorders_facts(self, monkeypatch):
"""fact_id comes directly from create_fact, not derived from the returned list."""
created = {"id": "fact_new123", "content": "User prefers dark mode"}
older = {"id": "fact_old999", "content": "Older fact"}
# Storage may reorder facts; create_fact returns the id directly so the
# tool doesn't depend on list position or content matching.
mgr = _MockManager(facts=[], created_fact=created)
mgr.create_fact = lambda content, category="context", confidence=0.5, *, agent_name=None, user_id=None: ({"facts": [created, older]}, "fact_new123")
_install_manager(monkeypatch, mgr)
result_json = memory_add_tool.func(SimpleNamespace(context={}), "User prefers dark mode")
result = json.loads(result_json)
assert result["fact_id"] == "fact_new123"
def test_add_reports_not_stored_when_cap_evicts_new_fact(self, monkeypatch):
"""When the cap evicts the new fact (create_fact returns None id), report
'not stored' instead of a dangling id + false 'added'."""
mgr = _MockManager(facts=[])
recorded = []
def fake_create(content, category="context", confidence=0.5, *, agent_name=None, user_id=None):
recorded.append(content)
return {"facts": []}, None
mgr.create_fact = fake_create
_install_manager(monkeypatch, mgr)
result_json = memory_add_tool.func(SimpleNamespace(context={}), "low confidence fact", confidence=0.1)
result = json.loads(result_json)
assert result == {"error": "Fact was not stored because memory.max_facts kept higher-confidence facts"}
assert recorded == ["low confidence fact"]
def test_uses_runtime_scope(self, monkeypatch):
"""Should pass agent_name + user_id from runtime to the manager."""
captured = {}
mgr = _MockManager(facts=[], created_fact={"id": "fact_new", "content": "x"})
orig_create = mgr.create_fact
def spy(content, category="context", confidence=0.5, *, agent_name=None, user_id=None):
captured["agent_name"] = agent_name
captured["user_id"] = user_id
return orig_create(content, category=category, confidence=confidence, agent_name=agent_name, user_id=user_id)
mgr.create_fact = spy
_install_manager(monkeypatch, mgr)
runtime = SimpleNamespace(context={"agent_name": "code-agent"})
# resolve_runtime_user_id is monkeypatched to "test-user" by _install_manager;
# override here to assert the runtime channel flows through.
import deerflow.agents.memory.tools as tools_mod
tools_mod.resolve_runtime_user_id = lambda r: "runtime-user"
result_json = memory_add_tool.func(runtime, "User prefers dark mode")
result = json.loads(result_json)
assert result["status"] == "added"
assert captured == {"agent_name": "code-agent", "user_id": "runtime-user"}
def test_rejects_existing_duplicate_content(self, monkeypatch):
"""Should not create a fact whose normalized content already exists."""
existing = [{"id": "fact_existing", "content": "User prefers dark mode"}]
mgr = _install_manager(monkeypatch, _MockManager(facts=existing))
result_json = memory_add_tool.func(SimpleNamespace(context={}), " User prefers dark mode ")
result = json.loads(result_json)
assert result == {"error": "Duplicate fact"}
assert not any(c[0] == "create_fact" for c in mgr.calls)
def test_rejects_duplicate_content_outside_top_k(self, monkeypatch):
"""Dup check reads the full memory (get_memory), not a capped search."""
facts = [{"id": f"fact_{i}", "content": f"variant {i}", "category": "preference", "confidence": 0.9} for i in range(12)]
facts.append({"id": "fact_exact", "content": "User prefers dark mode", "category": "preference", "confidence": 0.1})
mgr = _install_manager(monkeypatch, _MockManager(facts=facts))
result_json = memory_add_tool.func(SimpleNamespace(context={}), " User prefers dark mode ")
result = json.loads(result_json)
assert result == {"error": "Duplicate fact"}
assert not any(c[0] == "create_fact" for c in mgr.calls)
def test_empty_content_returns_error(self, monkeypatch):
"""Should return error JSON for empty content without touching the manager."""
mgr = _install_manager(monkeypatch, _MockManager())
result_json = memory_add_tool.func(SimpleNamespace(context={}), " ")
result = json.loads(result_json)
assert "error" in result
assert not any(c[0] == "create_fact" for c in mgr.calls)
def test_backend_without_create_fact_returns_error(self, monkeypatch):
"""A backend lacking create_fact (e.g. noop) gets a clear JSON error."""
_install_manager(monkeypatch, _MockManager(facts=[], supports_create=False))
result_json = memory_add_tool.func(SimpleNamespace(context={}), "something")
result = json.loads(result_json)
assert "error" in result
assert "create_fact" in result["error"]
class TestMemoryUpdateTool:
"""Tests for memory_update tool handler."""
def test_updates_fact_and_returns_json(self, monkeypatch):
"""Should update a fact and return JSON."""
mgr = _install_manager(monkeypatch, _MockManager())
result_json = memory_update_tool.func(SimpleNamespace(context={}), "fact_abc", content="updated content")
result = json.loads(result_json)
assert result["status"] == "updated"
assert result["fact_id"] == "fact_abc"
assert any(c[0] == "update_fact" and c[1] == "fact_abc" for c in mgr.calls)
def test_invalid_fact_id_returns_error(self, monkeypatch):
"""Should return error JSON for invalid fact_id (KeyError)."""
_install_manager(monkeypatch, _MockManager(raise_on_update=KeyError("fact_xxx")))
result_json = memory_update_tool.func(SimpleNamespace(context={}), "fact_xxx", content="nope")
result = json.loads(result_json)
assert "error" in result
assert "fact_xxx" in result["error"]
def test_backend_without_update_fact_returns_error(self, monkeypatch):
"""A backend lacking update_fact gets a clear JSON error."""
_install_manager(monkeypatch, _MockManager(supports_update=False))
result_json = memory_update_tool.func(SimpleNamespace(context={}), "fact_abc", content="x")
result = json.loads(result_json)
assert "error" in result
assert "update_fact" in result["error"]
class TestMemoryDeleteTool:
"""Tests for memory_delete tool handler."""
def test_deletes_fact_and_returns_json(self, monkeypatch):
"""Should delete a fact and return JSON."""
mgr = _install_manager(monkeypatch, _MockManager())
result_json = memory_delete_tool.func(SimpleNamespace(context={}), "fact_abc")
result = json.loads(result_json)
assert result["status"] == "deleted"
assert result["fact_id"] == "fact_abc"
assert any(c[0] == "delete_fact" and c[1] == "fact_abc" for c in mgr.calls)
def test_invalid_fact_id_returns_error(self, monkeypatch):
"""Should return error JSON for invalid fact_id (KeyError)."""
_install_manager(monkeypatch, _MockManager(raise_on_delete=KeyError("fact_xxx")))
result_json = memory_delete_tool.func(SimpleNamespace(context={}), "fact_xxx")
result = json.loads(result_json)
assert "error" in result
assert "fact_xxx" in result["error"]
def test_backend_without_delete_fact_returns_error(self, monkeypatch):
"""A backend lacking delete_fact gets a clear JSON error."""
_install_manager(monkeypatch, _MockManager(supports_delete=False))
result_json = memory_delete_tool.func(SimpleNamespace(context={}), "fact_abc")
result = json.loads(result_json)
assert "error" in result
assert "delete_fact" in result["error"]
class TestModeGating:
"""Integration tests for memory.mode exclusivity."""
def test_tool_mode_registers_tools_not_middleware(self, monkeypatch):
"""When mode=tool, get_memory_tools are added to extra_tools and
MemoryMiddleware is NOT in the chain."""
from deerflow.agents.factory import _assemble_from_features
from deerflow.agents.features import RuntimeFeatures
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
from deerflow.config.memory_config import MemoryConfig
tool_config = MemoryConfig(enabled=True, mode="tool")
monkeypatch.setattr(
"deerflow.config.memory_config.get_memory_config",
lambda: tool_config,
)
feat = RuntimeFeatures(memory=True)
chain, extra_tools = _assemble_from_features(feat, name="test-agent")
middleware_types = [type(m) for m in chain]
assert MemoryMiddleware not in middleware_types, "MemoryMiddleware should not be in the chain in tool mode"
tool_names = [t.name for t in extra_tools]
assert "memory_search" in tool_names
assert "memory_add" in tool_names
assert "memory_update" in tool_names
assert "memory_delete" in tool_names
def test_explicit_memory_config_drives_factory_mode(self, monkeypatch):
"""Factory mode gating should use the explicit config before ambient globals."""
from deerflow.agents.factory import _assemble_from_features
from deerflow.agents.features import RuntimeFeatures
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
from deerflow.config.memory_config import MemoryConfig
monkeypatch.setattr(
"deerflow.config.memory_config.get_memory_config",
lambda: MemoryConfig(enabled=True, mode="middleware"),
)
feat = RuntimeFeatures(memory=True, memory_config=MemoryConfig(enabled=True, mode="tool"))
chain, extra_tools = _assemble_from_features(feat, name="test-agent")
middleware_types = [type(m) for m in chain]
tool_names = [t.name for t in extra_tools]
assert MemoryMiddleware not in middleware_types
assert "memory_add" in tool_names
def test_middleware_mode_appends_middleware_not_tools(self, monkeypatch):
"""When mode=middleware (default), MemoryMiddleware IS in the chain
and memory tools are NOT in extra_tools."""
from deerflow.agents.factory import _assemble_from_features
from deerflow.agents.features import RuntimeFeatures
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
from deerflow.config.memory_config import MemoryConfig
mw_config = MemoryConfig(enabled=True, mode="middleware")
monkeypatch.setattr(
"deerflow.config.memory_config.get_memory_config",
lambda: mw_config,
)
feat = RuntimeFeatures(memory=True)
chain, extra_tools = _assemble_from_features(feat, name="test-agent")
middleware_types = [type(m) for m in chain]
assert MemoryMiddleware in middleware_types, "MemoryMiddleware should be in the chain in middleware mode"
tool_names = [t.name for t in extra_tools]
assert "memory_search" not in tool_names, "memory_search should not be registered in middleware mode"
def test_memory_disabled_skips_both(self, monkeypatch):
"""When memory.enabled=False, middleware IS appended but no-ops at
runtime (the enabled check is inside after_agent, not the factory).
Tools are never registered because mode is middleware (default)."""
from deerflow.agents.factory import _assemble_from_features
from deerflow.agents.features import RuntimeFeatures
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
from deerflow.config.memory_config import MemoryConfig
disabled_config = MemoryConfig(enabled=False, mode="middleware")
monkeypatch.setattr(
"deerflow.config.memory_config.get_memory_config",
lambda: disabled_config,
)
feat = RuntimeFeatures(memory=True)
chain, extra_tools = _assemble_from_features(feat, name="test-agent")
# Middleware is appended - it checks enabled internally in after_agent
middleware_types = [type(m) for m in chain]
assert MemoryMiddleware in middleware_types
# Tools should NOT be registered in middleware mode regardless of enabled
tool_names = [t.name for t in extra_tools]
assert "memory_search" not in tool_names
def test_should_use_memory_tools_requires_tool_mode_and_enabled(self):
"""Tool-mode helper should require both mode=tool and enabled=True."""
from deerflow.config.memory_config import MemoryConfig, should_use_memory_tools
assert should_use_memory_tools(MemoryConfig(enabled=True, mode="tool")) is True
assert should_use_memory_tools(MemoryConfig(enabled=False, mode="tool")) is False
assert should_use_memory_tools(MemoryConfig(enabled=True, mode="middleware")) is False
def test_tool_mode_disabled_logs_warning_and_uses_middleware(self, monkeypatch, caplog):
"""mode=tool with enabled=False should be visible and still disable tools."""
from deerflow.agents.factory import _assemble_from_features
from deerflow.agents.features import RuntimeFeatures
from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware
from deerflow.config.memory_config import MemoryConfig
disabled_tool_config = MemoryConfig(enabled=False, mode="tool")
monkeypatch.setattr(
"deerflow.config.memory_config.get_memory_config",
lambda: disabled_tool_config,
)
chain, extra_tools = _assemble_from_features(RuntimeFeatures(memory=True), name="test-agent")
assert MemoryMiddleware in [type(m) for m in chain]
assert "memory_add" not in [t.name for t in extra_tools]
assert "memory.mode is 'tool' but memory.enabled is false" in caplog.text
def test_lead_agent_deduplicates_memory_tools_after_appending(self, monkeypatch):
"""Configured tools should not duplicate tool-mode memory tools."""
from deerflow.agents.lead_agent import agent as lead_agent_module
from deerflow.config.memory_config import MemoryConfig
monkeypatch.setattr(lead_agent_module, "_resolve_model_name", lambda x=None, **kwargs: "default-model")
monkeypatch.setattr(lead_agent_module, "create_chat_model", lambda **kwargs: "model")
monkeypatch.setattr(lead_agent_module, "build_middlewares", lambda *args, **kwargs: [])
monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt")
monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs)
monkeypatch.setattr(lead_agent_module, "build_tracing_callbacks", lambda: [])
monkeypatch.setattr(
lead_agent_module,
"load_agent_config",
lambda name: SimpleNamespace(model=None, skills=None, tool_groups=None),
)
monkeypatch.setattr(lead_agent_module, "_load_enabled_skills_for_tool_policy", lambda available_skills, *, app_config, user_id=None: [])
monkeypatch.setattr(lead_agent_module, "filter_tools_by_skill_allowed_tools", lambda tools, skills, always_allowed_tool_names=(): tools)
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [_NamedTool("memory_search"), _NamedTool("bash")])
app_config = SimpleNamespace(
get_model_config=lambda name: SimpleNamespace(supports_thinking=False, supports_vision=False),
memory=MemoryConfig(enabled=True, mode="tool"),
skills=SimpleNamespace(deferred_discovery=False, container_path="/tmp/skills"),
tool_search=SimpleNamespace(enabled=False, auto_promote_top_k=0),
)
agent_kwargs = lead_agent_module._make_lead_agent({"configurable": {"agent_name": "test-agent"}}, app_config=app_config)
tool_names = [tool.name for tool in agent_kwargs["tools"]]
assert tool_names.count("memory_search") == 1
assert "memory_add" in tool_names
def test_lead_agent_preserves_non_memory_duplicate_tool_names(self, monkeypatch):
"""Memory-tool collision handling should not drop unrelated duplicate tools."""
from deerflow.agents.lead_agent import agent as lead_agent_module
from deerflow.config.memory_config import MemoryConfig
monkeypatch.setattr(lead_agent_module, "_resolve_model_name", lambda x=None, **kwargs: "default-model")
monkeypatch.setattr(lead_agent_module, "create_chat_model", lambda **kwargs: "model")
monkeypatch.setattr(lead_agent_module, "build_middlewares", lambda *args, **kwargs: [])
monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt")
monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs)
monkeypatch.setattr(lead_agent_module, "build_tracing_callbacks", lambda: [])
monkeypatch.setattr(
lead_agent_module,
"load_agent_config",
lambda name: SimpleNamespace(model=None, skills=None, tool_groups=None),
)
monkeypatch.setattr(lead_agent_module, "_load_enabled_skills_for_tool_policy", lambda available_skills, *, app_config, user_id=None: [])
monkeypatch.setattr(lead_agent_module, "filter_tools_by_skill_allowed_tools", lambda tools, skills, always_allowed_tool_names=(): tools)
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [_NamedTool("bash"), _NamedTool("bash")])
app_config = SimpleNamespace(
get_model_config=lambda name: SimpleNamespace(supports_thinking=False, supports_vision=False),
memory=MemoryConfig(enabled=True, mode="tool"),
skills=SimpleNamespace(deferred_discovery=False, container_path="/tmp/skills"),
tool_search=SimpleNamespace(enabled=False, auto_promote_top_k=0),
)
agent_kwargs = lead_agent_module._make_lead_agent({"configurable": {"agent_name": "test-agent"}}, app_config=app_config)
tool_names = [tool.name for tool in agent_kwargs["tools"]]
assert tool_names.count("bash") == 2
assert tool_names.count("memory_add") == 1