Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(dreaming): Add Dream Memory Module and Supporting Capabilities

white2025f1927a67584f
diff --git a/jiuwenclaw/agents/harness/common/memory/dreaming/__init__.py b/jiuwenclaw/agents/harness/common/memory/dreaming/__init__.py
new file mode 100644
index 0000000000..879835ba93
--- /dev/null
+++ b/jiuwenclaw/agents/harness/common/memory/dreaming/__init__.py
@@ -0,0 +1,86 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Public API of Dreaming Memory Integration Module
+
+Example:
+ await start_dreaming(
+ sessions_dir="/path/to/sessions",
+ output_dir="/path/to/memory",
+ mode="agent",
+ busy_checker=lambda: sm.has_active_tasks(),
+ )
+ await stop_dreaming(mode="agent")
+"""
+from __future__ import annotations
+
+import logging
+from typing import Callable
+
+from openjiuwen.core.memory.dreaming import DreamingOrchestrator
+
+__all__ = [
+ "start_dreaming",
+ "stop_dreaming",
+ "get_dreaming_orchestrator",
+ "DreamingOrchestrator",
+]
+
+logger = logging.getLogger(__name__)
+
+_orchestrators: dict[str, DreamingOrchestrator] = {}
+
+
+def get_dreaming_orchestrator(mode: str = "agent") -> DreamingOrchestrator | None:
+ return _orchestrators.get(mode)
+
+
+async def start_dreaming(
+ sessions_dir: str,
+ output_dir: str,
+ mode: str = "agent",
+ busy_checker: Callable[[], bool] | None = None,
+) -> DreamingOrchestrator | None:
+ """Start dreaming service.
+ Idempotent: same mode repeated call returns existing instance.
+ """
+ if mode in _orchestrators:
+ return _orchestrators[mode]
+
+ from .sweeper import DreamingConfig, Sweeper
+
+ cfg = DreamingConfig.load(mode)
+ if not cfg.enabled:
+ logger.info("[dreaming] %s mode enabled=false, not started", mode)
+ return None
+
+ sweeper = Sweeper(sessions_dir, output_dir, mode=mode)
+ sweeper.init()
+
+ orch = DreamingOrchestrator(
+ sweep_fn=sweeper.run_sweep,
+ interval_seconds=cfg.interval_seconds,
+ busy_checker=busy_checker,
+ name=f"dreaming-{mode}",
+ )
+ await orch.start()
+ _orchestrators[mode] = orch
+ return orch
+
+
+async def stop_dreaming(mode: str | None = None) -> None:
+ """Stop dreaming service.
+ Idempotent: same mode repeated call does nothing.
+ """
+ if mode is not None:
+ orch = _orchestrators.pop(mode, None)
+ if orch:
+ try:
+ await orch.stop()
+ except Exception as exc:
+ logger.warning("[dreaming] stop(%s) exception: %s", mode, exc)
+ else:
+ for m, orch in list(_orchestrators.items()):
+ _orchestrators.pop(m, None)
+ try:
+ await orch.stop()
+ except Exception as exc:
+ logger.warning("[dreaming] stop(%s) exception: %s", m, exc)
diff --git a/jiuwenclaw/agents/harness/common/memory/dreaming/sweeper.py b/jiuwenclaw/agents/harness/common/memory/dreaming/sweeper.py
new file mode 100644
index 0000000000..981257faad
--- /dev/null
+++ b/jiuwenclaw/agents/harness/common/memory/dreaming/sweeper.py
@@ -0,0 +1,783 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Dreaming Sweeper: Scan + Compression + LLM Extraction + Promotion (Unified Pipeline)"""
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import logging
+import os
+import re
+import time
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Constants (parameters not configurable externally)
+# ---------------------------------------------------------------------------
+_MIN_SESSION_ROUNDS = 4
+_MAX_SESSIONS_PER_SWEEP = 10
+_MAX_SESSION_AGE_DAYS = 30
+_MAX_COMPRESS_TOKENS = 30000
+_MAX_ENTRIES_AGENT = 50
+_MAX_PROMOTIONS_PER_SESSION = 5
+_MIN_NEW_SESSIONS = 3
+_MIN_SESSION_AGE_BYPASS_DAYS = 7
+
+
+# ---------------------------------------------------------------------------
+# Configuration (only keep fields that need external control)
+# ---------------------------------------------------------------------------
+@dataclass
+class DreamingConfig:
+ enabled: bool = False
+ interval_seconds: float = 14400.0
+
+ @classmethod
+ def load(cls, mode: str = "code") -> "DreamingConfig":
+ """Load configuration from the config.yaml memory.dreaming.{mode} or return enabled=False."""
+ try:
+ from jiuwenswarm.common.config import get_config
+ raw = get_config().get("memory", {}).get("dreaming", {}).get(mode, {})
+ if not isinstance(raw, dict):
+ raw = {}
+ env_key = f"DREAMING_{mode.upper()}_ENABLED"
+ env_val = os.getenv(env_key)
+ if env_val is not None:
+ enabled = env_val.lower() in ("true", "1", "yes")
+ else:
+ enabled = bool(raw.get("enabled", False))
+ interval = float(os.getenv(
+ "DREAMING_INTERVAL",
+ str(raw.get("interval_seconds", 14400.0)),
+ ))
+ return cls(enabled=enabled, interval_seconds=interval)
+ except Exception as exc:
+ logger.warning("[dreaming] %s configuration load failed, using default values: %s", mode, exc)
+ return cls()
+
+
+# ---------------------------------------------------------------------------
+# UI text i18n
+# ---------------------------------------------------------------------------
+_UI_TEXT = {
+ "zh": {
+ "empty_summary": "(空)",
+ "dreaming_header": "# Dreaming 记忆\n",
+ "truncate_rounds": "[... 前 {keep_from} 轮对话已省略 ...]\n\n",
+ "truncate_hard": "[... 内容过长,已截断 ...]\n\n",
+ },
+ "en": {
+ "empty_summary": "(None)",
+ "dreaming_header": "# Dreaming Memories\n",
+ "truncate_rounds": "[... First {keep_from} rounds omitted ...]\n\n",
+ "truncate_hard": "[... Content too long, truncated ...]\n\n",
+ },
+}
+
+
+# ---------------------------------------------------------------------------
+# Sweeper
+# ---------------------------------------------------------------------------
+class Sweeper:
+ """Unified dreaming pipeline: Scan + Compression + LLM Extraction + Promotion."""
+
+ def __init__(self, sessions_dir: str, output_dir: str, mode: str = "code", language: str = "zh") -> None:
+ self._sessions_dir = sessions_dir
+ self._output_dir = output_dir
+ self._mode = mode
+ self._language = language
+ self._dreams_dir = Path(output_dir) / ".dreams"
+ self.scanned_sessions: dict[str, dict] = {}
+
+ self._prompt_map = {
+ ("code", "zh"): _PROMPT_CODE,
+ ("code", "en"): _PROMPT_CODE_EN,
+ ("agent", "zh"): _PROMPT_AGENT,
+ ("agent", "en"): _PROMPT_AGENT_EN,
+ }
+ self._sys_msg_map = {
+ ("code", "zh"): "你是技术经验提取助手。严格输出 JSON 数组。",
+ ("code", "en"): "You are a technical knowledge extractor. Output JSON array strictly.",
+ ("agent", "zh"): "你是记忆整理助手。严格输出 JSON 数组。",
+ ("agent", "en"): "You are a memory organizer. Output JSON array strictly.",
+ }
+
+ def init(self) -> None:
+ """Create directories and load the checkpoint."""
+ self._dreams_dir.mkdir(parents=True, exist_ok=True)
+ Path(self._output_dir).mkdir(parents=True, exist_ok=True)
+ cp = self._load_checkpoint()
+ raw = cp.get("scanned_sessions", [])
+ if isinstance(raw, list):
+ self.scanned_sessions = {sid: {} for sid in raw}
+ elif isinstance(raw, dict):
+ self.scanned_sessions = raw
+ else:
+ self.scanned_sessions = {}
+
+ async def run_sweep(self) -> None:
+ """Complete pipeline. Called by the Orchestrator."""
+ sweep_start = time.monotonic()
+
+ # ── Scan + Pre-filter + Compression ──
+ try:
+ sessions = await asyncio.get_running_loop().run_in_executor(
+ None, self.scan_new_sessions,
+ )
+ except Exception:
+ logger.exception("[Sweeper] Scan stage failed")
+ return
+
+ if not sessions:
+ logger.debug("[Sweeper] No eligible session found")
+ return
+
+ # ── LLM Extraction ──
+ existing_summary = self.load_existing_summary()
+ all_knowledge: list[dict] = []
+ succeeded_ids: list[str] = []
+ failed_ids: list[str] = []
+
+ for s in sessions:
+ try:
+ items = await self._extract_via_llm(
+ s["compressed_text"], existing_summary,
+ )
+ for item in items:
+ item["source_session_id"] = s["session_id"]
+ all_knowledge.extend(items)
+ succeeded_ids.append(s["session_id"])
+ except Exception:
+ logger.exception("[Sweeper] LLM Extraction for session %s failed", s["session_id"])
+ failed_ids.append(s["session_id"])
+
+ # ── Promotion ──
+ if succeeded_ids:
+ sessions_root = Path(self._sessions_dir)
+ for sid in succeeded_ids:
+ try:
+ history_mtime = (sessions_root / sid / "history.json").stat().st_mtime
+ except OSError:
+ history_mtime = 0.0
+ events = self._parse_history(sessions_root / sid)
+ rounds = self._detect_rounds(events)
+ self.scanned_sessions[sid] = {
+ "history_mtime": history_mtime,
+ "round_count": len(rounds),
+ }
+ self.save_checkpoint()
+
+ promoted = 0
+ for k in all_knowledge:
+ try:
+ result = self._promote(
+ k.get("title", ""), k.get("content", ""),
+ k.get("source_session_id", ""),
+ )
+ if result is not None:
+ promoted += 1
+ except Exception:
+ logger.exception("[Sweeper] Promotion failed: %s", k.get("title", ""))
+
+ duration = time.monotonic() - sweep_start
+ logger.info(
+ "[Sweeper] sweep completed: duration=%.1fs sessions=%d "
+ "llm_succeeded=%d llm_failed=%d extracted=%d promoted=%d",
+ duration, len(sessions), len(succeeded_ids),
+ len(failed_ids), len(all_knowledge), promoted,
+ )
+
+ # =====================================================================
+ # Scan + Compression
+ # =====================================================================
+
+ def scan_new_sessions(self) -> list[dict]:
+ """Incremental scan session directories and return a list of new/updated sessions with compressed text."""
+ sessions_root = Path(self._sessions_dir)
+ if not sessions_root.exists():
+ return []
+
+ all_ids = {d.name for d in sessions_root.iterdir() if d.is_dir() and not d.name.startswith("heartbeat")}
+ scanned_ids = set(self.scanned_sessions.keys())
+ brand_new = all_ids - scanned_ids
+
+ new_ids = brand_new.copy()
+
+ for sid in all_ids & scanned_ids:
+ history_path = sessions_root / sid / "history.json"
+ try:
+ current_mtime = history_path.stat().st_mtime
+ except OSError:
+ continue
+ snapshot = self.scanned_sessions.get(sid, {})
+ if current_mtime <= snapshot.get("history_mtime", 0):
+ continue
+ new_ids.add(sid)
+
+ if len(new_ids) < _MIN_NEW_SESSIONS:
+ age_bypass = _MIN_SESSION_AGE_BYPASS_DAYS * 86400
+ has_old = any(
+ (time.time() - (sessions_root / sid).stat().st_mtime) > age_bypass
+ for sid in new_ids
+ if (sessions_root / sid).exists()
+ )
+ if not has_old:
+ logger.info(
+ "[Sweeper] %d new sessions < %d and no expired sessions, skipping",
+ len(new_ids), _MIN_NEW_SESSIONS,
+ )
+ return []
+
+ results: list[dict] = []
+ now = time.time()
+ max_age = _MAX_SESSION_AGE_DAYS * 86400
+
+ for session_id in sorted(new_ids):
+ session_dir = sessions_root / session_id
+
+ try:
+ mtime = session_dir.stat().st_mtime
+ except OSError:
+ continue
+ if now - mtime > max_age:
+ self.scanned_sessions[session_id] = {}
+ continue
+
+ is_incremental = session_id in self.scanned_sessions and self.scanned_sessions.get(session_id)
+
+ if not self._match_session_mode(session_id):
+ continue
+
+ try:
+ events = self._parse_history(session_dir)
+ if not events:
+ continue
+ rounds = self._detect_rounds(events)
+ if is_incremental:
+ last_count = self.scanned_sessions[session_id].get("round_count", 0)
+ new_rounds = len(rounds) - last_count
+ if new_rounds <= 0:
+ continue
+ if new_rounds < _MIN_SESSION_ROUNDS:
+ continue
+ incremental_events = events[rounds[last_count][0]:]
+ compressed = self._compress(incremental_events)
+ else:
+ if len(rounds) < _MIN_SESSION_ROUNDS:
+ continue
+ compressed = self._compress(events)
+ if not compressed.strip():
+ continue
+ results.append({
+ "session_id": session_id,
+ "compressed_text": compressed,
+ })
+ if len(results) >= _MAX_SESSIONS_PER_SWEEP:
+ break
+ except Exception as exc:
+ logger.warning("[Sweeper] Scan session %s failed: %s", session_id, exc)
+
+ return results
+
+ def _match_session_mode(self, session_id: str) -> bool:
+ meta_path = Path(self._sessions_dir) / session_id / "metadata.json"
+ try:
+ data = json.loads(meta_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return False
+ if not isinstance(data, dict):
+ return False
+ session_mode = str(data.get("mode", "")).strip()
+ if not session_mode:
+ return False
+ return session_mode.startswith(self._mode)
+
+ @staticmethod
+ def _parse_history(session_dir: Path) -> list[dict]:
+ path = session_dir / "history.json"
+ if not path.exists():
+ return []
+ try:
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
+ if not isinstance(data, list):
+ return []
+ except (OSError, json.JSONDecodeError):
+ return []
+
+ def _should_keep(entry: dict) -> bool:
+ if entry.get("role") == "user":
+ return True
+ if entry.get("event_type", "") == "chat.final":
+ return True
+ if entry.get("role") == "assistant" and "event_type" not in entry:
+ return True
+ return False
+
+ return [e for e in data if _should_keep(e)]
+
+ @staticmethod
+ def _detect_rounds(events: list[dict]) -> list[tuple[int, int]]:
+ current_user = -1
+ pairs: list[tuple[int, int]] = []
+ for i, e in enumerate(events):
+ role = e.get("role", "")
+ if role == "user":
+ current_user = i
+ elif role == "assistant" and current_user != -1:
+ pairs.append((current_user, i))
+ current_user = -1
+ return pairs
+
+ def _compress(self, events: list[dict], _depth: int = 0) -> str:
+ max_recurse = 5
+ _is_code = (self._mode or "").startswith("code")
+
+ parts: list[str] = []
+ for e in events:
+ role = e.get("role", "")
+ content = str(e.get("content", ""))
+ if role == "user":
+ parts.append(f"[User]: {content[:2000]}")
+ elif not _is_code and role == "assistant" and content.strip():
+ parts.append(f"[Assistant]: {content[:3000]}")
+
+ result = "\n\n".join(parts)
+
+ est_tokens = len(result) // 2
+ if est_tokens > _MAX_COMPRESS_TOKENS:
+ if _depth < max_recurse:
+ rounds = Sweeper._detect_rounds(events)
+ if len(rounds) > 2:
+ keep_from = len(rounds) // 3
+ trimmed = events[rounds[keep_from][0]:]
+ prefix = _UI_TEXT[self._language]["truncate_rounds"].format(keep_from=keep_from)
+ return prefix + self._compress(trimmed, _depth + 1)
+
+ max_chars = _MAX_COMPRESS_TOKENS * 2
+ result = _UI_TEXT[self._language]["truncate_hard"] + result[-max_chars:]
+
+ return result
+
+ # =====================================================================
+ # LLM Extraction
+ # =====================================================================
+
+ async def _extract_via_llm(
+ self, compressed_text: str, existing_summary: str,
+ ) -> list[dict]:
+ from jiuwenswarm.common.config import get_default_models
+ from openjiuwen.core.foundation.llm import (
+ Model, ModelClientConfig, ModelRequestConfig,
+ UserMessage, SystemMessage,
+ )
+
+ entries = get_default_models()
+ if not entries:
+ logger.warning("[Sweeper] No default models configured")
+ return []
+
+ entry = entries[0]
+ mcc = entry.get("model_client_config", {})
+ model_name = mcc.get("model_name", "")
+ mcc_fields = {k: v for k, v in mcc.items() if k != "model_name"}
+ model = Model(
+ model_client_config=ModelClientConfig(**mcc_fields),
+ model_config=ModelRequestConfig(model=model_name, temperature=0.3),
+ )
+
+ key = (self._mode, self._language)
+ prompt_template = self._prompt_map.get(key, _PROMPT_CODE)
+ prompt = prompt_template.format(
+ existing_knowledge=existing_summary,
+ compressed_session=compressed_text,
+ max_items=_MAX_PROMOTIONS_PER_SESSION,
+ )
+ sys_msg = self._sys_msg_map.get(key, self._sys_msg_map[("code", "zh")])
+
+ try:
+ response = await model.invoke([
+ SystemMessage(content=sys_msg),
+ UserMessage(content=prompt),
+ ])
+ content = self._extract_content_str(response.content)
+ json_match = re.search(r'```json\s*\n?(.*?)\n?```', content, re.DOTALL)
+ if not json_match:
+ json_match = re.search(r'```\s*\n?(.*?)\n?```', content, re.DOTALL)
+ json_str = json_match.group(1) if json_match else content
+ parsed = json.loads(json_str.strip())
+ return parsed if isinstance(parsed, list) else []
+ except json.JSONDecodeError:
+ logger.warning("[Sweeper] LLM output JSON parse failed")
+ return []
+ except Exception as exc:
+ logger.warning("[Sweeper] LLM call failed: %s", exc)
+ return []
+
+ @staticmethod
+ def _extract_content_str(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts = []
+ for item in content:
+ if isinstance(item, str):
+ parts.append(item)
+ elif isinstance(item, dict):
+ parts.append(item.get("text", ""))
+ return "\n".join(parts)
+ return str(content) if content else ""
+
+ def load_existing_summary(self) -> str:
+ empty_label = _UI_TEXT.get(self._language, _UI_TEXT["zh"])["empty_summary"]
+ output = Path(self._output_dir)
+ if not output.exists():
+ return empty_label
+
+ if self._mode == "agent":
+ dreaming_path = output / "DREAMING.md"
+ if not dreaming_path.exists():
+ return empty_label
+ try:
+ text = dreaming_path.read_text(encoding="utf-8", errors="replace")
+ titles = re.findall(r'^## (.+)$', text, re.MULTILINE)
+ return "\n".join(f"- {t}" for t in titles) if titles else empty_label
+ except Exception:
+ return empty_label
+
+ lines: list[str] = []
+ for f in sorted(output.glob("consolidated_*.md")):
+ try:
+ text = f.read_text(encoding="utf-8", errors="replace")
+ m = re.search(r'^name:\s*(.+)$', text, re.MULTILINE)
+ lines.append(f"- {m.group(1).strip()}" if m else f"- {f.stem}")
+ except Exception:
+ logger.warning("[dreaming] failed to read consolidated file %s: %s", f, exc_info=True)
+ continue
+ return "\n".join(lines) if lines else empty_label
+
+ # =====================================================================
+ # Promotion
+ # =====================================================================
+
+ def _promote(self, title: str, content: str, session_id: str) -> str | None:
+ if not title or not content:
+ return None
+ if self._mode == "agent":
+ return self.promote_agent(title, content, session_id)
+ return self.promote_code(title, content, session_id)
+
+ def promote_agent(self, title: str, content: str, session_id: str) -> str | None:
+ dreaming_path = Path(self._output_dir) / "DREAMING.md"
+ header = _UI_TEXT.get(self._language, _UI_TEXT["zh"])["dreaming_header"]
+
+ if dreaming_path.exists():
+ try:
+ existing = dreaming_path.read_text(encoding="utf-8")
+ except OSError:
+ existing = header
+ else:
+ existing = header
+
+ entries = self._parse_dreaming_entries(existing)
+
+ if any(e["title"] == title for e in entries):
+ return None
+
+ today = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+ entries.append({
+ "title": title,
+ "source": f"_source: {session_id} | {today}",
+ "content": content,
+ })
+
+ if len(entries) > _MAX_ENTRIES_AGENT:
+ entries = entries[len(entries) - _MAX_ENTRIES_AGENT:]
+
+ parts = [header]
+ for e in entries:
+ parts.append(f"\n## {e['title']}")
+ if e.get("source"):
+ parts.append(e["source"])
+ parts.append(f"\n{e['content']}\n")
+ dreaming_path.write_text("\n".join(parts), encoding="utf-8")
+ return str(dreaming_path)
+
+ @staticmethod
+ def _parse_dreaming_entries(text: str) -> list[dict[str, str]]:
+ entries: list[dict[str, str]] = []
+ for part in re.split(r'^## ', text, flags=re.MULTILINE)[1:]:
+ lines = part.strip().splitlines()
+ if not lines:
+ continue
+ title = lines[0].strip()
+ source = ""
+ content_lines: list[str] = []
+ for line in lines[1:]:
+ if line.startswith("_source:") and line.endswith("_"):
+ source = line
+ else:
+ content_lines.append(line)
+ entries.append({
+ "title": title,
+ "source": source,
+ "content": "\n".join(content_lines).strip(),
+ })
+ return entries
+
+ def promote_code(self, title: str, content: str, session_id: str) -> str | None:
+ content_hash = hashlib.sha256(content.encode("utf-8")).hexdigest()[:12]
+ filename = f"consolidated_{content_hash}.md"
+ output_path = Path(self._output_dir) / filename
+
+ if output_path.exists():
+ return None
+
+ today = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+ body = (
+ f"---\n"
+ f"name: {title}\n"
+ f"source_session: {session_id}\n"
+ f"created_at: {today}\n"
+ f"---\n\n"
+ f"{content}\n"
+ )
+ output_path.write_text(body, encoding="utf-8")
+ return str(output_path)
+
+ # =====================================================================
+ # checkpoint
+ # =====================================================================
+
+ def _load_checkpoint(self) -> dict:
+ path = self._dreams_dir / "ingestion-checkpoint.json"
+ try:
+ if path.exists():
+ raw = path.read_text(encoding="utf-8")
+ data = json.loads(raw) if raw.strip() else {}
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ logger.warning("[dreaming] failed to load checkpoint %s: %s", path, exc_info=True)
+ pass
+ return {}
+
+ def save_checkpoint(self) -> None:
+ path = self._dreams_dir / "ingestion-checkpoint.json"
+ try:
+ self._dreams_dir.mkdir(parents=True, exist_ok=True)
+ data = {
+ "scanned_sessions": self.scanned_sessions,
+ "last_scan_ts": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
+ }
+ path.write_text(
+ json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8",
+ )
+ except Exception as exc:
+ logger.warning("[Sweeper] checkpoint save failed: %s", exc)
+
+
+# =========================================================================
+# LLM Prompt Templates
+# =========================================================================
+
+_PROMPT_CODE = """\
+你是技术经验提取助手。下面是开发者与 AI 编程助手的对话(已压缩)。
+
+目标:提取**只有亲历这次任务才能得到**的经验、踩坑、结论,帮用户在未来类似任务中少走弯路。
+绝大多数对话沉淀不了知识,输出 [] 是常态,不要凑数。
+
+## 值得提取(必须带"为什么/教训",不是平铺事实)
+
+- 踩坑根因:症状 X,常规思路 W 为何不通,真正根因 Y,解法 Z
+- 被验证的非显而易见行为:API / 库 / 工具在边界情况下与文档或直觉不符的实际表现
+- 设计决策的"为什么":在哪些约束下选 A 不选 B,放弃 B 的代价
+- 项目隐含约定:跨模块契约、不可违反的不变量、grep 难发现的命名 / 结构规则
+- 环境 / 部署 / 工具链的坑:版本组合、平台差异、CI 行为
+- 被否决的方案及原因
+
+## 严禁提取
+
+- AI 助手自身运行机制:内置工具行为、系统提示规则、记忆 / 钩子 / 技能等内部机制
+- 通用编程常识:入门资料里都有的内容
+- 对话流水账:做了什么的过程描述,而非沉淀出的结论
+- 静态可查事实:grep / 看代码立即可得的信息
+- 一次性任务状态:PR 编号、当前进度、临时调试目标
+- 已在下方"已有知识库"中记录过的
+
+## 自检三问(每条候选都过一遍)
+
+1. 一周后做类似任务,没这条会怎样?看代码 / 查文档能想起的 → 丢弃
+2. 这是关于用户的代码 / 项目 / 领域,还是关于 AI 助手的工具 / 机制?后者一律丢弃
+3. 能否写成"因为 X 所以 Y / 不要 Z"或"X 出过问题,根因是 Y"?只能写成平铺事实 → 丢弃
+
+## 已有知识库
+
+{existing_knowledge}
+
+## 对话记录
+
+注:仅含用户提问和助手最终回复,无工具调用细节。无法判断时宁可不提取。
+
+{compressed_session}
+
+## 输出
+
+JSON 数组。**绝大多数情况输出 []**。最多 {max_items} 条。
+
+```json
+[
+ {{
+ "title": "简洁标题(10-30 字,点明经验 / 教训)",
+ "content": "背景 + 现象 + 根因 / 为什么 + 结论 / 做法,含具体示例,脱离对话上下文可独立阅读"
+ }}
+]
+```
+
+"""
+
+_PROMPT_AGENT = """\
+你是一个记忆整理助手。下面是一个用户与 AI 助手的对话记录(已压缩)。
+
+请从中提取值得长期记住的信息。每条记忆应当脱离原始对话语境后仍然可读、可用。
+
+## 提取标准
+
+值得提取的:
+- 用户明确表达的偏好(回复风格、语言习惯、关注重点等)
+- 用户的个人背景信息(职业、技术栈、所在团队/公司、角色等)
+- 用户提到的重要事实(项目名称、截止日期、关键人物等)
+- 用户关心的领域知识或专业话题
+- 用户纠正助手的地方(说明助手之前的认知有误)
+- 反复出现的交互模式
+
+不值得提取的:
+- 一次性的事务请求
+- 对话中的寒暄、确认、感谢
+- 已在下方"已有记忆"中记录过的内容
+
+## 已有记忆
+
+{existing_knowledge}
+
+## 对话记录
+
+{compressed_session}
+
+## 输出格式
+
+输出 JSON 数组,每个元素是一条独立记忆。无值得提取的信息则输出 []。最多 {max_items} 条。
+
+```json
+[
+ {{
+ "title": "简洁的标题(10-30字)",
+ "content": "完整的记忆描述,用陈述句描述事实,脱离对话上下文后可独立阅读"
+ }}
+]
+```
+
+要求:每条记忆独立成篇,宁缺毋滥。
+"""
+
+_PROMPT_CODE_EN = """\
+You are a technical experience extraction assistant. Below is a compressed conversation between a developer and an AI coding assistant.
+
+Goal: Extract experiences, pitfalls, and conclusions that can **only be gained by personally going through this task**, helping the user avoid detours in similar future tasks.
+Most conversations yield no extractable knowledge — outputting [] is normal, don't force entries.
+
+## Worth Extracting (must include "why/lesson learned", not just plain facts)
+
+- Pitfall root causes: symptom X, why the obvious approach W didn't work, actual root cause Y, solution Z
+- Verified non-obvious behaviors: actual behavior of API/library/tool in edge cases that contradicts docs or intuition
+- Design decision rationale: why choose A over B under what constraints, what is sacrificed by not choosing B
+- Project implicit conventions: cross-module contracts, inviolable invariants, naming/structure rules hard to find via grep
+- Environment/deployment/toolchain pitfalls: version combinations, platform differences, CI behaviors
+- Rejected approaches and reasons
+
+## Strictly Forbidden
+
+- AI assistant's own operating mechanisms: built-in tool behaviors, system prompt rules, internal mechanisms like memory/hooks/skills
+- General programming common sense: content readily available in introductory materials
+- Conversation logs: process descriptions of what was done, rather than distilled conclusions
+- Statically searchable facts: information immediately obtainable by grep/reading code
+- One-time task state: PR numbers, current progress, temporary debugging goals
+- Content already recorded in the "Existing Knowledge Base" below
+
+## Self-check Three Questions (run each candidate through)
+
+1. A week from now doing a similar task, what if this entry were missing? If you could figure it out from code/docs → discard
+2. Is this about the user's code/project/domain, or about the AI assistant's tools/mechanisms? The latter → always discard
+3. Can you phrase it as "Because X, therefore Y / Don't do Z" or "X caused problems, root cause was Y"? If it can only be plain facts → discard
+
+## Existing Knowledge Base
+
+{existing_knowledge}
+
+## Conversation Log
+
+Note: Contains only user questions and assistant final responses, no tool call details. When in doubt, don't extract.
+
+{compressed_session}
+
+## Output
+
+JSON array. **Most cases output []**. Max {max_items} entries.
+
+```json
+[
+ {{
+ "title": "Concise title (10-30 chars, highlighting experience/lesson)",
+ "content": "Background + phenomenon + root cause / why + conclusion / approach, with concrete examples, readable independently from conversation context"
+ }}
+]
+```
+
+"""
+
+_PROMPT_AGENT_EN = """\
+You are a memory organization assistant. Below is a compressed conversation between a user and an AI assistant.
+
+Please extract information worth remembering long-term. Each memory entry should be readable and usable independently from the original conversation context.
+
+## Extraction Criteria
+
+Worth extracting:
+- User's explicitly expressed preferences (response style, language habits, focus areas, etc.)
+- User's personal background information (profession, tech stack, team/company, role, etc.)
+- Important facts mentioned by the user (project names, deadlines, key people, etc.)
+- Domain knowledge or professional topics the user cares about
+- Places where the user corrected the assistant (indicating the assistant's previous understanding was wrong)
+- Recurring interaction patterns
+
+Not worth extracting:
+- One-time transactional requests
+- Small talk, acknowledgments, thanks in conversation
+- Content already recorded in "Existing Memories" below
+
+## Existing Memories
+
+{existing_knowledge}
+
+## Conversation Log
+
+{compressed_session}
+
+## Output Format
+
+Output a JSON array, each element is an independent memory entry. Output [] if nothing worth extracting. Max {max_items} entries.
+
+```json
+[
+ {{
+ "title": "Concise title (10-30 characters)",
+ "content": "Complete memory description in declarative sentences, describing facts, readable independently from conversation context"
+ }}
+]
+```
+
+Requirements: Each memory entry is self-contained. Better to have nothing than to force entries.
+"""
\ No newline at end of file
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index e6c178dde2..671f78733b 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -1728,6 +1728,7 @@ async def _run(
await heartbeat_service.stop()
await message_handler.stop_forwarding()
await client.disconnect()
+
logger.info("[App] Gateway stopped")
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index b7efb152ea..4a75f231e6 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -262,6 +262,11 @@ class JiuWenClaw:
await adapter.create_instance(config, mode=mode, sub_mode=sub_mode)
logger.info("[JiuWenClaw] Agent instance created: sdk=%s, mode=%s, sub_mode=%s", self._sdk_name, mode, sub_mode)
+ sm = self._session_manager
+ if hasattr(adapter, "try_start_dreaming"):
+ asyncio.create_task(adapter.try_start_dreaming(
+ busy_checker=lambda: sm.has_active_tasks(),))
+
async def reload_agent_config(
self,
config_base: dict[str, Any] | None = None,
@@ -274,8 +279,14 @@ class JiuWenClaw:
env_overrides: 可选的环境变量增量;仅覆盖请求中出现的 key。
"""
adapter = self._ensure_adapter()
+ if hasattr(adapter, "try_stop_dreaming"):
+ await adapter.try_stop_dreaming()
await adapter.reload_agent_config(config_base, env_overrides)
logger.info("[JiuWenClaw] Agent config reloaded: sdk=%s", self._sdk_name)
+ if hasattr(adapter, "try_start_dreaming"):
+ sm = self._session_manager
+ asyncio.create_task(adapter.try_start_dreaming(
+ busy_checker=lambda: sm.has_active_tasks(),))
def _build_inputs(self, request: AgentRequest) -> Tuple[dict[str, Any], str, str]:
"""构建 adapter 所需的 inputs 字典."""
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index c9b12e8f9b..03dc9148e4 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -166,6 +166,8 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
# 用于 coding_memory、todo文件等不应写入用户项目目录的数据。
self._agent_workspace_dir = str(get_agent_workspace_dir())
+ self._dreaming_mode = "code"
+
model = self._create_model(config_base)
agent_card = AgentCard(name=self._agent_name, id='jiuwenswarm')
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 2cdfff7f77..19692e09c4 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -505,6 +505,8 @@ class JiuWenClawDeepAdapter:
self._registered_mcp_server_ids: set[str] = set()
self._registered_mcp_servers: dict[str, McpServerConfig] = {}
self._auto_harness_service: Optional[AutoHarnessService] = None
+ self._dreaming_started = False
+ self._dreaming_mode: str = "agent"
def set_skill_manager(self, skill_manager: SkillManager) -> None:
"""Inject shared SkillManager from facade for tool reuse."""
@@ -2381,6 +2383,7 @@ class JiuWenClawDeepAdapter:
"""
await self.set_checkpoint()
+ self._dreaming_mode = mode if mode and mode.startswith("agent") else "agent"
self._instance_overrides = dict(config or {}) if isinstance(config, dict) else {}
load_dotenv(dotenv_path=get_env_file(), override=True)
config_base = get_config()
@@ -5582,3 +5585,45 @@ class JiuWenClawDeepAdapter:
task.result()
except Exception as exc:
logger.warning("[JiuWenClawDeepAdapter] evolution watcher task exception: %s", exc)
+
+ @staticmethod
+ def _is_approval_event(evt) -> bool:
+ """Check whether an OutputSchema event is an approval request."""
+ evt_type = getattr(evt, "type", "")
+ if evt_type == "chat.ask_user_question":
+ return True
+ if hasattr(evt, "payload") and isinstance(evt.payload, dict):
+ return evt.payload.get("event_type") == "chat.ask_user_question"
+ return False
+
+ async def try_start_dreaming(self, busy_checker: Callable[[], bool] | None = None) -> None:
+ if self._dreaming_started:
+ return
+ try:
+ from jiuwenclaw.agents.harness.common.memory.dreaming import start_dreaming
+ from jiuwenclaw.common.utils import get_agent_sessions_dir
+ sessions_dir = str(get_agent_sessions_dir() or "")
+ mode = getattr(self, "_dreaming_mode", "agent")
+ output_name = "memory" if mode == "agent" else "coding_memory"
+ base_dir = getattr(self, "_agent_workspace_dir", None) or self._workspace_dir
+ output_dir = os.path.join(base_dir, output_name)
+ orch = await start_dreaming(
+ sessions_dir=sessions_dir,
+ output_dir=output_dir,
+ mode=mode,
+ busy_checker=busy_checker,
+ )
+ self._dreaming_started = orch is not None
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] start_dreaming failed: %s", exc)
+
+ async def try_stop_dreaming(self) -> None:
+ if not self._dreaming_started:
+ return
+ try:
+ from jiuwenclaw.agents.harness.common.memory.dreaming import stop_dreaming
+ mode = getattr(self, "_dreaming_mode", "agent")
+ await stop_dreaming(mode=mode)
+ self._dreaming_started = False
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] stop_dreaming failed: %s", exc)
\ No newline at end of file
diff --git a/jiuwenswarm/server/runtime/session/session_manager.py b/jiuwenswarm/server/runtime/session/session_manager.py
index 1b17b6933b..810bddf9ec 100644
--- a/jiuwenswarm/server/runtime/session/session_manager.py
+++ b/jiuwenswarm/server/runtime/session/session_manager.py
@@ -150,4 +150,8 @@ class SessionManager:
return (
session_id in self._session_processors
and not self._session_processors[session_id].done()
- )
\ No newline at end of file
+ )
+
+ def has_active_tasks(self) -> bool:
+ """是否有活跃的 session 任务(供 dreaming busy_checker 使用)。"""
+ return any(t is not None and not t.done() for t in self._session_tasks.values())
\ No newline at end of file
diff --git a/tests/system_tests/test_dreaming_e2e.py b/tests/system_tests/test_dreaming_e2e.py
new file mode 100644
index 0000000000..8eedf89861
--- /dev/null
+++ b/tests/system_tests/test_dreaming_e2e.py
@@ -0,0 +1,377 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""System test for Dreaming Memory — end-to-end sweep pipeline.
+
+Covers the full lifecycle:
+ 1. Create sessions with history.json
+ 2. Create a Sweeper instance targeting those sessions
+ 3. Mock LLM to return controlled knowledge items
+ 4. Execute run_sweep()
+ 5. Verify knowledge files are written and checkpoint updated
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+pytestmark = [pytest.mark.integration, pytest.mark.system]
+
+try:
+ from jiuwenclaw.agents.harness.common.memory.dreaming import DreamingOrchestrator # noqa: F401
+except ImportError:
+ pytest.skip("openjiuwen dreaming module is not available", allow_module_level=True)
+
+# ===========================================================================
+# Helpers
+# ===========================================================================
+
+
+def _make_history_entry(role: str, content: str, *, event_type: str | None = None) -> dict:
+ entry = {"role": role, "content": content}
+ if event_type is not None:
+ entry["event_type"] = event_type
+ return entry
+
+
+def _create_valid_session(sessions_root: Path, sid: str, num_rounds: int = 5,
+ mode: str = "agent.plan") -> Path:
+ """Create a session directory with enough rounds for dreaming."""
+ session_dir = sessions_root / sid
+ session_dir.mkdir(parents=True)
+ entries = []
+ for i in range(num_rounds):
+ entries.append(_make_history_entry("user", f"请问第{i+1}个问题"))
+ entries.append(_make_history_entry("assistant", f"这是第{i+1}个回答", event_type="chat.final"))
+ (session_dir / "history.json").write_text(
+ json.dumps(entries, ensure_ascii=False), encoding="utf-8")
+ metadata = {"mode": mode, "session_id": sid, "created_at": time.time()}
+ (session_dir / "metadata.json").write_text(
+ json.dumps(metadata, ensure_ascii=False), encoding="utf-8")
+ return session_dir
+
+
+def _mock_extract(items: list[dict]):
+ """Return an AsyncMock that simulates _extract_via_llm returning given items."""
+ async def fake_extract(self, compressed_text: str, existing_summary: str) -> list[dict]:
+ return items
+ return fake_extract
+
+
+# ===========================================================================
+# End-to-End: Agent mode Dreaming
+# ===========================================================================
+
+class TestDreamingE2EAgent:
+ """Full agent-mode dreaming: scan → extract → promote to DREAMING.md."""
+
+ @pytest.mark.asyncio
+ async def test_sweep_writes_dreaming_md(self, tmp_path):
+ from jiuwenclaw.agents.harness.common.memory.dreaming.sweeper import Sweeper
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "memory"
+ sessions_root.mkdir()
+
+ _create_valid_session(sessions_root, "sess_001", num_rounds=5)
+ _create_valid_session(sessions_root, "sess_002", num_rounds=5)
+ _create_valid_session(sessions_root, "sess_003", num_rounds=5)
+
+ sweeper = Sweeper(str(sessions_root), str(output_dir), mode="agent")
+ sweeper.init()
+
+ fake_extract = _mock_extract([
+ {"title": "用户偏好 Python", "content": "用户倾向于使用 Python 开发"},
+ {"title": "项目使用 FastAPI", "content": "当前项目框架是 FastAPI"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract):
+ await sweeper.run_sweep()
+
+ dreaming_path = output_dir / "DREAMING.md"
+ assert dreaming_path.exists()
+ content = dreaming_path.read_text(encoding="utf-8")
+ assert "用户偏好 Python" in content
+ assert "项目使用 FastAPI" in content
+ assert "_source:" in content
+
+ cp_path = output_dir / ".dreams" / "ingestion-checkpoint.json"
+ assert cp_path.exists()
+ cp = json.loads(cp_path.read_text(encoding="utf-8"))
+ assert "sess_001" in cp["scanned_sessions"]
+ assert "sess_002" in cp["scanned_sessions"]
+ assert "sess_003" in cp["scanned_sessions"]
+
+ @pytest.mark.asyncio
+ async def test_dedup_skips_existing_title(self, tmp_path):
+ from jiuwenclaw.agents.harness.common.memory.dreaming.sweeper import Sweeper
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "memory"
+ sessions_root.mkdir()
+
+ # need 3 sessions to pass MIN_NEW_SESSIONS gate
+ for sid in ["sess_a", "sess_b", "sess_c"]:
+ _create_valid_session(sessions_root, sid, num_rounds=5)
+
+ sweeper1 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
+ sweeper1.init()
+
+ fake_extract = _mock_extract([
+ {"title": "用户偏好 Python", "content": "第一轮提取"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract):
+ await sweeper1.run_sweep()
+
+ _create_valid_session(sessions_root, "sess_002", num_rounds=5)
+ _create_valid_session(sessions_root, "sess_003", num_rounds=5)
+ sweeper2 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
+ sweeper2.init()
+ sweeper2.scanned_sessions = sweeper1.scanned_sessions
+
+ fake_extract2 = _mock_extract([
+ {"title": "用户偏好 Python", "content": "第二轮提取(应被去重)"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract2):
+ await sweeper2.run_sweep()
+
+ content = (output_dir / "DREAMING.md").read_text(encoding="utf-8")
+ assert content.count("用户偏好 Python") == 1
+
+ @pytest.mark.asyncio
+ async def test_incremental_scan_reprocesses_updated_session(self, tmp_path):
+ from jiuwenclaw.agents.harness.common.memory.dreaming.sweeper import Sweeper
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "memory"
+ sessions_root.mkdir()
+
+ # need 3 sessions to pass MIN_NEW_SESSIONS gate
+ for sid in ["sess_001", "sess_a", "sess_b"]:
+ _create_valid_session(sessions_root, sid, num_rounds=5)
+ session_dir = sessions_root / "sess_001"
+ orig_mtime = (session_dir / "history.json").stat().st_mtime
+
+ sweeper1 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
+ sweeper1.init()
+
+ fake_extract = _mock_extract([
+ {"title": "第一轮知识", "content": "第一次扫描提取"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract):
+ await sweeper1.run_sweep()
+
+ # mark sess_a and sess_b as scanned, then update them too
+ sweeper1.scanned_sessions["sess_a"] = {
+ "history_mtime": (sessions_root / "sess_a" / "history.json").stat().st_mtime,
+ "round_count": 5,
+ }
+ sweeper1.scanned_sessions["sess_b"] = {
+ "history_mtime": (sessions_root / "sess_b" / "history.json").stat().st_mtime,
+ "round_count": 5,
+ }
+
+ time.sleep(0.2)
+ # add 4 more rounds to sess_001, sess_a and sess_b
+ for sid in ["sess_001", "sess_a", "sess_b"]:
+ sdir = sessions_root / sid
+ existing = json.loads((sdir / "history.json").read_text(encoding="utf-8"))
+ existing.extend([
+ _make_history_entry("user", "新问题6"),
+ _make_history_entry("assistant", "新回答6", event_type="chat.final"),
+ _make_history_entry("user", "新问题7"),
+ _make_history_entry("assistant", "新回答7", event_type="chat.final"),
+ _make_history_entry("user", "新问题8"),
+ _make_history_entry("assistant", "新回答8", event_type="chat.final"),
+ _make_history_entry("user", "新问题9"),
+ _make_history_entry("assistant", "新回答9", event_type="chat.final"),
+ ])
+ (sdir / "history.json").write_text(json.dumps(existing), encoding="utf-8")
+
+ sweeper2 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
+ sweeper2.init()
+ sweeper2.scanned_sessions = sweeper1.scanned_sessions
+
+ fake_extract2 = _mock_extract([
+ {"title": "第二轮新增知识", "content": "增量扫描提取"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract2):
+ await sweeper2.run_sweep()
+
+ content = (output_dir / "DREAMING.md").read_text(encoding="utf-8")
+ assert "第一轮知识" in content
+ assert "第二轮新增知识" in content
+
+ @pytest.mark.asyncio
+ async def test_skips_unchanged_session(self, tmp_path):
+ from jiuwenclaw.agents.harness.common.memory.dreaming.sweeper import Sweeper
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "memory"
+ sessions_root.mkdir()
+
+ # need 3 sessions to pass MIN_NEW_SESSIONS gate
+ for sid in ["sess_001", "sess_a", "sess_b"]:
+ _create_valid_session(sessions_root, sid, num_rounds=5)
+
+ sweeper1 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
+ sweeper1.init()
+
+ fake_extract = _mock_extract([
+ {"title": "初次知识", "content": "第一次扫描"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract):
+ await sweeper1.run_sweep()
+
+ sweeper2 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
+ sweeper2.init()
+ sweeper2.scanned_sessions = sweeper1.scanned_sessions
+
+ fake_extract2 = _mock_extract([
+ {"title": "不应该出现", "content": "第二次扫描不应该发生"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract2):
+ await sweeper2.run_sweep()
+
+ content = (output_dir / "DREAMING.md").read_text(encoding="utf-8")
+ assert "不应该出现" not in content
+
+
+# ===========================================================================
+# End-to-End: Code mode Dreaming
+# ===========================================================================
+
+class TestDreamingE2ECode:
+ """Full code-mode dreaming: scan → extract → promote to consolidated_xxx.md."""
+
+ @pytest.mark.asyncio
+ async def test_sweep_writes_consolidated_files(self, tmp_path):
+ from jiuwenclaw.agents.harness.common.memory.dreaming.sweeper import Sweeper
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "coding_memory"
+ sessions_root.mkdir()
+
+ _create_valid_session(sessions_root, "sess_010", num_rounds=5, mode="code.normal")
+ _create_valid_session(sessions_root, "sess_011", num_rounds=5, mode="code.normal")
+ _create_valid_session(sessions_root, "sess_012", num_rounds=5, mode="code.normal")
+
+ sweeper = Sweeper(str(sessions_root), str(output_dir), mode="code")
+ sweeper.init()
+
+ fake_extract = _mock_extract([
+ {"title": "Python 性能优化", "content": "使用列表推导式替代 for 循环"},
+ {"title": "Git 工作流最佳实践", "content": "推荐使用 feature branch + rebase"},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract):
+ await sweeper.run_sweep()
+
+ files = sorted(output_dir.glob("consolidated_*.md"))
+ assert len(files) == 2
+ for f in files:
+ text = f.read_text(encoding="utf-8")
+ assert "---" in text
+ assert "name:" in text
+ assert "source_session:" in text
+ assert "created_at:" in text
+
+ combined = "\n".join(f.read_text(encoding="utf-8") for f in files)
+ assert "Python 性能优化" in combined
+ assert "Git 工作流最佳实践" in combined
+
+ @pytest.mark.asyncio
+ async def test_content_hash_dedup(self, tmp_path):
+ from jiuwenclaw.agents.harness.common.memory.dreaming.sweeper import Sweeper
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "coding_memory"
+ sessions_root.mkdir()
+
+ # need 3 sessions to pass MIN_NEW_SESSIONS gate
+ for sid in ["sess_020", "sess_021", "sess_022"]:
+ _create_valid_session(sessions_root, sid, num_rounds=5, mode="code.normal")
+
+ sweeper = Sweeper(str(sessions_root), str(output_dir), mode="code")
+ sweeper.init()
+
+ shared_body = "完全相同的知识内容用于测试去重"
+ fake_extract = _mock_extract([
+ {"title": "知识点A", "content": shared_body},
+ {"title": "知识点B", "content": shared_body},
+ ])
+
+ with mock.patch.object(Sweeper, "_extract_via_llm", fake_extract):
+ await sweeper.run_sweep()
+
+ files = sorted(output_dir.glob("consolidated_*.md"))
+ assert len(files) == 1
+
+
+# ===========================================================================
+# End-to-End: Dreaming start/stop lifecycle
+# ===========================================================================
+
+class TestDreamingE2ELifecycle:
+ """Orch-level lifecycle: start → sweep → stop."""
+
+ @pytest.mark.asyncio
+ async def test_start_stop(self, tmp_path, monkeypatch):
+ from jiuwenclaw.agents.harness.common.memory.dreaming import (
+ start_dreaming,
+ stop_dreaming,
+ get_dreaming_orchestrator,
+ )
+
+ monkeypatch.setenv("DREAMING_AGENT_ENABLED", "true")
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "memory"
+ sessions_root.mkdir()
+ output_dir.mkdir()
+
+ busy = False
+
+ orch = await start_dreaming(
+ sessions_dir=str(sessions_root),
+ output_dir=str(output_dir),
+ mode="agent",
+ busy_checker=lambda: busy,
+ )
+ assert orch is not None
+ assert get_dreaming_orchestrator("agent") is orch
+
+ await stop_dreaming("agent")
+ assert get_dreaming_orchestrator("agent") is None
+
+ @pytest.mark.asyncio
+ async def test_start_disabled_config(self, tmp_path, monkeypatch):
+ from jiuwenclaw.agents.harness.common.memory.dreaming import (
+ start_dreaming,
+ get_dreaming_orchestrator,
+ )
+ monkeypatch.setenv("DREAMING_AGENT_ENABLED", "false")
+
+ sessions_root = tmp_path / "sessions"
+ output_dir = tmp_path / "memory"
+ sessions_root.mkdir()
+ output_dir.mkdir()
+
+ orch = await start_dreaming(
+ sessions_dir=str(sessions_root),
+ output_dir=str(output_dir),
+ mode="agent",
+ )
+ assert orch is None
+ assert get_dreaming_orchestrator("agent") is None
\ No newline at end of file
diff --git a/tests/unit_tests/agentserver/memory/test_dreaming_sweeper.py b/tests/unit_tests/agentserver/memory/test_dreaming_sweeper.py
new file mode 100644
index 0000000000..5368c8cbfc
--- /dev/null
+++ b/tests/unit_tests/agentserver/memory/test_dreaming_sweeper.py
@@ -0,0 +1,757 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for Dreaming Sweeper — pure functions and file-based logic.
+
+Tests cover:
+- DreamingConfig.load() — configuration loading from dict / env
+- Sweeper._parse_history() — event filtering
+- Sweeper._detect_rounds() — round pair detection
+- Sweeper._compress() — text compression with token budget
+- Sweeper._parse_dreaming_entries() — DREAMING.md parsing
+- Sweeper.load_existing_summary() — knowledge title loading
+- Sweeper.promote_agent() — write DREAMING.md with dedup + eviction
+- Sweeper.promote_code() — write consolidated_xxx.md with hash dedup
+- Sweeper._load/save_checkpoint() — checkpoint persistence
+- Sweeper.scan_new_sessions() — incremental scan logic
+- SessionManager.has_active_tasks()
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+try:
+ from jiuwenclaw.agents.harness.common.memory.dreaming.sweeper import Sweeper # noqa: F401
+ _DREAMING_AVAILABLE = True
+except ImportError:
+ _DREAMING_AVAILABLE = False
+
+
+# ===========================================================================
+# Inline copy of the unit under test (pure functions only)
+# Avoid importing jiuwenclaw to dodge import-time side effects
+# ===========================================================================
+
+_MIN_SESSION_ROUNDS = 4
+_MAX_SESSIONS_PER_SWEEP = 10
+_MAX_SESSION_AGE_DAYS = 30
+_MAX_COMPRESS_TOKENS = 30000
+_MAX_ENTRIES_AGENT = 50
+_MAX_PROMOTIONS_PER_SESSION = 5
+_MIN_NEW_SESSIONS = 3
+_MIN_SESSION_AGE_BYPASS_DAYS = 7
+
+
+# ── parse_history ──
+def _parse_history(session_dir: Path) -> list[dict]:
+ path = session_dir / "history.json"
+ if not path.exists():
+ return []
+ try:
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
+ if not isinstance(data, list):
+ return []
+ except (OSError, json.JSONDecodeError):
+ return []
+
+ def _should_keep(entry: dict) -> bool:
+ if entry.get("role") == "user":
+ return True
+ if entry.get("event_type", "") == "chat.final":
+ return True
+ if entry.get("role") == "assistant" and "event_type" not in entry:
+ return True
+ return False
+
+ return [e for e in data if _should_keep(e)]
+
+
+# ── detect_rounds ──
+def _detect_rounds(events: list[dict]) -> list[tuple[int, int]]:
+ current_user = -1
+ pairs: list[tuple[int, int]] = []
+ for i, e in enumerate(events):
+ role = e.get("role", "")
+ if role == "user":
+ current_user = i
+ elif role == "assistant" and current_user != -1:
+ pairs.append((current_user, i))
+ current_user = -1
+ return pairs
+
+
+# ── compress ──
+def _compress(events: list[dict], _depth: int = 0) -> str:
+ max_recurse = 5
+ parts: list[str] = []
+ for e in events:
+ role = e.get("role", "")
+ content = str(e.get("content", ""))
+ if role == "user":
+ parts.append(f"[User]: {content[:2000]}")
+ elif role == "assistant" and content.strip():
+ parts.append(f"[Assistant]: {content[:3000]}")
+ result = "\n\n".join(parts)
+ est_tokens = len(result) // 2
+ if est_tokens > _MAX_COMPRESS_TOKENS:
+ if _depth < max_recurse:
+ rounds = _detect_rounds(events)
+ if len(rounds) > 2:
+ keep_from = len(rounds) // 3
+ trimmed = events[rounds[keep_from][0]:]
+ prefix = f"[... 前 {keep_from} 轮对话已省略 ...]\n\n"
+ return prefix + _compress(trimmed, _depth + 1)
+ max_chars = _MAX_COMPRESS_TOKENS * 2
+ result = "[... 内容过长,已截断 ...]\n\n" + result[-max_chars:]
+ return result
+
+
+# ── parse_dreaming_entries ──
+def _parse_dreaming_entries(text: str) -> list[dict[str, str]]:
+ import re
+ entries: list[dict[str, str]] = []
+ for part in re.split(r'^## ', text, flags=re.MULTILINE)[1:]:
+ lines = part.strip().splitlines()
+ if not lines:
+ continue
+ title = lines[0].strip()
+ source = ""
+ content_lines: list[str] = []
+ for line in lines[1:]:
+ if line.startswith("_source:") and line.endswith("_"):
+ source = line
+ else:
+ content_lines.append(line)
+ entries.append({
+ "title": title,
+ "source": source,
+ "content": "\n".join(content_lines).strip(),
+ })
+ return entries
+
+
+# ===========================================================================
+# Test helpers
+# ===========================================================================
+
+def _make_history_entry(role: str, content: str, event_type: str | None = None) -> dict:
+ entry = {"role": role, "content": content}
+ if event_type is not None:
+ entry["event_type"] = event_type
+ return entry
+
+
+def _write_history_json(path: Path, entries: list[dict]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(entries, ensure_ascii=False), encoding="utf-8")
+
+
+# ===========================================================================
+# DreamingConfig.load()
+# ===========================================================================
+
+class TestDreamingConfigLoad:
+ """Test DreamingConfig.load() with mock config."""
+
+ def test_default_disabled(self):
+ cfg = self._cfg({})
+ assert cfg.enabled is False
+ assert cfg.interval_seconds == 14400.0
+
+ def test_enabled_via_config(self):
+ cfg = self._cfg({"memory": {"dreaming": {"code": {"enabled": True}}}})
+ assert cfg.enabled is True
+
+ def test_interval_via_config(self):
+ cfg = self._cfg({"memory": {"dreaming": {"code": {"enabled": True, "interval_seconds": 7200}}}})
+ assert cfg.interval_seconds == 7200.0
+
+ def test_enabled_via_env(self, monkeypatch):
+ monkeypatch.setenv("DREAMING_CODE_ENABLED", "true")
+ cfg = self._cfg({})
+ assert cfg.enabled is True
+
+ def test_disabled_via_env(self, monkeypatch):
+ monkeypatch.setenv("DREAMING_CODE_ENABLED", "0")
+ cfg = self._cfg({"memory": {"dreaming": {"code": {"enabled": True}}}})
+ assert cfg.enabled is False
+
+ def test_interval_via_env(self, monkeypatch):
+ monkeypatch.setenv("DREAMING_INTERVAL", "3600")
+ cfg = self._cfg({"memory": {"dreaming": {"code": {"enabled": True}}}})
+ assert cfg.interval_seconds == 3600.0
+
+ def test_agent_mode(self):
+ cfg = self._cfg({"memory": {"dreaming": {"agent": {"enabled": True}}}}, mode="agent")
+ assert cfg.enabled is True
+
+ @staticmethod
+ def _cfg(memory_overrides: dict, *, mode: str = "code") -> object:
+ from dataclasses import dataclass
+
+ @dataclass
+ class DreamingConfig:
+ enabled: bool = False
+ interval_seconds: float = 14400.0
+
+ @classmethod
+ def load(cls, mode: str = "code"):
+ config = {"memory": memory_overrides.get("memory", {})}
+ raw = config.get("memory", {}).get("dreaming", {}).get(mode, {})
+ if not isinstance(raw, dict):
+ raw = {}
+ env_key = f"DREAMING_{mode.upper()}_ENABLED"
+ env_val = os.getenv(env_key)
+ enabled = env_val.lower() in ("true", "1", "yes") if env_val is not None else bool(
+ raw.get("enabled", False))
+ interval = float(os.getenv("DREAMING_INTERVAL", str(raw.get("interval_seconds", 14400.0))))
+ return cls(enabled=enabled, interval_seconds=interval)
+
+ return DreamingConfig.load(mode=mode)
+
+
+# ===========================================================================
+# _parse_history
+# ===========================================================================
+
+class TestParseHistory:
+ @staticmethod
+ def test_empty_dir(tmp_path):
+ result = _parse_history(tmp_path / "nonexistent")
+ assert result == []
+
+ @staticmethod
+ def test_no_history_json(tmp_path):
+ session_dir = tmp_path / "sess_001"
+ session_dir.mkdir()
+ result = _parse_history(session_dir)
+ assert result == []
+
+ @staticmethod
+ def test_filters_deltas(tmp_path):
+ entries = [
+ _make_history_entry("user", "hello"),
+ _make_history_entry("assistant", "part 1", "chat.delta"),
+ _make_history_entry("assistant", "full answer", "chat.final"),
+ ]
+ _write_history_json(tmp_path / "sess_001" / "history.json", entries)
+
+ result = _parse_history(tmp_path / "sess_001")
+ assert len(result) == 2
+ assert result[0]["role"] == "user"
+ assert result[1]["event_type"] == "chat.final"
+
+ @staticmethod
+ def test_filters_errors(tmp_path):
+ entries = [
+ _make_history_entry("user", "hello"),
+ _make_history_entry("assistant", "error msg", "chat.error"),
+ _make_history_entry("assistant", "final", "chat.final"),
+ ]
+ _write_history_json(tmp_path / "sess_001" / "history.json", entries)
+
+ result = _parse_history(tmp_path / "sess_001")
+ assert len(result) == 2
+
+ @staticmethod
+ def test_keeps_legacy_assistant(tmp_path):
+ entries = [
+ _make_history_entry("user", "hello"),
+ _make_history_entry("assistant", "old format"), # no event_type
+ ]
+ _write_history_json(tmp_path / "sess_001" / "history.json", entries)
+
+ result = _parse_history(tmp_path / "sess_001")
+ assert len(result) == 2
+ assert result[1]["role"] == "assistant"
+
+ @staticmethod
+ def test_corrupted_json_returns_empty(tmp_path):
+ path = tmp_path / "sess_001" / "history.json"
+ path.parent.mkdir()
+ path.write_text("{invalid json", encoding="utf-8")
+ result = _parse_history(tmp_path / "sess_001")
+ assert result == []
+
+
+# ===========================================================================
+# _detect_rounds
+# ===========================================================================
+
+class TestDetectRounds:
+ @staticmethod
+ def test_empty():
+ assert _detect_rounds([]) == []
+
+ @staticmethod
+ def test_single_round():
+ events = [
+ {"role": "user"}, {"role": "assistant"},
+ ]
+ assert _detect_rounds(events) == [(0, 1)]
+
+ @staticmethod
+ def test_multi_round():
+ events = [
+ {"role": "user"}, {"role": "assistant"},
+ {"role": "user"}, {"role": "assistant"},
+ {"role": "user"}, {"role": "assistant"},
+ ]
+ rounds = _detect_rounds(events)
+ assert len(rounds) == 3
+ assert rounds[0] == (0, 1)
+ assert rounds[1] == (2, 3)
+ assert rounds[2] == (4, 5)
+
+ @staticmethod
+ def test_consecutive_users_takes_last():
+ events = [
+ {"role": "user"}, {"role": "user"}, {"role": "assistant"},
+ ]
+ rounds = _detect_rounds(events)
+ assert rounds == [(1, 2)]
+
+ @staticmethod
+ def test_unmatched_user():
+ events = [
+ {"role": "user"}, {"role": "assistant"}, {"role": "user"},
+ ]
+ rounds = _detect_rounds(events)
+ assert rounds == [(0, 1)]
+
+ @staticmethod
+ def test_unmatched_assistant():
+ events = [
+ {"role": "assistant"}, {"role": "user"}, {"role": "assistant"},
+ ]
+ rounds = _detect_rounds(events)
+ assert rounds == [(1, 2)]
+
+
+# ===========================================================================
+# _compress
+# ===========================================================================
+
+class TestCompress:
+ @staticmethod
+ def test_simple():
+ events = [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "hello"},
+ ]
+ result = _compress(events)
+ assert "[User]: hi" in result
+ assert "[Assistant]: hello" in result
+
+ @staticmethod
+ def test_truncates_long_messages():
+ long_user = "x" * 3000
+ long_assistant = "y" * 5000
+ events = [
+ {"role": "user", "content": long_user},
+ {"role": "assistant", "content": long_assistant},
+ ]
+ result = _compress(events)
+ assert len("[User]: " + long_user) > len(result.split("[User]: ")[1].split("\n")[0])
+ user_part = result.split("[User]: ")[1].split("\n\n")[0]
+ assert len(user_part) <= 2000
+
+ @staticmethod
+ def test_empty_assistant_skipped():
+ events = [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": ""},
+ ]
+ result = _compress(events)
+ assert "assistant" not in result.lower()
+ assert "[User]: hi" in result
+
+ @staticmethod
+ def test_triggers_trim_on_large_input():
+ events = []
+ for i in range(100):
+ events.append({"role": "user", "content": "x" * 2000})
+ events.append({"role": "assistant", "content": "y" * 3000})
+ result = _compress(events)
+ assert "已省略" in result or "已截断" in result
+
+
+# ===========================================================================
+# _parse_dreaming_entries
+# ===========================================================================
+
+class TestParseDreamingEntries:
+ @staticmethod
+ def test_empty():
+ assert _parse_dreaming_entries("") == []
+
+ @staticmethod
+ def test_single_entry():
+ text = "# Dreaming 记忆\n\n## 标题A\n_source: sess_1 | 2026-04-15_\n正文内容"
+ entries = _parse_dreaming_entries(text)
+ assert len(entries) == 1
+ assert entries[0]["title"] == "标题A"
+ assert entries[0]["source"] == "_source: sess_1 | 2026-04-15_"
+ assert entries[0]["content"] == "正文内容"
+
+ @staticmethod
+ def test_multi_entry():
+ text = "# Dreaming\n\n## A\n_source: s1_\nbody a\n\n## B\n_source: s2_\nbody b"
+ entries = _parse_dreaming_entries(text)
+ assert len(entries) == 2
+ assert entries[0]["title"] == "A"
+ assert entries[1]["title"] == "B"
+
+ @staticmethod
+ def test_no_source_line():
+ text = "# Dreaming\n\n## A\njust content"
+ entries = _parse_dreaming_entries(text)
+ assert entries[0]["source"] == ""
+ assert entries[0]["content"] == "just content"
+
+
+# ===========================================================================
+# promote_agent
+# ===========================================================================
+
[email protected](not _DREAMING_AVAILABLE, reason="openjiuwen dreaming module is not available")
+class TestPromoteAgent:
+ @staticmethod
+ def test_first_entry_creates_file(tmp_path):
+ output_dir = tmp_path / "memory"
+ output_dir.mkdir(parents=True, exist_ok=True)
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="agent")
+ result = sweeper.promote_agent("New Title", "New content body", "sess_001")
+ assert result is not None
+ text = Path(result).read_text(encoding="utf-8")
+ assert "# Dreaming" in text
+ assert "## New Title" in text
+ assert "New content body" in text
+
+ @staticmethod
+ def test_dedup_title(tmp_path):
+ output_dir = tmp_path / "memory"
+ output_dir.mkdir(parents=True, exist_ok=True)
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="agent")
+ sweeper.promote_agent("Same Title", "Content A", "sess_001")
+ result = sweeper.promote_agent("Same Title", "Content B", "sess_002")
+ assert result is None
+
+ @staticmethod
+ def test_eviction_at_limit(tmp_path):
+ output_dir = tmp_path / "memory"
+ output_dir.mkdir(parents=True, exist_ok=True)
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="agent")
+ for i in range(_MAX_ENTRIES_AGENT + 5):
+ sweeper.promote_agent(f"Title_{i:03d}", f"Content {i}", "sess_001")
+
+ entries = _parse_dreaming_entries(
+ (tmp_path / "memory" / "DREAMING.md").read_text(encoding="utf-8")
+ )
+ assert len(entries) == _MAX_ENTRIES_AGENT
+ assert entries[0]["title"] == "Title_005"
+
+
+# ===========================================================================
+# promote_code
+# ===========================================================================
+
[email protected](not _DREAMING_AVAILABLE, reason="openjiuwen dreaming module is not available")
+class TestPromoteCode:
+ @staticmethod
+ def test_creates_file_with_hash_name(tmp_path):
+ output_dir = tmp_path / "memory"
+ output_dir.mkdir(parents=True, exist_ok=True)
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="code")
+ result = sweeper.promote_code("Title A", "Body content", "sess_001")
+ assert result is not None
+ path = Path(result)
+ assert path.exists()
+ assert path.name.startswith("consolidated_")
+ assert path.name.endswith(".md")
+ text = path.read_text(encoding="utf-8")
+ assert "name: Title A" in text
+ assert "source_session: sess_001" in text
+ assert "Body content" in text
+
+ @staticmethod
+ def test_same_content_dedup(tmp_path):
+ output_dir = tmp_path / "memory"
+ output_dir.mkdir(parents=True, exist_ok=True)
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="code")
+ r1 = sweeper.promote_code("Title", "Same body", "sess_001")
+ r2 = sweeper.promote_code("Title", "Same body", "sess_001")
+ assert r1 is not None
+ assert r2 is None
+
+
+# ===========================================================================
+# checkpoint
+# ===========================================================================
+
[email protected](not _DREAMING_AVAILABLE, reason="openjiuwen dreaming module is not available")
+class TestCheckpoint:
+ @staticmethod
+ def test_save_and_load(tmp_path):
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ sweeper.scanned_sessions["sess_001"] = {"history_mtime": 1.0, "round_count": 3}
+ sweeper.save_checkpoint()
+
+ sweeper2 = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper2.init()
+ assert "sess_001" in sweeper2.scanned_sessions
+ assert sweeper2.scanned_sessions["sess_001"]["round_count"] == 3
+
+ @staticmethod
+ def test_backward_compat_list_format(tmp_path):
+ cp_path = tmp_path / "memory" / ".dreams" / "ingestion-checkpoint.json"
+ cp_path.parent.mkdir(parents=True)
+ cp_path.write_text(json.dumps({"scanned_sessions": ["sess_a", "sess_b"]}), encoding="utf-8")
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ assert "sess_a" in sweeper.scanned_sessions
+ assert sweeper.scanned_sessions["sess_a"] == {}
+
+
+# ===========================================================================
+# scan_new_sessions
+# ===========================================================================
+
[email protected](not _DREAMING_AVAILABLE, reason="openjiuwen dreaming module is not available")
+class TestScanNewSessions:
+ @staticmethod
+ def _make_session(sessions_root: Path, sid: str, entries: list[dict], age_delta: float = 0):
+ session_dir = sessions_root / sid
+ session_dir.mkdir(parents=True)
+ _write_history_json(session_dir / "history.json", entries)
+ metadata = {"mode": "code.normal", "session_id": sid, "created_at": time.time()}
+ _write_history_json(session_dir / "metadata.json", metadata)
+ mtime = time.time() - age_delta
+ os.utime(session_dir, (mtime, mtime))
+ os.utime(session_dir / "history.json", (mtime, mtime))
+
+ @staticmethod
+ def test_no_sessions_dir(tmp_path):
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "no_such_dir"),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ result = sweeper.scan_new_sessions()
+ assert result == []
+
+ def test_excludes_heartbeat(self, tmp_path):
+ sessions_root = tmp_path / "sessions"
+ (sessions_root / "heartbeat_check").mkdir(parents=True)
+ # create 3 valid sessions with 4 rounds each
+ for i in range(3):
+ entries = []
+ for j in range(1, 5):
+ entries.append(_make_history_entry("user", f"q{j}"))
+ entries.append(_make_history_entry("assistant", f"a{j}", "chat.final"))
+ self._make_session(sessions_root, f"sess_00{i+1}", entries)
+ sweeper = Sweeper(sessions_dir=str(sessions_root),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ result = sweeper.scan_new_sessions()
+ ids = {s["session_id"] for s in result}
+ assert "heartbeat_check" not in ids
+
+ def test_skips_insufficient_rounds(self, tmp_path):
+ sessions_root = tmp_path / "sessions"
+ # create 3 sessions, each with only 2 rounds (< MIN_SESSION_ROUNDS)
+ for i in range(3):
+ entries = [
+ _make_history_entry("user", "hi"), _make_history_entry("assistant", "hey", "chat.final"),
+ _make_history_entry("user", "bye"), _make_history_entry("assistant", "bye", "chat.final"),
+ ]
+ self._make_session(sessions_root, f"sess_00{i+1}", entries)
+ sweeper = Sweeper(sessions_dir=str(sessions_root),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ result = sweeper.scan_new_sessions()
+ assert result == []
+
+ def test_scans_valid_session(self, tmp_path):
+ sessions_root = tmp_path / "sessions"
+ # create 3 sessions, each with 4 valid rounds
+ for i in range(3):
+ entries = []
+ for j in range(1, 5):
+ entries.append(_make_history_entry("user", f"q{j}"))
+ entries.append(_make_history_entry("assistant", f"a{j}", "chat.final"))
+ self._make_session(sessions_root, f"sess_00{i+1}", entries)
+ sweeper = Sweeper(sessions_dir=str(sessions_root),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ result = sweeper.scan_new_sessions()
+ assert len(result) == 3
+ assert result[0]["session_id"] == "sess_001"
+ assert result[0]["compressed_text"]
+
+ def test_incremental_scan_unchanged_skipped(self, tmp_path):
+ sessions_root = tmp_path / "sessions"
+ # create 3 sessions, each with 4 valid rounds
+ for i in range(3):
+ entries = []
+ for j in range(1, 5):
+ entries.append(_make_history_entry("user", f"q{j}"))
+ entries.append(_make_history_entry("assistant", f"a{j}", "chat.final"))
+ self._make_session(sessions_root, f"sess_00{i+1}", entries)
+ sweeper = Sweeper(sessions_dir=str(sessions_root),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ result1 = sweeper.scan_new_sessions()
+ assert len(result1) == 3
+
+ # mark all 3 as scanned
+ for i in range(3):
+ sid = f"sess_00{i+1}"
+ sweeper.scanned_sessions[sid] = {
+ "history_mtime": (sessions_root / sid / "history.json").stat().st_mtime,
+ "round_count": 4,
+ }
+ result2 = sweeper.scan_new_sessions()
+ assert result2 == []
+
+ def test_incremental_scan_updated_reprocesses(self, tmp_path):
+ sessions_root = tmp_path / "sessions"
+ # create 3 sessions, each with 4 valid rounds
+ for i in range(3):
+ entries = []
+ for j in range(1, 5):
+ entries.append(_make_history_entry("user", f"q{j}"))
+ entries.append(_make_history_entry("assistant", f"a{j}", "chat.final"))
+ self._make_session(sessions_root, f"sess_00{i+1}", entries)
+ sweeper = Sweeper(sessions_dir=str(sessions_root),
+ output_dir=str(tmp_path / "memory"), mode="code")
+ sweeper.init()
+ # mark sess_001 as already scanned (with 4 rounds), sess_002 and sess_003 as new
+ sweeper.scanned_sessions["sess_001"] = {
+ "history_mtime": (sessions_root / "sess_001" / "history.json").stat().st_mtime - 1,
+ "round_count": 4,
+ }
+
+ time.sleep(0.1)
+ # add 4 more rounds to sess_001
+ more_entries = [
+ _make_history_entry("user", "q5"), _make_history_entry("assistant", "a5", "chat.final"),
+ _make_history_entry("user", "q6"), _make_history_entry("assistant", "a6", "chat.final"),
+ _make_history_entry("user", "q7"), _make_history_entry("assistant", "a7", "chat.final"),
+ _make_history_entry("user", "q8"), _make_history_entry("assistant", "a8", "chat.final"),
+ ]
+ existing = json.loads((sessions_root / "sess_001" / "history.json").read_text(encoding="utf-8"))
+ existing.extend(more_entries)
+ (sessions_root / "sess_001" / "history.json").write_text(json.dumps(existing), encoding="utf-8")
+
+ result = sweeper.scan_new_sessions()
+ assert len(result) == 3 # sess_001 updated + sess_002 & sess_003 new
+ # find the sess_001 result
+ sess_001_result = [r for r in result if r["session_id"] == "sess_001"]
+ assert len(sess_001_result) == 1
+ assert "q5" in sess_001_result[0]["compressed_text"]
+
+
+# ===========================================================================
+# load_existing_summary
+# ===========================================================================
+
[email protected](not _DREAMING_AVAILABLE, reason="openjiuwen dreaming module is not available")
+class TestLoadExistingSummary:
+ @staticmethod
+ def test_empty_output_dir(tmp_path):
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(tmp_path / "not_exist"), mode="agent")
+ assert sweeper.load_existing_summary() == "(空)"
+
+ @staticmethod
+ def test_agent_mode_no_file(tmp_path):
+ output_dir = tmp_path / "memory"
+ output_dir.mkdir()
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="agent")
+ assert sweeper.load_existing_summary() == "(空)"
+
+ @staticmethod
+ def test_agent_mode_with_entries(tmp_path):
+ output_dir = tmp_path / "memory"
+ output_dir.mkdir()
+ (output_dir / "DREAMING.md").write_text(
+ "# Dreaming 记忆\n\n## 标题A\n_source: s1_\nbody a\n\n## 标题B\n_source: s2_\nbody b",
+ encoding="utf-8",
+ )
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="agent")
+ result = sweeper.load_existing_summary()
+ assert "- 标题A" in result
+ assert "- 标题B" in result
+
+ @staticmethod
+ def test_code_mode_with_files(tmp_path):
+ output_dir = tmp_path / "coding_memory"
+ output_dir.mkdir()
+ import hashlib
+ h = hashlib.sha256("body".encode()).hexdigest()[:12]
+ (output_dir / f"consolidated_{h}.md").write_text(
+ "---\nname: 知识点X\n---\n\nbody\n", encoding="utf-8",
+ )
+ sweeper = Sweeper(sessions_dir=str(tmp_path / "sessions"),
+ output_dir=str(output_dir), mode="code")
+ result = sweeper.load_existing_summary()
+ assert "- 知识点X" in result
+
+
+# ===========================================================================
+# SessionManager.has_active_tasks
+# ===========================================================================
+
+class TestSessionManagerHasActiveTasks:
+ @staticmethod
+ def test_no_tasks():
+ from jiuwenswarm.server.runtime.session.session_manager import SessionManager
+ sm = SessionManager()
+ assert sm.has_active_tasks() is False
+
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_with_active_task():
+ from jiuwenswarm.server.runtime.session.session_manager import SessionManager
+ import asyncio
+ sm = SessionManager()
+
+ async def sleepy():
+ await asyncio.sleep(99)
+
+ await sm.submit_task("sess_1", sleepy)
+ await asyncio.sleep(0.05)
+ assert sm.has_active_tasks() is True
+ await sm.cancel_session_task("sess_1")
+ await asyncio.sleep(0)
+ assert sm.has_active_tasks() is False
+
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_ignores_none_tasks():
+ from jiuwenswarm.server.runtime.session.session_manager import SessionManager
+ import asyncio
+ sm = SessionManager()
+
+ async def quick():
+ pass
+
+ await sm.submit_task("sess_1", quick)
+ await asyncio.sleep(0.05)
+ assert sm.has_active_tasks() is False
\ No newline at end of file