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

[mirror] openJiuwen-ai/jiuwenswarm#1624: fix(/rewind) conversation-only mode deleting file snapshots and a metadata.js...

gcw_6ZTnJdNN5ff689601326
diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.py
index 7662e2a5a5..99d53bdfdb 100644
--- a/jiuwenswarm/agents/harness/common/session_ops_service.py
+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py
@@ -205,6 +205,17 @@ def rewind_session(
# 在截断 history 之前,记录目标 turn 的时间戳(用于后续清理 file_ops)
cut_timestamp = history[cut_index].get("timestamp")
+ # 同样必须在下面 update_session_metadata 之前解析项目目录:metadata.json 是
+ # 非原子的原地覆写且走后台线程,之后再让 truncate_file_ops 自己去推断,会撞上
+ # 半截文件 → JSONDecodeError → 静默返回 None → 扫不到 file_ops → 清理无声失效。
+ project_dir: str | None = None
+ try:
+ from jiuwenswarm.server.utils.diff_service import get_diff_service
+
+ project_dir = get_diff_service().resolve_project_dir(session_id)
+ except Exception as exc:
+ logger.warning("rewind_session: failed to resolve project_dir: %s", exc)
+
result = truncate_history_records(session_id=session_id, cut_index=cut_index)
from jiuwenswarm.server.runtime.session.session_metadata import update_session_metadata
@@ -216,11 +227,16 @@ def rewind_session(
# 清理 session-specific file_ops 日志,使 turn diff 显示与截断后的 history 一致
# 必须在 truncate_history_records 之后调用,但传入截断前获取的时间戳
+ #
+ # soft=True: 本函数只回退对话、不动工作区文件。硬删除快照会让这些文件永久
+ # 失去回滚能力(后续 /rewind 选 code 找不到它们,却仍报告成功)。
if cut_timestamp is not None:
try:
from jiuwenswarm.server.utils.diff_service import get_diff_service
- get_diff_service().truncate_file_ops_by_timestamp(session_id, cut_timestamp)
+ get_diff_service().truncate_file_ops_by_timestamp(
+ session_id, cut_timestamp, project_dir=project_dir, soft=True,
+ )
except Exception as exc:
logger.warning("rewind_session: failed to truncate file_ops: %s", exc)
@@ -284,15 +300,27 @@ def compact_partial_session(
if direction == "from":
cut_timestamp = history[target_user_index].get("timestamp")
summarized_count = len(history) - target_user_index
+ # 在 update_session_metadata 之前解析(同 rewind_session,避免元数据写入竞态)
+ compact_project_dir: str | None = None
+ try:
+ from jiuwenswarm.server.utils.diff_service import get_diff_service
+
+ compact_project_dir = get_diff_service().resolve_project_dir(session_id)
+ except Exception as exc:
+ logger.warning("compact_partial_session: failed to resolve project_dir: %s", exc)
result = truncate_history_records(session_id=session_id, cut_index=target_user_index)
remaining = result["remaining_records"]
removed = result["removed_records"]
+ # soft=True: 摘要化同样只改对话、不动工作区文件(同 rewind_session)
if cut_timestamp is not None:
try:
from jiuwenswarm.server.utils.diff_service import get_diff_service
- get_diff_service().truncate_file_ops_by_timestamp(session_id, cut_timestamp)
+ get_diff_service().truncate_file_ops_by_timestamp(
+ session_id, cut_timestamp,
+ project_dir=compact_project_dir, soft=True,
+ )
except Exception as exc:
logger.warning("compact_partial_session: failed to truncate file_ops: %s", exc)
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.ts
index 53e96724b6..11f06dd0d5 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.ts
@@ -332,8 +332,17 @@ export function createRewindCommand(): SlashCommand {
const restoredFiles = restorePayload.restored_files ?? [];
const deletedFiles = restorePayload.deleted_files ?? [];
const restoreErrors = restorePayload.restore_errors ?? [];
-
- let msg = `Restored files to state before turn ${selectedTurnIndex}:`;
+ // 不要在实际什么都没还原(或有文件失败)时报告纯成功——用户会据此
+ // 误判工作区状态。标题按结果分级,失败文件逐个列出。
+ const anyRestored = restoredFiles.length > 0 || deletedFiles.length > 0;
+ let msg: string;
+ if (!anyRestored && restoreErrors.length === 0) {
+ msg = `No file changes to restore before turn ${selectedTurnIndex}.`;
+ } else if (restoreErrors.length > 0) {
+ msg = `Partially restored files to state before turn ${selectedTurnIndex}:`;
+ } else {
+ msg = `Restored files to state before turn ${selectedTurnIndex}:`;
+ }
if (restoredFiles.length > 0) {
msg += `\n Written back: ${restoredFiles.length} file(s)`;
}
@@ -341,13 +350,14 @@ export function createRewindCommand(): SlashCommand {
msg += `\n Deleted: ${deletedFiles.length} file(s)`;
}
if (restoreErrors.length > 0) {
- msg += `\n Failed: ${restoreErrors.length} file(s)`;
- }
- if (restoredFiles.length === 0 && deletedFiles.length === 0) {
- msg += "\n No file changes found to restore.";
- }
-
- ctx.addItem(addInfo(ctx.sessionId, msg, "i"));
+ msg += `\n Failed to restore ${restoreErrors.length} file(s):`;
+ for (const e of restoreErrors) {
+ msg += `\n - ${e.file}: ${e.error}`;
+ }
+ msg += "\n These files still hold the agent's changes.";
+ }
+
+ ctx.addItem(addInfo(ctx.sessionId, msg, restoreErrors.length > 0 ? "w" : "i"));
} else if (optionValue === "summarize") {
ctx.addItem(
addInfo(ctx.sessionId, "Messages after this point will be summarized.", "i", { view: "dim" }),
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index 9f3422c376..d590c00a38 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -40,6 +40,10 @@ WORKTREE_HISTORY_CONTAINERS: tuple[tuple[str, ...], ...] = (
# change_sets.json 写入锁:保证同一进程内多线程惰性回填时不互相覆盖。
_CHANGE_SET_LOCK = threading.Lock()
+# file_ops 条目上的软删除标记。被 conversation 回退"截断"掉的快照打上此标记后
+# 对 turn diff 显示层不可见,但仍保留 old_content,从而不丢失文件回滚能力。
+_REWOUND_KEY = "rewound_out"
+
class DiffHistoryExpiredError(RuntimeError):
"""历史 diff 索引仍存在但详情已无法重建。"""
@@ -569,6 +573,18 @@ class DiffService:
except Exception:
return []
+ @staticmethod
+ def resolve_project_dir(session_id: str) -> str | None:
+ """解析 session 的项目目录(``_get_project_dir_from_metadata`` 的公开入口).
+
+ 调用方若随后会写 ``metadata.json``(如 ``rewind_session`` 调
+ ``update_session_metadata``),**必须在写之前**调用本函数并把结果显式
+ 传给下游,不要让下游自己去推断:``metadata.json`` 是非原子的原地覆写
+ 且由后台线程执行,下游读到半截文件会 ``JSONDecodeError`` → 静默返回
+ ``None`` → 扫不到项目目录下的 file_ops → 整个清理变成无声的空操作。
+ """
+ return DiffService._get_project_dir_from_metadata(session_id)
+
@staticmethod
def _get_project_dir_from_metadata(session_id: str) -> str | None:
"""从 session metadata.json 中读取项目目录.
@@ -761,6 +777,7 @@ class DiffService:
project_dir: str | None = None,
*,
extra_history_roots: list[str] | None = None,
+ include_rewound: bool = False
) -> dict[str, Any]:
"""读取 .agent_history(同时读取全局与 session-specific 文件并合并).
@@ -768,6 +785,11 @@ class DiffService:
session_id: 若提供,额外扫描匹配该 session 的 file_ops 文件。
project_dir: 项目目录路径,若提供则也从项目目录读取 .agent_history。
extra_history_roots: 额外写入根目录,例如 team/member workspace。
+ include_rewound: 是否包含被标记为 ``rewound_out`` 的条目(软删除快照)。
+ 默认 ``False``——**显示层**(turn diff)不应看到它们,否则会展示
+ 已被回退掉的 turn 的改动。**还原层**(``get_files_to_restore``)
+ 必须传 ``True``:这些快照仍持有文件的原始内容,是回滚能力的唯一
+ 来源。详见 ``truncate_file_ops_by_timestamp`` 的 ``soft`` 参数。
"""
result: dict[str, Any] = {}
history_file_priorities: dict[str, int] = {}
@@ -891,6 +913,9 @@ class DiffService:
result_entry_priorities[normalized_path] = []
# 合并条目,避免时间戳相近的重复记录
for entry in entries:
+ # 软删除的快照默认对显示层不可见(见 include_rewound)
+ if not include_rewound and entry.get(_REWOUND_KEY):
+ continue
# 检查是否已存在相同时间戳(±1秒)的相同操作
ts = entry.get("timestamp", "")
action = entry.get("action", "")
@@ -1829,9 +1854,11 @@ class DiffService:
return {}
# 2. 读取 file_ops 日志
+ # include_rewound=True: 之前的 conversation 回退只截断了对话、没有动
+ # 工作区,那些被软删除的快照仍是对应文件唯一的原始内容来源,必须纳入,
+ # 否则文件会永久失去回滚能力。
agent_history = self._read_agent_history(
- session_id,
- project_dir,
+ session_id, project_dir, include_rewound=True,
extra_history_roots=extra_history_roots,
)
@@ -1864,11 +1891,24 @@ class DiffService:
session_id: str,
cutoff_ts: float,
project_dir: str | None = None,
+ soft: bool = False,
*,
extra_history_roots: list[str] | None = None,
) -> None:
"""截断 file_ops 日志,移除 timestamp >= cutoff_ts 的条目.
+ ``soft`` 决定"截断"的含义,取值应与调用方**是否同时还原了工作区文件**一致:
+
+ - ``soft=False``(硬删除,默认): 条目被物理移除。仅当调用方已经把这些
+ 文件写回原始内容时才正确(如 ``discard_turn_changes``)——文件已回到
+ 旧状态,快照失去意义。
+ - ``soft=True``(软删除): 条目保留 ``old_content``,只打上 ``rewound_out``
+ 标记。用于**只回退对话、不动文件**的场景(``rewind_session`` 的
+ conversation 模式、``compact_partial_session``)。此时硬删除会让文件
+ 陷入"已被修改、但系统不再持有其原始内容"的状态,后续任何 /rewind 都
+ 无法还原它,且不会报错(issue #2241)。标记后显示层照旧看不到这些条目,
+ 还原层仍可用——显示一致性与回滚能力各取所需。
+
在 rewind / discard_turn_changes 操作后调用,确保 file_ops 日志与
截断后的 history.json / 实际工作区一致。
@@ -1889,6 +1929,7 @@ class DiffService:
覆盖 ``channel_metadata.cwd`` 缺失的场景(如 Web/code 模式新会话)。
为 ``None`` 时底层从 session metadata 推断(读取顺序见
``_get_project_dir_from_metadata``)。
+ soft: 见上文。调用方未还原工作区文件时必须传 ``True``。
"""
# 收集所有 session-specific file_ops 文件
@@ -1946,6 +1987,14 @@ class DiffService:
continue
if entry_ts < cutoff_ts:
filtered.append(e)
+ elif soft:
+ # 保留快照(old_content),仅对显示层隐藏
+ if not e.get(_REWOUND_KEY):
+ e[_REWOUND_KEY] = True
+ truncated = True
+ filtered.append(e)
+ else:
+ truncated = True
if len(filtered) != len(entries):
truncated = True
if filtered:
@@ -1957,8 +2006,8 @@ class DiffService:
encoding="utf-8",
)
logger.info(
- "truncate_file_ops: cleaned %s (cutoff_ts=%s)",
- file_ops_path.name, cutoff_ts,
+ "truncate_file_ops: cleaned %s (cutoff_ts=%s, soft=%s)",
+ file_ops_path.name, cutoff_ts, soft,
)
except Exception as exc:
logger.warning(
diff --git a/tests/unit_tests/server/test_diff_service_rewound_snapshots.py b/tests/unit_tests/server/test_diff_service_rewound_snapshots.py
new file mode 100644
index 0000000000..1df7965f8e
--- /dev/null
+++ b/tests/unit_tests/server/test_diff_service_rewound_snapshots.py
@@ -0,0 +1,190 @@
+# Copyright (c) Huawei Technologies, Co., Ltd. 2025. All rights reserved.
+"""conversation 回退不得销毁文件回滚能力.
+
+复现场景(两个 turn 各改一个文件):
+
+ turn 1 编辑 demo.txt ORIGINAL -> MODIFIED
+ turn 2 编辑 notes.txt ORIGINAL -> CHANGED
+ /rewind 2 选 conversation (只截断对话,**不动**工作区文件)
+ /rewind 1 选 code (应把两个文件都还原到 turn 1 之前)
+
+修复前 conversation 回退会**物理删除** notes.txt 的 file_ops 快照,
+notes.txt 从此处于"已被修改、但系统不再持有其原始内容"的状态:
+后续 /rewind 找不到它,却仍报告成功。
+
+修复后改为软删除(打 ``rewound_out`` 标记):
+显示层(turn diff)照旧看不到这些条目,还原层仍能用。
+"""
+
+import json
+from datetime import datetime, timezone
+
+import pytest
+
+from jiuwenswarm.server.utils.diff_service import DiffService
+
+TURN1_TS = 1_700_000_000.0
+TURN2_TS = 1_700_000_100.0
+# 每个 turn 内的编辑发生在该 turn 的 user 消息之后
+EDIT1_TS = TURN1_TS + 10
+EDIT2_TS = TURN2_TS + 10
+
+
+def _iso(ts: float) -> str:
+ return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
+
+
+def _history() -> list[dict]:
+ return [
+ {"role": "user", "content": "把 demo.txt 改成 MODIFIED", "timestamp": TURN1_TS},
+ {"role": "assistant", "content": "done", "event_type": "chat.final",
+ "timestamp": TURN1_TS + 20},
+ {"role": "user", "content": "把 notes.txt 改成 CHANGED", "timestamp": TURN2_TS},
+ {"role": "assistant", "content": "done", "event_type": "chat.final",
+ "timestamp": TURN2_TS + 20},
+ ]
+
+
+def project(tmp_path, monkeypatch):
+ """搭一个带 history + file_ops 的项目目录,返回 (service, dir, ops_path)."""
+ demo = tmp_path / "demo.txt"
+ notes = tmp_path / "notes.txt"
+ demo.write_text("MODIFIED-LINE-1\n", encoding="utf-8")
+ notes.write_text("CHANGED-A\n", encoding="utf-8")
+
+ hist_dir = tmp_path / ".agent_history"
+ hist_dir.mkdir()
+ ops_path = hist_dir / "file_ops_jiuwenswarm_tui_sess2241.json"
+ ops_path.write_text(json.dumps({
+ str(demo): [{
+ "action": "edit", "timestamp": _iso(EDIT1_TS),
+ "old_content": "ORIGINAL-LINE-1\n", "new_content": "MODIFIED-LINE-1\n",
+ }],
+ str(notes): [{
+ "action": "edit", "timestamp": _iso(EDIT2_TS),
+ "old_content": "ORIGINAL-A\n", "new_content": "CHANGED-A\n",
+ }],
+ }), encoding="utf-8")
+
+ service = DiffService()
+ monkeypatch.setattr(DiffService, "_read_history", staticmethod(lambda _sid: _history()))
+ # 隔离掉真实 workspace 下的全局/其它 session file_ops,避免污染断言
+ monkeypatch.setattr(
+ "jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",
+ lambda: tmp_path / "_agent_ws",
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.utils.diff_service.get_user_workspace_dir",
+ lambda: tmp_path / "_user_ws",
+ )
+ return service, tmp_path, ops_path, demo, notes
+
+
+def test_soft_truncate_keeps_files_restorable(project):
+ """核心回归:conversation 回退后,被回退 turn 的文件仍能被 code 回退还原。"""
+ service, proj_dir, _ops, demo, notes = project
+
+ # 步骤 5:/rewind 2 选 conversation —— 只截断对话,不动文件
+ service.truncate_file_ops_by_timestamp(
+ "sess2241", TURN2_TS, project_dir=str(proj_dir), soft=True,
+ )
+
+ # 步骤 6:/rewind 1 选 code —— 两个文件都应可还原
+ to_restore = service.get_files_to_restore("sess2241", 1, project_dir=str(proj_dir))
+
+ assert str(demo) in to_restore, "demo.txt 应可还原"
+ assert str(notes) in to_restore, "notes.txt 的快照被软删除后仍应可还原(#2241)"
+ assert to_restore[str(demo)]["restore_content"] == "ORIGINAL-LINE-1\n"
+ assert to_restore[str(notes)]["restore_content"] == "ORIGINAL-A\n"
+
+
+def test_soft_truncate_hides_rewound_entries_from_turn_diff(project):
+ """软删除必须保住原有的显示层语义:被回退的 turn 不再出现在 turn diff 中。"""
+ service, proj_dir, _ops, demo, notes = project
+
+ before = service.get_turn_diffs("sess2241", project_dir=str(proj_dir))
+ assert {t["turnIndex"] for t in before} == {1, 2}
+
+ service.truncate_file_ops_by_timestamp(
+ "sess2241", TURN2_TS, project_dir=str(proj_dir), soft=True,
+ )
+
+ after = service.get_turn_diffs("sess2241", project_dir=str(proj_dir))
+ assert {t["turnIndex"] for t in after} == {1}, "turn 2 的改动不应再显示"
+ assert str(notes) not in after[0]["files"]
+ assert str(demo) in after[0]["files"]
+
+
+def test_soft_truncate_marks_but_does_not_drop_entries(project):
+ """软删除落盘形态:条目保留、old_content 保留,只是多了标记。"""
+ service, proj_dir, ops_path, _demo, notes = project
+
+ service.truncate_file_ops_by_timestamp(
+ "sess2241", TURN2_TS, project_dir=str(proj_dir), soft=True,
+ )
+
+ data = json.loads(ops_path.read_text(encoding="utf-8"))
+ assert str(notes) in data, "软删除不得整个丢掉文件的 key"
+ entry = data[str(notes)][0]
+ assert entry["rewound_out"] is True
+ assert entry["old_content"] == "ORIGINAL-A\n"
+
+
+def test_hard_truncate_still_removes_entries(project):
+ """硬删除路径(discard_turn_changes:文件已被写回)行为不变。"""
+ service, proj_dir, ops_path, demo, notes = project
+
+ service.truncate_file_ops_by_timestamp(
+ "sess2241", TURN2_TS, project_dir=str(proj_dir),
+ )
+
+ data = json.loads(ops_path.read_text(encoding="utf-8"))
+ assert str(notes) not in data
+ assert str(demo) in data
+
+
+def test_repeated_soft_truncate_is_idempotent(project):
+ """重复 conversation 回退不应叠加副作用,也不应丢失快照。"""
+ service, proj_dir, ops_path, _demo, notes = project
+
+ for _ in range(3):
+ service.truncate_file_ops_by_timestamp(
+ "sess2241", TURN2_TS, project_dir=str(proj_dir), soft=True,
+ )
+
+ data = json.loads(ops_path.read_text(encoding="utf-8"))
+ assert len(data[str(notes)]) == 1
+ assert data[str(notes)][0]["old_content"] == "ORIGINAL-A\n"
+
+
+def test_later_edit_becomes_new_baseline(project, monkeypatch):
+ """软删除的快照不会"复活"成错误的还原目标.
+
+ 若 conversation 回退后用户又在新 turn 里改了同一个文件,
+ 新一轮的 /rewind 应还原到**新**快照,而非更早的软删除快照。
+ """
+ service, proj_dir, ops_path, _demo, notes = project
+
+ service.truncate_file_ops_by_timestamp(
+ "sess2241", TURN2_TS, project_dir=str(proj_dir), soft=True,
+ )
+
+ # 新 turn 2:再次编辑 notes.txt(时间戳晚于软删除的那条)
+ new_turn2_ts = TURN2_TS + 1000
+ data = json.loads(ops_path.read_text(encoding="utf-8"))
+ data[str(notes)].append({
+ "action": "edit", "timestamp": _iso(new_turn2_ts + 10),
+ "old_content": "CHANGED-A\n", "new_content": "REWRITTEN-A\n",
+ })
+ ops_path.write_text(json.dumps(data), encoding="utf-8")
+
+ history = _history()[:2] + [
+ {"role": "user", "content": "再改 notes.txt", "timestamp": new_turn2_ts},
+ {"role": "assistant", "content": "done", "event_type": "chat.final",
+ "timestamp": new_turn2_ts + 20},
+ ]
+ monkeypatch.setattr(DiffService, "_read_history", staticmethod(lambda _sid: history))
+
+ to_restore = service.get_files_to_restore("sess2241", 2, project_dir=str(proj_dir))
+ assert to_restore[str(notes)]["restore_content"] == "CHANGED-A\n"
diff --git a/tests/unit_tests/test_rewind_project_dir_race.py b/tests/unit_tests/test_rewind_project_dir_race.py
new file mode 100644
index 0000000000..92fd5cfc9c
--- /dev/null
+++ b/tests/unit_tests/test_rewind_project_dir_race.py
@@ -0,0 +1,112 @@
+# Copyright (c) Huawei Technologies, Co., Ltd. 2026. All rights reserved.
+"""回归:rewind / compact 必须显式传 project_dir,且在写 metadata 之前解析.
+
+``metadata.json`` 是非原子的原地覆写(``_write_metadata_sync`` 用
+``fpath.write_text``),且由后台线程执行。若 ``truncate_file_ops_by_timestamp``
+自己去调 ``_get_project_dir_from_metadata``,会撞上刚被 ``update_session_metadata``
+截断到一半的文件 → ``JSONDecodeError`` → 静默返回 ``None`` → 扫不到项目目录下的
+file_ops → 整个清理变成无声空操作(文件从此失去回滚能力,且没有任何报错)。
+
+这是实测撞到的偶发失败:同样的 /rewind 2,一次标记成功、一次完全没动。
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+def _history():
+ return [
+ {"role": "user", "content": "turn one", "timestamp": 1000.0},
+ {"role": "assistant", "content": "ok", "timestamp": 1010.0},
+ {"role": "user", "content": "turn two", "timestamp": 1100.0},
+ {"role": "assistant", "content": "ok", "timestamp": 1110.0},
+ ]
+
+
+def wired(tmp_path):
+ """接管 history/metadata 读写,返回 (diff_service_mock, call_order)。"""
+ call_order: list[str] = []
+
+ ds = MagicMock()
+ ds.resolve_project_dir.side_effect = lambda _sid: (
+ call_order.append("resolve_project_dir") or str(tmp_path)
+ )
+ ds.truncate_file_ops_by_timestamp.side_effect = lambda *a, **k: call_order.append(
+ "truncate_file_ops"
+ )
+
+ def _update_meta(**_kw):
+ call_order.append("update_session_metadata")
+
+ hist_path = tmp_path / "history.jsonl"
+ hist_path.write_text("", encoding="utf-8")
+
+ with (
+ patch("jiuwenswarm.server.utils.diff_service.get_diff_service", return_value=ds),
+ patch(
+ "jiuwenswarm.agents.harness.common.session_ops_service.get_read_history_path",
+ return_value=hist_path,
+ ),
+ patch(
+ "jiuwenswarm.agents.harness.common.session_ops_service.load_history_records",
+ return_value=_history(),
+ ),
+ patch(
+ "jiuwenswarm.server.runtime.session.session_history.truncate_history_records",
+ return_value={"remaining_records": 2, "removed_records": 2},
+ ),
+ patch(
+ "jiuwenswarm.server.runtime.session.session_metadata.update_session_metadata",
+ side_effect=_update_meta,
+ ),
+ ):
+ yield ds, call_order
+
+
+def test_rewind_passes_explicit_project_dir(wired, tmp_path):
+ from jiuwenswarm.agents.harness.common.session_ops_service import rewind_session
+
+ ds, _order = wired
+ rewind_session(session_id="sess-race", turn_index=2)
+
+ ds.truncate_file_ops_by_timestamp.assert_called_once()
+ kwargs = ds.truncate_file_ops_by_timestamp.call_args.kwargs
+ assert kwargs.get("project_dir") == str(tmp_path), (
+ "必须显式传 project_dir,否则下游自行推断会撞上 metadata 写入竞态"
+ )
+ # conversation 回退不动工作区文件,必须软删除(#2241)
+ assert kwargs.get("soft") is True
+
+
+def test_project_dir_resolved_before_metadata_write(wired):
+ """顺序断言:解析必须发生在 update_session_metadata 之前。"""
+ from jiuwenswarm.agents.harness.common.session_ops_service import rewind_session
+
+ _ds, order = wired
+ rewind_session(session_id="sess-race", turn_index=2)
+
+ assert "resolve_project_dir" in order
+ assert "update_session_metadata" in order
+ assert order.index("resolve_project_dir") < order.index("update_session_metadata"), (
+ f"解析晚于元数据写入,竞态窗口仍在:{order}"
+ )
+
+
+def test_compact_passes_explicit_project_dir(wired, tmp_path):
+ from jiuwenswarm.agents.harness.common.session_ops_service import (
+ compact_partial_session,
+ )
+
+ ds, order = wired
+ with patch(
+ "jiuwenswarm.agents.harness.common.session_ops_service._write_records_to_path"
+ ):
+ compact_partial_session(session_id="sess-race", turn_index=2, direction="from")
+
+ ds.truncate_file_ops_by_timestamp.assert_called_once()
+ kwargs = ds.truncate_file_ops_by_timestamp.call_args.kwargs
+ assert kwargs.get("project_dir") == str(tmp_path)
+ assert kwargs.get("soft") is True
+ assert order.index("resolve_project_dir") < order.index("update_session_metadata")