feat(memory): add progressive wiki and drain Dream history (#4477)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-18 16:28:43 +08:00
1 parent 9ccf3b6214
commit 74d070f699
40 files changed
+1513 -738

No files matched your search

+122 -3
View File
@@ -54,8 +54,17 @@ def _loop(tmp_path, responses: list[str], **kwargs) -> AgentLoop:
@pytest.mark.asyncio
async def test_transient_session_keeps_history_without_persisting_or_durable_tools(tmp_path) -> None:
loop = _loop(tmp_path, ["first answer", "second answer"])
loop = _loop(tmp_path, ["first answer", "second answer", "ordinary answer"])
loop.context.memory.write_memory("private durable memory")
(tmp_path / "SOUL.md").write_text("private agent profile", encoding="utf-8")
(tmp_path / "USER.md").write_text("private user profile", encoding="utf-8")
(tmp_path / "AGENTS.md").write_text("shared project guidance", encoding="utf-8")
helper = tmp_path / "skills" / "helper" / "SKILL.md"
helper.parent.mkdir(parents=True)
helper.write_text("---\nname: helper\ndescription: Project helper\n---\nProject helper procedure", encoding="utf-8")
memory_skill = tmp_path / "skills" / "memory" / "SKILL.md"
memory_skill.parent.mkdir()
memory_skill.write_text("---\nname: memory\ndescription: Memory skill discovery cue\n---\nMemory skill body", encoding="utf-8")
temporary_chats = WebUITemporaryChats(
bus=loop.bus, session_manager=loop.sessions, logger=logger,
workspaces=WebUIWorkspaceController(
@@ -65,14 +74,32 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
)
key = f"websocket:{await temporary_chats.create(object(), trusted_webui=True)}"
await loop._process_message(_message(key, "first question"))
await loop._process_message(_message(key, "first question $memory $helper $cron"))
await loop._process_message(_message(key, "second question"))
await loop.process_direct("ordinary question $memory $helper $cron", session_key="cli:ordinary")
calls = loop.provider.chat_stream_with_retry.await_args_list
assert "private durable memory" not in str(calls[0].kwargs["messages"])
private_markers = (
"private durable memory", "private agent profile", "private user profile",
"Memory skill discovery cue", "Memory skill body", "memory/wiki/index.md",
)
for call in calls[:2]:
provider_context = str(call.kwargs["messages"])
assert all(marker not in provider_context for marker in private_markers)
assert "shared project guidance" in provider_context
transient_messages = calls[0].kwargs["messages"]
ordinary_messages = calls[2].kwargs["messages"]
assert "Project helper procedure" in str(transient_messages)
assert all(marker in str(ordinary_messages) for marker in private_markers)
assert "Scheduling is unavailable" in transient_messages[0]["content"]
assert "cron/SKILL.md" not in transient_messages[0]["content"]
assert "## Update a Task" not in transient_messages[-1]["content"]
assert "cron/SKILL.md" in ordinary_messages[0]["content"]
assert "## Update a Task" in ordinary_messages[-1]["content"]
tool_names = {item["function"]["name"] for item in calls[0].kwargs["tools"]}
assert "read_session" in tool_names
assert {"create_goal", "update_goal", "subagent", "cron"}.isdisjoint(tool_names)
assert "subagent" in {item["function"]["name"] for item in calls[2].kwargs["tools"]}
assert "first answer" in str(calls[1].kwargs["messages"])
session = loop.sessions.get_cached(key)
assert session is not None
@@ -87,6 +114,98 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
await loop.aclose()
async def test_temporary_chat_does_not_execute_unadvertised_subagent_call(tmp_path) -> None:
loop = _loop(tmp_path, [])
chats = WebUITemporaryChats(
bus=loop.bus, session_manager=loop.sessions, logger=logger,
workspaces=WebUIWorkspaceController(
session_manager=loop.sessions, default_workspace=tmp_path,
default_restrict_to_workspace=True,
),
)
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, finish_reason="tool_calls", tool_calls=[ToolCallRequest(
id="delegate", name="subagent", arguments={"action": "create", "task": "Synthetic task", "wait": True},
)]),
LLMResponse(content="Done without delegating."),
])
try:
key = f"websocket:{await chats.create(object(), trusted_webui=True)}"
await loop._process_message(_message(key, "Do a small task."))
calls = loop.provider.chat_stream_with_retry.await_args_list
assert len(calls) == 2
tool_result = next(message for message in calls[1].kwargs["messages"] if message["role"] == "tool")
assert "Tool 'subagent' not found" in tool_result["content"]
assert not loop.subagents.statuses_for_session(key)
finally:
chats.close()
await loop.aclose()
async def test_transient_session_file_tools_keep_shared_memory_out_of_the_turn(tmp_path) -> None:
loop = _loop(tmp_path, [], restrict_to_workspace=True)
memory = loop.context.memory
memory.user_file.write_text("Profile contains Private Marker", encoding="utf-8")
memory.wiki_dir.mkdir()
(memory.wiki_dir / "project.md").write_text("Wiki contains Private Marker", encoding="utf-8")
(tmp_path / "notes.txt").write_text("Project contains Private Marker", encoding="utf-8")
heartbeat = tmp_path / "HEARTBEAT.md"
heartbeat.write_text("Existing scheduled checks", encoding="utf-8")
key = "websocket:private-files"
await loop.sessions.state.register_transient(key, disabled_tools={"cron"})
try:
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="", tool_calls=[
ToolCallRequest(id="profile", name="read_file", arguments={"path": "USER.md"}),
ToolCallRequest(id="skill", name="read_file", arguments={"path": "skills/memory/SKILL.md"}),
ToolCallRequest(id="wiki", name="read_file", arguments={"path": "memory/wiki/project.md"}),
ToolCallRequest(id="listing", name="list_dir", arguments={"path": ".", "recursive": True}),
ToolCallRequest(id="read-heartbeat", name="read_file", arguments={"path": "HEARTBEAT.md"}),
ToolCallRequest(id="edit-heartbeat", name="edit_file", arguments={
"path": "HEARTBEAT.md", "old_text": "Existing scheduled checks", "new_text": "New checks",
}),
ToolCallRequest(id="edit", name="edit_file", arguments={
"path": "USER.md", "old_text": "Private Marker", "new_text": "Remember this",
}),
ToolCallRequest(id="project", name="write_file", arguments={
"path": "result.txt", "content": "Project artifact",
}),
]),
LLMResponse(content="done"),
])
await loop._process_message(_message(key, "Work with these files"))
request = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
results = {row['tool_call_id']: row['content'] for row in request if row['role'] == 'tool'}
for tool_call_id in ("profile", "wiki", "skill", "edit"):
assert "This path is not available in this session" in results[tool_call_id]
assert "notes.txt" in results["listing"]
assert "USER.md" not in results["listing"]
assert "project.md" not in results["listing"]
assert memory.user_file.read_text(encoding="utf-8") == "Profile contains Private Marker"
assert "Existing scheduled checks" in results["read-heartbeat"]
assert "read-only to file tools in this session" in results["edit-heartbeat"]
assert heartbeat.read_text(encoding="utf-8") == "Existing scheduled checks"
assert (tmp_path / "result.txt").read_text(encoding="utf-8") == "Project artifact"
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="", tool_calls=[
ToolCallRequest(id="read", name="read_file", arguments={"path": "memory/wiki/project.md"}),
ToolCallRequest(id="read-heartbeat", name="read_file", arguments={"path": "HEARTBEAT.md"}),
]),
LLMResponse(content="", tool_calls=[ToolCallRequest(id="edit-heartbeat", name="edit_file", arguments={
"path": "HEARTBEAT.md", "old_text": "Existing scheduled checks", "new_text": "New checks",
})]),
LLMResponse(content="done"),
])
await loop.process_direct("Read project memory and update scheduled checks", session_key="cli:ordinary")
assert heartbeat.read_text(encoding="utf-8") == "New checks"
request = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert any(row['role'] == 'tool' and "Wiki contains Private Marker" in row['content'] for row in request)
finally:
await loop.aclose()
@pytest.mark.parametrize("selection", ["explicit_empty", "disable_all", "default"])
async def test_turn_tool_selection_preserves_empty_registries(tmp_path, monkeypatch, selection) -> None:
monkeypatch.setattr("nanobot.agent.tools.loader.entry_points", lambda **kwargs: [])