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(coding-memory): isolate project storage and import legacy markdown
NickFuryXXX6a6bad494443
diff --git a/docs/en/CodingMemory.md b/docs/en/CodingMemory.mdindex 2cf43ce040..4ff9fd3d44 100644--- a/docs/en/CodingMemory.md+++ b/docs/en/CodingMemory.md@@ -77,7 +77,39 @@ All three memory systems can coexist in Code mode.## Storage-Coding memory data is stored in the `workspace/agent/memory/` directory, sharing the storage path with built-in memory.+Coding memory is isolated from built-in memory and stored per project under the+Agent data workspace:++```text+<agent_workspace>/coding_memory/<project_name>/+```++When no project is bound, `project_name` is `default`. `MEMORY.md` is the memory+index, other top-level Markdown files contain the memories, and files such as+`memory.db` are rebuildable search indexes.++### Upgrading from the legacy backend++The legacy backend stored project coding memory directly in+`<project_dir>/coding_memory/`. The first time the project enters Code mode, or+an automatic coding-memory extraction runs, its top-level Markdown files are+merged into the new project bucket automatically:++- The legacy directory remains unchanged for rollback.+- Identical content is deduplicated by SHA-256. A same-name file with different+ content is imported as `<stem>__legacy_<hash8>.md`; new data is never overwritten.+- Databases, lock files, caches, subdirectories, and symbolic links are not+ migrated. The new backend rebuilds its search index from Markdown.+- Migration is idempotent. If a rollback adds legacy memories, the changed source+ fingerprint causes a later initialization to merge only the new content.+- The target records `.coding-memory-migration-v1.json`. A failed attempt does not+ block Code mode or mark that source complete, so the next initialization retries it.++Only an Agent workspace that can be identified unambiguously as the default space+considers the legacy `service_default/agent_default` and flat legacy workspace+paths. A non-default `workspace_key` does not import them even when no project is+bound. The system does not scan arbitrary `service_id/agent_id` directories because+their ownership cannot be inferred safely.---@@ -93,4 +125,4 @@ See [Memory → Dreaming: Sleep-Time Memory Consolidation](Memory.md#dreaming-sl- [Modes](Modes.md) — Mode configuration and switching- [Memory](Memory.md) — Built-in memory and external memory-- [Task Memory](TaskMemory.md) — Task-level experience retrieval\ No newline at end of file+- [Task Memory](TaskMemory.md) — Task-level experience retrievaldiff --git "a/docs/zh/\347\274\226\347\240\201\350\256\260\345\277\206.md" "b/docs/zh/\347\274\226\347\240\201\350\256\260\345\277\206.md"index 61d5e0afc3..c5093ce140 100644--- "a/docs/zh/\347\274\226\347\240\201\350\256\260\345\277\206.md"+++ "b/docs/zh/\347\274\226\347\240\201\350\256\260\345\277\206.md"@@ -77,7 +77,34 @@ modes:## 存储-编码记忆数据存储在 `workspace/agent/memory/` 目录下,与内建记忆共享存储路径。+编码记忆与内建记忆隔离,按项目存储在 Agent 数据工作区中:++```text+<agent_workspace>/coding_memory/<project_name>/+```++未绑定项目时,`project_name` 为 `default`。目录中的 `MEMORY.md` 是记忆索引,+其他顶层 Markdown 文件保存具体记忆;`memory.db` 等文件是可重建的检索索引。++### 从旧版升级++旧版把编码记忆直接存放在 `<project_dir>/coding_memory/`。升级后第一次进入对应+项目的 Code 模式或触发自动编码记忆提取时,系统会把旧版顶层 Markdown 文件自动+合并到新的项目目录:++- 旧目录只读保留,不会移动或删除,可用于回滚。+- 相同内容按 SHA-256 去重;同名但内容不同的旧文件保存为+ `<stem>__legacy_<hash8>.md`,不会覆盖新版文件。+- `memory.db`、锁文件、缓存、子目录和符号链接不会迁移;新版会根据 Markdown+ 重新建立检索索引。+- 迁移具有幂等性;旧版回滚后新增的记忆会在下次使用时继续增量合并。+- 迁移报告写入目标目录的 `.coding-memory-migration-v1.json`。单次迁移失败不会+ 阻断 Code 模式,也不会写入完成标记,后续初始化会自动重试。++只有当前 Agent 工作区能够明确识别为默认空间时,系统才会兼容迁移旧版+`service_default/agent_default` 和旧扁平工作区中的编码记忆。非 default 的+`workspace_key` 即使未绑定项目也不会导入这些目录;系统不会扫描任意+`service_id/agent_id`,以免无法确认归属时发生跨用户迁移。---@@ -93,4 +120,4 @@ Code 模式启用 Dreaming 后,系统会闲时回看历史 coding 会话,自- [模式系统](模式系统.md) — 各模式配置与切换- [记忆系统](记忆.md) — 内建记忆与外接记忆-- [经验记忆](经验记忆.md) — 任务级经验检索\ No newline at end of file+- [经验记忆](经验记忆.md) — 任务级经验检索diff --git a/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py b/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.pyindex c84543ffb0..e9143af065 100644--- a/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py+++ b/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py@@ -214,11 +214,30 @@ async def _execute_auto_memory_extraction(# Get coding memory directory (unified with Auto Memory)from jiuwenswarm.common.utils import get_agent_workspace_dir- from jiuwenswarm.common.coding_memory_paths import resolve_project_coding_memory_dir- memory_dir = Path(resolve_project_coding_memory_dir(+ from jiuwenswarm.common.coding_memory_paths import prepare_project_coding_memory_dir+ migration = prepare_project_coding_memory_dir(agent_workspace_dir=get_agent_workspace_dir(),project_dir=project_dir,- ))+ )+ memory_dir = Path(migration.target_dir)+ if migration.failed or migration.index_truncated:+ logger.warning(+ "[auto_memory] Coding Memory legacy migration needs attention; "+ "continuing with the new directory",+ extra={+ "user_visible": "progress",+ "coding_memory_migration": {+ "target": migration.target_dir,+ "sources": migration.source_paths,+ "sources_found": migration.sources_found,+ "sources_migrated": migration.sources_migrated,+ "copied": migration.copied,+ "duplicates": migration.duplicates,+ "renamed": migration.renamed,+ "index_truncated": migration.index_truncated,+ },+ },+ )# Ensure memory directory existsmemory_dir.mkdir(parents=True, exist_ok=True)diff --git a/jiuwenswarm/common/coding_memory_paths.py b/jiuwenswarm/common/coding_memory_paths.pyindex e881bad909..5f531b0e36 100644--- a/jiuwenswarm/common/coding_memory_paths.py+++ b/jiuwenswarm/common/coding_memory_paths.py@@ -1,14 +1,58 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Helpers for resolving project-scoped coding memory paths."""+"""Resolve project-scoped Coding Memory paths and import legacy data."""from __future__ import annotations+from dataclasses import dataclass+from datetime import datetime, timezone+import hashlib+import json+import loggingimport ntpathimport osfrom os import PathLike+from pathlib import Path+import re+import tempfile+from typing import Any++import portalocker+++logger = logging.getLogger(__name__)DEFAULT_CODING_MEMORY_PROJECT = "default"+_INDEX_FILENAME = "MEMORY.md"+_MIGRATION_REPORT_FILENAME = ".coding-memory-migration-v1.json"+_MIGRATION_REPORT_VERSION = 1+_MAX_INDEX_LINES = 200+_LOCK_TIMEOUT_SECONDS = 1+_INDEX_ENTRY_RE = re.compile(+ r"^\s*-\s+\[(?P<name>.+?)\]\((?P<path>[^)]+)\)\s+(?:—|-)\s+(?P<description>.*)$"+)+++@dataclass(frozen=True)+class CodingMemoryMigrationResult:+ """Outcome of preparing one project-scoped Coding Memory directory."""++ target_dir: str+ source_paths: tuple[str, ...] = ()+ sources_found: int = 0+ sources_migrated: int = 0+ copied: int = 0+ duplicates: int = 0+ renamed: int = 0+ index_truncated: int = 0+ warnings: tuple[str, ...] = ()+ failed: bool = False+++@dataclass(frozen=True)+class _LegacyMemoryFile:+ path: Path+ content_hash: strdef resolve_coding_memory_project_name(project_dir: str | PathLike[str] | None) -> str:@@ -32,7 +76,7 @@ def resolve_project_coding_memory_dir(agent_workspace_dir: str | PathLike[str],project_dir: str | PathLike[str] | None,) -> str:- """Resolve ``<agent_workspace>/coding_memory/<project_name>``."""+ """Resolve <agent_workspace>/coding_memory/<project_name>."""return os.path.join(os.path.abspath(str(agent_workspace_dir)),"coding_memory",@@ -44,8 +88,550 @@ def resolve_project_coding_memory_workspace_path(*,project_dir: str | PathLike[str] | None,) -> str:- """Resolve the workspace-relative ``coding_memory/<project_name>`` path."""+ """Resolve the workspace-relative coding_memory/<project_name> path."""return os.path.join("coding_memory",resolve_coding_memory_project_name(project_dir),)+++def _canonical_path(path: Path) -> str:+ try:+ return os.path.normcase(str(path.resolve(strict=False)))+ except (OSError, RuntimeError):+ return os.path.normcase(os.path.abspath(str(path)))+++def _data_root_from_agent_workspace(agent_workspace: Path) -> Path | None:+ """Return the root for <root>/<tenant>/agent/workspace layouts."""+ try:+ if (+ agent_workspace.name in {"workspace", "jiuwenclaw_workspace"}+ and agent_workspace.parent.name == "agent"+ ):+ tenant_root = agent_workspace.parents[1]+ if (+ tenant_root.name.startswith("agent_")+ and tenant_root.parent.name.startswith("service_")+ ):+ return tenant_root.parents[1]+ if tenant_root.name.startswith("workspace_"):+ return tenant_root.parent+ return tenant_root+ except IndexError:+ return None+ return None+++def _is_default_agent_workspace(agent_workspace: Path) -> bool:+ """Return whether an unbound workspace has an unambiguous default identity."""+ try:+ if (+ agent_workspace.name not in {"workspace", "jiuwenclaw_workspace"}+ or agent_workspace.parent.name != "agent"+ ):+ return False+ tenant_root = agent_workspace.parents[1]+ if tenant_root.name == "workspace_default":+ return True+ if (+ tenant_root.name == "agent_default"+ and tenant_root.parent.name == "service_default"+ ):+ return True+ return not (+ tenant_root.name.startswith("workspace_")+ or tenant_root.name.startswith("agent_")+ )+ except IndexError:+ return False+++def _legacy_source_candidates(+ *,+ agent_workspace_dir: Path,+ project_dir: str | PathLike[str] | None,+) -> list[Path]:+ raw_project_dir = str(project_dir).strip() if project_dir is not None else ""+ if raw_project_dir:+ return [Path(raw_project_dir).expanduser() / "coding_memory"]++ if not _is_default_agent_workspace(agent_workspace_dir):+ return []++ data_root = _data_root_from_agent_workspace(agent_workspace_dir)+ roots: list[Path] = []+ if data_root is not None:+ roots.append(data_root)+ if data_root.name == ".jiuwenswarm":+ roots.append(data_root.parent / ".jiuwenclaw")++ candidates: list[Path] = []+ for root in roots:+ candidates.extend(+ [+ root+ / "service_default"+ / "agent_default"+ / "agent"+ / "jiuwenclaw_workspace"+ / "coding_memory",+ root / "agent" / "jiuwenclaw_workspace" / "coding_memory",+ ]+ )++ unique: list[Path] = []+ seen: set[str] = set()+ for candidate in candidates:+ key = _canonical_path(candidate)+ if key not in seen:+ seen.add(key)+ unique.append(candidate)+ return unique+++def _hash_file(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as file_obj:+ for chunk in iter(lambda: file_obj.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _scan_markdown_files(source: Path) -> tuple[list[_LegacyMemoryFile], list[str]]:+ files: list[_LegacyMemoryFile] = []+ warnings: list[str] = []+ for path in sorted(source.iterdir(), key=lambda item: item.name.casefold()):+ if path.name.casefold() == _INDEX_FILENAME.casefold():+ continue+ if path.suffix.casefold() != ".md":+ continue+ if path.is_symlink():+ warnings.append(f"skipped symbolic link: {path.name}")+ continue+ if not path.is_file():+ continue+ files.append(_LegacyMemoryFile(path=path, content_hash=_hash_file(path)))+ return files, warnings+++def _source_fingerprint(source: Path, files: list[_LegacyMemoryFile]) -> str:+ digest = hashlib.sha256()+ index_path = source / _INDEX_FILENAME+ if index_path.is_file() and not index_path.is_symlink():+ digest.update(_INDEX_FILENAME.encode("utf-8"))+ digest.update(_hash_file(index_path).encode("ascii"))+ for memory_file in files:+ digest.update(memory_file.path.name.encode("utf-8", errors="surrogatepass"))+ digest.update(memory_file.content_hash.encode("ascii"))+ return digest.hexdigest()+++def _source_state_token(source: Path) -> str:+ """Hash cheap file metadata for the completed-migration fast path."""+ digest = hashlib.sha256()+ for path in sorted(source.iterdir(), key=lambda item: item.name.casefold()):+ if path.is_symlink() or not path.is_file():+ continue+ if (+ path.name.casefold() != _INDEX_FILENAME.casefold()+ and path.suffix.casefold() != ".md"+ ):+ continue+ stat = path.stat()+ digest.update(path.name.encode("utf-8", errors="surrogatepass"))+ digest.update(b"\0")+ digest.update(str(stat.st_size).encode("ascii"))+ digest.update(b"\0")+ digest.update(str(stat.st_mtime_ns).encode("ascii"))+ digest.update(b"\0")+ digest.update(str(stat.st_ctime_ns).encode("ascii"))+ digest.update(b"\0")+ return digest.hexdigest()+++def _read_json_object(path: Path) -> dict[str, Any]:+ try:+ value = json.loads(path.read_text(encoding="utf-8"))+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):+ return {}+ return value if isinstance(value, dict) else {}+++def _atomic_write_bytes(path: Path, content: bytes) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temp_name = tempfile.mkstemp(+ prefix=f".{path.name}.",+ suffix=".tmp",+ dir=path.parent,+ )+ try:+ with os.fdopen(fd, "wb") as file_obj:+ file_obj.write(content)+ file_obj.flush()+ os.fsync(file_obj.fileno())+ os.replace(temp_name, path)+ except BaseException:+ try:+ os.unlink(temp_name)+ except OSError:+ pass+ raise+++def _atomic_write_text(path: Path, content: str) -> None:+ _atomic_write_bytes(path, content.encode("utf-8"))+++def _parse_index_entries(path: Path) -> tuple[list[str], dict[str, tuple[str, str]]]:+ if path.is_symlink():+ return [], {}+ try:+ lines = path.read_text(encoding="utf-8").splitlines()+ except (FileNotFoundError, OSError, UnicodeError):+ return [], {}+ entries: dict[str, tuple[str, str]] = {}+ for line in lines:+ match = _INDEX_ENTRY_RE.match(line)+ if match:+ entries[os.path.normcase(match.group("path"))] = (+ match.group("name"),+ match.group("description"),+ )+ return lines, entries+++def _frontmatter_title_and_description(path: Path) -> tuple[str, str] | None:+ try:+ text = path.read_text(encoding="utf-8")+ except (OSError, UnicodeError):+ return None+ stripped = text.lstrip()+ if not stripped.startswith("---"):+ return None+ end = stripped.find("---", 3)+ if end < 0:+ return None+ fields: dict[str, str] = {}+ for line in stripped[3:end].splitlines():+ key, separator, value = line.partition(":")+ if separator:+ fields[key.strip()] = value.strip()+ name = fields.get("name")+ description = fields.get("description")+ if not name or not description:+ return None+ return name, description+++def _conflict_filename(target: Path, source_file: _LegacyMemoryFile) -> str:+ stem = source_file.path.stem+ suffix = source_file.path.suffix+ for length in (8, 12, 16, 64):+ candidate = f"{stem}__legacy_{source_file.content_hash[:length]}{suffix}"+ candidate_path = target / candidate+ if candidate_path.is_symlink():+ continue+ if (+ not candidate_path.exists()+ or _hash_file(candidate_path) == source_file.content_hash+ ):+ return candidate+ raise FileExistsError(+ f"unable to allocate conflict filename for {source_file.path.name}"+ )+++def _append_index_entries(+ *,+ target: Path,+ source: Path,+ final_names: dict[str, str],+) -> int:+ target_index = target / _INDEX_FILENAME+ target_lines, target_entries = _parse_index_entries(target_index)+ source_lines, source_entries = _parse_index_entries(source / _INDEX_FILENAME)+ appended: list[str] = []++ final_names_by_key = {+ os.path.normcase(name): value for name, value in final_names.items()+ }+ ordered_source_names: list[str] = []+ seen_source_names: set[str] = set()+ for line in source_lines:+ match = _INDEX_ENTRY_RE.match(line)+ if match:+ source_name = match.group("path")+ source_key = os.path.normcase(source_name)+ if source_key in final_names_by_key:+ ordered_source_names.append(source_name)+ seen_source_names.add(source_key)+ ordered_source_names.extend(+ name for name in final_names if os.path.normcase(name) not in seen_source_names+ )++ for source_name in ordered_source_names:+ final_name = final_names_by_key[os.path.normcase(source_name)]+ if os.path.normcase(final_name) in target_entries:+ continue+ metadata = _frontmatter_title_and_description(target / final_name)+ if metadata is None:+ metadata = source_entries.get(os.path.normcase(source_name))+ if metadata is None:+ metadata = (Path(final_name).stem, "Imported legacy coding memory")+ name, description = metadata+ appended.append(f"- [{name}]({final_name}) — {description}")+ target_entries[os.path.normcase(final_name)] = metadata++ if not appended:+ return 0+ merged_lines = target_lines + appended+ truncated = max(0, len(merged_lines) - _MAX_INDEX_LINES)+ _atomic_write_text(+ target_index,+ "\n".join(merged_lines[:_MAX_INDEX_LINES]),+ )+ return truncated+++def _load_report(path: Path) -> dict[str, Any]:+ report = _read_json_object(path)+ if report.get("version") != _MIGRATION_REPORT_VERSION:+ return {"version": _MIGRATION_REPORT_VERSION, "sources": {}}+ if not isinstance(report.get("sources"), dict):+ report["sources"] = {}+ return report+++def _report_entry_is_complete(entry: dict[str, Any]) -> bool:+ complete = entry.get("complete")+ if isinstance(complete, bool):+ return complete+ return entry.get("index_truncated", 0) == 0+++def prepare_project_coding_memory_dir(+ *,+ agent_workspace_dir: str | PathLike[str],+ project_dir: str | PathLike[str] | None,+) -> CodingMemoryMigrationResult:+ """Prepare the new Coding Memory directory and import legacy Markdown.++ Migration is best-effort and fail-open. Legacy sources are never modified,+ and derived databases and caches are intentionally not copied.+ """+ target = Path(+ resolve_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace_dir,+ project_dir=project_dir,+ )+ )+ warnings: list[str] = []+ source_paths: list[str] = []+ totals = {+ "sources_found": 0,+ "sources_migrated": 0,+ "copied": 0,+ "duplicates": 0,+ "renamed": 0,+ "index_truncated": 0,+ }++ try:+ candidates = _legacy_source_candidates(+ agent_workspace_dir=Path(agent_workspace_dir).absolute(),+ project_dir=project_dir,+ )+ target_key = _canonical_path(target)+ regular_sources = [+ source+ for source in candidates+ if _canonical_path(source) != target_key+ and source.is_dir()+ and not source.is_symlink()+ ]++ if not any(+ _canonical_path(source) != target_key and source.is_dir()+ for source in candidates+ ):+ target.mkdir(parents=True, exist_ok=True)+ return CodingMemoryMigrationResult(target_dir=str(target))++ if regular_sources and target.is_dir():+ report = _load_report(target / _MIGRATION_REPORT_FILENAME)+ report_sources = report["sources"]+ fast_path_matches = True+ for source in regular_sources:+ source_key = _canonical_path(source)+ previous = report_sources.get(source_key)+ if (+ not isinstance(previous, dict)+ or not _report_entry_is_complete(previous)+ or previous.get("state") != _source_state_token(source)+ ):+ fast_path_matches = False+ break+ if fast_path_matches:+ return CodingMemoryMigrationResult(+ target_dir=str(target),+ source_paths=tuple(_canonical_path(item) for item in regular_sources),+ sources_found=len(regular_sources),+ )++ target.parent.mkdir(parents=True, exist_ok=True)+ project_name = resolve_coding_memory_project_name(project_dir)+ lock_path = target.parent / f".{project_name}.coding-memory-migration.lock"+ with portalocker.Lock(+ str(lock_path),+ mode="a",+ timeout=_LOCK_TIMEOUT_SECONDS,+ ):+ target.mkdir(parents=True, exist_ok=True)+ report_path = target / _MIGRATION_REPORT_FILENAME+ report = _load_report(report_path)+ report_sources = report["sources"]++ existing_hashes: dict[str, str] = {}+ for path in target.iterdir():+ if (+ path.is_file()+ and not path.is_symlink()+ and path.suffix.casefold() == ".md"+ and path.name.casefold() != _INDEX_FILENAME.casefold()+ ):+ existing_hashes[_hash_file(path)] = path.name++ report_changed = False+ for source in candidates:+ if _canonical_path(source) == target_key or not source.is_dir():+ continue+ if source.is_symlink():+ warnings.append(f"{source}: skipped symbolic-link source")+ continue+ totals["sources_found"] += 1+ source_key = _canonical_path(source)+ source_paths.append(source_key)+ try:+ source_files, source_warnings = _scan_markdown_files(source)+ warnings.extend(f"{source}: {item}" for item in source_warnings)+ fingerprint = _source_fingerprint(source, source_files)+ state = _source_state_token(source)+ previous = report_sources.get(source_key)+ if (+ isinstance(previous, dict)+ and previous.get("fingerprint") == fingerprint+ and _report_entry_is_complete(previous)+ ):+ if previous.get("state") != state:+ previous["state"] = state+ report_changed = True+ continue++ final_names: dict[str, str] = {}+ copied = duplicates = renamed = 0+ for source_file in source_files:+ duplicate_name = existing_hashes.get(source_file.content_hash)+ if duplicate_name is not None:+ final_names[source_file.path.name] = duplicate_name+ duplicates += 1+ continue++ destination_name = source_file.path.name+ destination = target / destination_name+ if destination.exists():+ destination_name = _conflict_filename(target, source_file)+ destination = target / destination_name+ renamed += 1++ if (+ destination.exists()+ and _hash_file(destination) == source_file.content_hash+ ):+ duplicates += 1+ else:+ _atomic_write_bytes(+ destination,+ source_file.path.read_bytes(),+ )+ copied += 1+ existing_hashes[source_file.content_hash] = destination_name+ final_names[source_file.path.name] = destination_name++ truncated = _append_index_entries(+ target=target,+ source=source,+ final_names=final_names,+ )+ report_sources[source_key] = {+ "source": source_key,+ "fingerprint": fingerprint,+ "state": state,+ "complete": truncated == 0,+ "completed_at": datetime.now(timezone.utc).isoformat(),+ "copied": copied,+ "duplicates": duplicates,+ "renamed": renamed,+ "index_truncated": truncated,+ "warning_count": len(source_warnings),+ "warnings": source_warnings,+ }+ totals["sources_migrated"] += 1+ totals["copied"] += copied+ totals["duplicates"] += duplicates+ totals["renamed"] += renamed+ totals["index_truncated"] += truncated+ report_changed = True+ except (OSError, UnicodeError, ValueError) as exc:+ warnings.append(f"failed to migrate {source}: {exc}")++ if report_changed:+ _atomic_write_text(+ report_path,+ json.dumps(+ report,+ ensure_ascii=False,+ indent=2,+ sort_keys=True,+ )+ + "\n",+ )+ except (OSError, portalocker.exceptions.LockException) as exc:+ warnings.append(f"failed to prepare {target}: {exc}")++ failed = any(item.startswith("failed to ") for item in warnings)+ result = CodingMemoryMigrationResult(+ target_dir=str(target),+ source_paths=tuple(source_paths),+ warnings=tuple(warnings),+ failed=failed,+ **totals,+ )+ log_extra = {+ "coding_memory_migration": {+ "target": result.target_dir,+ "sources": result.source_paths,+ "sources_found": result.sources_found,+ "sources_migrated": result.sources_migrated,+ "copied": result.copied,+ "duplicates": result.duplicates,+ "renamed": result.renamed,+ "index_truncated": result.index_truncated,+ "failed": result.failed,+ }+ }+ if result.failed:+ logger.warning("Coding Memory legacy migration incomplete", extra=log_extra)+ elif result.sources_migrated:+ logger.info("Coding Memory legacy migration completed", extra=log_extra)+ return result+++__all__ = [+ "CodingMemoryMigrationResult",+ "DEFAULT_CODING_MEMORY_PROJECT",+ "prepare_project_coding_memory_dir",+ "resolve_coding_memory_project_name",+ "resolve_project_coding_memory_dir",+ "resolve_project_coding_memory_workspace_path",+]diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex cfe33aa5ed..2f26981441 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -79,7 +79,7 @@ from jiuwenswarm.agents.harness.common.tools.harness_named_web_tools import (from jiuwenswarm.common.config import get_configfrom jiuwenswarm.common.tool_ownership import mark_stateless, register_toolfrom jiuwenswarm.common.coding_memory_paths import (- resolve_project_coding_memory_dir,+ prepare_project_coding_memory_dir,resolve_project_coding_memory_workspace_path,)from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import CodeAgentRail@@ -241,18 +241,6 @@ _TOOL_BUILD_NAMES: dict[str, str] = {}-def _resolve_coding_memory_dir(- *,- project_dir: str | None,- agent_workspace_dir: str,-) -> str:- """Resolve the app-owned CodingMemory directory scoped by project."""- return resolve_project_coding_memory_dir(- agent_workspace_dir=agent_workspace_dir,- project_dir=project_dir,- )--def _build_coding_memory_directory_node(coding_memory_path: str,*,@@ -322,10 +310,29 @@ def create_coding_memory_rail("registering tools with memory fallback provider")- coding_memory_dir = _resolve_coding_memory_dir(+ migration = prepare_project_coding_memory_dir(project_dir=project_dir,agent_workspace_dir=agent_workspace_dir,)+ coding_memory_dir = migration.target_dir+ if migration.failed or migration.index_truncated:+ logger.warning(+ "[JiuwenSwarmCodeAdapter] Coding Memory legacy migration needs attention; "+ "continuing with the new directory",+ extra={+ "user_visible": "progress",+ "coding_memory_migration": {+ "target": migration.target_dir,+ "sources": migration.source_paths,+ "sources_found": migration.sources_found,+ "sources_migrated": migration.sources_migrated,+ "copied": migration.copied,+ "duplicates": migration.duplicates,+ "renamed": migration.renamed,+ "index_truncated": migration.index_truncated,+ },+ },+ )os.makedirs(coding_memory_dir, exist_ok=True)return CodingMemoryRail(diff --git a/tests/unit_tests/agentserver/test_code_adapter_acp_chat_tool.py b/tests/unit_tests/agentserver/test_code_adapter_acp_chat_tool.pyindex 313fcef5eb..d5a4f1ad14 100644--- a/tests/unit_tests/agentserver/test_code_adapter_acp_chat_tool.py+++ b/tests/unit_tests/agentserver/test_code_adapter_acp_chat_tool.py@@ -68,6 +68,12 @@ def test_code_adapter_builds_coding_memory_rail_without_embedding_config(monkeypproject_dir = tmp_path / "project"agent_workspace_dir = tmp_path / "agent_workspace"+ legacy_dir = project_dir / "coding_memory"+ legacy_dir.mkdir(parents=True)+ legacy_content = (+ "---\nname: Legacy\ndescription: Legacy memory\ntype: project\n---\n\nbody\n"+ )+ (legacy_dir / "legacy.md").write_text(legacy_content, encoding="utf-8")rail = interface_code.create_coding_memory_rail(project_dir=str(project_dir),@@ -82,3 +88,5 @@ def test_code_adapter_builds_coding_memory_rail_without_embedding_config(monkeypassert created["embedding_config"].model_name == "text-embedding-v3"assert created["embedding_config"].base_url == ""assert created["embedding_config"].api_key is None+ migrated = agent_workspace_dir / "coding_memory" / "project" / "legacy.md"+ assert migrated.read_text(encoding="utf-8") == legacy_contentdiff --git a/tests/unit_tests/common/test_coding_memory_paths.py b/tests/unit_tests/common/test_coding_memory_paths.pynew file mode 100644index 0000000000..15a55e577b--- /dev/null+++ b/tests/unit_tests/common/test_coding_memory_paths.py@@ -0,0 +1,533 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from concurrent.futures import ProcessPoolExecutor+import hashlib+import json+from pathlib import Path+from unittest.mock import AsyncMock++import pytest++from jiuwenswarm.common import coding_memory_paths+from jiuwenswarm.common.coding_memory_paths import (+ CodingMemoryMigrationResult,+ prepare_project_coding_memory_dir,+)+++def _memory(name: str, description: str, body: str) -> str:+ return (+ "---\n"+ f"name: {name}\n"+ f"description: {description}\n"+ "type: project\n"+ "---\n\n"+ f"{body}\n"+ )+++def _agent_workspace(root: Path) -> Path:+ return root / "workspace_default" / "agent" / "workspace"+++def _prepare_in_subprocess(+ paths: tuple[Path, Path],+) -> CodingMemoryMigrationResult:+ agent_workspace, project = paths+ return prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )+++def test_project_migration_copies_only_authoritative_markdown_and_is_incremental(+ tmp_path: Path,+) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "projects" / "demo"+ legacy = project / "coding_memory"+ legacy.mkdir(parents=True)+ first_content = _memory("First", "First description", "first body")+ (legacy / "first.md").write_text(first_content, encoding="utf-8")+ (legacy / "MEMORY.md").write_text(+ "- [First](first.md) — First description\n",+ encoding="utf-8",+ )+ (legacy / "memory.db").write_bytes(b"derived")+ (legacy / "nested").mkdir()+ (legacy / "nested" / "ignored.md").write_text("ignored", encoding="utf-8")++ first = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ target = Path(first.target_dir)+ assert first.failed is False+ assert first.sources_migrated == 1+ assert first.copied == 1+ assert (target / "first.md").read_text(encoding="utf-8") == first_content+ assert not (target / "memory.db").exists()+ assert not (target / "nested").exists()+ assert (legacy / "first.md").read_text(encoding="utf-8") == first_content+ report = json.loads(+ (target / ".coding-memory-migration-v1.json").read_text(encoding="utf-8")+ )+ assert report["version"] == 1++ unchanged = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )+ assert unchanged.sources_migrated == 0+ assert unchanged.copied == 0++ second_content = _memory("Second", "Second description", "second body")+ (legacy / "second.md").write_text(second_content, encoding="utf-8")+ incremental = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )+ assert incremental.sources_migrated == 1+ assert incremental.copied == 1+ assert incremental.duplicates == 1+ assert (target / "second.md").read_text(encoding="utf-8") == second_content+++def test_migration_deduplicates_content_and_renames_filename_conflicts(+ tmp_path: Path,+) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ target = agent_workspace / "coding_memory" / "demo"+ legacy.mkdir(parents=True)+ target.mkdir(parents=True)++ legacy_conflict = _memory("Legacy", "Legacy description", "legacy body")+ duplicate = _memory("Duplicate", "Duplicate description", "same body")+ (legacy / "same.md").write_text(legacy_conflict, encoding="utf-8")+ (legacy / "duplicate-old.md").write_text(duplicate, encoding="utf-8")+ (legacy / "MEMORY.md").write_text(+ "- [Legacy](same.md) — Legacy description\n"+ "- [Duplicate](duplicate-old.md) — Duplicate description\n",+ encoding="utf-8",+ )+ (target / "same.md").write_text(+ _memory("New", "New description", "new body"),+ encoding="utf-8",+ )+ (target / "already-there.md").write_text(duplicate, encoding="utf-8")+ (target / "MEMORY.md").write_text(+ "- [New](same.md) — New description\n",+ encoding="utf-8",+ )++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ legacy_hash = hashlib.sha256((legacy / "same.md").read_bytes()).hexdigest()[:8]+ renamed = f"same__legacy_{legacy_hash}.md"+ assert result.renamed == 1+ assert result.duplicates == 1+ assert (target / renamed).read_text(encoding="utf-8") == legacy_conflict+ assert not (target / "duplicate-old.md").exists()+ index = (target / "MEMORY.md").read_text(encoding="utf-8")+ assert index.splitlines()[0] == "- [New](same.md) — New description"+ assert f"- [Legacy]({renamed}) — Legacy description" in index+ assert "(already-there.md)" in index+++def test_default_workspace_migrates_only_known_default_legacy_location(+ tmp_path: Path,+) -> None:+ data_root = tmp_path / ".jiuwenswarm"+ agent_workspace = _agent_workspace(data_root)+ legacy = (+ data_root+ / "service_default"+ / "agent_default"+ / "agent"+ / "jiuwenclaw_workspace"+ / "coding_memory"+ )+ legacy.mkdir(parents=True)+ (legacy / "default-note.md").write_text(+ _memory("Default", "Default description", "default body"),+ encoding="utf-8",+ )+ unrelated = (+ data_root+ / "service_other"+ / "agent_other"+ / "agent"+ / "jiuwenclaw_workspace"+ / "coding_memory"+ )+ unrelated.mkdir(parents=True)+ (unrelated / "must-not-copy.md").write_text("secret", encoding="utf-8")++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=None,+ )++ target = Path(result.target_dir)+ assert (target / "default-note.md").is_file()+ assert not (target / "must-not-copy.md").exists()+ assert result.sources_found == 1+++def test_default_workspace_migrates_flat_and_previous_root_locations(+ tmp_path: Path,+) -> None:+ current_root = tmp_path / ".jiuwenswarm"+ previous_root = tmp_path / ".jiuwenclaw"+ agent_workspace = _agent_workspace(current_root)+ sources = [+ current_root / "agent" / "jiuwenclaw_workspace" / "coding_memory",+ previous_root+ / "service_default"+ / "agent_default"+ / "agent"+ / "jiuwenclaw_workspace"+ / "coding_memory",+ ]+ for index, source in enumerate(sources):+ source.mkdir(parents=True)+ (source / f"legacy-{index}.md").write_text(+ _memory(f"Legacy {index}", f"Description {index}", f"body {index}"),+ encoding="utf-8",+ )++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=None,+ )++ target = Path(result.target_dir)+ assert result.sources_found == 2+ assert result.sources_migrated == 2+ assert (target / "legacy-0.md").is_file()+ assert (target / "legacy-1.md").is_file()+++def test_non_default_unbound_workspace_does_not_import_default_tenant(+ tmp_path: Path,+) -> None:+ data_root = tmp_path / ".jiuwenswarm"+ agent_workspace = data_root / "workspace_customer" / "agent" / "workspace"+ legacy = (+ data_root+ / "service_default"+ / "agent_default"+ / "agent"+ / "jiuwenclaw_workspace"+ / "coding_memory"+ )+ legacy.mkdir(parents=True)+ (legacy / "default-only.md").write_text("default tenant", encoding="utf-8")++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=None,+ )++ assert result.sources_found == 0+ assert not (Path(result.target_dir) / "default-only.md").exists()+++def test_default_legacy_named_agent_workspace_is_recognized(tmp_path: Path) -> None:+ data_root = tmp_path / ".jiuwenswarm"+ agent_workspace = (+ data_root / "workspace_default" / "agent" / "jiuwenclaw_workspace"+ )+ legacy = (+ data_root+ / "service_default"+ / "agent_default"+ / "agent"+ / "jiuwenclaw_workspace"+ / "coding_memory"+ )+ legacy.mkdir(parents=True)+ (legacy / "legacy.md").write_text("legacy", encoding="utf-8")++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=None,+ )++ assert (Path(result.target_dir) / "legacy.md").is_file()+++def test_index_limit_does_not_drop_imported_memory_files(tmp_path: Path) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ target = agent_workspace / "coding_memory" / "demo"+ legacy.mkdir(parents=True)+ target.mkdir(parents=True)+ (target / "MEMORY.md").write_text(+ "\n".join(f"# existing {index}" for index in range(199)),+ encoding="utf-8",+ )+ for index in range(2):+ (legacy / f"legacy-{index}.md").write_text(+ _memory(+ f"Legacy {index}",+ f"Legacy description {index}",+ f"body {index}",+ ),+ encoding="utf-8",+ )++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ assert result.index_truncated == 1+ assert len((target / "MEMORY.md").read_text(encoding="utf-8").splitlines()) == 200+ assert (target / "legacy-0.md").is_file()+ assert (target / "legacy-1.md").is_file()++ retained_lines = (target / "MEMORY.md").read_text(encoding="utf-8").splitlines()+ (target / "MEMORY.md").write_text(+ "\n".join(retained_lines[1:]),+ encoding="utf-8",+ )+ retried = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )+ retried_index = (target / "MEMORY.md").read_text(encoding="utf-8")+ assert retried.sources_migrated == 1+ assert retried.index_truncated == 0+ assert "(legacy-0.md)" in retried_index+ assert "(legacy-1.md)" in retried_index+++def test_completed_migration_fast_path_does_not_hash_file_contents(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ legacy.mkdir(parents=True)+ (legacy / "legacy.md").write_text("legacy body", encoding="utf-8")+ prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ def _unexpected_hash(_path: Path) -> str:+ raise AssertionError("completed migration should not hash file contents")++ class _UnexpectedLock:+ def __init__(self, *_args: object, **_kwargs: object) -> None:+ raise AssertionError("completed migration should not acquire the lock")++ monkeypatch.setattr(coding_memory_paths, "_hash_file", _unexpected_hash)+ monkeypatch.setattr(coding_memory_paths.portalocker, "Lock", _UnexpectedLock)+ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ assert result.sources_found == 1+ assert result.sources_migrated == 0+++def test_index_metadata_falls_back_to_legacy_index_then_filename(+ tmp_path: Path,+) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ legacy.mkdir(parents=True)+ (legacy / "indexed.md").write_text("no frontmatter", encoding="utf-8")+ (legacy / "orphan.md").write_text("also no frontmatter", encoding="utf-8")+ (legacy / "MEMORY.md").write_text(+ "- [Legacy title](indexed.md) — Legacy description\n",+ encoding="utf-8",+ )++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ index = (Path(result.target_dir) / "MEMORY.md").read_text(encoding="utf-8")+ assert index.splitlines() == [+ "- [Legacy title](indexed.md) — Legacy description",+ "- [orphan](orphan.md) — Imported legacy coding memory",+ ]+++def test_failed_copy_is_fail_open_and_retried(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ legacy.mkdir(parents=True)+ (legacy / "legacy.md").write_text(+ _memory("Legacy", "Legacy description", "body"),+ encoding="utf-8",+ )+ original_atomic_write = coding_memory_paths._atomic_write_bytes++ def _fail_memory_copy(path: Path, content: bytes) -> None:+ if path.name == "legacy.md":+ raise OSError("simulated read-only target")+ original_atomic_write(path, content)++ monkeypatch.setattr(coding_memory_paths, "_atomic_write_bytes", _fail_memory_copy)+ failed = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )+ assert failed.failed is True+ assert not (+ Path(failed.target_dir) / ".coding-memory-migration-v1.json"+ ).exists()+ assert (legacy / "legacy.md").is_file()++ monkeypatch.setattr(coding_memory_paths, "_atomic_write_bytes", original_atomic_write)+ retried = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )+ assert retried.failed is False+ assert (Path(retried.target_dir) / "legacy.md").is_file()+++def test_lock_failure_is_fail_open_and_leaves_source_untouched(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ legacy.mkdir(parents=True)+ source_file = legacy / "legacy.md"+ source_file.write_text("legacy body", encoding="utf-8")++ class _UnavailableLock:+ def __init__(self, *_args: object, **_kwargs: object) -> None:+ pass++ def __enter__(self) -> None:+ raise coding_memory_paths.portalocker.exceptions.LockException(+ "simulated timeout"+ )++ def __exit__(self, *_args: object) -> None:+ pass++ monkeypatch.setattr(coding_memory_paths.portalocker, "Lock", _UnavailableLock)+ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ assert result.failed is True+ assert source_file.read_text(encoding="utf-8") == "legacy body"+ assert not (+ Path(result.target_dir) / ".coding-memory-migration-v1.json"+ ).exists()+++def test_symbolic_link_markdown_is_not_migrated(tmp_path: Path) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ legacy.mkdir(parents=True)+ outside = tmp_path / "outside.md"+ outside.write_text("outside", encoding="utf-8")+ link = legacy / "linked.md"+ try:+ link.symlink_to(outside)+ except OSError:+ pytest.skip("symbolic links are unavailable in this environment")++ result = prepare_project_coding_memory_dir(+ agent_workspace_dir=agent_workspace,+ project_dir=project,+ )++ assert not (Path(result.target_dir) / "linked.md").exists()+ assert result.warnings+++def test_concurrent_prepare_is_idempotent(tmp_path: Path) -> None:+ agent_workspace = _agent_workspace(tmp_path / "data")+ project = tmp_path / "demo"+ legacy = project / "coding_memory"+ legacy.mkdir(parents=True)+ (legacy / "legacy.md").write_text(+ _memory("Legacy", "Legacy description", "body"),+ encoding="utf-8",+ )++ with ProcessPoolExecutor(max_workers=2) as executor:+ results = list(+ executor.map(+ _prepare_in_subprocess,+ [(agent_workspace, project)] * 2,+ )+ )++ target = Path(results[0].target_dir)+ assert sum(result.sources_migrated for result in results) == 1+ assert sorted(path.name for path in target.glob("*.md")) == ["MEMORY.md", "legacy.md"]+++async def test_auto_extraction_prepares_migration_before_scanning(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jiuwenswarm.agents.harness.common.auto_memory import extraction_runner+ from jiuwenswarm.agents.harness.common.auto_memory import extract_memories+ from jiuwenswarm.common import utils++ project = tmp_path / "demo"+ project.mkdir()+ agent_workspace = _agent_workspace(tmp_path / "data")+ legacy = project / "coding_memory"+ legacy.mkdir()+ (legacy / "legacy.md").write_text(+ _memory("Legacy", "Legacy description", "body"),+ encoding="utf-8",+ )+ monkeypatch.setattr(utils, "get_agent_workspace_dir", lambda: agent_workspace)+ monkeypatch.setattr(+ extract_memories,+ "_check_coding_memory_write_in_history",+ lambda _history: False,+ )+ run_extraction = AsyncMock()+ monkeypatch.setattr(+ extraction_runner,+ "_run_memory_extraction_with_cache_sharing",+ run_extraction,+ )++ await extraction_runner._execute_auto_memory_extraction(+ project_dir=str(project),+ session_id="session",+ messages=[{"role": "user", "content": "remember this"}],+ )++ target = agent_workspace / "coding_memory" / "demo"+ assert (target / "legacy.md").is_file()+ assert run_extraction.await_count == 1+ assert run_extraction.await_args.kwargs["memory_dir"] == target