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(rails): 基线 diff 产物检测——修复 bash 工具产物(截图/PPTX 等)未触发水印 hook 的问题

white202589073c224ab8
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index fc68bc6984..56af5c74ca 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -51,6 +51,7 @@ from jiuwenswarm.agents.harness.common.rails.read_file_validation import (
)
from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY,
+ extract_effective_project_dir,
)
from jiuwenswarm.common.tool_display import (
build_tool_display_name,
@@ -1263,9 +1264,9 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
set_effective_request_workspace_dir,
set_interactive_ask,
)
- _epd = _md.get("effective_project_dir")
- if isinstance(_epd, str) and _epd.strip():
- ws_token = set_effective_request_workspace_dir(_epd.strip())
+ _epd = extract_effective_project_dir(_md)
+ if _epd is not None:
+ ws_token = set_effective_request_workspace_dir(_epd)
ctx.extra[_SKILL_TURBO_WORKSPACE_TOKEN_EXTRA_KEY] = ws_token
_ia = _md.get("interactive_ask")
if _ia is not None:
diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
index 1b46ac1534..0ff81dd3a2 100644
--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
@@ -9,9 +9,11 @@ so downstream tool/artifact events can be attributed to the active task.
from __future__ import annotations
import asyncio
+import hashlib
import json
import os
import re
+import stat
import threading
import time
from contextvars import ContextVar
@@ -65,6 +67,11 @@ _ALWAYS_EXCLUDED_PATH_PATTERNS = [
# bash/powershell 大输出落盘目录(供模型查阅,非用户产物)
re.compile(r'[/\\][^/\\]*bash_outputs[/\\]', re.IGNORECASE),
re.compile(r'[/\\][^/\\]*powershell_outputs[/\\]', re.IGNORECASE),
+ # 临时/缓存文件(基线快照与正文提取共用排除)
+ re.compile(r'\.tmp$', re.IGNORECASE),
+ re.compile(r'~\$\w', re.IGNORECASE), # Office 临时锁文件 ~$xxx.pptx
+ re.compile(r'\.swp$', re.IGNORECASE),
+ re.compile(r'\.DS_Store$', re.IGNORECASE),
]
@@ -173,9 +180,34 @@ _ARTIFACT_PATH_PATTERNS = [
# 产物路径正则扫描的文本长度上限:超过直接跳过 findall,避免超大正文
# (如 evaluate_script ~800K HTML)爆炸匹配 + 逐条 stat() 阻塞事件循环。
-# 64K 覆盖正常 code/bash stdout 的产物路径声明。
+# 64K 覆盖正常 bash stdout 的产物路径声明。
_ARTIFACT_SCAN_MAX_TEXT_BYTES = 64 * 1024
+# ---------------------------------------------------------------------------
+# 基线 diff 产物检测参数(bash 类工具:工具执行前建工作区快照,
+# 执行后增量 diff 出新增/变更文件作为候选产物,不依赖工具输出文本)
+# ---------------------------------------------------------------------------
+# 快照文件数上限:超限放弃基线 diff,降级文本提取
+MAX_SCAN_FILES = 2000
+# 单文件 sha256 上限:超限跳过哈希,信任 mtime/size 判定
+MAX_HASH_BYTES = 100 * 1024 * 1024
+# 静默期 finalize:等待文件大小稳定(防后台进程 / tmp->rename 竞态)
+STABLE_INTERVAL_S = 0.5
+# finalize 静默期总窗口(秒):所有候选共享一个窗口批量轮询,
+# 不随候选数线性放大(逐文件串行等待会超出外层 ARTIFACT_DETECT_TIMEOUT_S,
+# 导致整体超时后基线不更新、变化累积、下一轮继续超时的循环)
+FINALIZE_TIMEOUT_S = 1.0
+# diff 阶段 sha256 累计预算(秒):耗尽后放弃 hash 保守判变更,
+# 无死循环(该文件下次 diff mtime/size 未变即跳过)
+_HASH_BUDGET_S = 0.3
+# before_tool_call 懒建基线快照超时(秒):超时后本会话禁用基线路径
+# (公开常量:供 SkillTurboArtifactRail 跨模块复用)
+BASELINE_SNAPSHOT_TIMEOUT_S = 2.0
+
+# 工作区快照:normcase 相对路径 -> (绝对路径, mtime_ns, size, sha256|None)
+# sha256 懒计算,仅 diff 发现 mtime/size 变化时才读取文件计算
+WorkspaceSnapshot = dict[str, tuple[str, int, int, str | None]]
+
def _clean_path_candidate(path_str: str) -> str:
"""清理正则提取到的路径候选首尾非法字符。"""
@@ -438,13 +470,13 @@ def _artifact_identity(path: str) -> tuple[str, int, int] | None:
stat 失败(文件不存在等)返回 None。
"""
try:
- stat = Path(path).stat()
+ st = Path(path).stat()
except OSError:
return None
return (
os.path.normcase(os.path.abspath(path)),
- stat.st_mtime_ns,
- stat.st_size,
+ st.st_mtime_ns,
+ st.st_size,
)
@@ -484,7 +516,7 @@ def _validate_artifact_candidates(
if _is_excluded_path(path):
continue
try:
- stat = file_path.stat()
+ st = file_path.stat()
except OSError:
continue
if (
@@ -494,7 +526,7 @@ def _validate_artifact_candidates(
continue
if (
tool_start_time is not None
- and stat.st_mtime < tool_start_time - _MTIME_TOLERANCE_S
+ and st.st_mtime < tool_start_time - _MTIME_TOLERANCE_S
):
continue
identity = os.path.normcase(os.path.abspath(path))
@@ -505,6 +537,228 @@ def _validate_artifact_candidates(
return paths
+def _file_sha256(path: str) -> str | None:
+ """计算文件 sha256(超 MAX_HASH_BYTES 或读取失败返回 None)。"""
+ try:
+ if os.path.getsize(path) > MAX_HASH_BYTES:
+ return None
+ digest = hashlib.sha256()
+ with open(path, "rb") as fh:
+ while True:
+ chunk = fh.read(1024 * 1024)
+ if not chunk:
+ break
+ digest.update(chunk)
+ return digest.hexdigest()
+ except OSError:
+ return None
+
+
+def _snapshot_workspace(
+ workspace_base: Path,
+ cancel_event: threading.Event | None = None,
+) -> WorkspaceSnapshot | None:
+ """递归快照工作区文件:rel_key -> (abs, mtime_ns, size, sha256)。
+
+ sha256 懒计算(快照阶段为 None);黑名单目录剪枝不进入;
+ 文件数超 MAX_SCAN_FILES 或扫描异常返回 None(降级文本提取)。
+ """
+ snapshot: WorkspaceSnapshot = {}
+ try:
+ for root, dirs, files in os.walk(workspace_base, followlinks=False):
+ if cancel_event is not None and cancel_event.is_set():
+ return None
+ # 目录剪枝:黑名单目录(node_modules 等)不进入(补尾部斜杠以匹配模式)
+ dirs[:] = [
+ d for d in dirs
+ if not _is_excluded_path(os.path.join(root, d) + os.sep)
+ ]
+ for name in files:
+ abs_path = os.path.join(root, name)
+ if _is_excluded_path(abs_path):
+ continue
+ try:
+ st = os.stat(abs_path)
+ except OSError:
+ continue
+ # os.walk 的 files 已排除目录;stat 成功后复用 st_mode
+ # 判常规文件,避免 isfile 造成第二次 stat 系统调用
+ if not stat.S_ISREG(st.st_mode):
+ continue
+ rel = os.path.normcase(os.path.relpath(abs_path, workspace_base))
+ snapshot[rel.replace("\\", "/")] = (
+ abs_path, st.st_mtime_ns, st.st_size, None,
+ )
+ if len(snapshot) > MAX_SCAN_FILES:
+ logger.warning(
+ "[artifact-detect] workspace scan exceeds "
+ "MAX_SCAN_FILES=%d, fallback to text extraction",
+ MAX_SCAN_FILES,
+ )
+ return None
+ except OSError as exc:
+ logger.warning(
+ "[artifact-detect] workspace scan failed: %s", exc,
+ )
+ return None
+ return snapshot
+
+
+def _diff_snapshot(
+ old: WorkspaceSnapshot,
+ new: WorkspaceSnapshot,
+ cancel_event: threading.Event | None = None,
+) -> list[str]:
+ """对比新旧快照,返回新增/变更文件的绝对路径列表。
+
+ 仅检测增量(新增/变更),不检测删除:遍历 new.keys(),基线独有
+ (已删除)的文件不会出现在候选中。下游 hook(水印/署名等)只
+ 消费新生成的产物,删除检测无消费方;残留的旧 entry 无害——
+ 文件被重建时仍会走 mtime/size/hash 对比正确检出。
+
+ 变更判定:mtime/size 变化后再算 sha256 对比。基线 hash 为懒计算
+ (首次变化时基线 hash 未知,保守判为变更),本次算出的 hash 写回
+ new 快照,作为下次基线的参照,此后 touch(内容未变)可精确排除。
+ hash 计算受 _HASH_BUDGET_S 累计预算约束:预算耗尽后放弃 hash
+ 保守判变更,避免大量变更文件把 sha256 读盘耗时放大到外层超时之外。
+ """
+ candidates: list[str] = []
+ hash_deadline = time.monotonic() + _HASH_BUDGET_S
+ for key, (abs_path, mtime_ns, size, new_hash) in new.items():
+ if cancel_event is not None and cancel_event.is_set():
+ break
+ old_entry = old.get(key)
+ if old_entry is None:
+ logger.debug("[artifact-detect] baseline new: %s", abs_path)
+ candidates.append(abs_path)
+ continue
+ old_mtime, old_size, old_hash = old_entry[1], old_entry[2], old_entry[3]
+ if old_mtime == mtime_ns and old_size == size:
+ continue
+ # mtime/size 变化:算 hash 并写回本次快照(下次基线的参照)
+ if new_hash is not None:
+ cur_hash = new_hash
+ elif time.monotonic() < hash_deadline:
+ cur_hash = _file_sha256(abs_path)
+ else:
+ cur_hash = None # 预算耗尽:保守判变更
+ new[key] = (abs_path, mtime_ns, size, cur_hash)
+ if (
+ cur_hash is not None
+ and old_hash is not None
+ and cur_hash == old_hash
+ ):
+ logger.debug("[artifact-detect] baseline touch skip: %s", abs_path)
+ continue
+ logger.debug("[artifact-detect] baseline changed: %s", abs_path)
+ candidates.append(abs_path)
+ return candidates
+
+
+def _finalize_candidates(
+ paths: list[str],
+ cancel_event: threading.Event | None = None,
+) -> list[str]:
+ """静默期 finalize(批量轮询):所有候选共享窗口等待大小稳定。
+
+ 防后台进程 / tmp->rename 竞态。所有候选并行轮询(总耗时与候选数
+ 解耦,上限 FINALIZE_TIMEOUT_S),超时仍未稳定的文件也保留
+ (对齐原"超时取最后一次"的宽松语义,宁多勿漏)。
+ """
+ pending: dict[str, int] = {}
+ for path in paths:
+ try:
+ pending[path] = os.path.getsize(path)
+ except OSError:
+ continue # 已消失,剔除
+ stable: set[str] = set()
+ deadline = time.monotonic() + FINALIZE_TIMEOUT_S
+ while pending and time.monotonic() < deadline:
+ time.sleep(STABLE_INTERVAL_S)
+ if cancel_event is not None and cancel_event.is_set():
+ break
+ still: dict[str, int] = {}
+ for path, size0 in pending.items():
+ try:
+ current = os.path.getsize(path)
+ except OSError:
+ continue # 等待期间消失,剔除
+ if current == size0:
+ stable.add(path)
+ else:
+ still[path] = current # 仍在写,下一轮再看
+ pending = still
+ return [p for p in paths if p in stable or p in pending]
+
+
+def _refresh_baseline_entries(
+ snapshot: WorkspaceSnapshot,
+ workspace_base: Path,
+ paths: list[str],
+) -> None:
+ """局部刷新基线:hook 可能原地改写文件(水印),重新 stat + hash。"""
+ for path in paths:
+ try:
+ rel = os.path.normcase(os.path.relpath(path, workspace_base))
+ except ValueError:
+ continue
+ key = rel.replace("\\", "/")
+ try:
+ st = os.stat(path)
+ new_hash = _file_sha256(path)
+ except OSError:
+ snapshot.pop(key, None)
+ continue
+ snapshot[key] = (
+ os.path.abspath(path), st.st_mtime_ns, st.st_size, new_hash,
+ )
+
+
+def update_baseline_after_hook(
+ snapshot: WorkspaceSnapshot | None,
+ fired: bool,
+ paths: list[str],
+ workspace_base: Path | None = None,
+) -> WorkspaceSnapshot | None:
+ """返回 fire 后应存为实例基线的新快照(hook 可能原地改写文件,局部刷新)。
+
+ snapshot 为 None(非基线路径/降级)时返回 None,调用方保持原基线不变。
+ """
+ if snapshot is None:
+ return None
+ if fired and paths:
+ if workspace_base is not None:
+ _refresh_baseline_entries(snapshot, workspace_base, paths)
+ else:
+ logger.debug(
+ "[artifact-detect] baseline refresh skipped: no workspace_base"
+ )
+ return snapshot
+
+
+def _detect_via_baseline(
+ baseline: WorkspaceSnapshot,
+ workspace_base: Path,
+ cancel_event: threading.Event | None = None,
+) -> tuple[list[str], WorkspaceSnapshot | None]:
+ """基线 diff 检测:返回 (候选路径, 本次扫描快照)。
+
+ 快照失败/超限返回 ([], None),调用方降级文本提取。
+ """
+ snapshot = _snapshot_workspace(workspace_base, cancel_event)
+ if snapshot is None:
+ return [], None
+ candidates = _diff_snapshot(baseline, snapshot, cancel_event)
+ candidates = _finalize_candidates(candidates, cancel_event)
+ candidates = _validate_artifact_candidates(
+ candidates,
+ tool_start_time=None, # 基线 diff 已保证变化,无需 mtime 校验
+ workspace_base=workspace_base,
+ cancel_event=cancel_event,
+ )
+ return candidates, snapshot
+
+
def _extract_artifact_paths_from_result(
tool_result: Any,
tool_start_time: float | None = None,
@@ -560,6 +814,10 @@ class ArtifactDetection(NamedTuple):
tool_name: str
paths: list[str]
+ # 本次检测的当前工作区快照(仅基线 diff 路径返回,供调用方更新基线)
+ baseline_snapshot: WorkspaceSnapshot | None = None
+ # 基线 diff 快照失败/超限:调用方据此禁用本会话基线路径(降级文本提取)
+ baseline_scan_failed: bool = False
def detect_artifact_paths(
@@ -570,6 +828,7 @@ def detect_artifact_paths(
tool_start_time: float | None = None,
workspace_base: Path | None = None,
cancel_event: threading.Event | None = None,
+ baseline: WorkspaceSnapshot | None = None,
) -> ArtifactDetection:
"""统一产物检测入口,供 TaskExecutionRail / SkillTurboArtifactRail 共用。
@@ -599,6 +858,8 @@ def detect_artifact_paths(
tool_args = inner_args if inner_args is not None else {}
paths: list[str] = []
+ baseline_snapshot: WorkspaceSnapshot | None = None
+ baseline_scan_failed = False
if tool_name in IMAGE_TOOL_NAMES:
# 图像工具返回权威路径,不做 mtime/工作区校验
@@ -620,17 +881,28 @@ def detect_artifact_paths(
paths.extend(str(p).strip() for p in raw_list if str(p).strip())
paths = list(dict.fromkeys(paths))
else:
- # code / bash / mcp_exec_command:统一提取(含黑名单/mtime/工作区过滤)
- paths = _extract_artifact_paths_from_result(
- tool_result,
- tool_start_time=tool_start_time,
- workspace_base=workspace_base,
- cancel_event=cancel_event,
- )
+ # bash / mcp_exec_command:优先基线 diff(不依赖工具输出文本),
+ # 基线缺失/快照失败时降级文本提取
+ if baseline is not None and workspace_base is not None:
+ paths, baseline_snapshot = _detect_via_baseline(
+ baseline, workspace_base, cancel_event,
+ )
+ # 快照失败/超限:调用方据此禁用本会话基线路径,
+ # 避免后续工具反复无效扫描(超限工作区)
+ baseline_scan_failed = baseline_snapshot is None
+ if not paths:
+ paths = _extract_artifact_paths_from_result(
+ tool_result,
+ tool_start_time=tool_start_time,
+ workspace_base=workspace_base,
+ cancel_event=cancel_event,
+ )
# 统一出口:仅保留实际存在的文件(跳过 UNC 网络路径避免同步阻塞)
paths = [p for p in paths if not _is_unc_path(p) and Path(p).exists()]
- return ArtifactDetection(tool_name, paths)
+ return ArtifactDetection(
+ tool_name, paths, baseline_snapshot, baseline_scan_failed,
+ )
def resolve_workspace_base() -> Path | None:
@@ -674,6 +946,7 @@ async def detect_artifact_paths_safe(
tool_start_time: float | None,
*,
log_prefix: str,
+ baseline: WorkspaceSnapshot | None = None,
) -> ArtifactDetection | None:
"""线程中执行产物检测并加超时保护,超时/异常时返回 None(跳过检测)。
@@ -693,6 +966,7 @@ async def detect_artifact_paths_safe(
tool_start_time=tool_start_time,
workspace_base=resolve_workspace_base(),
cancel_event=cancel_event,
+ baseline=baseline,
),
timeout=ARTIFACT_DETECT_TIMEOUT_S,
)
@@ -723,6 +997,155 @@ async def detect_artifact_paths_safe(
return None
+def extract_effective_project_dir(metadata: Any) -> str | None:
+ """从请求 metadata 提取 effective_project_dir(strip 后非空才返回)。
+
+ 供 StreamEventRail 的 ContextVar 重绑块与 TaskExecutionRail 的
+ workspace 副本直读共用,避免提取逻辑双份维护。
+ """
+ if not isinstance(metadata, dict):
+ return None
+ epd = metadata.get("effective_project_dir")
+ if isinstance(epd, str) and epd.strip():
+ return epd.strip()
+ return None
+
+
+class WorkspaceBaselineState:
+ """工作区基线懒建状态,供 TaskExecutionRail 与 SkillTurboArtifactRail 组合复用。
+
+ 双检锁懒建基线:并行 tool_call 时首个 bash 建一次快照,其余等待复用。
+ 快路径不碰锁(会话首个 bash 之后的常态调用零开销);拿锁后双检,等待
+ 期间其他协程可能已建好/已禁用。基线必须先于本轮任何执行类工具建立,
+ 等待者串行化到快照完成(毫秒级)后才放行工具执行;超时场景等待者拿锁
+ 后双检发现已禁用,直接走降级,不再重复烧一次完整超时扫描。
+
+ workspace_base:调用方直读的请求级工作区(如 TaskExecutionRail 从
+ metadata 副本解析);为 None 时回退 resolve_workspace_base() 读
+ ContextVar,供无副本的调用方(SkillTurboArtifactRail)使用。
+
+ 基线状态(snapshot/disabled)本质上是 per-workspace 的,而本实例
+ 随 rail 跨请求复用(per-session):记录状态所属的 snapshot_base,
+ ensure() 发现工作区切换(ACP 请求级 workspace_dir 可变)时重置
+ 状态重建基线,避免用 W1 的基线 diff W2 的状态导致全量误报;
+ disabled 结论同样只对所属工作区有效,切换时重置重新尝试。
+ """
+
+ def __init__(self) -> None:
+ # 工作区基线快照:bash 类工具执行前的文件状态,供增量 diff 检测产物
+ self.snapshot: WorkspaceSnapshot | None = None
+ # 基线状态所属的工作区:成功/禁用都记录,供切换检测与重置判定
+ # (snapshot_base=None 表示尚未建过,_same_base 恒 False)
+ self.snapshot_base: Path | None = None
+ # 基线 diff 会话级禁用标志:快照超时/失败一次即禁用本会话基线路径
+ # (降级文本提取,与基线引入前行为一致),避免反复无效扫描/超时
+ self.disabled = False
+ # 基线懒建双检锁:并行 tool_call 时首个 bash 建一次快照,等待者复用
+ self.init_lock = asyncio.Lock()
+
+ def _same_base(self, base: Path) -> bool:
+ """工作区一致性判定:normcase 归一后字符串比较。
+
+ 两个 base 来源(metadata 副本 / ContextVar)均已 .resolve(),
+ normcase 覆盖 Windows 大小写与斜杠方向差异即可。
+ """
+ return (
+ self.snapshot_base is not None
+ and os.path.normcase(str(self.snapshot_base))
+ == os.path.normcase(str(base))
+ )
+
+ @property
+ def effective(self) -> WorkspaceSnapshot | None:
+ """当前生效的基线:禁用后返回 None(跳过基线 diff,走文本提取)。"""
+ return None if self.disabled else self.snapshot
+
+ async def ensure(
+ self,
+ tool_name: str,
+ tool_args: Any,
+ *,
+ log_prefix: str,
+ workspace_base: Path | None = None,
+ ) -> None:
+ """懒建基线:首个 bash 类工具执行前建工作区快照,等待者复用。
+
+ invoke_tool 间接调用时按解包出的内部工具名判定(与 after 路径
+ detect_artifact_paths 的解包对齐),使 invoke_tool -> bash 场景
+ 也能在执行前懒建基线,而非降级文本提取。无需建立时保持现状。
+ 工作区切换时重置 snapshot/disabled 重建基线(见类 docstring)。
+ """
+ effective_name = tool_name
+ if tool_name in INVOKE_TOOL_NAMES:
+ inner_name, _ = _unwrap_invoke_tool(tool_args, None)
+ if inner_name is not None:
+ effective_name = inner_name
+ if effective_name not in CODE_EXEC_TOOL_NAMES:
+ return
+ base = workspace_base if workspace_base is not None else resolve_workspace_base()
+ if base is None:
+ return
+ # 快路径:已建/已禁用且工作区未变才直接返回——不比较 base 会把
+ # 旧工作区的基线/禁用结论套到新工作区(跨请求切换时全量误报)
+ if (self.snapshot is not None or self.disabled) and self._same_base(base):
+ return
+ async with self.init_lock:
+ # 双检同样带 base 比较:等待者拿锁期间若他人建的是其他工作区
+ # 的基线,不可复用(否则回到陈旧基线误报问题)
+ if (self.snapshot is not None or self.disabled) and self._same_base(base):
+ return
+ # 工作区切换:旧 snapshot/disabled 结论只对旧工作区有效,
+ # 重置后重建(disabled 随切换重置:旧工作区超限/超时不代表
+ # 新工作区也超限,切换是一次性的,无重试风暴)
+ if not self._same_base(base):
+ logger.info(
+ "%s workspace changed %s -> %s, rebuild baseline",
+ log_prefix, self.snapshot_base, base,
+ )
+ self.snapshot = None
+ self.disabled = False
+ # 线程 + 超时 + cancel_event 三重防护,防 stat 阻塞 event loop;
+ # 超时一次即禁用本会话基线路径,避免反复重试超时
+ cancel_event = threading.Event()
+ try:
+ snapshot = await asyncio.wait_for(
+ asyncio.to_thread(_snapshot_workspace, base, cancel_event),
+ timeout=BASELINE_SNAPSHOT_TIMEOUT_S,
+ )
+ except asyncio.TimeoutError:
+ # 通知后台线程在下一个检查点退出;本会话禁用基线路径,
+ # 避免后续工具反复重试超时
+ cancel_event.set()
+ logger.warning(
+ "%s baseline snapshot timed out (%.1fs), disable baseline "
+ "diff for this session",
+ log_prefix,
+ BASELINE_SNAPSHOT_TIMEOUT_S,
+ )
+ self.disabled = True
+ self.snapshot_base = base
+ return
+ if snapshot is not None:
+ logger.info(
+ "%s baseline ready files=%d", log_prefix, len(snapshot)
+ )
+ self.snapshot = snapshot
+ self.snapshot_base = base
+ else:
+ # 快照失败/超限返回 None(具体原因已由 _snapshot_workspace
+ # 记录):本会话禁用基线路径,与超时路径保持一致,避免后续
+ # bash 工具反复重扫(超限工作区每次都要扫满 MAX_SCAN_FILES
+ # 才放弃);after 路径 baseline_scan_failed 因 baseline 为
+ # None 无法兜底,必须在此禁用
+ self.disabled = True
+ self.snapshot_base = base
+ logger.warning(
+ "%s baseline snapshot unavailable, disable baseline "
+ "diff for this session",
+ log_prefix,
+ )
+
+
def filter_unhooked(
paths: list[str], hooked: set[tuple[str, int, int]]
) -> list[str]:
@@ -870,6 +1293,42 @@ class TaskExecutionRail(DeepAgentRail):
self._tool_start_times: dict[str, float] = {}
# 已触发过产物 hook 的文件身份(路径+mtime_ns+size),防止重复后处理
self._hooked_artifacts: set[tuple[str, int, int]] = set()
+ # 工作区基线懒建状态:bash 类工具执行前的文件快照,供增量 diff 检测产物
+ self._baseline = WorkspaceBaselineState()
+ # 请求 metadata 副本(adapter 每轮 bind_request 注入):工具运行在
+ # supervisor round task 不继承请求任务的 ContextVar,且本 rail 先于
+ # StreamEventRail 执行(priority 大者先),workspace 须从副本直读
+ self._skill_turbo_request_metadata: dict | None = None
+
+ def set_skill_turbo_request_metadata(self, metadata: dict | None) -> None:
+ """注入当前请求 metadata 副本,供 before_tool_call 解析请求级工作区。"""
+ self._skill_turbo_request_metadata = (
+ dict(metadata) if isinstance(metadata, dict) else None
+ )
+
+ def _resolve_metadata_workspace_base(self) -> Path | None:
+ """从请求 metadata 副本直读请求级工作区。
+
+ resolve_workspace_base() 读 ``_effective_request_workspace_dir``
+ ContextVar,该绑定在请求任务设置、supervisor round task 不继承,
+ 且 StreamEventRail 的重绑发生在本 rail 之后(priority 数值大者
+ 先执行),before 阶段读不到。这里直接从 adapter 注入的 metadata
+ 副本提取 effective_project_dir;不 set/reset ContextVar,避免
+ 与 StreamEventRail after 阶段的 token reset 乱序冲突。
+ """
+ epd = extract_effective_project_dir(
+ self._skill_turbo_request_metadata
+ )
+ if epd is not None:
+ try:
+ return Path(epd).resolve()
+ except OSError:
+ logger.warning(
+ "[TaskExecutionRail] invalid effective_project_dir in "
+ "request metadata: %r",
+ epd,
+ )
+ return None
def get_current_task_id(self) -> str | None:
return _ACTIVE_TASK_ID.get()
@@ -971,6 +1430,16 @@ class TaskExecutionRail(DeepAgentRail):
tool_call_id = str(getattr(tc, "id", "") or "")
if tool_call_id:
self._tool_start_times[tool_call_id] = time.time()
+ # bash 类工具懒建基线(含 invoke_tool 间接调用的内部工具名
+ # 判定、超时禁用与并行去重,详见 WorkspaceBaselineState.ensure)。workspace_base 从 metadata
+ # 副本直读:ContextVar 在本 rail 执行时尚未由 StreamEventRail
+ # 重绑(priority 大者先执行)
+ await self._baseline.ensure(
+ tool_name,
+ getattr(ctx.inputs, "tool_args", None),
+ log_prefix="[TaskExecutionRail]",
+ workspace_base=self._resolve_metadata_workspace_base(),
+ )
self._bind_context_to_in_progress_task()
if tool_name == "skill_acceleration_exec":
@@ -1139,31 +1608,49 @@ class TaskExecutionRail(DeepAgentRail):
return
# 线程 + 超时 + 异常兜底执行产物检测,避免阻塞 event loop
+ # (基线禁用后传 None:跳过基线 diff,走文本提取)
detection = await detect_artifact_paths_safe(
ctx,
session_id,
pop_tool_start_time(self._tool_start_times, ctx),
log_prefix="[TaskExecutionRail]",
+ baseline=self._baseline.effective,
)
if detection is None:
return
+ # 基线 diff 快照失败/超限:禁用本会话基线路径,避免反复无效扫描
+ if detection.baseline_scan_failed:
+ self._baseline.disabled = True
+ logger.warning(
+ "[TaskExecutionRail] baseline scan failed, disable baseline "
+ "diff for this session"
+ )
task_id = _ACTIVE_TASK_ID.get()
+ snapshot = detection.baseline_snapshot
# 去重:跳过已 hook 过且内容未变化的文件
paths = filter_unhooked(detection.paths, self._hooked_artifacts)
- if not paths:
- return
-
- fired = await fire_artifact_hook(
- session_id=session_id,
- tool_name=detection.tool_name,
- task_id=task_id,
- artifact_paths=paths,
- log_prefix="[TaskExecutionRail]",
- )
- if fired:
- mark_hooked(paths, self._hooked_artifacts)
+ fired = False
+ if paths:
+ fired = await fire_artifact_hook(
+ session_id=session_id,
+ tool_name=detection.tool_name,
+ task_id=task_id,
+ artifact_paths=paths,
+ log_prefix="[TaskExecutionRail]",
+ )
+ if fired:
+ mark_hooked(paths, self._hooked_artifacts)
+
+ # 更新基线:仅拿到本次快照时更新(snapshot 为 None 表示非基线路径/
+ # 降级,保持原基线不变);hook 可能原地改写文件(水印),局部刷新
+ # 候选条目(含 sha256 读文件,放线程防阻塞 event loop)
+ if snapshot is not None:
+ self._baseline.snapshot = await asyncio.to_thread(
+ update_baseline_after_hook,
+ snapshot, fired, paths, resolve_workspace_base(),
+ )
async def after_invoke(self, ctx: AgentCallbackContext) -> None:
self._todo_map_before_tool = {}
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index bfa3f26017..f495bd2605 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -9995,6 +9995,11 @@ class JiuWenSwarmDeepAdapter:
# 随机 UUID sid 下、恢复时无法命中(fallback DeepAgent 全量重跑)。
if self._stream_event_rail is not None:
self._stream_event_rail.set_skill_turbo_request_metadata(meta)
+ # 同步副本到 TaskExecutionRail:其 priority(85) 高于
+ # StreamEventRail(80),before_tool_call 先于 ContextVar 重绑
+ # 执行,产物基线懒建需直接从副本解析请求级工作区
+ if self._task_execution_rail is not None:
+ self._task_execution_rail.set_skill_turbo_request_metadata(meta)
except Exception:
logger.warning(
"[AgentServer] bind request metadata for skill_turbo failed: "
diff --git a/jiuwenswarm/server/runtime/skill_turbo/environment.py b/jiuwenswarm/server/runtime/skill_turbo/environment.py
index dd904796ea..8d032cbe86 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/environment.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/environment.py
@@ -218,7 +218,7 @@ class SkillTurboEnvironment:
def _resolve_sys_operation(self) -> Any:
"""解析 sys_operation。
- sys_operation 是 openjiuwen 提供的系统操作抽象层,bash/code/filesystem
+ sys_operation 是 openjiuwen 提供的系统操作抽象层,bash/filesystem
等工具依赖它。DeepAgent 在初始化时已将 sys_operation 注册到全局
Runner.resource_mgr 中,SkillTurbo 可直接获取,无需 interface_deep.py
显式传入。
diff --git a/jiuwenswarm/server/runtime/skill_turbo/rails/artifact_rail.py b/jiuwenswarm/server/runtime/skill_turbo/rails/artifact_rail.py
index 1a3c1ed86b..16f2a8a2a2 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/rails/artifact_rail.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/rails/artifact_rail.py
@@ -11,6 +11,7 @@ session stream。
from __future__ import annotations
+import asyncio
import logging
import time
from pathlib import Path
@@ -25,11 +26,14 @@ from openjiuwen.core.single_agent.rail.base import (
# 复用 jiuwenswarm TaskExecutionRail 的共享产物检测逻辑
from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
ARTIFACT_DETECTION_TOOL_NAMES,
+ WorkspaceBaselineState,
detect_artifact_paths_safe,
filter_unhooked,
fire_artifact_hook,
mark_hooked,
pop_tool_start_time,
+ resolve_workspace_base,
+ update_baseline_after_hook,
)
logger = logging.getLogger(__name__)
@@ -55,16 +59,26 @@ class SkillTurboArtifactRail:
self._hooked_artifacts: set[tuple[str, int, int]] = set()
# 工具调用开始时间(按 tool_call_id 记录,用于 mtime 校验)
self._tool_start_times: dict[str, float] = {}
+ # 工作区基线懒建状态:bash 类工具执行前的文件快照,供增量 diff 检测产物
+ self._baseline = WorkspaceBaselineState()
async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
if not isinstance(ctx.inputs, ToolCallInputs):
return
- if ctx.inputs.tool_name not in ARTIFACT_DETECTION_TOOL_NAMES:
+ tool_name = ctx.inputs.tool_name
+ if tool_name not in ARTIFACT_DETECTION_TOOL_NAMES:
return
tc = getattr(ctx.inputs, "tool_call", None)
tool_call_id = str(getattr(tc, "id", "") or "")
if tool_call_id:
self._tool_start_times[tool_call_id] = time.time()
+ # bash 类工具懒建基线(含 invoke_tool 间接调用的内部工具名
+ # 判定、超时禁用与并行去重,详见 WorkspaceBaselineState.ensure)
+ await self._baseline.ensure(
+ tool_name,
+ getattr(ctx.inputs, "tool_args", None),
+ log_prefix=_LOG_PREFIX,
+ )
async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
if ctx.session is None or not isinstance(ctx.inputs, ToolCallInputs):
@@ -77,21 +91,40 @@ class SkillTurboArtifactRail:
detect_start = time.perf_counter()
# 线程 + 超时 + 异常兜底执行产物检测,避免 stat() 阻塞 event loop
- # (共享 TaskExecutionRail 的 detect_artifact_paths_safe)
+ # (共享 TaskExecutionRail 的 detect_artifact_paths_safe;
+ # 基线禁用后传 None:跳过基线 diff,走文本提取)
detection = await detect_artifact_paths_safe(
ctx,
session_id,
pop_tool_start_time(self._tool_start_times, ctx),
log_prefix=_LOG_PREFIX,
+ baseline=self._baseline.effective,
)
if detection is None:
return
+ # 基线 diff 快照失败/超限:禁用本会话基线路径,避免反复无效扫描
+ if detection.baseline_scan_failed:
+ self._baseline.disabled = True
+ logger.warning(
+ "%s baseline scan failed, disable baseline diff for this "
+ "session",
+ _LOG_PREFIX,
+ )
+ snapshot = detection.baseline_snapshot
# 去重:跳过已 hook 过且内容未变化的文件
# (存在性过滤已在 detect_artifact_paths 统一出口处理)
paths = filter_unhooked(detection.paths, self._hooked_artifacts)
+ fired = False
if not paths:
+ # 无新产物:仅在有本次快照时刷新基线(记录当前状态)后返回
+ # (snapshot 为 None 表示非基线路径/降级,保持原基线不变)
+ if snapshot is not None:
+ self._baseline.snapshot = await asyncio.to_thread(
+ update_baseline_after_hook,
+ snapshot, fired, paths, resolve_workspace_base(),
+ )
return
logger.info(
@@ -113,6 +146,15 @@ class SkillTurboArtifactRail:
if fired:
mark_hooked(paths, self._hooked_artifacts)
+ # 更新基线:仅在有本次快照时更新(snapshot 为 None 表示非基线路径/
+ # 降级,保持原基线不变);hook 可能原地改写文件(水印),局部刷新
+ # 候选条目(含 sha256 读文件,放线程防阻塞 event loop)
+ if snapshot is not None:
+ self._baseline.snapshot = await asyncio.to_thread(
+ update_baseline_after_hook,
+ snapshot, fired, paths, resolve_workspace_base(),
+ )
+
# 发射 artifact.generated 事件到 session stream
emitted = await self._emit_artifact_generated(
ctx.session, paths, session_id, detection.tool_name, task_id
diff --git a/tests/unit_tests/agentserver/rails/test_task_execution_baseline.py b/tests/unit_tests/agentserver/rails/test_task_execution_baseline.py
new file mode 100644
index 0000000000..091d80dbb3
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_task_execution_baseline.py
@@ -0,0 +1,415 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""基线 diff 产物检测(WorkspaceBaselineState / _detect_via_baseline 等)UT。
+
+覆盖 P0(并发去重、超时降级、懒建分支矩阵、diff 核心语义、临时文件排除)
+与 P1(extract_effective_project_dir 边界、metadata 副本解析链、基线局部刷新)。
+"""
+
+from __future__ import annotations
+
+import asyncio
+import tempfile
+import warnings
+
+warnings.filterwarnings(
+ "ignore",
+ message=r"Protobuf gencode version.*",
+)
+
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
+ BASELINE_SNAPSHOT_TIMEOUT_S,
+ TaskExecutionRail,
+ WorkspaceBaselineState,
+ _detect_via_baseline,
+ _diff_snapshot,
+ _refresh_baseline_entries,
+ _snapshot_workspace,
+ extract_effective_project_dir,
+ update_baseline_after_hook,
+)
+
+_SNAPSHOT_MODULE = (
+ "jiuwenswarm.agents.harness.common.rails.task_execution_rail"
+)
+
+
+def _patch_snapshot(monkeypatch, fn) -> dict:
+ """替换 _snapshot_workspace 并返回调用计数器。"""
+ calls = {"n": 0}
+
+ def wrapper(base, cancel_event=None):
+ calls["n"] += 1
+ return fn(base, cancel_event)
+
+ monkeypatch.setattr(f"{_SNAPSHOT_MODULE}._snapshot_workspace", wrapper)
+ return calls
+
+
+# ---------------------------------------------------------------------------
+# P0: WorkspaceBaselineState.ensure —— 并发去重与超时降级
+# ---------------------------------------------------------------------------
+
+
+async def test_ensure_concurrent_only_one_snapshot(tmp_path, monkeypatch) -> None:
+ """并行 N 个 bash 的 ensure:仅建一次快照,等待者复用(双检锁)。"""
+
+ def fake_snapshot(base, cancel_event=None):
+ time.sleep(0.05) # 拉长快照窗口,放大并发窗口
+ return _snapshot_workspace(Path(base), cancel_event)
+
+ calls = _patch_snapshot(monkeypatch, fake_snapshot)
+ state = WorkspaceBaselineState()
+ await asyncio.gather(*[
+ state.ensure("bash", {}, log_prefix="[T]", workspace_base=tmp_path)
+ for _ in range(3)
+ ])
+ assert calls["n"] == 1, "并行 ensure 应只建一次快照"
+ assert state.snapshot is not None
+ assert not state.disabled
+
+ # 快路径:基线已建后再次调用不碰锁、不重建
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=tmp_path)
+ assert calls["n"] == 1
+
+
+async def test_ensure_snapshot_none_disables(tmp_path, monkeypatch) -> None:
+ """快照返回 None(超限/扫描失败降级):一次即置禁用,后续 bash 不重扫。"""
+
+ def fake_snapshot(base, cancel_event=None):
+ return None # 模拟 MAX_SCAN_FILES 超限 / 扫描异常降级
+
+ calls = _patch_snapshot(monkeypatch, fake_snapshot)
+ state = WorkspaceBaselineState()
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=tmp_path)
+ assert state.snapshot is None
+ assert state.disabled is True
+ # 禁用后再次调用:快路径直接返回,不重复扫描
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=tmp_path)
+ assert calls["n"] == 1, "快照失败禁用后不应重试扫描"
+
+
+async def test_ensure_timeout_disables_and_waiter_degrades(
+ tmp_path, monkeypatch
+) -> None:
+ """首建者超时置 disabled 后,等待者拿锁双检直接降级,不重复扫描。"""
+
+ def slow_snapshot(base, cancel_event=None):
+ time.sleep(BASELINE_SNAPSHOT_TIMEOUT_S + 2)
+ return {}
+
+ calls = _patch_snapshot(monkeypatch, slow_snapshot)
+ state = WorkspaceBaselineState()
+ await asyncio.gather(
+ state.ensure("bash", {}, log_prefix="[T]", workspace_base=tmp_path),
+ state.ensure("bash", {}, log_prefix="[T]", workspace_base=tmp_path),
+ )
+ assert state.disabled is True
+ assert state.snapshot is None
+ assert calls["n"] == 1, "等待者不应重复发起快照扫描"
+ # 禁用后再次调用:快路径直接返回(不碰锁、不扫描)
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=tmp_path)
+ assert calls["n"] == 1
+
+
+# ---------------------------------------------------------------------------
+# P0: ensure 分支矩阵 —— 非 bash 跳过 / invoke_tool 解包 / workspace_base 缺失跳过
+# ---------------------------------------------------------------------------
+
+
+async def test_ensure_workspace_switch_rebuilds(tmp_path_factory, monkeypatch) -> None:
+ """工作区切换(W1->W2)触发基线重建;同 base 再调不重建;回 W1 也重建。"""
+ w1 = tmp_path_factory.mktemp("w1")
+ w2 = tmp_path_factory.mktemp("w2")
+ (w1 / "old.txt").write_text("w1")
+ (w2 / "other.txt").write_text("w2")
+
+ calls = _patch_snapshot(
+ monkeypatch, lambda base, cancel_event=None: _snapshot_workspace(base)
+ )
+ state = WorkspaceBaselineState()
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w1)
+ assert calls["n"] == 1
+ assert state.snapshot is not None
+ assert "old.txt" in state.snapshot
+ assert state.snapshot_base is not None
+
+ # 切到 W2:重建,基线反映 W2 的内容(不能用 W1 基线 diff W2)
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w2)
+ assert calls["n"] == 2, "工作区切换应重建基线"
+ assert state.snapshot is not None
+ assert "other.txt" in state.snapshot
+ assert "old.txt" not in state.snapshot
+
+ # 同 base 再次调用:快路径直接返回,不重建
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w2)
+ assert calls["n"] == 2
+
+ # 回 W1:当前记录的是 W2,仍视为切换,重建
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w1)
+ assert calls["n"] == 3
+ assert "old.txt" in state.snapshot
+
+
+async def test_ensure_workspace_switch_resets_disabled(
+ tmp_path_factory, monkeypatch
+) -> None:
+ """W1 失败禁用后切 W2:disabled 重置重新尝试;W2 也失败则再次禁用。"""
+ w1 = tmp_path_factory.mktemp("w1")
+ w2 = tmp_path_factory.mktemp("w2")
+
+ calls = _patch_snapshot(monkeypatch, lambda base, cancel_event=None: None)
+ state = WorkspaceBaselineState()
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w1)
+ assert state.disabled is True
+ assert state.snapshot_base == w1
+
+ # 切到 W2:disabled 随切换重置,重新尝试
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w2)
+ assert state.disabled is True, "W2 也失败,应再次禁用"
+ assert calls["n"] == 2, "切换后应重新扫描一次"
+ assert state.snapshot_base == w2, "禁用结论应归属 W2"
+
+ # W2 内再次调用:快路径命中(禁用且同 base),不重扫
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w2)
+ assert calls["n"] == 2
+
+
+async def test_ensure_switch_concurrent_single_rebuild(
+ tmp_path_factory, monkeypatch
+) -> None:
+ """W1 基线已存在时并行多个 ensure(W2):双检带 base 比较,只重建一次。"""
+ w1 = tmp_path_factory.mktemp("w1")
+ w2 = tmp_path_factory.mktemp("w2")
+
+ def slow_snapshot(base, cancel_event=None):
+ time.sleep(0.05) # 拉长窗口,放大并发竞态
+ return _snapshot_workspace(base, cancel_event)
+
+ calls = _patch_snapshot(monkeypatch, slow_snapshot)
+ state = WorkspaceBaselineState()
+ await state.ensure("bash", {}, log_prefix="[T]", workspace_base=w1)
+ assert calls["n"] == 1
+
+ await asyncio.gather(*[
+ state.ensure("bash", {}, log_prefix="[T]", workspace_base=w2)
+ for _ in range(3)
+ ])
+ assert calls["n"] == 2, "并行切换请求应只重建一次"
+ assert state.snapshot is not None
+ assert state.snapshot_base == w2
+
+
+async def test_ensure_skips_non_exec_tool(tmp_path, monkeypatch) -> None:
+ """write_file 等非 CODE_EXEC 工具不建基线(走文本提取路径)。"""
+ calls = _patch_snapshot(monkeypatch, lambda base, cancel_event=None: {})
+ state = WorkspaceBaselineState()
+ await state.ensure("write_file", {"path": "a.py"}, log_prefix="[T]")
+ await state.ensure("edit_file", {}, log_prefix="[T]")
+ await state.ensure("todo_create", {}, log_prefix="[T]")
+ assert calls["n"] == 0
+ assert state.snapshot is None
+
+ # invoke_tool 解包出 bash 时应建立基线
+ await state.ensure(
+ "invoke_tool",
+ {"tool_name": "bash", "command": "ls"},
+ log_prefix="[T]",
+ workspace_base=tmp_path,
+ )
+ assert calls["n"] == 1
+ assert state.snapshot is not None
+
+
+async def test_ensure_no_workspace_base_skips(monkeypatch) -> None:
+ """workspace_base=None 且 ContextVar 回退也为 None 时跳过(不建基线不报错)。"""
+ calls = _patch_snapshot(monkeypatch, lambda base, cancel_event=None: {})
+ monkeypatch.setattr(
+ f"{_SNAPSHOT_MODULE}.resolve_workspace_base", lambda: None
+ )
+ state = WorkspaceBaselineState()
+ await state.ensure("bash", {}, log_prefix="[T]")
+ assert calls["n"] == 0
+ assert state.snapshot is None
+ assert not state.disabled
+
+
+# ---------------------------------------------------------------------------
+# P0: _detect_via_baseline —— diff 核心语义
+# ---------------------------------------------------------------------------
+
+
+def test_detect_via_baseline_new_file() -> None:
+ """新增文件被检出,且出现在本次快照中(供 hook 后局部刷新)。"""
+ with tempfile.TemporaryDirectory() as td:
+ base = Path(td).resolve()
+ (base / "old.txt").write_text("old")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+ (base / "new.png").write_bytes(b"png")
+ candidates, snapshot = _detect_via_baseline(baseline, base)
+ assert candidates == [str(base / "new.png")]
+ assert snapshot is not None
+ assert "new.png" in snapshot
+
+
+def test_detect_via_baseline_unchanged_not_reported() -> None:
+ """未变化文件不检出。"""
+ with tempfile.TemporaryDirectory() as td:
+ base = Path(td).resolve()
+ (base / "a.txt").write_text("a")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+ candidates, _ = _detect_via_baseline(baseline, base)
+ assert candidates == []
+
+
+def test_diff_snapshot_touch_same_content_not_reported() -> None:
+ """mtime 变但内容相同(touch):基线携带 hash 后 sha256 对比排除误报。"""
+ with tempfile.TemporaryDirectory() as td:
+ base = Path(td).resolve()
+ f = base / "same.txt"
+ f.write_text("stable")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+ # 模拟 hook 后基线写回 hash(_refresh_baseline_entries 的效果)
+ _refresh_baseline_entries(baseline, base, [str(f)])
+ assert baseline["same.txt"][3] is not None
+ # touch:mtime 变化,内容不变
+ os.utime(f, (time.time() + 10, time.time() + 10))
+ candidates = _diff_snapshot(baseline, _snapshot_workspace(base))
+ assert candidates == [], "touch(内容未变)不应误报为变更"
+
+
+def test_detect_via_baseline_changed_file() -> None:
+ """内容变更文件被检出,新 hash 写回本次快照(下次基线参照)。"""
+ with tempfile.TemporaryDirectory() as td:
+ base = Path(td).resolve()
+ f = base / "c.txt"
+ f.write_text("v1")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+ f.write_text("v2-longer-content")
+ candidates, snapshot = _detect_via_baseline(baseline, base)
+ assert candidates == [str(f)]
+ assert snapshot is not None
+ assert snapshot["c.txt"][3] is not None
+
+
+def test_detect_via_baseline_excludes_temp_files() -> None:
+ """临时/锁文件(~$xxx.pptx、.tmp、.swp、.DS_Store)不检出。"""
+ with tempfile.TemporaryDirectory() as td:
+ base = Path(td).resolve()
+ (base / "ok.txt").write_text("ok")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+ for name in ("~$lock.pptx", "x.tmp", "y.swp", ".DS_Store"):
+ (base / name).write_bytes(b"x")
+ candidates, _ = _detect_via_baseline(baseline, base)
+ assert candidates == []
+
+
+# ---------------------------------------------------------------------------
+# P1: extract_effective_project_dir —— 提取边界
+# ---------------------------------------------------------------------------
+
+
+def test_extract_effective_project_dir_boundaries() -> None:
+ assert extract_effective_project_dir(None) is None
+ assert extract_effective_project_dir("not-a-dict") is None
+ assert extract_effective_project_dir({}) is None
+ assert extract_effective_project_dir({"effective_project_dir": None}) is None
+ assert extract_effective_project_dir({"effective_project_dir": 123}) is None
+ assert extract_effective_project_dir({"effective_project_dir": " "}) is None
+ assert extract_effective_project_dir(
+ {"effective_project_dir": " E:\\ws\\proj "}
+ ) == "E:\\ws\\proj"
+
+
+# ---------------------------------------------------------------------------
+# P1: metadata 副本解析链(set_skill_turbo_request_metadata)
+# ---------------------------------------------------------------------------
+
+
+def test_rail_metadata_workspace_base_resolution(tmp_path) -> None:
+ """注入 metadata 后 _resolve_metadata_workspace_base 直读工作区。"""
+ rail = TaskExecutionRail()
+ assert rail._resolve_metadata_workspace_base() is None
+
+ epd = str(tmp_path.resolve())
+ rail.set_skill_turbo_request_metadata({"effective_project_dir": epd})
+ assert rail._resolve_metadata_workspace_base() == Path(epd).resolve()
+
+ # 空白值:回退 None(不抛异常)
+ rail.set_skill_turbo_request_metadata({"effective_project_dir": " "})
+ assert rail._resolve_metadata_workspace_base() is None
+ # None / 非 dict 类型容错
+ rail.set_skill_turbo_request_metadata(None)
+ assert rail._resolve_metadata_workspace_base() is None
+ rail.set_skill_turbo_request_metadata("bad") # type: ignore[arg-type]
+ assert rail._resolve_metadata_workspace_base() is None
+
+
+# ---------------------------------------------------------------------------
+# P1: update_baseline_after_hook —— 基线局部刷新
+# ---------------------------------------------------------------------------
+
+
+def test_update_baseline_after_hook_refresh(tmp_path) -> None:
+ """hook 原地改写文件后局部刷新:下一轮 diff 不再误报该文件。"""
+ base = tmp_path.resolve()
+ f = base / "w.png"
+ f.write_bytes(b"v1")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+
+ # 模拟水印 hook 原地改写
+ f.write_bytes(b"v1-watermarked")
+ refreshed = update_baseline_after_hook(
+ baseline, fired=True, paths=[str(f)], workspace_base=base
+ )
+ assert refreshed is baseline
+ candidates, _ = _detect_via_baseline(refreshed, base)
+ assert candidates == [], "hook 改写过的文件刷新后不应再被 diff 出"
+
+
+def test_update_baseline_after_hook_none_passthrough(tmp_path) -> None:
+ """snapshot=None(降级路径)返回 None;fired=False/paths 空:原样返回。"""
+ assert update_baseline_after_hook(None, True, ["x"]) is None
+ base = tmp_path.resolve()
+ (base / "a.txt").write_text("a")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+ assert update_baseline_after_hook(
+ baseline, fired=False, paths=[], workspace_base=base
+ ) is baseline
+
+
+def test_update_baseline_after_hook_no_workspace_base(tmp_path) -> None:
+ """workspace_base=None:跳过刷新,变化保留给下一轮 diff(宁多勿漏)。"""
+ base = tmp_path.resolve()
+ f = base / "a.txt"
+ f.write_text("a")
+ baseline = _snapshot_workspace(base)
+ assert baseline is not None
+ f.write_text("changed")
+ result = update_baseline_after_hook(
+ baseline, fired=True, paths=[str(f)], workspace_base=None
+ )
+ assert result is baseline
+ candidates, _ = _detect_via_baseline(result, base)
+ assert str(f) in candidates