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(flash): 消除 edit_file 编辑冗余 I/O(快照缓存 / hunks 批量 / JSONL history)问题

qwqssqwq3f533a600d69
diff --git a/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py b/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
index 3e22c6360a..c7ac87ea9a 100644
--- a/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
+++ b/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
@@ -30,12 +30,12 @@ class SlimSysOperationRail(SysOperationRail):
)
from openjiuwen.harness.tools.code import CodeTool
from openjiuwen.harness.tools.filesystem import (
- EditFileTool,
GrepTool,
WriteFileTool,
)
from ..tools.flash_bash_tool import FlashBashTool
+ from ..tools.flash_edit_tool import FlashEditFileTool
from ..tools.flash_glob_tool import FlashGlobTool
from ..tools.flash_read_tool import FlashReadFileTool
@@ -52,7 +52,7 @@ class SlimSysOperationRail(SysOperationRail):
enable_image_multimodal=enable_read_image_multimodal,
)
write_tool = WriteFileTool(self.sys_operation, lang, agent_id)
- edit_tool = EditFileTool(self.sys_operation, lang, agent_id)
+ edit_tool = FlashEditFileTool(self.sys_operation, lang, agent_id)
glob_tool = FlashGlobTool(self.sys_operation, lang, agent_id)
grep_tool = GrepTool(self.sys_operation, lang, agent_id)
bash_tool = FlashBashTool(
diff --git a/jiuwenswarm/agents/harness/flash/tools/__init__.py b/jiuwenswarm/agents/harness/flash/tools/__init__.py
index 8cf620dfae..abbaff2f37 100644
--- a/jiuwenswarm/agents/harness/flash/tools/__init__.py
+++ b/jiuwenswarm/agents/harness/flash/tools/__init__.py
@@ -6,6 +6,7 @@ cron_flash / web_flash 的工厂留在各自模块内懒加载(导入一个 fl
不会连带初始化另一个的后端依赖);本文件的显式导出供包根聚合使用。
"""
+from .flash_edit_tool import FlashEditFileTool
from .flash_glob_tool import FlashGlobTool
from .flash_memory_tool import FlashMemoryTool
from .flash_read_tool import FlashReadFileTool
@@ -13,6 +14,7 @@ from .flash_todo import UnifiedTodoTool
from .slim_skill_toolkit import SlimSkillToolkit
__all__ = [
+ "FlashEditFileTool",
"FlashGlobTool",
"FlashMemoryTool",
"FlashReadFileTool",
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_bash_history.py b/jiuwenswarm/agents/harness/flash/tools/flash_bash_history.py
new file mode 100644
index 0000000000..6fa171106c
--- /dev/null
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_bash_history.py
@@ -0,0 +1,247 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Flash Bash 删除探测的双账本适配层。
+
+stock ``BashTool`` 的删除兜底只读取 ``file_ops_*.json``;flash edit 的
+最新内容则在 ``file_ops_flash_*.jsonl``。这里将两种账本合并后按时间取
+“最新有效条目”,再把缺失的 delete 记录追加回 flash JSONL:
+
+- flash-only 历史:不再因为 stock 账本为空而漏记;
+- stock + flash 混合历史:不会拿 stock 里的旧 ``new_content`` 当删除前内容;
+- 显式 ``rm`` 目标:命令执行前读取当前文件内容,保证即使文件从未入账
+ 也能记录删除前全文。
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import pathlib
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional
+
+from openjiuwen.core.common.exception.codes import StatusCode
+from openjiuwen.core.sys_operation.cwd import get_cwd
+
+from .flash_file_history import (
+ _history_lock,
+ _rewrite_flash_history_unlocked,
+ append_flash_history_entry,
+ load_flash_history,
+)
+
+
+logger = logging.getLogger(__name__)
+
+# ``rewound_out`` 只回退对话可见性,工作区文件仍保留该次编辑的结果;只有
+# ``discarded_out`` 表示 discard 已经把工作区恢复到旧版本。删除探测关注
+# 磁盘当前内容,因此不能把 conversation rewind 的条目排除掉。
+_DISCARDED_OUT_KEY = "discarded_out"
+
+
+def _load_stock_history(history_path: Optional[str]) -> Dict[str, List[Dict[str, Any]]]:
+ if not history_path:
+ return {}
+ path = pathlib.Path(history_path)
+ if not path.is_file():
+ return {}
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError) as exc:
+ logger.warning(
+ "[flash bash history] failed to read stock history %s: %s", path, exc
+ )
+ return {}
+ if not isinstance(raw, dict):
+ return {}
+
+ result: Dict[str, List[Dict[str, Any]]] = {}
+ for file_path, entries in raw.items():
+ if not isinstance(file_path, str) or not isinstance(entries, list):
+ continue
+ valid_entries = [entry for entry in entries if isinstance(entry, dict)]
+ if valid_entries:
+ result[file_path] = valid_entries
+ return result
+
+
+def _path_key(file_path: str) -> str:
+ try:
+ return os.path.normcase(str(pathlib.Path(file_path).resolve()))
+ except OSError:
+ return os.path.normcase(os.path.abspath(file_path))
+
+
+def _entry_sort_ts(entry: Dict[str, Any]) -> float:
+ """时间戳排序键;无法解析的条目不参与“最新内容”竞争。"""
+ ts = entry.get("timestamp")
+ if not isinstance(ts, str) or not ts:
+ return float("-inf")
+ try:
+ parsed = datetime.fromisoformat(ts.replace("Z", "+00:00"))
+ except ValueError:
+ return float("-inf")
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.timestamp()
+
+
+def _latest_effective_entry(entries: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+ """返回能代表当前磁盘状态的最新条目。
+
+ ``rewound_out`` 只影响对话可见性,工作区仍保留该次写入,因此按普通条目
+ 参与重放。``discarded_out`` 表示 discard 已经把该时间戳之后的写入恢复到
+ 本轮开始前;如果被丢弃的是文件的全部历史(例如文件首次被 agent 修改后
+ 又被 discard),不能因为没有更早的有效条目而丢失删除前内容,应取首个
+ discarded 条目的 ``old_content``。
+ """
+ if not entries:
+ return None
+
+ latest = max(entries, key=_entry_sort_ts)
+ if not latest.get(_DISCARDED_OUT_KEY):
+ return latest
+
+ non_discarded = [
+ entry for entry in entries if not entry.get(_DISCARDED_OUT_KEY)
+ ]
+ baseline_ts = (
+ max(_entry_sort_ts(entry) for entry in non_discarded)
+ if non_discarded
+ else float("-inf")
+ )
+ discarded_suffix = [
+ entry
+ for entry in entries
+ if entry.get(_DISCARDED_OUT_KEY) and _entry_sort_ts(entry) > baseline_ts
+ ]
+ if not discarded_suffix:
+ return None
+
+ restored = min(discarded_suffix, key=_entry_sort_ts)
+ old_content = restored.get("old_content")
+ if old_content is None:
+ # 文件在被丢弃的轮次开始前不存在;discard 已经把它删除。
+ return {"action": "delete", "new_content": None}
+ return {"action": "edit", "new_content": old_content}
+
+
+def _merged_latest_by_path(
+ stock_data: Dict[str, List[Dict[str, Any]]],
+ flash_data: Dict[str, List[Dict[str, Any]]],
+) -> Dict[str, Dict[str, Any]]:
+ """按规范化路径合并两种账本;代表路径优先使用 flash 侧路径。"""
+ merged: Dict[str, Dict[str, Any]] = {}
+ for source in (flash_data, stock_data):
+ for file_path, entries in source.items():
+ key = _path_key(file_path)
+ item = merged.setdefault(key, {"path": file_path, "entries": []})
+ if source is flash_data:
+ item["path"] = file_path
+ item["entries"].extend(entries)
+ return merged
+
+
+def record_detected_deletions(
+ stock_history_path: Optional[str],
+ flash_history_path: Optional[str],
+) -> None:
+ """命令成功后扫描双账本,把消失文件的最新内容记为 delete。
+
+ 读改写全程持有 flash per-path 锁,避免与 flash edit 的追加或其他
+ rewrite 交错覆盖。stock 账本只读,不改变其内容;diff_service 后续会
+ 按时间戳把 flash 侧 delete 与 stock/flash 编辑合并。
+ """
+ if not flash_history_path:
+ return
+ flash_path = pathlib.Path(flash_history_path)
+ try:
+ with _history_lock(str(flash_path)):
+ flash_data = load_flash_history(flash_path)
+ stock_data = _load_stock_history(stock_history_path)
+ merged = _merged_latest_by_path(stock_data, flash_data)
+ now = datetime.now(timezone.utc).isoformat()
+ changed = False
+
+ for item in merged.values():
+ latest = _latest_effective_entry(item["entries"])
+ if latest is None or latest.get("action") == "delete":
+ continue
+ file_path = item["path"]
+ if os.path.exists(file_path):
+ continue
+ flash_data.setdefault(file_path, []).append(
+ {
+ "action": "delete",
+ "timestamp": now,
+ "old_content": latest.get("new_content"),
+ "new_content": None,
+ }
+ )
+ changed = True
+
+ if changed:
+ _rewrite_flash_history_unlocked(flash_path, flash_data)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[flash bash history] failed to record deletions (%s, %s): %s",
+ stock_history_path,
+ flash_history_path,
+ exc,
+ )
+
+
+async def record_rm_targets_before_deletion(
+ flash_history_path: Optional[str],
+ file_paths: List[str],
+ operation: Any,
+) -> None:
+ """显式 rm 目标执行前读取当前全文并追加 delete 记录。"""
+ if not flash_history_path or not file_paths:
+ return
+ cwd = get_cwd()
+ for raw_path in file_paths:
+ try:
+ expanded = pathlib.Path(raw_path).expanduser()
+ abs_path = str(
+ (pathlib.Path(cwd) / expanded).resolve()
+ if not expanded.is_absolute()
+ else expanded.resolve()
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[flash bash history] path resolve failed %s: %s", raw_path, exc
+ )
+ continue
+ if not os.path.isfile(abs_path):
+ continue
+ try:
+ res = await operation.fs().read_file(abs_path)
+ if res.code != StatusCode.SUCCESS.code:
+ continue
+ content = res.data.content if res.data else ""
+ if isinstance(content, bytes):
+ content = content.decode("utf-8", errors="replace")
+ entry = {
+ "action": "delete",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "old_content": content,
+ "new_content": None,
+ }
+ await asyncio.to_thread(
+ append_flash_history_entry, flash_history_path, abs_path, entry
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[flash bash history] failed to record rm target %s: %s",
+ abs_path,
+ exc,
+ )
+
+
+__all__ = [
+ "record_detected_deletions",
+ "record_rm_targets_before_deletion",
+]
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
index 240ebdef8a..3358cf6bc5 100644
--- a/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
@@ -12,22 +12,87 @@ command was not found. All other stock semantics are preserved unchanged.
from __future__ import annotations
+import asyncio
import os
from typing import Any, AsyncIterator, Dict
+from openjiuwen.core.sys_operation import OperationMode
+from openjiuwen.core.session import get_current_session
from openjiuwen.harness.rails.sys_operation_rail import SysOperationRail
from openjiuwen.harness.tools.base_tool import ToolOutput
from openjiuwen.harness.tools.shell.bash._tool import BashTool
+from openjiuwen.harness.tools.filesystem import _parse_rm_targets
from jiuwenswarm.agents.harness.common.tools.command_tools import (
_build_subprocess_env,
_windows_not_found_hint,
)
+from jiuwenswarm.agents.harness.flash.tools.flash_bash_history import (
+ record_detected_deletions,
+ record_rm_targets_before_deletion,
+)
+from jiuwenswarm.agents.harness.flash.tools.flash_file_history import (
+ build_flash_history_path,
+)
class FlashBashTool(BashTool):
"""Stock BashTool plus Windows PATH hardening and command-not-found hints."""
+ def _build_history_path(self, session: Any) -> str | None:
+ """Disable stock's single-ledger history hook.
+
+ Stock ``invoke``/``stream`` would read and rewrite only
+ ``file_ops_*.json``. Flash sessions instead use the dual-ledger adapter
+ in this class: stock JSON + flash JSONL are merged before a delete is
+ recorded, so the latest flash edit cannot be silently replaced by an
+ older stock snapshot.
+ """
+ return None
+
+ def _history_recording_enabled(self, parsed) -> bool:
+ """Mirror the stock preconditions that precede explicit-rm recording."""
+ if self._operation.mode == OperationMode.SANDBOX:
+ return False
+ if not parsed.command or parsed.run_in_background:
+ return False
+ if parsed.workdir and not os.path.isdir(parsed.workdir):
+ return False
+ if (
+ os.getenv("OPENJIUWEN_BASH_STRICT") == "1"
+ and self._guard(parsed) is not None
+ ):
+ return False
+ return True
+
+ async def _record_rm_targets(self, command: str) -> None:
+ session = get_current_session()
+ if session is None:
+ return
+ flash_history_path = build_flash_history_path(session)
+ if not flash_history_path:
+ return
+ targets = _parse_rm_targets(command)
+ if not targets:
+ return
+ await record_rm_targets_before_deletion(
+ flash_history_path, targets, self._operation
+ )
+
+ async def _record_detected_deletions(self) -> None:
+ session = get_current_session()
+ if session is None:
+ return
+ flash_history_path = build_flash_history_path(session)
+ if not flash_history_path:
+ return
+ stock_history_path = BashTool._build_history_path(self, session)
+ await asyncio.to_thread(
+ record_detected_deletions,
+ stock_history_path,
+ flash_history_path,
+ )
+
@staticmethod
def _hardened_inputs(inputs: Dict[str, Any]) -> Dict[str, Any]:
"""Return a copy of *inputs* with hardened env on Windows.
@@ -85,7 +150,13 @@ class FlashBashTool(BashTool):
async def invoke(self, inputs: Dict[str, Any], **kwargs: Any) -> ToolOutput:
hardened = self._hardened_inputs(inputs)
+ parsed = self._parse_inputs(hardened)
+ record_history = self._history_recording_enabled(parsed)
+ if record_history:
+ await self._record_rm_targets(parsed.command)
result = await super().invoke(hardened, **kwargs)
+ if record_history and result.success:
+ await self._record_detected_deletions()
return self._annotate_not_found(hardened, result)
async def stream(
@@ -93,6 +164,10 @@ class FlashBashTool(BashTool):
) -> AsyncIterator[ToolOutput]:
"""Stream variant that also hardens PATH and annotates the final chunk."""
hardened = self._hardened_inputs(inputs)
+ parsed = self._parse_inputs(hardened)
+ record_history = self._history_recording_enabled(parsed)
+ if record_history:
+ await self._record_rm_targets(parsed.command)
final_chunk = None
async for chunk in super().stream(hardened, **kwargs):
if self._is_final_rendered_content_chunk(chunk):
@@ -100,6 +175,8 @@ class FlashBashTool(BashTool):
continue
yield chunk
if final_chunk is not None:
+ if record_history and final_chunk.success:
+ await self._record_detected_deletions()
yield self._annotate_final_chunk(hardened, final_chunk)
@staticmethod
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_edit_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_edit_tool.py
new file mode 100644
index 0000000000..dac898ad79
--- /dev/null
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_edit_tool.py
@@ -0,0 +1,736 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""FlashEditFileTool — EditFileTool 的 flash 增强版。
+
+在不修改 agent-core 的前提下,对 stock EditFileTool 的三处 I/O 浪费做
+"语义不变、路径变短"的覆写(设计论证见仓库根
+``flash-editfile-io-analysis-and-optimization.md``):
+
+1. **缓存命中免读盘**:read_file 注册快照时(FlashReadFileTool 覆写)已
+ 把全文存进 stock ``_FILE_READ_REGISTRY``、原始字节元数据存进侧车
+ (sha256/EOL/编码,快照版本绑定 mtime+size)。本工具在校验通过且
+ 本地模式下直接用缓存内容匹配,消除每次编辑固定的全量读;写回仍传
+ ``expected_content_sha256``,fs 层 CAS(仅 LOCAL 后端实现)保证竞态
+ 防护与 stock 等价。
+2. **history 纯追加**:stock 每次编辑整读+整写全部历史(二次方恶化);
+ flash 写独立 JSONL(``file_ops_flash_*.jsonl``),条目 schema 与
+ stock 一致,diff_service 合并读取后轮次 diff / /rewind 回滚 / 重做 /
+ 删除探测全链路可见。
+3. **hunks 批量编辑**:一次调用提交同一文件的多处修改,统一对同一份
+ 内容快照匹配、拒绝重叠、全部命中才一次写回(all-or-nothing),
+ 省 N-1 次完整链路与工具往返。
+
+边界:沙箱(jiuwenbox)后端不执行 CAS 且本地 os.stat 退化,缓存路径仅
+LOCAL 模式启用;沙箱与 Office 文件走 stock 全量读路径,行为不变。
+依赖 agent-core 私有 API(``_FILE_READ_REGISTRY`` 等)——与
+FlashReadFileTool 同款升级漂移风险,agent-core 升级时必须重跑
+"flash read → flash edit 同文件"回归。
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import os
+from bisect import bisect_left
+from datetime import datetime, timezone
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple
+
+from openjiuwen.core.common.exception.codes import StatusCode
+from openjiuwen.core.common.logging import logger
+from openjiuwen.core.session import get_current_session
+from openjiuwen.core.sys_operation import OperationMode
+from openjiuwen.harness.tools.base_tool import ToolOutput
+from openjiuwen.harness.tools.filesystem import (
+ EditFileTool,
+ _FILE_READ_REGISTRY,
+ _FileReadState,
+ _OFFICE_WRITE_EXTENSIONS,
+ _is_office_doc_path,
+ _is_unc_path,
+ _office_write_unsupported_error,
+ _read_office_plain_text_async,
+ _resolve_tool_file_path,
+ _write_office_document_async,
+)
+
+from .flash_file_history import append_flash_history_entry, build_flash_history_path
+from .flash_file_meta import get_file_meta, pop_file_meta, record_written_meta
+
+
+@dataclass
+class _EolContext:
+ """一次扫描得到的 EOL 元数据,供 offset 映射和替换文本复用。"""
+
+ to_original: Any
+ orig_starts: List[int]
+ styles: List[str]
+ # None 仅表示混合 EOL;无换行时默认 LF。
+ uniform_eol: Optional[str]
+
+
+def _build_eol_context(content: str) -> _EolContext:
+ """构造 LF 归一化索引 → 原始索引映射,并记录每个换行的原始风格。
+
+ CRLF 在归一化文本中比原始文本少一个字符。这里按换行建立断点,
+ 避免为每个字符保存一份 offset 列表导致大文件额外内存膨胀。EOL 风格
+ 也在同一次扫描中确定,后续大量 replace_all 不再反复扫描全文。
+ """
+ norm_positions: List[int] = []
+ orig_starts: List[int] = []
+ styles: List[str] = []
+ crlf_prefix: List[int] = []
+ crlf_count = 0
+ lf_count = 0
+ delta = 0
+ idx = content.find("\n")
+ while idx != -1:
+ is_crlf = idx > 0 and content[idx - 1] == "\r"
+ norm_positions.append(idx - delta - (1 if is_crlf else 0))
+ orig_starts.append(idx - 1 if is_crlf else idx)
+ crlf_prefix.append(crlf_count)
+ if is_crlf:
+ crlf_count += 1
+ delta += 1
+ styles.append("\r\n")
+ else:
+ lf_count += 1
+ styles.append("\n")
+ idx = content.find("\n", idx + 1)
+
+ if not styles:
+ uniform_eol = "\n"
+ elif crlf_count and not lf_count:
+ uniform_eol = "\r\n"
+ elif lf_count and not crlf_count:
+ uniform_eol = "\n"
+ else:
+ uniform_eol = None
+
+ def to_original(normalized_index: int) -> int:
+ if not norm_positions:
+ return normalized_index
+ pos = bisect_left(norm_positions, normalized_index)
+ if pos < len(norm_positions) and norm_positions[pos] == normalized_index:
+ return orig_starts[pos]
+ return normalized_index + (
+ crlf_prefix[pos] if pos < len(crlf_prefix) else crlf_count
+ )
+
+ return _EolContext(
+ to_original=to_original,
+ orig_starts=orig_starts,
+ styles=styles,
+ uniform_eol=uniform_eol,
+ )
+
+
+def _replacement_with_original_eol(
+ context: _EolContext,
+ orig_start: int,
+ orig_end: int,
+ replacement: str,
+) -> str:
+ """按原文件/局部 EOL 写回替换文本;未编辑区域由外层原样拼接保留。"""
+ if "\n" not in replacement:
+ return replacement
+ if context.uniform_eol is not None:
+ return replacement.replace("\n", context.uniform_eol)
+
+ # 混合 EOL:替换区间内的换行按原风格还原;新增换行沿用邻近风格。
+ left = bisect_left(context.orig_starts, orig_start)
+ right = bisect_left(context.orig_starts, orig_end)
+ span_styles = context.styles[left:right]
+ if "\r\n" in span_styles:
+ local_eol = "\r\n"
+ elif right < len(context.styles):
+ local_eol = context.styles[right]
+ elif left > 0:
+ local_eol = context.styles[left - 1]
+ else:
+ local_eol = "\n"
+
+ remaining_styles = iter(span_styles)
+ pieces: List[str] = []
+ for index, segment in enumerate(replacement.split("\n")):
+ if index:
+ pieces.append(next(remaining_styles, local_eol))
+ pieces.append(segment)
+ return "".join(pieces)
+
+
+async def _office_registry_content(file_path: str, written_content: str) -> str:
+ """Office 写入后读取实际抽取文本,保持 registry 与 stock 口径一致。"""
+ try:
+ content = await _read_office_plain_text_async(file_path)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[FlashEditFileTool] Failed to re-read office content after write "
+ "(%s): %s; falling back to written text",
+ file_path,
+ exc,
+ )
+ return written_content.replace("\r\n", "\n")
+ return content.replace("\r\n", "\n")
+
+
+FLASH_EDIT_DESCRIPTION: Dict[str, str] = {
+ "cn": (
+ "文件精确编辑工具。用 old_string 在文件中定位要修改的片段并替换为 "
+ "new_string,非 replace_all 时 old_string 必须在文件中恰好出现一次"
+ "(多匹配时补充上下文使其唯一)。编辑前必须先 read_file 读过该文件。"
+ "同一文件有多处修改时,推荐用 hunks 参数一次性提交全部修改:"
+ "所有修改统一匹配、互相不得重叠,全部成功才一次写回,"
+ "任一失败则整个调用失败且文件保持不变。"
+ ),
+ "en": (
+ "Precise file edit tool. Replaces old_string with new_string in a "
+ "file; old_string must occur exactly once unless replace_all is set "
+ "(add surrounding context to disambiguate). The file must be read "
+ "with read_file before editing. For multiple changes in one file, "
+ "prefer the hunks parameter: all edits are matched together, "
+ "overlaps are rejected, and the file is written once only if every "
+ "hunk matches (all-or-nothing)."
+ ),
+}
+
+
+def get_flash_edit_input_params(language: str = "cn") -> Dict[str, Any]:
+ if language == "en":
+ return {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Absolute path of the file to edit",
+ },
+ "old_string": {
+ "type": "string",
+ "description": "Text to replace (single-edit mode)",
+ },
+ "new_string": {
+ "type": "string",
+ "description": "Replacement text (single-edit mode)",
+ },
+ "replace_all": {
+ "type": "boolean",
+ "description": "Replace every occurrence (default false)",
+ },
+ "hunks": {
+ "type": "array",
+ "description": (
+ "Batch mode: all edits for this file in one call. "
+ "Matched together against the same snapshot; overlaps "
+ "rejected; written in one pass only if every hunk "
+ "succeeds. Takes precedence over old_string/new_string."
+ ),
+ "items": {
+ "type": "object",
+ "properties": {
+ "old_string": {"type": "string"},
+ "new_string": {"type": "string"},
+ "replace_all": {"type": "boolean"},
+ },
+ "required": ["old_string", "new_string"],
+ },
+ },
+ },
+ "required": ["file_path"],
+ }
+ return {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "要编辑文件的绝对路径",
+ },
+ "old_string": {
+ "type": "string",
+ "description": "要替换的文本片段(单处修改模式)",
+ },
+ "new_string": {
+ "type": "string",
+ "description": "替换后的文本(单处修改模式)",
+ },
+ "replace_all": {
+ "type": "boolean",
+ "description": "替换所有匹配项(默认 false)",
+ },
+ "hunks": {
+ "type": "array",
+ "description": (
+ "批量修改模式:一次提交同一文件的全部修改,优先级高于 "
+ "old_string/new_string。所有 hunk 对同一份内容快照匹配、"
+ "互相不得重叠,全部成功才一次写回"
+ ),
+ "items": {
+ "type": "object",
+ "properties": {
+ "old_string": {"type": "string"},
+ "new_string": {"type": "string"},
+ "replace_all": {"type": "boolean"},
+ },
+ "required": ["old_string", "new_string"],
+ },
+ },
+ },
+ "required": ["file_path"],
+ }
+
+
+class FlashEditFileTool(EditFileTool):
+ """EditFileTool with snapshot-cache matching, JSONL history and hunks."""
+
+ def __init__(self, operation, language: str = "cn", agent_id: Optional[str] = None):
+ super().__init__(operation, language, agent_id)
+ lang = language or "cn"
+ self.card.description = FLASH_EDIT_DESCRIPTION.get(
+ lang, FLASH_EDIT_DESCRIPTION["cn"]
+ )
+ self.card.input_params = get_flash_edit_input_params(lang)
+
+ # ------------------------------------------------------------------
+ # Input normalization
+ # ------------------------------------------------------------------
+
+ def _parse_hunks(self, inputs: Dict[str, Any]) -> Tuple[Optional[List[Tuple[str, str, bool]]], Optional[str]]:
+ """归一化为 [(old, new, replace_all)] 列表;出错返回 (None, error)。"""
+ hunks_raw = inputs.get("hunks")
+ if hunks_raw:
+ if not isinstance(hunks_raw, list):
+ return None, "hunks must be an array of {old_string, new_string} objects."
+ if not hunks_raw:
+ return None, "hunks must not be empty."
+ hunks: List[Tuple[str, str, bool]] = []
+ for idx, hunk in enumerate(hunks_raw):
+ if not isinstance(hunk, dict):
+ return None, f"hunks[{idx}] must be an object."
+ hunk_old = hunk.get("old_string", "")
+ hunk_new = hunk.get("new_string")
+ if hunk_new is None:
+ return None, f"hunks[{idx}].new_string is required."
+ if not isinstance(hunk_old, str) or not isinstance(hunk_new, str):
+ return None, f"hunks[{idx}] old_string/new_string must be strings."
+ hunks.append((hunk_old, hunk_new, bool(hunk.get("replace_all", False))))
+ return hunks, None
+ new_str = inputs.get("new_string")
+ if new_str is None:
+ return None, "new_string is required."
+ return [(inputs.get("old_string", ""), new_str, bool(inputs.get("replace_all", False)))], None
+
+ # ------------------------------------------------------------------
+ # New-file creation (mirrors stock lines 1856-1904, incl. no-history)
+ # ------------------------------------------------------------------
+
+ async def _create_new_file(
+ self,
+ file_path: str,
+ new_str: str,
+ *,
+ file_exists: bool,
+ is_unc: bool,
+ is_office: bool,
+ ) -> ToolOutput:
+ if file_exists and not is_unc:
+ try:
+ if is_office:
+ existing_content = await _read_office_plain_text_async(file_path)
+ else:
+ existing_content, _ = await self._read_existing_text(file_path)
+ except Exception as exc:
+ return ToolOutput(success=False, error=str(exc))
+ if existing_content.strip() != "":
+ return ToolOutput(
+ success=False,
+ error="Cannot create new file - file already exists.",
+ )
+ if is_office:
+ try:
+ await _write_office_document_async(file_path, new_str)
+ except Exception as exc:
+ return ToolOutput(success=False, error=f"Create failed: {exc}")
+ else:
+ write_res = await self.operation.fs().write_file(
+ file_path, new_str, prepend_newline=False, create_if_not_exist=True
+ )
+ if write_res.code != StatusCode.SUCCESS.code:
+ return ToolOutput(success=False, error=f"Create failed: {write_res.message}")
+ try:
+ _st = os.stat(file_path)
+ registered = new_str.replace("\r\n", "\n")
+ if is_office:
+ registered = await _office_registry_content(file_path, new_str)
+ line_count = len(registered.splitlines()) if registered else 0
+ _FILE_READ_REGISTRY[file_path] = _FileReadState(
+ mtime_ns=_st.st_mtime_ns,
+ size_bytes=_st.st_size,
+ is_partial=False,
+ content=registered,
+ total_lines=line_count,
+ read_ranges=[(1, line_count)] if line_count > 0 else [],
+ )
+ if not is_office:
+ record_written_meta(
+ file_path,
+ new_str,
+ mtime_ns=_st.st_mtime_ns,
+ size_bytes=_st.st_size,
+ )
+ except OSError:
+ _FILE_READ_REGISTRY.pop(file_path, None)
+ pop_file_meta(file_path)
+ return ToolOutput(
+ success=True,
+ data={"file_path": file_path, "replacements": 0, "created": True},
+ )
+
+ # ------------------------------------------------------------------
+ # invoke
+ # ------------------------------------------------------------------
+
+ async def _invoke_unlocked(self, inputs: Dict[str, Any], **kwargs) -> ToolOutput: # noqa: C901
+ hunks, parse_error = self._parse_hunks(inputs)
+ if parse_error:
+ return ToolOutput(success=False, error=parse_error)
+
+ file_path = inputs.get("file_path")
+ if not file_path:
+ return ToolOutput(success=False, error="file_path is required")
+ try:
+ file_path = _resolve_tool_file_path(self.operation, file_path)
+ except ValueError as exc:
+ return ToolOutput(success=False, error=str(exc))
+
+ if file_path.lower().endswith(".ipynb"):
+ return ToolOutput(
+ success=False,
+ error="Cannot edit .ipynb files with this tool. Use NotebookEdit instead.",
+ )
+
+ is_office = _is_office_doc_path(file_path)
+ if is_office:
+ _, office_ext = os.path.splitext(file_path.lower())
+ if office_ext not in _OFFICE_WRITE_EXTENSIONS:
+ return ToolOutput(
+ success=False,
+ error=_office_write_unsupported_error(file_path, "edit_file"),
+ )
+
+ for idx, (hunk_old, hunk_new, _) in enumerate(hunks):
+ if hunk_old == hunk_new:
+ where = f"hunks[{idx}]" if len(hunks) > 1 else "old_string and new_string"
+ return ToolOutput(
+ success=False,
+ error=f"{where} are identical; no changes would be made.",
+ )
+
+ is_unc = _is_unc_path(file_path)
+ if is_unc:
+ file_exists = True
+ elif self.operation.mode == OperationMode.SANDBOX:
+ # 沙箱模式下 os.path.exists 只能看到主容器文件系统,实际文件在
+ # jiuwenbox sidecar 中,用沙箱 fs 探测真实存在性(stock 同款)。
+ try:
+ _probe = await self.operation.fs().read_file(file_path, mode="bytes")
+ file_exists = _probe.code == StatusCode.SUCCESS.code
+ except Exception:
+ file_exists = False
+ else:
+ file_exists = os.path.exists(file_path)
+
+ # ---- 新建文件:仅单 hunk 且 old 为空时保持 stock 语义 --------------
+ empty_old_count = sum(1 for hunk_old, _, _ in hunks if hunk_old == "")
+ if empty_old_count:
+ if len(hunks) == 1:
+ return await self._create_new_file(
+ file_path,
+ hunks[0][1],
+ file_exists=file_exists,
+ is_unc=is_unc,
+ is_office=is_office,
+ )
+ return ToolOutput(
+ success=False,
+ error=(
+ "empty old_string (file creation) cannot be mixed with "
+ "other hunks in one call."
+ ),
+ )
+
+ if not file_exists:
+ similar = self._find_similar_paths(file_path)
+ hint = f" Similar paths: {similar}" if similar else ""
+ return ToolOutput(
+ success=False,
+ error=f"File not found: '{file_path}'.{hint}",
+ )
+
+ # ---- 体积护栏 + stat(stock 1916-1939) ----------------------------
+ if not is_unc:
+ _stat = None
+ try:
+ _stat = os.stat(file_path)
+ except OSError as exc:
+ if self.operation.mode != OperationMode.SANDBOX:
+ return ToolOutput(success=False, error=str(exc))
+ if _stat is not None and _stat.st_size > self.MAX_FILE_SIZE:
+ return ToolOutput(
+ success=False,
+ error=(
+ f"File is too large ({_stat.st_size // (1024 ** 3)} GiB). "
+ "Maximum allowed size is 1 GiB."
+ ),
+ )
+ current_mtime = _stat.st_mtime_ns if _stat else 0
+ current_size = _stat.st_size if _stat else 0
+ else:
+ current_mtime = 0
+ current_size = 0
+
+ # ---- 准入门槛(stock 1941-1957:必须读过,部分读也算数) ------------
+ read_state = _FILE_READ_REGISTRY.get(file_path)
+ if read_state is None:
+ return ToolOutput(
+ success=False,
+ error=(
+ f"File must be read before editing. "
+ f"Call read_file on '{file_path}' first."
+ ),
+ )
+
+ # ---- 内容获取:缓存命中 or 全量读(含外部修改检测折叠) --------------
+ meta = get_file_meta(file_path)
+ cache_ok = (
+ not is_office
+ and not is_unc
+ and self.operation.mode == OperationMode.LOCAL
+ and read_state.content is not None
+ and read_state.mtime_ns == current_mtime
+ and read_state.size_bytes == current_size
+ and meta is not None
+ and not meta.mixed_eol
+ and meta.snapshot_mtime_ns == current_mtime
+ and meta.snapshot_size_bytes == current_size
+ )
+
+ mtime_matches = (
+ read_state.mtime_ns == current_mtime
+ and read_state.size_bytes == current_size
+ )
+
+ original_content: str
+ if cache_ok:
+ # 零读盘:registry 内容快照 + 侧车元数据同代(mtime/size 双绑)。
+ # registry 只存 LF 归一化文本;统一 EOL 可无损重建,混合 EOL
+ # 已在 cache_ok 中排除,必须回退 fresh read 取原始文本。
+ content_lf = read_state.content
+ original_content = (
+ content_lf.replace("\n", meta.eol) if meta.eol == "\r\n" else content_lf
+ )
+ expected_sha = meta.sha256
+ else:
+ try:
+ if is_office:
+ original_content = await _read_office_plain_text_async(file_path)
+ expected_sha = None
+ else:
+ original_content, raw = await self._read_existing_text(file_path)
+ expected_sha = hashlib.sha256(raw).hexdigest()
+ except Exception as exc:
+ return ToolOutput(success=False, error=str(exc))
+
+ if not is_unc and not mtime_matches:
+ # 外部修改检测(stock 1959-1981 的折叠实现:这一次读同时供
+ # 比对与编辑,比 stock 的"比对读一次 + 主读再一次"少一读)。
+ content_lf_check = original_content.replace("\r\n", "\n")
+ if read_state.content is None or content_lf_check != read_state.content:
+ _FILE_READ_REGISTRY.pop(file_path, None)
+ pop_file_meta(file_path)
+ return ToolOutput(
+ success=False,
+ error=(
+ f"'{file_path}' has been modified externally since it was last read. "
+ "Re-read the file before editing."
+ ),
+ )
+
+ content_lf = original_content.replace("\r\n", "\n")
+
+ # ---- 逐 hunk 匹配(stock 1998-2028 的清洗/容错/唯一性逐个套用) -----
+ _, ext = os.path.splitext(file_path.lower())
+ preserve_md = ext in self._MD_EXTENSIONS
+
+ planned: List[Tuple[int, int, str]] = [] # (start, end, new_text)
+ for idx, (hunk_old, hunk_new, hunk_replace_all) in enumerate(hunks):
+ where = f"hunks[{idx}]" if len(hunks) > 1 else "old_string"
+ old_clean = self._desanitize(hunk_old).replace("\r\n", "\n")
+ new_clean = self._desanitize(hunk_new).replace("\r\n", "\n")
+ if not old_clean:
+ return ToolOutput(
+ success=False,
+ error=f"{where} is empty after sanitization.",
+ )
+ if not preserve_md:
+ new_clean = self._strip_trailing_whitespace(new_clean)
+
+ match_str = old_clean
+ if match_str not in content_lf:
+ variant = self._try_quote_variants(content_lf, old_clean)
+ if variant is None:
+ return ToolOutput(
+ success=False,
+ error=f"{where} not found in '{file_path}'.",
+ )
+ match_str = variant
+ new_clean = self._preserve_quote_style(old_clean, match_str, new_clean)
+
+ count = content_lf.count(match_str)
+ if not hunk_replace_all and count > 1:
+ return ToolOutput(
+ success=False,
+ error=(
+ f"{where} matches {count} times in '{file_path}'. "
+ "Provide more surrounding context to make it unique, "
+ "or set replace_all=true to replace every occurrence."
+ ),
+ )
+
+ positions: List[int] = []
+ if hunk_replace_all:
+ cursor = 0
+ while True:
+ pos = content_lf.find(match_str, cursor)
+ if pos == -1:
+ break
+ positions.append(pos)
+ cursor = pos + len(match_str)
+ else:
+ positions.append(content_lf.find(match_str))
+ for pos in positions:
+ planned.append((pos, pos + len(match_str), new_clean))
+
+ # ---- 重叠拒绝 + 应用(从后往前,避免偏移失效) ----------------------
+ planned.sort(key=lambda item: item[0])
+ for prev, curr in zip(planned, planned[1:]):
+ if curr[0] < prev[1]:
+ return ToolOutput(
+ success=False,
+ error=(
+ "Overlapping edits are not allowed: two hunks match "
+ "overlapping regions of the file. Merge them into one hunk."
+ ),
+ )
+
+ # LF span → original span 后在原始文本上一次 join:
+ # 1) 混合 EOL 文件的未编辑区域逐字节保持原样;
+ # 2) replace_all 大量匹配时不再反复切片复制整份文件。
+ eol_context = _build_eol_context(original_content)
+ parts: List[str] = []
+ cursor = 0
+ for start, end, text in planned:
+ orig_start = eol_context.to_original(start)
+ orig_end = eol_context.to_original(end)
+ parts.append(original_content[cursor:orig_start])
+ parts.append(
+ _replacement_with_original_eol(
+ eol_context,
+ orig_start,
+ orig_end,
+ text,
+ )
+ )
+ cursor = orig_end
+ parts.append(original_content[cursor:])
+ new_content = "".join(parts)
+ new_content_lf = new_content.replace("\r\n", "\n")
+
+ # ---- 写回(stock 2041-2055:CAS 乐观锁仅本地后端执行) -------------
+ if is_office:
+ try:
+ await _write_office_document_async(file_path, new_content_lf)
+ except Exception as exc:
+ return ToolOutput(success=False, error=f"Write failed: {exc}")
+ else:
+ options = (
+ {"expected_content_sha256": expected_sha}
+ if expected_sha
+ else None
+ )
+ write_res = await self.operation.fs().write_file(
+ file_path,
+ new_content,
+ prepend_newline=False,
+ options=options,
+ )
+ if write_res.code != StatusCode.SUCCESS.code:
+ return ToolOutput(success=False, error=f"Write failed: {write_res.message}")
+
+ # ---- registry 回填(stock 语义)+ 侧车更新 --------------------------
+ try:
+ _st2 = os.stat(file_path)
+ line_count = len(new_content_lf.splitlines()) if new_content_lf else 0
+ registered = new_content_lf
+ if is_office:
+ registered = await _office_registry_content(file_path, new_content_lf)
+ line_count = len(registered.splitlines()) if registered else 0
+ _FILE_READ_REGISTRY[file_path] = _FileReadState(
+ mtime_ns=_st2.st_mtime_ns,
+ size_bytes=_st2.st_size,
+ is_partial=False,
+ content=registered,
+ total_lines=line_count,
+ read_ranges=[(1, line_count)] if line_count > 0 else [],
+ )
+ if not is_office:
+ record_written_meta(
+ file_path,
+ new_content,
+ mtime_ns=_st2.st_mtime_ns,
+ size_bytes=_st2.st_size,
+ )
+ except OSError:
+ _FILE_READ_REGISTRY.pop(file_path, None)
+ pop_file_meta(file_path)
+
+ # ---- history 纯追加(schema 与 stock 一致,diff_service 合并读取) --
+ # old/new 均保存实际原文/写回文本:缓存路径只会在统一 EOL 下重建,
+ # 混合 EOL 强制 fresh read;Office 写入器始终消费 LF 文本。
+ _session = get_current_session()
+ if _session is not None:
+ _history_path = build_flash_history_path(_session)
+ if _history_path:
+ old_for_history = content_lf if is_office else original_content
+ new_for_history = new_content_lf if is_office else new_content
+ entry = {
+ "action": "edit",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "old_content": old_for_history,
+ "new_content": new_for_history,
+ }
+ try:
+ await asyncio.to_thread(
+ append_flash_history_entry, _history_path, file_path, entry
+ )
+ except Exception as exc: # noqa: BLE001
+ # history 是旁路账本:写失败不阻断编辑主流程(stock 同款
+ # 容忍度,只 warning)。
+ logger.warning(
+ "[FlashEditFileTool] Failed to append flash history: %s", exc
+ )
+
+ return ToolOutput(
+ success=True,
+ data={
+ "file_path": file_path,
+ "replacements": len(planned),
+ "hunks": len(hunks),
+ },
+ )
+
+ async def stream(self, inputs: Dict[str, Any], **kwargs) -> Any:
+ # 与 FlashReadFileTool 同约定:flash 工具不走增量流式,整包产出。
+ yield await self.invoke(inputs, **kwargs)
+
+
+__all__ = ["FlashEditFileTool"]
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_file_history.py b/jiuwenswarm/agents/harness/flash/tools/flash_file_history.py
new file mode 100644
index 0000000000..4be43506aa
--- /dev/null
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_file_history.py
@@ -0,0 +1,162 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""flash 文件操作的 JSONL history(热路径纯追加 + 低频原子重写)。
+
+stock 的 ``_append_op_history``(agent-core,冻结)每次操作都要
+json.load 整个历史 → append → json.dump 整文件原子替换,单次成本
+O(全部历史),长会话内随编辑次数二次方恶化。flash edit_file 改为独立
+JSONL 账本:
+
+- **热路径(每次编辑)**:``append_flash_history_entry`` 纯追加一行,
+ O(单条目),不触碰旧行;
+- **低频路径(/rewind 软删 / restore / discard)**:diff_service 调
+ ``rewrite_flash_history`` 原子重写——语义与 stock 的整文件重写完全
+ 一致,只是把重写成本从"每次编辑"挪到"每次回退"(用户触发的稀有
+ 操作)。
+
+条目 schema 与 stock JSON 一致(``{action, timestamp, old_content,
+new_content}`` + 软删标记字段),差异仅在文件形状:JSONL 每行一条并
+额外携带 ``file_path`` 分组键。``load_flash_history`` 聚合后即为 stock
+的 ``{file_path: [entries]}`` dict,diff_service 的合并/去重/回滚/软删
+逻辑零改动复用。
+
+文件名约定 ``file_ops_flash_{agent_id}_{session_id}.jsonl``:以
+``file_ops_`` 开头保证 cleanup 扫描与 diff_service 的 session 匹配可
+及;``.jsonl`` 后缀保证不会被 stock 的 ``.json`` 精确匹配误当成 JSON
+解析。
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import threading
+from pathlib import Path
+from typing import Any, Dict, Optional, Union
+
+from openjiuwen.core.sys_operation.cwd import get_cwd, get_workspace
+
+# 进程内互斥:append(flash 工具,async 侧经 to_thread 调入)与 rewrite
+# (diff_service,同步调用)共用同一把 per-path 锁,保证追加与重写不交错。
+# stock 只用 asyncio.Lock 护自己的写入,同样不跨进程——这里与其风险等级
+# 对齐,不引入文件锁。
+_HISTORY_LOCKS: Dict[str, threading.Lock] = {}
+_HISTORY_LOCKS_GUARD = threading.Lock()
+
+FLASH_HISTORY_SUFFIX = ".jsonl"
+
+
+def _history_lock(history_path: str) -> threading.Lock:
+ key = os.path.normcase(os.path.abspath(history_path))
+ with _HISTORY_LOCKS_GUARD:
+ lock = _HISTORY_LOCKS.get(key)
+ if lock is None:
+ lock = threading.Lock()
+ _HISTORY_LOCKS[key] = lock
+ return lock
+
+
+def build_flash_history_path(session: Any) -> Optional[str]:
+ """与 stock EditFileTool._build_history_path 同口径的落点推导。
+
+ stock edit 在 flash 会话里写的就是这个 base_dir(get_workspace() 或
+ cwd)下的 .agent_history,diff_service 也从这里扫描——flash 账本落在
+ 同一目录才能被合并读取。
+ """
+ try:
+ base_dir = get_workspace() or str(Path(get_cwd()).expanduser().resolve())
+ agent_id = (
+ session.agent_id() if hasattr(session, "agent_id")
+ else session.get_agent_id() if hasattr(session, "get_agent_id")
+ else None
+ ) or "default"
+ return os.path.join(
+ base_dir, ".agent_history",
+ f"file_ops_flash_{agent_id}_{session.get_session_id()}.jsonl",
+ )
+ except Exception:
+ return None
+
+
+def append_flash_history_entry(
+ history_path: str,
+ file_path: str,
+ entry: Dict[str, Any],
+) -> None:
+ """追加一条 file_ops 记录(同步函数;调用方负责 to_thread)。"""
+ line = {"file_path": file_path, **entry}
+ payload = json.dumps(line, ensure_ascii=False) + "\n"
+ with _history_lock(history_path):
+ os.makedirs(os.path.dirname(history_path), exist_ok=True)
+ with open(history_path, "a", encoding="utf-8") as f:
+ f.write(payload)
+
+
+def load_flash_history(history_path: Union[str, Path]) -> Dict[str, list]:
+ """JSONL → {file_path: [entries]}(stock JSON 的聚合形状)。"""
+ result: Dict[str, list] = {}
+ path = Path(history_path)
+ if not path.is_file():
+ return result
+ try:
+ with open(path, "r", encoding="utf-8") as f:
+ for raw_line in f:
+ line = raw_line.strip()
+ if not line:
+ continue
+ try:
+ record = json.loads(line)
+ except json.JSONDecodeError:
+ # 单行损坏只丢该行,不拖垮整个历史(stock 对整个 JSON
+ # 解析失败的容忍度是丢整个文件,这里逐行更细)。
+ continue
+ if not isinstance(record, dict):
+ continue
+ file_path = record.get("file_path")
+ if not isinstance(file_path, str) or not file_path:
+ continue
+ entry = {k: v for k, v in record.items() if k != "file_path"}
+ result.setdefault(file_path, []).append(entry)
+ except OSError:
+ return {}
+ return result
+
+
+def _rewrite_flash_history_unlocked(path: Path, data: Dict[str, Any]) -> None:
+ lines = []
+ for file_path, entries in data.items():
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ lines.append(
+ json.dumps({"file_path": file_path, **entry}, ensure_ascii=False)
+ )
+ path_str = str(path)
+ os.makedirs(os.path.dirname(path_str), exist_ok=True)
+ tmp = path_str + ".tmp"
+ with open(tmp, "w", encoding="utf-8") as f:
+ f.write("\n".join(lines) + ("\n" if lines else ""))
+ os.replace(tmp, path_str)
+
+
+def rewrite_flash_history(history_path: Union[str, Path], data: Dict[str, Any]) -> None:
+ """按 stock 形状原子重写 JSONL(软删/恢复/截断专用,低频路径)。"""
+ path = Path(history_path)
+ with _history_lock(str(path)):
+ _rewrite_flash_history_unlocked(path, data)
+
+
+def is_flash_history_name(name: str) -> bool:
+ return name.startswith("file_ops_flash_") and name.endswith(FLASH_HISTORY_SUFFIX)
+
+
+__all__ = [
+ "FLASH_HISTORY_SUFFIX",
+ "append_flash_history_entry",
+ "build_flash_history_path",
+ "is_flash_history_name",
+ "load_flash_history",
+ "rewrite_flash_history",
+]
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_file_meta.py b/jiuwenswarm/agents/harness/flash/tools/flash_file_meta.py
new file mode 100644
index 0000000000..1ab1dcd560
--- /dev/null
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_file_meta.py
@@ -0,0 +1,144 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""flash 文件元数据侧车缓存(snapshot-bound sidecar)。
+
+agent-core 的读注册表(``_FILE_READ_REGISTRY``)只保存 LF 归一化后的文本
+内容,原始字节里的 sha256 / EOL / 编码在读取时被丢弃。本模块在 flash 读
+文件时顺手把这三样元数据补记下来,供 FlashEditFileTool 在"缓存命中"路
+径上零读盘匹配,并把 CAS 乐观锁哈希(``expected_content_sha256``)原样
+传给 fs 层——竞态防护与 stock 每次全量读的方案完全等价。
+
+绑定规则(评审确立的不变量):**内容、摘要、EOL、编码必须来自同一份快照**,
+以 (mtime_ns, size_bytes) 作为快照版本号。任何一项失配即视为快照过期,
+调用方必须回退全量读,不得拼用两代快照的字段。stock write_file 等非
+flash 工具改写文件后 mtime 变化,旧侧车自然失效,一次全量读后自愈。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import os
+from dataclasses import dataclass
+from typing import Dict, Optional
+
+
+@dataclass
+class FlashFileMeta:
+ """单文件快照元数据:与 registry 内容快照同源同拍。"""
+
+ sha256: str
+ eol: str
+ encoding: str
+ mixed_eol: bool
+ snapshot_mtime_ns: int
+ snapshot_size_bytes: int
+
+
+_FILE_META_CACHE: Dict[str, FlashFileMeta] = {}
+
+
+def _meta_key(file_path: str) -> str:
+ return os.path.normcase(os.path.abspath(file_path))
+
+
+def detect_encoding(raw: bytes) -> str:
+ """UTF-16 LE BOM 探测,与 agent-core EditFileTool._detect_encoding 同口径。"""
+ return "utf-16-le" if raw[:2] == b"\xff\xfe" else "utf-8"
+
+
+def detect_eol(raw: bytes) -> str:
+ """与 agent-core EditFileTool._detect_eol 同口径。"""
+ return "\r\n" if b"\r\n" in raw else "\n"
+
+
+def detect_mixed_eol(raw: bytes) -> bool:
+ """是否同时存在 CRLF 与独立 LF。
+
+ 统一 CRLF / 统一 LF 都能从 LF 归一化文本无损重建;只有二者混合时,
+ “LF 归一化 + 单一 EOL” 不足以还原原始字节,必须回退全量读。
+ """
+ if b"\r\n" not in raw:
+ return False
+ idx = raw.find(b"\n")
+ while idx != -1:
+ if idx == 0 or raw[idx - 1] != 0x0D:
+ return True
+ idx = raw.find(b"\n", idx + 1)
+ return False
+
+
+def _text_has_mixed_eol(content: str) -> bool:
+ if "\r\n" not in content:
+ return False
+ idx = content.find("\n")
+ while idx != -1:
+ if idx == 0 or content[idx - 1] != "\r":
+ return True
+ idx = content.find("\n", idx + 1)
+ return False
+
+
+def record_file_meta(file_path: str, raw: bytes, mtime_ns: int, size_bytes: int) -> FlashFileMeta:
+ """读取快照后记录元数据(raw 必须是刚读到的原始字节,读前 stat)。"""
+ meta = FlashFileMeta(
+ sha256=hashlib.sha256(raw).hexdigest(),
+ eol=detect_eol(raw),
+ encoding=detect_encoding(raw),
+ mixed_eol=detect_mixed_eol(raw),
+ snapshot_mtime_ns=mtime_ns,
+ snapshot_size_bytes=size_bytes,
+ )
+ _FILE_META_CACHE[_meta_key(file_path)] = meta
+ return meta
+
+
+def record_written_meta(
+ file_path: str,
+ content: str,
+ *,
+ mtime_ns: int,
+ size_bytes: int,
+ encoding: str = "utf-8",
+) -> FlashFileMeta:
+ """写回后按实际提交内容记录元数据。
+
+ fs 层 write_file 的默认编码是 utf-8(stock EditFileTool 不传 encoding,
+ 二者同口径);EOL 从写回内容本身探测。调用方拿不到写后 stat(如沙箱
+ 本地 os.stat 失败)时应改调 pop_file_meta 主动作废,宁慢不错配。
+ """
+ meta = FlashFileMeta(
+ sha256=hashlib.sha256(content.encode(encoding, errors="replace")).hexdigest(),
+ eol="\r\n" if "\r\n" in content else "\n",
+ encoding=encoding,
+ mixed_eol=_text_has_mixed_eol(content),
+ snapshot_mtime_ns=mtime_ns,
+ snapshot_size_bytes=size_bytes,
+ )
+ _FILE_META_CACHE[_meta_key(file_path)] = meta
+ return meta
+
+
+def get_file_meta(file_path: str) -> Optional[FlashFileMeta]:
+ return _FILE_META_CACHE.get(_meta_key(file_path))
+
+
+def pop_file_meta(file_path: str) -> None:
+ _FILE_META_CACHE.pop(_meta_key(file_path), None)
+
+
+def clear_file_meta_cache() -> None:
+ """测试隔离用:清空进程内缓存。"""
+ _FILE_META_CACHE.clear()
+
+
+__all__ = [
+ "FlashFileMeta",
+ "clear_file_meta_cache",
+ "detect_encoding",
+ "detect_eol",
+ "detect_mixed_eol",
+ "get_file_meta",
+ "pop_file_meta",
+ "record_file_meta",
+ "record_written_meta",
+]
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
index d18dee3f61..d14ace773a 100644
--- a/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
@@ -27,13 +27,17 @@ import os
import re
from typing import Any, Dict, List, Optional
+from openjiuwen.core.common.exception.codes import StatusCode
from openjiuwen.harness.tools.base_tool import ToolOutput
from openjiuwen.harness.tools.filesystem import (
ReadFileTool,
_ReadStateRecord,
+ _RawTextState,
_resolve_tool_file_path,
)
+from .flash_file_meta import detect_encoding, record_file_meta
+
logger = logging.getLogger(__name__)
MAX_FILES_PER_CALL = 10
@@ -144,6 +148,51 @@ class FlashReadFileTool(ReadFileTool):
)
self.card.input_params = get_flash_read_input_params(lang)
+ # ------------------------------------------------------------------
+ # Snapshot read override (bytes fast path)
+ # ------------------------------------------------------------------
+
+ async def _read_raw_text_for_edit_state(self, file_path: str) -> Optional[_RawTextState]:
+ """bytes 一次读快照(覆写 stock 的 text 逐行全读)。
+
+ stock 实现走 ``fs.read_file`` 默认 text 模式 → ``_read_full`` 的
+ aiofiles 逐行 yield,每行一次 executor 往返(隔离微基准:240KB /
+ 1 万行约 720-810ms,bytes 全读 0.49-0.68ms)。本覆写改为 bytes
+ 模式一次读完,在内存中解码归一化,返回签名与 stock 一致——
+ ``_record_read_state`` 的调用方(单文件/多文件两条路径)无感知。
+
+ 顺手把 stock 丢弃的原始字节元数据(sha256/EOL/编码)记入侧车缓存
+ (读前 stat 绑定快照版本),供 FlashEditFileTool 缓存命中路径使用。
+ """
+ if self._is_office_doc(file_path):
+ # Office 文本抽取管线与 raw bytes 语义不同,维持 stock 行为。
+ return await super()._read_raw_text_for_edit_state(file_path)
+ try:
+ try:
+ _st = os.stat(file_path)
+ mtime_ns, size_bytes = _st.st_mtime_ns, _st.st_size
+ except OSError:
+ # 沙箱:文件在 jiuwenbox sidecar,本地 stat 不可用。仍注册
+ # (mtime/size 记 0);缓存路径不依赖它——沙箱无 CAS,flash
+ # edit 在沙箱下不走缓存。
+ mtime_ns, size_bytes = 0, 0
+ res = await self.operation.fs().read_file(file_path, mode="bytes")
+ if res.code != StatusCode.SUCCESS.code:
+ return None
+ raw = res.data.content if res.data else b""
+ if isinstance(raw, str):
+ raw = raw.encode("utf-8")
+ record_file_meta(file_path, raw, mtime_ns, size_bytes)
+ content = raw.decode(detect_encoding(raw), errors="replace")
+ normalized = str(content).replace("\r\n", "\n")
+ return _RawTextState(
+ content=normalized,
+ line_count=self._raw_line_count(normalized),
+ )
+ except Exception:
+ # 与 stock 同口径:读失败返回 None,调用方按无快照处理。
+ return None
+
# ------------------------------------------------------------------
# Single-file reader (reused in both single and multi modes)
# ------------------------------------------------------------------
diff --git a/jiuwenswarm/common/cleanup.py b/jiuwenswarm/common/cleanup.py
index bda739b69c..6830cddd1d 100644
--- a/jiuwenswarm/common/cleanup.py
+++ b/jiuwenswarm/common/cleanup.py
@@ -107,7 +107,12 @@ def cleanup_orphan_file_ops() -> dict[str, int]:
if not f.is_file():
continue
name = f.name
- if not name.startswith(f"file_ops_{AGENT_ID}_") or not name.endswith(".json"):
+ # flash edit_file 的追加账本:file_ops_flash_{AGENT_ID}_* 前缀 +
+ # .jsonl 后缀(注意不能只查 file_ops_{AGENT_ID}_ 前缀——flash
+ # 账本多一段 flash_,前缀不匹配会导致孤儿 .jsonl 永不清理)。
+ if not name.startswith(
+ (f"file_ops_{AGENT_ID}_", f"file_ops_flash_{AGENT_ID}_")
+ ) or not name.endswith((".json", ".jsonl")):
continue
# 检查文件名中是否包含某个现存 session 的 id
orphaned = True
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index cb852cfdd4..49b7bf347e 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -55,6 +55,73 @@ class DiffHistoryExpiredError(RuntimeError):
"""历史 diff 索引仍存在但详情已无法重建。"""
+def _load_file_ops_data(path: Path) -> dict[str, Any]:
+ """按扩展名加载 file_ops:``.json``(stock 整档 dict)或 ``.jsonl``(flash 追加账本)。
+
+ flash edit_file 的 JSONL 条目 schema 与 stock 一致,``load_flash_history``
+ 聚合后即为 stock 的 ``{file_path: [entries]}`` 形状——上层合并/去重/软删
+ 逻辑对两种来源无差别。
+ """
+ if path.name.endswith(".jsonl"):
+ try:
+ from jiuwenswarm.agents.harness.flash.tools.flash_file_history import (
+ load_flash_history,
+ )
+ except ImportError:
+ # flash 包被裁剪的发行版里残留的 .jsonl 账本:按空账本降级
+ # (与损坏 JSON 的容忍度对齐——warning + 跳过),不让 ImportError
+ # 穿透上层 ``except (json.JSONDecodeError, OSError)`` 打断整条
+ # diff / rewind 链;stock 账本照常可见(评审意见:懒 import 失败面)。
+ logger.warning(
+ "_load_file_ops_data: flash module unavailable, "
+ "skip jsonl ledger %s",
+ path,
+ )
+ return {}
+ return load_flash_history(path)
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _save_file_ops_data(path: Path, data: dict[str, Any]) -> None:
+ """按扩展名写回 file_ops(截断/软删/恢复等低频重写路径专用)。
+
+ JSONL 走 flash 模块的原子重写(与 append 共用 per-path 锁,追加与重写
+ 不交错);JSON 维持 stock 的整文件写法。
+ """
+ if path.name.endswith(".jsonl"):
+ try:
+ from jiuwenswarm.agents.harness.flash.tools.flash_file_history import (
+ rewrite_flash_history,
+ )
+ except ImportError:
+ # 与 _load_file_ops_data 对称:flash 模块缺失时跳过重写并留痕,
+ # 残留账本保持原样(不写半截),调用方(truncate/restore)继续
+ # 处理其余账本。
+ logger.warning(
+ "_save_file_ops_data: flash module unavailable, "
+ "skip rewrite of %s",
+ path,
+ )
+ return
+ rewrite_flash_history(path, data)
+ return
+ path.write_text(
+ json.dumps(data, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+
+
+def _entry_sort_ts(ts: Any) -> float:
+ """条目时间戳排序键:无法解析的排最后(稳定排序保留同刻原序)。"""
+ try:
+ parsed = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.timestamp()
+ except (ValueError, TypeError):
+ return float("inf")
+
+
class DiffService:
"""提供 turn-based diff 查询服务."""
@@ -703,8 +770,12 @@ class DiffService:
"""检查文件名是否是有效的 file_ops 文件.
文件名约定: ``file_ops_{agent_id}_{session_id}.json``,其中 session_id
- 始终是 ``.json`` 前的最后一段。使用 ``_{session_id}.json`` 后缀匹配替代
+ 始终是扩展名前的最后一段。使用 ``_{session_id}.json`` 后缀匹配替代
子串匹配,避免短 session_id 误匹配其他 agent 的 file_ops 文件。
+ flash edit_file 的追加账本 ``file_ops_flash_*_{session_id}.jsonl``
+ 遵循同一命名骨架;匹配前先剥掉 ``flash_`` 段,使其与 stock 的
+ ``file_ops_{agent}_...`` 等价处理(否则子代理形态下 agent 段变成
+ ``flash_xxx`` 含下划线,会被 stock 的无下划线校验误拒)。
当 session_id 对应的是父会话时,也接受子 agent 会话(后缀形如
``_sub_{type}_{suffix}``)的 file_ops 文件,使 diff 统计能覆盖子 agent
@@ -712,18 +783,23 @@ class DiffService:
"""
if not name.startswith("file_ops_"):
return False
- if not name.endswith(".json"):
+ if name.endswith(".json"):
+ stem = name[: -len(".json")]
+ elif name.endswith(".jsonl"):
+ stem = name[: -len(".jsonl")]
+ if stem.startswith("file_ops_flash_"):
+ stem = "file_ops_" + stem[len("file_ops_flash_"):]
+ else:
return False
if not session_id:
return not require_session
- suffix = f"_{session_id}.json"
- if name.endswith(suffix):
+ if stem.endswith(f"_{session_id}"):
return True
sub_marker = f"_{session_id}_sub_"
- marker_pos = name.find(sub_marker, len("file_ops_"))
+ marker_pos = stem.find(sub_marker, len("file_ops_"))
if marker_pos < 0:
return False
- agent_id = name[len("file_ops_"):marker_pos]
+ agent_id = stem[len("file_ops_"):marker_pos]
return bool(agent_id) and "_" not in agent_id
@staticmethod
@@ -978,7 +1054,7 @@ class DiffService:
for history_file in paths:
if history_file.exists():
try:
- data = json.loads(history_file.read_text(encoding="utf-8"))
+ data = _load_file_ops_data(history_file)
history_priority = history_file_priorities.get(
path_key(history_file),
HISTORY_PRIORITY_UNKNOWN,
@@ -1041,6 +1117,13 @@ class DiffService:
except (json.JSONDecodeError, OSError) as e:
logger.warning("Failed to read agent history file %s: %s", history_file, e)
+ # 跨账本(stock JSON + flash JSONL)合并后,同一文件的条目按时间戳
+ # 稳定排序:``get_files_to_restore`` 等还原层取"第一条 >= 目标时间"
+ # 的条目,其正确性依赖时间序——文件扫描顺序(OS iterdir)不应影响
+ # 语义。单账本场景下条目本就按写入时序追加,排序为幂等操作。
+ for entries in result.values():
+ entries.sort(key=lambda e: _entry_sort_ts(e.get("timestamp", "")))
+
return result
def _find_file_edits_by_time_range(
@@ -1161,7 +1244,6 @@ class DiffService:
# First change of this hunk is at opcodes[i]; absorb following
# changes whose separating equal run is short enough that their
# context windows bridge the gap (run length <= 2*context_lines).
- change_start = i
o_lo = max(0, i1 - context_lines)
n_lo = max(0, j1 - context_lines)
last_i2 = i2
@@ -2235,7 +2317,7 @@ class DiffService:
for file_ops_path in file_ops_paths:
try:
- data = json.loads(file_ops_path.read_text(encoding="utf-8"))
+ data = _load_file_ops_data(file_ops_path)
if not isinstance(data, dict):
continue
@@ -2267,10 +2349,7 @@ class DiffService:
new_data[file_path] = filtered
if truncated:
- file_ops_path.write_text(
- json.dumps(new_data, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
+ _save_file_ops_data(file_ops_path, new_data)
logger.info(
"truncate_file_ops: cleaned %s (cutoff_ts=%s, soft=%s, marker=%s)",
file_ops_path.name, cutoff_ts, soft, marker,
@@ -2318,7 +2397,7 @@ class DiffService:
for file_ops_path in file_ops_paths:
try:
- data = json.loads(file_ops_path.read_text(encoding="utf-8"))
+ data = _load_file_ops_data(file_ops_path)
if not isinstance(data, dict):
continue
@@ -2342,10 +2421,7 @@ class DiffService:
new_data[file_path] = filtered
if restored:
- file_ops_path.write_text(
- json.dumps(new_data, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
+ _save_file_ops_data(file_ops_path, new_data)
logger.info(
"restore_rewound_entries: restored %s (cutoff_ts=%s, marker=%s)",
file_ops_path.name, cutoff_ts, marker,
diff --git a/tests/unit_tests/agentserver/test_flash_bash_history.py b/tests/unit_tests/agentserver/test_flash_bash_history.py
new file mode 100644
index 0000000000..c5ed242b9c
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_flash_bash_history.py
@@ -0,0 +1,486 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""FlashBashTool 双账本删除探测回归测试。
+
+锁定评审 P1:文件被 flash edit 更新后,再通过 Bash 删除时,delete 记录
+必须保存 flash 侧的最新内容,而不是 stock JSON 里的旧快照。
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import tempfile
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+from openjiuwen.core.common.exception.codes import StatusCode
+from openjiuwen.core.sys_operation import OperationMode
+from openjiuwen.harness.tools.base_tool import ToolOutput
+from openjiuwen.harness.tools.shell.bash._tool import BashTool
+
+import openjiuwen.core.sys_operation.cwd as agent_cwd
+from jiuwenswarm.agents.harness.flash.tools import flash_bash_tool
+from jiuwenswarm.agents.harness.flash.tools import flash_file_history
+from jiuwenswarm.agents.harness.flash.tools.flash_bash_history import (
+ record_detected_deletions,
+)
+from jiuwenswarm.agents.harness.flash.tools.flash_bash_tool import FlashBashTool
+
+
+class _FakeSession:
+ def __init__(self) -> None:
+ self._session_id = "sess-flash-bash"
+ self._agent_id = "flash-bash-agent"
+
+ def get_session_id(self) -> str:
+ return self._session_id
+
+ def agent_id(self) -> str:
+ return self._agent_id
+
+
+class _FakeFs:
+ def __init__(self, content: str) -> None:
+ self._content = content
+
+ async def read_file(self, file_path: str):
+ return SimpleNamespace(
+ code=StatusCode.SUCCESS.code,
+ data=SimpleNamespace(content=self._content),
+ )
+
+
+class _FakeOperation:
+ def __init__(self, content: str) -> None:
+ self.mode = OperationMode.LOCAL
+ self._fs = _FakeFs(content)
+
+ def fs(self) -> _FakeFs:
+ return self._fs
+
+
+def _parsed_command(command: str = "echo hi") -> SimpleNamespace:
+ return SimpleNamespace(
+ command=command,
+ run_in_background=False,
+ workdir=None,
+ )
+
+
+def temp_dir():
+ dir_path = tempfile.mkdtemp()
+ yield dir_path
+ shutil.rmtree(dir_path, ignore_errors=True)
+
+
+def _entry(
+ action: str,
+ timestamp: str,
+ old_content: str,
+ new_content: str | None,
+ **extra,
+) -> dict:
+ return {
+ "action": action,
+ "timestamp": timestamp,
+ "old_content": old_content,
+ "new_content": new_content,
+ **extra,
+ }
+
+
+def test_delete_detection_uses_latest_flash_content(temp_dir):
+ """stock 旧快照 + flash 新快照混合时,delete 必须记录 flash 最新内容。"""
+ file_path = str(Path(temp_dir) / "mixed.txt")
+ stock_path = Path(temp_dir) / ".agent_history" / "file_ops_agent_session.json"
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ stock_path.parent.mkdir(parents=True, exist_ok=True)
+ stock_path.write_text(
+ json.dumps(
+ {
+ file_path: [
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ "original",
+ )
+ ]
+ },
+ ensure_ascii=False,
+ ),
+ encoding="utf-8",
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:01:00+00:00",
+ "original",
+ "updated",
+ ),
+ )
+
+ record_detected_deletions(str(stock_path), str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 2
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "updated"
+ assert entries[-1]["new_content"] is None
+
+
+def test_delete_detection_covers_flash_only_history(temp_dir):
+ """文件只有 flash 历史、没有 stock JSON 时,删除也不能漏记。"""
+ file_path = str(Path(temp_dir) / "flash-only.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "",
+ "flash only",
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "flash only"
+
+
+def test_delete_detection_keeps_rewound_edit_as_current_content(temp_dir):
+ """conversation rewind 不恢复工作区,删除前内容必须取 rewound edit。"""
+ file_path = str(Path(temp_dir) / "rewound-edit.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ "updated",
+ rewound_out=True,
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 2
+ assert entries[-1]["old_content"] == "updated"
+
+
+def test_delete_detection_does_not_duplicate_rewound_delete(temp_dir):
+ """rewound delete 已表示当前文件缺失,不能再追加旧内容的 delete。"""
+ file_path = str(Path(temp_dir) / "rewound-delete.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ "updated",
+ ),
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "delete",
+ "2026-01-01T00:01:00+00:00",
+ "updated",
+ None,
+ rewound_out=True,
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 2
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "updated"
+
+
+def test_delete_detection_skips_discarded_edit(temp_dir):
+ """discard 已恢复工作区,删除前内容必须取更早的有效版本。"""
+ file_path = str(Path(temp_dir) / "discarded-edit.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ "updated",
+ ),
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:01:00+00:00",
+ "updated",
+ "discarded",
+ discarded_out=True,
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 3
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "updated"
+
+
+def test_delete_detection_treats_discard_as_stronger_than_rewind(temp_dir):
+ """同一条 rewound+discarded 时,按 discard 处理。"""
+ file_path = str(Path(temp_dir) / "discarded-rewound.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ "updated",
+ ),
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:01:00+00:00",
+ "updated",
+ "discarded",
+ rewound_out=True,
+ discarded_out=True,
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "updated"
+
+
+def test_delete_detection_after_all_history_discarded_uses_restored_content(temp_dir):
+ """文件首次修改后被 discard 时,删除前内容是恢复后的 old_content。"""
+ file_path = str(Path(temp_dir) / "all-discarded.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ "updated",
+ discarded_out=True,
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 2
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "original"
+
+
+def test_delete_detection_after_discarded_delete_uses_restored_content(temp_dir):
+ """discard 一个 delete 会恢复 old_content,后续删除不能记录为已删除。"""
+ file_path = str(Path(temp_dir) / "discarded-delete.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "delete",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ None,
+ discarded_out=True,
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 2
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "original"
+
+
+def test_delete_detection_after_discarded_create_does_not_record(temp_dir):
+ """discard agent 新建文件后文件本应不存在,无需追加 delete。"""
+ file_path = str(Path(temp_dir) / "discarded-create.txt")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ None,
+ "created",
+ discarded_out=True,
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 1
+
+
+def test_history_recording_is_disabled_in_sandbox_mode():
+ """沙箱文件不在本地文件系统可见,删除探测必须整体关闭,避免虚假 delete。"""
+ tool = FlashBashTool.__new__(FlashBashTool)
+ tool._operation = SimpleNamespace(mode=OperationMode.SANDBOX)
+
+ assert tool._history_recording_enabled(_parsed_command()) is False
+
+
+def test_history_recording_remains_enabled_in_local_mode():
+ tool = FlashBashTool.__new__(FlashBashTool)
+ tool._operation = SimpleNamespace(mode=OperationMode.LOCAL)
+
+ assert tool._history_recording_enabled(_parsed_command()) is True
+
+
+def test_delete_detection_keeps_existing_file_untouched(temp_dir):
+ file_path = str(Path(temp_dir) / "exists.txt")
+ Path(file_path).write_text("still here\n", encoding="utf-8")
+ flash_path = (
+ Path(temp_dir) / ".agent_history" / "file_ops_flash_agent_session.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "",
+ "still here\n",
+ ),
+ )
+
+ record_detected_deletions(None, str(flash_path))
+
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 1
+ assert entries[0]["action"] == "edit"
+
+
+async def test_flash_bash_post_detection_uses_flash_ledger(temp_dir, monkeypatch):
+ """完整 FlashBashTool 链路:stock hook 关闭,post-detect 读双账本。"""
+ file_path = str(Path(temp_dir) / "post-detect.txt")
+ Path(file_path).write_text("updated\n", encoding="utf-8")
+ flash_path = (
+ Path(temp_dir)
+ / ".agent_history"
+ / "file_ops_flash_flash-bash-agent_sess-flash-bash.jsonl"
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_path),
+ file_path,
+ _entry(
+ "edit",
+ "2026-01-01T00:00:00+00:00",
+ "original",
+ "updated",
+ ),
+ )
+
+ session = _FakeSession()
+ monkeypatch.setattr(flash_bash_tool, "get_current_session", lambda: session)
+ monkeypatch.setattr(flash_file_history, "get_workspace", lambda: str(temp_dir))
+ monkeypatch.setattr(agent_cwd, "get_workspace", lambda: str(temp_dir))
+
+ async def fake_stock_invoke(self, inputs, **kwargs):
+ # stock 单账本 hook 必须被 FlashBashTool 关闭,避免把旧内容写进 JSON。
+ assert self._build_history_path(session) is None
+ Path(file_path).unlink()
+ return ToolOutput(success=True, data={"content": "deleted"})
+
+ monkeypatch.setattr(BashTool, "invoke", fake_stock_invoke)
+ tool = FlashBashTool(MagicMock(), language="en", agent_id="flash-bash-agent")
+
+ result = await tool.invoke({"command": f"Remove-Item -LiteralPath {file_path}"})
+
+ assert result.success is True
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 2
+ assert entries[-1]["action"] == "delete"
+ assert entries[-1]["old_content"] == "updated"
+
+
+async def test_flash_bash_explicit_rm_records_current_content(temp_dir, monkeypatch):
+ """显式 rm 在执行前读取当前全文,未入账文件也能恢复。"""
+ file_path = str(Path(temp_dir) / "explicit-rm.txt")
+ Path(file_path).write_text("current before rm\n", encoding="utf-8")
+ flash_path = (
+ Path(temp_dir)
+ / ".agent_history"
+ / "file_ops_flash_flash-bash-agent_sess-flash-bash.jsonl"
+ )
+
+ session = _FakeSession()
+ monkeypatch.setattr(flash_bash_tool, "get_current_session", lambda: session)
+ monkeypatch.setattr(flash_file_history, "get_workspace", lambda: str(temp_dir))
+ monkeypatch.setattr(agent_cwd, "get_workspace", lambda: str(temp_dir))
+
+ async def fake_stock_invoke(self, inputs, **kwargs):
+ Path(file_path).unlink()
+ return ToolOutput(success=True, data={"content": "deleted"})
+
+ monkeypatch.setattr(BashTool, "invoke", fake_stock_invoke)
+ operation = _FakeOperation("current before rm\n")
+ tool = FlashBashTool(operation, language="en", agent_id="flash-bash-agent")
+
+ command_path = file_path.replace("\\", "/")
+ result = await tool.invoke({"command": f"rm {command_path}"})
+
+ assert result.success is True
+ entries = flash_file_history.load_flash_history(flash_path)[file_path]
+ assert len(entries) == 1
+ assert entries[0]["action"] == "delete"
+ assert entries[0]["old_content"] == "current before rm\n"
diff --git a/tests/unit_tests/agentserver/test_flash_edit_tool.py b/tests/unit_tests/agentserver/test_flash_edit_tool.py
new file mode 100644
index 0000000000..0a6fdf5041
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_flash_edit_tool.py
@@ -0,0 +1,679 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""FlashEditFileTool 单测:缓存命中零读盘 / 回退路径 / hunks 原子性 / JSONL history。
+
+覆盖验收项(见 flash-editfile-io-analysis-and-optimization.md §7):
+- flash read → flash edit 同文件链路(缓存命中时工具层零 fs 读);
+- 无侧车(stock read)/ 外部修改 / 沙箱约束下的回退与拒绝语义;
+- hunks 全命中才写回、重叠拒绝;
+- history 纯追加(schema 与 stock 对齐,可被 diff_service 合并读取)。
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import tempfile
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.sys_operation import (
+ LocalWorkConfig,
+ OperationMode,
+ SysOperationCard,
+)
+from openjiuwen.harness.tools.filesystem import (
+ ReadFileTool,
+ _FILE_READ_REGISTRY,
+)
+
+from jiuwenswarm.agents.harness.flash.tools import flash_file_history
+from jiuwenswarm.agents.harness.flash.tools import flash_edit_tool
+from jiuwenswarm.agents.harness.flash.tools.flash_edit_tool import FlashEditFileTool
+from jiuwenswarm.agents.harness.flash.tools.flash_file_meta import clear_file_meta_cache
+from jiuwenswarm.agents.harness.flash.tools.flash_read_tool import FlashReadFileTool
+
+
+class _CountingFsProxy:
+ """对真实 fs 操作计数(read_file / write_file),其余透传。"""
+
+ def __init__(self, real_fs):
+ self._real = real_fs
+ self.read_calls = 0
+ self.write_calls = 0
+
+ async def read_file(self, *args, **kwargs):
+ self.read_calls += 1
+ return await self._real.read_file(*args, **kwargs)
+
+ async def write_file(self, *args, **kwargs):
+ self.write_calls += 1
+ return await self._real.write_file(*args, **kwargs)
+
+ def __getattr__(self, name):
+ return getattr(self._real, name)
+
+
+class _CountingOpProxy:
+ """包一层 SysOperation:fs() 返回计数代理,其余属性透传。"""
+
+ def __init__(self, real_op):
+ self._real = real_op
+ self.mode = real_op.mode
+ self.fs_proxy = _CountingFsProxy(real_op.fs())
+
+ def fs(self):
+ return self.fs_proxy
+
+ def __getattr__(self, name):
+ return getattr(self._real, name)
+
+
+class _FakeSession:
+ def __init__(self, session_id="sess-flash-edit", agent_id="flash-edit-agent"):
+ self._session_id = session_id
+ self._agent_id = agent_id
+
+ def get_session_id(self):
+ return self._session_id
+
+ def agent_id(self):
+ return self._agent_id
+
+
[email protected](autouse=True)
+def _isolate_registries():
+ _FILE_READ_REGISTRY.clear()
+ clear_file_meta_cache()
+ yield
+ _FILE_READ_REGISTRY.clear()
+ clear_file_meta_cache()
+
+
+@pytest_asyncio.fixture(name="sys_op")
+async def sys_op_fixture():
+ await Runner.start()
+ card_id = "test_flash_edit_tool_op"
+ card = SysOperationCard(
+ id=card_id,
+ mode=OperationMode.LOCAL,
+ work_config=LocalWorkConfig(shell_allowlist=["echo"]),
+ )
+ Runner.resource_mgr.add_sys_operation(card)
+ op = Runner.resource_mgr.get_sys_operation(card_id)
+ yield op
+ Runner.resource_mgr.remove_sys_operation(sys_operation_id=card_id)
+ await Runner.stop()
+
+
+def temp_dir():
+ dir_path = tempfile.mkdtemp()
+ yield dir_path
+ shutil.rmtree(dir_path, ignore_errors=True)
+
+
+def _make_tools(sys_op):
+ proxy = _CountingOpProxy(sys_op)
+ read_tool = FlashReadFileTool(proxy)
+ edit_tool = FlashEditFileTool(proxy)
+ return read_tool, edit_tool, proxy
+
+
+async def test_tool_card_keeps_stock_edit_file_contract(sys_op):
+ """flash 实现必须保持 stock 工具名,避免安全/禁用/前端按名断链。"""
+ _, edit_tool, _ = _make_tools(sys_op)
+
+ assert edit_tool.card.name == "edit_file"
+ assert edit_tool.card.id.startswith("EditFileTool_")
+
+
+async def test_gate_requires_prior_read(sys_op, temp_dir):
+ _, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "gate.txt")
+ Path(file_path).write_text("hello\n", encoding="utf-8")
+
+ result = await edit_tool.invoke({"file_path": file_path, "old_string": "hello", "new_string": "world"})
+
+ assert result.success is False
+ assert "must be read before editing" in result.error
+
+
+async def test_read_then_edit_single(sys_op, temp_dir):
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "single.txt")
+ Path(file_path).write_text("alpha\nbeta\ngamma\n", encoding="utf-8")
+
+ read_res = await read_tool.invoke({"file_path": file_path})
+ assert read_res.success is True
+
+ edit_res = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "beta",
+ "new_string": "BETA",
+ })
+ assert edit_res.success is True, edit_res.error
+ assert edit_res.data["replacements"] == 1
+ assert Path(file_path).read_text(encoding="utf-8") == "alpha\nBETA\ngamma\n"
+
+
+async def test_cache_hit_zero_fs_reads(sys_op, temp_dir):
+ """核心验收:flash read 之后连续两次 edit,工具层零 fs 读(缓存命中)。"""
+ read_tool, edit_tool, proxy = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "cache.txt")
+ Path(file_path).write_text("one\ntwo\nthree\nfour\n", encoding="utf-8")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ reads_after_read = proxy.fs_proxy.read_calls
+ assert reads_after_read >= 1 # 注册快照的 bytes 读
+
+ first = await edit_tool.invoke({"file_path": file_path, "old_string": "two", "new_string": "TWO"})
+ assert first.success is True, first.error
+ assert proxy.fs_proxy.read_calls == reads_after_read, "第一次 edit 不应触发工具层读"
+ assert proxy.fs_proxy.write_calls == 1
+
+ # 写后回填(registry + 侧车)应让第二次 edit 继续命中缓存。
+ second = await edit_tool.invoke({"file_path": file_path, "old_string": "four", "new_string": "FOUR"})
+ assert second.success is True, second.error
+ assert proxy.fs_proxy.read_calls == reads_after_read, "第二次 edit 仍不应触发工具层读"
+ assert proxy.fs_proxy.write_calls == 2
+
+ assert Path(file_path).read_text(encoding="utf-8") == "one\nTWO\nthree\nFOUR\n"
+
+
+async def test_fresh_read_fallback_without_sidecar(sys_op, temp_dir):
+ """stock read_file 只填 registry 不填侧车 → edit 应回退一次全量读并成功。"""
+ proxy = _CountingOpProxy(sys_op)
+ stock_read = ReadFileTool(proxy)
+ edit_tool = FlashEditFileTool(proxy)
+ file_path = os.path.join(temp_dir, "fallback.txt")
+ Path(file_path).write_text("aaa\nbbb\n", encoding="utf-8")
+
+ assert (await stock_read.invoke({"file_path": file_path})).success is True
+ reads_after_read = proxy.fs_proxy.read_calls
+
+ result = await edit_tool.invoke({"file_path": file_path, "old_string": "bbb", "new_string": "BBB"})
+
+ assert result.success is True, result.error
+ assert proxy.fs_proxy.read_calls == reads_after_read + 1, "无侧车时应恰好一次全量读"
+ assert Path(file_path).read_text(encoding="utf-8") == "aaa\nBBB\n"
+
+
+async def test_external_modification_rejected(sys_op, temp_dir):
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "external.txt")
+ Path(file_path).write_text("original\n", encoding="utf-8")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ # 外部改写:内容与长度都变(mtime+size 双失配)。
+ Path(file_path).write_text("tampered-with-longer-content\n", encoding="utf-8")
+
+ result = await edit_tool.invoke({"file_path": file_path, "old_string": "original", "new_string": "x"})
+
+ assert result.success is False
+ assert "modified externally" in result.error
+ # registry 被作废:不重读就再编辑必须再次撞准入门槛。
+ retry = await edit_tool.invoke({"file_path": file_path, "old_string": "tampered", "new_string": "y"})
+ assert retry.success is False
+ assert "must be read before editing" in retry.error
+
+
+async def test_hunks_all_or_nothing(sys_op, temp_dir):
+ read_tool, edit_tool, proxy = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "hunks.txt")
+ original = "aaa\nbbb\nccc\n"
+ Path(file_path).write_text(original, encoding="utf-8")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ bad = await edit_tool.invoke({
+ "file_path": file_path,
+ "hunks": [
+ {"old_string": "aaa", "new_string": "XXX"},
+ {"old_string": "nope", "new_string": "YYY"},
+ ],
+ })
+ assert bad.success is False
+ assert "hunks[1]" in bad.error
+ assert Path(file_path).read_text(encoding="utf-8") == original, "任一 hunk 失败文件必须保持不变"
+ assert proxy.fs_proxy.write_calls == 0
+
+ good = await edit_tool.invoke({
+ "file_path": file_path,
+ "hunks": [
+ {"old_string": "aaa", "new_string": "XXX"},
+ {"old_string": "ccc", "new_string": "ZZZ"},
+ {"old_string": "bbb", "new_string": "YYY"},
+ ],
+ })
+ assert good.success is True, good.error
+ assert good.data["replacements"] == 3
+ assert proxy.fs_proxy.write_calls == 1, "全部命中共一次写回"
+ assert Path(file_path).read_text(encoding="utf-8") == "XXX\nYYY\nZZZ\n"
+
+
+async def test_hunks_overlap_rejected(sys_op, temp_dir):
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "overlap.txt")
+ Path(file_path).write_text("abcdef\n", encoding="utf-8")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "hunks": [
+ {"old_string": "abc", "new_string": "X"},
+ {"old_string": "bcd", "new_string": "Y"},
+ ],
+ })
+
+ assert result.success is False
+ assert "Overlapping" in result.error
+ assert Path(file_path).read_text(encoding="utf-8") == "abcdef\n"
+
+
+async def test_replace_all_within_hunk(sys_op, temp_dir):
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "replace_all.txt")
+ Path(file_path).write_text("x\nx\nx\ny\n", encoding="utf-8")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "hunks": [{"old_string": "x", "new_string": "z", "replace_all": True}],
+ })
+
+ assert result.success is True, result.error
+ assert result.data["replacements"] == 3
+ assert Path(file_path).read_text(encoding="utf-8") == "z\nz\nz\ny\n"
+
+
+async def test_replace_all_many_matches_uses_one_pass_join(sys_op, temp_dir):
+ """大量匹配不能退化为“匹配次数 × 文件长度”的反复整文复制。"""
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "replace-all-many.txt")
+ matches = 65_536
+ Path(file_path).write_bytes(b"x" * matches)
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "x",
+ "new_string": "y",
+ "replace_all": True,
+ })
+
+ assert result.success is True, result.error
+ assert result.data["replacements"] == matches
+ assert Path(file_path).read_bytes() == b"y" * matches
+
+
+async def test_crlf_eol_preserved(sys_op, temp_dir):
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "crlf.txt")
+ Path(file_path).write_bytes("first\r\nsecond\r\n".encode("utf-8"))
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "second",
+ "new_string": "SECOND",
+ })
+
+ assert result.success is True, result.error
+ assert Path(file_path).read_bytes() == b"first\r\nSECOND\r\n", "CRLF 必须按原样保留"
+
+
+async def test_replace_all_many_crlf_matches_is_linear(sys_op, temp_dir):
+ """统一 CRLF 的大量替换也不能在每个匹配上重复扫描全文。"""
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "replace-all-crlf.txt")
+ matches = 20_000
+ Path(file_path).write_bytes(b"x\r\n" * matches)
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "x",
+ "new_string": "y",
+ "replace_all": True,
+ })
+
+ assert result.success is True, result.error
+ assert result.data["replacements"] == matches
+ assert Path(file_path).read_bytes() == b"y\r\n" * matches
+
+
+async def test_lf_edit_after_last_newline_maps_offsets(sys_op, temp_dir):
+ """LF 文件末换行之后仍有内容时,offset 兜底分支不能越界。"""
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "lf-after-last-newline.txt")
+ Path(file_path).write_bytes(b"first\nsecond")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "second",
+ "new_string": "SECOND",
+ })
+
+ assert result.success is True, result.error
+ assert Path(file_path).read_bytes() == b"first\nSECOND"
+
+
+async def test_crlf_edit_after_last_newline_maps_offsets(sys_op, temp_dir):
+ """CRLF 文件末换行之后的编辑终点需要补偿全部 CRLF 长度。"""
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "crlf-after-last-newline.txt")
+ Path(file_path).write_bytes(b"first\r\nsecond")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "second",
+ "new_string": "SECOND",
+ })
+
+ assert result.success is True, result.error
+ assert Path(file_path).read_bytes() == b"first\r\nSECOND"
+
+
+async def test_mixed_eol_edit_after_last_newline_maps_offsets(sys_op, temp_dir):
+ """混合 EOL 且末换行之后有内容时,补偿必须使用累计 CRLF 数。"""
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "mixed-after-last-newline.txt")
+ Path(file_path).write_bytes(b"first\r\nsecond\nthird")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "third",
+ "new_string": "THIRD",
+ })
+
+ assert result.success is True, result.error
+ assert Path(file_path).read_bytes() == b"first\r\nsecond\nTHIRD"
+
+
+async def test_mixed_eol_preserved_and_cache_falls_back_to_fresh_read(sys_op, temp_dir):
+ """混合 LF/CRLF 不能用“LF 快照 + 单一 EOL”重建,必须回退原始全量读。"""
+ read_tool, edit_tool, proxy = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "mixed-eol.txt")
+ Path(file_path).write_bytes(b"first\r\nsecond\nthird\r\n")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+ reads_after_read = proxy.fs_proxy.read_calls
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "second",
+ "new_string": "SECOND",
+ })
+
+ assert result.success is True, result.error
+ assert proxy.fs_proxy.read_calls == reads_after_read + 1, "混合 EOL 必须回退一次原始读"
+ assert Path(file_path).read_bytes() == b"first\r\nSECOND\nthird\r\n", "未编辑区域的换行必须逐字节保留"
+
+
+async def test_mixed_eol_history_keeps_exact_content(sys_op, temp_dir, monkeypatch):
+ """history 必须保存混合换行原文,否则 /rewind 会恢复错误版本。"""
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.harness.flash.tools.flash_edit_tool.get_current_session",
+ lambda: _FakeSession(),
+ )
+ monkeypatch.setattr(flash_file_history, "get_workspace", lambda: str(temp_dir))
+
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "mixed-eol-history.txt")
+ Path(file_path).write_bytes(b"first\r\nsecond\nthird\r\n")
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "second",
+ "new_string": "SECOND",
+ })
+ assert result.success is True, result.error
+
+ history_path = Path(temp_dir) / ".agent_history" / "file_ops_flash_flash-edit-agent_sess-flash-edit.jsonl"
+ entries = flash_file_history.load_flash_history(history_path)[file_path]
+ assert len(entries) == 1
+ assert entries[0]["old_content"] == "first\r\nsecond\nthird\r\n"
+ assert entries[0]["new_content"] == "first\r\nSECOND\nthird\r\n"
+
+
+async def test_mixed_eol_replacement_uses_local_newline_style(sys_op, temp_dir):
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "mixed-eol-newline.txt")
+ Path(file_path).write_bytes(b"first\r\nsecond\nthird\r\n")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "second\nthird",
+ "new_string": "SECOND\nTHIRD",
+ })
+
+ assert result.success is True, result.error
+ assert Path(file_path).read_bytes() == b"first\r\nSECOND\nTHIRD\r\n"
+
+
+async def test_mixed_eol_newline_without_span_newline_uses_next_style(sys_op, temp_dir):
+ """替换片段自身无换行时,新增换行沿用后续原换行风格。"""
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "mixed-eol-following-style.txt")
+ Path(file_path).write_bytes(b"first\r\nsecond\nthird\r\n")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "second",
+ "new_string": "SECOND\nTAIL",
+ })
+
+ assert result.success is True, result.error
+ assert Path(file_path).read_bytes() == b"first\r\nSECOND\nTAIL\nthird\r\n"
+
+
+async def test_file_without_newline_defaults_to_lf(sys_op, temp_dir):
+ """无换行文件插入新行时默认 LF,不依赖平台换行。"""
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "without-newline.txt")
+ Path(file_path).write_bytes(b"alpha")
+
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "alpha",
+ "new_string": "one\ntwo",
+ })
+
+ assert result.success is True, result.error
+ assert Path(file_path).read_bytes() == b"one\ntwo"
+
+
+async def test_empty_old_string_after_sanitization_is_rejected(
+ sys_op, temp_dir, monkeypatch
+):
+ """清洗后 old_string 为空必须直接报错,不能进入匹配循环。"""
+ monkeypatch.setattr(FlashEditFileTool, "_desanitize", lambda self, value: "")
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "empty-after-sanitize.txt")
+ Path(file_path).write_text("hello\n", encoding="utf-8")
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "hello",
+ "new_string": "world",
+ })
+
+ assert result.success is False
+ assert result.error == "old_string is empty after sanitization."
+
+
+async def test_create_new_file(sys_op, temp_dir):
+ _, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "created", "new.txt")
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "",
+ "new_string": "brand new\ncontent\n",
+ })
+
+ assert result.success is True, result.error
+ assert result.data["created"] is True
+ assert Path(file_path).read_text(encoding="utf-8") == "brand new\ncontent\n"
+
+ # 创建即注册读状态:紧接着的编辑不应再要求 read_file。
+ follow = await edit_tool.invoke({"file_path": file_path, "old_string": "brand", "new_string": "BRAND"})
+ assert follow.success is True, follow.error
+
+
+async def test_office_create_registers_readback_content(sys_op, temp_dir, monkeypatch):
+ """Office 创建后 registry 必须登记抽取器看到的实际文本。"""
+ async def fake_write(file_path: str, content: str) -> None:
+ Path(file_path).write_text(content, encoding="utf-8")
+
+ async def fake_read(file_path: str) -> str:
+ # 模拟 DOCX 写入器/抽取器把单个换行展开为空行的行为。
+ return Path(file_path).read_text(encoding="utf-8").replace("\n", "\n\n")
+
+ monkeypatch.setattr(flash_edit_tool, "_write_office_document_async", fake_write)
+ monkeypatch.setattr(flash_edit_tool, "_read_office_plain_text_async", fake_read)
+ _, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "created.docx")
+
+ result = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "",
+ "new_string": "alpha\nbeta\n",
+ })
+
+ assert result.success is True, result.error
+ assert _FILE_READ_REGISTRY[file_path].content == "alpha\n\nbeta\n\n"
+
+
+async def test_office_edit_registers_readback_and_survives_mtime_only_change(
+ sys_op, temp_dir, monkeypatch
+):
+ """Office 编辑后读回注册;仅 mtime 变化且内容一致时不能误报外部修改。"""
+ async def fake_write(file_path: str, content: str) -> None:
+ Path(file_path).write_text(content, encoding="utf-8")
+
+ async def fake_read(file_path: str) -> str:
+ return Path(file_path).read_text(encoding="utf-8").replace("\n", "\n\n")
+
+ monkeypatch.setattr(flash_edit_tool, "_write_office_document_async", fake_write)
+ monkeypatch.setattr(flash_edit_tool, "_read_office_plain_text_async", fake_read)
+ _, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "edit.docx")
+
+ assert (
+ await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "",
+ "new_string": "alpha\nbeta\n",
+ })
+ ).success is True
+
+ edited = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "beta",
+ "new_string": "BETA",
+ })
+ assert edited.success is True, edited.error
+ assert _FILE_READ_REGISTRY[file_path].content == "alpha\n\n\n\nBETA\n\n\n\n"
+
+ stat_before = os.stat(file_path)
+ os.utime(
+ file_path,
+ ns=(stat_before.st_atime_ns, stat_before.st_mtime_ns + 1),
+ )
+ retry = await edit_tool.invoke({
+ "file_path": file_path,
+ "old_string": "BETA",
+ "new_string": "GAMMA",
+ })
+ assert retry.success is True, retry.error
+
+
+async def test_history_jsonl_appended_purely(sys_op, temp_dir, monkeypatch):
+ """history 纯追加:多次编辑逐行追加,不重写旧行;schema 与 stock 对齐。"""
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.harness.flash.tools.flash_edit_tool.get_current_session",
+ lambda: _FakeSession(),
+ )
+ monkeypatch.setattr(flash_file_history, "get_workspace", lambda: str(temp_dir))
+
+ read_tool, edit_tool, _ = _make_tools(sys_op)
+ file_path = os.path.join(temp_dir, "hist.txt")
+ # write_bytes 固定 LF:Windows 下 write_text 会把 \n 翻译成 \r\n,
+ # 这里要断言的是与写入字节完全一致的 history 条目。
+ Path(file_path).write_bytes(b"v1\n")
+ assert (await read_tool.invoke({"file_path": file_path})).success is True
+
+ assert (await edit_tool.invoke({"file_path": file_path, "old_string": "v1", "new_string": "v2"})).success
+ assert (await edit_tool.invoke({"file_path": file_path, "old_string": "v2", "new_string": "v3"})).success
+
+ history_path = Path(temp_dir) / ".agent_history" / "file_ops_flash_flash-edit-agent_sess-flash-edit.jsonl"
+ assert history_path.is_file()
+
+ data = flash_file_history.load_flash_history(history_path)
+ entries = data[file_path]
+ assert len(entries) == 2
+
+ first, second = entries
+ assert first["action"] == "edit"
+ assert first["old_content"] == "v1\n"
+ assert first["new_content"] == "v2\n"
+ assert first["timestamp"]
+ assert second["old_content"] == "v2\n"
+ assert second["new_content"] == "v3\n"
+
+ # 纯追加验证:第三条编辑后前两行字节级不变。
+ with open(history_path, "r", encoding="utf-8") as f:
+ lines_before = f.readlines()
+ assert (await edit_tool.invoke({"file_path": file_path, "old_string": "v3", "new_string": "v4"})).success
+ with open(history_path, "r", encoding="utf-8") as f:
+ lines_after = f.readlines()
+ assert lines_after[:2] == lines_before
+ assert len(lines_after) == 3
+ assert json.loads(lines_after[2])["new_content"] == "v4\n"
+
+
+async def test_multi_file_read_registers_state_for_edit(sys_op, temp_dir):
+ """flash 多文件并行读也走 bytes 快照覆写 → registry+侧车就绪 → edit 缓存命中。"""
+ read_tool, edit_tool, proxy = _make_tools(sys_op)
+ file_a = os.path.join(temp_dir, "a.txt")
+ file_b = os.path.join(temp_dir, "b.txt")
+ Path(file_a).write_text("aaa\n", encoding="utf-8")
+ Path(file_b).write_text("bbb\n", encoding="utf-8")
+
+ multi = await read_tool.invoke({"file_paths": [file_a, file_b]})
+ assert multi.success is True
+ assert multi.data["succeeded"] == 2
+
+ reads_after_read = proxy.fs_proxy.read_calls
+ for path, old, new in ((file_a, "aaa", "AAA"), (file_b, "bbb", "BBB")):
+ result = await edit_tool.invoke({"file_path": path, "old_string": old, "new_string": new})
+ assert result.success is True, result.error
+
+ assert proxy.fs_proxy.read_calls == reads_after_read, "多文件读注册后编辑同样零读盘"
diff --git a/tests/unit_tests/server/test_cleanup_flash_jsonl.py b/tests/unit_tests/server/test_cleanup_flash_jsonl.py
new file mode 100644
index 0000000000..549c2dd7f3
--- /dev/null
+++ b/tests/unit_tests/server/test_cleanup_flash_jsonl.py
@@ -0,0 +1,71 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""cleanup_orphan_file_ops 对 flash JSONL 账本的覆盖(深查补测)。
+
+回归背景:flash 账本文件名是 ``file_ops_flash_{AGENT_ID}_{session}.jsonl``,
+比 stock 多一段 ``flash_``。此前只把扩展名检查放宽到 ``.jsonl``,前缀
+检查仍是 ``file_ops_{AGENT_ID}_``——flash 孤儿账本永远不匹配,清理静默
+失效(会话删除后 .jsonl 无限堆积)。
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.common import cleanup as cleanup_module
+from jiuwenswarm.common.cleanup import cleanup_orphan_file_ops
+
+
+def orphan_env(tmp_path, monkeypatch):
+ """搭一个带存活会话与孤儿账本的假环境,返回 .agent_history 目录。"""
+ sessions_dir = tmp_path / "sessions"
+ (sessions_dir / "alive_sess").mkdir(parents=True)
+
+ agent_ws = tmp_path / "agent_ws"
+ user_ws = tmp_path / "user_ws"
+ hist_dir = agent_ws / ".agent_history"
+ hist_dir.mkdir(parents=True)
+
+ keep_stock = hist_dir / "file_ops_jiuwenswarm_alive_sess.json"
+ keep_stock.write_text("{}", encoding="utf-8")
+ keep_flash = hist_dir / "file_ops_flash_jiuwenswarm_alive_sess.jsonl"
+ keep_flash.write_text("{}\n", encoding="utf-8")
+ orphan_stock = hist_dir / "file_ops_jiuwenswarm_dead_sess.json"
+ orphan_stock.write_text("{}", encoding="utf-8")
+ orphan_flash = hist_dir / "file_ops_flash_jiuwenswarm_dead_sess.jsonl"
+ orphan_flash.write_text("{}\n", encoding="utf-8")
+
+ monkeypatch.setattr(cleanup_module, "get_agent_sessions_dir", lambda: sessions_dir)
+ monkeypatch.setattr(cleanup_module, "get_agent_workspace_dir", lambda: agent_ws)
+ monkeypatch.setattr(cleanup_module, "get_user_workspace_dir", lambda: user_ws)
+ return hist_dir
+
+
+def test_orphan_flash_jsonl_is_cleaned(orphan_env):
+ """核心回归:会话已删除的 flash .jsonl 必须被清掉(此前前缀不匹配漏清理)。"""
+ result = cleanup_orphan_file_ops()
+
+ assert result["removed"] >= 1
+ assert not (orphan_env / "file_ops_flash_jiuwenswarm_dead_sess.jsonl").exists()
+ assert not (orphan_env / "file_ops_jiuwenswarm_dead_sess.json").exists()
+
+
+def test_alive_session_files_are_kept(orphan_env):
+ cleanup_orphan_file_ops()
+
+ assert (orphan_env / "file_ops_jiuwenswarm_alive_sess.json").exists()
+ assert (orphan_env / "file_ops_flash_jiuwenswarm_alive_sess.jsonl").exists()
+
+
+def test_foreign_names_are_untouched(orphan_env):
+ """非本 agent 命名 / 非账本文件不得误删(flash 前缀放宽不能伤及无辜)。"""
+ foreign = orphan_env / "file_ops_flash_other_agent_dead.jsonl"
+ foreign.write_text("{}\n", encoding="utf-8")
+ unrelated = orphan_env / "notes.jsonl"
+ unrelated.write_text("x\n", encoding="utf-8")
+
+ cleanup_orphan_file_ops()
+
+ assert foreign.exists()
+ assert unrelated.exists()
diff --git a/tests/unit_tests/server/test_diff_service_flash_jsonl.py b/tests/unit_tests/server/test_diff_service_flash_jsonl.py
new file mode 100644
index 0000000000..2dcf37a23b
--- /dev/null
+++ b/tests/unit_tests/server/test_diff_service_flash_jsonl.py
@@ -0,0 +1,278 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""flash JSONL history 与 stock JSON 的消费面一致性(diff_service 合并适配)。
+
+验收项(见 flash-editfile-io-analysis-and-optimization.md §7):
+- flash 编辑条目正确参与轮次 diff / /rewind 还原(get_files_to_restore);
+- 软删除截断(truncate soft=True)对 JSONL 打 rewound_out 标记:显示层
+ 不可见、还原层仍可用;
+- restore / 硬删除对 JSONL 的行为与 stock JSON 完全一致。
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+
+import pytest
+
+from jiuwenswarm.agents.harness.flash.tools import flash_file_history
+from jiuwenswarm.server.utils.diff_service import DiffService, _entry_sort_ts
+
+TURN1_TS = 1_700_001_000.0
+EDIT1_TS = TURN1_TS + 10 # stock JSON 记录的编辑(demo.txt)
+EDIT2_TS = TURN1_TS + 20 # flash JSONL 记录的编辑(notes.txt)
+EDIT3_TS = TURN1_TS + 30 # flash JSONL 记录的编辑(demo.txt,与 stock 同文件)
+
+SESSION_ID = "sessflash01"
+
+
+def _iso(ts: float) -> str:
+ return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
+
+
+def _history() -> list[dict]:
+ return [
+ {"role": "user", "content": "改两个文件", "timestamp": TURN1_TS},
+ {"role": "assistant", "content": "done", "event_type": "chat.final",
+ "timestamp": TURN1_TS + 60},
+ ]
+
+
+def project(tmp_path, monkeypatch):
+ """项目目录同时携带 stock JSON 与 flash JSONL 两本账本。"""
+ demo = tmp_path / "demo.txt"
+ notes = tmp_path / "notes.txt"
+ demo.write_text("AFTER\n", encoding="utf-8")
+ notes.write_text("CHANGED\n", encoding="utf-8")
+
+ hist_dir = tmp_path / ".agent_history"
+ hist_dir.mkdir()
+
+ stock_ops = hist_dir / f"file_ops_jiuwenswarm_tui_{SESSION_ID}.json"
+ stock_ops.write_text(json.dumps({
+ str(demo): [{
+ "action": "edit", "timestamp": _iso(EDIT1_TS),
+ "old_content": "BEFORE\n", "new_content": "AFTER\n",
+ }],
+ }), encoding="utf-8")
+
+ flash_ops = hist_dir / f"file_ops_flash_jiuwenswarm_tui_{SESSION_ID}.jsonl"
+ flash_file_history.append_flash_history_entry(
+ str(flash_ops), str(notes), {
+ "action": "edit", "timestamp": _iso(EDIT2_TS),
+ "old_content": "ORIGINAL\n", "new_content": "CHANGED\n",
+ },
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_ops), str(demo), {
+ "action": "edit", "timestamp": _iso(EDIT3_TS),
+ "old_content": "AFTER\n", "new_content": "AFTER-FLASH\n",
+ },
+ )
+
+ service = DiffService()
+ monkeypatch.setattr(DiffService, "_read_history", staticmethod(lambda _sid: _history()))
+ 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, demo, notes, stock_ops, flash_ops
+
+
+def test_jsonl_entries_merged_into_agent_history(project):
+ service, proj_dir, demo, notes, _stock_ops, flash_ops = project
+
+ history = service._read_agent_history(SESSION_ID, str(proj_dir))
+
+ assert str(notes) in history, "flash JSONL 条目必须被合并读取"
+ assert str(demo) in history
+ demo_entries = history[str(demo)]
+ assert len(demo_entries) == 2, "同文件的 stock+flash 条目应合并到同一列表"
+ assert {e["old_content"] for e in demo_entries} == {"BEFORE\n", "AFTER\n"}
+
+
+def test_naive_timestamps_are_interpreted_as_utc():
+ """diff 侧排序键必须与 flash_bash_history 的 naive→UTC 策略一致。"""
+ naive = _entry_sort_ts("2026-01-01T00:00:00")
+ aware = _entry_sort_ts("2026-01-01T00:00:00+00:00")
+
+ assert naive == aware
+ assert naive == datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp()
+
+
+def test_turn_diffs_include_flash_edits(project):
+ service, proj_dir, demo, notes, _stock_ops, _flash_ops = project
+
+ diffs = service.get_turn_diffs(SESSION_ID, project_dir=str(proj_dir))
+
+ assert len(diffs) == 1
+ files = diffs[0]["files"]
+ assert str(notes) in files, "flash 编辑必须出现在轮次 diff 中"
+ assert str(demo) in files
+
+
+def test_get_files_to_restore_sees_flash_entries(project):
+ """/rewind code:flash 条目的 old_content 是还原依据,不得漏。"""
+ service, proj_dir, demo, notes, _stock_ops, _flash_ops = project
+
+ to_restore = service.get_files_to_restore(SESSION_ID, 1, project_dir=str(proj_dir))
+
+ assert to_restore[str(demo)]["restore_content"] == "BEFORE\n"
+ assert to_restore[str(notes)]["restore_content"] == "ORIGINAL\n"
+
+
+def test_soft_truncate_marks_jsonl_entries(project):
+ service, proj_dir, demo, notes, _stock_ops, flash_ops = project
+
+ # 截断掉 turn 1 的全部编辑(soft:只对显示层隐藏,保留快照)。
+ service.truncate_file_ops_by_timestamp(
+ SESSION_ID, TURN1_TS, project_dir=str(proj_dir), soft=True,
+ )
+
+ # 显示层:条目被隐藏。
+ visible = service._read_agent_history(SESSION_ID, str(proj_dir))
+ assert visible == {} or not any(
+ not e.get("rewound_out") for entries in visible.values() for e in entries
+ )
+
+ # 还原层:仍能拿到 old_content。
+ to_restore = service.get_files_to_restore(SESSION_ID, 1, project_dir=str(proj_dir))
+ assert to_restore[str(notes)]["restore_content"] == "ORIGINAL\n"
+
+ # 落盘形态:JSONL 被原子重写为带标记的条目(不再是无标记原文)。
+ on_disk = flash_file_history.load_flash_history(flash_ops)
+ assert on_disk[str(notes)][0].get("rewound_out") is True
+
+
+def test_restore_rewound_jsonl_entries(project):
+ service, proj_dir, demo, notes, _stock_ops, flash_ops = project
+
+ service.truncate_file_ops_by_timestamp(
+ SESSION_ID, TURN1_TS, project_dir=str(proj_dir), soft=True,
+ )
+ service.restore_rewound_entries_by_timestamp(
+ SESSION_ID, TURN1_TS, project_dir=str(proj_dir),
+ )
+
+ visible = service._read_agent_history(SESSION_ID, str(proj_dir))
+ assert str(notes) in visible
+ assert not visible[str(notes)][0].get("rewound_out")
+ on_disk = flash_file_history.load_flash_history(flash_ops)
+ assert not on_disk[str(notes)][0].get("rewound_out")
+
+
+def test_hard_truncate_removes_jsonl_entries(project):
+ service, proj_dir, demo, notes, _stock_ops, flash_ops = project
+
+ service.truncate_file_ops_by_timestamp(
+ SESSION_ID, TURN1_TS, project_dir=str(proj_dir), soft=False,
+ )
+
+ visible = service._read_agent_history(SESSION_ID, str(proj_dir))
+ assert visible == {}
+ on_disk = flash_file_history.load_flash_history(flash_ops)
+ assert on_disk == {}
+
+
+def test_get_files_to_redo_sees_flash_entries(project):
+ """redo(discard 软删后的重做):flash 条目的 new_content 是重做依据。
+
+ 同文件多代快照时取"最后一条"被标记条目——合并后的时间戳稳定排序
+ 保证该语义跨账本成立(demo 的 stock 与 flash 条目分属两本账本)。
+ """
+ service, proj_dir, demo, notes, _stock_ops, flash_ops = project
+
+ service.truncate_file_ops_by_timestamp(
+ SESSION_ID, TURN1_TS, project_dir=str(proj_dir), soft=True, discarded=True,
+ )
+
+ to_redo = service.get_files_to_redo(SESSION_ID, 1, project_dir=str(proj_dir))
+
+ assert to_redo[str(notes)]["content"] == "CHANGED\n"
+ # demo: stock 条目(BEFORE→AFTER, EDIT1) + flash 条目(AFTER→AFTER-FLASH,
+ # EDIT3) 都被标记;重做应取时间戳最大的 flash 条目的 new_content。
+ assert to_redo[str(demo)]["content"] == "AFTER-FLASH\n"
+ on_disk = flash_file_history.load_flash_history(flash_ops)
+ assert on_disk[str(demo)][-1].get("discarded_out") is True
+
+
+def test_dirty_timestamps_sort_last_and_merge_survives(project):
+ """缺省 / 非法 timestamp 条目:排序稳定落尾,不阻断合并(评审意见 2)。
+
+ ``_entry_sort_ts`` 对无法解析的时间戳返回 inf(排最后);合法条目的
+ 时间序不受脏数据影响。truncate 对解析失败条目"保留"是存量容忍行为,
+ 本测试同时钉住。
+ """
+ service, proj_dir, demo, notes, _stock_ops, flash_ops = project
+
+ flash_file_history.append_flash_history_entry(
+ str(flash_ops), str(notes),
+ {"action": "edit", "old_content": "x", "new_content": "y"}, # 缺 timestamp
+ )
+ flash_file_history.append_flash_history_entry(
+ str(flash_ops), str(notes),
+ {
+ "action": "edit", "timestamp": "not-a-date",
+ "old_content": "x", "new_content": "y",
+ },
+ )
+
+ history = service._read_agent_history(SESSION_ID, str(proj_dir))
+
+ entries = history[str(notes)]
+ assert len(entries) == 3
+ assert entries[0]["timestamp"] == _iso(EDIT2_TS), "合法条目仍按时间序在前"
+ assert set(e.get("timestamp") for e in entries[1:]) == {None, "not-a-date"}
+ # demo 的合法跨账本条目不受 notes 的脏数据影响
+ assert [e["old_content"] for e in history[str(demo)]] == ["BEFORE\n", "AFTER\n"]
+
+
+def test_flash_module_missing_degrades_gracefully(project, monkeypatch):
+ """flash 包被裁剪(ImportError)时 load/save 优雅降级(评审意见 1)。
+
+ 读:.jsonl 按空账本跳过(stock 条目照常可见),ImportError 不得穿透
+ ``_read_agent_history`` 的窄 except 打断 diff 链;写:跳过重写不抛错。
+ """
+ import sys
+
+ service, proj_dir, demo, notes, stock_ops, flash_ops = project
+
+ monkeypatch.setitem(
+ sys.modules,
+ "jiuwenswarm.agents.harness.flash.tools.flash_file_history",
+ None,
+ )
+
+ history = service._read_agent_history(SESSION_ID, str(proj_dir))
+ assert str(demo) in history, "stock 账本条目必须仍然可见"
+ assert str(notes) not in history, "flash-only 条目降级为不可见(不抛错)"
+
+ # 截断 / 恢复路径同样不抛 ImportError,stock 账本照常处理
+ service.truncate_file_ops_by_timestamp(
+ SESSION_ID, TURN1_TS, project_dir=str(proj_dir), soft=False,
+ )
+ visible_after = service._read_agent_history(SESSION_ID, str(proj_dir))
+ assert visible_after == {}, "stock 账本条目(>= cutoff)应被正常截断"
+
+
+def test_is_valid_file_ops_file_jsonl_naming():
+ valid = DiffService._is_valid_file_ops_file
+
+ assert valid(f"file_ops_flash_jiuwenswarm_tui_{SESSION_ID}.jsonl", SESSION_ID)
+ assert valid(f"file_ops_flash_jiuwenswarm_tui_{SESSION_ID}.jsonl", SESSION_ID, require_session=True)
+ # 子 agent 会话的 JSONL 同样接受。
+ assert valid(f"file_ops_flash_demo_{SESSION_ID}_sub_gp_abc123.jsonl", SESSION_ID)
+ # 其它 session / 非约定前缀 / 未知扩展名一律拒绝;stock .json 命名继续有效。
+ assert not valid("file_ops_flash_jiuwenswarm_tui_other_session.jsonl", SESSION_ID)
+ assert not valid("notes_file_ops_flash_x.jsonl", SESSION_ID)
+ assert not valid("file_ops_flash_x.jsonl.bak", SESSION_ID)
+ assert valid(f"file_ops_jiuwenswarm_tui_{SESSION_ID}.json", SESSION_ID)
+ # 无 session_id 时:任何约定命名的 file_ops 都算(require_session=False)。
+ assert valid("file_ops_flash_jiuwenswarm_tui_sessflash01.jsonl", None)
+ assert not valid("file_ops_flash_jiuwenswarm_tui_sessflash01.jsonl", None, require_session=True)