mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-08-10 14:58:46 +00:00
* 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>
847 lines
36 KiB
Python
847 lines
36 KiB
Python
"""Tests for custom agent support."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from pathlib import Path
|
||
from unittest.mock import patch
|
||
|
||
import pytest
|
||
import yaml
|
||
from fastapi.testclient import TestClient
|
||
|
||
from deerflow.config.agents_api_config import AgentsApiConfig, get_agents_api_config, set_agents_api_config
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Helpers
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _make_paths(base_dir: Path):
|
||
"""Return a Paths instance pointing to base_dir."""
|
||
from deerflow.config.paths import Paths
|
||
|
||
return Paths(base_dir=base_dir)
|
||
|
||
|
||
def _write_agent(base_dir: Path, name: str, config: dict, soul: str = "You are helpful.") -> None:
|
||
"""Write an agent directory with config.yaml and SOUL.md."""
|
||
agent_dir = base_dir / "agents" / name
|
||
agent_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
config_copy = dict(config)
|
||
if "name" not in config_copy:
|
||
config_copy["name"] = name
|
||
|
||
with open(agent_dir / "config.yaml", "w") as f:
|
||
yaml.dump(config_copy, f)
|
||
|
||
(agent_dir / "SOUL.md").write_text(soul, encoding="utf-8")
|
||
|
||
|
||
# ===========================================================================
|
||
# 1. Paths class – agent path methods
|
||
# ===========================================================================
|
||
|
||
|
||
class TestPaths:
|
||
def test_agents_dir(self, tmp_path):
|
||
paths = _make_paths(tmp_path)
|
||
assert paths.agents_dir == tmp_path / "agents"
|
||
|
||
def test_agent_dir(self, tmp_path):
|
||
paths = _make_paths(tmp_path)
|
||
assert paths.agent_dir("code-reviewer") == tmp_path / "agents" / "code-reviewer"
|
||
|
||
def test_agent_memory_file(self, tmp_path):
|
||
paths = _make_paths(tmp_path)
|
||
assert paths.agent_memory_file("code-reviewer") == tmp_path / "agents" / "code-reviewer" / "memory.json"
|
||
|
||
def test_user_md_file(self, tmp_path):
|
||
paths = _make_paths(tmp_path)
|
||
assert paths.user_md_file == tmp_path / "USER.md"
|
||
|
||
def test_paths_are_different_from_global(self, tmp_path):
|
||
paths = _make_paths(tmp_path)
|
||
assert paths.memory_file != paths.agent_memory_file("my-agent")
|
||
assert paths.memory_file == tmp_path / "memory.json"
|
||
assert paths.agent_memory_file("my-agent") == tmp_path / "agents" / "my-agent" / "memory.json"
|
||
|
||
|
||
# ===========================================================================
|
||
# 2. AgentConfig – Pydantic parsing
|
||
# ===========================================================================
|
||
|
||
|
||
class TestAgentConfig:
|
||
def test_minimal_config(self):
|
||
from deerflow.config.agents_config import AgentConfig
|
||
|
||
cfg = AgentConfig(name="my-agent")
|
||
assert cfg.name == "my-agent"
|
||
assert cfg.description == ""
|
||
assert cfg.model is None
|
||
assert cfg.tool_groups is None
|
||
|
||
def test_full_config(self):
|
||
from deerflow.config.agents_config import AgentConfig
|
||
|
||
cfg = AgentConfig(
|
||
name="code-reviewer",
|
||
description="Specialized for code review",
|
||
model="deepseek-v3",
|
||
tool_groups=["file:read", "bash"],
|
||
)
|
||
assert cfg.name == "code-reviewer"
|
||
assert cfg.model == "deepseek-v3"
|
||
assert cfg.tool_groups == ["file:read", "bash"]
|
||
|
||
def test_config_from_dict(self):
|
||
from deerflow.config.agents_config import AgentConfig
|
||
|
||
data = {"name": "test-agent", "description": "A test", "model": "gpt-4"}
|
||
cfg = AgentConfig(**data)
|
||
assert cfg.name == "test-agent"
|
||
assert cfg.model == "gpt-4"
|
||
assert cfg.tool_groups is None
|
||
|
||
|
||
# ===========================================================================
|
||
# 3. load_agent_config
|
||
# ===========================================================================
|
||
|
||
|
||
class TestLoadAgentConfig:
|
||
def test_load_valid_config(self, tmp_path):
|
||
config_dict = {"name": "code-reviewer", "description": "Code review agent", "model": "deepseek-v3"}
|
||
_write_agent(tmp_path, "code-reviewer", config_dict)
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
cfg = load_agent_config("code-reviewer")
|
||
|
||
assert cfg.name == "code-reviewer"
|
||
assert cfg.description == "Code review agent"
|
||
assert cfg.model == "deepseek-v3"
|
||
|
||
def test_load_missing_agent_raises(self, tmp_path):
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
with pytest.raises(FileNotFoundError):
|
||
load_agent_config("nonexistent-agent")
|
||
|
||
def test_load_missing_config_yaml_raises(self, tmp_path):
|
||
# Create directory without config.yaml
|
||
(tmp_path / "agents" / "broken-agent").mkdir(parents=True)
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
with pytest.raises(FileNotFoundError):
|
||
load_agent_config("broken-agent")
|
||
|
||
def test_load_config_infers_name_from_dir(self, tmp_path):
|
||
"""Config without 'name' field should use directory name."""
|
||
agent_dir = tmp_path / "agents" / "inferred-name"
|
||
agent_dir.mkdir(parents=True)
|
||
(agent_dir / "config.yaml").write_text("description: My agent\n")
|
||
(agent_dir / "SOUL.md").write_text("Hello")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
cfg = load_agent_config("inferred-name")
|
||
|
||
assert cfg.name == "inferred-name"
|
||
|
||
def test_load_config_with_tool_groups(self, tmp_path):
|
||
config_dict = {"name": "restricted", "tool_groups": ["file:read", "file:write"]}
|
||
_write_agent(tmp_path, "restricted", config_dict)
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
cfg = load_agent_config("restricted")
|
||
|
||
assert cfg.tool_groups == ["file:read", "file:write"]
|
||
|
||
def test_load_config_with_skills_empty_list(self, tmp_path):
|
||
config_dict = {"name": "no-skills-agent", "skills": []}
|
||
_write_agent(tmp_path, "no-skills-agent", config_dict)
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
cfg = load_agent_config("no-skills-agent")
|
||
|
||
assert cfg.skills == []
|
||
|
||
def test_load_config_with_skills_omitted(self, tmp_path):
|
||
config_dict = {"name": "default-skills-agent"}
|
||
_write_agent(tmp_path, "default-skills-agent", config_dict)
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
cfg = load_agent_config("default-skills-agent")
|
||
|
||
assert cfg.skills is None
|
||
|
||
def test_legacy_prompt_file_field_ignored(self, tmp_path):
|
||
"""Unknown fields like the old prompt_file should be silently ignored."""
|
||
agent_dir = tmp_path / "agents" / "legacy-agent"
|
||
agent_dir.mkdir(parents=True)
|
||
(agent_dir / "config.yaml").write_text("name: legacy-agent\nprompt_file: system.md\n")
|
||
(agent_dir / "SOUL.md").write_text("Soul content")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
cfg = load_agent_config("legacy-agent")
|
||
|
||
assert cfg.name == "legacy-agent"
|
||
|
||
|
||
# ===========================================================================
|
||
# 3b. resolve_agent_dir — memory-only directory fallback (#3390)
|
||
# ===========================================================================
|
||
|
||
|
||
class TestResolveAgentDirMemoryOnlyFallback:
|
||
"""Regression tests for #3390.
|
||
|
||
When memory is enabled, the first conversation creates a user-isolated
|
||
agent directory containing only ``memory.json`` (no ``config.yaml``).
|
||
On the next turn ``resolve_agent_dir`` must fall through to the legacy
|
||
shared layout instead of returning the incomplete user directory.
|
||
"""
|
||
|
||
def test_user_dir_with_only_memory_falls_back_to_legacy(self, tmp_path):
|
||
"""User dir has memory.json but no config.yaml → use legacy dir."""
|
||
from deerflow.config.agents_config import resolve_agent_dir
|
||
|
||
# Legacy agent with full config
|
||
legacy_dir = tmp_path / "agents" / "my-agent"
|
||
legacy_dir.mkdir(parents=True)
|
||
(legacy_dir / "config.yaml").write_text("name: my-agent\n", encoding="utf-8")
|
||
(legacy_dir / "SOUL.md").write_text("legacy soul", encoding="utf-8")
|
||
|
||
# User dir created by memory write — no config.yaml
|
||
user_dir = tmp_path / "users" / "u1" / "agents" / "my-agent"
|
||
user_dir.mkdir(parents=True)
|
||
(user_dir / "memory.json").write_text("{}", encoding="utf-8")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)), patch("deerflow.config.agents_config.get_effective_user_id", return_value="u1"):
|
||
result = resolve_agent_dir("my-agent", user_id="u1")
|
||
|
||
assert result == legacy_dir
|
||
|
||
def test_user_dir_with_config_takes_priority(self, tmp_path):
|
||
"""User dir with config.yaml should still win over legacy."""
|
||
from deerflow.config.agents_config import resolve_agent_dir
|
||
|
||
# Legacy
|
||
legacy_dir = tmp_path / "agents" / "my-agent"
|
||
legacy_dir.mkdir(parents=True)
|
||
(legacy_dir / "config.yaml").write_text("name: my-agent\n", encoding="utf-8")
|
||
|
||
# User dir with full config (migrated)
|
||
user_dir = tmp_path / "users" / "u1" / "agents" / "my-agent"
|
||
user_dir.mkdir(parents=True)
|
||
(user_dir / "config.yaml").write_text("name: my-agent\nmodel: gpt-4\n", encoding="utf-8")
|
||
(user_dir / "memory.json").write_text("{}", encoding="utf-8")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)), patch("deerflow.config.agents_config.get_effective_user_id", return_value="u1"):
|
||
result = resolve_agent_dir("my-agent", user_id="u1")
|
||
|
||
assert result == user_dir
|
||
|
||
def test_load_config_falls_back_when_user_dir_is_memory_only(self, tmp_path):
|
||
"""End-to-end: load_agent_config works when user dir only has memory.json."""
|
||
config_dict = {"name": "my-agent", "description": "Legacy agent", "model": "deepseek-v3"}
|
||
_write_agent(tmp_path, "my-agent", config_dict)
|
||
|
||
# Simulate memory write creating user dir without config
|
||
user_dir = tmp_path / "users" / "u1" / "agents" / "my-agent"
|
||
user_dir.mkdir(parents=True)
|
||
(user_dir / "memory.json").write_text("{}", encoding="utf-8")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)), patch("deerflow.config.agents_config.get_effective_user_id", return_value="u1"):
|
||
from deerflow.config.agents_config import load_agent_config
|
||
|
||
cfg = load_agent_config("my-agent", user_id="u1")
|
||
|
||
assert cfg.name == "my-agent"
|
||
assert cfg.model == "deepseek-v3"
|
||
|
||
|
||
# ===========================================================================
|
||
# 4. load_agent_soul
|
||
# ===========================================================================
|
||
|
||
|
||
class TestLoadAgentSoul:
|
||
def test_reads_soul_file(self, tmp_path):
|
||
expected_soul = "You are a specialized code review expert."
|
||
_write_agent(tmp_path, "code-reviewer", {"name": "code-reviewer"}, soul=expected_soul)
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import AgentConfig, load_agent_soul
|
||
|
||
cfg = AgentConfig(name="code-reviewer")
|
||
soul = load_agent_soul(cfg.name)
|
||
|
||
assert soul == expected_soul
|
||
|
||
def test_missing_soul_file_returns_none(self, tmp_path):
|
||
agent_dir = tmp_path / "agents" / "no-soul"
|
||
agent_dir.mkdir(parents=True)
|
||
(agent_dir / "config.yaml").write_text("name: no-soul\n")
|
||
# No SOUL.md created
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import AgentConfig, load_agent_soul
|
||
|
||
cfg = AgentConfig(name="no-soul")
|
||
soul = load_agent_soul(cfg.name)
|
||
|
||
assert soul is None
|
||
|
||
def test_empty_soul_file_returns_none(self, tmp_path):
|
||
agent_dir = tmp_path / "agents" / "empty-soul"
|
||
agent_dir.mkdir(parents=True)
|
||
(agent_dir / "config.yaml").write_text("name: empty-soul\n")
|
||
(agent_dir / "SOUL.md").write_text(" \n ")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import AgentConfig, load_agent_soul
|
||
|
||
cfg = AgentConfig(name="empty-soul")
|
||
soul = load_agent_soul(cfg.name)
|
||
|
||
assert soul is None
|
||
|
||
def test_loads_soul_without_config_yaml(self, tmp_path):
|
||
"""SOUL.md should load even when the agent dir has no config.yaml (#4135)."""
|
||
agent_dir = tmp_path / "agents" / "soul-only"
|
||
agent_dir.mkdir(parents=True)
|
||
# Deliberately no config.yaml – the agent is configured externally
|
||
(agent_dir / "SOUL.md").write_text("You are a brave agent.", encoding="utf-8")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)), patch("deerflow.config.agents_config.get_effective_user_id", return_value="default"):
|
||
from deerflow.config.agents_config import load_agent_soul
|
||
|
||
soul = load_agent_soul("soul-only")
|
||
|
||
assert soul == "You are a brave agent."
|
||
|
||
def test_loads_soul_from_user_dir_without_config_yaml(self, tmp_path):
|
||
"""Fallback should find SOUL.md when resolver returns a default dir without it (#4135).
|
||
|
||
Setup: per-user agent 'foo' exists as a memory-only directory
|
||
(no config.yaml, no SOUL.md). Legacy agent 'foo' has SOUL.md but
|
||
no config.yaml. resolve_agent_dir returns the per-user path as
|
||
default (neither dir has config.yaml). The fallback then finds
|
||
SOUL.md in the legacy directory.
|
||
"""
|
||
# Per-user dir: memory-only (no config.yaml, no SOUL.md)
|
||
user_dir = tmp_path / "users" / "test-user" / "agents" / "foo"
|
||
user_dir.mkdir(parents=True)
|
||
(user_dir / "memory.json").write_text("{}", encoding="utf-8")
|
||
|
||
# Legacy dir: has SOUL.md but no config.yaml
|
||
legacy_dir = tmp_path / "agents" / "foo"
|
||
legacy_dir.mkdir(parents=True)
|
||
(legacy_dir / "SOUL.md").write_text("You are a legacy agent.", encoding="utf-8")
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)), patch("deerflow.config.agents_config.get_effective_user_id", return_value="test-user"):
|
||
from deerflow.config.agents_config import load_agent_soul
|
||
|
||
soul = load_agent_soul("foo")
|
||
|
||
assert soul == "You are a legacy agent."
|
||
|
||
def test_soul_not_leaked_from_legacy_when_per_user_has_config(self, tmp_path):
|
||
"""Per-user agent with config.yaml but no SOUL.md should NOT fall back to legacy SOUL.md.
|
||
|
||
This verifies the gated condition: fallback only fires when the
|
||
resolved dir lacks config.yaml. A properly-resolved per-user agent
|
||
that simply has no SOUL.md returns None, preserving the
|
||
"per-user entries fully shadow legacy entries" invariant.
|
||
"""
|
||
# Legacy dir: has SOUL.md
|
||
legacy_dir = tmp_path / "agents" / "foo"
|
||
legacy_dir.mkdir(parents=True)
|
||
(legacy_dir / "config.yaml").write_text("name: foo\n")
|
||
(legacy_dir / "SOUL.md").write_text("You are a legacy agent.", encoding="utf-8")
|
||
|
||
# Per-user dir: has config.yaml (resolver returns this) but no SOUL.md
|
||
user_dir = tmp_path / "users" / "test-user" / "agents" / "foo"
|
||
user_dir.mkdir(parents=True)
|
||
(user_dir / "config.yaml").write_text("name: foo\n")
|
||
# No SOUL.md in per-user dir
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)), patch("deerflow.config.agents_config.get_effective_user_id", return_value="test-user"):
|
||
from deerflow.config.agents_config import load_agent_soul
|
||
|
||
soul = load_agent_soul("foo")
|
||
|
||
assert soul is None
|
||
|
||
|
||
# ===========================================================================
|
||
# 5. list_custom_agents
|
||
# ===========================================================================
|
||
|
||
|
||
class TestListCustomAgents:
|
||
def test_empty_when_no_agents_dir(self, tmp_path):
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import list_custom_agents
|
||
|
||
agents = list_custom_agents()
|
||
|
||
assert agents == []
|
||
|
||
def test_discovers_multiple_agents(self, tmp_path):
|
||
_write_agent(tmp_path, "agent-a", {"name": "agent-a"})
|
||
_write_agent(tmp_path, "agent-b", {"name": "agent-b", "description": "B"})
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import list_custom_agents
|
||
|
||
agents = list_custom_agents()
|
||
|
||
names = [a.name for a in agents]
|
||
assert "agent-a" in names
|
||
assert "agent-b" in names
|
||
|
||
def test_skips_dirs_without_config_yaml(self, tmp_path):
|
||
# Valid agent
|
||
_write_agent(tmp_path, "valid-agent", {"name": "valid-agent"})
|
||
# Invalid dir (no config.yaml)
|
||
(tmp_path / "agents" / "invalid-dir").mkdir(parents=True)
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import list_custom_agents
|
||
|
||
agents = list_custom_agents()
|
||
|
||
assert len(agents) == 1
|
||
assert agents[0].name == "valid-agent"
|
||
|
||
def test_skips_non_directory_entries(self, tmp_path):
|
||
# Create the agents dir with a file (not a dir)
|
||
agents_dir = tmp_path / "agents"
|
||
agents_dir.mkdir(parents=True)
|
||
(agents_dir / "not-a-dir.txt").write_text("hello")
|
||
_write_agent(tmp_path, "real-agent", {"name": "real-agent"})
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import list_custom_agents
|
||
|
||
agents = list_custom_agents()
|
||
|
||
assert len(agents) == 1
|
||
assert agents[0].name == "real-agent"
|
||
|
||
def test_returns_sorted_by_name(self, tmp_path):
|
||
_write_agent(tmp_path, "z-agent", {"name": "z-agent"})
|
||
_write_agent(tmp_path, "a-agent", {"name": "a-agent"})
|
||
_write_agent(tmp_path, "m-agent", {"name": "m-agent"})
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=_make_paths(tmp_path)):
|
||
from deerflow.config.agents_config import list_custom_agents
|
||
|
||
agents = list_custom_agents()
|
||
|
||
names = [a.name for a in agents]
|
||
assert names == sorted(names)
|
||
|
||
|
||
# ===========================================================================
|
||
# 7. Memory isolation: _get_memory_file_path
|
||
# ===========================================================================
|
||
|
||
|
||
class TestMemoryFilePath:
|
||
def test_global_memory_path(self, tmp_path, monkeypatch):
|
||
"""None agent_name should return global memory file."""
|
||
from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemConfig
|
||
from deerflow.agents.memory.backends.deermem.deermem.core.storage import FileMemoryStorage
|
||
|
||
monkeypatch.setenv("DEERMEM_DATA_DIR", str(tmp_path))
|
||
storage = FileMemoryStorage(DeerMemConfig())
|
||
path = storage._get_memory_file_path(None)
|
||
assert path == tmp_path / "memory.json"
|
||
|
||
def test_agent_memory_path(self, tmp_path, monkeypatch):
|
||
"""Providing agent_name should return per-agent memory file."""
|
||
from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemConfig
|
||
from deerflow.agents.memory.backends.deermem.deermem.core.storage import FileMemoryStorage
|
||
|
||
monkeypatch.setenv("DEERMEM_DATA_DIR", str(tmp_path))
|
||
storage = FileMemoryStorage(DeerMemConfig())
|
||
path = storage._get_memory_file_path("code-reviewer")
|
||
assert path == tmp_path / "agents" / "code-reviewer" / "memory.json"
|
||
|
||
def test_different_paths_for_different_agents(self, tmp_path, monkeypatch):
|
||
from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemConfig
|
||
from deerflow.agents.memory.backends.deermem.deermem.core.storage import FileMemoryStorage
|
||
|
||
monkeypatch.setenv("DEERMEM_DATA_DIR", str(tmp_path))
|
||
storage = FileMemoryStorage(DeerMemConfig())
|
||
path_global = storage._get_memory_file_path(None)
|
||
path_a = storage._get_memory_file_path("agent-a")
|
||
path_b = storage._get_memory_file_path("agent-b")
|
||
|
||
assert path_global != path_a
|
||
assert path_global != path_b
|
||
assert path_a != path_b
|
||
|
||
|
||
# ===========================================================================
|
||
# 8. Gateway API – Agents endpoints
|
||
# ===========================================================================
|
||
|
||
|
||
def _make_test_app(tmp_path: Path):
|
||
"""Create a FastAPI app with the agents router, patching paths to tmp_path."""
|
||
from fastapi import FastAPI
|
||
|
||
from app.gateway.routers.agents import router
|
||
|
||
app = FastAPI()
|
||
app.include_router(router)
|
||
return app
|
||
|
||
|
||
@pytest.fixture()
|
||
def agent_client(tmp_path):
|
||
"""TestClient with agents router, using tmp_path as base_dir."""
|
||
import app.gateway.routers.agents as agents_router
|
||
|
||
paths_instance = _make_paths(tmp_path)
|
||
previous_config = AgentsApiConfig(**get_agents_api_config().model_dump())
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=paths_instance), patch.object(agents_router, "get_paths", return_value=paths_instance):
|
||
set_agents_api_config(AgentsApiConfig(enabled=True))
|
||
try:
|
||
app = _make_test_app(tmp_path)
|
||
with TestClient(app) as client:
|
||
client._tmp_path = tmp_path # type: ignore[attr-defined]
|
||
yield client
|
||
finally:
|
||
set_agents_api_config(previous_config)
|
||
|
||
|
||
@pytest.fixture()
|
||
def disabled_agent_client(tmp_path):
|
||
"""TestClient with agents router while the management API is disabled."""
|
||
import app.gateway.routers.agents as agents_router
|
||
|
||
paths_instance = _make_paths(tmp_path)
|
||
previous_config = AgentsApiConfig(**get_agents_api_config().model_dump())
|
||
|
||
with patch("deerflow.config.agents_config.get_paths", return_value=paths_instance), patch.object(agents_router, "get_paths", return_value=paths_instance):
|
||
set_agents_api_config(AgentsApiConfig(enabled=False))
|
||
try:
|
||
app = _make_test_app(tmp_path)
|
||
with TestClient(app) as client:
|
||
yield client
|
||
finally:
|
||
set_agents_api_config(previous_config)
|
||
|
||
|
||
class TestAgentsAPI:
|
||
def test_list_agents_empty(self, agent_client):
|
||
response = agent_client.get("/api/agents")
|
||
assert response.status_code == 200
|
||
data = response.json()
|
||
assert data["agents"] == []
|
||
|
||
def test_create_agent(self, agent_client):
|
||
payload = {
|
||
"name": "code-reviewer",
|
||
"description": "Reviews code",
|
||
"soul": "You are a code reviewer.",
|
||
}
|
||
response = agent_client.post("/api/agents", json=payload)
|
||
assert response.status_code == 201
|
||
data = response.json()
|
||
assert data["name"] == "code-reviewer"
|
||
assert data["description"] == "Reviews code"
|
||
assert data["soul"] == "You are a code reviewer."
|
||
|
||
def test_create_agent_invalid_name(self, agent_client):
|
||
payload = {"name": "Code Reviewer!", "soul": "test"}
|
||
response = agent_client.post("/api/agents", json=payload)
|
||
assert response.status_code == 422
|
||
|
||
def test_create_duplicate_agent_409(self, agent_client):
|
||
payload = {"name": "my-agent", "soul": "test"}
|
||
agent_client.post("/api/agents", json=payload)
|
||
|
||
# Second create should fail
|
||
response = agent_client.post("/api/agents", json=payload)
|
||
assert response.status_code == 409
|
||
|
||
def test_list_agents_after_create(self, agent_client):
|
||
agent_client.post("/api/agents", json={"name": "agent-one", "soul": "p1"})
|
||
agent_client.post("/api/agents", json={"name": "agent-two", "soul": "p2"})
|
||
|
||
response = agent_client.get("/api/agents")
|
||
assert response.status_code == 200
|
||
names = [a["name"] for a in response.json()["agents"]]
|
||
assert "agent-one" in names
|
||
assert "agent-two" in names
|
||
|
||
def test_list_agents_includes_soul(self, agent_client):
|
||
agent_client.post("/api/agents", json={"name": "soul-agent", "soul": "My soul content"})
|
||
|
||
response = agent_client.get("/api/agents")
|
||
assert response.status_code == 200
|
||
agents = response.json()["agents"]
|
||
soul_agent = next(a for a in agents if a["name"] == "soul-agent")
|
||
assert soul_agent["soul"] == "My soul content"
|
||
|
||
def test_get_agent(self, agent_client):
|
||
agent_client.post("/api/agents", json={"name": "test-agent", "soul": "Hello world"})
|
||
|
||
response = agent_client.get("/api/agents/test-agent")
|
||
assert response.status_code == 200
|
||
data = response.json()
|
||
assert data["name"] == "test-agent"
|
||
assert data["soul"] == "Hello world"
|
||
|
||
def test_get_missing_agent_404(self, agent_client):
|
||
response = agent_client.get("/api/agents/nonexistent")
|
||
assert response.status_code == 404
|
||
|
||
def test_update_agent_soul(self, agent_client):
|
||
agent_client.post("/api/agents", json={"name": "update-me", "soul": "original"})
|
||
|
||
response = agent_client.put("/api/agents/update-me", json={"soul": "updated"})
|
||
assert response.status_code == 200
|
||
assert response.json()["soul"] == "updated"
|
||
|
||
def test_update_agent_description(self, agent_client):
|
||
agent_client.post("/api/agents", json={"name": "desc-agent", "description": "old desc", "soul": "p"})
|
||
|
||
response = agent_client.put("/api/agents/desc-agent", json={"description": "new desc"})
|
||
assert response.status_code == 200
|
||
assert response.json()["description"] == "new desc"
|
||
|
||
def test_update_agent_preserves_hand_authored_github_block(self, agent_client):
|
||
"""A hand-authored ``github:`` block on disk must survive PATCH.
|
||
|
||
The HTTP route does not expose ``github`` as an editable field
|
||
(and rightly so — the GitHub App credentials and binding triggers
|
||
are operator-authored, not end-user-editable). But it MUST carry
|
||
the block forward when rewriting ``config.yaml`` for a description /
|
||
model / tool_groups / skills change, otherwise an operator who
|
||
edits the agent's description from the Web UI silently strips the
|
||
binding and the next webhook delivery silently no-ops.
|
||
|
||
Mirrors the same property the harness ``update_agent`` tool enforces
|
||
via ``preserve_non_managed_fields``; both surfaces share the helper.
|
||
"""
|
||
# Create an agent through the API, then hand-author a github: block
|
||
# into its config.yaml — exactly the workflow an operator would
|
||
# follow when wiring a new repo binding.
|
||
agent_client.post("/api/agents", json={"name": "github-agent", "description": "old desc", "soul": "p"})
|
||
|
||
tmp_path: Path = agent_client._tmp_path # type: ignore[attr-defined]
|
||
agent_dir = tmp_path / "users" / "test-user-autouse" / "agents" / "github-agent"
|
||
config_file = agent_dir / "config.yaml"
|
||
config_data = yaml.safe_load(config_file.read_text())
|
||
config_data["github"] = {
|
||
"installation_id": 99999,
|
||
"bot_login": "github-agent-bot",
|
||
"bindings": [
|
||
{
|
||
"repo": "acme/widget",
|
||
"triggers": {"pull_request": {"actions": ["opened"]}},
|
||
}
|
||
],
|
||
}
|
||
config_file.write_text(yaml.safe_dump(config_data, sort_keys=False), encoding="utf-8")
|
||
|
||
# PATCH only the description.
|
||
response = agent_client.put("/api/agents/github-agent", json={"description": "new desc"})
|
||
assert response.status_code == 200
|
||
|
||
# github: block must survive verbatim.
|
||
reloaded = yaml.safe_load(config_file.read_text())
|
||
assert reloaded["description"] == "new desc"
|
||
assert reloaded["github"] == {
|
||
"installation_id": 99999,
|
||
"bot_login": "github-agent-bot",
|
||
"bindings": [
|
||
{
|
||
"repo": "acme/widget",
|
||
"triggers": {"pull_request": {"actions": ["opened"]}},
|
||
}
|
||
],
|
||
}
|
||
|
||
def test_update_memory_only_user_dir_with_legacy_agent_returns_409(self, agent_client, tmp_path):
|
||
"""Regression for #3390's PUT /api/agents/{name} guard.
|
||
|
||
A per-user agent directory can exist containing only memory.json
|
||
(written the first time this user chats with a legacy shared
|
||
agent). The stale guard checked bare directory existence and
|
||
missed this case, letting the route silently fork a brand-new
|
||
config.yaml/SOUL.md into the memory-only directory instead of
|
||
blocking with the migration-script guidance.
|
||
"""
|
||
legacy_dir = tmp_path / "agents" / "legacy-agent"
|
||
legacy_dir.mkdir(parents=True)
|
||
(legacy_dir / "config.yaml").write_text("name: legacy-agent\ndescription: legacy\n", encoding="utf-8")
|
||
(legacy_dir / "SOUL.md").write_text("legacy soul", encoding="utf-8")
|
||
|
||
user_agent_dir = tmp_path / "users" / "test-user-autouse" / "agents" / "legacy-agent"
|
||
user_agent_dir.mkdir(parents=True)
|
||
(user_agent_dir / "memory.json").write_text("{}", encoding="utf-8")
|
||
|
||
response = agent_client.put("/api/agents/legacy-agent", json={"soul": "should not write"})
|
||
|
||
assert response.status_code == 409
|
||
assert not (user_agent_dir / "config.yaml").exists()
|
||
assert not (user_agent_dir / "SOUL.md").exists()
|
||
assert (user_agent_dir / "memory.json").exists(), "the user's existing memory must be left untouched"
|
||
|
||
def test_update_missing_agent_404(self, agent_client):
|
||
response = agent_client.put("/api/agents/ghost-agent", json={"soul": "new"})
|
||
assert response.status_code == 404
|
||
|
||
def test_delete_agent(self, agent_client):
|
||
agent_client.post("/api/agents", json={"name": "del-me", "soul": "bye"})
|
||
|
||
response = agent_client.delete("/api/agents/del-me")
|
||
assert response.status_code == 204
|
||
|
||
# Verify it's gone
|
||
response = agent_client.get("/api/agents/del-me")
|
||
assert response.status_code == 404
|
||
|
||
def test_delete_missing_agent_404(self, agent_client):
|
||
response = agent_client.delete("/api/agents/does-not-exist")
|
||
assert response.status_code == 404
|
||
|
||
def test_create_agent_with_model_and_tool_groups(self, agent_client):
|
||
payload = {
|
||
"name": "specialized",
|
||
"description": "Specialized agent",
|
||
"model": "deepseek-v3",
|
||
"tool_groups": ["file:read", "bash"],
|
||
"soul": "You are specialized.",
|
||
}
|
||
response = agent_client.post("/api/agents", json=payload)
|
||
assert response.status_code == 201
|
||
data = response.json()
|
||
assert data["model"] == "deepseek-v3"
|
||
assert data["tool_groups"] == ["file:read", "bash"]
|
||
|
||
def test_create_persists_files_on_disk(self, agent_client, tmp_path):
|
||
agent_client.post("/api/agents", json={"name": "disk-check", "soul": "disk soul"})
|
||
|
||
# tests/conftest.py installs an autouse fixture that sets the
|
||
# contextvar to "test-user-autouse", so the agent is persisted under
|
||
# users/test-user-autouse/agents/ rather than the legacy shared dir.
|
||
agent_dir = tmp_path / "users" / "test-user-autouse" / "agents" / "disk-check"
|
||
assert agent_dir.exists()
|
||
assert (agent_dir / "config.yaml").exists()
|
||
assert (agent_dir / "SOUL.md").exists()
|
||
assert (agent_dir / "SOUL.md").read_text() == "disk soul"
|
||
|
||
def test_delete_removes_files_from_disk(self, agent_client, tmp_path):
|
||
agent_client.post("/api/agents", json={"name": "remove-me", "soul": "bye"})
|
||
agent_dir = tmp_path / "users" / "test-user-autouse" / "agents" / "remove-me"
|
||
assert agent_dir.exists()
|
||
|
||
agent_client.delete("/api/agents/remove-me")
|
||
assert not agent_dir.exists()
|
||
|
||
def test_create_rejects_legacy_name_collision(self, agent_client, tmp_path):
|
||
"""An unmigrated legacy agent must still block name collision so that
|
||
running the migration script later won't shadow the legacy entry."""
|
||
legacy_dir = tmp_path / "agents" / "legacy-agent"
|
||
legacy_dir.mkdir(parents=True)
|
||
(legacy_dir / "config.yaml").write_text("name: legacy-agent\n", encoding="utf-8")
|
||
(legacy_dir / "SOUL.md").write_text("legacy soul", encoding="utf-8")
|
||
|
||
response = agent_client.post("/api/agents", json={"name": "legacy-agent", "soul": "x"})
|
||
assert response.status_code == 409
|
||
|
||
|
||
# ===========================================================================
|
||
# 9. Gateway API – User Profile endpoints
|
||
# ===========================================================================
|
||
|
||
|
||
class TestUserProfileAPI:
|
||
def test_get_user_profile_empty(self, agent_client):
|
||
response = agent_client.get("/api/user-profile")
|
||
assert response.status_code == 200
|
||
assert response.json()["content"] is None
|
||
|
||
def test_put_user_profile(self, agent_client, tmp_path):
|
||
content = "# User Profile\n\nI am a developer."
|
||
response = agent_client.put("/api/user-profile", json={"content": content})
|
||
assert response.status_code == 200
|
||
assert response.json()["content"] == content
|
||
|
||
# File should be written to disk
|
||
user_md = tmp_path / "USER.md"
|
||
assert user_md.exists()
|
||
assert user_md.read_text(encoding="utf-8") == content
|
||
|
||
def test_get_user_profile_after_put(self, agent_client):
|
||
content = "# Profile\n\nI work on data science."
|
||
agent_client.put("/api/user-profile", json={"content": content})
|
||
|
||
response = agent_client.get("/api/user-profile")
|
||
assert response.status_code == 200
|
||
assert response.json()["content"] == content
|
||
|
||
def test_put_empty_user_profile_returns_none(self, agent_client):
|
||
response = agent_client.put("/api/user-profile", json={"content": ""})
|
||
assert response.status_code == 200
|
||
assert response.json()["content"] is None
|
||
|
||
|
||
class TestAgentsApiDisabled:
|
||
def test_agents_list_returns_403(self, disabled_agent_client):
|
||
response = disabled_agent_client.get("/api/agents")
|
||
assert response.status_code == 403
|
||
assert "agents_api.enabled=true" in response.json()["detail"]
|
||
|
||
def test_agent_get_returns_403(self, disabled_agent_client):
|
||
response = disabled_agent_client.get("/api/agents/example-agent")
|
||
assert response.status_code == 403
|
||
|
||
def test_agent_name_check_returns_403(self, disabled_agent_client):
|
||
response = disabled_agent_client.get("/api/agents/check", params={"name": "example-agent"})
|
||
assert response.status_code == 403
|
||
|
||
def test_agent_create_returns_403(self, disabled_agent_client):
|
||
response = disabled_agent_client.post("/api/agents", json={"name": "example-agent", "soul": "blocked"})
|
||
assert response.status_code == 403
|
||
|
||
def test_agent_update_returns_403(self, disabled_agent_client):
|
||
response = disabled_agent_client.put("/api/agents/example-agent", json={"description": "blocked"})
|
||
assert response.status_code == 403
|
||
|
||
def test_agent_delete_returns_403(self, disabled_agent_client):
|
||
response = disabled_agent_client.delete("/api/agents/example-agent")
|
||
assert response.status_code == 403
|
||
|
||
def test_user_profile_routes_return_403(self, disabled_agent_client):
|
||
get_response = disabled_agent_client.get("/api/user-profile")
|
||
put_response = disabled_agent_client.put("/api/user-profile", json={"content": "blocked"})
|
||
|
||
assert get_response.status_code == 403
|
||
assert put_response.status_code == 403
|