mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-27 14:22:35 +08:00
fix(agent): exclude history storage from runtime signatures
This commit is contained in:
@@ -19,6 +19,7 @@ from app.runtime.log import logger
|
||||
|
||||
CURRENT_PERSONA_FILE = "CURRENT_PERSONA.md"
|
||||
SYSTEM_RUNTIME_DIR = "runtime"
|
||||
HISTORY_DIR = "history"
|
||||
MEMORY_DIR = "memory"
|
||||
SKILLS_DIR = "skills"
|
||||
JOBS_DIR = "jobs"
|
||||
@@ -449,18 +450,26 @@ class AgentRuntimeManager:
|
||||
return updated_persona, created
|
||||
|
||||
def _build_signature(self) -> tuple[tuple[str, int, int], ...]:
|
||||
"""基于运行时配置和内置人格生成文件签名。"""
|
||||
"""生成配置签名,排除实时历史库并容忍扫描期间文件被并发删除。"""
|
||||
entries: list[tuple[str, int, int]] = []
|
||||
for prefix, root in (
|
||||
("runtime", self.runtime_dir),
|
||||
("bundled", self.bundled_defaults_dir),
|
||||
):
|
||||
if not root.exists():
|
||||
continue
|
||||
for path in sorted(root.rglob("*")):
|
||||
if not path.is_file():
|
||||
paths: list[Path] = []
|
||||
for directory, dirnames, filenames in root.walk():
|
||||
if directory == self.runtime_dir:
|
||||
# 历史库及 WAL 边车不是配置,必须在递归前排除整个目录。
|
||||
dirnames[:] = [name for name in dirnames if name != HISTORY_DIR]
|
||||
paths.extend(directory / name for name in filenames)
|
||||
for path in sorted(paths):
|
||||
try:
|
||||
if not path.is_file():
|
||||
continue
|
||||
stat = path.stat()
|
||||
except FileNotFoundError:
|
||||
# 类型检查与元数据读取之间,文件仍可能被删除或替换。
|
||||
continue
|
||||
stat = path.stat()
|
||||
relative = path.relative_to(root).as_posix()
|
||||
entries.append((f"{prefix}:{relative}", stat.st_mtime_ns, stat.st_size))
|
||||
return tuple(entries)
|
||||
@@ -551,6 +560,7 @@ class AgentRuntimeManager:
|
||||
logger.info(f"已迁移旧版 Agent memory 文件: {path} -> {target}")
|
||||
|
||||
def _load_from_root(self, root: Path) -> AgentRuntimeConfig:
|
||||
"""从指定根目录解析人格、子代理和额外上下文,配置错误交由调用方回退。"""
|
||||
current_persona_path = root / CURRENT_PERSONA_FILE
|
||||
current_doc = self._read_markdown(current_persona_path)
|
||||
current_meta = current_doc.metadata
|
||||
@@ -721,6 +731,7 @@ class AgentRuntimeManager:
|
||||
|
||||
@staticmethod
|
||||
def _read_markdown(path: Path) -> ParsedMarkdownDocument:
|
||||
"""解析配置正文与元数据,并将读取或格式错误转换为配置异常。"""
|
||||
if not path.exists():
|
||||
raise AgentRuntimeConfigError(f"缺少配置文件: {path}")
|
||||
try:
|
||||
@@ -743,6 +754,7 @@ class AgentRuntimeManager:
|
||||
|
||||
@staticmethod
|
||||
def _resolve_optional_paths(root: Path, values: Any) -> list[Path]:
|
||||
"""校验额外上下文路径数组,并按配置根目录解析相对路径。"""
|
||||
if not values:
|
||||
return []
|
||||
if not isinstance(values, list):
|
||||
@@ -751,11 +763,13 @@ class AgentRuntimeManager:
|
||||
|
||||
@staticmethod
|
||||
def _resolve_relative_path(root: Path, value: str) -> Path:
|
||||
"""保留显式绝对路径,相对路径以所属配置根目录为基准。"""
|
||||
candidate = Path(value)
|
||||
return candidate if candidate.is_absolute() else (root / candidate).resolve()
|
||||
|
||||
@staticmethod
|
||||
def _normalize_string_list(values: Any, field_name: str) -> list[str]:
|
||||
"""严格校验数组类型,清理空白后保留非空配置项。"""
|
||||
if values is None:
|
||||
return []
|
||||
if not isinstance(values, list):
|
||||
@@ -769,6 +783,7 @@ class AgentRuntimeManager:
|
||||
|
||||
@staticmethod
|
||||
def _coerce_string_list(values: Any) -> list[str]:
|
||||
"""宽容读取可选字符串数组,非数组配置按空值处理。"""
|
||||
if not isinstance(values, list):
|
||||
return []
|
||||
return [str(value).strip() for value in values if str(value).strip()]
|
||||
@@ -852,6 +867,7 @@ class AgentRuntimeManager:
|
||||
extra_context_paths: list[Path],
|
||||
persona_text: str,
|
||||
) -> list[str]:
|
||||
"""收集重复引用和废弃短语警告,不阻止有效人格加载。"""
|
||||
warnings: list[str] = []
|
||||
required_paths = [persona_path]
|
||||
duplicates = self._find_duplicate_paths(required_paths + extra_context_paths)
|
||||
@@ -867,6 +883,7 @@ class AgentRuntimeManager:
|
||||
|
||||
@staticmethod
|
||||
def _find_duplicate_paths(paths: Iterable[Path]) -> list[Path]:
|
||||
"""按解析后的文件路径识别重复引用,每条重复路径只报告一次。"""
|
||||
seen: set[Path] = set()
|
||||
duplicates: list[Path] = []
|
||||
for path in paths:
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
"""Agent 运行时配置与已废弃活动目录的 pytest 回归。"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import textwrap
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
@@ -20,6 +23,108 @@ def context(tmp_path):
|
||||
_manager=lambda: AgentRuntimeManager(agent_root_dir=agent_root, bundled_defaults_dir=defaults_root))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def signature_manager(context):
|
||||
"""签名测试使用临时配置与默认模板,避免改动仓库内置文件。"""
|
||||
defaults_root = context.temp_root / 'defaults'
|
||||
shutil.copytree(context.defaults_root, defaults_root)
|
||||
manager = AgentRuntimeManager(agent_root_dir=context.agent_root, bundled_defaults_dir=defaults_root)
|
||||
manager.ensure_layout()
|
||||
return manager
|
||||
|
||||
|
||||
def test_signature_ignores_history_wal_lifecycle(signature_manager, monkeypatch):
|
||||
"""历史库及 WAL 边车的创建、写入和删除不应改变配置签名。"""
|
||||
manager = signature_manager
|
||||
monkeypatch.setattr(manager, '_signature_check_interval', 0)
|
||||
config = manager.load_runtime_config()
|
||||
signature = manager.current_signature()
|
||||
database = manager.runtime_dir / 'history' / 'users' / 'test-user' / 'state.db'
|
||||
database.parent.mkdir(parents=True)
|
||||
|
||||
for value in ('first message', 'second message'):
|
||||
with closing(sqlite3.connect(database)) as connection:
|
||||
connection.execute('PRAGMA journal_mode=WAL')
|
||||
connection.execute('CREATE TABLE IF NOT EXISTS messages (text TEXT)')
|
||||
connection.execute('INSERT INTO messages VALUES (?)', (value,))
|
||||
connection.commit()
|
||||
assert database.with_name('state.db-wal').exists()
|
||||
assert database.with_name('state.db-shm').exists()
|
||||
assert manager.current_signature() == signature
|
||||
assert manager.load_runtime_config() is config
|
||||
|
||||
assert not database.with_name('state.db-wal').exists()
|
||||
assert not database.with_name('state.db-shm').exists()
|
||||
assert manager.current_signature() == signature
|
||||
|
||||
with closing(sqlite3.connect(database)) as connection:
|
||||
assert connection.execute('SELECT COUNT(*) FROM messages').fetchone()[0] == 2
|
||||
|
||||
|
||||
def test_signature_does_not_traverse_history_directory(signature_manager, monkeypatch):
|
||||
"""历史目录应在递归前排除,避免扫描持续增长且并发变化的用户数据。"""
|
||||
manager = signature_manager
|
||||
signature = manager._build_signature()
|
||||
history_root = manager.runtime_dir / 'history'
|
||||
(history_root / 'users' / 'test-user').mkdir(parents=True)
|
||||
original_scandir = os.scandir
|
||||
|
||||
def guarded_scandir(path):
|
||||
"""以文件系统边界断言扫描器没有进入历史目录。"""
|
||||
assert not Path(path).is_relative_to(history_root)
|
||||
return original_scandir(path)
|
||||
|
||||
monkeypatch.setattr(os, 'scandir', guarded_scandir)
|
||||
assert manager._build_signature() == signature
|
||||
|
||||
|
||||
@pytest.mark.parametrize('root_name', ['runtime_dir', 'bundled_defaults_dir'])
|
||||
def test_signature_tolerates_file_removed_after_type_check(signature_manager, monkeypatch, root_name):
|
||||
"""确定性复现文件类型检查成功、读取元数据前文件被并发删除的竞态。"""
|
||||
manager = signature_manager
|
||||
signature = manager._build_signature()
|
||||
transient = getattr(manager, root_name) / 'transient.md'
|
||||
transient.write_text('temporary context', encoding='utf-8')
|
||||
original_is_file = Path.is_file
|
||||
removed = []
|
||||
|
||||
def remove_after_type_check(path):
|
||||
"""在扫描器确认文件类型后删除文件,复现 Issue 中的消失时序。"""
|
||||
result = original_is_file(path)
|
||||
if path == transient and result:
|
||||
path.unlink()
|
||||
removed.append(path)
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(Path, 'is_file', remove_after_type_check)
|
||||
assert manager._build_signature() == signature
|
||||
assert removed == [transient]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('root_name', ['runtime_dir', 'bundled_defaults_dir'])
|
||||
@pytest.mark.parametrize('relative_path', [
|
||||
'CURRENT_PERSONA.md',
|
||||
'personas/default/PERSONA.md',
|
||||
'subagents/general-purpose/SUBAGENT.md',
|
||||
'extra/history/context.md',
|
||||
])
|
||||
def test_signature_tracks_configuration_changes(signature_manager, root_name, relative_path):
|
||||
"""排除历史数据库后,人格、子代理和任意额外上下文仍参与增改删检测。"""
|
||||
manager = signature_manager
|
||||
path = getattr(manager, root_name) / relative_path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.unlink(missing_ok=True)
|
||||
absent = manager._build_signature()
|
||||
path.write_text('context', encoding='utf-8')
|
||||
created = manager._build_signature()
|
||||
assert created != absent
|
||||
path.write_text('updated context', encoding='utf-8')
|
||||
updated = manager._build_signature()
|
||||
assert updated != created
|
||||
path.unlink()
|
||||
assert manager._build_signature() == absent
|
||||
|
||||
|
||||
def test_default_root_uses_runtime_settings_service(context):
|
||||
"""未显式传入目录时,管理器应读取组合根提供的配置目录。"""
|
||||
config_root = context.temp_root / 'configured'
|
||||
|
||||
Reference in New Issue
Block a user