feat(memory): add progressive wiki and drain Dream history (#4477)
This commit is contained in:
1 parent
9ccf3b6214
commit
74d070f699
40 files changed
+1513
-738
No files matched your search
@@ -1509,6 +1509,7 @@ class TestCompactIdleSession:
|
||||
current_message="next project question",
|
||||
channel="websocket",
|
||||
workspace=project,
|
||||
has_cron=False,
|
||||
)
|
||||
|
||||
await loop.consolidator.compact_idle_session(
|
||||
|
||||
@@ -127,6 +127,23 @@ class TestLoadBootstrapFiles:
|
||||
assert "project soul collision" not in result
|
||||
assert "project user collision" not in result
|
||||
|
||||
def test_resident_memory_keeps_navigation_without_loading_wiki_pages(self, tmp_path):
|
||||
builder = _builder(tmp_path)
|
||||
builder.memory.write_soul("Always verify corrections.")
|
||||
builder.memory.write_user("Prefer concise Chinese replies.")
|
||||
builder.memory.write_memory("Deployment details: [Wiki](wiki/index.md).")
|
||||
builder.memory.wiki_dir.mkdir()
|
||||
(builder.memory.wiki_dir / "index.md").write_text(
|
||||
"Detailed deployment uses region-west.\n", encoding="utf-8",
|
||||
)
|
||||
|
||||
prompt = builder.build_system_prompt()
|
||||
|
||||
assert "Always verify corrections." in prompt
|
||||
assert "Prefer concise Chinese replies." in prompt
|
||||
assert "Deployment details: [Wiki](wiki/index.md)." in prompt
|
||||
assert "Detailed deployment uses region-west." not in prompt
|
||||
|
||||
def test_selected_project_without_agents_does_not_fall_back(self, tmp_path):
|
||||
agent_home = tmp_path / "agent-home"
|
||||
project = tmp_path / "project"
|
||||
@@ -268,14 +285,11 @@ class TestBuildSystemPrompt:
|
||||
result = builder.build_system_prompt()
|
||||
|
||||
assert "## Runtime\n" in result
|
||||
assert "Agent profile: SOUL.md and USER.md" in result
|
||||
assert "History log: memory/history.jsonl" in result
|
||||
|
||||
def test_default_identity_uses_relative_agent_paths(self, tmp_path):
|
||||
result = ContextBuilder(tmp_path)._get_identity()
|
||||
|
||||
assert "Agent profile: SOUL.md and USER.md" in result
|
||||
assert "History log: memory/history.jsonl" in result
|
||||
assert "`memory/wiki/index.md` in the agent workspace" in result
|
||||
assert "Custom skills: skills/{skill-name}/SKILL.md" in result
|
||||
|
||||
def test_selected_project_identity_keeps_agent_data_in_agent_workspace(self, tmp_path):
|
||||
@@ -287,7 +301,7 @@ class TestBuildSystemPrompt:
|
||||
result = ContextBuilder(agent_home)._get_identity(workspace=project)
|
||||
|
||||
assert f"agent workspace is at: {agent_home.resolve()}" in result
|
||||
assert f"{agent_home.resolve()}/SOUL.md" in result
|
||||
assert "`memory/wiki/index.md` in the agent workspace" in result
|
||||
assert f"Custom skills: {agent_home.resolve()}/skills/" in result
|
||||
|
||||
def test_includes_bootstrap_files(self, tmp_path):
|
||||
|
||||
@@ -69,22 +69,6 @@ def test_selected_project_path_follows_shared_cache_prefix(tmp_path) -> None:
|
||||
assert prompt_a == builder.build_system_prompt(workspace=project_a)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selected_project", [False, True])
|
||||
def test_system_prompt_reflects_current_dream_memory_contract(tmp_path, selected_project) -> None:
|
||||
workspace = _make_workspace(tmp_path)
|
||||
builder = ContextBuilder(workspace)
|
||||
project = tmp_path / "project" if selected_project else workspace
|
||||
project.mkdir(exist_ok=True)
|
||||
|
||||
prompt = builder.build_system_prompt(workspace=project)
|
||||
|
||||
assert "memory/history.jsonl" in prompt
|
||||
assert (
|
||||
"Only Dream memory-consolidation tasks may edit the profile and long-term memory files "
|
||||
"listed above."
|
||||
) in prompt
|
||||
|
||||
|
||||
def test_provider_context_appended_after_user_content(tmp_path) -> None:
|
||||
workspace = _make_workspace(tmp_path)
|
||||
builder = ContextBuilder(workspace)
|
||||
@@ -152,14 +136,12 @@ def test_scheduling_contract_reaches_fresh_and_legacy_workspaces(tmp_path, legac
|
||||
messages = builder.build_messages(history=[], current_message="每天早上8点提醒我喝水")
|
||||
system = messages[0]["content"]
|
||||
|
||||
assert '"Every day at 8am, remind me to drink water" is a cron task, not a heartbeat task.' in system
|
||||
assert "Heartbeat does not guarantee a requested time or interval." in system
|
||||
assert "background checks with flexible timing" in system
|
||||
assert system.count("## Scheduling") == 1
|
||||
assert "Use `cron` for a specified time or interval, even if it repeats" in system
|
||||
assert "Use `HEARTBEAT.md` only for flexible checks" in system
|
||||
if legacy_workspace:
|
||||
assert "Reply in Chinese." in system
|
||||
assert system.index(legacy_rule) < system.index("## Scheduling")
|
||||
assert "even if workspace guidance describes recurring tasks as heartbeat tasks" in system
|
||||
assert "Do not substitute heartbeat for an explicit schedule" in system
|
||||
else:
|
||||
assert "## AGENTS.md" not in system
|
||||
assert "每天早上8点提醒我喝水" in messages[-1]["content"]
|
||||
@@ -222,16 +204,15 @@ def test_build_messages_passes_channel_to_system_prompt(tmp_path) -> None:
|
||||
assert "messaging app" in system
|
||||
|
||||
|
||||
def test_memory_skill_is_lazy_loaded_from_skills_index(tmp_path) -> None:
|
||||
workspace = _make_workspace(tmp_path)
|
||||
builder = ContextBuilder(workspace)
|
||||
@pytest.mark.parametrize("disabled", [False, True])
|
||||
def test_memory_skill_is_discoverable_and_lazy_only_when_enabled(tmp_path, disabled) -> None:
|
||||
builder = ContextBuilder(_make_workspace(tmp_path), disabled_skills=["memory"] if disabled else None)
|
||||
system, user = builder.build_messages(history=[], current_message="$memory Find the decision")
|
||||
|
||||
prompt = builder.build_system_prompt()
|
||||
|
||||
assert "### Skill: memory" not in prompt
|
||||
assert "**memory**" in prompt
|
||||
assert "Search Past Events" not in prompt
|
||||
assert "Examples (replace `keyword`)" not in prompt
|
||||
assert "memory/wiki/index.md" in system["content"]
|
||||
assert ("**memory**" in system["content"]) is not disabled
|
||||
assert "Search Past Events" not in system["content"]
|
||||
assert ("Search Past Events" in user["content"]) is not disabled
|
||||
|
||||
|
||||
def test_fresh_workspace_omits_default_prompt_scaffolding(tmp_path) -> None:
|
||||
@@ -257,7 +238,6 @@ def test_template_memory_md_is_skipped(tmp_path) -> None:
|
||||
prompt = builder.build_system_prompt()
|
||||
|
||||
assert "# Long-term Memory" not in prompt
|
||||
assert "History log: memory/history.jsonl" in prompt
|
||||
assert "This file is automatically updated by nanobot" not in prompt
|
||||
|
||||
|
||||
|
||||
+64
-167
@@ -23,32 +23,6 @@ class TestBuildDreamPrompt:
|
||||
def test_returns_none_when_no_history(self, store):
|
||||
assert store.build_dream_prompt() is None
|
||||
|
||||
def test_returns_prompt_with_history(self, store):
|
||||
store.append_history("hello")
|
||||
result = store.build_dream_prompt()
|
||||
assert result is not None
|
||||
prompt, cursor = result
|
||||
assert cursor > 0
|
||||
assert "## Conversation History" in prompt
|
||||
assert "hello" in prompt
|
||||
|
||||
def test_cursor_advances_only_new_entries(self, store):
|
||||
store.append_history("first")
|
||||
r1 = store.build_dream_prompt()
|
||||
assert r1 is not None
|
||||
_, c1 = r1
|
||||
|
||||
assert store.build_dream_prompt() is not None
|
||||
|
||||
store.set_last_dream_cursor(c1)
|
||||
assert store.build_dream_prompt() is None
|
||||
|
||||
store.append_history("second")
|
||||
r2 = store.build_dream_prompt()
|
||||
assert r2 is not None
|
||||
_, c2 = r2
|
||||
assert c2 > c1
|
||||
|
||||
def test_prompt_includes_skill_creator_path(self, store):
|
||||
store.append_history("test")
|
||||
result = store.build_dream_prompt()
|
||||
@@ -56,15 +30,6 @@ class TestBuildDreamPrompt:
|
||||
prompt, _ = result
|
||||
assert "skill-creator" in prompt
|
||||
|
||||
def test_prompt_does_not_duplicate_current_memory_file_contents(self, store):
|
||||
store.append_history("hello")
|
||||
result = store.build_dream_prompt()
|
||||
assert result is not None
|
||||
prompt, _ = result
|
||||
assert "## Current Memory Files" not in prompt
|
||||
assert "Project X active" not in prompt
|
||||
assert "Helpful" not in prompt
|
||||
|
||||
def test_workspace_dream_prompt_overrides_default(self, store):
|
||||
store.dream_prompt_file.parent.mkdir(parents=True)
|
||||
store.dream_prompt_file.write_text(
|
||||
@@ -79,7 +44,8 @@ class TestBuildDreamPrompt:
|
||||
prompt, _ = result
|
||||
assert prompt.startswith("Custom Dream prompt.")
|
||||
assert "## Conversation History" in prompt
|
||||
assert "keep this fact" in prompt
|
||||
assert f"History file: {store.history_file.resolve()}" in prompt
|
||||
assert "Read lines 1-1" in prompt
|
||||
|
||||
def test_workspace_dream_prompt_override_is_capped(self, store):
|
||||
store.dream_prompt_file.parent.mkdir(parents=True)
|
||||
@@ -93,7 +59,7 @@ class TestBuildDreamPrompt:
|
||||
assert "x" * 40_000 not in prompt
|
||||
assert "... (truncated)" in prompt
|
||||
assert "## Conversation History" in prompt
|
||||
assert "keep this fact" in prompt
|
||||
assert "Read lines 1-1" in prompt
|
||||
|
||||
def test_empty_workspace_dream_prompt_uses_default(self, store):
|
||||
store.dream_prompt_file.parent.mkdir(parents=True)
|
||||
@@ -106,40 +72,28 @@ class TestBuildDreamPrompt:
|
||||
prompt, _ = result
|
||||
assert prompt.startswith(store.default_dream_prompt() + "\n\n## Conversation History\n")
|
||||
|
||||
def test_truncates_long_entries_at_1000_chars(self, store):
|
||||
long_content = "x" * 2000
|
||||
store.append_history(long_content)
|
||||
result = store.build_dream_prompt()
|
||||
assert result is not None
|
||||
prompt, _ = result
|
||||
assert long_content not in prompt
|
||||
assert "x" * 1000 in prompt
|
||||
assert "x" * 1001 not in prompt
|
||||
|
||||
def test_batches_oldest_unprocessed_entries_first(self, store):
|
||||
for i in range(25):
|
||||
def test_range_covers_all_pending_records_after_history_retention(self, store):
|
||||
for i in range(35):
|
||||
store.append_history(f"entry-{i + 1:02d}")
|
||||
store.set_last_dream_cursor(10)
|
||||
store.max_history_entries = 30
|
||||
store.compact_history()
|
||||
|
||||
result = store.build_dream_prompt(max_entries=20)
|
||||
result = store.build_dream_prompt()
|
||||
assert result is not None
|
||||
prompt, cursor = result
|
||||
|
||||
assert cursor == 20
|
||||
assert "entry-01" in prompt
|
||||
assert "entry-20" in prompt
|
||||
assert "entry-21" not in prompt
|
||||
|
||||
assert cursor == 35
|
||||
assert "Read lines 6-30 (inclusive): 25 pending records" in prompt
|
||||
assert "10 < cursor <= 35" in prompt
|
||||
assert store.get_last_dream_cursor() == 10
|
||||
store.set_last_dream_cursor(cursor)
|
||||
next_result = store.build_dream_prompt(max_entries=20)
|
||||
assert next_result is not None
|
||||
next_prompt, next_cursor = next_result
|
||||
assert next_cursor == 25
|
||||
assert "entry-21" in next_prompt
|
||||
assert "entry-25" in next_prompt
|
||||
assert store.build_dream_prompt() is None
|
||||
|
||||
def test_skips_malformed_history_entries(self, store):
|
||||
store.history_file.write_text(
|
||||
'{"cursor": 1, "timestamp": "2026-04-01 10:00"}\n'
|
||||
'\nnot-json\n'
|
||||
'{"cursor": 2, "timestamp": "2026-04-01 10:01", "content": "usable memory"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
@@ -149,7 +103,20 @@ class TestBuildDreamPrompt:
|
||||
assert result is not None
|
||||
prompt, cursor = result
|
||||
assert cursor == 2
|
||||
assert "usable memory" in prompt
|
||||
assert "Read lines 4-4 (inclusive): 1 pending records" in prompt
|
||||
|
||||
async def test_history_range_counts_unicode_separators_as_read_file_lines(self, store):
|
||||
store.append_history("old\u2028record")
|
||||
store.set_last_dream_cursor(1)
|
||||
store.append_history("new\u2028record")
|
||||
prompt, cursor = store.build_dream_prompt()
|
||||
assert "Read lines 3-4" in prompt
|
||||
assert cursor == 2
|
||||
result = await store.build_dream_tools().execute("read_file", {
|
||||
"path": str(store.history_file), "offset": 3, "limit": 2,
|
||||
})
|
||||
assert '"cursor": 2' in result
|
||||
assert '4| record"}' in result
|
||||
|
||||
def test_dream_prompt_consumes_consolidator_attribute_tags(self):
|
||||
prompt = render_template(
|
||||
@@ -243,6 +210,23 @@ class TestDreamTools:
|
||||
assert "Precise" in store.soul_file.read_text(encoding="utf-8")
|
||||
assert "**Name**: Ada" in store.user_file.read_text(encoding="utf-8")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dream_can_create_and_update_wiki_pages(self, store):
|
||||
tools = store.build_dream_tools()
|
||||
path = "memory/wiki/projects/example.md"
|
||||
assert "Successfully wrote" in await tools.execute(
|
||||
"write_file", {"path": path, "content": "# Example\nRegion east\n"},
|
||||
)
|
||||
assert "Region east" in await tools.execute("read_file", {"path": path})
|
||||
assert "Patch applied" in await tools.execute("apply_patch", {"edits": [{
|
||||
"path": path, "action": "replace", "old_text": "Region east", "new_text": "Region west",
|
||||
}]})
|
||||
await tools.execute("read_file", {"path": path})
|
||||
assert "Patch applied" in await tools.execute("edit_file", {
|
||||
"path": path, "old_text": "Region west", "new_text": "Region north",
|
||||
})
|
||||
assert "Region north" in (store.workspace / path).read_text(encoding="utf-8")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dream_can_write_workspace_skills(self, store):
|
||||
tools = store.build_dream_tools()
|
||||
@@ -420,6 +404,24 @@ class TestEphemeralDirect:
|
||||
assert loop.model == "test-model"
|
||||
assert loop.model_preset is None
|
||||
|
||||
async def test_dream_stays_pending_when_initial_request_cannot_fit(self, _make_loop):
|
||||
from nanobot.agent.dream import run_dream
|
||||
|
||||
loop, _ = _make_loop
|
||||
store = loop.context.memory
|
||||
checkpoint = "[durable] Project knowledge.\n" * 500 + "TAIL: current decision"
|
||||
cursor = store.append_history(checkpoint)
|
||||
loop.provider.estimate_prompt_tokens.return_value = (100_000, "test-provider")
|
||||
|
||||
result = await run_dream(loop, commit_prefix="dream: manual run")
|
||||
|
||||
assert result.error and "context budget" in result.error
|
||||
assert store.get_last_dream_cursor() == 0
|
||||
assert store.read_unprocessed_history(0)[0]["cursor"] == cursor
|
||||
measured = loop.provider.estimate_prompt_tokens.call_args.args[0]
|
||||
assert any("Read lines 1-1" in str(message.get("content")) for message in measured)
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
|
||||
async def test_ephemeral_skips_raw_archive(self, tmp_path, _make_loop):
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -574,111 +576,6 @@ class TestEphemeralDirect:
|
||||
tool_result = next(message for message in second_request if message["role"] == "tool")
|
||||
assert "Error" in tool_result["content"]
|
||||
|
||||
async def test_dream_turn_can_skip_unbatched_recent_history(self, tmp_path):
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
store = MemoryStore(tmp_path)
|
||||
for i in range(60):
|
||||
store.append_history(f"entry-{i + 1:02d}")
|
||||
|
||||
result = store.build_dream_prompt(max_entries=20)
|
||||
assert result is not None
|
||||
prompt, cursor = result
|
||||
assert cursor == 20
|
||||
|
||||
captured: dict[str, list[dict]] = {}
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.supports_tools = True
|
||||
provider.generation = MagicMock(max_tokens=4096)
|
||||
|
||||
async def chat_stream_with_retry(**kwargs):
|
||||
captured["messages"] = kwargs["messages"]
|
||||
return LLMResponse(content="done", finish_reason="stop")
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
loop = AgentLoop(
|
||||
bus=MessageBus(),
|
||||
provider=provider,
|
||||
workspace=tmp_path,
|
||||
context_window_tokens=32_000,
|
||||
)
|
||||
|
||||
await loop.process_direct(
|
||||
prompt,
|
||||
session_key="dream:test",
|
||||
ephemeral=True,
|
||||
tools=store.build_dream_tools(),
|
||||
)
|
||||
|
||||
messages = captured["messages"]
|
||||
system_prompt = messages[0]["content"]
|
||||
request_text = "\n".join(str(message.get("content", "")) for message in messages)
|
||||
assert "# Recent History" not in system_prompt
|
||||
assert "entry-01" in request_text
|
||||
assert "entry-20" in request_text
|
||||
assert "entry-21" not in request_text
|
||||
assert "entry-60" not in request_text
|
||||
|
||||
async def test_dream_turn_injects_memory_files_once_and_persists_session(self, tmp_path):
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
markers = {
|
||||
"SOUL.md": "DREAM_SOUL_MARKER",
|
||||
"USER.md": "DREAM_USER_MARKER",
|
||||
"memory/MEMORY.md": "DREAM_MEMORY_MARKER",
|
||||
}
|
||||
store = MemoryStore(tmp_path)
|
||||
store.write_soul(markers["SOUL.md"])
|
||||
store.write_user(markers["USER.md"])
|
||||
store.write_memory(markers["memory/MEMORY.md"])
|
||||
store.append_history("history-marker")
|
||||
(tmp_path / "AGENTS.md").write_text("DREAM_AGENTS_MARKER", encoding="utf-8")
|
||||
|
||||
result = store.build_dream_prompt()
|
||||
assert result is not None
|
||||
prompt, _ = result
|
||||
|
||||
captured: dict[str, list[dict]] = {}
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.supports_tools = True
|
||||
provider.generation = MagicMock(max_tokens=4096)
|
||||
|
||||
async def chat_stream_with_retry(**kwargs):
|
||||
captured["messages"] = kwargs["messages"]
|
||||
return LLMResponse(content="done", finish_reason="stop")
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
loop = AgentLoop(
|
||||
bus=MessageBus(),
|
||||
provider=provider,
|
||||
workspace=tmp_path,
|
||||
context_window_tokens=32_000,
|
||||
)
|
||||
session_key = "dream:single-memory-copy"
|
||||
|
||||
await loop.process_direct(
|
||||
prompt,
|
||||
session_key=session_key,
|
||||
ephemeral=True,
|
||||
tools=store.build_dream_tools(),
|
||||
)
|
||||
|
||||
messages = captured["messages"]
|
||||
system_prompt = str(messages[0]["content"])
|
||||
request_text = "\n".join(str(message.get("content", "")) for message in messages)
|
||||
for marker in [*markers.values(), "DREAM_AGENTS_MARKER"]:
|
||||
assert marker in system_prompt
|
||||
assert request_text.count(marker) == 1
|
||||
assert loop.sessions.read_session_snapshot(session_key) is not None
|
||||
|
||||
|
||||
class TestEphemeralHooks:
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.dream import run_dream
|
||||
from nanobot.agent.memory import MemoryStore
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
|
||||
|
||||
def response(reason="completed"):
|
||||
return OutboundMessage(
|
||||
channel="cli", chat_id="dream", content="done", metadata={"_stop_reason": reason},
|
||||
)
|
||||
|
||||
|
||||
def loop_for(store, process):
|
||||
return SimpleNamespace(
|
||||
context=SimpleNamespace(memory=store),
|
||||
sessions=SimpleNamespace(state=SimpleNamespace(prune_dream_sessions=AsyncMock())),
|
||||
dream_runtime=lambda: None,
|
||||
process_direct=process,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_dream_reads_full_pages_and_defers_new_history(tmp_path):
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.supports_tools = True
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (200_000, "test-provider")
|
||||
loop = AgentLoop(
|
||||
bus=MessageBus(), provider=provider, workspace=tmp_path,
|
||||
context_window_tokens=512_000,
|
||||
)
|
||||
store = loop.context.memory
|
||||
markers = ("DREAM_SOUL_MARKER", "DREAM_USER_MARKER", "DREAM_MEMORY_MARKER", "DREAM_AGENTS_MARKER")
|
||||
store.write_soul(markers[0])
|
||||
store.write_user(markers[1])
|
||||
store.write_memory(markers[2])
|
||||
(tmp_path / "AGENTS.md").write_text(markers[3], encoding="utf-8")
|
||||
store.git.init()
|
||||
checkpoints = ["Project knowledge. " * 3000 + f"TAIL-{i}" for i in range(3)]
|
||||
for checkpoint in checkpoints:
|
||||
store.append_history(checkpoint)
|
||||
for index in range(23):
|
||||
store.append_history(f"queued record {index}")
|
||||
model_calls = 0
|
||||
read_records = []
|
||||
|
||||
def call(name, **arguments):
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id=f"call-{model_calls}", name=name, arguments=arguments,
|
||||
)], finish_reason="tool_calls")
|
||||
|
||||
def collect_read(messages):
|
||||
text = next(message["content"] for message in reversed(messages) if message["role"] == "tool")
|
||||
for line in text.splitlines():
|
||||
number, separator, encoded = line.partition("| ")
|
||||
if separator and number.isdigit():
|
||||
read_records.append(json.loads(encoded))
|
||||
|
||||
async def chat(**kwargs):
|
||||
nonlocal model_calls
|
||||
model_calls += 1
|
||||
messages = kwargs["messages"]
|
||||
assert store.get_last_dream_cursor() == 0
|
||||
if model_calls == 1:
|
||||
task = messages[-1]["content"]
|
||||
assert str(store.history_file.resolve()) in task
|
||||
assert "Read lines 1-26" in task and "0 < cursor <= 26" in task
|
||||
request = "\n".join(str(message.get("content", "")) for message in messages)
|
||||
for marker in markers:
|
||||
assert marker in messages[0]["content"] and request.count(marker) == 1
|
||||
assert "TAIL-0" not in request and "queued record 22" not in request
|
||||
store.append_history("Arrived while Dream was running")
|
||||
return call("read_file", path=str(store.history_file), offset=1, limit=26)
|
||||
if model_calls == 2:
|
||||
collect_read(messages)
|
||||
assert [entry["content"] for entry in read_records] == checkpoints[:2]
|
||||
return call("read_file", path=str(store.history_file), offset=3, limit=24)
|
||||
if model_calls == 3:
|
||||
collect_read(messages)
|
||||
assert [entry["cursor"] for entry in read_records] == list(range(1, 27))
|
||||
assert read_records[2]["content"] == checkpoints[2]
|
||||
assert read_records[-1]["content"] == "queued record 22"
|
||||
return call("write_file", path=str(store.wiki_dir / "index.md"), content="# Wiki\nCurrent knowledge")
|
||||
return LLMResponse(content="History range consolidated.")
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
|
||||
try:
|
||||
result = await run_dream(loop, commit_prefix="dream: periodic memory consolidation")
|
||||
assert result.error is None
|
||||
assert model_calls == 4
|
||||
assert store.get_last_dream_cursor() == 26
|
||||
assert result.commit_sha
|
||||
commit, diff = store.git.show_commit_diff(result.commit_sha)
|
||||
assert commit.message.startswith("dream: periodic memory consolidation\n\n")
|
||||
assert "memory/wiki/index.md" in diff and "Current knowledge" in commit.message
|
||||
assert ".dream_cursor" not in commit.message
|
||||
assert (store.wiki_dir / "index.md").read_text(encoding="utf-8") == "# Wiki\nCurrent knowledge"
|
||||
sessions = await loop.sessions.state.list_sessions()
|
||||
assert len(sessions) == 1
|
||||
assert loop.sessions.read_session_snapshot(sessions[0]["key"]) is not None
|
||||
next_prompt, next_cursor = store.build_dream_prompt()
|
||||
assert "Read lines 27-27" in next_prompt
|
||||
assert next_cursor == 27
|
||||
finally:
|
||||
await loop.sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failure", ["length", "exception"])
|
||||
async def test_failed_task_keeps_entire_range_pending_after_restart(tmp_path, failure):
|
||||
store = MemoryStore(tmp_path, max_history_entries=5)
|
||||
store.git.init()
|
||||
for index in range(25):
|
||||
store.append_history(f"record-{index:02d}")
|
||||
|
||||
async def process(prompt, **kwargs):
|
||||
assert "Read lines 1-25" in prompt
|
||||
store.write_memory("# Memory\nPartial update")
|
||||
if failure == "exception":
|
||||
raise RuntimeError("Provider unavailable")
|
||||
return response(failure)
|
||||
|
||||
result = await run_dream(loop_for(store, process), commit_prefix="dream: manual run")
|
||||
assert result.error
|
||||
assert store.get_last_dream_cursor() == 0
|
||||
assert len(store.read_unprocessed_history(0)) == 25
|
||||
assert result.commit_sha
|
||||
assert store.read_memory() == "# Memory\nPartial update"
|
||||
|
||||
restarted = MemoryStore(tmp_path)
|
||||
resumed = []
|
||||
|
||||
async def finish(prompt, **kwargs):
|
||||
resumed.append(prompt)
|
||||
return response()
|
||||
|
||||
result = await run_dream(loop_for(restarted, finish), commit_prefix="dream: manual run")
|
||||
assert result.error is None
|
||||
assert restarted.get_last_dream_cursor() == 25
|
||||
assert len(resumed) == 1
|
||||
assert "Read lines 1-25" in resumed[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_overlapping_manual_and_periodic_runs_do_not_repeat_history(tmp_path):
|
||||
store = MemoryStore(tmp_path)
|
||||
store.append_history("One pending record")
|
||||
entered, release, second_started = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
||||
calls = []
|
||||
|
||||
async def process(prompt, **kwargs):
|
||||
calls.append(prompt)
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return response()
|
||||
|
||||
loop = loop_for(store, process)
|
||||
first = asyncio.create_task(run_dream(loop, commit_prefix="dream: periodic memory consolidation"))
|
||||
await entered.wait()
|
||||
|
||||
async def manual():
|
||||
second_started.set()
|
||||
return await run_dream(loop, commit_prefix="dream: manual run")
|
||||
|
||||
second = asyncio.create_task(manual())
|
||||
try:
|
||||
await second_started.wait()
|
||||
assert len(calls) == 1
|
||||
finally:
|
||||
release.set()
|
||||
outcomes = await asyncio.gather(first, second)
|
||||
assert len(calls) == 1
|
||||
assert all(outcome.error is None for outcome in outcomes)
|
||||
assert [outcome.had_input for outcome in outcomes] == [True, False]
|
||||
assert store.get_last_dream_cursor() == 1
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
from nanobot.agent.memory import MemoryStore
|
||||
@@ -9,13 +9,13 @@ class TestDreamSessionKey:
|
||||
def test_contains_timestamp(self):
|
||||
key = MemoryStore.dream_session_key()
|
||||
assert key.startswith("dream:")
|
||||
ts_part = key.split(":", 1)[1]
|
||||
ts_part = key.split(":", 1)[1].rsplit("-", 1)[0]
|
||||
datetime.strptime(ts_part, "%Y%m%d-%H%M%S")
|
||||
|
||||
def test_unique_across_calls(self):
|
||||
now = datetime(2026, 5, 28, 10, 0, 0)
|
||||
with patch("nanobot.agent.memory.datetime") as mock_dt:
|
||||
mock_dt.now.side_effect = [now, now + timedelta(seconds=1)]
|
||||
mock_dt.now.return_value = now
|
||||
k1 = MemoryStore.dream_session_key()
|
||||
k2 = MemoryStore.dream_session_key()
|
||||
|
||||
|
||||
@@ -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: [])
|
||||
|
||||
@@ -7,6 +7,7 @@ import pytest
|
||||
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.context import (
|
||||
RequestContext,
|
||||
bind_request_context,
|
||||
@@ -22,9 +23,10 @@ from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
from nanobot.session.turn_continuation import INTERNAL_CONTINUATION_META
|
||||
|
||||
|
||||
class _ContextRecordingTool:
|
||||
class _ContextRecordingTool(Tool):
|
||||
name = "cron"
|
||||
concurrency_safe = False
|
||||
description = "Record the active request context."
|
||||
parameters = {"type": "object", "properties": {"action": {"type": "string"}}}
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.contexts: list[dict] = []
|
||||
@@ -43,24 +45,6 @@ class _ContextRecordingTool:
|
||||
return "created"
|
||||
|
||||
|
||||
class _Tools:
|
||||
def __init__(self, tool: _ContextRecordingTool) -> None:
|
||||
self.tool = tool
|
||||
|
||||
@property
|
||||
def tool_names(self) -> list[str]:
|
||||
return ["cron"]
|
||||
|
||||
def get(self, name: str):
|
||||
return self.tool if name == "cron" else None
|
||||
|
||||
def get_definitions(self) -> list:
|
||||
return []
|
||||
|
||||
def prepare_call(self, name: str, arguments: dict):
|
||||
return (self.tool, arguments, None) if name == "cron" else (None, arguments, None)
|
||||
|
||||
|
||||
def test_loop_registers_default_tools_in_injected_registry(tmp_path: Path) -> None:
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
@@ -152,7 +136,7 @@ async def test_loop_binds_request_context_for_tool_execution(tmp_path: Path) ->
|
||||
model="test-model",
|
||||
)
|
||||
cron = _ContextRecordingTool()
|
||||
loop.tools = _Tools(cron)
|
||||
loop.tools.register(cron)
|
||||
|
||||
metadata = {"slack": {"thread_ts": "111.222", "channel_type": "channel"}}
|
||||
runtime = loop.llm_runtime()
|
||||
|
||||
@@ -5,6 +5,8 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.memory import _HISTORY_ENTRY_HARD_CAP, MemoryStore
|
||||
from nanobot.utils.gitstore import GitStore
|
||||
from nanobot.utils.helpers import sync_workspace_templates
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -291,18 +293,24 @@ class TestDreamCursor:
|
||||
store2 = MemoryStore(store.workspace)
|
||||
assert store2.get_last_dream_cursor() == 3
|
||||
|
||||
def test_git_restore_rolls_back_dream_cursor(self, tmp_path):
|
||||
@pytest.mark.parametrize("existing_repo", [False, True], ids=["new-workspace", "existing-workspace"])
|
||||
def test_git_restore_rolls_back_dream_cursor(self, tmp_path, existing_repo):
|
||||
store = MemoryStore(tmp_path)
|
||||
store.write_memory("before")
|
||||
store.set_last_dream_cursor(1)
|
||||
assert store.git.init() is True
|
||||
if existing_repo:
|
||||
# Workspaces initialized before the fix ignore the runtime cursor.
|
||||
old_git = GitStore(tmp_path, tracked_files=["memory/MEMORY.md"], tracked_dirs=["memory/wiki"])
|
||||
assert old_git.init()
|
||||
assert store.git.auto_commit("dream: save first cursor checkpoint")
|
||||
else:
|
||||
sync_workspace_templates(tmp_path, silent=True)
|
||||
|
||||
store.write_memory("after")
|
||||
store.set_last_dream_cursor(2)
|
||||
dream_sha = store.git.auto_commit("dream: update")
|
||||
assert dream_sha is not None
|
||||
|
||||
store.write_memory("newer")
|
||||
store.set_last_dream_cursor(3)
|
||||
|
||||
restore_sha = store.git.revert(dream_sha)
|
||||
|
||||
@@ -369,13 +369,6 @@ def test_build_skills_summary_keeps_absolute_roots_for_selected_project(tmp_path
|
||||
assert str(project.resolve()) not in summary
|
||||
|
||||
|
||||
def test_bundled_memory_skill_uses_agent_owned_path(tmp_path: Path) -> None:
|
||||
memory = SkillsLoader(tmp_path).load_skill("memory")
|
||||
|
||||
assert memory is not None
|
||||
assert "`History log` path from the system prompt" in memory
|
||||
|
||||
|
||||
def test_disabled_skills_excluded_from_get_always_skills(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "ws"
|
||||
ws_skills = workspace / "skills"
|
||||
|
||||
@@ -168,6 +168,8 @@ def test_subagent_prompt_keeps_agent_paths_for_selected_project(tmp_path):
|
||||
assert str(project.resolve()) not in prompt
|
||||
assert f"Nanobot's agent workspace: {agent_workspace.resolve()}" in prompt
|
||||
assert f"History log: {agent_workspace.resolve() / 'memory' / 'history.jsonl'}" in prompt
|
||||
assert f"Memory wiki: {agent_workspace.resolve()}/memory/wiki/" in prompt
|
||||
assert "Update durable memory only if the main agent assigns that work" in prompt
|
||||
assert "global-custom" in prompt
|
||||
assert "project-custom" not in prompt
|
||||
|
||||
@@ -187,6 +189,7 @@ def test_subagent_prompt_uses_relative_paths_in_agent_workspace(tmp_path):
|
||||
|
||||
assert str(tmp_path.resolve()) not in prompt
|
||||
assert "History log: memory/history.jsonl" in prompt
|
||||
assert "Memory wiki: memory/wiki/" in prompt
|
||||
assert "### Workspace skills (`skills`)" in prompt
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
@@ -109,6 +112,42 @@ async def _wait_for_background_callbacks(loop) -> None:
|
||||
|
||||
|
||||
class TestBackgroundTaskTracking:
|
||||
def test_shutdown_drains_completed_task_before_its_callback(self, tmp_path):
|
||||
# A busy loop cannot be bounded by an asyncio timeout in the same loop.
|
||||
script = """
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
async def main():
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
agent = AgentLoop(bus=MessageBus(), provider=provider, workspace=Path(sys.argv[1]))
|
||||
|
||||
async def finish():
|
||||
return
|
||||
|
||||
agent.schedule_background(finish())
|
||||
task = next(iter(agent._background_tasks))
|
||||
await asyncio.sleep(0)
|
||||
assert task.done() and task in agent._background_tasks
|
||||
await agent.aclose()
|
||||
assert not agent._background_tasks
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script, str(tmp_path)],
|
||||
cwd=Path(__file__).resolve().parents[2],
|
||||
capture_output=True, text=True, timeout=15,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
|
||||
)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_background_task_is_removed(self, monkeypatch):
|
||||
loop, _bus = _make_loop()
|
||||
@@ -174,6 +213,43 @@ class TestBackgroundTaskTracking:
|
||||
mock_logger.opt.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_shutdown_drains_work_scheduled_by_background_task(self):
|
||||
loop, _bus = _make_loop()
|
||||
loop.subagents.close = AsyncMock()
|
||||
loop._exec_session_manager.close_all = AsyncMock()
|
||||
scan_started = asyncio.Event()
|
||||
release_scan = asyncio.Event()
|
||||
archival_started = asyncio.Event()
|
||||
release_archival = asyncio.Event()
|
||||
|
||||
async def archive():
|
||||
archival_started.set()
|
||||
await release_archival.wait()
|
||||
|
||||
async def scan():
|
||||
scan_started.set()
|
||||
await release_scan.wait()
|
||||
loop.schedule_background(archive())
|
||||
|
||||
loop.schedule_background(scan())
|
||||
await scan_started.wait()
|
||||
closing = asyncio.create_task(loop.aclose())
|
||||
try:
|
||||
await asyncio.sleep(0)
|
||||
release_scan.set()
|
||||
await archival_started.wait()
|
||||
assert not closing.done()
|
||||
loop.subagents.close.assert_not_awaited()
|
||||
finally:
|
||||
release_scan.set()
|
||||
release_archival.set()
|
||||
await closing
|
||||
|
||||
assert not loop._background_tasks
|
||||
loop.subagents.close.assert_awaited_once()
|
||||
loop._exec_session_manager.close_all.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_shutdown_drains_background_failure_and_logs_it_once(self, monkeypatch):
|
||||
loop, _bus = _make_loop()
|
||||
|
||||
@@ -176,6 +176,7 @@ async def test_restricted_project_can_read_agent_skills_and_exact_history(tmp_pa
|
||||
skill_file = agent_workspace / "skills" / "custom" / "SKILL.md"
|
||||
history_file = agent_workspace / "memory" / "history.jsonl"
|
||||
private_memory_file = agent_workspace / "memory" / "private.txt"
|
||||
wiki_file = agent_workspace / "memory" / "wiki" / "projects" / "example.md"
|
||||
private_file = agent_workspace / "private.txt"
|
||||
project_file = project / "project.txt"
|
||||
skill_file.parent.mkdir(parents=True)
|
||||
@@ -183,6 +184,8 @@ async def test_restricted_project_can_read_agent_skills_and_exact_history(tmp_pa
|
||||
project.mkdir()
|
||||
skill_file.write_text("global skill", encoding="utf-8")
|
||||
history_file.write_text('{"content":"global history"}\n', encoding="utf-8")
|
||||
wiki_file.parent.mkdir(parents=True)
|
||||
wiki_file.write_text("Wiki deployment details", encoding="utf-8")
|
||||
private_memory_file.write_text("private memory", encoding="utf-8")
|
||||
private_file.write_text("private", encoding="utf-8")
|
||||
project_file.write_text("project", encoding="utf-8")
|
||||
@@ -209,6 +212,8 @@ async def test_restricted_project_can_read_agent_skills_and_exact_history(tmp_pa
|
||||
path=str(history_file),
|
||||
output_mode="content",
|
||||
)
|
||||
wiki_result = await read_tool.execute(path=str(wiki_file))
|
||||
wiki_write_result = await write_tool.execute(path=str(wiki_file), content="changed")
|
||||
private_memory_result = await read_tool.execute(path=str(private_memory_file))
|
||||
private_result = await read_tool.execute(path=str(private_file))
|
||||
write_result = await write_tool.execute(path=str(skill_file), content="changed")
|
||||
@@ -219,6 +224,9 @@ async def test_restricted_project_can_read_agent_skills_and_exact_history(tmp_pa
|
||||
assert "project" in project_result
|
||||
assert "global skill" in skill_result
|
||||
assert "global history" in history_result
|
||||
assert "Wiki deployment details" in wiki_result
|
||||
assert "outside allowed directory" in wiki_write_result
|
||||
assert wiki_file.read_text(encoding="utf-8") == "Wiki deployment details"
|
||||
assert "outside allowed directory" in private_memory_result
|
||||
assert "outside allowed directory" in private_result
|
||||
assert "outside allowed directory" in write_result
|
||||
|
||||
@@ -317,36 +317,6 @@ def test_disabled_dream_cursor_only_advances_when_behind(tmp_path) -> None:
|
||||
assert store.get_last_dream_cursor() == 10
|
||||
|
||||
|
||||
def test_commit_dream_changes_skips_noop_run(tmp_path) -> None:
|
||||
store = MemoryStore(tmp_path)
|
||||
store.write_soul("# Soul")
|
||||
store.write_memory("# Memory")
|
||||
store.git.init()
|
||||
store.git.auto_commit("initial")
|
||||
store.git.auto_commit = MagicMock(wraps=store.git.auto_commit)
|
||||
|
||||
assert cli_gateway_runtime._commit_dream_changes(store) is None
|
||||
store.git.auto_commit.assert_not_called()
|
||||
|
||||
|
||||
def test_commit_dream_changes_commits_real_edits(tmp_path) -> None:
|
||||
store = MemoryStore(tmp_path)
|
||||
store.write_soul("# Soul")
|
||||
store.write_memory("# Memory")
|
||||
store.git.init()
|
||||
store.git.auto_commit("initial")
|
||||
store.write_memory("# Memory\n- Research notes")
|
||||
store.git.auto_commit = MagicMock(wraps=store.git.auto_commit)
|
||||
|
||||
sha = cli_gateway_runtime._commit_dream_changes(store)
|
||||
|
||||
assert sha is not None
|
||||
store.git.auto_commit.assert_called_once()
|
||||
message = store.git.auto_commit.call_args.args[0]
|
||||
assert message.startswith("dream: periodic memory consolidation\n\n")
|
||||
assert "Research notes" in message
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_paths():
|
||||
"""Mock config/workspace paths for test isolation."""
|
||||
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
|
||||
|
||||
@@ -209,7 +209,7 @@ async def test_queued_skill_sources_reach_the_request(tmp_path: Path):
|
||||
runtime = loop.llm_runtime()
|
||||
request = RequestContext(channel='websocket', chat_id='skill-provenance', session_key=session.key,
|
||||
runtime=runtime, original_user_text='$example')
|
||||
blocks = await loop._resolve_runtime_context_for_request(request, loop.tools)
|
||||
blocks = await loop._resolve_runtime_context_for_request(request, loop.tools, include_memory=True)
|
||||
assert await loop._persist_user_message_early(message, session, runtime_context_blocks=blocks)
|
||||
expected_path = str(skill / 'SKILL.md')
|
||||
from nanobot.events import EventSink
|
||||
|
||||
@@ -12,6 +12,48 @@ from nanobot.agent.tools.filesystem import (
|
||||
WriteFileTool,
|
||||
)
|
||||
from nanobot.execution.files import WorkspaceFiles
|
||||
from nanobot.security.workspace_access import (
|
||||
bind_workspace_scope,
|
||||
build_workspace_scope,
|
||||
reset_workspace_scope,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("access_mode", ["restricted", "full"])
|
||||
async def test_file_tools_treat_runtime_memory_state_as_read_only(tmp_path, access_mode):
|
||||
agent_workspace = tmp_path / "agent"
|
||||
project = agent_workspace if access_mode == "restricted" else tmp_path / "project"
|
||||
(project / "memory").mkdir(parents=True)
|
||||
(agent_workspace / "memory").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
read = ReadFileTool(workspace=agent_workspace)
|
||||
write = WriteFileTool(workspace=agent_workspace)
|
||||
edit = EditFileTool(workspace=agent_workspace)
|
||||
patch = ApplyPatchTool(workspace=agent_workspace)
|
||||
token = bind_workspace_scope(build_workspace_scope(project, access_mode))
|
||||
try:
|
||||
for name in ("history.jsonl", ".cursor", ".dream_cursor"):
|
||||
file = agent_workspace / "memory" / name
|
||||
file.write_text("original runtime state", encoding="utf-8")
|
||||
path = file.relative_to(project).as_posix() if project == agent_workspace else str(file)
|
||||
assert "original runtime state" in await read.execute(path=path)
|
||||
results = (
|
||||
await write.execute(path=path, content="changed"),
|
||||
await edit.execute(path=path, old_text="original runtime state", new_text="changed"),
|
||||
await patch.execute(edits=[{"path": path, "action": "add", "new_text": "changed"}]),
|
||||
)
|
||||
assert all(result.is_error and "managed by the runtime" in result for result in results)
|
||||
assert file.read_text(encoding="utf-8") == "original runtime state"
|
||||
|
||||
for path in ("memory/MEMORY.md", "memory/wiki/topic.md"):
|
||||
await write.execute(path=path, content="Editable notes")
|
||||
assert (project / path).read_text(encoding="utf-8") == "Editable notes"
|
||||
if project != agent_workspace:
|
||||
# Protection belongs to the agent's state, not to every file with the same name.
|
||||
await write.execute(path="memory/.cursor", content="Project-specific cursor")
|
||||
assert (project / "memory" / ".cursor").read_text(encoding="utf-8") == "Project-specific cursor"
|
||||
finally:
|
||||
reset_workspace_scope(token)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="requires a POSIX named pipe")
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.utils.gitstore import GitStore
|
||||
from nanobot.utils.gitstore import GitStore, GitStoreError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -229,3 +231,223 @@ class TestCommitIdEncoding:
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout.strip()
|
||||
assert git._resolve_sha(real) is not None
|
||||
|
||||
|
||||
def _git_output(workspace, *args):
|
||||
return subprocess.run(
|
||||
["git", "-C", str(workspace), *args],
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def _write_page(workspace, relative, content):
|
||||
path = workspace / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wiki_git(tmp_path):
|
||||
git = GitStore(
|
||||
tmp_path,
|
||||
tracked_files=["SOUL.md", "USER.md", "memory/MEMORY.md", "memory/.dream_cursor"],
|
||||
tracked_dirs=["memory/wiki"],
|
||||
)
|
||||
git.init()
|
||||
return git
|
||||
|
||||
|
||||
class TestTrackedDirectories:
|
||||
|
||||
def test_wiki_changes_are_audited_and_restore_the_selected_parent(self, tmp_path):
|
||||
git = GitStore(tmp_path, tracked_files=["SOUL.md"], tracked_dirs=["memory/wiki"])
|
||||
topic = _write_page(tmp_path, "memory/wiki/nested/topic.md", "original topic\n")
|
||||
empty = _write_page(tmp_path, "memory/wiki/obsolete.md", "")
|
||||
renamed = _write_page(tmp_path, "memory/wiki/old.md", "same content\n")
|
||||
journal = _write_page(tmp_path, "memory/history.jsonl", "synthetic journal\n")
|
||||
sibling = _write_page(tmp_path, "memory/wiki-other/private.md", "not a wiki page\n")
|
||||
assert git.init()
|
||||
before = _git_output(tmp_path, "rev-parse", "HEAD")
|
||||
|
||||
topic.write_text("updated topic\n", encoding="utf-8")
|
||||
empty.unlink()
|
||||
renamed_to = renamed.rename(renamed.with_name("new.md"))
|
||||
added = _write_page(tmp_path, "memory/wiki/deep/page.md", "")
|
||||
summary = git.summarize_working_tree([], directories=["memory/wiki"])
|
||||
assert "memory/wiki/nested/topic.md: +1 -1" in summary
|
||||
assert "memory/wiki/obsolete.md: +0 -0" in summary
|
||||
assert "memory/wiki/deep/page.md: +0 -0" in summary
|
||||
assert "memory/wiki/old.md" in summary and "memory/wiki/new.md" in summary
|
||||
selected = git.auto_commit("dream: update wiki")
|
||||
assert selected
|
||||
assert _git_output(tmp_path, "ls-tree", "-r", "--name-only", "HEAD").splitlines() == [
|
||||
".gitignore", "SOUL.md", "memory/wiki/deep/page.md", "memory/wiki/nested/topic.md", "memory/wiki/new.md",
|
||||
]
|
||||
assert _git_output(tmp_path, "check-ignore", "memory/history.jsonl") == "memory/history.jsonl"
|
||||
|
||||
later = _write_page(tmp_path, "memory/wiki/later.md", "later committed page\n")
|
||||
assert git.auto_commit("dream: later")
|
||||
assert git.revert(selected)
|
||||
assert _git_output(tmp_path, "diff", "--exit-code", before, "HEAD") == ""
|
||||
assert topic.read_text(encoding="utf-8") == "original topic\n"
|
||||
assert renamed.read_text(encoding="utf-8") == "same content\n"
|
||||
assert empty.read_bytes() == b""
|
||||
assert not any(path.exists() for path in (added, renamed_to, later))
|
||||
assert journal.read_text(encoding="utf-8") == "synthetic journal\n"
|
||||
assert sibling.read_text(encoding="utf-8") == "not a wiki page\n"
|
||||
|
||||
def test_deleted_directory_is_committed_and_restored_with_missing_parents(self, wiki_git, tmp_path):
|
||||
page = _write_page(tmp_path, "memory/wiki/deep/topic.md", "nested page\n")
|
||||
_write_page(tmp_path, "memory/MEMORY.md", "fixed memory\n")
|
||||
assert wiki_git.auto_commit("dream: populate") is not None
|
||||
shutil.rmtree(tmp_path / "memory")
|
||||
|
||||
assert "memory/wiki/deep/topic.md: +0 -1" in wiki_git.summarize_working_tree(
|
||||
[], directories=["memory/wiki"],
|
||||
)
|
||||
deleted = wiki_git.auto_commit("dream: remove directory")
|
||||
assert deleted is not None
|
||||
assert "memory/" not in _git_output(tmp_path, "ls-tree", "-r", "--name-only", "HEAD")
|
||||
|
||||
assert wiki_git.revert(deleted) is not None
|
||||
assert page.read_text(encoding="utf-8") == "nested page\n"
|
||||
assert (tmp_path / "memory/MEMORY.md").read_text(encoding="utf-8") == "fixed memory\n"
|
||||
assert (tmp_path / "memory/.dream_cursor").is_file()
|
||||
assert _git_output(tmp_path, "show", "HEAD:memory/wiki/deep/topic.md") == "nested page"
|
||||
|
||||
def test_old_repository_and_snapshots_without_wiki_need_no_migration(self, tmp_path):
|
||||
old = GitStore(tmp_path, tracked_files=["SOUL.md"])
|
||||
old.init()
|
||||
(tmp_path / "SOUL.md").write_text("legacy state\n", encoding="utf-8")
|
||||
legacy = old.auto_commit("dream: before wiki")
|
||||
assert legacy
|
||||
git = GitStore(tmp_path, tracked_files=["SOUL.md"], tracked_dirs=["memory/wiki"])
|
||||
page = _write_page(tmp_path, "memory/wiki/nested/new.md", "first wiki\n")
|
||||
created = git.auto_commit("dream: add wiki")
|
||||
assert created
|
||||
assert _git_output(tmp_path, "show", "HEAD:memory/wiki/nested/new.md") == "first wiki"
|
||||
|
||||
assert git.revert(created)
|
||||
assert not page.exists()
|
||||
assert _git_output(tmp_path, "diff", "--exit-code", legacy, "HEAD") == ""
|
||||
|
||||
|
||||
def _make_link(link, target, *, junction=False):
|
||||
if junction:
|
||||
if os.name != "nt":
|
||||
pytest.skip("junctions are Windows-only")
|
||||
subprocess.run(
|
||||
["cmd", "/c", "mklink", "/J", str(link), str(target)],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
link.symlink_to(target, target_is_directory=target.is_dir())
|
||||
except OSError as exc:
|
||||
pytest.skip(f"symlinks unavailable: {exc}")
|
||||
|
||||
|
||||
class TestDirectoryBoundaries:
|
||||
|
||||
@pytest.mark.parametrize(("kind", "location", "target_scope"), [
|
||||
("symlink", "root", "history"),
|
||||
("symlink", "nested", "outside"),
|
||||
("symlink", "ancestor", "outside"),
|
||||
("junction", "root", "history"),
|
||||
("junction", "nested", "outside"),
|
||||
("junction", "ancestor", "outside"),
|
||||
])
|
||||
def test_directory_links_fail_before_staging_reading_or_restoring(
|
||||
self, tmp_path, kind, location, target_scope,
|
||||
):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
git = GitStore(workspace, tracked_files=["SOUL.md"], tracked_dirs=["memory/wiki"])
|
||||
git.init()
|
||||
_write_page(workspace, "memory/wiki/page.md", "safe page\n")
|
||||
assert git.auto_commit("dream: safe page") is not None
|
||||
(workspace / "SOUL.md").write_text("latest soul\n", encoding="utf-8")
|
||||
latest = git.auto_commit("dream: latest")
|
||||
assert latest is not None
|
||||
|
||||
target = workspace / "memory" if target_scope == "history" else tmp_path / "outside"
|
||||
target.mkdir(exist_ok=True)
|
||||
secret = _write_page(target, "history.jsonl", "synthetic private journal\n")
|
||||
link = {
|
||||
"root": workspace / "memory/wiki",
|
||||
"nested": workspace / "memory/wiki/escape",
|
||||
"ancestor": workspace / "memory",
|
||||
}[location]
|
||||
if link.exists():
|
||||
shutil.rmtree(link)
|
||||
_make_link(link, target, junction=kind == "junction")
|
||||
try:
|
||||
with pytest.raises(GitStoreError, match="auto-commit failed"):
|
||||
git.auto_commit("must not capture journal")
|
||||
with pytest.raises(GitStoreError, match="summary failed"):
|
||||
git.summarize_working_tree(["SOUL.md"], directories=["memory/wiki"])
|
||||
with pytest.raises(GitStoreError, match="revert failed"):
|
||||
git.revert(latest)
|
||||
assert git.log()[0].sha == latest
|
||||
assert (workspace / "SOUL.md").read_text(encoding="utf-8") == "latest soul\n"
|
||||
assert secret.read_text(encoding="utf-8") == "synthetic private journal\n"
|
||||
assert _git_output(workspace, "diff", "--cached", "--exit-code") == ""
|
||||
finally:
|
||||
if kind == "junction":
|
||||
link.rmdir()
|
||||
else:
|
||||
link.unlink()
|
||||
|
||||
@pytest.mark.parametrize("target_scope", ["history", "outside"])
|
||||
def test_page_symlink_does_not_read_or_overwrite_its_target(self, tmp_path, target_scope):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
git = GitStore(workspace, tracked_files=["SOUL.md"], tracked_dirs=["memory/wiki"])
|
||||
git.init()
|
||||
page = _write_page(workspace, "memory/wiki/page.md", "safe page\n")
|
||||
latest = git.auto_commit("dream: safe page")
|
||||
assert latest is not None
|
||||
if target_scope == "history":
|
||||
secret = _write_page(workspace, "memory/history.jsonl", "synthetic private journal\n")
|
||||
else:
|
||||
secret = _write_page(tmp_path, "outside/secret.md", "synthetic outside data\n")
|
||||
original = secret.read_bytes()
|
||||
page.unlink()
|
||||
_make_link(page, secret)
|
||||
try:
|
||||
with pytest.raises(GitStoreError, match="auto-commit failed"):
|
||||
git.auto_commit("must not capture link")
|
||||
with pytest.raises(GitStoreError, match="summary failed"):
|
||||
git.summarize_working_tree([], directories=["memory/wiki"])
|
||||
with pytest.raises(GitStoreError, match="summary failed"):
|
||||
git.summarize_working_tree(["memory/wiki/page.md"])
|
||||
with pytest.raises(GitStoreError, match="revert failed"):
|
||||
git.revert(latest)
|
||||
assert secret.read_bytes() == original
|
||||
assert git.log()[0].sha == latest
|
||||
finally:
|
||||
page.unlink()
|
||||
|
||||
@pytest.mark.parametrize("kind", ["symlink", "junction"])
|
||||
def test_init_rejects_linked_ancestor_before_creating_fixed_files(self, tmp_path, kind):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
outside = tmp_path / "outside"
|
||||
sentinel = _write_page(outside, "wiki/private.md", "outside page\n")
|
||||
link = workspace / "memory"
|
||||
_make_link(link, outside, junction=kind == "junction")
|
||||
git = GitStore(
|
||||
workspace, tracked_files=["memory/MEMORY.md"], tracked_dirs=["memory/wiki"],
|
||||
)
|
||||
try:
|
||||
with pytest.raises(GitStoreError, match="init failed"):
|
||||
git.init()
|
||||
assert not (workspace / ".git").exists()
|
||||
assert not (outside / "MEMORY.md").exists()
|
||||
assert sentinel.read_text(encoding="utf-8") == "outside page\n"
|
||||
finally:
|
||||
if kind == "junction":
|
||||
link.rmdir()
|
||||
else:
|
||||
link.unlink()
|
||||
Reference in new issue
Block a user