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

fix(workspace): remove entire workspace directory before initialization

z2tngc26e5d6f9531
diff --git a/jiuwenclaw/init_workspace.py b/jiuwenclaw/init_workspace.py
index 73ff6b122e..5579dff3b9 100644
--- a/jiuwenclaw/init_workspace.py
+++ b/jiuwenclaw/init_workspace.py
@@ -5,23 +5,28 @@
- 同时复制 config.yaml、builtin_rules.yaml、.env.template、agent 模板等到 ~/.jiuwenclaw;
- 根据语言偏好复制多语言文件(AGENT.md、HEARTBEAT.md、IDENTITY.md、SOUL.md 等),
源文件使用 _ZH/_EN 后缀,目标文件不带后缀。
+
+使用方式:
+- jiuwenclaw-init -f: 强制清理,删除整个 ~/.jiuwenclaw 后重新初始化
+- jiuwenclaw-init: 保留原有数据,执行迁移合并
"""
from __future__ import annotations
+import argparse
import logging
import sys
from jiuwenclaw.utils import init_user_workspace
-def run_init() -> int:
+def run_init(force: bool = False) -> int:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
- target = init_user_workspace(overwrite=True)
+ target = init_user_workspace(overwrite=force)
if target == "cancelled":
return 1
print(f"[jiuwenclaw-init] initialized: {target}")
@@ -29,7 +34,18 @@ def run_init() -> int:
def main() -> int:
- return run_init()
+ parser = argparse.ArgumentParser(
+ description="Initialize jiuwenclaw workspace directory (~/.jiuwenclaw)"
+ )
+ parser.add_argument(
+ "-f",
+ "--force",
+ action="store_true",
+ help="Force clean initialization: delete entire ~/.jiuwenclaw before init",
+ )
+ args = parser.parse_args()
+ return run_init(force=args.force)
+
if __name__ == "__main__":
sys.exit(main())
diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.py
index d5d4e19f9d..74f9221a93 100644
--- a/jiuwenclaw/utils.py
+++ b/jiuwenclaw/utils.py
@@ -742,17 +742,49 @@ def init_user_workspace(overwrite: bool = True) -> Path | Literal["cancelled"]:
不再由 JiuwenClaw 复制到用户工作区。
交互式 init 会先询问语言;首次启动 app 时非交互 prepare_workspace 则沿用模板 config 中的语言。
+
+ Args:
+ overwrite: True 时强制清理整个工作空间目录后初始化;
+ False 时保留原有数据,执行迁移合并逻辑。
"""
workspace_dir = get_user_workspace_dir()
if workspace_dir.exists():
- # Warn user about data loss and ask for confirmation
- print("[jiuwenclaw-init] WARNING: This will delete all historical configuration and memory information.")
- print("[jiuwenclaw-init] This action cannot be undone.")
- confirmation = input("[jiuwenclaw-init] Do you want to confirm reinitialization? (yes/no): ").strip().lower()
-
- if confirmation not in ("yes", "y"):
- print("[jiuwenclaw-init] Initialization cancelled. Exiting.")
- return "cancelled"
+ if overwrite:
+ # Force mode: explain both modes and ask for confirmation
+ print(
+ "[jiuwenclaw-init] With -f/--force flag, "
+ "entire ~/.jiuwenclaw will be deleted for clean initialization."
+ )
+ print("[jiuwenclaw-init] WARNING: This will delete all historical configuration and memory information.")
+ print("[jiuwenclaw-init] This action cannot be undone.")
+ confirmation = input(
+ "[jiuwenclaw-init] Do you want to confirm reinitialization? (yes/no): "
+ ).strip().lower()
+
+ if confirmation not in ("yes", "y"):
+ print("[jiuwenclaw-init] Initialization cancelled. Exiting.")
+ return "cancelled"
+
+ # Delete entire workspace directory for clean initialization
+ try:
+ shutil.rmtree(workspace_dir)
+ logger.info(f"Removed workspace directory: {workspace_dir}")
+ except OSError as e:
+ logger.error(f"Failed to remove workspace directory: {e}")
+ print(f"[jiuwenclaw-init] ERROR: Failed to remove workspace: {e}")
+ return "cancelled"
+ else:
+ # Merge mode: inform about preservation
+ print(
+ "[jiuwenclaw-init] Without -f/--force flag, "
+ "existing files will be preserved and merged with template."
+ )
+ print("[jiuwenclaw-init] This action cannot be undone.")
+ confirmation = input("[jiuwenclaw-init] Do you want to continue? (yes/no): ").strip().lower()
+
+ if confirmation not in ("yes", "y"):
+ print("[jiuwenclaw-init] Initialization cancelled. Exiting.")
+ return "cancelled"
lang = prompt_preferred_language()
if lang is None:
diff --git a/tests/system_tests/test_init_workspace.py b/tests/system_tests/test_init_workspace.py
index f5b82a7b64..936187e60c 100644
--- a/tests/system_tests/test_init_workspace.py
+++ b/tests/system_tests/test_init_workspace.py
@@ -204,19 +204,19 @@ class TestInitWorkspaceMain:
"""Test init_workspace.py main entry point."""
@staticmethod
- def test_main_successful_init(clean_environment: None, monkeypatch: pytest.MonkeyPatch,
+ def test_main_successful_init(clean_environment: None, monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture):
"""Test main function with successful initialization."""
- from jiuwenclaw.init_workspace import main
+ from jiuwenclaw.init_workspace import run_init
# Simulate user selecting Chinese
monkeypatch.setattr("builtins.input", lambda _: "1")
- # Run main and get exit code
- exit_code = main()
- if exit_code == 1:
- pytest.skip("Init was cancelled - may occur in some test environments")
- assert exit_code == 0
+ # Run init directly (bypass argparse)
+ exit_code = run_init(force=False)
+ if exit_code == 1:
+ pytest.skip("Init was cancelled - may occur in some test environments")
+ assert exit_code == 0
# Check output
captured = capsys.readouterr()
@@ -226,15 +226,33 @@ class TestInitWorkspaceMain:
@staticmethod
def test_main_cancelled_init(clean_environment: None, monkeypatch: pytest.MonkeyPatch):
"""Test main function with cancelled initialization."""
- from jiuwenclaw.init_workspace import main
+ from jiuwenclaw.init_workspace import run_init
# Simulate user cancelling
monkeypatch.setattr("builtins.input", lambda _: "cancelled")
# Should exit with code 1
- exit_code = main()
+ exit_code = run_init(force=False)
assert exit_code == 1
+ @staticmethod
+ def test_main_force_init(clean_environment: None, monkeypatch: pytest.MonkeyPatch):
+ """Test main function with -f flag for force initialization."""
+ from jiuwenclaw.init_workspace import run_init
+
+ # Simulate user confirming force init and selecting Chinese
+ def mock_input(prompt):
+ if "confirm" in prompt.lower():
+ return "yes"
+ return "1"
+
+ monkeypatch.setattr("builtins.input", mock_input)
+
+ exit_code = run_init(force=True)
+ if exit_code == 1:
+ pytest.skip("Init was cancelled - may occur in some test environments")
+ assert exit_code == 0
+
class TestInitCLI:
"""Test jiuwenclaw-init command line interface."""