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

+85 -139
View File
@@ -4,6 +4,7 @@ import asyncio
from types import SimpleNamespace
import pytest
from dulwich import porcelain
from nanobot.agent.memory import MemoryStore
from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -25,19 +26,20 @@ class _FakeStore:
git,
last_dream_cursor: int = 1,
dream_prompt_result=None,
content_diff: str = "",
):
self.git = git
self._last_dream_cursor = last_dream_cursor
self._dream_prompt_result = dream_prompt_result
self._content_diff = content_diff
self.compact_history_called = False
self.dream_lock = asyncio.Lock()
def get_last_dream_cursor(self) -> int:
return self._last_dream_cursor
def build_dream_prompt(self):
return self._dream_prompt_result
if self._dream_prompt_result and self._last_dream_cursor < self._dream_prompt_result[1]:
return self._dream_prompt_result
return None
def build_dream_tools(self):
return None
@@ -46,7 +48,7 @@ class _FakeStore:
self._last_dream_cursor = value
def dream_content_diff(self) -> str:
return self._content_diff
return ""
def compact_history(self) -> None:
self.compact_history_called = True
@@ -212,147 +214,36 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:
assert progress_sentinel not in completion.content
def _build_runnable_dream(
tmp_path,
*,
initialized: bool,
content_diff: str,
stop_reason: str = "completed",
tool_error: bool = False,
) -> tuple[CommandContext, _FakeStore]:
"""Build a /dream ctx whose run is driven by a canned stop reason + diff."""
msg = InboundMessage(channel="cli", sender_id="u1", chat_id="direct", content="/dream")
store = _FakeStore(
_FakeGit(initialized=initialized),
last_dream_cursor=5,
dream_prompt_result=("dream prompt", 42),
content_diff=content_diff,
)
@pytest.mark.parametrize("completed", [True, False])
async def test_dream_command_reports_outcome_and_versions_only_real_edits(tmp_path, completed) -> None:
ctx, bus = _make_dream_ctx(tmp_path)
store = MemoryStore(ctx.loop.sessions.workspace)
assert store.git.init()
versions = store.git.log()
cursor = store.append_history("A confirmed finding")
async def process_direct(*args, **kwargs):
if tool_error:
await kwargs["on_progress"](
"",
tool_events=[{
"phase": "error",
"name": "edit_file",
"error": "edit failed",
}],
)
async def process_direct(prompt, **kwargs):
if not completed:
store.write_memory("A partial update")
return OutboundMessage(
channel="cli",
chat_id="direct",
content="done",
metadata={"_stop_reason": stop_reason},
channel="cli", chat_id="direct", content="done",
metadata={"_stop_reason": "completed" if completed else "length"},
)
bus = _FakeBus()
loop = SimpleNamespace(
bus=bus,
context=SimpleNamespace(memory=store, timezone="UTC"),
sessions=_make_sessions(tmp_path),
process_direct=process_direct,
dream_runtime=lambda: None,
)
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)
return ctx, store
@pytest.mark.asyncio
async def test_dream_advances_cursor_when_diff_nonempty(tmp_path) -> None:
ctx, store = _build_runnable_dream(tmp_path, initialized=True, content_diff="SOUL.md: +1 -0")
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42
@pytest.mark.asyncio
async def test_dream_advances_cursor_on_completed_noop(tmp_path) -> None:
ctx, store = _build_runnable_dream(tmp_path, initialized=True, content_diff="")
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42
assert "no memory changes" in ctx.loop.bus.outbound[0].content
@pytest.mark.asyncio
async def test_dream_keeps_cursor_when_incomplete_with_diff(tmp_path) -> None:
ctx, store = _build_runnable_dream(
tmp_path,
initialized=True,
content_diff="SOUL.md: +1 -0",
stop_reason="length",
)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 5
assert "did not complete" in ctx.loop.bus.outbound[0].content
@pytest.mark.asyncio
async def test_dream_advances_cursor_when_completed_after_tool_error(tmp_path) -> None:
ctx, store = _build_runnable_dream(
tmp_path,
initialized=True,
content_diff="",
tool_error=True,
)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42
assert "no memory changes" in ctx.loop.bus.outbound[0].content
@pytest.mark.asyncio
async def test_dream_noop_batch_unlocks_following_history(tmp_path) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
store = MemoryStore(workspace)
store.write_soul("# Soul")
store.write_memory("# Memory")
for index in range(1, 22):
store.append_history(f"entry-{index:02d}")
store.git.init()
processed_prompts: list[str] = []
async def process_direct(prompt, *args, **kwargs):
processed_prompts.append(prompt)
return OutboundMessage(
channel="cli",
chat_id="direct",
content="done",
metadata={"_stop_reason": "completed"},
)
msg = InboundMessage(channel="cli", sender_id="u1", chat_id="direct", content="/dream")
bus = _FakeBus()
loop = SimpleNamespace(
bus=bus,
context=SimpleNamespace(memory=store, timezone="UTC"),
sessions=_make_sessions(tmp_path),
process_direct=process_direct,
dream_runtime=lambda: None,
)
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)
ctx.loop.context.memory = store
ctx.loop.process_direct = process_direct
ctx.loop.dream_runtime = lambda: None
await _run_dream_command(ctx)
assert len(processed_prompts) == 1
assert "entry-20" in processed_prompts[0]
assert "entry-21" not in processed_prompts[0]
assert store.get_last_dream_cursor() == 20
next_result = store.build_dream_prompt()
assert next_result is not None
next_prompt, next_cursor = next_result
assert next_cursor == 21
assert "entry-21" in next_prompt
assert "entry-01" not in next_prompt
@pytest.mark.asyncio
async def test_dream_non_git_falls_back_to_completion_gate(tmp_path) -> None:
ctx, store = _build_runnable_dream(
tmp_path, initialized=False, content_diff="", stop_reason="completed",
)
await _run_dream_command(ctx)
assert store._last_dream_cursor == 42
if completed:
assert "no memory changes" in bus.outbound[0].content
assert store.get_last_dream_cursor() == cursor
assert store.git.log() == versions
else:
assert "did not complete" in bus.outbound[0].content
assert store.get_last_dream_cursor() == 0
assert store.read_memory() == "A partial update"
assert store.git.log()[0] != versions[0]
@pytest.mark.asyncio
@@ -557,3 +448,58 @@ async def test_dream_restore_rejects_non_dream_commit_clearly() -> None:
assert "Only Dream memory versions can be restored." in out.content
assert "Use `/dream-restore` to list recent versions." in out.content
assert git.revert_calls == []
@pytest.mark.parametrize("dirty", ["untracked", "edited", "deleted", "staged", None])
async def test_dream_restore_preserves_uncommitted_memory(tmp_path, dirty) -> None:
store = MemoryStore(tmp_path)
assert store.git.init()
store.wiki_dir.mkdir()
page = store.wiki_dir / "known.md"
page.write_bytes(b"before\n")
store.write_memory("before")
store.set_last_dream_cursor(1)
assert store.git.auto_commit("dream: before")
page.write_bytes(b"current\n")
store.write_memory("current")
store.set_last_dream_cursor(2)
sha = store.git.auto_commit("dream: current")
assert sha
store.set_last_dream_cursor(3) # A no-op Dream does not create a commit.
draft = store.wiki_dir / "draft.md"
if dirty == "untracked":
draft.write_bytes(b"uncommitted draft\n")
elif dirty == "edited":
store.write_memory("user edit")
elif dirty == "deleted":
page.unlink()
elif dirty == "staged":
page.write_bytes(b"staged page\n")
porcelain.add(str(tmp_path), paths=[str(page)])
page.write_bytes(b"current\n") # Only the index differs from HEAD.
msg = InboundMessage(channel="cli", sender_id="u1", chat_id="direct", content=f"/dream-restore {sha}")
loop = SimpleNamespace(consolidator=SimpleNamespace(store=store))
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw=msg.content, args=sha, loop=loop)
out = await cmd_dream_restore(ctx)
if dirty is None:
assert "Restored Dream memory" in out.content
assert store.read_memory() == "before"
assert store.get_last_dream_cursor() == 1
assert page.read_bytes() == b"before\n"
else:
assert "Couldn't restore" in out.content
assert "Commit or undo your changes" in out.content
assert store.git.log()[0].sha == sha
assert store.get_last_dream_cursor() == 3
assert store.read_memory() == ("user edit" if dirty == "edited" else "current")
if dirty == "deleted":
assert not page.exists()
else:
assert page.read_bytes() == b"current\n"
if dirty == "untracked":
assert draft.read_bytes() == b"uncommitted draft\n"
if dirty == "staged":
assert porcelain.get_tree_changes(str(tmp_path))["modify"] == [b"memory/wiki/known.md"]
+4 -3
View File
@@ -194,10 +194,11 @@ async def test_compacted_session_waits_for_new_input_without_continuation(
assert response.content == "Hello!"
loop.provider.chat_stream_with_retry.assert_awaited_once()
sent = loop.provider.chat_stream_with_retry.call_args.kwargs["messages"]
expected_summary = reloaded.metadata["_last_summary"] if summary != "(nothing)" else None
assert sent[0]["role"] == "system"
assert sent[0]["content"] == loop.context.build_system_prompt(channel="cli", session_summary=expected_summary)
assert [message["role"] for message in sent] == ["system", "user"]
expected_summary = reloaded.metadata["_last_summary"] if summary != "(nothing)" else None
assert sent[0]["content"] == loop.context.build_system_prompt(
channel="cli", session_summary=expected_summary, has_cron=False,
)
assert sent[1]["content"].startswith("hi\n\n")
assert "File access: no workspace restriction." in sent[1]["content"]