From eb45ed6b777614d4149cb8843249bf2d7b36f189 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 28 Aug 2026 16:39:29 +0800 Subject: [PATCH] refactor(runtime): remove data service locators --- app/agent/memory/__init__.py | 42 +- app/agent/orchestrator.py | 158 ++++-- app/agent/tools/base.py | 29 +- app/agent/tools/factory.py | 140 ++--- app/agent/tools/impl/_filter_rule_utils.py | 20 +- app/agent/tools/impl/add_download_tasks.py | 3 +- app/agent/tools/impl/add_rule_group.py | 5 +- app/agent/tools/impl/add_subscribe.py | 3 +- app/agent/tools/impl/create_agent_task.py | 14 +- app/agent/tools/impl/delete_agent_task.py | 3 +- .../tools/impl/delete_download_history.py | 3 +- app/agent/tools/impl/delete_rule_group.py | 7 +- .../tools/impl/delete_transfer_history.py | 9 +- app/agent/tools/impl/query_agent_tasks.py | 12 +- app/agent/tools/impl/query_download_tasks.py | 31 +- app/agent/tools/impl/query_plugin_data.py | 15 +- app/agent/tools/impl/query_rule_groups.py | 7 +- app/agent/tools/impl/query_site_userdata.py | 3 +- app/agent/tools/impl/query_sites.py | 3 +- .../tools/impl/query_subscribe_history.py | 3 +- app/agent/tools/impl/query_subscribes.py | 3 +- .../tools/impl/query_transfer_history.py | 5 +- app/agent/tools/impl/run_agent_task.py | 3 +- app/agent/tools/impl/search_subscribe.py | 3 +- app/agent/tools/impl/test_site.py | 9 +- app/agent/tools/impl/update_agent_task.py | 22 +- app/agent/tools/impl/update_rule_group.py | 8 +- app/agent/tools/impl/update_site.py | 3 +- app/agent/tools/impl/update_site_cookie.py | 5 +- app/agent/tools/manager.py | 18 + app/api/dependencies/history.py | 8 + app/api/endpoints/history.py | 20 +- app/api/endpoints/transfer.py | 25 +- app/application/agent.py | 33 ++ app/application/agentdata.py | 178 ------ app/application/agenttask.py | 183 ++++-- app/application/chain/context.py | 24 +- app/application/chain/data.py | 146 ----- app/application/messaging/chat.py | 28 +- app/application/plugin/data.py | 16 +- app/chain/__init__.py | 9 + app/chain/_contracts.py | 8 +- app/chain/_messaging.py | 7 +- app/chain/_music.py | 9 +- app/chain/_transfer.py | 29 +- app/chain/download.py | 15 +- app/chain/interaction.py | 5 +- app/chain/mediaserver.py | 3 +- app/chain/site.py | 19 +- app/chain/subscribe.py | 78 +-- app/chain/torrents.py | 3 +- app/chain/transfer.py | 32 +- app/chain/user.py | 10 +- app/db/adapters/agent.py | 351 ++++++++++++ app/db/models/subscribehistory.py | 2 +- app/scheduler.py | 28 +- app/startup/composition/context.py | 4 + app/startup/initializers/agent.py | 47 +- app/startup/initializers/modules.py | 91 +-- app/startup/initializers/scheduler.py | 8 +- app/workflow/actions/add_subscribe.py | 3 +- app/workflow/actions/transfer_file.py | 3 +- docs/architecture-optimization-checklist.md | 16 +- docs/architecture-overview.md | 11 +- docs/architecture-refactor-roadmap.md | 8 +- docs/rules/05-architecture.md | 28 +- tests/conftest.py | 93 ++-- .../architecture/coverage-baseline.json | 6 +- .../architecture/dependency-baseline.json | 138 ++--- .../fixtures/architecture/mypy-baseline.json | 27 +- .../fixtures/architecture/ruff-baseline.json | 76 --- .../startup-performance-baseline.json | 274 ++++----- tests/test_agent_add_subscribe_tool.py | 47 +- tests/test_agent_data_ports.py | 254 ++++++++- tests/test_agent_lifecycle.py | 51 +- tests/test_agent_music_tools.py | 32 +- tests/test_agent_plugin_tools.py | 18 +- tests/test_agent_query_download_tasks_tool.py | 22 +- tests/test_agent_query_subscribes.py | 21 +- tests/test_agent_resource_flow_permissions.py | 67 +-- tests/test_agent_scheduled_tasks.py | 20 +- tests/test_agent_search_subscribe.py | 15 +- tests/test_agent_task_runs.py | 15 +- tests/test_architecture_dependencies.py | 525 +++++------------- tests/test_bluray.py | 21 +- tests/test_chain_rate_limit.py | 17 +- tests/test_chain_runtime_context.py | 41 +- tests/test_data_locator_architecture.py | 144 +++++ tests/test_delete_transfer_history_tool.py | 62 +-- tests/test_download_chain.py | 54 +- tests/test_history_ai_retry_gate.py | 30 +- tests/test_host_runtime_context.py | 15 + tests/test_manual_transfer_history.py | 23 +- tests/test_mediaserver_sync_incremental.py | 44 +- tests/test_music_download.py | 15 +- tests/test_music_subscribe.py | 45 +- tests/test_music_transfer.py | 11 +- tests/test_release_group.py | 7 +- tests/test_rule_group_media.py | 9 +- tests/test_site_architecture.py | 43 +- tests/test_slash_command_interactions.py | 24 +- tests/test_subscribe_chain.py | 162 +++--- tests/test_subscribe_files_info.py | 10 +- tests/test_subscribe_search_state.py | 14 +- tests/test_subscription_architecture.py | 43 +- tests/test_transfer_durable_retry_owner.py | 37 +- tests/test_transfer_failed_retry_buttons.py | 43 +- tests/test_transfer_job_manager.py | 89 +-- tests/test_transfer_legacy_terminal_compat.py | 21 +- tests/test_transfer_manual_review_api.py | 14 +- .../test_transfer_manual_review_discovery.py | 11 +- tests/test_transfer_movie_collection.py | 14 +- tests/test_transfer_overwrite_declined.py | 16 +- tests/test_transfer_planning_checkpoint.py | 22 +- tests/test_transfer_queue_service.py | 8 +- tests/test_transfer_sync_extra_files.py | 118 +--- tests/test_transfer_tmdb_category.py | 6 +- tests/test_workflow_runtime_config.py | 16 +- 118 files changed, 2646 insertions(+), 2381 deletions(-) delete mode 100644 app/application/agentdata.py delete mode 100644 app/application/chain/data.py create mode 100644 app/db/adapters/agent.py create mode 100644 tests/test_data_locator_architecture.py diff --git a/app/agent/memory/__init__.py b/app/agent/memory/__init__.py index 1ce19dde3..027ff1808 100644 --- a/app/agent/memory/__init__.py +++ b/app/agent/memory/__init__.py @@ -6,8 +6,9 @@ from typing import Dict, List, Optional from langchain_core.messages import BaseMessage, messages_from_dict, messages_to_dict -from app.application.agentdata import get_agent_chat_port from app.application.messaging.chat import ( + AgentChatPersistenceService, + AgentChatService, get_configured_agent_chat_persistence, get_configured_agent_chat_service, ) @@ -21,12 +22,36 @@ class MemoryManager: 对话记忆管理器 """ - def __init__(self): + def __init__( + self, + chat: AgentChatService | None = None, + persistence: AgentChatPersistenceService | None = None, + ): + """创建记忆缓存,并保存组合根显式注入的会话能力。""" + self._chat = chat + self._persistence = persistence # 内存中的会话记忆缓存 self.memory_cache: Dict[str, ConversationMemory] = {} # 内存缓存清理任务 self.cleanup_task: Optional[asyncio.Task] = None + def configure( + self, + chat: AgentChatService, + persistence: AgentChatPersistenceService, + ) -> None: + """在 Agent 启动前绑定唯一会话查询与写入服务。""" + self._chat = chat + self._persistence = persistence + + def _chat_service(self) -> AgentChatService: + """返回显式注入服务,兼容测试未装配时使用既有应用服务。""" + return self._chat or get_configured_agent_chat_service() + + def _chat_persistence(self) -> AgentChatPersistenceService: + """返回显式注入写服务,兼容测试未装配时使用既有应用服务。""" + return self._persistence or get_configured_agent_chat_persistence() + def initialize(self): """ 初始化记忆管理器 @@ -84,9 +109,12 @@ class MemoryManager: return memory.messages try: - chat = get_agent_chat_port().get(session_id=session_id, user_id=user_id) + chat = self._chat_service().get_sync( + session_id=session_id, + user_id=user_id, + ) if not chat: - chat = get_agent_chat_port().get(session_id=session_id) + chat = self._chat_service().get_sync(session_id=session_id) except Exception as e: logger.debug(f"读取持久化Agent会话失败: {e}") return [] @@ -116,7 +144,7 @@ class MemoryManager: return memory.messages try: - service = get_configured_agent_chat_service() + service = self._chat_service() chat = await service.get( session_id=session_id, user_id=user_id, @@ -159,7 +187,7 @@ class MemoryManager: # 更新内存缓存 self.save_memory(memory) try: - get_agent_chat_port().save_agent_messages( + self._chat_service().save_agent_messages( session_id=session_id, user_id=user_id, messages=messages_to_dict(messages), @@ -179,7 +207,7 @@ class MemoryManager: memory.updated_at = datetime.now() self.save_memory(memory) try: - persistence = get_configured_agent_chat_persistence() + persistence = self._chat_persistence() await persistence.async_save_agent_messages( session_id=session_id, user_id=user_id, diff --git a/app/agent/orchestrator.py b/app/agent/orchestrator.py index b2b1ef0b1..0a45d1ca5 100644 --- a/app/agent/orchestrator.py +++ b/app/agent/orchestrator.py @@ -13,22 +13,21 @@ from typing import Any, Awaitable, Callable, Dict, List, Optional from langchain.agents import create_agent from langchain_core.messages import ( # noqa: F401 - HumanMessage, BaseMessage, + HumanMessage, SystemMessage, ) - from langgraph.checkpoint.memory import InMemorySaver -from app.runtime.execution import run_in_threadpool from app.agent.callback import StreamingHandler from app.agent.contracts import ReplyMode, build_display_message from app.agent.llm.helper import LLMHelper from app.agent.llm.server_tools import ServerToolRegistry -from app.agent.memory import memory_manager +from app.agent.mcp import agent_mcp_manager +from app.agent.memory import MemoryManager, memory_manager from app.agent.middleware.activity_log import ( - ActivityLogMiddleware, QUERY_ACTIVITY_LOG_TOOL_NAME, + ActivityLogMiddleware, ) from app.agent.middleware.jobs import ( JobsMiddleware, @@ -40,59 +39,58 @@ from app.agent.middleware.patch_tool_calls import PatchToolCallsMiddleware from app.agent.middleware.policy import AgentPolicyMiddleware from app.agent.middleware.runtime_config import RuntimeConfigMiddleware from app.agent.middleware.skills import SKILL_TOOL_NAME, SkillsMiddleware -from app.agent.middleware.summarization import ( - ContextPreservingSummarizationMiddleware as SummarizationMiddleware, - FinalRequestCompactionMiddleware, -) from app.agent.middleware.subagents import ( SUBAGENT_CONTROL_TOOL_NAME, SUBAGENT_TASK_TOOL_NAME, create_subagent_middlewares, is_subagent_stream_metadata, ) +from app.agent.middleware.summarization import ( + ContextPreservingSummarizationMiddleware as SummarizationMiddleware, +) +from app.agent.middleware.summarization import ( + FinalRequestCompactionMiddleware, +) from app.agent.middleware.tool_selection import ToolSelectorMiddleware from app.agent.middleware.usage import UsageMiddleware -from app.agent.prompt import prompt_manager from app.agent.policy.contracts import ( AuthSource, PrincipalType, ToolOrigin, ToolPolicyContext, ) +from app.agent.prompt import prompt_manager from app.agent.runtime import agent_runtime_manager -from app.agent.mcp import agent_mcp_manager from app.agent.tools.catalog import ToolCatalogSnapshot from app.agent.tools.impl.mcp import ( create_external_mcp_tools, select_legacy_mcp_tools, ) from app.agent.tools.impl.query_system_settings import QuerySystemSettingsTool -from app.chain.agent import AgentChain -from app.runtime.settings import get_runtime_setting - -from app.runtime.events import eventmanager -from app.runtime.observability import record_metric +from app.application.agent import AgentDataContext +from app.application.agenttask import get_agent_task_execution_service +from app.application.messaging.chat import ( + get_configured_agent_chat_persistence, + get_configured_agent_chat_service, + has_custom_agent_chat_title, +) from app.application.plugin.runtime import get_plugin_manager +from app.chain.agent import AgentChain +from app.foundation.identity import SYSTEM_INTERNAL_USER_ID +from app.runtime.events import eventmanager +from app.runtime.execution import run_in_threadpool +from app.runtime.log import logger +from app.runtime.observability import record_metric +from app.runtime.settings import get_runtime_setting +from app.schemas.event import AgentLLMProviderEventData, AgentTokensUsageEventData +from app.schemas.message import Message, MessageType +from app.schemas.notification import ChannelCapability, ChannelCapabilityManager +from app.schemas.types import ChainEventType, EventType, NotificationChannel def _get_plugin_tools_revision() -> int: """读取插件工具目录修订号,避免 Agent 编排依赖具体管理器类型。""" return get_plugin_manager().get_plugin_agent_tools_revision() -from app.application.agenttask import get_agent_task_execution_service -from app.application.agentdata import get_agent_user_port -from app.application.messaging.chat import ( - get_configured_agent_chat_service, - get_configured_agent_chat_persistence, - has_custom_agent_chat_title, -) -from app.runtime.log import logger -from app.schemas.event import AgentLLMProviderEventData -from app.schemas.event import AgentTokensUsageEventData -from app.schemas.message import Message -from app.schemas.message import MessageType -from app.schemas.notification import ChannelCapabilityManager, ChannelCapability -from app.schemas.types import ChainEventType, EventType, NotificationChannel -from app.foundation.identity import SYSTEM_INTERNAL_USER_ID warnings.filterwarnings("ignore", message=".*allowed_objects.*") @@ -412,7 +410,10 @@ class MoviePilotAgent: allow_message_tools: bool = True, output_callback: Optional[Callable[[str], None]] = None, protected_output_callback: Optional[Callable[[str], Optional[bool]]] = None, + data: Optional[AgentDataContext] = None, + memory: Optional[MemoryManager] = None, ): + """创建会话 Agent,并保存组合根注入的数据与记忆能力。""" self.session_id = session_id self.user_id = user_id self.channel = channel @@ -425,6 +426,8 @@ class MoviePilotAgent: self.allow_message_tools = allow_message_tools self.output_callback = output_callback self.protected_output_callback = protected_output_callback + self._data = data + self._memory = memory or memory_manager self._tool_context: Dict[str, object] = {} self._pending_secret_confirmation: Optional[_PendingSecretConfirmation] = None self._streamed_output = "" @@ -976,7 +979,9 @@ class MoviePilotAgent: if not self.username: return False try: - user = await get_agent_user_port().async_get_by_name(self.username) + if self._data is None: + return False + user = await self._data.users.async_get_by_name(self.username) except Exception as e: logger.error(f"检查 Agent 用户管理员身份失败: {e}") return False @@ -1620,6 +1625,7 @@ class MoviePilotAgent: stream_handler=self.stream_handler, agent_context=self._tool_context, allow_message_tools=self.allow_message_tools, + data=self._data, ) def _initialize_local_tool_catalogs( @@ -1880,6 +1886,7 @@ class MoviePilotAgent: "require_secret_confirmation": True, }, allow_message_tools=False, + data=self._data, ) async def _initialize_mcp_tools(self, specs=None) -> List: @@ -2228,7 +2235,7 @@ class MoviePilotAgent: # 获取历史消息 messages = list( - await memory_manager.async_get_agent_messages( + await self._memory.async_get_agent_messages( session_id=self.session_id, user_id=self.user_id, ) @@ -2526,7 +2533,7 @@ class MoviePilotAgent: await self._save_assistant_display_message_once(display_text) if self._should_persist_agent_chat(): - await memory_manager.async_save_agent_messages( + await self._memory.async_save_agent_messages( session_id=self.session_id, user_id=self.user_id, messages=agent.get_state(agent_config).values.get("messages", []), @@ -2672,7 +2679,16 @@ class AgentManager: 同一会话的消息按顺序排队处理,不同会话之间互不影响。 """ - def __init__(self): + def __init__( + self, + data: Optional[AgentDataContext] = None, + memory: Optional[MemoryManager] = None, + ) -> None: + """创建管理器,并保存组合根注入的 Agent 数据与记忆能力。""" + self._data = data + self._memory = memory or memory_manager + if data is not None: + self._memory.configure(data.chat, data.chat_persistence) self.active_agents: Dict[str, MoviePilotAgent] = {} # 每个会话的消息队列 self._session_queues: Dict[str, asyncio.Queue] = {} @@ -2696,6 +2712,15 @@ class AgentManager: self._lifecycle_lock = asyncio.Lock() self._accepting_tasks = False + def configure_data_context(self, data: AgentDataContext) -> None: + """在服务启动前绑定唯一数据上下文并配置记忆服务。""" + if self._data is data: + return + if self._accepting_tasks or self.active_agents: + raise RuntimeError("AgentManager 已运行,不能替换数据上下文") + self._data = data + self._memory.configure(data.chat, data.chat_persistence) + def get_session_status(self, session_id: str) -> dict[str, Any]: """获取会话当前模型与 token 使用状态。""" agent = self.active_agents.get(session_id) @@ -2760,7 +2785,7 @@ class AgentManager: return if self._close_finalizer_task and not self._close_finalizer_task.done(): raise AgentManagerUnavailableError("AgentManager 仍在完成上一代关闭") - memory_manager.initialize() + self._memory.initialize() if not self._idle_cleanup_task or self._idle_cleanup_task.done(): self._idle_cleanup_task = asyncio.create_task( self._cleanup_idle_sessions() @@ -2848,7 +2873,7 @@ class AgentManager: len(self.active_agents), ) return False - await memory_manager.close() + await self._memory.close() self._closed = True return True @@ -3170,24 +3195,41 @@ class AgentManager: logger.info( f"创建新的AI智能体实例,session_id: {session_id}, user_id: {task.user_id}" ) - agent_factory = task.agent_factory or MoviePilotAgent - agent_kwargs = { - "session_id": session_id, - "user_id": task.user_id, - "channel": task.channel, - "source": task.source, - "username": task.username, - "is_channel_admin": task.is_channel_admin, - "original_message_id": task.original_message_id, - "original_chat_id": task.original_chat_id, - "replay_mode": task.reply_mode, - "allow_message_tools": task.allow_message_tools, - "output_callback": task.output_callback, - "protected_output_callback": task.protected_output_callback, - } - if task.message_callback is not None and task.agent_factory: - agent_kwargs["message_callback"] = task.message_callback - agent = agent_factory(**agent_kwargs) + if task.agent_factory is None: + agent = MoviePilotAgent( + session_id=session_id, + user_id=task.user_id, + channel=task.channel, + source=task.source, + username=task.username, + is_channel_admin=task.is_channel_admin, + original_message_id=task.original_message_id, + original_chat_id=task.original_chat_id, + replay_mode=task.reply_mode, + allow_message_tools=task.allow_message_tools, + output_callback=task.output_callback, + protected_output_callback=task.protected_output_callback, + data=self._data, + memory=self._memory, + ) + else: + agent_kwargs = { + "session_id": session_id, + "user_id": task.user_id, + "channel": task.channel, + "source": task.source, + "username": task.username, + "is_channel_admin": task.is_channel_admin, + "original_message_id": task.original_message_id, + "original_chat_id": task.original_chat_id, + "replay_mode": task.reply_mode, + "allow_message_tools": task.allow_message_tools, + "output_callback": task.output_callback, + "protected_output_callback": task.protected_output_callback, + } + if task.message_callback is not None: + agent_kwargs["message_callback"] = task.message_callback + agent = task.agent_factory(**agent_kwargs) self.active_agents[session_id] = agent else: agent = self.active_agents[session_id] @@ -3341,7 +3383,7 @@ class AgentManager: ) return del self.active_agents[session_id] - memory_manager.clear_memory(session_id, user_id) + self._memory.clear_memory(session_id, user_id) logger.info(f"会话 {session_id} 的记忆已清空") def _defer_session_cleanup( @@ -3410,7 +3452,7 @@ class AgentManager: ) return self.active_agents.pop(session_id, None) - memory_manager.clear_memory(session_id, user_id) + self._memory.clear_memory(session_id, user_id) logger.info(f"会话 {session_id} 的记忆已清空") async def _finish_deferred_close( @@ -3438,7 +3480,7 @@ class AgentManager: len(self.active_agents), ) return - await memory_manager.close() + await self._memory.close() self._closed = True finally: self._close_finalizer_task = None diff --git a/app/agent/tools/base.py b/app/agent/tools/base.py index 542b18a30..2c77f1277 100644 --- a/app/agent/tools/base.py +++ b/app/agent/tools/base.py @@ -3,7 +3,8 @@ import inspect import json import threading from abc import ABCMeta, abstractmethod -from concurrent.futures import Future as ConcurrentFuture, ThreadPoolExecutor +from concurrent.futures import Future as ConcurrentFuture +from concurrent.futures import ThreadPoolExecutor from contextvars import Context, copy_context from functools import partial from pathlib import Path @@ -18,14 +19,14 @@ from app.agent.policy.sanitizer import ( summarize_result, ) from app.agent.tools.tags import ToolTag -from app.chain import ChainBase -from app.runtime.settings import get_runtime_setting - +from app.application.agent import AgentDataContext from app.application.messaging.agent import matches_channel_admin from app.application.notification import get_notification_configs +from app.chain import ChainBase from app.runtime.log import logger +from app.runtime.settings import get_runtime_setting from app.schemas.message import Message -from app.schemas.types import NotificationChannel, MessageType +from app.schemas.types import MessageType, NotificationChannel if TYPE_CHECKING: from app.agent.callback import StreamingHandler as _StreamingHandlerProtocol @@ -356,17 +357,33 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta): _stream_handler: Optional[_StreamingHandlerProtocol] = PrivateAttr(default=None) _require_admin: bool = PrivateAttr(default=False) _agent_context: dict = PrivateAttr(default_factory=dict) + _data: Optional[AgentDataContext] = PrivateAttr(default=None) - def __init__(self, session_id: str, user_id: str, **kwargs): + def __init__( + self, + session_id: str, + user_id: str, + data: Optional[AgentDataContext] = None, + **kwargs, + ): + """保存会话身份及组合根注入的 Agent 数据上下文。""" super().__init__(**kwargs) self._session_id = session_id self._user_id = user_id + self._data = data # require_admin 在各工具子类以 pydantic 字段声明,pydantic v2 不在类对象上暴露字段值 # (getattr(cls, ...) 取不到),必须经实例读取——super().__init__() 已按字段默认填充实例; # getattr 兜底兼容未声明该字段的工具,缺省按非管理员(False)处理。 self._require_admin = getattr(self, "require_admin", False) self.tags = self._build_tool_tags() + @property + def data(self) -> AgentDataContext: + """返回工具数据上下文;未装配时稳定失败而非回退全局 locator。""" + if self._data is None: + raise RuntimeError("Agent 工具数据上下文尚未注入") + return self._data + @staticmethod def _normalize_tag_values(tags: Optional[Any]) -> set[str]: """规范化 LangChain 工具标签。""" diff --git a/app/agent/tools/factory.py b/app/agent/tools/factory.py index 62036edda..7c68df2ba 100644 --- a/app/agent/tools/factory.py +++ b/app/agent/tools/factory.py @@ -1,97 +1,98 @@ import hashlib - from typing import Callable, List, Optional, Type +from app.agent.llm.capability import AgentCapabilityManager +from app.agent.tools.impl.add_custom_filter_rule import AddCustomFilterRuleTool from app.agent.tools.impl.add_download_tasks import AddDownloadTasksTool +from app.agent.tools.impl.add_rule_group import AddRuleGroupTool from app.agent.tools.impl.add_subscribe import AddSubscribeTool -from app.agent.tools.impl.update_subscribe import UpdateSubscribeTool -from app.agent.tools.impl.search_subscribe import SearchSubscribeTool +from app.agent.tools.impl.apply_patch import ApplyPatchTool +from app.agent.tools.impl.ask_user_choice import AskUserChoiceTool +from app.agent.tools.impl.browse_webpage import BrowseWebpageTool +from app.agent.tools.impl.create_agent_task import CreateAgentTaskTool +from app.agent.tools.impl.delete_agent_task import DeleteAgentTaskTool +from app.agent.tools.impl.delete_custom_filter_rule import DeleteCustomFilterRuleTool +from app.agent.tools.impl.delete_download_history import DeleteDownloadHistoryTool +from app.agent.tools.impl.delete_download_tasks import DeleteDownloadTasksTool +from app.agent.tools.impl.delete_rule_group import DeleteRuleGroupTool +from app.agent.tools.impl.delete_subscribe import DeleteSubscribeTool +from app.agent.tools.impl.delete_transfer_history import DeleteTransferHistoryTool +from app.agent.tools.impl.edit_file import EditFileTool +from app.agent.tools.impl.execute_command import ExecuteCommandTool from app.agent.tools.impl.get_recommendations import GetRecommendationsTool -from app.agent.tools.impl.query_downloaders import QueryDownloadersTool -from app.agent.tools.impl.query_download_tasks import QueryDownloadTasksTool -from app.agent.tools.impl.query_library_exists import QueryLibraryExistsTool -from app.agent.tools.impl.query_library_latest import QueryLibraryLatestTool -from app.agent.tools.impl.query_sites import QuerySitesTool -from app.agent.tools.impl.update_site import UpdateSiteTool -from app.agent.tools.impl.query_site_userdata import QuerySiteUserdataTool -from app.agent.tools.impl.test_site import TestSiteTool -from app.agent.tools.impl.query_subscribes import QuerySubscribesTool -from app.agent.tools.impl.query_subscribe_shares import QuerySubscribeSharesTool -from app.agent.tools.impl.query_rule_groups import QueryRuleGroupsTool +from app.agent.tools.impl.get_search_results import GetSearchResultsTool +from app.agent.tools.impl.install_plugin import InstallPluginTool +from app.agent.tools.impl.list_directory import ListDirectoryTool +from app.agent.tools.impl.list_slash_commands import ListSlashCommandsTool +from app.agent.tools.impl.query_agent_tasks import QueryAgentTasksTool from app.agent.tools.impl.query_builtin_filter_rules import QueryBuiltinFilterRulesTool from app.agent.tools.impl.query_custom_filter_rules import QueryCustomFilterRulesTool -from app.agent.tools.impl.add_custom_filter_rule import AddCustomFilterRuleTool -from app.agent.tools.impl.update_custom_filter_rule import UpdateCustomFilterRuleTool -from app.agent.tools.impl.delete_custom_filter_rule import DeleteCustomFilterRuleTool -from app.agent.tools.impl.add_rule_group import AddRuleGroupTool -from app.agent.tools.impl.update_rule_group import UpdateRuleGroupTool -from app.agent.tools.impl.delete_rule_group import DeleteRuleGroupTool +from app.agent.tools.impl.query_custom_identifiers import QueryCustomIdentifiersTool +from app.agent.tools.impl.query_directory_settings import QueryDirectorySettingsTool +from app.agent.tools.impl.query_doctor_report import QueryDoctorReportTool +from app.agent.tools.impl.query_download_tasks import QueryDownloadTasksTool +from app.agent.tools.impl.query_downloaders import QueryDownloadersTool +from app.agent.tools.impl.query_episode_schedule import QueryEpisodeScheduleTool +from app.agent.tools.impl.query_installed_plugins import QueryInstalledPluginsTool +from app.agent.tools.impl.query_library_exists import QueryLibraryExistsTool +from app.agent.tools.impl.query_library_latest import QueryLibraryLatestTool +from app.agent.tools.impl.query_market_plugins import QueryMarketPluginsTool +from app.agent.tools.impl.query_media_detail import QueryMediaDetailTool +from app.agent.tools.impl.query_personas import QueryPersonasTool +from app.agent.tools.impl.query_plugin_capabilities import QueryPluginCapabilitiesTool +from app.agent.tools.impl.query_plugin_config import QueryPluginConfigTool +from app.agent.tools.impl.query_plugin_data import QueryPluginDataTool from app.agent.tools.impl.query_popular_subscribes import QueryPopularSubscribesTool +from app.agent.tools.impl.query_rule_groups import QueryRuleGroupsTool +from app.agent.tools.impl.query_schedulers import QuerySchedulersTool +from app.agent.tools.impl.query_site_userdata import QuerySiteUserdataTool +from app.agent.tools.impl.query_sites import QuerySitesTool from app.agent.tools.impl.query_subscribe_history import QuerySubscribeHistoryTool -from app.agent.tools.impl.delete_subscribe import DeleteSubscribeTool +from app.agent.tools.impl.query_subscribe_shares import QuerySubscribeSharesTool +from app.agent.tools.impl.query_subscribes import QuerySubscribesTool +from app.agent.tools.impl.query_system_settings import QuerySystemSettingsTool +from app.agent.tools.impl.query_transfer_history import QueryTransferHistoryTool +from app.agent.tools.impl.query_workflows import QueryWorkflowsTool +from app.agent.tools.impl.read_file import ReadFileTool +from app.agent.tools.impl.recognize_captcha import RecognizeCaptchaTool +from app.agent.tools.impl.recognize_media import RecognizeMediaTool +from app.agent.tools.impl.reload_plugin import ReloadPluginTool +from app.agent.tools.impl.run_agent_task import RunAgentTaskTool +from app.agent.tools.impl.run_scheduler import RunSchedulerTool +from app.agent.tools.impl.run_slash_command import RunSlashCommandTool +from app.agent.tools.impl.run_workflow import RunWorkflowTool +from app.agent.tools.impl.scrape_metadata import ScrapeMetadataTool from app.agent.tools.impl.search_media import SearchMediaTool from app.agent.tools.impl.search_person import SearchPersonTool from app.agent.tools.impl.search_person_credits import SearchPersonCreditsTool -from app.agent.tools.impl.recognize_media import RecognizeMediaTool -from app.agent.tools.impl.scrape_metadata import ScrapeMetadataTool -from app.agent.tools.impl.query_episode_schedule import QueryEpisodeScheduleTool -from app.agent.tools.impl.query_media_detail import QueryMediaDetailTool +from app.agent.tools.impl.search_subscribe import SearchSubscribeTool from app.agent.tools.impl.search_torrents import SearchTorrentsTool -from app.agent.tools.impl.get_search_results import GetSearchResultsTool from app.agent.tools.impl.search_web import SearchWebTool -from app.agent.tools.impl.recognize_captcha import RecognizeCaptchaTool -from app.agent.tools.impl.send_message import SendMessageTool -from app.agent.tools.impl.ask_user_choice import AskUserChoiceTool from app.agent.tools.impl.send_local_file import SendLocalFileTool +from app.agent.tools.impl.send_message import SendMessageTool from app.agent.tools.impl.send_voice_message import SendVoiceMessageTool -from app.agent.tools.impl.create_agent_task import CreateAgentTaskTool -from app.agent.tools.impl.delete_agent_task import DeleteAgentTaskTool -from app.agent.tools.impl.query_agent_tasks import QueryAgentTasksTool -from app.agent.tools.impl.query_schedulers import QuerySchedulersTool -from app.agent.tools.impl.run_agent_task import RunAgentTaskTool -from app.agent.tools.impl.run_scheduler import RunSchedulerTool -from app.agent.tools.impl.update_agent_task import UpdateAgentTaskTool -from app.agent.tools.impl.query_workflows import QueryWorkflowsTool -from app.agent.tools.impl.run_workflow import RunWorkflowTool -from app.agent.tools.impl.query_personas import QueryPersonasTool from app.agent.tools.impl.switch_persona import SwitchPersonaTool -from app.agent.tools.impl.update_persona_definition import UpdatePersonaDefinitionTool -from app.agent.tools.impl.update_site_cookie import UpdateSiteCookieTool -from app.agent.tools.impl.delete_download_tasks import DeleteDownloadTasksTool -from app.agent.tools.impl.delete_download_history import DeleteDownloadHistoryTool -from app.agent.tools.impl.delete_transfer_history import DeleteTransferHistoryTool -from app.agent.tools.impl.update_download_tasks import UpdateDownloadTasksTool -from app.agent.tools.impl.query_directory_settings import QueryDirectorySettingsTool -from app.agent.tools.impl.list_directory import ListDirectoryTool -from app.agent.tools.impl.query_transfer_history import QueryTransferHistoryTool +from app.agent.tools.impl.test_site import TestSiteTool from app.agent.tools.impl.transfer_file import TransferFileTool -from app.agent.tools.impl.execute_command import ExecuteCommandTool -from app.agent.tools.impl.apply_patch import ApplyPatchTool -from app.agent.tools.impl.edit_file import EditFileTool -from app.agent.tools.impl.write_file import WriteFileTool -from app.agent.tools.impl.read_file import ReadFileTool -from app.agent.tools.impl.browse_webpage import BrowseWebpageTool -from app.agent.tools.impl.query_installed_plugins import QueryInstalledPluginsTool -from app.agent.tools.impl.query_market_plugins import QueryMarketPluginsTool -from app.agent.tools.impl.query_plugin_capabilities import QueryPluginCapabilitiesTool -from app.agent.tools.impl.query_plugin_config import QueryPluginConfigTool -from app.agent.tools.impl.update_plugin_config import UpdatePluginConfigTool -from app.agent.tools.impl.reload_plugin import ReloadPluginTool -from app.agent.tools.impl.query_plugin_data import QueryPluginDataTool -from app.agent.tools.impl.install_plugin import InstallPluginTool from app.agent.tools.impl.uninstall_plugin import UninstallPluginTool -from app.agent.tools.impl.run_slash_command import RunSlashCommandTool -from app.agent.tools.impl.list_slash_commands import ListSlashCommandsTool -from app.agent.tools.impl.query_custom_identifiers import QueryCustomIdentifiersTool -from app.agent.tools.impl.query_doctor_report import QueryDoctorReportTool +from app.agent.tools.impl.update_agent_task import UpdateAgentTaskTool +from app.agent.tools.impl.update_custom_filter_rule import UpdateCustomFilterRuleTool from app.agent.tools.impl.update_custom_identifiers import UpdateCustomIdentifiersTool -from app.agent.tools.impl.query_system_settings import QuerySystemSettingsTool +from app.agent.tools.impl.update_download_tasks import UpdateDownloadTasksTool +from app.agent.tools.impl.update_persona_definition import UpdatePersonaDefinitionTool +from app.agent.tools.impl.update_plugin_config import UpdatePluginConfigTool +from app.agent.tools.impl.update_rule_group import UpdateRuleGroupTool +from app.agent.tools.impl.update_site import UpdateSiteTool +from app.agent.tools.impl.update_site_cookie import UpdateSiteCookieTool +from app.agent.tools.impl.update_subscribe import UpdateSubscribeTool from app.agent.tools.impl.update_system_settings import UpdateSystemSettingsTool -from app.agent.llm.capability import AgentCapabilityManager +from app.agent.tools.impl.write_file import WriteFileTool +from app.application.agent import AgentDataContext from app.application.plugin.runtime import get_plugin_manager from app.runtime.log import logger from app.schemas.notification import ChannelCapabilityManager from app.schemas.types import NotificationChannel + from .base import MoviePilotTool from .catalog import ToolCatalogError, ToolCatalogSnapshot @@ -281,6 +282,7 @@ class MoviePilotToolFactory: stream_handler: Callable = None, agent_context: dict = None, allow_message_tools: bool = True, + data: Optional[AgentDataContext] = None, ) -> List[MoviePilotTool]: """ 创建MoviePilot工具列表 @@ -289,7 +291,7 @@ class MoviePilotToolFactory: tool_definitions = cls._get_builtin_tool_classes(channel) # 创建内置工具 for ToolClass in tool_definitions: - tool = ToolClass(session_id=session_id, user_id=user_id) + tool = ToolClass(session_id=session_id, user_id=user_id, data=data) if not allow_message_tools and getattr(tool, "sends_message", False): continue tool.set_message_attr(channel=channel, source=source, username=username) diff --git a/app/agent/tools/impl/_filter_rule_utils.py b/app/agent/tools/impl/_filter_rule_utils.py index d03dfb491..dd9665f06 100644 --- a/app/agent/tools/impl/_filter_rule_utils.py +++ b/app/agent/tools/impl/_filter_rule_utils.py @@ -4,7 +4,6 @@ import copy import re from typing import Any, Callable, Dict, Iterable, Optional -from app.application.agentdata import get_agent_subscribe_port from app.application.configuration import get_configured_system_config from app.application.rules import ( BUILTIN_RULE_SET, @@ -12,6 +11,7 @@ from app.application.rules import ( RuleParser, replace_group_name_in_list, ) +from app.application.subscription.contract import SubscriptionRepository from app.runtime.events import eventmanager from app.schemas.event import ConfigChangeEventData from app.schemas.rule import CustomRule @@ -252,6 +252,7 @@ def default_rule_group_usage() -> dict: async def collect_rule_group_usages( + repository: SubscriptionRepository, group_names: Optional[Iterable[str]] = None, ) -> Dict[str, dict]: """收集规则组在全局配置和订阅上的引用情况。""" @@ -289,7 +290,7 @@ async def collect_rule_group_usages( continue ensure_usage(name)["used_in_global_best_version"] = True - subscribes = await get_agent_subscribe_port().async_list() + subscribes = await repository.async_list() for subscribe in subscribes: filter_groups = [str(name) for name in subscribe.filter_groups] \ if isinstance(subscribe.filter_groups, list) else [] @@ -456,6 +457,7 @@ async def _publish_rule_config_changed( async def _rewrite_rule_group_references( + repository: SubscriptionRepository, map_names: Callable[[Iterable[str]], list[str]], ) -> dict: """按名称映射器更新全局、默认订阅配置和已有订阅引用。""" @@ -490,7 +492,6 @@ async def _rewrite_rule_group_references( await save_system_config(config_key, updated) changed["global_settings"][config_key.value] = updated - repository = get_agent_subscribe_port() subscribes = await repository.async_list() for subscribe in subscribes: original = [str(name) for name in subscribe.filter_groups] \ @@ -511,16 +512,25 @@ async def _rewrite_rule_group_references( return changed -async def rename_rule_group_references(old_name: str, new_name: str) -> dict: +async def rename_rule_group_references( + repository: SubscriptionRepository, + old_name: str, + new_name: str, +) -> dict: """规则组改名后,联动更新全部配置和已有订阅引用。""" return await _rewrite_rule_group_references( + repository, lambda values: replace_group_name_in_list(values, old_name, new_name) ) -async def remove_rule_group_references(group_name: str) -> dict: +async def remove_rule_group_references( + repository: SubscriptionRepository, + group_name: str, +) -> dict: """删除规则组后,清理全部配置和已有订阅中的悬空引用。""" return await _rewrite_rule_group_references( + repository, lambda values: [value for value in values or [] if value != group_name] ) diff --git a/app/agent/tools/impl/add_download_tasks.py b/app/agent/tools/impl/add_download_tasks.py index 83032f8ec..ff6059880 100644 --- a/app/agent/tools/impl/add_download_tasks.py +++ b/app/agent/tools/impl/add_download_tasks.py @@ -9,7 +9,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_site_port from app.application.directory import DirectoryHelper, validate_download_save_path from app.chain.download import DownloadChain from app.chain.media import MediaChain @@ -275,7 +274,7 @@ class AddDownloadTasksTool(MoviePilotTool): failed_messages.append(f"{torrent_input} 缺少站点名称") continue - siteinfo = await get_agent_site_port().async_get_by_name(site_name) + siteinfo = await self.data.sites.async_get_by_name(site_name) if not siteinfo: failed_messages.append(f"{torrent_input} 未找到站点信息 {site_name}") continue diff --git a/app/agent/tools/impl/add_rule_group.py b/app/agent/tools/impl/add_rule_group.py index 23e8b28e7..611ff2884 100644 --- a/app/agent/tools/impl/add_rule_group.py +++ b/app/agent/tools/impl/add_rule_group.py @@ -92,7 +92,10 @@ class AddRuleGroupTool(MoviePilotTool): SystemConfigKey.UserFilterRuleGroups, [group.model_dump(exclude_none=True) for group in rule_groups], ) - usage = await collect_rule_group_usages([new_group.name]) + usage = await collect_rule_group_usages( + self.data.subscriptions, + [new_group.name], + ) return json.dumps( { diff --git a/app/agent/tools/impl/add_subscribe.py b/app/agent/tools/impl/add_subscribe.py index d178046e8..a13eacd65 100644 --- a/app/agent/tools/impl/add_subscribe.py +++ b/app/agent/tools/impl/add_subscribe.py @@ -6,7 +6,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_user_port from app.chain.subscribe import SubscribeChain from app.domain.media import normalize_music_type from app.runtime.log import logger @@ -154,7 +153,7 @@ class AddSubscribeTool(MoviePilotTool): mapped_username = await self.run_blocking( "db", - get_agent_user_port().find_name_by_bindings, + self.data.users.find_name_by_bindings, {key: self._user_id for key in binding_keys}, ) return mapped_username or resolved_username diff --git a/app/agent/tools/impl/create_agent_task.py b/app/agent/tools/impl/create_agent_task.py index f60356fa5..ed6787468 100644 --- a/app/agent/tools/impl/create_agent_task.py +++ b/app/agent/tools/impl/create_agent_task.py @@ -7,11 +7,9 @@ from pydantic import BaseModel, Field, model_validator from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.runtime.settings import get_runtime_setting - -from app.application.agentdata import get_agent_chat_port -from app.application.agentdata import get_agent_task_port +from app.application.agenttask import agent_task_to_dict from app.runtime.scheduling import TimerUtils +from app.runtime.settings import get_runtime_setting class CreateAgentTaskInput(BaseModel): @@ -114,11 +112,11 @@ class CreateAgentTaskTool(MoviePilotTool): timezone_name=get_runtime_setting('TZ'), require_future=True, ) - chat = get_agent_chat_port().get( + chat = self.data.chat.get_sync( session_id=self._session_id, user_id=self._user_id, ) - task = get_agent_task_port().add( + task = self.data.tasks.add( name=payload.name.strip(), content=payload.content.strip(), trigger_type=payload.trigger_type, @@ -131,8 +129,10 @@ class CreateAgentTaskTool(MoviePilotTool): source=self._source or (chat.source if chat else None), original_chat_id=chat.original_chat_id if chat else None, ) + if task is None: + raise RuntimeError("Agent 定时任务创建后无法读取") next_run_at = update_agent_task_job(task.id) - return get_agent_task_port().to_dict( + return agent_task_to_dict( task, next_run_at=next_run_at, timezone=get_runtime_setting('TZ'), diff --git a/app/agent/tools/impl/delete_agent_task.py b/app/agent/tools/impl/delete_agent_task.py index 0c5396a1b..caec6df34 100644 --- a/app/agent/tools/impl/delete_agent_task.py +++ b/app/agent/tools/impl/delete_agent_task.py @@ -4,7 +4,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_task_port class DeleteAgentTaskInput(BaseModel): @@ -33,7 +32,7 @@ class DeleteAgentTaskTool(MoviePilotTool): """删除当前用户的任务并移除运行时调度。""" from app.application.scheduling import remove_agent_task_job - deleted = get_agent_task_port().delete( + deleted = self.data.tasks.delete( task_id=task_id, user_id=str(self._user_id), ) diff --git a/app/agent/tools/impl/delete_download_history.py b/app/agent/tools/impl/delete_download_history.py index abfdc131c..d17c094ef 100644 --- a/app/agent/tools/impl/delete_download_history.py +++ b/app/agent/tools/impl/delete_download_history.py @@ -6,7 +6,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_download_history_port from app.runtime.log import logger @@ -37,7 +36,7 @@ class DeleteDownloadHistoryTool(MoviePilotTool): logger.info(f"执行工具: {self.name}, 参数: history_id={history_id}") try: - await get_agent_download_history_port().async_delete(history_id) + await self.data.download_history.async_delete(history_id) return f"下载历史记录 ID: {history_id} 已成功删除" except Exception as e: logger.error(f"删除下载历史记录失败: {e}", exc_info=True) diff --git a/app/agent/tools/impl/delete_rule_group.py b/app/agent/tools/impl/delete_rule_group.py index 77944251f..559e86362 100644 --- a/app/agent/tools/impl/delete_rule_group.py +++ b/app/agent/tools/impl/delete_rule_group.py @@ -6,12 +6,12 @@ from typing import Optional, Type from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool -from app.agent.tools.tags import ToolTag from app.agent.tools.impl._filter_rule_utils import ( get_rule_groups, remove_rule_group_references, save_system_config, ) +from app.agent.tools.tags import ToolTag from app.runtime.log import logger from app.schemas.types import SystemConfigKey @@ -60,7 +60,10 @@ class DeleteRuleGroupTool(MoviePilotTool): SystemConfigKey.UserFilterRuleGroups, [group.model_dump(exclude_none=True) for group in remaining_groups], ) - reference_changes = await remove_rule_group_references(name) + reference_changes = await remove_rule_group_references( + self.data.subscriptions, + name, + ) return json.dumps( { diff --git a/app/agent/tools/impl/delete_transfer_history.py b/app/agent/tools/impl/delete_transfer_history.py index 09212ebe5..b04e534e0 100644 --- a/app/agent/tools/impl/delete_transfer_history.py +++ b/app/agent/tools/impl/delete_transfer_history.py @@ -7,10 +7,9 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_transfer_history_port -from app.application.chain.data import get_chain_transfer_execution_port from app.application.transfer.execution import ( TransferExecutionCommand, + TransferExecutionRepository, TransferRetryRequestResult, ) from app.chain.storage import StorageChain @@ -35,6 +34,7 @@ def _delete_history_destination_file(fileitem: FileItem) -> tuple[bool, bool]: def _request_transfer_retry( + repository: TransferExecutionRepository, *, history_id: int, task_id: str, @@ -42,7 +42,7 @@ def _request_transfer_retry( ) -> TransferRetryRequestResult: """在线程池中登记 durable 重试,避免 Agent 事件循环执行同步数据库 I/O。""" return TransferExecutionCommand( - get_chain_transfer_execution_port() + repository ).request_retry( task_id=task_id, reason=f"Agent 请求重试整理历史 #{history_id}", @@ -75,7 +75,7 @@ class DeleteTransferHistoryTool(MoviePilotTool): logger.info(f"执行工具: {self.name}, 参数: history_id={history_id}") try: - transferhis = get_agent_transfer_history_port() + transferhis = self.data.transfer_history history = await transferhis.async_get(history_id) if not history: return f"错误:整理历史记录不存在,ID={history_id}" @@ -85,6 +85,7 @@ class DeleteTransferHistoryTool(MoviePilotTool): retry = await self.run_blocking( "db", _request_transfer_retry, + self.data.transfer_execution, history_id=history_id, task_id=task_id, user_id=self._user_id, diff --git a/app/agent/tools/impl/query_agent_tasks.py b/app/agent/tools/impl/query_agent_tasks.py index fc2911012..6c5e36aa3 100644 --- a/app/agent/tools/impl/query_agent_tasks.py +++ b/app/agent/tools/impl/query_agent_tasks.py @@ -5,7 +5,7 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_task_port +from app.application.agenttask import agent_task_run_to_dict, agent_task_to_dict from app.runtime.settings import get_runtime_setting @@ -46,26 +46,26 @@ class QueryAgentTasksTool(MoviePilotTool): self, task_id: Optional[int], enabled: Optional[bool], - ) -> list[dict]: + ) -> list[dict[str, object]]: """读取当前用户的任务及运行时下一次触发时间。""" from app.application.scheduling import get_agent_task_next_run - oper = get_agent_task_port() + oper = self.data.tasks if task_id: task = oper.get(task_id=task_id, user_id=str(self._user_id)) tasks = [task] if task else [] else: tasks = oper.list(user_id=str(self._user_id), enabled=enabled) - result = [] + result: list[dict[str, object]] = [] for task in tasks: - data = oper.to_dict( + data = agent_task_to_dict( task, next_run_at=get_agent_task_next_run(task.id), timezone=get_runtime_setting('TZ'), ) if task_id: data["recent_runs"] = [ - oper.run_to_dict(run) + agent_task_run_to_dict(run) for run in oper.list_runs( task_id=task.id, user_id=str(self._user_id), diff --git a/app/agent/tools/impl/query_download_tasks.py b/app/agent/tools/impl/query_download_tasks.py index 44c1ce44d..861809558 100644 --- a/app/agent/tools/impl/query_download_tasks.py +++ b/app/agent/tools/impl/query_download_tasks.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_download_history_port from app.application.history import DownloadHistorySnapshot from app.chain.download import DownloadChain from app.runtime.log import logger @@ -164,19 +163,18 @@ class QueryDownloadTasksTool(MoviePilotTool): media = music.get("media") return media if isinstance(media, dict) else {} - @classmethod def _load_history_map( - cls, torrents: List[DownloaderTorrent] + self, + torrents: List[DownloaderTorrent], ) -> Dict[str, DownloadHistorySnapshot]: """批量加载下载历史,避免逐条查询形成 N+1。""" hashes = [torrent.hash for torrent in torrents if torrent.hash] if not hashes: return {} - return get_agent_download_history_port().get_by_hashes(hashes) + return self.data.download_history.get_by_hashes(hashes) - @classmethod def _query_downloads_sync( - cls, + self, downloader: Optional[str] = None, status: Optional[str] = "all", hash_value: Optional[str] = None, @@ -189,8 +187,8 @@ class QueryDownloadTasksTool(MoviePilotTool): 同步查询下载器和下载历史,整个链路放在线程池中执行。 """ download_chain = DownloadChain() - query_status = cls._normalize_query_status(status) - include_all_tags = cls._normalize_include_all_tags(include_all_tags) + query_status = self._normalize_query_status(status) + include_all_tags = self._normalize_include_all_tags(include_all_tags) if hash_value: torrents = ( @@ -206,17 +204,17 @@ class QueryDownloadTasksTool(MoviePilotTool): "message": f"未找到hash为 {hash_value} 的下载任务(该任务可能已完成、已删除或不存在)" } - history_map = cls._load_history_map(torrents) + history_map = self._load_history_map(torrents) for torrent in torrents: - cls._apply_download_history(torrent, history_map.get(torrent.hash)) + self._apply_download_history(torrent, history_map.get(torrent.hash)) filtered_downloads = list(torrents) elif title: - all_torrents = cls._get_all_torrents( + all_torrents = self._get_all_torrents( download_chain, downloader, include_all_tags=include_all_tags, ) - history_map = cls._load_history_map(all_torrents) + history_map = self._load_history_map(all_torrents) filtered_downloads = [] title_lower = title.lower() @@ -231,7 +229,7 @@ class QueryDownloadTasksTool(MoviePilotTool): if not matched: continue - cls._apply_download_history(torrent, history) + self._apply_download_history(torrent, history) filtered_downloads.append(torrent) if not filtered_downloads: @@ -252,9 +250,12 @@ class QueryDownloadTasksTool(MoviePilotTool): include_all_tags=include_all_tags, ) or [] - history_map = cls._load_history_map(filtered_downloads) + history_map = self._load_history_map(filtered_downloads) for torrent in filtered_downloads: - cls._apply_download_history(torrent, history_map.get(torrent.hash)) + self._apply_download_history( + torrent, + history_map.get(torrent.hash), + ) if tag and filtered_downloads: tag_lower = tag.lower() diff --git a/app/agent/tools/impl/query_plugin_data.py b/app/agent/tools/impl/query_plugin_data.py index 242d52572..0ed85dc8d 100644 --- a/app/agent/tools/impl/query_plugin_data.py +++ b/app/agent/tools/impl/query_plugin_data.py @@ -6,13 +6,12 @@ from typing import Optional, Type from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool -from app.agent.tools.tags import ToolTag from app.agent.tools.impl._plugin_tool_utils import ( PLUGIN_DATA_KEY_PREVIEW_LIMIT, build_preview_payload, get_plugin_snapshot, ) -from app.application.agentdata import get_agent_plugin_data_port +from app.agent.tools.tags import ToolTag from app.runtime.log import logger @@ -56,9 +55,11 @@ class QueryPluginDataTool(MoviePilotTool): return f"查询插件数据: {plugin_id}.{key}" return f"查询插件全部数据: {plugin_id}" - @staticmethod async def _query_plugin_data( - plugin_id: str, key: Optional[str] = None, max_chars: Optional[int] = None + self, + plugin_id: str, + key: Optional[str] = None, + max_chars: Optional[int] = None, ) -> str: """ 插件数据改走异步 ORM 查询,避免再套一层线程池。 @@ -73,9 +74,8 @@ class QueryPluginDataTool(MoviePilotTool): ensure_ascii=False, ) - plugin_data_oper = get_agent_plugin_data_port() if key: - value = await plugin_data_oper.async_get_data(plugin_id, key) + value = await self.data.plugin_data.get(plugin_id, key) if value is None: return json.dumps( { @@ -108,8 +108,7 @@ class QueryPluginDataTool(MoviePilotTool): result["value"] = value return json.dumps(result, ensure_ascii=False, indent=2, default=str) - rows = await plugin_data_oper.async_get_data_all(plugin_id) or [] - data_map = {row.key: row.value for row in rows} + data_map = await self.data.plugin_data.list(plugin_id) keys = list(data_map.keys()) key_preview = keys[:PLUGIN_DATA_KEY_PREVIEW_LIMIT] diff --git a/app/agent/tools/impl/query_rule_groups.py b/app/agent/tools/impl/query_rule_groups.py index fc2692b83..8cedf5d9a 100644 --- a/app/agent/tools/impl/query_rule_groups.py +++ b/app/agent/tools/impl/query_rule_groups.py @@ -1,18 +1,18 @@ """查询过滤规则组工具。""" import json -from typing import Optional, Type, List +from typing import List, Optional, Type from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool -from app.agent.tools.tags import ToolTag from app.agent.tools.impl._filter_rule_utils import ( + RULE_STRING_SYNTAX, collect_rule_group_usages, get_rule_groups, serialize_rule_group, - RULE_STRING_SYNTAX, ) +from app.agent.tools.tags import ToolTag from app.runtime.log import logger @@ -69,6 +69,7 @@ class QueryRuleGroupsTool(MoviePilotTool): usage_map = {} if include_usage: usage_map = await collect_rule_group_usages( + self.data.subscriptions, [group.name for group in rule_groups if group.name] ) diff --git a/app/agent/tools/impl/query_site_userdata.py b/app/agent/tools/impl/query_site_userdata.py index e5a1d6890..9a7b5ece5 100644 --- a/app/agent/tools/impl/query_site_userdata.py +++ b/app/agent/tools/impl/query_site_userdata.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_site_port from app.domain import site as site_rules from app.runtime.log import logger from app.schemas.common import JsonData @@ -69,7 +68,7 @@ class QuerySiteUserdataTool(MoviePilotTool): ) try: - repository = get_agent_site_port() + repository = self.data.sites site = await repository.async_get(site_id) if not site: return json.dumps( diff --git a/app/agent/tools/impl/query_sites.py b/app/agent/tools/impl/query_sites.py index 2104f3110..7136c985b 100644 --- a/app/agent/tools/impl/query_sites.py +++ b/app/agent/tools/impl/query_sites.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_site_port from app.runtime.log import logger @@ -58,7 +57,7 @@ class QuerySitesTool(MoviePilotTool): logger.info(f"执行工具: {self.name}, 参数: status={status}, name={name}") try: is_admin = await self.is_admin_user() - repository = get_agent_site_port() + repository = self.data.sites # 获取所有站点(按优先级排序) sites = await repository.async_list() filtered_sites = [] diff --git a/app/agent/tools/impl/query_subscribe_history.py b/app/agent/tools/impl/query_subscribe_history.py index 653e0218e..2d5886a81 100644 --- a/app/agent/tools/impl/query_subscribe_history.py +++ b/app/agent/tools/impl/query_subscribe_history.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_subscribe_history_port from app.domain.media import normalize_music_type from app.runtime.log import logger from app.schemas.types import MUSIC_ENTITY_RECORDING, MediaType, media_type_to_agent @@ -106,7 +105,7 @@ class QuerySubscribeHistoryTool(MoviePilotTool): if MediaType.MUSIC.value not in requested_types: return "错误:music_type 仅能与 media_type='music' 或 'all' 一起使用" - repository = get_agent_subscribe_history_port() + repository = self.data.subscription_history if name: # 有名称过滤时,获取足够多的记录在内存中过滤,不分页 fetch_count = 500 diff --git a/app/agent/tools/impl/query_subscribes.py b/app/agent/tools/impl/query_subscribes.py index 98e302367..130052ceb 100644 --- a/app/agent/tools/impl/query_subscribes.py +++ b/app/agent/tools/impl/query_subscribes.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_subscribe_port from app.domain.media import normalize_music_type from app.runtime.log import logger from app.schemas.subscribe import Subscribe as SubscribeSchema @@ -157,7 +156,7 @@ class QuerySubscribesTool(MoviePilotTool): if media_type not in ("all", "music"): return "错误:music_type 仅能与 media_type='music' 或 'all' 一起使用" - repository = get_agent_subscribe_port() + repository = self.data.subscriptions subscribes = await repository.async_list() filtered_subscribes = [] for sub in subscribes: diff --git a/app/agent/tools/impl/query_transfer_history.py b/app/agent/tools/impl/query_transfer_history.py index 5316b6e84..38951b448 100644 --- a/app/agent/tools/impl/query_transfer_history.py +++ b/app/agent/tools/impl/query_transfer_history.py @@ -7,10 +7,9 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_transfer_history_port +from app.foundation.text import cut as jieba_cut from app.runtime.log import logger from app.schemas.types import media_type_to_agent -from app.foundation.text import cut as jieba_cut class QueryTransferHistoryInput(BaseModel): @@ -75,7 +74,7 @@ class QueryTransferHistoryTool(MoviePilotTool): # 每页固定 30 条,与工具说明保持一致,避免整理路径等字段撑大上下文。 count = 30 - transferhis = get_agent_transfer_history_port() + transferhis = self.data.transfer_history # 处理标题搜索 if title: # 使用统一分词封装处理标题,便于替换底层实现。 diff --git a/app/agent/tools/impl/run_agent_task.py b/app/agent/tools/impl/run_agent_task.py index e7f4028b4..1c1efdacb 100644 --- a/app/agent/tools/impl/run_agent_task.py +++ b/app/agent/tools/impl/run_agent_task.py @@ -6,7 +6,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_task_port class RunAgentTaskInput(BaseModel): @@ -42,7 +41,7 @@ class RunAgentTaskTool(MoviePilotTool): def _get_task_state(self, task_id: int) -> tuple[str, Optional[str]]: """校验任务归属和状态,返回可执行性及任务名称。""" - task = get_agent_task_port().get( + task = self.data.tasks.get( task_id=task_id, user_id=str(self._user_id), ) diff --git a/app/agent/tools/impl/search_subscribe.py b/app/agent/tools/impl/search_subscribe.py index 68c070f84..76b24643c 100644 --- a/app/agent/tools/impl/search_subscribe.py +++ b/app/agent/tools/impl/search_subscribe.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_subscribe_port from app.application.subscription.contract import SubscriptionPatch from app.chain.subscribe import SubscribeChain from app.runtime.log import logger @@ -58,7 +57,7 @@ class SearchSubscribeTool(MoviePilotTool): try: # 先验证订阅是否存在 - repository = get_agent_subscribe_port() + repository = self.data.subscriptions subscribe = await repository.async_get(subscribe_id) if not subscribe: diff --git a/app/agent/tools/impl/test_site.py b/app/agent/tools/impl/test_site.py index ac76e5d54..406dc2ae2 100644 --- a/app/agent/tools/impl/test_site.py +++ b/app/agent/tools/impl/test_site.py @@ -6,7 +6,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_site_port from app.chain.site import SiteChain from app.domain import site as site_rules from app.runtime.log import logger @@ -31,10 +30,12 @@ class TestSiteTool(MoviePilotTool): site_identifier = kwargs.get("site_identifier") return f"测试站点连通性: {site_identifier}" - @staticmethod - def _test_site_sync(site_identifier: int) -> tuple[Optional[str], Optional[str], bool, str]: + def _test_site_sync( + self, + site_identifier: int, + ) -> tuple[Optional[str], Optional[str], bool, str]: """在同步线程里执行站点联通测试,避免网络请求卡住事件循环。""" - site = get_agent_site_port().get(site_identifier) + site = self.data.sites.get(site_identifier) if not site: return None, None, False, f"未找到站点:{site_identifier},请使用 query_sites 工具查询可用的站点" diff --git a/app/agent/tools/impl/update_agent_task.py b/app/agent/tools/impl/update_agent_task.py index c5be3a81f..711634c65 100644 --- a/app/agent/tools/impl/update_agent_task.py +++ b/app/agent/tools/impl/update_agent_task.py @@ -7,7 +7,7 @@ from pydantic import BaseModel, Field, model_validator from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_task_port +from app.application.agenttask import agent_task_to_dict from app.runtime.scheduling import TimerUtils from app.runtime.settings import get_runtime_setting @@ -98,11 +98,14 @@ class UpdateAgentTaskTool(MoviePilotTool): """生成更新定时任务的提示消息。""" return f"更新自主定时任务:{kwargs.get('task_id', '')}" - def _update_task(self, payload: UpdateAgentTaskInput) -> Optional[dict]: + def _update_task( + self, + payload: UpdateAgentTaskInput, + ) -> Optional[dict[str, object]]: """更新当前用户的任务并刷新运行时调度。""" from app.application.scheduling import update_agent_task_job - oper = get_agent_task_port() + oper = self.data.tasks task = oper.get(task_id=payload.task_id, user_id=str(self._user_id)) if not task: return None @@ -129,6 +132,8 @@ class UpdateAgentTaskTool(MoviePilotTool): and trigger_type == "date" ) if has_schedule_update or validates_existing_date_schedule: + if trigger_value is None: + raise ValueError("Agent 定时任务缺少触发配置") normalized_type, normalized_trigger = TimerUtils.normalize_schedule_trigger( trigger_type=trigger_type, trigger_value=trigger_value, @@ -142,7 +147,7 @@ class UpdateAgentTaskTool(MoviePilotTool): ), ) - update_payload = {} + update_payload: dict[str, object] = {} if payload.name is not None: update_payload["name"] = payload.name.strip() if payload.content is not None: @@ -176,7 +181,9 @@ class UpdateAgentTaskTool(MoviePilotTool): return None next_run_at = update_agent_task_job(payload.task_id) updated_task = oper.get(task_id=payload.task_id, user_id=str(self._user_id)) - return oper.to_dict( + if updated_task is None: + return None + return agent_task_to_dict( updated_task, next_run_at=next_run_at, timezone=get_runtime_setting('TZ'), @@ -206,6 +213,7 @@ class UpdateAgentTaskTool(MoviePilotTool): task = await self.run_blocking("db", self._update_task, payload) if not task: return f"Agent 定时任务 {task_id} 不存在或不属于当前用户" - if task.get("error"): - return task["error"] + error = task.get("error") + if error: + return str(error) return json.dumps(task, ensure_ascii=False, indent=2) diff --git a/app/agent/tools/impl/update_rule_group.py b/app/agent/tools/impl/update_rule_group.py index 8525b25ca..4269bba60 100644 --- a/app/agent/tools/impl/update_rule_group.py +++ b/app/agent/tools/impl/update_rule_group.py @@ -6,7 +6,6 @@ from typing import Optional, Type from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool -from app.agent.tools.tags import ToolTag from app.agent.tools.impl._filter_rule_utils import ( build_custom_rule_map, collect_rule_group_usages, @@ -18,6 +17,7 @@ from app.agent.tools.impl._filter_rule_utils import ( save_system_config, serialize_rule_group, ) +from app.agent.tools.tags import ToolTag from app.runtime.log import logger from app.schemas.types import SystemConfigKey @@ -131,11 +131,15 @@ class UpdateRuleGroupTool(MoviePilotTool): reference_changes = {} if updated_group.name != current_group.name: reference_changes = await rename_rule_group_references( + self.data.subscriptions, current_group.name, updated_group.name, ) - usage = await collect_rule_group_usages([updated_group.name]) + usage = await collect_rule_group_usages( + self.data.subscriptions, + [updated_group.name], + ) return json.dumps( { "success": True, diff --git a/app/agent/tools/impl/update_site.py b/app/agent/tools/impl/update_site.py index 31755e51b..882e53989 100644 --- a/app/agent/tools/impl/update_site.py +++ b/app/agent/tools/impl/update_site.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.agentdata import get_agent_site_port from app.application.site.contract import SiteMutation from app.foundation import url as url_tools from app.runtime.events import eventmanager @@ -125,7 +124,7 @@ class UpdateSiteTool(MoviePilotTool): logger.info(f"执行工具: {self.name}, 参数: site_id={site_id}") try: - repository = get_agent_site_port() + repository = self.data.sites site = await repository.async_get(site_id) if not site: return json.dumps( diff --git a/app/agent/tools/impl/update_site_cookie.py b/app/agent/tools/impl/update_site_cookie.py index cd7f8b31d..f6ffdea4f 100644 --- a/app/agent/tools/impl/update_site_cookie.py +++ b/app/agent/tools/impl/update_site_cookie.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, Field from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag from app.chain.site import SiteChain -from app.application.agentdata import get_agent_site_port from app.runtime.log import logger @@ -49,8 +48,8 @@ class UpdateSiteCookieTool(MoviePilotTool): return message - @staticmethod def _update_site_cookie_sync( + self, site_identifier: int, username: str, password: str, @@ -59,7 +58,7 @@ class UpdateSiteCookieTool(MoviePilotTool): """ 在同步线程里执行站点登录和 Cookie 更新,避免网络登录阻塞协程。 """ - site = get_agent_site_port().get(site_identifier) + site = self.data.sites.get(site_identifier) if not site: return None, False, f"未找到站点:{site_identifier},请使用 query_sites 工具查询可用的站点" diff --git a/app/agent/tools/manager.py b/app/agent/tools/manager.py index 4b9a884aa..59867e542 100644 --- a/app/agent/tools/manager.py +++ b/app/agent/tools/manager.py @@ -12,6 +12,7 @@ if TYPE_CHECKING: from app.agent.policy.contracts import ToolPolicyContext from app.agent.policy.orchestrator import AgentToolPolicyOrchestrator from app.agent.tools.catalog import ToolCatalogSnapshot + from app.application.agent import AgentDataContext class ToolDefinition: @@ -36,6 +37,7 @@ class MoviePilotToolsManager: session_id: str = uuid.uuid4(), is_admin: bool = True, policy_orchestrator: Optional[AgentToolPolicyOrchestrator] = None, + data: Optional[AgentDataContext] = None, ): """ 初始化工具管理器 @@ -48,6 +50,7 @@ class MoviePilotToolsManager: self.session_id = session_id self.is_admin = is_admin self.policy_orchestrator = policy_orchestrator + self._data = data self._policy_context: Optional[ToolPolicyContext] = None self.tools: List[Any] = [] self.catalog: Optional[ToolCatalogSnapshot] = None @@ -56,6 +59,20 @@ class MoviePilotToolsManager: self._catalog_materialized = False self._catalog_managed_by_factory = False + def set_data_context(self, data: AgentDataContext) -> None: + """绑定组合根上下文,并使工厂拥有的旧工具快照原子失效。""" + with self._tools_lock: + if self._data is data: + return + if self._catalog_materialized and not self._catalog_managed_by_factory: + raise RuntimeError("调用方工具目录已物化,不能替换数据上下文") + self._data = data + self.tools = [] + self.catalog = None + self._plugin_agent_tools_revision = -1 + self._catalog_materialized = False + self._catalog_managed_by_factory = False + @staticmethod def _summarize_error(error: Exception) -> str: """仅在错误路径加载策略脱敏器,保持默认导入轻量。""" @@ -81,6 +98,7 @@ class MoviePilotToolsManager: username="API Client", stream_handler=None, agent_context={"is_admin": self.is_admin}, + data=self._data, ) self.catalog = catalog self.tools = catalog.tools diff --git a/app/api/dependencies/history.py b/app/api/dependencies/history.py index c43f00958..44d956024 100644 --- a/app/api/dependencies/history.py +++ b/app/api/dependencies/history.py @@ -14,6 +14,7 @@ from app.application.history import ( clear_transfer_failures, ) from app.application.mediaserver import MediaServerQueryService +from app.application.transfer.execution import TransferExecutionRepository from app.chain.storage import StorageChain from app.runtime.events import eventmanager from app.schemas.types import EventType @@ -74,6 +75,13 @@ def get_transfer_history_lookup_service( ) +def get_transfer_execution_repository( + runtime: HostRuntime = Depends(get_host_runtime), +) -> TransferExecutionRepository: + """返回 durable 整理任务的显式执行仓储。""" + return runtime.history.transfer_execution_repository + + def get_transfer_history_mutation_command( db: Session = Depends(get_sync_session), runtime: HostRuntime = Depends(get_host_runtime), diff --git a/app/api/endpoints/history.py b/app/api/endpoints/history.py index 8fa343014..df4421e8e 100644 --- a/app/api/endpoints/history.py +++ b/app/api/endpoints/history.py @@ -24,11 +24,11 @@ from app.api.dependencies.auth import ( from app.api.dependencies.history import ( get_download_history_mutation_command, get_history_query_service, + get_transfer_execution_repository, get_transfer_history_mutation_command, ) from app.api.response import ResponseAPIRouter from app.application.agent import get_running_agent_manager -from app.application.chain.data import get_chain_transfer_execution_port from app.application.configuration import ApiRuntimeConfig from app.application.history import ( DownloadHistoryMutationCommand, @@ -37,6 +37,7 @@ from app.application.history import ( ) from app.application.transfer.execution import ( TransferExecutionCommand, + TransferExecutionRepository, TransferRetryRequestResult, ) from app.runtime.config import global_vars @@ -69,11 +70,10 @@ def _request_durable_transfer_retry( history_id: int, task_id: str, requested_by: str, + repository: TransferExecutionRepository, ) -> TransferRetryRequestResult: """把 durable 历史重试交给唯一持久调度器,不在请求线程执行整理。""" - return TransferExecutionCommand( - get_chain_transfer_execution_port() - ).request_retry( + return TransferExecutionCommand(repository).request_retry( task_id=task_id, reason=f"AI REST 请求重试整理历史 #{history_id}", requested_by=requested_by, @@ -102,6 +102,7 @@ def _partition_durable_histories( async def _request_batch_durable_retries( histories: list[_SchemaTransferHistory], + repository: TransferExecutionRepository, ) -> tuple[int, list[tuple[int, TransferRetryRequestResult]]]: """逐任务登记 durable 重试并保留每条拒绝的稳定状态。""" accepted_count = 0 @@ -112,6 +113,7 @@ async def _request_batch_durable_retries( history_id=history.id, task_id=history.transfer_task_id or "", requested_by="history_ai_redo_batch", + repository=repository, ) if retry.accepted: accepted_count += 1 @@ -400,6 +402,9 @@ async def ai_redo_transfer_history( runtime_config: ApiRuntimeConfig = Depends(get_api_runtime_config), _: object = Depends(get_current_active_manage_user), task_registry: TaskRegistry = Depends(get_background_task_registry), + execution_repository: TransferExecutionRepository = Depends( + get_transfer_execution_repository + ), ) -> Any: """ 手动触发单条历史记录的 AI 重新整理,并返回进度键。 @@ -415,6 +420,7 @@ async def ai_redo_transfer_history( history_id=history.id, task_id=history.transfer_task_id, requested_by="history_ai_redo", + repository=execution_repository, ) if not retry.accepted: return _SchemaResponse(success=False, message=retry.message) @@ -456,6 +462,9 @@ async def batch_ai_redo_transfer_history( runtime_config: ApiRuntimeConfig = Depends(get_api_runtime_config), _: object = Depends(get_current_active_manage_user), task_registry: TaskRegistry = Depends(get_background_task_registry), + execution_repository: TransferExecutionRepository = Depends( + get_transfer_execution_repository + ), ) -> Any: """ 手动触发多条历史记录的 AI 批量重新整理,并返回进度键。 @@ -476,7 +485,8 @@ async def batch_ai_redo_transfer_history( durable_histories, legacy_histories = _partition_durable_histories(histories) accepted_count, rejections = await _request_batch_durable_retries( - durable_histories + durable_histories, + execution_repository, ) response_message_parts = _durable_retry_messages( accepted_count=accepted_count, diff --git a/app/api/endpoints/transfer.py b/app/api/endpoints/transfer.py index ba6575e86..b9f294d39 100644 --- a/app/api/endpoints/transfer.py +++ b/app/api/endpoints/transfer.py @@ -5,15 +5,15 @@ from fastapi import Depends, HTTPException, Query, status from app.adapters.web.security.access import verify_apitoken, verify_token from app.api.dependencies.auth import get_current_active_manage_user -from app.api.dependencies.history import get_transfer_history_lookup_service +from app.api.dependencies.history import get_transfer_execution_repository, get_transfer_history_lookup_service from app.api.response import ResponseAPIRouter -from app.application.chain.data import get_chain_transfer_execution_port from app.application.configuration import get_api_runtime_config_snapshot from app.application.directory import DirectoryHelper from app.application.history import TransferHistoryLookupService from app.application.transfer.execution import ( TransferExecutionCommand, TransferExecutionConflictError, + TransferExecutionRepository, TransferExecutionState, TransferManualReviewDecision, TransferManualReviewQuery, @@ -96,12 +96,13 @@ def list_transfer_manual_reviews( page: int = Query(default=1, ge=1), page_size: int = Query(default=30, ge=1, le=100), current_user: object = Depends(get_current_active_manage_user), + repository: TransferExecutionRepository = Depends( + get_transfer_execution_repository + ), ) -> Any: """分页返回待复核或已判定等待 durable 恢复的任务。""" del current_user - result = TransferManualReviewQuery( - get_chain_transfer_execution_port() - ).list( + result = TransferManualReviewQuery(repository).list( state=TransferExecutionState(state_filter), page=page, page_size=page_size, @@ -125,12 +126,13 @@ def list_transfer_manual_reviews( def get_transfer_manual_review( task_id: str, current_user: object = Depends(get_current_active_manage_user), + repository: TransferExecutionRepository = Depends( + get_transfer_execution_repository + ), ) -> Any: """按任务标识返回严格裁剪的人工复核详情。""" del current_user - task = TransferManualReviewQuery( - get_chain_transfer_execution_port() - ).get(task_id=task_id) + task = TransferManualReviewQuery(repository).get(task_id=task_id) if task is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, @@ -148,6 +150,9 @@ def resolve_transfer_manual_review( task_id: str, review: _SchemaTransferManualReviewRequest, current_user: object = Depends(get_current_active_manage_user), + repository: TransferExecutionRepository = Depends( + get_transfer_execution_repository + ), ) -> Any: """提交无租约人工判定,并返回不含 attempt 与 lease 的公开状态。""" result = ( @@ -156,9 +161,7 @@ def resolve_transfer_manual_review( else None ) try: - resolved = TransferExecutionCommand( - get_chain_transfer_execution_port() - ).resolve_manual_review( + resolved = TransferExecutionCommand(repository).resolve_manual_review( task_id=task_id, operation_id=review.operation_id, decision=TransferManualReviewDecision(review.decision), diff --git a/app/application/agent.py b/app/application/agent.py index 498097855..fb4454351 100644 --- a/app/application/agent.py +++ b/app/application/agent.py @@ -9,8 +9,41 @@ chain 层需要触发 Agent 后台任务、渲染提示词、查询模型能力 本模块禁止静态或函数内导入 app.agent,否则会重新形成跨层循环依赖。 """ +from dataclasses import dataclass from typing import Any, Callable, Optional +from app.application.agenttask import AgentTaskRepository +from app.application.history import DownloadHistoryRepository, TransferHistoryRepository +from app.application.messaging.chat import ( + AgentChatPersistenceService, + AgentChatService, +) +from app.application.plugin.data import PluginDataQueryRepository +from app.application.security.user import ChainUserRepository +from app.application.site.contract import SiteRepository +from app.application.subscription.contract import ( + SubscriptionHistoryQueryPort, + SubscriptionRepository, +) +from app.application.transfer.execution import TransferExecutionRepository + + +@dataclass(frozen=True, slots=True) +class AgentDataContext: + """由启动组合根构造并注入 Agent 运行面的类型化数据能力。""" + + chat: AgentChatService + chat_persistence: AgentChatPersistenceService + tasks: AgentTaskRepository + users: ChainUserRepository + sites: SiteRepository + subscriptions: SubscriptionRepository + subscription_history: SubscriptionHistoryQueryPort + transfer_history: TransferHistoryRepository + transfer_execution: TransferExecutionRepository + download_history: DownloadHistoryRepository + plugin_data: PluginDataQueryRepository + Provider = Callable[[], Any] # provider 注册表由 startup/initializers/agent.py 在组合根装配。 diff --git a/app/application/agentdata.py b/app/application/agentdata.py deleted file mode 100644 index 0e0bdbdb9..000000000 --- a/app/application/agentdata.py +++ /dev/null @@ -1,178 +0,0 @@ -"""Agent 编排和工具使用的数据端口组合根注册表。""" - -from __future__ import annotations - -from collections.abc import Callable -from dataclasses import dataclass -from typing import Any, cast - -from app.application.history import ( - DownloadHistoryRepository, - TransferHistoryRepository, -) -from app.application.security.user import ChainUserRepository -from app.application.site.contract import SiteRepository -from app.application.subscription.contract import ( - SubscriptionHistoryQueryPort, - SubscriptionRepository, -) - -AgentDataFactory = Callable[[], Any] - - -class _PortMeta(type): - """支持旧测试按 Oper 方法打桩的端口代理元类。""" - - def __getattr__(cls, name: str) -> Any: - """把类级方法访问转发到当前配置端口。""" - return getattr(cls(), name) - - -class _PortProxy(metaclass=_PortMeta): - """将存量 Oper 调用形态转发到 Agent 数据端口。""" - - port_name: str - - def __getattr__(self, name: str) -> Any: - """转发未被测试替换的实例方法。""" - ports = get_agent_data_ports() - return getattr(getattr(ports, self.port_name)(), name) - - -class AgentChatPort(_PortProxy): - """Agent 会话数据端口代理。""" - - port_name = "agent_chat" - - -class AgentTaskPort(_PortProxy): - """Agent 定时任务数据端口代理。""" - - port_name = "agent_task" - - -class TransferHistoryPort(_PortProxy): - """整理历史数据端口代理。""" - - port_name = "transfer_history" - - -class DownloadHistoryPort(_PortProxy): - """下载历史数据端口代理。""" - - port_name = "download_history" - - -class PluginDataPort(_PortProxy): - """插件数据端口代理。""" - - port_name = "plugin_data" - - -@dataclass(frozen=True, slots=True) -class AgentDataPorts: - """Agent 入口所需的持久化端口集合。""" - - agent_chat: AgentDataFactory - agent_task: AgentDataFactory - user: AgentDataFactory - site: AgentDataFactory - subscribe: AgentDataFactory - subscribe_history: AgentDataFactory - transfer_history: AgentDataFactory - download_history: AgentDataFactory - plugin_data: AgentDataFactory - - -_ports: AgentDataPorts | None = None - - -def configure_agent_data_ports(**factories: AgentDataFactory) -> None: - """由启动组合根登记 Agent 数据端口实现。""" - required = { - "agent_chat", - "agent_task", - "user", - "site", - "subscribe", - "subscribe_history", - "transfer_history", - "download_history", - "plugin_data", - } - missing = sorted(required - factories.keys()) - if missing: - raise ValueError(f"Agent 数据端口缺少实现: {', '.join(missing)}") - global _ports - _ports = AgentDataPorts( - agent_chat=factories["agent_chat"], - agent_task=factories["agent_task"], - user=factories["user"], - site=factories["site"], - subscribe=factories["subscribe"], - subscribe_history=factories["subscribe_history"], - transfer_history=factories["transfer_history"], - download_history=factories["download_history"], - plugin_data=factories["plugin_data"], - ) - - -def get_agent_data_ports() -> AgentDataPorts: - """返回已登记的 Agent 数据端口。""" - if _ports is None: - raise RuntimeError("Agent 数据端口尚未配置") - return _ports - - -def get_agent_chat_port() -> Any: - """创建 Agent 会话数据端口实例。""" - return get_agent_data_ports().agent_chat() - - -def get_agent_task_port() -> Any: - """创建 Agent 定时任务数据端口实例。""" - return get_agent_data_ports().agent_task() - - -def get_agent_user_port() -> ChainUserRepository: - """创建 Agent 用户数据端口实例。""" - return cast(ChainUserRepository, get_agent_data_ports().user()) - - -def get_agent_site_port() -> SiteRepository: - """创建 Agent 类型化站点查询与写入端口实例。""" - return cast(SiteRepository, get_agent_data_ports().site()) - - -def get_agent_subscribe_port() -> SubscriptionRepository: - """创建 Agent 类型化订阅查询与写入端口实例。""" - return cast(SubscriptionRepository, get_agent_data_ports().subscribe()) - - -def get_agent_subscribe_history_port() -> SubscriptionHistoryQueryPort: - """创建 Agent 类型化订阅历史查询端口实例。""" - return cast( - SubscriptionHistoryQueryPort, - get_agent_data_ports().subscribe_history(), - ) - - -def get_agent_transfer_history_port() -> TransferHistoryRepository: - """创建 Agent 类型化整理历史数据端口实例。""" - return cast( - TransferHistoryRepository, - get_agent_data_ports().transfer_history(), - ) - - -def get_agent_download_history_port() -> DownloadHistoryRepository: - """创建 Agent 类型化下载历史数据端口实例。""" - return cast( - DownloadHistoryRepository, - get_agent_data_ports().download_history(), - ) - - -def get_agent_plugin_data_port() -> Any: - """创建 Agent 插件数据端口实例。""" - return get_agent_data_ports().plugin_data() diff --git a/app/application/agenttask.py b/app/application/agenttask.py index eeb5f4f1a..5b06e117b 100644 --- a/app/application/agenttask.py +++ b/app/application/agenttask.py @@ -6,29 +6,46 @@ import asyncio import threading from collections.abc import Callable from dataclasses import dataclass -from typing import Protocol, TypeVar +from typing import List, Optional, Protocol, TypeVar from uuid import uuid4 from app.application.database import AsyncDatabaseExecutor from app.runtime.execution import await_task_to_terminal from app.schemas.exception import DatabaseWorkerOverloadedError - T = TypeVar("T") SyncTransaction = Callable[[Callable[[object], T]], T] -class AgentTaskRecord(Protocol): - """执行认领与终态判定所需的任务投影。""" +@dataclass(frozen=True, slots=True) +class AgentTaskSnapshot: + """脱离数据库 Session 的自主任务完整快照。""" id: int + name: str + content: str + trigger_type: str + cron_expression: str | None + run_at: str | None enabled: bool - last_run_id: str | None + user_id: str + username: str | None + session_id: str + channel: str | None + source: str | None + original_chat_id: str | None last_status: str + last_run_at: str | None + last_result: str | None + last_run_id: str | None + run_count: int + created_at: str + updated_at: str -class AgentTaskRunRecord(Protocol): - """执行期间需要脱离数据库会话持有的运行记录字段。""" +@dataclass(frozen=True, slots=True) +class AgentTaskRunSnapshot: + """脱离数据库 Session 的自主任务运行快照。""" run_id: str task_id: int @@ -41,13 +58,54 @@ class AgentTaskRunRecord(Protocol): user_id: str username: str | None session_id: str + channel: str | None + message_source: str | None + original_chat_id: str | None + status: str + started_at: str + finished_at: str | None + result: str | None class AgentTaskRepository(Protocol): - """AgentTask 执行用例使用的同步短事务仓储合同。""" + """调度、工具与执行用例共享的类型化自主任务仓储合同。""" - def get(self, task_id: int) -> AgentTaskRecord | None: + def add(self, **values: object) -> AgentTaskSnapshot | None: + """新增任务并返回提交后的冻结快照。""" + ... + + def get( + self, + task_id: int, + user_id: Optional[str] = None, + ) -> AgentTaskSnapshot | None: """读取任务当前投影。""" + ... + + def list( + self, + user_id: Optional[str] = None, + enabled: Optional[bool] = None, + ) -> list[AgentTaskSnapshot]: + """按归属和启用状态读取任务快照。""" + ... + + def update( + self, + task_id: int, + payload: dict[str, object], + user_id: Optional[str] = None, + ) -> bool: + """更新非运行中任务。""" + ... + + def delete(self, task_id: int, user_id: Optional[str] = None) -> bool: + """删除非运行中任务及其运行记录。""" + ... + + def mark_interrupted(self, task_id: int, result: str) -> bool: + """把遗留运行态收口为结果未知。""" + ... def begin_run( self, @@ -55,8 +113,18 @@ class AgentTaskRepository(Protocol): trigger_source: str = "scheduled", *, run_id: str | None = None, - ) -> AgentTaskRunRecord | None: + ) -> AgentTaskRunSnapshot | None: """原子认领任务并创建运行快照。""" + ... + + def list_runs( + self, + task_id: int, + user_id: Optional[str] = None, + limit: int = 10, + ) -> List[AgentTaskRunSnapshot]: + """读取指定任务最近的运行快照。""" + ... def finish_run_outcome( self, @@ -70,32 +138,26 @@ class AgentTaskRepository(Protocol): class AgentTaskFinishRecord(Protocol): """同步仓储返回的结构化运行终态。""" - run_finalized: bool - task_projection_updated: bool - date_task_disabled: bool + @property + def run_finalized(self) -> bool: + """运行记录是否已进入终态。""" + ... + + @property + def task_projection_updated(self) -> bool: + """任务最新运行投影是否由本次执行更新。""" + ... + + @property + def date_task_disabled(self) -> bool: + """一次性任务是否已随本次执行停用。""" + ... AgentTaskRepositoryFactory = Callable[[object], AgentTaskRepository] AgentTaskScheduleRemover = Callable[[int, int, str], bool] -@dataclass(frozen=True, slots=True) -class AgentTaskRunSnapshot: - """任务认领成功后可安全跨越数据库会话的执行快照。""" - - run_id: str - task_id: int - trigger_source: str - name: str - content: str - trigger_type: str - cron_expression: str | None - run_at: str | None - user_id: str - username: str | None - session_id: str - - @dataclass(frozen=True, slots=True) class AgentTaskClaim: """任务认领结果;拒绝原因保持现有 Agent 用户提示合同。""" @@ -113,6 +175,51 @@ class AgentTaskFinishOutcome: date_task_disabled: bool +def agent_task_to_dict( + task: AgentTaskSnapshot, + *, + next_run_at: str | None = None, + timezone: str | None = None, +) -> dict[str, object]: + """把自主任务快照转换为 Agent 工具稳定返回结构。""" + return { + "id": task.id, + "name": task.name, + "content": task.content, + "trigger_type": task.trigger_type, + "cron_expression": task.cron_expression, + "run_at": task.run_at, + "timezone": timezone, + "enabled": task.enabled, + "last_status": task.last_status, + "last_run_at": task.last_run_at, + "last_result": task.last_result, + "last_run_id": task.last_run_id, + "run_count": task.run_count, + "next_run_at": next_run_at, + "created_at": task.created_at, + "updated_at": task.updated_at, + } + + +def agent_task_run_to_dict(run: AgentTaskRunSnapshot) -> dict[str, object]: + """把自主任务运行快照转换为 Agent 工具稳定返回结构。""" + return { + "run_id": run.run_id, + "task_id": run.task_id, + "trigger_source": run.trigger_source, + "name": run.name, + "content": run.content, + "trigger_type": run.trigger_type, + "cron_expression": run.cron_expression, + "run_at": run.run_at, + "status": run.status, + "started_at": run.started_at, + "finished_at": run.finished_at, + "result": run.result, + } + + class AgentTaskExecutionService: """通过有界数据库 worker 认领并收口一次 AgentTask 执行。""" @@ -129,21 +236,9 @@ class AgentTaskExecutionService: self._sync_transaction = sync_transaction @staticmethod - def _snapshot(run: AgentTaskRunRecord) -> AgentTaskRunSnapshot: + def _snapshot(run: AgentTaskRunSnapshot) -> AgentTaskRunSnapshot: """在事务内复制运行字段,避免 ORM 对象越过会话边界。""" - return AgentTaskRunSnapshot( - run_id=run.run_id, - task_id=run.task_id, - trigger_source=run.trigger_source, - name=run.name, - content=run.content, - trigger_type=run.trigger_type, - cron_expression=run.cron_expression, - run_at=run.run_at, - user_id=run.user_id, - username=run.username, - session_id=run.session_id, - ) + return run async def claim( self, diff --git a/app/application/chain/context.py b/app/application/chain/context.py index 20a9e29ad..217e479d4 100644 --- a/app/application/chain/context.py +++ b/app/application/chain/context.py @@ -4,12 +4,25 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass, field -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, Optional from app.application.chain.events import ChainDurableEventWriter from app.application.configuration import ChainRuntimeConfig from app.runtime.stop import StopState, runtime_stop_state +if TYPE_CHECKING: + from app.application.download.failures import DownloadFailureRepository + from app.application.history import ( + DownloadHistoryRepository, + TransferHistoryRepository, + ) + from app.application.mediaserver import MediaServerRepository + from app.application.security.user import ChainUserRepository + from app.application.site.contract import SiteRepository + from app.application.subscription.contract import SubscriptionRepository + from app.application.transfer.execution import TransferExecutionRepository + from app.application.transfer.workflow import TransferAdmissionRepository + MessageQueueFactory = Callable[[Callable[..., Any]], Any] ModuleDispatcherFactory = Callable[..., Any] LegacyTransferCommand = Callable[..., Any] @@ -29,6 +42,15 @@ class ChainRuntimeContext: async_file_cache: Any message_queue_factory: MessageQueueFactory module_dispatcher_factory: ModuleDispatcherFactory + site_repository: SiteRepository + subscription_repository: SubscriptionRepository + download_history_repository: DownloadHistoryRepository + transfer_history_repository: TransferHistoryRepository + transfer_admission_repository: TransferAdmissionRepository + transfer_execution_repository: TransferExecutionRepository + media_server_repository: MediaServerRepository + download_failure_repository: DownloadFailureRepository + user_repository: ChainUserRepository legacy_transfer_command: Optional[LegacyTransferCommand] = None durable_event_writer: Optional[ChainDurableEventWriter] = None configuration: ChainRuntimeConfig = field( diff --git a/app/application/chain/data.py b/app/application/chain/data.py deleted file mode 100644 index c49d38e69..000000000 --- a/app/application/chain/data.py +++ /dev/null @@ -1,146 +0,0 @@ -"""Chain 所需持久化端口的组合根注册表。 - -Chain 只依赖本模块声明的工厂,不再直接导入数据库 Oper 或 ORM 模型。 -具体适配器由 ``app.startup`` 在进程启动时装配,测试也可以登记隔离替身。 -""" - -from __future__ import annotations - -from collections.abc import Callable -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Optional, Protocol - -if TYPE_CHECKING: - from app.application.download.failures import DownloadFailureRepository - from app.application.history import ( - DownloadHistoryRepository, - TransferHistoryRepository, - ) - from app.application.mediaserver import MediaServerRepository - from app.application.security.user import ChainUserRepository - from app.application.site.contract import SiteRepository - from app.application.subscription.contract import SubscriptionRepository - from app.application.transfer.execution import TransferExecutionRepository - from app.application.transfer.workflow import TransferAdmissionRepository - -OperFactory = Callable[[], Any] -SiteRepositoryFactory = Callable[[], "SiteRepository"] -SubscriptionRepositoryFactory = Callable[[], "SubscriptionRepository"] -DownloadFailureRepositoryFactory = Callable[[], "DownloadFailureRepository"] -MediaServerRepositoryFactory = Callable[[], "MediaServerRepository"] -ChainUserRepositoryFactory = Callable[[], "ChainUserRepository"] -TransferAdmissionRepositoryFactory = Callable[[], "TransferAdmissionRepository"] -TransferExecutionRepositoryFactory = Callable[[], "TransferExecutionRepository"] - - -class DownloadHistoryRepositoryFactory(Protocol): - """构造下载历史仓储且不在注册表导入时初始化其实现。""" - - def __call__(self) -> "DownloadHistoryRepository": - """返回下载历史仓储。""" - ... - - -class TransferHistoryRepositoryFactory(Protocol): - """构造整理历史仓储且不在注册表导入时初始化其实现。""" - - def __call__(self) -> "TransferHistoryRepository": - """返回整理历史仓储。""" - ... - - -@dataclass(frozen=True, slots=True) -class ChainDataPorts: - """跨领域 Chain 使用的最小持久化端口工厂集合。""" - - site: SiteRepositoryFactory - subscribe: SubscriptionRepositoryFactory - download_history: DownloadHistoryRepositoryFactory - transfer_history: TransferHistoryRepositoryFactory - transfer_pending: TransferAdmissionRepositoryFactory - transfer_execution: TransferExecutionRepositoryFactory - media_server: MediaServerRepositoryFactory - download_failure: DownloadFailureRepositoryFactory - user: ChainUserRepositoryFactory - - -_ports: Optional[ChainDataPorts] = None - - -def configure_chain_data_ports( - *, - site: SiteRepositoryFactory, - subscribe: SubscriptionRepositoryFactory, - download_history: DownloadHistoryRepositoryFactory, - transfer_history: TransferHistoryRepositoryFactory, - transfer_pending: TransferAdmissionRepositoryFactory, - transfer_execution: TransferExecutionRepositoryFactory, - media_server: MediaServerRepositoryFactory, - download_failure: DownloadFailureRepositoryFactory, - user: ChainUserRepositoryFactory, -) -> None: - """由启动组合根登记显式命名的 Chain 数据端口实现。""" - global _ports - _ports = ChainDataPorts( - site=site, - subscribe=subscribe, - download_history=download_history, - transfer_history=transfer_history, - transfer_pending=transfer_pending, - transfer_execution=transfer_execution, - media_server=media_server, - download_failure=download_failure, - user=user, - ) - - -def get_chain_data_ports() -> ChainDataPorts: - """返回启动阶段登记的 Chain 数据端口。""" - if _ports is None: - raise RuntimeError("Chain 数据端口尚未配置") - return _ports - - -def get_chain_site_port() -> SiteRepository: - """创建类型化站点查询与写入端口实例。""" - return get_chain_data_ports().site() - - -def get_chain_subscribe_port() -> SubscriptionRepository: - """创建类型化订阅查询与写入端口实例。""" - return get_chain_data_ports().subscribe() - - -def get_chain_download_history_port() -> DownloadHistoryRepository: - """创建类型化的下载历史查询与事务端口实例。""" - return get_chain_data_ports().download_history() - - -def get_chain_transfer_history_port() -> TransferHistoryRepository: - """创建类型化的整理历史查询与变更端口实例。""" - return get_chain_data_ports().transfer_history() - - -def get_chain_transfer_pending_port() -> TransferAdmissionRepository: - """创建类型化的整理任务 durable admission 仓储。""" - return get_chain_data_ports().transfer_pending() - - -def get_chain_transfer_execution_port() -> TransferExecutionRepository: - """创建类型化的整理步骤执行与终态结算仓储。""" - return get_chain_data_ports().transfer_execution() - - -def get_chain_media_server_port() -> MediaServerRepository: - """创建类型化的媒体服务器本地缓存端口实例。""" - return get_chain_data_ports().media_server() - - -def get_chain_download_failure_port() -> DownloadFailureRepository: - """创建类型化的下载失败冷却持久化端口实例。""" - return get_chain_data_ports().download_failure() - - -def get_chain_user_port() -> ChainUserRepository: - """创建用户数据端口实例。""" - return get_chain_data_ports().user() diff --git a/app/application/messaging/chat.py b/app/application/messaging/chat.py index 9fd5c2c62..8ecbb928b 100644 --- a/app/application/messaging/chat.py +++ b/app/application/messaging/chat.py @@ -3,18 +3,17 @@ from __future__ import annotations import asyncio -from dataclasses import dataclass from collections.abc import Callable -from typing import Any, Optional, Protocol +from dataclasses import dataclass +from typing import Any, List, Optional, Protocol from weakref import WeakValueDictionary from app.application.database import ( AsyncDatabaseExecutor, ) +from app.runtime.observability import record_metric from app.schemas.agent import AgentChatSessionDetail, AgentChatSessionSummary from app.schemas.exception import AgentChatPersistenceUnavailableError -from app.runtime.observability import record_metric - DEFAULT_AGENT_CHAT_WRITE_CAPACITY = 32 DEFAULT_AGENT_CHAT_SESSION_CAPACITY = 4 @@ -245,11 +244,28 @@ class AgentChatService: await self._unit_of_work.rollback() raise - def get_sync(self, session_id: str) -> Optional[AgentChatRecord]: + def get_sync( + self, + session_id: str, + user_id: Optional[str] = None, + ) -> Optional[AgentChatRecord]: """同步读取会话投影,供同步 Agent 编排路径使用。""" - record = self._repository.get(session_id=session_id) + record = self._repository.get(session_id=session_id, user_id=user_id) return self._project(record) if record is not None else None + def save_agent_messages( + self, + session_id: str, + user_id: str, + messages: List[dict[str, Any]], + ) -> None: + """同步保存可恢复消息,兼容非协程 Agent 调用路径。""" + sync_repository = self._repository + save = getattr(sync_repository, "save_agent_messages", None) + if not callable(save): + raise RuntimeError("Agent 会话仓储不支持同步消息保存") + save(session_id=session_id, user_id=user_id, messages=messages) + @staticmethod def can_access( record: AgentChatRecord, diff --git a/app/application/plugin/data.py b/app/application/plugin/data.py index c7c940854..2b589439d 100644 --- a/app/application/plugin/data.py +++ b/app/application/plugin/data.py @@ -1,7 +1,21 @@ -"""插件持久化数据写用例。""" +"""插件持久化数据查询与写用例。""" from typing import Protocol +from app.schemas.common import JsonData + + +class PluginDataQueryRepository(Protocol): + """Agent 插件数据查询所需的类型化异步端口。""" + + async def get(self, plugin_id: str, key: str) -> JsonData: + """读取插件指定键的数据。""" + ... + + async def list(self, plugin_id: str) -> dict[str, JsonData]: + """读取插件全部键值并在 Session 内完成投影。""" + ... + class PluginDataMutationRepository(Protocol): """插件数据删除命令所需的无提交仓储端口。""" diff --git a/app/chain/__init__.py b/app/chain/__init__.py index 4e7770c21..f7af5ed95 100644 --- a/app/chain/__init__.py +++ b/app/chain/__init__.py @@ -56,6 +56,15 @@ class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, self.pluginmanager = context.plugin_manager self.filecache = context.file_cache self.async_filecache = context.async_file_cache + self.site_repository = context.site_repository + self.subscription_repository = context.subscription_repository + self.download_history_repository = context.download_history_repository + self.transfer_history_repository = context.transfer_history_repository + self.transfer_admission_repository = context.transfer_admission_repository + self.transfer_execution_repository = context.transfer_execution_repository + self.media_server_repository = context.media_server_repository + self.download_failure_repository = context.download_failure_repository + self.user_repository = context.user_repository self.runtime_config = context.configuration self.stop_state = context.stop_state self.durable_event_writer = context.durable_event_writer diff --git a/app/chain/_contracts.py b/app/chain/_contracts.py index e51414a8d..2ab7c6f06 100644 --- a/app/chain/_contracts.py +++ b/app/chain/_contracts.py @@ -2,7 +2,11 @@ from __future__ import annotations -from typing import Any, Protocol +from typing import TYPE_CHECKING, Any, Protocol + +if TYPE_CHECKING: + from app.application.history import TransferHistoryRepository + from app.application.transfer.execution import TransferExecutionRepository class ChainRuntimeMixinHost(Protocol): @@ -98,3 +102,5 @@ class TransferMixinHost(ChainRuntimeMixinHost, Protocol): def obtain_images(self, *args: Any, **kwargs: Any) -> Any: ... def do_transfer(self, *args: Any, **kwargs: Any) -> Any: ... + transfer_history_repository: TransferHistoryRepository + transfer_execution_repository: TransferExecutionRepository diff --git a/app/chain/_messaging.py b/app/chain/_messaging.py index c170e7d01..263d083ac 100644 --- a/app/chain/_messaging.py +++ b/app/chain/_messaging.py @@ -8,9 +8,9 @@ import copy from datetime import datetime from typing import Any, Dict, List, Optional, Union, cast -from app.application.chain.data import get_chain_user_port from app.application.messaging.message import MessageTemplateHelper from app.application.notification import get_notification_switch +from app.application.security.user import ChainUserRepository from app.chain._contracts import ChainRuntimeMixinHost from app.domain.context import Context, MediaInfo, MusicInfo, TorrentInfo from app.domain.meta.metabase import MetaBase @@ -120,6 +120,7 @@ class MessageProcessingMixin: class NotificationMixin: __mixin_host_protocol__ = ChainRuntimeMixinHost + user_repository: ChainUserRepository """通知消息发送域:渲染、隔离路由、队列发送与消息编辑。""" def post_message( @@ -178,7 +179,7 @@ class NotificationMixin: # 是否已发送管理员标志 admin_sended = False send_orignal = False - useroper = get_chain_user_port() + useroper = self.user_repository for action in actions: send_message = copy.deepcopy(dispatch_message) if action == "admin" and not admin_sended: @@ -336,7 +337,7 @@ class NotificationMixin: # 是否已发送管理员标志 admin_sended = False send_orignal = False - useroper = get_chain_user_port() + useroper = self.user_repository for action in actions: send_message = copy.deepcopy(dispatch_message) if action == "admin" and not admin_sended: diff --git a/app/chain/_music.py b/app/chain/_music.py index c69ae07bc..e82161792 100644 --- a/app/chain/_music.py +++ b/app/chain/_music.py @@ -1,10 +1,10 @@ import copy from typing import Any, List, Optional, Tuple -from app.application.chain.data import get_chain_subscribe_port from app.application.configuration import get_configured_system_config from app.application.subscription.contract import ( SubscriptionPatch, + SubscriptionRepository, SubscriptionSnapshot, build_subscribe_meta, subscribe_media_key, @@ -37,6 +37,7 @@ def _normalize_music_total_tracks(value: Any) -> Optional[int]: class MusicSubscribeMixin: __mixin_host_protocol__ = MusicSubscribeMixinHost + subscription_repository: SubscriptionRepository """ 音乐订阅功能域 mixin:单曲/专辑目标识别、实体快照同步、候选筛选、 择优下载与完成推进。 @@ -183,8 +184,8 @@ class MusicSubscribeMixin: cover_url=getattr(subscribe, "poster", None) or getattr(subscribe, "backdrop", None), ) - @staticmethod def _sync_music_subscribe_target( + self, subscribe: SubscriptionSnapshot, mediainfo: MusicInfo, ) -> SubscriptionSnapshot: @@ -202,7 +203,7 @@ class MusicSubscribeMixin: update_data["total_tracks"] = total_tracks if not update_data: return subscribe - return get_chain_subscribe_port().update( + return self.subscription_repository.update( subscribe.id, SubscriptionPatch(update_data), ) or subscribe @@ -344,7 +345,7 @@ class MusicSubscribeMixin: context for context in successful if context.confirmed_full_coverage ] - repository = get_chain_subscribe_port() + repository = self.subscription_repository current_subscribe = None if subscribe.best_version and quality_downloads: best_context = max(quality_downloads, key=lambda item: item.torrent_info.pri_order) diff --git a/app/chain/_transfer.py b/app/chain/_transfer.py index ac28040f3..e9bb3f3c3 100644 --- a/app/chain/_transfer.py +++ b/app/chain/_transfer.py @@ -13,10 +13,6 @@ from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast from app.adapters.system.host import SystemUtils from app.application.agent import build_manual_redo_prompt, get_running_agent_manager -from app.application.chain.data import ( - get_chain_transfer_execution_port, - get_chain_transfer_history_port, -) from app.application.configuration import ( get_chain_runtime_config_snapshot, get_configured_system_config, @@ -31,7 +27,10 @@ from app.application.history import ( clear_transfer_failures, resolve_history, ) -from app.application.transfer.execution import TransferExecutionCommand +from app.application.transfer.execution import ( + TransferExecutionCommand, + TransferExecutionRepository, +) from app.application.transfer.workflow import TransferTask, job_lock from app.chain._contracts import TransferMixinHost from app.chain.media import MediaChain @@ -65,15 +64,14 @@ def _request_durable_transfer_retry( history: TransferHistorySnapshot, *, requested_by: str, + repository: TransferExecutionRepository, ) -> Optional[Tuple[bool, str]]: """将 durable 历史重试交还持久调度器,旧历史返回 ``None``。""" task_id = getattr(history, "transfer_task_id", None) if not task_id: return None try: - result = TransferExecutionCommand( - get_chain_transfer_execution_port() - ).request_retry( + result = TransferExecutionCommand(repository).request_retry( task_id=task_id, reason=f"用户请求重试整理历史 #{history.id}", requested_by=requested_by, @@ -1164,6 +1162,9 @@ class FileKeyMixin: class ManualHistoryMixin: __mixin_host_protocol__ = TransferMixinHost + transfer_history_repository: TransferHistoryRepository + transfer_execution_repository: TransferExecutionRepository + @staticmethod def _get_subscribe_custom_words( history_record: Optional[DownloadHistorySnapshot], @@ -1237,7 +1238,7 @@ class ManualHistoryMixin: :param fileitems: 待查询的文件或目录项 :return: 去重后的成功整理记录 """ - transfer_history_oper = get_chain_transfer_history_port() + transfer_history_oper = self.transfer_history_repository histories: Dict[int, TransferHistorySnapshot] = {} for fileitem in fileitems or []: if not fileitem or not fileitem.path: @@ -1286,6 +1287,7 @@ class ManualHistoryMixin: return _request_durable_transfer_retry( history, requested_by=requested_by, + repository=self.transfer_execution_repository, ) def _delete_manual_transfer_history( @@ -1323,6 +1325,9 @@ class ManualHistoryMixin: class FailedRetryMixin: __mixin_host_protocol__ = TransferMixinHost + transfer_history_repository: TransferHistoryRepository + transfer_execution_repository: TransferExecutionRepository + @staticmethod def build_failed_transfer_buttons( history_id: Optional[int], @@ -1462,7 +1467,7 @@ class FailedRetryMixin: 由智能助手接管一条失败的整理记录。 """ - history = get_chain_transfer_history_port().get(history_id) + history = self.transfer_history_repository.get(history_id) if not history: host = cast(TransferMixinHost, self) host.post_message( @@ -1482,6 +1487,7 @@ class FailedRetryMixin: durable_retry = _request_durable_transfer_retry( history, requested_by="ai_retry_button", + repository=self.transfer_execution_repository, ) if durable_retry is not None: accepted, message = durable_retry @@ -1614,13 +1620,14 @@ class FailedRetryMixin: :param media_id: 数据源原生 ID,必须与 media_source 成对提供 """ # 查询历史记录 - history = get_chain_transfer_history_port().get(logid) + history = self.transfer_history_repository.get(logid) if not history: logger.error(f"整理记录不存在,ID:{logid}") return False, "整理记录不存在" durable_retry = _request_durable_transfer_retry( history, requested_by="history_redo", + repository=self.transfer_execution_repository, ) if durable_retry is not None: return durable_retry diff --git a/app/chain/download.py b/app/chain/download.py index 56e6a99ca..e943dc7a9 100644 --- a/app/chain/download.py +++ b/app/chain/download.py @@ -11,11 +11,6 @@ from urllib.parse import parse_qs, urlencode, urljoin, urlparse from app.adapters.network.http import RequestUtils from app.adapters.system.host import SystemUtils -from app.application.chain.data import ( - get_chain_download_failure_port, - get_chain_download_history_port, - get_chain_media_server_port, -) from app.application.configuration import get_chain_runtime_config_snapshot from app.application.directory import DirectoryHelper, validate_download_save_path from app.application.download import selection as _selection @@ -880,7 +875,7 @@ class DownloadChain(ChainBase): torrent = context.torrent_info site = getattr(torrent, "site", None) try: - repository: DownloadFailureRepository = get_chain_download_failure_port() + repository: DownloadFailureRepository = self.download_failure_repository repository.record_failure( DownloadFailureWrite( fingerprint=fingerprint, @@ -941,7 +936,7 @@ class DownloadChain(ChainBase): return {} now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) try: - repository: DownloadFailureRepository = get_chain_download_failure_port() + repository: DownloadFailureRepository = self.download_failure_repository return repository.get_active_by_fingerprints( fingerprints=fingerprints, now_time=now_time, ) @@ -1336,7 +1331,7 @@ class DownloadChain(ChainBase): publish=lambda payload: self.eventmanager.send_event(EventType.DownloadAdded, payload), ) return - get_chain_download_history_port().add(history, frozen_files) + self.download_history_repository.add(history, frozen_files) after_commit() self.eventmanager.send_event(EventType.DownloadAdded, event_payload) @@ -2046,7 +2041,7 @@ class DownloadChain(ChainBase): if not totals: totals = {} - mediaserver = get_chain_media_server_port() + mediaserver = self.media_server_repository if mediainfo.type == MediaType.MOVIE: # 电影 itemid = mediaserver.get_item_id(mtype=mediainfo.type.value, @@ -2234,7 +2229,7 @@ class DownloadChain(ChainBase): """构造绑定当前下载器能力与历史仓储的任务服务。""" return DownloadTaskService( list_torrents=self.list_torrents, - get_history_by_hashes=get_chain_download_history_port().get_by_hashes, + get_history_by_hashes=self.download_history_repository.get_by_hashes, start_torrents=self.start_torrents, stop_torrents=self.stop_torrents, remove_torrents=self.remove_torrents, diff --git a/app/chain/interaction.py b/app/chain/interaction.py index 3a3946771..bb939708f 100644 --- a/app/chain/interaction.py +++ b/app/chain/interaction.py @@ -2,7 +2,6 @@ import math import re from typing import Any, Dict, List, Optional, Tuple, Union -from app.application.chain.data import get_chain_user_port from app.application.directory import DirectoryHelper from app.application.messaging.media import ( PendingMediaInteraction, @@ -669,7 +668,7 @@ class MediaInteractionChain(ChainBase): return mp_name = ( - get_chain_user_port().find_name_by_bindings( + self.user_repository.find_name_by_bindings( {f"{channel.name.lower()}_userid": userid} ) if channel @@ -982,7 +981,7 @@ class MediaInteractionChain(ChainBase): note = None mp_name = ( - get_chain_user_port().find_name_by_bindings( + self.user_repository.find_name_by_bindings( {f"{channel.name.lower()}_userid": userid} ) if channel diff --git a/app/chain/mediaserver.py b/app/chain/mediaserver.py index fb4466d49..18a0b2854 100644 --- a/app/chain/mediaserver.py +++ b/app/chain/mediaserver.py @@ -2,7 +2,6 @@ import threading from datetime import datetime from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union -from app.application.chain.data import get_chain_media_server_port from app.application.mediaserver import ( MediaServerRepository, MediaServerSyncItem, @@ -473,7 +472,7 @@ class MediaServerChain(ChainBase): with lock: # 汇总统计 total_count = 0 - repository = get_chain_media_server_port() + repository = self.media_server_repository mediaservers, total_servers, server_sync_contexts, global_media_total = ( self._prepare_sync_contexts(mediaservers, server, repository) ) diff --git a/app/chain/site.py b/app/chain/site.py index d6d94238b..f70ff9e0a 100644 --- a/app/chain/site.py +++ b/app/chain/site.py @@ -11,7 +11,6 @@ from app.adapters.external.cookiecloud import CookieCloudHelper from app.adapters.network.browser import PlaywrightHelper from app.adapters.network.cloudflare import under_challenge from app.adapters.network.http import RequestUtils -from app.application.chain.data import get_chain_site_port from app.application.configuration import get_configured_system_config from app.application.messaging.site import SiteInteractionHandler from app.application.rss import RssHelper @@ -77,7 +76,7 @@ class SiteChain(InteractionChainMixin, ChainBase): str(site.get("domain") or site.get("url") or "") ) name = str(site.get("name") or domain) - get_chain_site_port().update_userdata( + self.site_repository.update_userdata( domain=domain, name=name, mutation=SiteUserDataMutation(userdata.model_dump()), @@ -439,7 +438,7 @@ class SiteChain(InteractionChainMixin, ChainBase): self.messagehelper.put(msg, title="CookieCloud同步失败", role="system") return False, msg siteshelper = SitesHelper() - repository = get_chain_site_port() + repository = self.site_repository rsshelper = RssHelper() total_num = len(cookies) update_count = add_count = fail_count = 0 @@ -604,7 +603,7 @@ class SiteChain(InteractionChainMixin, ChainBase): if str(domain).startswith("http"): domain = site_rules.extract_domain(domain) # 站点信息 - repository = get_chain_site_port() + repository = self.site_repository siteshelper = SitesHelper() siteinfo = repository.get_by_domain(domain) if not siteinfo: @@ -687,7 +686,7 @@ class SiteChain(InteractionChainMixin, ChainBase): """ # 检查域名是否可用 domain = site_rules.extract_domain(url) - repository = get_chain_site_port() + repository = self.site_repository site_info = repository.get_by_domain(domain) if not site_info: return False, f"站点【{url}】不存在" @@ -765,7 +764,7 @@ class SiteChain(InteractionChainMixin, ChainBase): return SiteInteractionHandler( messenger=self, cookie_updater=self.update_cookie, - repository=get_chain_site_port(), + repository=self.site_repository, ) def remote_disable(self, arg_str: str, channel: NotificationChannel, @@ -779,7 +778,7 @@ class SiteChain(InteractionChainMixin, ChainBase): if not arg_str.isdigit(): return site_id = int(arg_str) - repository = get_chain_site_port() + repository = self.site_repository site = repository.get(site_id) if not site: self.post_message(Message( @@ -801,7 +800,7 @@ class SiteChain(InteractionChainMixin, ChainBase): if not arg_str: return arg_strs = str(arg_str).split() - repository = get_chain_site_port() + repository = self.site_repository for arg_str in arg_strs: arg_str = arg_str.strip() if not arg_str.isdigit(): @@ -843,7 +842,7 @@ class SiteChain(InteractionChainMixin, ChainBase): cookie, ua, msg = result if not cookie: return False, msg - get_chain_site_port().update(site_info.id, SiteMutation({ + self.site_repository.update(site_info.id, SiteMutation({ "cookie": cookie, "ua": ua })) @@ -891,7 +890,7 @@ class SiteChain(InteractionChainMixin, ChainBase): # 站点ID site_id = int(raw_site_id) # 站点信息 - site_info = get_chain_site_port().get(site_id) + site_info = self.site_repository.get(site_id) if not site_info: self.post_message(Message( channel=channel, diff --git a/app/chain/subscribe.py b/app/chain/subscribe.py index 228e99176..ad8eae4d2 100644 --- a/app/chain/subscribe.py +++ b/app/chain/subscribe.py @@ -8,11 +8,6 @@ from datetime import datetime from typing import Any, Callable, Dict, List, Optional, Tuple, Union from app.adapters.external.server import MoviePilotServerHelper -from app.application.chain.data import ( - get_chain_download_history_port, - get_chain_site_port, - get_chain_subscribe_port, -) from app.application.configuration import ( get_chain_runtime_config_snapshot, get_configured_system_config, @@ -1170,17 +1165,24 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): await self.__async_finalize_subscribe_create_context(context) return await self.__async_persist_subscribe_create(context) - @staticmethod - def _subscription_query() -> SubscriptionQueryService: + def _subscription_query(self) -> SubscriptionQueryService: """构造绑定订阅 Oper 的查询应用服务。""" - return SubscriptionQueryService(get_chain_subscribe_port()) + return SubscriptionQueryService(self.subscription_repository) @classmethod - def exists(cls, mediainfo: MediaInfo, meta: MetaBase = None): + def exists( + cls, + mediainfo: MediaInfo, + meta: MetaBase = None, + repository: Optional[SubscriptionRepository] = None, + ) -> bool: """ 判断订阅是否已存在 """ - return cls._subscription_query().exists(mediainfo, meta) + chain = cls() + if repository is not None: + chain.subscription_repository = repository + return chain._subscription_query().exists(mediainfo, meta) def _acquire_run_lock( self, @@ -1248,7 +1250,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): if not lock_acquired: return - repository = get_chain_subscribe_port() + repository = self.subscription_repository if sid: subscribe = repository.get(sid) subscribes = [subscribe] if subscribe else [] @@ -1500,8 +1502,8 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): self._rlock.release() logger.debug(f"search Lock released at {datetime.now()}") - @staticmethod def __update_movie_download_priority( + self, subscribe: SubscriptionSnapshot, mediainfo: MediaInfo, downloads: Optional[List[Context]], @@ -1517,7 +1519,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): if subscribe.type != MediaType.MOVIE.value: return subscribe - updated = get_chain_subscribe_port().update( + updated = self.subscription_repository.update( subscribe.id, SubscriptionPatch({"current_priority": priority, "last_update": now}) ) if subscribe.best_version and priority != 100: @@ -1676,7 +1678,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): :return: 返回[]代表所有站点命中,返回None代表没有订阅 """ ret_sites = [] - subscribes = get_chain_subscribe_port().list() + subscribes = self.subscription_repository.list() if not subscribes: # 没有订阅 return None @@ -1796,7 +1798,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): processed_torrents = self._prepare_match_torrents(torrents) # 所有订阅 - subscribes = get_chain_subscribe_port().list(self.get_states_for_search("R")) + subscribes = self.subscription_repository.list(self.get_states_for_search("R")) total_num = len(subscribes) if progress_callback: progress_callback( @@ -1832,7 +1834,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): # 订阅的站点域名列表 domains = [] if subscribe.sites: - domains = get_chain_site_port().get_domains_by_ids(subscribe.sites) + domains = self.site_repository.get_domains_by_ids(subscribe.sites) # 识别媒体信息 mediainfo: MediaInfo = MediaChain().recognize_media( meta=meta, @@ -2114,7 +2116,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): ) # 同步外部修改,更新订阅信息 - updated_subscribe = get_chain_subscribe_port().get(subscribe.id) + updated_subscribe = self.subscription_repository.get(subscribe.id) # 判断是否要完成订阅 if updated_subscribe: @@ -2148,7 +2150,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): :param progress_callback: 定时服务进度更新回调 """ # 查询所有订阅 - repository = get_chain_subscribe_port() + repository = self.subscription_repository subscribes = repository.list() total_num = len(subscribes) if progress_callback: @@ -2284,13 +2286,20 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): """ return self._subscription_query().get_by_source(self.parse_subscribe_source_keyword(source)) - @staticmethod - def follow(progress_callback: Optional[Callable[..., None]] = None) -> None: + @classmethod + def follow( + cls, + progress_callback: Optional[Callable[..., None]] = None, + repository: Optional[SubscriptionRepository] = None, + ) -> None: """ 刷新follow的用户分享,并自动添加订阅 :param progress_callback: 定时服务进度更新回调 """ + self = cls() + if repository is not None: + self.subscription_repository = repository follow_users: List[str] = _system_config().get(SystemConfigKey.FollowSubscribers) if not follow_users: if progress_callback: @@ -2298,7 +2307,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): return logger.info("开始刷新follow用户分享订阅 ...") success_count = 0 - repository = get_chain_subscribe_port() + repository = self.subscription_repository share_subscribes = MoviePilotServerHelper.get_subscribe_shares() or [] total_num = len(share_subscribes) if progress_callback: @@ -2404,7 +2413,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): :param progress_callback: 定时服务进度更新回调 """ logger.info("开始预缓存订阅日历 ...") - subscribes = await get_chain_subscribe_port().async_list() + subscribes = await self.subscription_repository.async_list() total_num = len(subscribes) if progress_callback: progress_callback( @@ -2465,8 +2474,11 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): if progress_callback: progress_callback(value=100, text="订阅日历预缓存完成") - @staticmethod - def __update_subscribe_note(subscribe: SubscriptionSnapshot, downloads: Optional[List[Context]]): + def __update_subscribe_note( + self, + subscribe: SubscriptionSnapshot, + downloads: Optional[List[Context]], + ) -> None: """ 更新已下载信息到note字段 """ @@ -2505,7 +2517,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): note = list(set(note).union(set(items))) # 更新订阅 if note: - get_chain_subscribe_port().update(subscribe.id, SubscriptionPatch({"note": note})) + self.subscription_repository.update(subscribe.id, SubscriptionPatch({"note": note})) @staticmethod def __get_downloaded(subscribe: SubscriptionSnapshot) -> List[int]: @@ -2550,8 +2562,8 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): touch_last_update=touch_last_update, ) - @staticmethod def __apply_subscribe_update( + self, subscribe: SubscriptionSnapshot, update_data: Dict[str, Any], ) -> SubscriptionSnapshot: @@ -2561,7 +2573,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): if not update_data: return subscribe return ( - get_chain_subscribe_port().update( + self.subscription_repository.update( subscribe.id, SubscriptionPatch(update_data), ) @@ -2908,7 +2920,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): return SubscribeInteractionHandler( messenger=self, actions=self, - repository=get_chain_subscribe_port(), + repository=self.subscription_repository, delete_subscription=self._delete_subscription, ) @@ -3090,7 +3102,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): site_id = event_data.get("site_id") if not site_id: return - repository = get_chain_subscribe_port() + repository = self.subscription_repository if site_id == "*": # 站点被重置 _system_config().set(SystemConfigKey.RssSites, []) @@ -3139,8 +3151,8 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): self._reconcile_rule_group_references(valid_names=_rule_group_names(value)) - @staticmethod def _reconcile_rule_group_references( + self, valid_names: set[str], repository: Optional[SubscriptionRepository] = None, subscribes: Optional[List[SubscriptionSnapshot]] = None, @@ -3171,7 +3183,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): updated["filter_groups"] = updated_groups system_config.set(config_key, updated) - repository = repository or get_chain_subscribe_port() + repository = repository or self.subscription_repository target_subscribes = subscribes if subscribes is not None else repository.list() for index, subscribe in enumerate(target_subscribes): original = getattr(subscribe, "filter_groups", None) or [] @@ -3277,7 +3289,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): episodes[0] = info # 所有下载记录 - downloadhis = get_chain_download_history_port() + downloadhis = self.download_history_repository download_his = [] if subscribe.media_source and subscribe.media_id: download_his = downloadhis.get_by_media_identity( @@ -3790,7 +3802,7 @@ class SubscribeChain(MusicSubscribeMixin, InteractionChainMixin, ChainBase): ) update_data["last_update"] = now subscribe = ( - get_chain_subscribe_port().update( + self.subscription_repository.update( subscribe.id, SubscriptionPatch(update_data), ) diff --git a/app/chain/torrents.py b/app/chain/torrents.py index 475434b97..2bbc82800 100644 --- a/app/chain/torrents.py +++ b/app/chain/torrents.py @@ -3,7 +3,6 @@ import re import traceback from typing import Callable, Dict, List, Optional, Union -from app.application.chain.data import get_chain_site_port from app.application.configuration import get_configured_system_config from app.application.rss import RssHelper from app.application.site.sites import SitesHelper # pylint: disable=import-error,no-name-in-module @@ -802,7 +801,7 @@ class TorrentsChain(ChainBase): # 获取过期rss除去passkey部分 new_rss = re.sub(r'&passkey=([a-zA-Z0-9]+)', f'&passkey={new_passkey}', site.get("rss")) logger.info(f"更新站点 {domain} RSS地址 ...") - get_chain_site_port().update_rss(domain=domain, rss=new_rss) + self.site_repository.update_rss(domain=domain, rss=new_rss) else: # 发送消息 self.post_message( diff --git a/app/chain/transfer.py b/app/chain/transfer.py index 58b2ecc30..d1c72ff21 100755 --- a/app/chain/transfer.py +++ b/app/chain/transfer.py @@ -14,12 +14,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union, c from pydantic_core import to_jsonable_python -from app.application.chain.data import ( - get_chain_download_history_port, - get_chain_transfer_execution_port, - get_chain_transfer_history_port, - get_chain_transfer_pending_port, -) +from app.application.chain.context import ChainRuntimeContext from app.application.chain.events import TransferResultSettlement from app.application.configuration import get_configured_system_config from app.application.directory import DirectoryHelper @@ -509,7 +504,7 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo transferinfo: TransferInfo, ) -> None: """无公开事件地原子提交旧同步调用的历史回执与任务终态。""" - transferhis = get_chain_transfer_history_port() + transferhis = self.transfer_history_repository overwrite_declined = self._is_overwrite_declined( task, transferinfo, @@ -615,9 +610,12 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo else: raise ValueError(f"不支持的整理结果事件:{event_type}") - def __init__(self) -> None: + def __init__( + self, + runtime_context: Optional[ChainRuntimeContext] = None, + ) -> None: """初始化文件整理处理链。""" - super().__init__() + super().__init__(runtime_context=runtime_context) # 主要媒体文件后缀 self._media_exts = self.runtime_config.video_extensions # 字幕文件后缀 @@ -640,8 +638,8 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo # 整理失败通知聚合器 self.failure_notification_aggregator = TransferFailureNotificationAggregator() # durable admission 仓储先于内存入队保存任务,进程退出后仍可恢复。 - self._transfer_admissions = get_chain_transfer_pending_port() - self._transfer_executions = get_chain_transfer_execution_port() + self._transfer_admissions = self.transfer_admission_repository + self._transfer_executions = self.transfer_execution_repository # 转移成功的文件清单 self._success_target_files: Dict[Tuple, List[str]] = {} # 批次级刮削缓冲,避免同一批多文件入库重复触发目录刮削 @@ -931,7 +929,7 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo username=task.username, ) - transferhis = get_chain_transfer_history_port() + transferhis = self.transfer_history_repository target_dir_path = self.__get_transfer_target_dir_path(transferinfo) job_id = self.jobview.get_job_id(task) overwrite_declined = False @@ -3386,7 +3384,7 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo if task.plan_checkpoint is not None: return self.__handle_planned_transfer(task, callback) # 识别 - transferhis = get_chain_transfer_history_port() + transferhis = self.transfer_history_repository # 显式标注联合:下面既会赋回音乐识别结果(MusicInfo),也会赋回影视识别 # 结果(MediaInfo),不标注时会被推断成其中一种,另一种就成了假错误 mediainfo: Optional[Union[MediaInfo, MusicInfo]] = task.mediainfo @@ -3689,7 +3687,7 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo # 查询下载记录识别情况 downloadhis: Optional[DownloadHistorySnapshot] = ( - get_chain_download_history_port().get_by_hash(torrent.hash) + self.download_history_repository.get_by_hash(torrent.hash) if torrent.hash else None ) @@ -4401,7 +4399,7 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo if not items: return [], {} - download_history_repository = get_chain_download_history_port() + download_history_repository = self.download_history_repository inherited_map: Dict[Tuple[str, str], MetaBase] = {} main_items_by_dir, extra_items_by_dir = _build_directory_index(items) main_items = [ @@ -4616,7 +4614,7 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo # 成功但源文件已变化放行交 overwrite_mode 决断);手动整理可清理失败记录, # 或按用户确认清理成功记录。 if (not force or reorganize) and not preview: - transfer_history_oper = get_chain_transfer_history_port() + transfer_history_oper = self.transfer_history_repository transferd = self._get_manual_transfer_history( fileitem=file_item, transfer_history_oper=transfer_history_oper, @@ -4700,7 +4698,7 @@ class TransferChain(FileFilterMixin, ScrapeBatchMixin, EpisodeFormatMixin, Histo continue # 提前获取下载历史,以便获取自定义识别词 - download_history_repository = get_chain_download_history_port() + download_history_repository = self.download_history_repository download_history = self._resolve_download_history( repository=download_history_repository, file_path=file_path, diff --git a/app/chain/user.py b/app/chain/user.py index 36e2d7b1c..87df8505b 100644 --- a/app/chain/user.py +++ b/app/chain/user.py @@ -2,7 +2,6 @@ import secrets from dataclasses import dataclass from typing import Literal, Optional, Tuple, Union -from app.application.chain.data import get_chain_user_port from app.application.security.otp import OtpUtils from app.application.security.token import get_password_hash, verify_password from app.application.security.user import AuxiliaryUserCreate, UserAuthSnapshot @@ -104,8 +103,9 @@ class UserChain(ChainBase): logger.debug(f"辅助认证未启用,认证类型 {grant_type} 未实现") return False, "不支持的认证类型" - @staticmethod + @classmethod def password_authenticate( + cls, credentials: AuthCredentials, ) -> Tuple[bool, Union[UserAuthSnapshot, str]]: """ @@ -123,7 +123,7 @@ class UserChain(ChainBase): logger.info("密码认证失败,用户名或密码为空") return False, PASSWORD_INVALID_CREDENTIALS_MESSAGE - user = get_chain_user_port().get_auth_by_name(name=credentials.username) + user = cls().user_repository.get_auth_by_name(name=credentials.username) if not user: logger.info(f"密码认证失败,用户 {credentials.username} 不存在") return False, PASSWORD_INVALID_CREDENTIALS_MESSAGE @@ -154,7 +154,7 @@ class UserChain(ChainBase): return False, "认证凭证无效" # 检查是否因为用户被禁用 - useroper = get_chain_user_port() + useroper = self.user_repository if credentials.username: user = useroper.get_auth_by_name(name=credentials.username) if user and not user.is_active: @@ -254,7 +254,7 @@ class UserChain(ChainBase): return False # 检查用户是否存在,如果不存在且当前为密码认证时则创建新用户 - useroper = get_chain_user_port() + useroper = self.user_repository user = useroper.get_auth_by_name(name=username) if user: # 如果用户存在,但是已经被禁用,则直接响应 diff --git a/app/db/adapters/agent.py b/app/db/adapters/agent.py new file mode 100644 index 000000000..89909277f --- /dev/null +++ b/app/db/adapters/agent.py @@ -0,0 +1,351 @@ +"""Agent 自主任务与插件数据的类型化持久化适配器。""" + +from __future__ import annotations + +from collections.abc import Callable +from contextlib import AbstractAsyncContextManager +from copy import deepcopy +from typing import List, Optional, TypeVar, cast + +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import Session + +from app.application.agenttask import ( + AgentTaskFinishOutcome, + AgentTaskRunSnapshot, + AgentTaskSnapshot, +) +from app.db.oper.agenttask import AgentTaskOper +from app.db.oper.plugindata import PluginDataOper +from app.db.uow import SqlAlchemyUnitOfWork +from app.schemas.common import JsonData + +ResultT = TypeVar("ResultT") + + +def _project_task(record: object) -> AgentTaskSnapshot: + """在 Session 内把自主任务 ORM 记录投影为冻结快照。""" + task_id = getattr(record, "id", None) + name = getattr(record, "name", None) + content = getattr(record, "content", None) + trigger_type = getattr(record, "trigger_type", None) + user_id = getattr(record, "user_id", None) + session_id = getattr(record, "session_id", None) + created_at = getattr(record, "created_at", None) + updated_at = getattr(record, "updated_at", None) + if ( + not isinstance(task_id, int) + or not isinstance(name, str) + or not isinstance(content, str) + or not isinstance(trigger_type, str) + or not isinstance(user_id, str) + or not isinstance(session_id, str) + or not isinstance(created_at, str) + or not isinstance(updated_at, str) + ): + raise ValueError("Agent 自主任务缺少稳定身份或必需字段") + return AgentTaskSnapshot( + id=task_id, + name=name, + content=content, + trigger_type=trigger_type, + cron_expression=getattr(record, "cron_expression", None), + run_at=getattr(record, "run_at", None), + enabled=bool(getattr(record, "enabled", False)), + user_id=user_id, + username=getattr(record, "username", None), + session_id=session_id, + channel=getattr(record, "channel", None), + source=getattr(record, "source", None), + original_chat_id=getattr(record, "original_chat_id", None), + last_status=str(getattr(record, "last_status", "")), + last_run_at=getattr(record, "last_run_at", None), + last_result=getattr(record, "last_result", None), + last_run_id=getattr(record, "last_run_id", None), + run_count=int(getattr(record, "run_count", 0) or 0), + created_at=created_at, + updated_at=updated_at, + ) + + +def _project_run(record: object) -> AgentTaskRunSnapshot: + """在 Session 内把自主任务运行 ORM 记录投影为冻结快照。""" + run_id = getattr(record, "run_id", None) + task_id = getattr(record, "task_id", None) + trigger_source = getattr(record, "trigger_source", None) + name = getattr(record, "name", None) + content = getattr(record, "content", None) + trigger_type = getattr(record, "trigger_type", None) + user_id = getattr(record, "user_id", None) + session_id = getattr(record, "session_id", None) + status = getattr(record, "status", None) + started_at = getattr(record, "started_at", None) + if ( + not isinstance(run_id, str) + or not isinstance(task_id, int) + or not isinstance(trigger_source, str) + or not isinstance(name, str) + or not isinstance(content, str) + or not isinstance(trigger_type, str) + or not isinstance(user_id, str) + or not isinstance(session_id, str) + or not isinstance(status, str) + or not isinstance(started_at, str) + ): + raise ValueError("Agent 自主任务运行记录缺少稳定身份或必需字段") + return AgentTaskRunSnapshot( + run_id=run_id, + task_id=task_id, + trigger_source=trigger_source, + name=name, + content=content, + trigger_type=trigger_type, + cron_expression=getattr(record, "cron_expression", None), + run_at=getattr(record, "run_at", None), + user_id=user_id, + username=getattr(record, "username", None), + session_id=session_id, + channel=getattr(record, "channel", None), + message_source=getattr(record, "message_source", None), + original_chat_id=getattr(record, "original_chat_id", None), + status=status, + started_at=started_at, + finished_at=getattr(record, "finished_at", None), + result=getattr(record, "result", None), + ) + + +class SessionAgentTaskRepository: + """把调用方同步 Session 适配为类型化自主任务仓储。""" + + def __init__(self, session: Session) -> None: + """保存调用方独占的同步 Session。""" + self._repository = AgentTaskOper(session) + + def add(self, **values: object) -> AgentTaskSnapshot | None: + """暂存新增任务并返回冻结快照。""" + record = self._repository.add(**values) + return _project_task(record) if record is not None else None + + def get( + self, + task_id: int, + user_id: Optional[str] = None, + ) -> AgentTaskSnapshot | None: + """读取一条任务并在 Session 内投影。""" + record = self._repository.get(task_id=task_id, user_id=user_id) + return _project_task(record) if record is not None else None + + def list( + self, + user_id: Optional[str] = None, + enabled: Optional[bool] = None, + ) -> list[AgentTaskSnapshot]: + """读取任务列表并在 Session 内投影。""" + return [ + _project_task(record) + for record in self._repository.list(user_id=user_id, enabled=enabled) + ] + + def update( + self, + task_id: int, + payload: dict[str, object], + user_id: Optional[str] = None, + ) -> bool: + """暂存任务更新。""" + return self._repository.update(task_id, payload, user_id) + + def delete(self, task_id: int, user_id: Optional[str] = None) -> bool: + """暂存任务及运行记录删除。""" + return self._repository.delete(task_id, user_id) + + def mark_interrupted(self, task_id: int, result: str) -> bool: + """暂存遗留运行态收口。""" + return self._repository.mark_interrupted(task_id, result) + + def begin_run( + self, + task_id: int, + trigger_source: str = "scheduled", + *, + run_id: str | None = None, + ) -> AgentTaskRunSnapshot | None: + """原子认领任务并返回运行快照。""" + record = self._repository.begin_run( + task_id, + trigger_source, + run_id=run_id, + ) + return _project_run(record) if record is not None else None + + def list_runs( + self, + task_id: int, + user_id: Optional[str] = None, + limit: int = 10, + ) -> List[AgentTaskRunSnapshot]: + """读取最近运行并在 Session 内投影。""" + return [ + _project_run(record) + for record in self._repository.list_runs(task_id, user_id, limit) + ] + + def finish_run_outcome( + self, + run_id: str, + success: bool, + result: str, + ) -> AgentTaskFinishOutcome: + """暂存精确运行收口并返回结构化事实。""" + outcome = self._repository.finish_run_outcome(run_id, success, result) + return AgentTaskFinishOutcome( + run_finalized=outcome.run_finalized, + task_projection_updated=outcome.task_projection_updated, + date_task_disabled=outcome.date_task_disabled, + ) + + +class TransactionalAgentTaskRepository: + """为 Scheduler 和 Agent 工具创建短生命周期自主任务事务。""" + + def __init__(self, session: Callable[[], Session]) -> None: + """保存由启动组合根提供的同步 Session 工厂。""" + self._session = session + + def _read( + self, + operation: Callable[[SessionAgentTaskRepository], ResultT], + ) -> ResultT: + """在独立 Session 内执行一次查询并完成投影。""" + session = self._session() + try: + return operation(SessionAgentTaskRepository(session)) + finally: + session.close() + + def _write( + self, + operation: Callable[[SessionAgentTaskRepository], ResultT], + ) -> ResultT: + """在独立短事务中执行一次写入。""" + session = self._session() + unit_of_work = SqlAlchemyUnitOfWork(session) + try: + result = operation(SessionAgentTaskRepository(session)) + unit_of_work.commit() + return result + except Exception: + unit_of_work.rollback() + raise + finally: + session.close() + + def add(self, **values: object) -> AgentTaskSnapshot | None: + """新增任务并提交短事务。""" + return self._write(lambda repository: repository.add(**values)) + + def get( + self, + task_id: int, + user_id: Optional[str] = None, + ) -> AgentTaskSnapshot | None: + """读取任务冻结快照。""" + return self._read(lambda repository: repository.get(task_id, user_id)) + + def list( + self, + user_id: Optional[str] = None, + enabled: Optional[bool] = None, + ) -> list[AgentTaskSnapshot]: + """读取任务冻结快照列表。""" + return self._read(lambda repository: repository.list(user_id, enabled)) + + def update( + self, + task_id: int, + payload: dict[str, object], + user_id: Optional[str] = None, + ) -> bool: + """更新任务并提交短事务。""" + return self._write( + lambda repository: repository.update(task_id, payload, user_id) + ) + + def delete(self, task_id: int, user_id: Optional[str] = None) -> bool: + """删除任务并提交短事务。""" + return self._write(lambda repository: repository.delete(task_id, user_id)) + + def mark_interrupted(self, task_id: int, result: str) -> bool: + """收口遗留运行态并提交短事务。""" + return self._write( + lambda repository: repository.mark_interrupted(task_id, result) + ) + + def begin_run( + self, + task_id: int, + trigger_source: str = "scheduled", + *, + run_id: str | None = None, + ) -> AgentTaskRunSnapshot | None: + """认领任务并提交短事务。""" + return self._write( + lambda repository: repository.begin_run( + task_id, + trigger_source, + run_id=run_id, + ) + ) + + def list_runs( + self, + task_id: int, + user_id: Optional[str] = None, + limit: int = 10, + ) -> List[AgentTaskRunSnapshot]: + """读取任务最近运行快照。""" + return self._read( + lambda repository: repository.list_runs(task_id, user_id, limit) + ) + + def finish_run_outcome( + self, + run_id: str, + success: bool, + result: str, + ) -> AgentTaskFinishOutcome: + """收口运行并提交短事务。""" + return self._write( + lambda repository: repository.finish_run_outcome( + run_id, + success, + result, + ) + ) + + +class TransactionalPluginDataRepository: + """为 Agent 插件数据读取创建短生命周期异步 Session。""" + + def __init__( + self, + async_session: Callable[[], AbstractAsyncContextManager[AsyncSession]], + ) -> None: + """保存由启动组合根提供的异步 Session 工厂。""" + self._async_session = async_session + + async def get(self, plugin_id: str, key: str) -> JsonData: + """读取单个键并复制 JSON 值。""" + async with self._async_session() as session: + value = await PluginDataOper(session).async_get_data(plugin_id, key) + return cast(JsonData, deepcopy(value)) + + async def list(self, plugin_id: str) -> dict[str, JsonData]: + """读取全部键值并在 Session 内投影为普通字典。""" + async with self._async_session() as session: + rows = await PluginDataOper(session).async_get_data_all(plugin_id) or [] + return { + str(row.key): cast(JsonData, deepcopy(row.value)) + for row in rows + } diff --git a/app/db/models/subscribehistory.py b/app/db/models/subscribehistory.py index ad663b226..5fd71cec8 100644 --- a/app/db/models/subscribehistory.py +++ b/app/db/models/subscribehistory.py @@ -1,6 +1,6 @@ from typing import Any, Optional -from sqlalchemy import Integer, String, Float, JSON, Index, or_, select +from sqlalchemy import JSON, Float, Index, Integer, String, or_, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Mapped, Session, mapped_column diff --git a/app/scheduler.py b/app/scheduler.py index 85ac60140..24af1859c 100644 --- a/app/scheduler.py +++ b/app/scheduler.py @@ -19,7 +19,7 @@ from apscheduler.triggers.cron import CronTrigger from app.adapters.external.server import MoviePilotServerHelper from app.adapters.system.update import system_update_manager -from app.application.agentdata import get_agent_task_port +from app.application.agenttask import AgentTaskRepository from app.application.configuration import ( SchedulerRuntimeConfig, get_configured_system_config, @@ -163,6 +163,19 @@ class Scheduler(ConfigReloadMixin, metaclass=SingletonClass): self._auth_message = False # 插件已按认证结果重建,但动态路由尚未完成投影时保留重试状态。 self._auth_plugin_routes_pending = False + self._agent_tasks: AgentTaskRepository | None = None + + def configure_agent_tasks(self, repository: AgentTaskRepository) -> None: + """在调度器启动前绑定唯一自主任务仓储。""" + if self._lifecycle_state not in {"new", "stopped"}: + raise RuntimeError("Scheduler 已运行,不能替换 AgentTask 仓储") + self._agent_tasks = repository + + def _agent_task_repository(self) -> AgentTaskRepository: + """返回显式注入仓储;缺少组合根装配时稳定失败。""" + if self._agent_tasks is None: + raise RuntimeError("Scheduler 的 AgentTask 仓储尚未注入") + return self._agent_tasks async def on_config_changed(self) -> None: """ @@ -1479,7 +1492,7 @@ class Scheduler(ConfigReloadMixin, metaclass=SingletonClass): """ 按数据库当前状态注册所有启用的 Agent 自主定时任务。 """ - for task in get_agent_task_port().list(enabled=True): + for task in self._agent_task_repository().list(enabled=True): self.update_agent_task_job(task.id) def _reconcile_agent_task_interruptions(self) -> None: @@ -1492,7 +1505,7 @@ class Scheduler(ConfigReloadMixin, metaclass=SingletonClass): with self._lock: if self._agent_task_interruptions_reconciled: return - oper = get_agent_task_port() + oper = self._agent_task_repository() for task in oper.list(): if task.last_status == "running": oper.mark_interrupted( @@ -1513,7 +1526,7 @@ class Scheduler(ConfigReloadMixin, metaclass=SingletonClass): """ config = get_scheduler_runtime_config() self.remove_agent_task_job(task_id) - task = get_agent_task_port().get(task_id) + task = self._agent_task_repository().get(task_id) if ( not config.ai_agent_enable or not task @@ -1525,6 +1538,9 @@ class Scheduler(ConfigReloadMixin, metaclass=SingletonClass): trigger_value = ( task.cron_expression if task.trigger_type == "cron" else task.run_at ) + if trigger_value is None: + logger.error(f"Agent 定时任务 {task_id} 缺少触发配置") + return None manual_only = task.trigger_type == "date" and task.last_status == "interrupted" trigger = None if not manual_only: @@ -1626,7 +1642,7 @@ class Scheduler(ConfigReloadMixin, metaclass=SingletonClass): if next_run_time: return next_run_time.isoformat(timespec="seconds") - task = get_agent_task_port().get(task_id) + task = self._agent_task_repository().get(task_id) if not task or not task.enabled: return None if task.trigger_type == "date" and task.last_status == "interrupted": @@ -1634,6 +1650,8 @@ class Scheduler(ConfigReloadMixin, metaclass=SingletonClass): trigger_value = ( task.cron_expression if task.trigger_type == "cron" else task.run_at ) + if trigger_value is None: + return None try: next_run_time = TimerUtils.get_schedule_next_run_time( trigger_type=task.trigger_type, diff --git a/app/startup/composition/context.py b/app/startup/composition/context.py index 2226484b4..38a940f76 100644 --- a/app/startup/composition/context.py +++ b/app/startup/composition/context.py @@ -4,6 +4,7 @@ from collections.abc import AsyncGenerator, Callable, Generator from dataclasses import dataclass, field from typing import Protocol +from app.application.agent import AgentDataContext from app.application.configuration import RuntimeConfiguration, RuntimeSettingsService from app.application.history import ( TransferHistoryMutationRepository, @@ -20,6 +21,7 @@ from app.application.subscription.contract import ( SubscriptionHistoryStagingPort, SubscriptionStagingPort, ) +from app.application.transfer.execution import TransferExecutionRepository from app.application.workflow import WorkflowCachePort, WorkflowQueryService from app.runtime.tasks import TaskRegistry @@ -160,6 +162,7 @@ class HistoryRuntime: transfer_repository: TransferHistoryRepository transfer_mutation_repository: TransferHistoryRepositoryFactory media_server_repository: RepositoryFactory + transfer_execution_repository: TransferExecutionRepository @dataclass(frozen=True, slots=True) @@ -196,6 +199,7 @@ class HostRuntime: """宿主组合根构建且在一个 FastAPI lifespan 内共享的运行时对象。""" agent_chat: AgentChatRuntime + agent: AgentDataContext persistence: PersistenceRuntime authentication: AuthenticationRuntime messaging: MessagingRuntime diff --git a/app/startup/initializers/agent.py b/app/startup/initializers/agent.py index 08c240194..c6a01f28c 100644 --- a/app/startup/initializers/agent.py +++ b/app/startup/initializers/agent.py @@ -14,7 +14,7 @@ from app.agent.runtime_loader import ( from app.agent.runtime_loader import ( get_running_agent_manager as get_runtime_running_agent_manager, ) -from app.application.agent import register_agent_service_providers +from app.application.agent import AgentDataContext, register_agent_service_providers from app.application.messaging.skill import register_skill_catalog_provider from app.runtime.events import Event, eventmanager from app.runtime.log import logger @@ -40,6 +40,35 @@ def _get_llm_provider_runtime() -> Any: # 嵌入式启动器可显式注入 manager;常规进程使用 Capability Runtime。 agent_manager: Any = None +_agent_data_context: AgentDataContext | None = None +_injected_agent_manager: Any = None + + +def configure_agent_data_context(context: AgentDataContext) -> None: + """登记组合根数据上下文,并丢弃未运行的旧 manager 缓存。""" + global _agent_data_context, _injected_agent_manager + if _agent_data_context is context: + return + manager = _injected_agent_manager + if manager is not None and ( + getattr(manager, "_accepting_tasks", False) + or bool(getattr(manager, "active_agents", {})) + ): + raise RuntimeError("AgentManager 已运行,不能替换数据上下文") + _agent_data_context = context + _injected_agent_manager = None + + +def _get_injected_agent_manager() -> Any: + """按需构造并缓存显式注入数据上下文的 AgentManager。""" + global _injected_agent_manager + if _agent_data_context is None: + raise RuntimeError("Agent 数据上下文尚未由启动组合根装配") + if _injected_agent_manager is None: + from app.agent.orchestrator import AgentManager + + _injected_agent_manager = AgentManager(data=_agent_data_context) + return _injected_agent_manager def _event_changed_keys(event: Event | None) -> set[str]: @@ -58,7 +87,11 @@ def _event_changed_keys(event: Event | None) -> set[str]: def _get_agent_manager() -> Any: """兼容显式注入对象,否则按需解析 canonical manager。""" - return agent_manager if agent_manager is not None else get_runtime_agent_manager() + if agent_manager is not None: + return agent_manager + if _agent_data_context is not None: + return _get_injected_agent_manager() + return get_runtime_agent_manager() def _get_running_agent_manager() -> Any | None: @@ -124,13 +157,17 @@ class AgentInitializer: try: self._shutdown_started = False self._shutdown_complete = False - if agent_manager is not None: + if agent_manager is not None or _agent_data_context is not None: if not get_runtime_setting('AI_AGENT_ENABLE'): logger.info("AI智能体功能未启用") return True - self._manager = agent_manager + self._manager = ( + agent_manager + if agent_manager is not None + else _get_injected_agent_manager() + ) self._compat_injected = True - await agent_manager.initialize() + await self._manager.initialize() else: self._manager = await activate_agent_service() self._compat_injected = False diff --git a/app/startup/initializers/modules.py b/app/startup/initializers/modules.py index 18dd7c65e..a92417f4a 100644 --- a/app/startup/initializers/modules.py +++ b/app/startup/initializers/modules.py @@ -34,7 +34,7 @@ from app.adapters.system.resource import ( ) from app.adapters.web.security.access import set_superuser_token_payload_provider from app.api.data import ApiDataPorts, configure_api_data_runtime -from app.application.agentdata import configure_agent_data_ports +from app.application.agent import AgentDataContext from app.application.agenttask import ( AgentTaskExecutionService, configure_agent_task_execution, @@ -43,7 +43,6 @@ from app.application.chain.context import ( ChainRuntimeContext, configure_chain_runtime_context_provider, ) -from app.application.chain.data import configure_chain_data_ports from app.application.chain.events import ( restore_download_added, restore_transfer_result, @@ -119,6 +118,11 @@ from app.application.workflow import ( configure_workflow_query, ) from app.command import CommandChain +from app.db.adapters.agent import ( + SessionAgentTaskRepository, + TransactionalAgentTaskRepository, + TransactionalPluginDataRepository, +) from app.db.adapters.chain import TransactionalChainDurableEventWriter from app.db.adapters.configuration import TransactionalUserConfigurationRepository from app.db.adapters.download import TransactionalDownloadFailureRepository @@ -158,11 +162,9 @@ from app.db.adapters.workflow import ( TransactionalWorkflowQueryRepository, ) from app.db.oper.agentchat import AgentChatOper -from app.db.oper.agenttask import AgentTaskOper from app.db.oper.mediaserver import MediaServerOper from app.db.oper.message import MessageOper from app.db.oper.passkey import PassKeyOper -from app.db.oper.plugindata import PluginDataOper from app.db.oper.systemconfig import SystemConfigOper from app.db.oper.workflow import WorkflowOper from app.db.session import ( @@ -223,11 +225,12 @@ from app.startup.composition.database import build_database_governance from app.startup.composition.subscription import ( configure_transactional_subscription_scopes, ) -from app.startup.initializers.agent import init_agent +from app.startup.initializers.agent import configure_agent_data_context, init_agent from app.startup.initializers.resources import ( init_managed_resources, stop_managed_resources, ) +from app.startup.initializers.scheduler import configure_scheduler_agent_tasks _database_worker: DatabaseWorker | None = None @@ -284,7 +287,13 @@ def _execute_legacy_transfer_command(**kwargs: Any) -> Any: return TransferChain().execute_legacy_transfer_command(**kwargs) -def _build_chain_runtime_context() -> ChainRuntimeContext: +def _build_chain_runtime_context( + *, + site: TransactionalSiteRepository, + subscription: TransactionalSubscriptionRepository, + download_history: TransactionalDownloadHistoryRepository, + transfer_history: TransactionalTransferHistoryRepository, +) -> ChainRuntimeContext: """在启动组合根创建 Chain 所需的运行时对象和数据端口。""" return ChainRuntimeContext( module_manager=ModuleManager(), @@ -296,6 +305,15 @@ def _build_chain_runtime_context() -> ChainRuntimeContext: async_file_cache=AsyncFileCache(), message_queue_factory=lambda callback: MessageQueueManager(send_callback=callback), module_dispatcher_factory=ModuleInvocationDispatcher, + site_repository=site, + subscription_repository=subscription, + download_history_repository=download_history, + transfer_history_repository=transfer_history, + transfer_admission_repository=TransactionalTransferAdmissionRepository(SessionFactory), + transfer_execution_repository=TransactionalTransferExecutionRepository(SessionFactory), + media_server_repository=TransactionalMediaServerRepository(SessionFactory), + download_failure_repository=TransactionalDownloadFailureRepository(SessionFactory), + user_repository=_build_transactional_user_repository(), legacy_transfer_command=_execute_legacy_transfer_command, configuration=build_chain_runtime_config(legacy_settings), durable_event_writer=TransactionalChainDurableEventWriter(SessionFactory), @@ -861,6 +879,25 @@ async def init_modules() -> HostRuntime: subscription_history_repository = TransactionalSubscriptionHistoryRepository( async_session=async_session_scope, ) + agent_chat_service = AgentChatService(repository=AgentChatOper()) + agent_task_repository = TransactionalAgentTaskRepository(SessionFactory) + plugin_data_repository = TransactionalPluginDataRepository(async_session_scope) + transfer_execution_repository = TransactionalTransferExecutionRepository( + SessionFactory + ) + agent_data = AgentDataContext( + chat=agent_chat_service, + chat_persistence=agent_chat_persistence, + tasks=agent_task_repository, + users=_build_transactional_user_repository(), + sites=site_repository, + subscriptions=subscription_repository, + subscription_history=subscription_history_repository, + transfer_history=transfer_history_repository, + transfer_execution=transfer_execution_repository, + download_history=download_history_repository, + plugin_data=plugin_data_repository, + ) host_runtime = HostRuntime( agent_chat=AgentChatRuntime( async_session=get_async_db, @@ -868,6 +905,7 @@ async def init_modules() -> HostRuntime: transaction=SqlAlchemyAsyncUnitOfWork, persistence=agent_chat_persistence, ), + agent=agent_data, persistence=PersistenceRuntime( sync_session=get_db, async_session=get_async_db, @@ -886,6 +924,7 @@ async def init_modules() -> HostRuntime: transfer_repository=transfer_history_repository, transfer_mutation_repository=SessionTransferHistoryRepository, media_server_repository=MediaServerOper, + transfer_execution_repository=transfer_execution_repository, ), site=SiteRuntime( repository=SessionSiteRepository, @@ -918,17 +957,6 @@ async def init_modules() -> HostRuntime: configure_runtime_data_providers(workflow_query, subscription_repository) workflow_execution = TransactionalWorkflowExecutionService(SessionFactory) configure_workflow_execution(workflow_execution) - configure_chain_data_ports( - site=lambda: site_repository, - subscribe=lambda: subscription_repository, - download_history=lambda: download_history_repository, - transfer_history=lambda: transfer_history_repository, - transfer_pending=lambda: TransactionalTransferAdmissionRepository(SessionFactory), - transfer_execution=lambda: TransactionalTransferExecutionRepository(SessionFactory), - media_server=lambda: TransactionalMediaServerRepository(SessionFactory), - download_failure=lambda: TransactionalDownloadFailureRepository(SessionFactory), - user=_build_transactional_user_repository, - ) configure_outbox_dispatcher(_build_outbox_dispatcher) configure_transfer_retry_config( lambda: TransferRetryConfig( @@ -936,7 +964,7 @@ async def init_modules() -> HostRuntime: ) ) configure_database_governance(build_database_governance()) - configure_agent_chat_service(AgentChatService(repository=AgentChatOper())) + configure_agent_chat_service(agent_chat_service) configure_agent_chat_persistence(agent_chat_persistence) configure_user_lookups( by_id=lambda user_id: _build_transactional_user_repository().get_by_id(user_id), @@ -961,20 +989,14 @@ async def init_modules() -> HostRuntime: configure_transfer_history_repository(lambda: transfer_history_repository) configure_site_query_service(SiteQueryService(repository=site_repository)) configure_site_health_service(SiteHealthService(repository=site_repository)) - configure_agent_data_ports( - agent_chat=lambda: AgentChatOper(), - agent_task=lambda: AgentTaskOper(), - user=_build_transactional_user_repository, - site=lambda: site_repository, - subscribe=lambda: subscription_repository, - subscribe_history=lambda: subscription_history_repository, - transfer_history=lambda: transfer_history_repository, - download_history=lambda: download_history_repository, - plugin_data=lambda: PluginDataOper(), - ) + configure_agent_data_context(agent_data) + from app.agent.tools.manager import moviepilot_tool_manager + + moviepilot_tool_manager.set_data_context(agent_data) + configure_scheduler_agent_tasks(agent_task_repository) configure_agent_task_execution( AgentTaskExecutionService( - repository=lambda session: AgentTaskOper(session), + repository=SessionAgentTaskRepository, async_executor=database_worker, sync_transaction=transaction_runner.sync, ) @@ -986,7 +1008,14 @@ async def init_modules() -> HostRuntime: # 应用服务不反向依赖 Chain,由启动组合层注入壁纸来源。 configure_wallpaper_services() # Chain 无参兼容入口由组合根明确提供依赖上下文;测试和新代码可直接注入替代上下文。 - configure_chain_runtime_context_provider(_build_chain_runtime_context) + configure_chain_runtime_context_provider( + lambda: _build_chain_runtime_context( + site=site_repository, + subscription=subscription_repository, + download_history=download_history_repository, + transfer_history=transfer_history_repository, + ) + ) # 认证访问层不反向依赖数据库实现,由启动组合层注入载荷提供器。 set_superuser_token_payload_provider(build_superuser_token_payload) # DoH diff --git a/app/startup/initializers/scheduler.py b/app/startup/initializers/scheduler.py index 6430dd6a9..3badd7f03 100644 --- a/app/startup/initializers/scheduler.py +++ b/app/startup/initializers/scheduler.py @@ -1,12 +1,18 @@ import asyncio -from app.application.scheduling import register_scheduler_class +from app.application.agenttask import AgentTaskRepository +from app.application.scheduling import get_scheduler, register_scheduler_class from app.scheduler import Scheduler # 导入期即向 application 门面注册调度器类,保证工具调用时不依赖静态边。 register_scheduler_class(Scheduler) +def configure_scheduler_agent_tasks(repository: AgentTaskRepository) -> None: + """在调度器启动前注入自主任务仓储。""" + get_scheduler().configure_agent_tasks(repository) + + def init_scheduler(): """ 初始化定时器 diff --git a/app/workflow/actions/add_subscribe.py b/app/workflow/actions/add_subscribe.py index 51e4d589c..5bc7d3cad 100644 --- a/app/workflow/actions/add_subscribe.py +++ b/app/workflow/actions/add_subscribe.py @@ -1,4 +1,3 @@ -from app.application.chain.data import get_chain_subscribe_port from app.application.configuration import get_chain_runtime_config_snapshot from app.chain.subscribe import SubscribeChain from app.domain.context import MediaInfo @@ -75,7 +74,7 @@ class AddSubscribeAction(BaseAction): if self._added_subscribes: logger.info(f"已添加 {len(self._added_subscribes)} 个订阅") for sid in self._added_subscribes: - subscribe = get_chain_subscribe_port().get(sid) + subscribe = subscribechain.subscription_repository.get(sid) if subscribe: if context.subscribes is None: context.subscribes = [] diff --git a/app/workflow/actions/transfer_file.py b/app/workflow/actions/transfer_file.py index 00b7ec2e5..e07ee6995 100644 --- a/app/workflow/actions/transfer_file.py +++ b/app/workflow/actions/transfer_file.py @@ -4,7 +4,6 @@ from typing import Optional from pydantic import Field -from app.application.chain.data import get_chain_transfer_history_port from app.chain.storage import StorageChain from app.chain.transfer import TransferChain from app.runtime.log import logger @@ -66,7 +65,7 @@ class TransferFileAction(BaseAction): _failed_count = 0 storagechain = StorageChain() transferchain = TransferChain() - transferhis = get_chain_transfer_history_port() + transferhis = transferchain.transfer_history_repository if params.source == "downloads": # 从下载任务中整理文件 for download in context.downloads: diff --git a/docs/architecture-optimization-checklist.md b/docs/architecture-optimization-checklist.md index 4b013c1ee..f6721a2dc 100644 --- a/docs/architecture-optimization-checklist.md +++ b/docs/architecture-optimization-checklist.md @@ -69,7 +69,7 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain` | 指标 | 当前值 | 解释 | |---|---:|---| -| 宿主 Python 模块 / 内部依赖边 | 859 / 7,089 | `dependency-baseline.json` 当前快照 | +| 宿主 Python 模块 / 内部依赖边 | 858 / 7,062 | `dependency-baseline.json` 当前快照 | | 非平凡 SCC | 2 | 新增 Chain 包根环;另一个是隔离的 29 模块 TMDB 移植包环 | | 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 | | Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 | @@ -78,8 +78,8 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain` | Python 源码量 | 约 271,400 行 | 60 个文件超过 1,000 行,14 个超过 2,000 行 | | 长方法 | 281 个超过 80 行 | 67 个超过 150 行,23 个超过 250 行;大量是私有方法 | | 全量 mypy 历史债务 | 11,734 / 596 文件 | strict frontier 当前覆盖 41 个文件,本批迁移路径的类型债务已清零 | -| Ruff 历史诊断 | 815 | 低水位门禁通过,但规则集只覆盖 `E4/E7/E9/F/I` | -| 覆盖率低水位 | Application 79.82%,Domain 79.29% | Chain、Runtime、Agent、Adapter、Startup 未进入包级覆盖率门禁 | +| Ruff 历史诊断 | 760 | 低水位门禁通过,但规则集只覆盖 `E4/E7/E9/F/I` | +| 覆盖率低水位 | Application 79.83%,Domain 79.29% | Chain、Runtime、Agent、Adapter、Startup 未进入包级覆盖率门禁 | ### 3.3 热点文件 @@ -310,14 +310,16 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain` ORM 投影,Chain/API/Agent/Workflow/interaction 全部消费 typed contract。 - [x] `app.db.subscribe_oper`、`app.db.subscribehistory_oper` 和 `app.db.oper` 包根旧符号统一经 `app/sdk/_legacy/subscribe.py` 与精确 Compat 映射保留;canonical 包根不增加重复 `__all__` 导出。 -- [ ] `ChainDataPorts`/`AgentDataPorts` 可暂时保留为兼容聚合器,但字段必须显式、可类型检查。 -- [ ] 以一个业务纵切面迁移并验证后,再迁移下一组,禁止一次替换所有 Oper。 +- [x] 删除 `ChainDataPorts`/`AgentDataPorts` 及其全局 getter;Chain 使用实例级 + `ChainRuntimeContext`,Agent manager/memory/tool/scheduler 使用同一 `AgentDataContext`,字段均显式可类型检查。 +- [x] User、History、Site、Subscription、Agent/Transfer locator 按纵切面逐批迁移并各自验证, + 未通过通用代理一次替换所有 Oper。 - [x] Subscription 增加 AST 门禁,禁止 canonical consumer 导入 raw Oper/ORM、以 `Any` 伪装 - Snapshot、复制 CRUD Protocol 或新增多词散落文件;全局 Agent/Transfer locator 清零由 S1-L3.8 继续。 + Snapshot、复制 CRUD Protocol 或新增多词散落文件;全局 Agent/Transfer locator 已清零并由独立 AST 门禁守护。 **后续顺序** -1. S1-L3.8 清除 Agent/Transfer locator 泄漏,并把全局 raw getter/Oper/`Any` 门禁补齐。 +1. S1-L4 收口 Subscription 新增、修改、删除、完成和批量修改的单一 UoW,删除自动提交写入口。 2. S1-L4 对 Subscription 新增、修改、删除、完成和批量修改逐用例验证单一 UoW,禁止把逐条短事务 误当作批量原子事务。 3. S1-L5 将站点、规则组引用的 SystemConfig 与 Subscription 更新合并为原子命令,并在 commit 后 diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index ec63f7a97..1f4f47bc2 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -156,10 +156,11 @@ flowchart TB -> db/oper 与 db/models ``` -`app/application/chain/data.py`、`app/application/agentdata.py` 和 -`app/application/history.py` 的 `get_*_port()` 是宿主生产代码读取组合根能力的现有接缝;其中 -Subscription、Site、History 等已完成迁移,尚未迁移的 Chain/Agent `Any` factory、裸 Oper 和 -locator 仍需进入类型化 Port/DTO,不能把当前 getter 聚合器当作最终合同。 +Chain 的持久化能力由 startup 构造 `ChainRuntimeContext` 并在 `ChainBase` 实例化时显式注入; +Agent manager、memory、tool 和 scheduler 共享同一个 `AgentDataContext`。原 +`app/application/chain/data.py`、`app/application/agentdata.py` 的进程级 getter 已删除,且不进入 +SDK/Compat。领域查询与写入继续使用 Application 所属的冻结 DTO/Port,具体实现只存在于 +`db/adapters`,宿主生产代码不得恢复 raw Oper、`Any` factory 或数据服务 locator。 需要跨进程恢复或 commit 后可靠执行的 业务副作用进入 `app/application/outbox.py` 定义的 Outbox 端口,由 `app/db/adapters/outbox.py` 实现;`app/runtime/tasks.py` 的 TaskRegistry 只负责进程内任务所有权、 @@ -711,7 +712,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 859 | -| 内部导入边 | 7,089 | +| 内部导入边 | 7,062 | | 非平凡 SCC | 2(`ARCH-107` 临时 Chain 包根环;精确 containment 的 TMDB 移植包环) | | Direct egress | 66(12 条待迁移债务,54 条精确 containment) | | Module Contract V2 spec | 217(其中 215 个进入 `run_module` 观察面) | diff --git a/docs/architecture-refactor-roadmap.md b/docs/architecture-refactor-roadmap.md index b17ebb764..73d4efaeb 100644 --- a/docs/architecture-refactor-roadmap.md +++ b/docs/architecture-refactor-roadmap.md @@ -98,16 +98,16 @@ canonical 主程序;兼容只经统一 Compat/SDK 门面提供。 | S1-L1.4 幂等执行与终态结算 | `VERIFIED` | S1-L1.3 | 文件操作、历史提交和 checkpoint 可重放;唯一 retry owner 生效,未知外部结果进入 `manual_review`,仅完整终态删除 pending | | S1-L1.5 E3 全链收口 | `DELIVERED` | S1-L1.4 | `e9de149db`、`a2e249f20`:崩溃矩阵、3.0.17 升降级、重复回放和插件 ABI 验收完整;旧 fail-open、重复状态与兼容层外旧入口删除;Unit Tests `33092427327`、Pylint `33092427348` 全绿,ARCH-102 债务归零 | | S1-L2 Workflow typed query | `DELIVERED` | S0 | `b4f873654`、`a01a35bcb`:Workflow Application Port 不返回 `Any`/ORM,Session 内投影冻结 DTO,正式调用方全部切换;Unit Tests `33098869736`、Pylint `33098869837` 全绿,覆盖率低水位提升至 Application `78.78%` | -| S1-L3 Chain/Agent typed data ports | `ACTIVE` | S1-L2 | `ChainDataPorts`/`AgentDataPorts` 的 raw Oper/`Any` factory 全部清零,兼容调用进入 Legacy 层 | +| S1-L3 Chain/Agent typed data ports | `VERIFIED` | S1-L2 | User、History、Site、Subscription 的冻结 DTO/typed Port 已完成;`ChainDataPorts`/`AgentDataPorts` 与 raw Oper/`Any` factory 清零,旧公开 ABI 仅由 Legacy/Compat 承接 | | S1-L3.1 Workflow typed execution | `DELIVERED` | S1-L2 | `17d8be2af`、`b33b29876`:Chain 直连类型化事务服务且单次执行只取一个 port;canonical Oper 删除旧 writer/无 Session 写方法,旧 ABI 只在 `_legacy/workflow.py` 与 Compat overlay;Unit Tests `33103913838`、Pylint `33103913935` 全绿,Application 覆盖率低水位提升至 `78.79%` | -| S1-L3.2 Chain registry/DI | `ACTIVE` | S1-L3.1 | 显式类型化 factory,删除 PortProxy 与失效的双重注入,构造器注入真实控制调用 | +| S1-L3.2 Chain registry/DI | `VERIFIED` | S1-L3.1 | 显式类型化 context,删除 PortProxy、全局数据 getter 与失效的双重注入,构造器注入真实控制调用 | | S1-L3.2.1 Registry hygiene | `DELIVERED` | S1-L3.1 | `ac7a20132`:删除零消费者 PortProxy/动态转发和 `ChainRuntimeContext.data_ports` 伪注入;Workflow 退出 Chain registry,只保留 Application owner 单一配置入口;Unit Tests `33120205586`、Pylint `33120205581` 全绿 | | S1-L3.3 DownloadFailure/MediaServer | `DELIVERED` | S1-L3.2 | `5fb62108a`:两组 raw factory 已替换为冻结 DTO/typed Port;失败冷却在 Session 内投影,媒体库查询只返回标量且每个 upsert/cleanup 独立短事务,远端枚举不持有 Session;旧 Oper 与插件可见 Chain ABI 保持不变;Unit Tests `33127544925`、Pylint `33127544927` 全绿,Application 覆盖率低水位提升至 `78.95%` | | S1-L3.4 User | `VERIFIED` | S1-L3.3 | User Chain/Agent/认证改用冻结 typed snapshot;创建、更名、删除与最后一个启用超级管理员保护归并到单 UoW;用户名唯一索引及 UserConfig/PassKey 级联迁移落地,UserConfig 在 commit 后持写锁重载数据库事实源并发布内存快照 | | S1-L3.5 History | `VERIFIED` | S1-L3.4 | DownloadHistory 与 TransferHistory 均已迁入深度冻结 DTO、typed query/write/staging Port 与短 Session adapter;请求级删除和 durable 结算各自保持单一 UoW,canonical 调用方不再接收 raw Oper/ORM,旧写入 ABI 只由 SDK Legacy/Compat 提供 | | S1-L3.6 Site | `VERIFIED` | S1-L3.5 | Site 配置、用户数据、图标和统计统一为深度冻结 DTO 与 typed query/write/staging Port;请求写入复用 AsyncSession,Chain/Agent 使用独立短事务,canonical 不再接收 raw Oper/ORM,旧插件 ABI 只经 SDK Legacy/Compat | | S1-L3.7 Subscription | `VERIFIED` | S1-L3.6 | `application/subscription/contract.py` 统一深度冻结 Snapshot/History/Identity/Patch 与 typed query/write/staging Repository;DB adapter 在 Session 内完成 ORM 投影,Chain/API/Agent/Workflow/interaction 不再消费 raw Oper/ORM/`Any`;旧 `SubscribeOper`/`SubscribeHistoryOper` 只经同一 SDK Legacy/Compat 门面保留插件 ABI | -| S1-L3.8 Agent/Transfer locator gate | `PLANNED` | S1-L3.7 | 删除 AgentDataPorts 与 Chain locator 跨层泄漏,AST 门禁确认 canonical 无 raw getter/Oper/Any | +| S1-L3.8 Agent/Transfer locator gate | `VERIFIED` | S1-L3.7 | `chain/data.py`、`agentdata.py` 及其 getter 已删除;Chain/Agent 改用显式 typed context,AST 门禁确认 canonical 无 raw getter/Oper/Any;全量有效 `6955 passed, 9 skipped`,Application 覆盖率提升至 `79.83%`,依赖边降至 `7,062` | | S1-L4 Subscription mutation UoW | `PLANNED` | S1-L3.8 | 在已完成 typed DTO/Port 的基础上,逐项证明新增、修改、删除、完成及批量修改由用例拥有单一 UoW;禁止把短事务 Repository 当作跨记录原子事务,旧自动事务入口退出 canonical 路径 | | S1-L5 站点/规则引用原子清理 | `PLANNED` | S1-L4 | SystemConfig+Subscribe 同事务更新,commit 后快照原子发布,并发/故障注入无部分状态 | | S1-L6 Outbox 完成语义 | `VERIFIED` | S0 | 事务内 `OutboxStager` 与独立短事务 `OutboxDispatchStore` 已分离;即时投递与 dispatcher 均先 claim,complete/retry 受 attempt fencing;`PostCommitResult` 区分已提交业务、已完成与 pending effect。事件载荷和宿主 correlation context 携带稳定 event key;旧通知插件保持原签名并承认 at-least-once 重复边界 | @@ -153,7 +153,7 @@ canonical 主程序;兼容只经统一 Compat/SDK 门面提供。 | S4-L2 Event strict contract | `PLANNED` | S0-L2.6,S1-L6 | 宿主事件输入/输出按风险 strict,诊断例外只属于第三方插件兼容 | | S4-L3 Complexity v2 | `PLANNED` | S3 | 私有方法、class/file、圈复杂度进入门禁;所有超限通过职责拆分归零 | | S4-L4 全量 mypy 清零 | `PLANNED` | S3,S4-L1,S4-L2 | `mypy-baseline.json` 归零并删除债务接受路径,全宿主 strict 类型通过 | -| S4-L5 Ruff 治理债务清零 | `PLANNED` | S3 | 当前受控 815 条诊断归零,规则集扩展经过独立审查且新增诊断为零 | +| S4-L5 Ruff 治理债务清零 | `PLANNED` | S3 | 当前受控 760 条诊断归零,规则集扩展经过独立审查且新增诊断为零 | | S4-L6 Coverage/并发/质量证据 | `PLANNED` | S3,S4-L1,S4-L2 | 高风险包纳入 coverage;raw concurrency 分类清零;Module Quality 有真实 evidence test | ### S5:Plugin、Agent、Domain、Startup 与最终收口 diff --git a/docs/rules/05-architecture.md b/docs/rules/05-architecture.md index 0cccfd72d..0cecdfaca 100644 --- a/docs/rules/05-architecture.md +++ b/docs/rules/05-architecture.md @@ -66,8 +66,8 @@ to make the directory tree look symmetrical. | `app/application/download/` | Download task querying/control and selection use cases; `failures.py` owns the frozen failure-cooldown write/query DTOs and persistence Port | | `app/application/history.py` | History use cases and persistence contracts; DownloadHistory and TransferHistory own deeply frozen DTOs plus typed query/write/staging ports | | `app/application/music/` | Multi-source music catalog orchestration | -| `app/application/chain/` | Injectable Chain runtime capabilities: `context.py` owns the runtime dependency aggregate, `data.py` owns named persistence ports, and `events.py` owns durable event write contracts plus replayable payload conversion | -| `app/application/agentdata.py` | Named Agent data ports; canonical Agent consumers use `get_agent_*_port()` and do not alias legacy proxies to Oper classes | +| `app/application/chain/` | Injectable Chain runtime capabilities: `context.py` owns the typed runtime and persistence dependency aggregate, and `events.py` owns durable event write contracts plus replayable payload conversion | +| `app/application/agent.py` | Agent orchestration facade and typed `AgentDataContext`; startup injects one explicit data context into the manager, memory, tool and scheduler owners without a process-wide persistence locator | | `app/application/outbox.py` | Durable intent, transaction-only stager, short-transaction dispatch store, claim fencing and structured post-commit result contracts | | `app/application/transfer/` | Durable transfer use cases: `workflow.py` owns admission/planning/queue behavior; `execution.py` owns stable operation identity, step/checkpoint state, retry/manual-review commands and terminal-settlement DTOs | | `app/application/plugin/` | Plugin market catalog, installation command, installed-plugin identity contract and startup migration, runtime port, folder operations and dynamic-route use cases; filenames remain single words (`catalog.py`, `identity.py`, `migration.py`, `install.py`, `runtime.py`, `folders.py`, `routes.py`) | @@ -138,19 +138,20 @@ Session. `app/db/adapters/` is the concrete persistence-adapter layer: it may depend on Application-owned Protocols, UoW/Session and Oper implementations. This deliberate dependency inversion is the only `DB implementation -> Application contract` direction; Application must remain free of DB imports. -Migrated user, interaction, messaging, music, site, media-server, download, subscribe and transfer -Chain consumers temporarily use the named `get_chain_*_port()` functions from -`app/application/chain/data.py` while each owner establishes typed DTO/Port contracts. -The retired migration-time `*PortProxy` classes and dynamic `__getattr__` forwarding must not -be recreated; they had no host, SDK or plugin consumers. Workflow execution uses its owning -`app.application.workflow` service directly and must not be registered again in `ChainDataPorts`. +User, interaction, messaging, music, site, media-server, download, subscribe and transfer +Chain consumers receive typed repositories through `ChainRuntimeContext`; `ChainBase` copies the +context fields to instance-owned capabilities during construction. The deleted process-wide +`chain/data.py` locator, migration-time `*PortProxy` classes and dynamic `__getattr__` forwarding +must not be recreated; they had no host, SDK or plugin consumers. Workflow execution uses its +owning `app.application.workflow` service directly and is not duplicated in the Chain context. Download-failure cooldown and media-server cache consumers use their typed Application DTO/Port contracts. Their DB adapters project ORM values before Session close and commit each local write in a separate short UoW, so remote media enumeration never holds a database transaction. -Agent orchestration, memory and tool implementations follow the same rule via -the named `get_agent_*_port()` functions from `app/application/agentdata.py`. -The legacy Agent `*Port` proxy classes remain import-compatible boundaries and -must not be reintroduced as Oper aliases in canonical Agent modules. +Agent orchestration, memory, tools and scheduler receive the single typed `AgentDataContext` +declared in `app/application/agent.py`. The deleted `agentdata.py` locator and its getter surface +were host-internal migration scaffolding, never plugin ABI, and must not gain SDK/Compat aliases. +Legacy public Agent imports remain exact SDK/Compat boundaries and must not be reintroduced as +Oper aliases in canonical Agent modules. Monitor history checks use `get_transfer_history_repository()` from `app/application/history.py`; old constructible Oper-style facades are available only through the exact SDK Legacy/Compat mapping. @@ -732,7 +733,8 @@ driven workflow registration. | Path | Purpose | |---|---| -| `app/application/agent.py` | Agent orchestration facade (`get_agent_manager` / `get_prompt_manager` / capability queries / prompt builders); lightweight providers register through `app/startup/initializers/agent.py`, with no static `application -> agent` edge | +| `app/application/agent.py` | Agent orchestration facade plus typed `AgentDataContext`; lightweight service providers register through `app/startup/initializers/agent.py`, with no static `application -> agent` edge or global persistence locator | +| `app/db/adapters/agent.py` | Agent task and plugin-data persistence implementations; ORM values are projected to Application snapshots before Session close | | `app/agent/runtime_loader.py` | Agent-specific capability discovery and canonical entrypoint/service materialization; reuses the generic Capability Runtime while keeping Agent ownership under `app/agent/` | | `app/application/subscription/contract.py` | Deeply frozen Subscription/History DTOs, media identity, write patch and typed query/write/staging Repository contracts | | `app/application/subscription/write.py` | Subscription media translation and sync/async write-command orchestration | diff --git a/tests/conftest.py b/tests/conftest.py index b8767e1f7..99022324b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -185,7 +185,6 @@ def configure_plugin_system_services(): ChainRuntimeContext, configure_chain_runtime_context_provider, ) - from app.application.chain.data import configure_chain_data_ports from app.application.messaging.chat import ( AgentChatPersistenceService, AgentChatService, @@ -220,12 +219,19 @@ def configure_plugin_system_services(): from app.workflow import WorkflowManager configure_workflow_runtime(lambda: WorkflowManager()) - from app.application.agentdata import configure_agent_data_ports + from app.application.agent import AgentDataContext from app.application.agenttask import ( AgentTaskExecutionService, configure_agent_task_execution, ) + from app.db.adapters.agent import ( + SessionAgentTaskRepository, + TransactionalAgentTaskRepository, + TransactionalPluginDataRepository, + ) from app.db.adapters.download import TransactionalDownloadFailureRepository + from app.db.adapters.history.download import TransactionalDownloadHistoryRepository + from app.db.adapters.history.transfer import TransactionalTransferHistoryRepository from app.db.adapters.mediaserver import TransactionalMediaServerRepository from app.db.adapters.site import TransactionalSiteRepository from app.db.adapters.subscription import TransactionalSubscriptionRepository @@ -318,16 +324,17 @@ def configure_plugin_system_services(): async_session=async_session_scope, ) - configure_chain_data_ports( - site=site_repository, - subscribe=lambda: SubscribeOper(), - download_history=lambda: DownloadHistoryOper(), - transfer_history=lambda: TransferHistoryOper(), - transfer_pending=lambda: TransactionalTransferAdmissionRepository(SessionFactory), - transfer_execution=lambda: TransactionalTransferExecutionRepository(SessionFactory), - media_server=lambda: TransactionalMediaServerRepository(SessionFactory), - download_failure=lambda: TransactionalDownloadFailureRepository(SessionFactory), - user=user_repository, + subscription_repository = TransactionalSubscriptionRepository( + sync_session=SessionFactory, + async_session=async_session_scope, + ) + download_history_repository = TransactionalDownloadHistoryRepository( + sync_session=SessionFactory, + async_session=async_session_scope, + ) + transfer_history_repository = TransactionalTransferHistoryRepository( + sync_session=SessionFactory, + async_session=async_session_scope, ) configure_chain_runtime_context_provider( lambda: ChainRuntimeContext( @@ -340,6 +347,15 @@ def configure_plugin_system_services(): async_file_cache=AsyncFileCache(), message_queue_factory=lambda callback: MessageQueueManager(send_callback=callback), module_dispatcher_factory=ModuleInvocationDispatcher, + site_repository=site_repository(), + subscription_repository=subscription_repository, + download_history_repository=download_history_repository, + transfer_history_repository=transfer_history_repository, + transfer_admission_repository=TransactionalTransferAdmissionRepository(SessionFactory), + transfer_execution_repository=TransactionalTransferExecutionRepository(SessionFactory), + media_server_repository=TransactionalMediaServerRepository(SessionFactory), + download_failure_repository=TransactionalDownloadFailureRepository(SessionFactory), + user_repository=user_repository(), configuration=build_chain_runtime_config(settings), ) ) @@ -353,35 +369,46 @@ def configure_plugin_system_services(): ) ) ) - from app.db.oper.agenttask import AgentTaskOper - from app.db.oper.plugindata import PluginDataOper + from app.db.adapters.subscription import ( + TransactionalSubscriptionHistoryRepository, + ) - configure_agent_data_ports( - agent_chat=lambda: AgentChatOper(), - agent_task=lambda: AgentTaskOper(), - user=user_repository, - site=site_repository, - subscribe=lambda: SubscribeOper(), - subscribe_history=lambda: SubscribeHistoryOper(), - transfer_history=lambda: TransferHistoryOper(), - download_history=lambda: DownloadHistoryOper(), - plugin_data=lambda: PluginDataOper(), + agent_chat_persistence = AgentChatPersistenceService( + repository=lambda session: AgentChatOper(session), + async_executor=database_executor, + sync_transaction=transaction_runner.sync, + ) + agent_chat_service = AgentChatService(repository=AgentChatOper()) + agent_task_repository = TransactionalAgentTaskRepository(SessionFactory) + agent_data_context = AgentDataContext( + chat=agent_chat_service, + chat_persistence=agent_chat_persistence, + tasks=agent_task_repository, + users=user_repository(), + sites=site_repository(), + subscriptions=subscription_repository, + subscription_history=TransactionalSubscriptionHistoryRepository( + async_session=async_session_scope, + ), + transfer_history=transfer_history_repository, + transfer_execution=TransactionalTransferExecutionRepository(SessionFactory), + download_history=download_history_repository, + plugin_data=TransactionalPluginDataRepository(async_session_scope), ) configure_agent_task_execution( AgentTaskExecutionService( - repository=lambda session: AgentTaskOper(session), + repository=SessionAgentTaskRepository, async_executor=database_executor, sync_transaction=transaction_runner.sync, ) ) - configure_agent_chat_persistence( - AgentChatPersistenceService( - repository=lambda session: AgentChatOper(session), - async_executor=database_executor, - sync_transaction=transaction_runner.sync, - ) - ) - configure_agent_chat_service(AgentChatService(repository=AgentChatOper())) + configure_agent_chat_persistence(agent_chat_persistence) + configure_agent_chat_service(agent_chat_service) + from app.agent.tools.manager import moviepilot_tool_manager + from app.scheduler import Scheduler + + moviepilot_tool_manager.set_data_context(agent_data_context) + Scheduler().configure_agent_tasks(agent_task_repository) from app.adapters.external.market import ( VERSION_BACKWARD_COMPATIBLE_FLAGS, PluginHelper, diff --git a/tests/fixtures/architecture/coverage-baseline.json b/tests/fixtures/architecture/coverage-baseline.json index 8c483be41..0ccd959f3 100644 --- a/tests/fixtures/architecture/coverage-baseline.json +++ b/tests/fixtures/architecture/coverage-baseline.json @@ -1,8 +1,8 @@ { "application": { - "covered_lines": 10943, - "percent": 79.82, - "statements": 13709 + "covered_lines": 10901, + "percent": 79.83, + "statements": 13656 }, "domain": { "covered_lines": 3392, diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 6671436c5..b36b0a9bb 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -1435,8 +1435,8 @@ "runtime_only": true } }, - "edge_count": 7089, - "edge_sha256": "7c5afef719934858c75a335dd2312a329c292d89409e575c4f8593ea784ffdea", + "edge_count": 7062, + "edge_sha256": "5aca9b3ce61d2ed53f133fb119eaaadb83e6a1ea6a07c1fb31aeac253cb2f000", "edges": [ "app -> app.runtime", "app -> app.runtime.compat", @@ -1690,7 +1690,6 @@ "app.agent.mcp -> app.schemas.agent", "app.agent.mcp -> app.schemas.types", "app.agent.memory -> app.application", - "app.agent.memory -> app.application.agentdata", "app.agent.memory -> app.application.messaging", "app.agent.memory -> app.application.messaging.chat", "app.agent.memory -> app.runtime", @@ -1803,7 +1802,7 @@ "app.agent.orchestrator -> app.agent.tools.impl.mcp", "app.agent.orchestrator -> app.agent.tools.impl.query_system_settings", "app.agent.orchestrator -> app.application", - "app.agent.orchestrator -> app.application.agentdata", + "app.agent.orchestrator -> app.application.agent", "app.agent.orchestrator -> app.application.agenttask", "app.agent.orchestrator -> app.application.messaging", "app.agent.orchestrator -> app.application.messaging.chat", @@ -1884,6 +1883,7 @@ "app.agent.tools.base -> app.agent.tools", "app.agent.tools.base -> app.agent.tools.tags", "app.agent.tools.base -> app.application", + "app.agent.tools.base -> app.application.agent", "app.agent.tools.base -> app.application.messaging", "app.agent.tools.base -> app.application.messaging.agent", "app.agent.tools.base -> app.application.notification", @@ -1990,6 +1990,7 @@ "app.agent.tools.factory -> app.agent.tools.impl.update_system_settings", "app.agent.tools.factory -> app.agent.tools.impl.write_file", "app.agent.tools.factory -> app.application", + "app.agent.tools.factory -> app.application.agent", "app.agent.tools.factory -> app.application.plugin", "app.agent.tools.factory -> app.application.plugin.runtime", "app.agent.tools.factory -> app.runtime", @@ -1998,9 +1999,10 @@ "app.agent.tools.factory -> app.schemas.notification", "app.agent.tools.factory -> app.schemas.types", "app.agent.tools.impl._filter_rule_utils -> app.application", - "app.agent.tools.impl._filter_rule_utils -> app.application.agentdata", "app.agent.tools.impl._filter_rule_utils -> app.application.configuration", "app.agent.tools.impl._filter_rule_utils -> app.application.rules", + "app.agent.tools.impl._filter_rule_utils -> app.application.subscription", + "app.agent.tools.impl._filter_rule_utils -> app.application.subscription.contract", "app.agent.tools.impl._filter_rule_utils -> app.runtime", "app.agent.tools.impl._filter_rule_utils -> app.runtime.events", "app.agent.tools.impl._filter_rule_utils -> app.schemas", @@ -2072,7 +2074,6 @@ "app.agent.tools.impl.add_download_tasks -> app.agent.tools.base", "app.agent.tools.impl.add_download_tasks -> app.agent.tools.tags", "app.agent.tools.impl.add_download_tasks -> app.application", - "app.agent.tools.impl.add_download_tasks -> app.application.agentdata", "app.agent.tools.impl.add_download_tasks -> app.application.directory", "app.agent.tools.impl.add_download_tasks -> app.chain", "app.agent.tools.impl.add_download_tasks -> app.chain.download", @@ -2102,8 +2103,6 @@ "app.agent.tools.impl.add_subscribe -> app.agent.tools", "app.agent.tools.impl.add_subscribe -> app.agent.tools.base", "app.agent.tools.impl.add_subscribe -> app.agent.tools.tags", - "app.agent.tools.impl.add_subscribe -> app.application", - "app.agent.tools.impl.add_subscribe -> app.application.agentdata", "app.agent.tools.impl.add_subscribe -> app.chain", "app.agent.tools.impl.add_subscribe -> app.chain.subscribe", "app.agent.tools.impl.add_subscribe -> app.domain", @@ -2147,7 +2146,7 @@ "app.agent.tools.impl.create_agent_task -> app.agent.tools.base", "app.agent.tools.impl.create_agent_task -> app.agent.tools.tags", "app.agent.tools.impl.create_agent_task -> app.application", - "app.agent.tools.impl.create_agent_task -> app.application.agentdata", + "app.agent.tools.impl.create_agent_task -> app.application.agenttask", "app.agent.tools.impl.create_agent_task -> app.application.scheduling", "app.agent.tools.impl.create_agent_task -> app.runtime", "app.agent.tools.impl.create_agent_task -> app.runtime.scheduling", @@ -2157,7 +2156,6 @@ "app.agent.tools.impl.delete_agent_task -> app.agent.tools.base", "app.agent.tools.impl.delete_agent_task -> app.agent.tools.tags", "app.agent.tools.impl.delete_agent_task -> app.application", - "app.agent.tools.impl.delete_agent_task -> app.application.agentdata", "app.agent.tools.impl.delete_agent_task -> app.application.scheduling", "app.agent.tools.impl.delete_custom_filter_rule -> app.agent", "app.agent.tools.impl.delete_custom_filter_rule -> app.agent.tools", @@ -2173,8 +2171,6 @@ "app.agent.tools.impl.delete_download_history -> app.agent.tools", "app.agent.tools.impl.delete_download_history -> app.agent.tools.base", "app.agent.tools.impl.delete_download_history -> app.agent.tools.tags", - "app.agent.tools.impl.delete_download_history -> app.application", - "app.agent.tools.impl.delete_download_history -> app.application.agentdata", "app.agent.tools.impl.delete_download_history -> app.runtime", "app.agent.tools.impl.delete_download_history -> app.runtime.log", "app.agent.tools.impl.delete_download_tasks -> app.agent", @@ -2210,9 +2206,6 @@ "app.agent.tools.impl.delete_transfer_history -> app.agent.tools.base", "app.agent.tools.impl.delete_transfer_history -> app.agent.tools.tags", "app.agent.tools.impl.delete_transfer_history -> app.application", - "app.agent.tools.impl.delete_transfer_history -> app.application.agentdata", - "app.agent.tools.impl.delete_transfer_history -> app.application.chain", - "app.agent.tools.impl.delete_transfer_history -> app.application.chain.data", "app.agent.tools.impl.delete_transfer_history -> app.application.transfer", "app.agent.tools.impl.delete_transfer_history -> app.application.transfer.execution", "app.agent.tools.impl.delete_transfer_history -> app.chain", @@ -2302,7 +2295,7 @@ "app.agent.tools.impl.query_agent_tasks -> app.agent.tools.base", "app.agent.tools.impl.query_agent_tasks -> app.agent.tools.tags", "app.agent.tools.impl.query_agent_tasks -> app.application", - "app.agent.tools.impl.query_agent_tasks -> app.application.agentdata", + "app.agent.tools.impl.query_agent_tasks -> app.application.agenttask", "app.agent.tools.impl.query_agent_tasks -> app.application.scheduling", "app.agent.tools.impl.query_agent_tasks -> app.runtime", "app.agent.tools.impl.query_agent_tasks -> app.runtime.settings", @@ -2353,7 +2346,6 @@ "app.agent.tools.impl.query_download_tasks -> app.agent.tools.base", "app.agent.tools.impl.query_download_tasks -> app.agent.tools.tags", "app.agent.tools.impl.query_download_tasks -> app.application", - "app.agent.tools.impl.query_download_tasks -> app.application.agentdata", "app.agent.tools.impl.query_download_tasks -> app.application.history", "app.agent.tools.impl.query_download_tasks -> app.chain", "app.agent.tools.impl.query_download_tasks -> app.chain.download", @@ -2468,8 +2460,6 @@ "app.agent.tools.impl.query_plugin_data -> app.agent.tools.impl", "app.agent.tools.impl.query_plugin_data -> app.agent.tools.impl._plugin_tool_utils", "app.agent.tools.impl.query_plugin_data -> app.agent.tools.tags", - "app.agent.tools.impl.query_plugin_data -> app.application", - "app.agent.tools.impl.query_plugin_data -> app.application.agentdata", "app.agent.tools.impl.query_plugin_data -> app.runtime", "app.agent.tools.impl.query_plugin_data -> app.runtime.log", "app.agent.tools.impl.query_popular_subscribes -> app.adapters", @@ -2506,8 +2496,6 @@ "app.agent.tools.impl.query_site_userdata -> app.agent.tools", "app.agent.tools.impl.query_site_userdata -> app.agent.tools.base", "app.agent.tools.impl.query_site_userdata -> app.agent.tools.tags", - "app.agent.tools.impl.query_site_userdata -> app.application", - "app.agent.tools.impl.query_site_userdata -> app.application.agentdata", "app.agent.tools.impl.query_site_userdata -> app.domain", "app.agent.tools.impl.query_site_userdata -> app.domain.site", "app.agent.tools.impl.query_site_userdata -> app.runtime", @@ -2518,16 +2506,12 @@ "app.agent.tools.impl.query_sites -> app.agent.tools", "app.agent.tools.impl.query_sites -> app.agent.tools.base", "app.agent.tools.impl.query_sites -> app.agent.tools.tags", - "app.agent.tools.impl.query_sites -> app.application", - "app.agent.tools.impl.query_sites -> app.application.agentdata", "app.agent.tools.impl.query_sites -> app.runtime", "app.agent.tools.impl.query_sites -> app.runtime.log", "app.agent.tools.impl.query_subscribe_history -> app.agent", "app.agent.tools.impl.query_subscribe_history -> app.agent.tools", "app.agent.tools.impl.query_subscribe_history -> app.agent.tools.base", "app.agent.tools.impl.query_subscribe_history -> app.agent.tools.tags", - "app.agent.tools.impl.query_subscribe_history -> app.application", - "app.agent.tools.impl.query_subscribe_history -> app.application.agentdata", "app.agent.tools.impl.query_subscribe_history -> app.domain", "app.agent.tools.impl.query_subscribe_history -> app.domain.media", "app.agent.tools.impl.query_subscribe_history -> app.runtime", @@ -2551,8 +2535,6 @@ "app.agent.tools.impl.query_subscribes -> app.agent.tools", "app.agent.tools.impl.query_subscribes -> app.agent.tools.base", "app.agent.tools.impl.query_subscribes -> app.agent.tools.tags", - "app.agent.tools.impl.query_subscribes -> app.application", - "app.agent.tools.impl.query_subscribes -> app.application.agentdata", "app.agent.tools.impl.query_subscribes -> app.domain", "app.agent.tools.impl.query_subscribes -> app.domain.media", "app.agent.tools.impl.query_subscribes -> app.runtime", @@ -2574,8 +2556,6 @@ "app.agent.tools.impl.query_transfer_history -> app.agent.tools", "app.agent.tools.impl.query_transfer_history -> app.agent.tools.base", "app.agent.tools.impl.query_transfer_history -> app.agent.tools.tags", - "app.agent.tools.impl.query_transfer_history -> app.application", - "app.agent.tools.impl.query_transfer_history -> app.application.agentdata", "app.agent.tools.impl.query_transfer_history -> app.foundation", "app.agent.tools.impl.query_transfer_history -> app.foundation.text", "app.agent.tools.impl.query_transfer_history -> app.runtime", @@ -2640,7 +2620,6 @@ "app.agent.tools.impl.run_agent_task -> app.agent.tools.base", "app.agent.tools.impl.run_agent_task -> app.agent.tools.tags", "app.agent.tools.impl.run_agent_task -> app.application", - "app.agent.tools.impl.run_agent_task -> app.application.agentdata", "app.agent.tools.impl.run_agent_task -> app.application.scheduling", "app.agent.tools.impl.run_scheduler -> app.agent", "app.agent.tools.impl.run_scheduler -> app.agent.tools", @@ -2729,7 +2708,6 @@ "app.agent.tools.impl.search_subscribe -> app.agent.tools.base", "app.agent.tools.impl.search_subscribe -> app.agent.tools.tags", "app.agent.tools.impl.search_subscribe -> app.application", - "app.agent.tools.impl.search_subscribe -> app.application.agentdata", "app.agent.tools.impl.search_subscribe -> app.application.subscription", "app.agent.tools.impl.search_subscribe -> app.application.subscription.contract", "app.agent.tools.impl.search_subscribe -> app.chain", @@ -2803,8 +2781,6 @@ "app.agent.tools.impl.test_site -> app.agent.tools", "app.agent.tools.impl.test_site -> app.agent.tools.base", "app.agent.tools.impl.test_site -> app.agent.tools.tags", - "app.agent.tools.impl.test_site -> app.application", - "app.agent.tools.impl.test_site -> app.application.agentdata", "app.agent.tools.impl.test_site -> app.chain", "app.agent.tools.impl.test_site -> app.chain.site", "app.agent.tools.impl.test_site -> app.domain", @@ -2837,7 +2813,7 @@ "app.agent.tools.impl.update_agent_task -> app.agent.tools.base", "app.agent.tools.impl.update_agent_task -> app.agent.tools.tags", "app.agent.tools.impl.update_agent_task -> app.application", - "app.agent.tools.impl.update_agent_task -> app.application.agentdata", + "app.agent.tools.impl.update_agent_task -> app.application.agenttask", "app.agent.tools.impl.update_agent_task -> app.application.scheduling", "app.agent.tools.impl.update_agent_task -> app.runtime", "app.agent.tools.impl.update_agent_task -> app.runtime.scheduling", @@ -2907,7 +2883,6 @@ "app.agent.tools.impl.update_site -> app.agent.tools.base", "app.agent.tools.impl.update_site -> app.agent.tools.tags", "app.agent.tools.impl.update_site -> app.application", - "app.agent.tools.impl.update_site -> app.application.agentdata", "app.agent.tools.impl.update_site -> app.application.site", "app.agent.tools.impl.update_site -> app.application.site.contract", "app.agent.tools.impl.update_site -> app.foundation", @@ -2921,8 +2896,6 @@ "app.agent.tools.impl.update_site_cookie -> app.agent.tools", "app.agent.tools.impl.update_site_cookie -> app.agent.tools.base", "app.agent.tools.impl.update_site_cookie -> app.agent.tools.tags", - "app.agent.tools.impl.update_site_cookie -> app.application", - "app.agent.tools.impl.update_site_cookie -> app.application.agentdata", "app.agent.tools.impl.update_site_cookie -> app.chain", "app.agent.tools.impl.update_site_cookie -> app.chain.site", "app.agent.tools.impl.update_site_cookie -> app.runtime", @@ -3025,6 +2998,8 @@ "app.api.dependencies.history -> app.application.dashboard", "app.api.dependencies.history -> app.application.history", "app.api.dependencies.history -> app.application.mediaserver", + "app.api.dependencies.history -> app.application.transfer", + "app.api.dependencies.history -> app.application.transfer.execution", "app.api.dependencies.history -> app.chain", "app.api.dependencies.history -> app.chain.dashboard", "app.api.dependencies.history -> app.chain.storage", @@ -3318,8 +3293,6 @@ "app.api.endpoints.history -> app.api.response", "app.api.endpoints.history -> app.application", "app.api.endpoints.history -> app.application.agent", - "app.api.endpoints.history -> app.application.chain", - "app.api.endpoints.history -> app.application.chain.data", "app.api.endpoints.history -> app.application.configuration", "app.api.endpoints.history -> app.application.history", "app.api.endpoints.history -> app.application.transfer", @@ -3829,8 +3802,6 @@ "app.api.endpoints.transfer -> app.api.dependencies.history", "app.api.endpoints.transfer -> app.api.response", "app.api.endpoints.transfer -> app.application", - "app.api.endpoints.transfer -> app.application.chain", - "app.api.endpoints.transfer -> app.application.chain.data", "app.api.endpoints.transfer -> app.application.configuration", "app.api.endpoints.transfer -> app.application.directory", "app.api.endpoints.transfer -> app.application.history", @@ -3965,14 +3936,21 @@ "app.api.servcookie -> app.runtime.log", "app.api.servcookie -> app.schemas", "app.api.servcookie -> app.schemas.servcookie", - "app.application.agentdata -> app.application", - "app.application.agentdata -> app.application.history", - "app.application.agentdata -> app.application.security", - "app.application.agentdata -> app.application.security.user", - "app.application.agentdata -> app.application.site", - "app.application.agentdata -> app.application.site.contract", - "app.application.agentdata -> app.application.subscription", - "app.application.agentdata -> app.application.subscription.contract", + "app.application.agent -> app.application", + "app.application.agent -> app.application.agenttask", + "app.application.agent -> app.application.history", + "app.application.agent -> app.application.messaging", + "app.application.agent -> app.application.messaging.chat", + "app.application.agent -> app.application.plugin", + "app.application.agent -> app.application.plugin.data", + "app.application.agent -> app.application.security", + "app.application.agent -> app.application.security.user", + "app.application.agent -> app.application.site", + "app.application.agent -> app.application.site.contract", + "app.application.agent -> app.application.subscription", + "app.application.agent -> app.application.subscription.contract", + "app.application.agent -> app.application.transfer", + "app.application.agent -> app.application.transfer.execution", "app.application.agenttask -> app.application", "app.application.agenttask -> app.application.database", "app.application.agenttask -> app.runtime", @@ -4224,6 +4202,8 @@ "app.application.plugin.catalog -> app.schemas.plugin", "app.application.plugin.config -> app.schemas", "app.application.plugin.config -> app.schemas.exception", + "app.application.plugin.data -> app.schemas", + "app.application.plugin.data -> app.schemas.common", "app.application.plugin.folders -> app.application", "app.application.plugin.folders -> app.application.configuration", "app.application.plugin.folders -> app.runtime", @@ -4563,12 +4543,12 @@ "app.chain._interaction -> app.schemas", "app.chain._interaction -> app.schemas.types", "app.chain._messaging -> app.application", - "app.chain._messaging -> app.application.chain", - "app.chain._messaging -> app.application.chain.data", "app.chain._messaging -> app.application.messaging", "app.chain._messaging -> app.application.messaging.agent", "app.chain._messaging -> app.application.messaging.message", "app.chain._messaging -> app.application.notification", + "app.chain._messaging -> app.application.security", + "app.chain._messaging -> app.application.security.user", "app.chain._messaging -> app.chain", "app.chain._messaging -> app.chain._contracts", "app.chain._messaging -> app.domain", @@ -4586,8 +4566,6 @@ "app.chain._messaging -> app.schemas.transfer", "app.chain._messaging -> app.schemas.types", "app.chain._music -> app.application", - "app.chain._music -> app.application.chain", - "app.chain._music -> app.application.chain.data", "app.chain._music -> app.application.configuration", "app.chain._music -> app.application.subscription", "app.chain._music -> app.application.subscription.contract", @@ -4631,8 +4609,6 @@ "app.chain._transfer -> app.adapters.system.host", "app.chain._transfer -> app.application", "app.chain._transfer -> app.application.agent", - "app.chain._transfer -> app.application.chain", - "app.chain._transfer -> app.application.chain.data", "app.chain._transfer -> app.application.configuration", "app.chain._transfer -> app.application.formatting", "app.chain._transfer -> app.application.history", @@ -4691,8 +4667,6 @@ "app.chain.download -> app.adapters.system", "app.chain.download -> app.adapters.system.host", "app.chain.download -> app.application", - "app.chain.download -> app.application.chain", - "app.chain.download -> app.application.chain.data", "app.chain.download -> app.application.configuration", "app.chain.download -> app.application.directory", "app.chain.download -> app.application.download", @@ -4731,8 +4705,6 @@ "app.chain.download -> app.schemas.types", "app.chain.download -> app.schemas.workflow", "app.chain.interaction -> app.application", - "app.chain.interaction -> app.application.chain", - "app.chain.interaction -> app.application.chain.data", "app.chain.interaction -> app.application.directory", "app.chain.interaction -> app.application.messaging", "app.chain.interaction -> app.application.messaging.media", @@ -4802,8 +4774,6 @@ "app.chain.media -> app.schemas.media", "app.chain.media -> app.schemas.types", "app.chain.mediaserver -> app.application", - "app.chain.mediaserver -> app.application.chain", - "app.chain.mediaserver -> app.application.chain.data", "app.chain.mediaserver -> app.application.mediaserver", "app.chain.mediaserver -> app.application.security", "app.chain.mediaserver -> app.application.security.url", @@ -4932,8 +4902,6 @@ "app.chain.site -> app.adapters.network.cloudflare", "app.chain.site -> app.adapters.network.http", "app.chain.site -> app.application", - "app.chain.site -> app.application.chain", - "app.chain.site -> app.application.chain.data", "app.chain.site -> app.application.configuration", "app.chain.site -> app.application.messaging", "app.chain.site -> app.application.messaging.site", @@ -4970,8 +4938,6 @@ "app.chain.subscribe -> app.adapters.external", "app.chain.subscribe -> app.adapters.external.server", "app.chain.subscribe -> app.application", - "app.chain.subscribe -> app.application.chain", - "app.chain.subscribe -> app.application.chain.data", "app.chain.subscribe -> app.application.configuration", "app.chain.subscribe -> app.application.mediaserver", "app.chain.subscribe -> app.application.messaging", @@ -5039,8 +5005,6 @@ "app.chain.tmdb -> app.schemas.tmdb", "app.chain.tmdb -> app.schemas.types", "app.chain.torrents -> app.application", - "app.chain.torrents -> app.application.chain", - "app.chain.torrents -> app.application.chain.data", "app.chain.torrents -> app.application.configuration", "app.chain.torrents -> app.application.rss", "app.chain.torrents -> app.application.site", @@ -5064,7 +5028,7 @@ "app.chain.torrents -> app.schemas.types", "app.chain.transfer -> app.application", "app.chain.transfer -> app.application.chain", - "app.chain.transfer -> app.application.chain.data", + "app.chain.transfer -> app.application.chain.context", "app.chain.transfer -> app.application.chain.events", "app.chain.transfer -> app.application.configuration", "app.chain.transfer -> app.application.directory", @@ -5109,8 +5073,6 @@ "app.chain.transfer -> app.schemas.workflow", "app.chain.tvdb -> app.chain", "app.chain.user -> app.application", - "app.chain.user -> app.application.chain", - "app.chain.user -> app.application.chain.data", "app.chain.user -> app.application.security", "app.chain.user -> app.application.security.otp", "app.chain.user -> app.application.security.token", @@ -5174,6 +5136,15 @@ "app.command -> app.schemas.event", "app.command -> app.schemas.message", "app.command -> app.schemas.types", + "app.db.adapters.agent -> app.application", + "app.db.adapters.agent -> app.application.agenttask", + "app.db.adapters.agent -> app.db", + "app.db.adapters.agent -> app.db.oper", + "app.db.adapters.agent -> app.db.oper.agenttask", + "app.db.adapters.agent -> app.db.oper.plugindata", + "app.db.adapters.agent -> app.db.uow", + "app.db.adapters.agent -> app.schemas", + "app.db.adapters.agent -> app.schemas.common", "app.db.adapters.chain -> app.application", "app.db.adapters.chain -> app.application.chain", "app.db.adapters.chain -> app.application.chain.events", @@ -7700,7 +7671,7 @@ "app.scheduler -> app.adapters.system.update", "app.scheduler -> app.application", "app.scheduler -> app.application.agent", - "app.scheduler -> app.application.agentdata", + "app.scheduler -> app.application.agenttask", "app.scheduler -> app.application.configuration", "app.scheduler -> app.application.database", "app.scheduler -> app.application.image", @@ -7990,6 +7961,7 @@ "app.startup.composition.configuration -> app.schemas", "app.startup.composition.configuration -> app.schemas.types", "app.startup.composition.context -> app.application", + "app.startup.composition.context -> app.application.agent", "app.startup.composition.context -> app.application.configuration", "app.startup.composition.context -> app.application.history", "app.startup.composition.context -> app.application.messaging", @@ -7999,6 +7971,8 @@ "app.startup.composition.context -> app.application.site.contract", "app.startup.composition.context -> app.application.subscription", "app.startup.composition.context -> app.application.subscription.contract", + "app.startup.composition.context -> app.application.transfer", + "app.startup.composition.context -> app.application.transfer.execution", "app.startup.composition.context -> app.application.workflow", "app.startup.composition.context -> app.runtime", "app.startup.composition.context -> app.runtime.tasks", @@ -8041,6 +8015,7 @@ "app.startup.initializers.agent -> app.agent.llm.gateway", "app.startup.initializers.agent -> app.agent.llm.helper", "app.startup.initializers.agent -> app.agent.llm.provider", + "app.startup.initializers.agent -> app.agent.orchestrator", "app.startup.initializers.agent -> app.agent.prompt", "app.startup.initializers.agent -> app.agent.prompt.transfer_redo", "app.startup.initializers.agent -> app.agent.runtime_loader", @@ -8104,14 +8079,16 @@ "app.startup.initializers.modules -> app.adapters.web", "app.startup.initializers.modules -> app.adapters.web.security", "app.startup.initializers.modules -> app.adapters.web.security.access", + "app.startup.initializers.modules -> app.agent", + "app.startup.initializers.modules -> app.agent.tools", + "app.startup.initializers.modules -> app.agent.tools.manager", "app.startup.initializers.modules -> app.api", "app.startup.initializers.modules -> app.api.data", "app.startup.initializers.modules -> app.application", - "app.startup.initializers.modules -> app.application.agentdata", + "app.startup.initializers.modules -> app.application.agent", "app.startup.initializers.modules -> app.application.agenttask", "app.startup.initializers.modules -> app.application.chain", "app.startup.initializers.modules -> app.application.chain.context", - "app.startup.initializers.modules -> app.application.chain.data", "app.startup.initializers.modules -> app.application.chain.events", "app.startup.initializers.modules -> app.application.configuration", "app.startup.initializers.modules -> app.application.database", @@ -8157,6 +8134,7 @@ "app.startup.initializers.modules -> app.command", "app.startup.initializers.modules -> app.db", "app.startup.initializers.modules -> app.db.adapters", + "app.startup.initializers.modules -> app.db.adapters.agent", "app.startup.initializers.modules -> app.db.adapters.chain", "app.startup.initializers.modules -> app.db.adapters.configuration", "app.startup.initializers.modules -> app.db.adapters.download", @@ -8178,11 +8156,9 @@ "app.startup.initializers.modules -> app.db.adapters.workflow", "app.startup.initializers.modules -> app.db.oper", "app.startup.initializers.modules -> app.db.oper.agentchat", - "app.startup.initializers.modules -> app.db.oper.agenttask", "app.startup.initializers.modules -> app.db.oper.mediaserver", "app.startup.initializers.modules -> app.db.oper.message", "app.startup.initializers.modules -> app.db.oper.passkey", - "app.startup.initializers.modules -> app.db.oper.plugindata", "app.startup.initializers.modules -> app.db.oper.systemconfig", "app.startup.initializers.modules -> app.db.oper.workflow", "app.startup.initializers.modules -> app.db.session", @@ -8219,6 +8195,7 @@ "app.startup.initializers.modules -> app.startup.initializers", "app.startup.initializers.modules -> app.startup.initializers.agent", "app.startup.initializers.modules -> app.startup.initializers.resources", + "app.startup.initializers.modules -> app.startup.initializers.scheduler", "app.startup.initializers.monitor -> app.monitor", "app.startup.initializers.monitor -> app.runtime", "app.startup.initializers.monitor -> app.runtime.execution", @@ -8289,6 +8266,7 @@ "app.startup.initializers.routers -> app.api.servarr", "app.startup.initializers.routers -> app.api.servcookie", "app.startup.initializers.scheduler -> app.application", + "app.startup.initializers.scheduler -> app.application.agenttask", "app.startup.initializers.scheduler -> app.application.scheduling", "app.startup.initializers.scheduler -> app.scheduler", "app.startup.initializers.transfer -> app.chain", @@ -8384,8 +8362,6 @@ "app.workflow.actions.add_download -> app.workflow", "app.workflow.actions.add_download -> app.workflow.actions", "app.workflow.actions.add_subscribe -> app.application", - "app.workflow.actions.add_subscribe -> app.application.chain", - "app.workflow.actions.add_subscribe -> app.application.chain.data", "app.workflow.actions.add_subscribe -> app.application.configuration", "app.workflow.actions.add_subscribe -> app.chain", "app.workflow.actions.add_subscribe -> app.chain.subscribe", @@ -8514,9 +8490,6 @@ "app.workflow.actions.send_message -> app.schemas.workflow", "app.workflow.actions.send_message -> app.workflow", "app.workflow.actions.send_message -> app.workflow.actions", - "app.workflow.actions.transfer_file -> app.application", - "app.workflow.actions.transfer_file -> app.application.chain", - "app.workflow.actions.transfer_file -> app.application.chain.data", "app.workflow.actions.transfer_file -> app.chain", "app.workflow.actions.transfer_file -> app.chain.storage", "app.workflow.actions.transfer_file -> app.chain.transfer", @@ -8528,7 +8501,7 @@ "app.workflow.actions.transfer_file -> app.workflow", "app.workflow.actions.transfer_file -> app.workflow.actions" ], - "module_count": 859, + "module_count": 858, "modules": [ "app", "app.adapters", @@ -8777,13 +8750,11 @@ "app.api.servcookie", "app.application", "app.application.agent", - "app.application.agentdata", "app.application.agenttask", "app.application.audio", "app.application.backup", "app.application.chain", "app.application.chain.context", - "app.application.chain.data", "app.application.chain.events", "app.application.commands", "app.application.configuration", @@ -8922,6 +8893,7 @@ "app.command", "app.db", "app.db.adapters", + "app.db.adapters.agent", "app.db.adapters.chain", "app.db.adapters.configuration", "app.db.adapters.download", diff --git a/tests/fixtures/architecture/mypy-baseline.json b/tests/fixtures/architecture/mypy-baseline.json index aed9fdb0f..a5bc91775 100644 --- a/tests/fixtures/architecture/mypy-baseline.json +++ b/tests/fixtures/architecture/mypy-baseline.json @@ -195,8 +195,8 @@ }, "app/agent/memory/__init__.py": { "arg-type": 1, - "no-untyped-call": 2, - "no-untyped-def": 8, + "no-untyped-call": 1, + "no-untyped-def": 7, "type-arg": 1 }, "app/agent/middleware/activity_log.py": { @@ -251,13 +251,13 @@ "no-any-return": 2 }, "app/agent/orchestrator.py": { - "arg-type": 17, + "arg-type": 13, "assignment": 14, "attr-defined": 7, "dict-item": 1, "no-any-return": 9, - "no-untyped-call": 7, - "no-untyped-def": 21, + "no-untyped-call": 6, + "no-untyped-def": 20, "type-arg": 35, "union-attr": 3, "var-annotated": 1 @@ -384,13 +384,11 @@ "assignment": 1, "import-untyped": 1, "misc": 2, - "no-any-return": 1, "override": 1, "type-arg": 1 }, "app/agent/tools/impl/delete_agent_task.py": { "misc": 1, - "no-any-return": 1, "override": 1 }, "app/agent/tools/impl/delete_custom_filter_rule.py": { @@ -468,8 +466,7 @@ "type-arg": 1 }, "app/agent/tools/impl/query_agent_tasks.py": { - "misc": 1, - "type-arg": 1 + "misc": 1 }, "app/agent/tools/impl/query_builtin_filter_rules.py": { "misc": 1, @@ -742,13 +739,9 @@ "override": 1 }, "app/agent/tools/impl/update_agent_task.py": { - "assignment": 1, - "dict-item": 3, "import-untyped": 1, "misc": 2, - "no-any-return": 2, - "override": 1, - "type-arg": 1 + "override": 1 }, "app/agent/tools/impl/update_custom_filter_rule.py": { "arg-type": 5, @@ -1505,7 +1498,7 @@ "no-any-return": 2, "no-redef": 2, "no-untyped-call": 19, - "no-untyped-def": 18, + "no-untyped-def": 16, "operator": 5, "return-value": 5, "truthy-function": 3, @@ -3344,14 +3337,14 @@ "no-untyped-def": 2 }, "app/startup/initializers/modules.py": { - "arg-type": 8, + "arg-type": 7, "assignment": 1, "attr-defined": 2, "misc": 1, "no-any-return": 2, "no-untyped-call": 32, "no-untyped-def": 6, - "return-value": 4 + "return-value": 3 }, "app/startup/initializers/plugins.py": { "arg-type": 5, diff --git a/tests/fixtures/architecture/ruff-baseline.json b/tests/fixtures/architecture/ruff-baseline.json index fb8ff5861..601e3c7af 100644 --- a/tests/fixtures/architecture/ruff-baseline.json +++ b/tests/fixtures/architecture/ruff-baseline.json @@ -73,10 +73,6 @@ "app/agent/middleware/utils.py": { "I001": 1 }, - "app/agent/orchestrator.py": { - "E402": 11, - "I001": 2 - }, "app/agent/policy/__init__.py": { "I001": 1 }, @@ -104,12 +100,6 @@ "app/agent/skills/metadata.py": { "I001": 1 }, - "app/agent/tools/base.py": { - "I001": 1 - }, - "app/agent/tools/factory.py": { - "I001": 1 - }, "app/agent/tools/impl/_command_safety.py": { "I001": 1 }, @@ -131,15 +121,9 @@ "app/agent/tools/impl/browse_webpage.py": { "I001": 1 }, - "app/agent/tools/impl/create_agent_task.py": { - "I001": 1 - }, "app/agent/tools/impl/delete_custom_filter_rule.py": { "I001": 1 }, - "app/agent/tools/impl/delete_rule_group.py": { - "I001": 1 - }, "app/agent/tools/impl/execute_command.py": { "I001": 1 }, @@ -179,24 +163,15 @@ "app/agent/tools/impl/query_plugin_config.py": { "I001": 1 }, - "app/agent/tools/impl/query_plugin_data.py": { - "I001": 1 - }, "app/agent/tools/impl/query_popular_subscribes.py": { "I001": 1 }, - "app/agent/tools/impl/query_rule_groups.py": { - "I001": 1 - }, "app/agent/tools/impl/query_subscribe_shares.py": { "I001": 1 }, "app/agent/tools/impl/query_system_settings.py": { "I001": 1 }, - "app/agent/tools/impl/query_transfer_history.py": { - "I001": 1 - }, "app/agent/tools/impl/recognize_captcha.py": { "I001": 1 }, @@ -245,12 +220,6 @@ "app/agent/tools/impl/update_plugin_config.py": { "I001": 1 }, - "app/agent/tools/impl/update_rule_group.py": { - "I001": 1 - }, - "app/agent/tools/impl/update_site_cookie.py": { - "I001": 1 - }, "app/agent/tools/impl/update_system_settings.py": { "I001": 1 }, @@ -264,9 +233,6 @@ "F401": 1, "I001": 1 }, - "app/application/agenttask.py": { - "I001": 1 - }, "app/application/directory.py": { "I001": 1 }, @@ -285,9 +251,6 @@ "app/application/messaging/agent.py": { "I001": 1 }, - "app/application/messaging/chat.py": { - "I001": 1 - }, "app/application/messaging/session.py": { "I001": 1 }, @@ -364,9 +327,6 @@ "app/db/models/siteuserdata.py": { "I001": 1 }, - "app/db/models/subscribehistory.py": { - "I001": 1 - }, "app/db/models/systemconfig.py": { "I001": 1 }, @@ -1012,24 +972,12 @@ "tests/test_agent_message_routing.py": { "I001": 1 }, - "tests/test_agent_music_tools.py": { - "I001": 1 - }, - "tests/test_agent_plugin_tools.py": { - "I001": 1 - }, "tests/test_agent_recognize_captcha_tool.py": { "I001": 1 }, - "tests/test_agent_resource_flow_permissions.py": { - "I001": 1 - }, "tests/test_agent_runtime.py": { "I001": 1 }, - "tests/test_agent_scheduled_tasks.py": { - "I001": 1 - }, "tests/test_agent_session_status.py": { "I001": 1 }, @@ -1042,9 +990,6 @@ "tests/test_agent_summarization_streaming.py": { "I001": 1 }, - "tests/test_agent_task_runs.py": { - "I001": 1 - }, "tests/test_agent_tokens_events.py": { "I001": 1 }, @@ -1081,9 +1026,6 @@ "tests/test_bangumi_media_type.py": { "F401": 1 }, - "tests/test_bluray.py": { - "I001": 1 - }, "tests/test_builtin_skill_boundaries.py": { "I001": 1 }, @@ -1096,10 +1038,6 @@ "tests/test_chain_layering.py": { "I001": 1 }, - "tests/test_chain_rate_limit.py": { - "E402": 4, - "I001": 1 - }, "tests/test_cli_auto_update.py": { "I001": 1 }, @@ -1147,9 +1085,6 @@ "tests/test_db_session_lifecycle.py": { "I001": 1 }, - "tests/test_delete_transfer_history_tool.py": { - "I001": 1 - }, "tests/test_docker_bootstrap.py": { "F841": 2, "I001": 1 @@ -1434,9 +1369,6 @@ "tests/test_recommend_chain.py": { "I001": 1 }, - "tests/test_release_group.py": { - "I001": 1 - }, "tests/test_reliability_adr.py": { "I001": 1 }, @@ -1496,10 +1428,6 @@ "E402": 6, "I001": 1 }, - "tests/test_slash_command_interactions.py": { - "E402": 8, - "I001": 1 - }, "tests/test_storage_download_path.py": { "I001": 1 }, @@ -1582,10 +1510,6 @@ "tests/test_transfer_failed_retry_budget.py": { "I001": 1 }, - "tests/test_transfer_failed_retry_buttons.py": { - "E402": 6, - "I001": 2 - }, "tests/test_transfer_history_gate.py": { "I001": 1 }, diff --git a/tests/fixtures/architecture/startup-performance-baseline.json b/tests/fixtures/architecture/startup-performance-baseline.json index 79fc74703..8aabec78d 100644 --- a/tests/fixtures/architecture/startup-performance-baseline.json +++ b/tests/fixtures/architecture/startup-performance-baseline.json @@ -1,41 +1,41 @@ { "schema_version": 2, - "generated_at": "2026-08-28T05:42:42.240504+00:00", + "generated_at": "2026-08-28T08:32:32.120021+00:00", "platform": "macOS-26.5.2-arm64-arm-64bit-Mach-O", "python": "3.14.3", "repeat": 3, "targets": { "app.startup.lifecycle": { - "loaded_app_module_count": 399, - "max_ms": 1058.446, - "median_ms": 1044.722, - "min_ms": 1038.692, + "loaded_app_module_count": 398, + "max_ms": 1530.347, + "median_ms": 1107.857, + "min_ms": 1095.15, "samples_ms": [ - 1058.446, - 1044.722, - 1038.692 + 1530.347, + 1107.857, + 1095.15 ] }, "app.factory": { - "loaded_app_module_count": 411, - "max_ms": 1127.973, - "median_ms": 1058.095, - "min_ms": 1056.804, + "loaded_app_module_count": 410, + "max_ms": 1179.018, + "median_ms": 1123.926, + "min_ms": 1112.387, "samples_ms": [ - 1056.804, - 1058.095, - 1127.973 + 1112.387, + 1123.926, + 1179.018 ] }, "app.main": { - "loaded_app_module_count": 413, - "max_ms": 1096.951, - "median_ms": 1091.7, - "min_ms": 1088.325, + "loaded_app_module_count": 412, + "max_ms": 1179.334, + "median_ms": 1136.928, + "min_ms": 1109.722, "samples_ms": [ - 1096.951, - 1088.325, - 1091.7 + 1179.334, + 1136.928, + 1109.722 ] } }, @@ -47,23 +47,85 @@ { "mode": "normal", "enabled_component_count": 25, - "startup_ms": 0.702, - "full_lifespan_ms": 1.497, + "startup_ms": 0.756, + "full_lifespan_ms": 1.568, "stage_ms": { - "后台任务登记器": 0.095, - "数据库准备": 0.04, - "HTTP 基础能力": 0.03, - "领域依赖装配": 0.029, + "后台任务登记器": 0.112, + "数据库准备": 0.041, + "HTTP 基础能力": 0.031, + "领域依赖装配": 0.03, "数据库引擎预热": 0.026, - "数据库连接预算": 0.028, + "数据库连接预算": 0.026, "路由": 0.026, "模块服务": 0.025, - "插件备份恢复": 0.022, + "插件备份恢复": 0.023, "插件": 0.025, - "定时器": 0.024, + "定时器": 0.026, + "监控器": 0.026, + "待处理整理回放": 0.024, + "命令服务": 0.025, + "工作流": 0.024, + "插件同步与启动收尾": 0.024 + }, + "threads_before": 2, + "threads_started": 2, + "threads_after": 2, + "tasks_before": 1, + "tasks_started": 1, + "tasks_after": 1, + "database_connections_started": 0 + }, + { + "mode": "normal", + "enabled_component_count": 25, + "startup_ms": 0.638, + "full_lifespan_ms": 1.621, + "stage_ms": { + "后台任务登记器": 0.079, + "数据库准备": 0.039, + "HTTP 基础能力": 0.03, + "领域依赖装配": 0.027, + "数据库引擎预热": 0.024, + "数据库连接预算": 0.023, + "路由": 0.023, + "模块服务": 0.022, + "插件备份恢复": 0.022, + "插件": 0.024, + "定时器": 0.023, + "监控器": 0.025, + "待处理整理回放": 0.022, + "命令服务": 0.021, + "工作流": 0.022, + "插件同步与启动收尾": 0.021 + }, + "threads_before": 2, + "threads_started": 2, + "threads_after": 2, + "tasks_before": 1, + "tasks_started": 1, + "tasks_after": 1, + "database_connections_started": 0 + }, + { + "mode": "normal", + "enabled_component_count": 25, + "startup_ms": 0.656, + "full_lifespan_ms": 1.453, + "stage_ms": { + "后台任务登记器": 0.079, + "数据库准备": 0.039, + "HTTP 基础能力": 0.034, + "领域依赖装配": 0.029, + "数据库引擎预热": 0.025, + "数据库连接预算": 0.023, + "路由": 0.022, + "模块服务": 0.022, + "插件备份恢复": 0.022, + "插件": 0.023, + "定时器": 0.023, "监控器": 0.022, "待处理整理回放": 0.021, - "命令服务": 0.024, + "命令服务": 0.021, "工作流": 0.021, "插件同步与启动收尾": 0.021 }, @@ -74,72 +136,10 @@ "tasks_started": 1, "tasks_after": 1, "database_connections_started": 0 - }, - { - "mode": "normal", - "enabled_component_count": 25, - "startup_ms": 0.684, - "full_lifespan_ms": 1.474, - "stage_ms": { - "后台任务登记器": 0.095, - "数据库准备": 0.041, - "HTTP 基础能力": 0.03, - "领域依赖装配": 0.029, - "数据库引擎预热": 0.026, - "数据库连接预算": 0.026, - "路由": 0.024, - "模块服务": 0.022, - "插件备份恢复": 0.024, - "插件": 0.022, - "定时器": 0.024, - "监控器": 0.022, - "待处理整理回放": 0.022, - "命令服务": 0.022, - "工作流": 0.021, - "插件同步与启动收尾": 0.021 - }, - "threads_before": 2, - "threads_started": 2, - "threads_after": 2, - "tasks_before": 1, - "tasks_started": 1, - "tasks_after": 1, - "database_connections_started": 0 - }, - { - "mode": "normal", - "enabled_component_count": 25, - "startup_ms": 0.682, - "full_lifespan_ms": 1.481, - "stage_ms": { - "后台任务登记器": 0.082, - "数据库准备": 0.039, - "HTTP 基础能力": 0.031, - "领域依赖装配": 0.028, - "数据库引擎预热": 0.027, - "数据库连接预算": 0.026, - "路由": 0.026, - "模块服务": 0.026, - "插件备份恢复": 0.025, - "插件": 0.024, - "定时器": 0.025, - "监控器": 0.024, - "待处理整理回放": 0.024, - "命令服务": 0.022, - "工作流": 0.023, - "插件同步与启动收尾": 0.024 - }, - "threads_before": 2, - "threads_started": 2, - "threads_after": 2, - "tasks_before": 1, - "tasks_started": 1, - "tasks_after": 1, - "database_connections_started": 0 } ], - "median_startup_ms": 0.684, - "median_full_lifespan_ms": 1.481, + "median_startup_ms": 0.656, + "median_full_lifespan_ms": 1.568, "enabled_component_count": 25, "enabled_components": [ "后台任务登记器", @@ -174,40 +174,16 @@ { "mode": "safe", "enabled_component_count": 13, - "startup_ms": 0.518, - "full_lifespan_ms": 0.934, + "startup_ms": 0.492, + "full_lifespan_ms": 0.904, "stage_ms": { - "后台任务登记器": 0.09, + "后台任务登记器": 0.08, "数据库准备": 0.038, - "HTTP 基础能力": 0.027, - "领域依赖装配": 0.025, - "数据库引擎预热": 0.022, - "数据库连接预算": 0.021, - "路由": 0.022, - "模块服务": 0.02, - "插件同步与启动收尾": 0.02 - }, - "threads_before": 2, - "threads_started": 2, - "threads_after": 2, - "tasks_before": 1, - "tasks_started": 1, - "tasks_after": 1, - "database_connections_started": 0 - }, - { - "mode": "safe", - "enabled_component_count": 13, - "startup_ms": 0.486, - "full_lifespan_ms": 0.903, - "stage_ms": { - "后台任务登记器": 0.081, - "数据库准备": 0.037, - "HTTP 基础能力": 0.03, + "HTTP 基础能力": 0.031, "领域依赖装配": 0.028, - "数据库引擎预热": 0.024, + "数据库引擎预热": 0.025, "数据库连接预算": 0.023, - "路由": 0.023, + "路由": 0.024, "模块服务": 0.023, "插件同步与启动收尾": 0.023 }, @@ -222,18 +198,42 @@ { "mode": "safe", "enabled_component_count": 13, - "startup_ms": 0.502, - "full_lifespan_ms": 0.895, + "startup_ms": 0.516, + "full_lifespan_ms": 0.914, "stage_ms": { - "后台任务登记器": 0.08, + "后台任务登记器": 0.085, + "数据库准备": 0.05, + "HTTP 基础能力": 0.03, + "领域依赖装配": 0.032, + "数据库引擎预热": 0.024, + "数据库连接预算": 0.023, + "路由": 0.023, + "模块服务": 0.022, + "插件同步与启动收尾": 0.022 + }, + "threads_before": 2, + "threads_started": 2, + "threads_after": 2, + "tasks_before": 1, + "tasks_started": 1, + "tasks_after": 1, + "database_connections_started": 0 + }, + { + "mode": "safe", + "enabled_component_count": 13, + "startup_ms": 0.492, + "full_lifespan_ms": 1.022, + "stage_ms": { + "后台任务登记器": 0.079, "数据库准备": 0.038, - "HTTP 基础能力": 0.031, - "领域依赖装配": 0.028, - "数据库引擎预热": 0.027, - "数据库连接预算": 0.026, + "HTTP 基础能力": 0.03, + "领域依赖装配": 0.03, + "数据库引擎预热": 0.026, + "数据库连接预算": 0.025, "路由": 0.025, - "模块服务": 0.025, - "插件同步与启动收尾": 0.023 + "模块服务": 0.023, + "插件同步与启动收尾": 0.022 }, "threads_before": 2, "threads_started": 2, @@ -244,8 +244,8 @@ "database_connections_started": 0 } ], - "median_startup_ms": 0.502, - "median_full_lifespan_ms": 0.903, + "median_startup_ms": 0.492, + "median_full_lifespan_ms": 0.914, "enabled_component_count": 13, "enabled_components": [ "后台任务登记器", diff --git a/tests/test_agent_add_subscribe_tool.py b/tests/test_agent_add_subscribe_tool.py index 234f6f508..6c194140c 100644 --- a/tests/test_agent_add_subscribe_tool.py +++ b/tests/test_agent_add_subscribe_tool.py @@ -18,7 +18,15 @@ class TestAgentAddSubscribeTool(unittest.TestCase): self.assertNotIn("第1季(默认)", message) def test_tv_subscription_without_season_reports_default_first_season(self): - tool = AddSubscribeTool(session_id="session-1", user_id="10001") + tool = AddSubscribeTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace( + users=SimpleNamespace( + find_name_by_bindings=lambda _bindings: "moviepilot-user" + ) + ), + ) tool.set_message_attr( channel=NotificationChannel.Telegram.value, source="telegram-main", @@ -28,12 +36,7 @@ class TestAgentAddSubscribeTool(unittest.TestCase): with patch( "app.agent.tools.impl.add_subscribe.SubscribeChain.async_add", new=AsyncMock(return_value=(1, "")), - ) as async_add, patch( - "app.agent.tools.impl.add_subscribe.get_agent_user_port", - return_value=SimpleNamespace( - find_name_by_bindings=lambda _bindings: "moviepilot-user" - ), - ): + ) as async_add: result = asyncio.run( tool.run( title="Breaking Bad", @@ -47,7 +50,13 @@ class TestAgentAddSubscribeTool(unittest.TestCase): self.assertIn("默认按第一季订阅", result) def test_subscription_falls_back_to_channel_username_when_no_binding_exists(self): - tool = AddSubscribeTool(session_id="session-1", user_id="10001") + tool = AddSubscribeTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace( + users=SimpleNamespace(find_name_by_bindings=lambda _bindings: None) + ), + ) tool.set_message_attr( channel=NotificationChannel.Telegram.value, source="telegram-main", @@ -57,12 +66,7 @@ class TestAgentAddSubscribeTool(unittest.TestCase): with patch( "app.agent.tools.impl.add_subscribe.SubscribeChain.async_add", new=AsyncMock(return_value=(1, "")), - ) as async_add, patch( - "app.agent.tools.impl.add_subscribe.get_agent_user_port", - return_value=SimpleNamespace( - find_name_by_bindings=lambda _bindings: None - ), - ): + ) as async_add: result = asyncio.run( tool.run( title="The Matrix", @@ -75,7 +79,13 @@ class TestAgentAddSubscribeTool(unittest.TestCase): self.assertIn("成功添加订阅:The Matrix (1999)", result) def test_feishu_subscription_uses_pre_resolved_username_when_openid_lookup_misses(self): - tool = AddSubscribeTool(session_id="session-1", user_id="ou_feishu_user") + tool = AddSubscribeTool( + session_id="session-1", + user_id="ou_feishu_user", + data=SimpleNamespace( + users=SimpleNamespace(find_name_by_bindings=lambda _bindings: None) + ), + ) tool.set_message_attr( channel=NotificationChannel.Feishu.value, source="feishu-main", @@ -85,12 +95,7 @@ class TestAgentAddSubscribeTool(unittest.TestCase): with patch( "app.agent.tools.impl.add_subscribe.SubscribeChain.async_add", new=AsyncMock(return_value=(1, "")), - ) as async_add, patch( - "app.agent.tools.impl.add_subscribe.get_agent_user_port", - return_value=SimpleNamespace( - find_name_by_bindings=lambda _bindings: None - ), - ): + ) as async_add: result = asyncio.run( tool.run( title="The Matrix", diff --git a/tests/test_agent_data_ports.py b/tests/test_agent_data_ports.py index 0be02b9b6..123893f3d 100644 --- a/tests/test_agent_data_ports.py +++ b/tests/test_agent_data_ports.py @@ -1,27 +1,235 @@ -"""Agent 命名数据端口工厂测试。""" +"""Agent 数据上下文与类型化任务适配器测试。""" -from app.application import agentdata +from dataclasses import FrozenInstanceError +from types import SimpleNamespace +from typing import cast +from unittest.mock import MagicMock + +import pytest + +import app.agent.tools.factory as tool_factory_module +import app.application.agent as agent_services +from app.agent.memory import MemoryManager +from app.agent.tools.factory import MoviePilotToolFactory +from app.agent.tools.impl.query_agent_tasks import QueryAgentTasksTool +from app.agent.tools.manager import MoviePilotToolsManager +from app.application.agent import AgentDataContext +from app.application.agenttask import AgentTaskRepository, AgentTaskSnapshot +from app.db.adapters.agent import TransactionalAgentTaskRepository +from app.db.session import SessionFactory +from app.scheduler import Scheduler +from app.startup.initializers import agent as agent_initializer -def test_named_agent_data_getters_use_registered_factories(monkeypatch) -> None: - """每个命名 getter 都应创建组合根登记的对应端口实例。""" - names = { - "agent_chat": agentdata.get_agent_chat_port, - "agent_task": agentdata.get_agent_task_port, - "user": agentdata.get_agent_user_port, - "site": agentdata.get_agent_site_port, - "subscribe": agentdata.get_agent_subscribe_port, - "subscribe_history": agentdata.get_agent_subscribe_history_port, - "transfer_history": agentdata.get_agent_transfer_history_port, - "download_history": agentdata.get_agent_download_history_port, - "plugin_data": agentdata.get_agent_plugin_data_port, - } - factories = { - name: (lambda current=name: current) - for name in names - } - monkeypatch.setattr(agentdata, "_ports", agentdata.AgentDataPorts(**factories)) +def _context(tasks: AgentTaskRepository) -> AgentDataContext: + """构造仅用于验证依赖身份的 Agent 数据上下文。""" + dependency = cast(object, SimpleNamespace()) + return AgentDataContext( + chat=cast(object, dependency), + chat_persistence=cast(object, dependency), + tasks=tasks, + users=cast(object, dependency), + sites=cast(object, dependency), + subscriptions=cast(object, dependency), + subscription_history=cast(object, dependency), + transfer_history=cast(object, dependency), + transfer_execution=cast(object, dependency), + download_history=cast(object, dependency), + plugin_data=cast(object, dependency), + ) - assert {name: getter() for name, getter in names.items()} == { - name: name for name in names - } + +def test_agent_tool_receives_exact_data_context() -> None: + """内置工具只能消费构造时注入的同一上下文,不再查询全局注册表。""" + repository = TransactionalAgentTaskRepository(SessionFactory) + context = _context(repository) + tool = QueryAgentTasksTool(session_id="session", user_id="user", data=context) + + assert tool.data is context + assert tool.data.tasks is repository + + +def test_agent_service_facade_resolves_registered_dependencies(monkeypatch) -> None: + """Agent 服务门面应稳定处理未装配状态并转发组合根注入能力。""" + provider_names = ( + "_agent_manager_provider", + "_running_agent_manager_provider", + "_prompt_manager_provider", + "_agent_capability_manager_provider", + "_llm_helper_provider", + "_manual_redo_prompt_builder_provider", + ) + for provider_name in provider_names: + monkeypatch.setattr(agent_services, provider_name, None) + + assert agent_services.get_running_agent_manager() is None + with pytest.raises(RuntimeError, match="agent_manager 未注册"): + agent_services.get_agent_manager() + + manager = object() + prompt_manager = object() + capability_manager = MagicMock() + capability_manager.is_audio_input_available.return_value = True + capability_manager.transcribe_audio.return_value = "转写结果" + llm_helper = MagicMock() + llm_helper.supports_image_input.return_value = True + agent_services.register_agent_services( + agent_manager=manager, + prompt_manager=prompt_manager, + capability_manager=capability_manager, + llm_helper=llm_helper, + ) + + assert agent_services.get_agent_manager() is manager + assert agent_services.get_running_agent_manager() is manager + assert agent_services.get_prompt_manager() is prompt_manager + assert agent_services.supports_image_input( + provider="openai", + model="vision-model", + base_url="https://example.com", + base_url_preset="custom", + ) + llm_helper.supports_image_input.assert_called_once_with( + provider="openai", + model="vision-model", + base_url="https://example.com", + base_url_preset="custom", + ) + assert agent_services.is_audio_input_available() + assert agent_services.transcribe_audio(b"audio", filename="voice.wav") == "转写结果" + capability_manager.transcribe_audio.assert_called_once_with( + b"audio", + filename="voice.wav", + ) + with pytest.raises(RuntimeError, match="提示词构建器未注册"): + agent_services.build_manual_redo_prompt(object()) + + agent_services.register_agent_services( + agent_manager=manager, + prompt_manager=prompt_manager, + capability_manager=capability_manager, + llm_helper=llm_helper, + manual_redo_prompt_builder=lambda history: f"redo:{history}", + ) + assert agent_services.build_manual_redo_prompt("history") == "redo:history" + + +def test_tool_factory_injects_context_only_into_builtin_tools(monkeypatch) -> None: + """工具工厂必须把上下文传给宿主工具,同时保持插件构造 ABI 不变。""" + repository = TransactionalAgentTaskRepository(SessionFactory) + context = _context(repository) + monkeypatch.setattr( + MoviePilotToolFactory, + "_get_builtin_tool_classes", + classmethod(lambda _cls, _channel=None: [QueryAgentTasksTool]), + ) + monkeypatch.setattr(tool_factory_module, "_get_plugin_agent_tools", lambda: []) + + tools = MoviePilotToolFactory.create_tools( + session_id="session", + user_id="user", + data=context, + ) + + assert len(tools) == 1 + assert tools[0].data is context + + +def test_tool_manager_reassembly_invalidates_factory_catalog() -> None: + """重复装配数据上下文时必须丢弃持有旧仓储的工厂工具快照。""" + first = _context(TransactionalAgentTaskRepository(SessionFactory)) + second = _context(TransactionalAgentTaskRepository(SessionFactory)) + manager = MoviePilotToolsManager(data=first) + manager.tools = [ + QueryAgentTasksTool(session_id="session", user_id="user", data=first) + ] + manager._catalog_materialized = True + manager._catalog_managed_by_factory = True + + manager.set_data_context(second) + + assert manager._data is second + assert manager.tools == [] + assert manager.catalog is None + assert manager._catalog_materialized is False + + +def test_memory_manager_reads_only_injected_chat_service() -> None: + """记忆恢复必须调用构造时注入的会话服务,不再查询数据 locator。""" + chat = MagicMock() + chat.get_sync.return_value = SimpleNamespace(agent_messages=[]) + manager = MemoryManager(chat=chat, persistence=MagicMock()) + + assert manager.get_agent_messages("session", "user") == [] + chat.get_sync.assert_called_once_with(session_id="session", user_id="user") + + +def test_scheduler_reads_injected_agent_task_repository() -> None: + """Scheduler 注册任务时必须读取显式注入的 AgentTask 仓储。""" + repository = MagicMock() + repository.list.return_value = [SimpleNamespace(id=9)] + scheduler = object.__new__(Scheduler) + Scheduler.__init__(scheduler) + scheduler.update_agent_task_job = MagicMock() + scheduler.configure_agent_tasks(repository) + + scheduler.init_agent_task_jobs() + + repository.list.assert_called_once_with(enabled=True) + scheduler.update_agent_task_job.assert_called_once_with(9) + + +def test_agent_initializer_reassembly_replaces_cached_manager(monkeypatch) -> None: + """组合根重装配后不得复用持有旧数据上下文的 manager。""" + first = _context(TransactionalAgentTaskRepository(SessionFactory)) + second = _context(TransactionalAgentTaskRepository(SessionFactory)) + monkeypatch.setattr(agent_initializer, "_agent_data_context", None) + monkeypatch.setattr(agent_initializer, "_injected_agent_manager", None) + monkeypatch.setattr( + "app.agent.orchestrator.memory_manager", + MemoryManager(), + ) + + agent_initializer.configure_agent_data_context(first) + first_manager = agent_initializer._get_injected_agent_manager() + agent_initializer.configure_agent_data_context(second) + second_manager = agent_initializer._get_injected_agent_manager() + + assert first_manager is not second_manager + assert first_manager._data is first + assert second_manager._data is second + + +def test_transactional_agent_task_repository_projects_frozen_snapshots() -> None: + """任务写入提交后必须返回脱离 Session 的冻结快照。""" + repository = TransactionalAgentTaskRepository(SessionFactory) + task = repository.add( + name="架构检查", + content="检查 Agent 数据边界", + trigger_type="cron", + cron_expression="0 8 * * *", + run_at=None, + user_id="user-1", + username="tester", + session_id="session-1", + channel=None, + source="test", + original_chat_id=None, + ) + + assert isinstance(task, AgentTaskSnapshot) + assert repository.get(task.id, user_id="user-1") == task + assert repository.list(user_id="user-1") == [task] + with pytest.raises(FrozenInstanceError): + task.name = "不可修改" # type: ignore[misc] + + assert repository.update( + task.id, + {"name": "已更新"}, + user_id="user-1", + ) + updated = repository.get(task.id, user_id="user-1") + assert updated is not None + assert updated.name == "已更新" + assert repository.delete(task.id, user_id="user-1") + assert repository.get(task.id, user_id="user-1") is None diff --git a/tests/test_agent_lifecycle.py b/tests/test_agent_lifecycle.py index f74d5c2dd..bfa479d76 100644 --- a/tests/test_agent_lifecycle.py +++ b/tests/test_agent_lifecycle.py @@ -13,7 +13,6 @@ from app.agent.orchestrator import ( ) from app.agent.tools.base import reopen_blocking_executors from app.application import query as query_application -from app.application.agentdata import get_agent_subscribe_history_port from app.application.messaging.agent import ( create_web_agent_background_task, shutdown_web_agent_background_tasks, @@ -100,9 +99,8 @@ async def test_agent_entrypoint_initializes_on_calling_loop(monkeypatch) -> None @pytest.mark.anyio async def test_agent_manager_background_tasks_share_owner_loop(monkeypatch) -> None: """长期清理任务必须在同一循环创建、复用并完成关闭。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) current_loop = asyncio.get_running_loop() await manager.initialize() @@ -133,10 +131,9 @@ async def test_agent_entrypoint_reuses_tasks_and_closes_idempotently( monkeypatch, ) -> None: """全局启停入口重复调用时必须复用任务并安全收口。""" - manager = AgentManager() memory_manager = MemoryManager() + manager = AgentManager(memory=memory_manager) initializer = agent_initializer.AgentInitializer() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) _patch_agent_settings(monkeypatch, True) monkeypatch.setattr(agent_initializer, "agent_manager", manager) monkeypatch.setattr(agent_initializer, "agent_initializer", initializer) @@ -207,7 +204,7 @@ async def test_agent_initialization_failure_does_not_stop_module_startup( query_page = await query_sdk.async_list_subscriptions({"ids": [-1]}) assert query_page.items == [] assert query_page.total == 0 - history_repository = get_agent_subscribe_history_port() + history_repository = runtime.agent.subscription_history assert ( await history_repository.async_list_by_type( "不存在的订阅类型", @@ -245,9 +242,8 @@ async def test_agent_manager_acceptance_gate_rejects_stale_references( monkeypatch, ) -> None: """未启动和关闭后的 manager 引用不得创建队列、worker 或 Agent。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) with pytest.raises(AgentManagerUnavailableError): await manager.process_message("before-init", "1", "hello") @@ -277,9 +273,8 @@ async def test_agent_manager_rejects_messages_when_session_queue_is_full( monkeypatch, ) -> None: """会话达到待处理容量后应立即拒绝,不得在生命周期锁内无限等待。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) started = asyncio.Event() async def block_current(_task): @@ -334,9 +329,8 @@ async def test_agent_manager_rejects_messages_when_session_queue_is_full( @pytest.mark.anyio async def test_agent_manager_records_queue_wait_time(monkeypatch) -> None: """任务开始执行后应保留最近一次排队等待的可观测值。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) started = asyncio.Event() async def process(_task): @@ -366,10 +360,9 @@ async def test_agent_manager_rejects_new_messages_while_worker_shutdown_is_pendi monkeypatch, ) -> None: """worker 未在关停上限内收敛时,同一会话必须保持停止态。""" - manager = AgentManager() - manager._shutdown_timeout = 0.01 memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) + manager._shutdown_timeout = 0.01 started = asyncio.Event() release = asyncio.Event() @@ -418,11 +411,10 @@ async def test_clear_session_defers_agent_cleanup_until_worker_finishes( monkeypatch, ) -> None: """clear_session 超时期间不得清理仍被 worker 使用的 Agent 和记忆。""" - manager = AgentManager() - manager._shutdown_timeout = 0.01 memory_manager = MemoryManager() memory_manager.clear_memory = MagicMock() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) + manager._shutdown_timeout = 0.01 started = asyncio.Event() release = asyncio.Event() cleanup_called = asyncio.Event() @@ -480,10 +472,9 @@ async def test_close_defers_shared_agent_teardown_after_worker_timeout( monkeypatch, ) -> None: """管理器关闭超时后,旧 worker 收敛前不得拆除共享 Agent 资源。""" - manager = AgentManager() - manager._shutdown_timeout = 0.01 memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) + manager._shutdown_timeout = 0.01 started = asyncio.Event() release = asyncio.Event() cleanup_called = asyncio.Event() @@ -537,9 +528,8 @@ async def test_close_retains_agent_until_detached_subagent_converges( monkeypatch, ) -> None: """Agent cleanup 返回 False 时 manager 必须保留 agent 和共享记忆 owner。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) class PendingSubagentOwner: """首次清理未收敛、第二次清理成功的最小 Agent 替身。""" @@ -577,9 +567,8 @@ async def test_agent_manager_close_serializes_racing_enqueue_and_clear( monkeypatch, ) -> None: """关闭、临时会话清理和迟到请求必须串行收口且只清理一次。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) started = asyncio.Event() cleanup_started = asyncio.Event() release_cleanup = asyncio.Event() @@ -639,9 +628,8 @@ async def test_agent_manager_close_serializes_racing_enqueue_and_clear( @pytest.mark.anyio async def test_clear_session_settles_current_and_queued_waiters(monkeypatch) -> None: """清空会话必须同时结束正在执行和尚未执行的等待请求。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) started = asyncio.Event() async def block_current(_task): @@ -688,9 +676,8 @@ async def test_background_prompt_is_owned_and_cancelled_by_manager_close( monkeypatch, ) -> None: """后台 prompt 必须进入 manager worker,关闭时同步结束且不残留临时会话。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) started = asyncio.Event() async def block_background(task): @@ -753,10 +740,9 @@ async def test_clear_session_cancellation_does_not_stick_cleanup_pending( monkeypatch, ) -> None: """clear_session 被调用方取消后必须能重试或已转交延迟清理。""" - manager = AgentManager() memory_manager = MemoryManager() memory_manager.clear_memory = MagicMock() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) session_id = "clear-caller-cancelled" started = asyncio.Event() cancellation_seen = asyncio.Event() @@ -854,9 +840,8 @@ async def test_session_worker_restarts_after_idle_timeout_races_with_full_enqueu monkeypatch, ) -> None: """空闲退出与满队列入队交错时必须保留会话消费者。""" - manager = AgentManager() memory_manager = MemoryManager() - monkeypatch.setattr(agent_module, "memory_manager", memory_manager) + manager = AgentManager(memory=memory_manager) session_id = "idle-timeout-full-queue" processed = [] first_processed = asyncio.Event() diff --git a/tests/test_agent_music_tools.py b/tests/test_agent_music_tools.py index 87627aced..ca162ef5c 100644 --- a/tests/test_agent_music_tools.py +++ b/tests/test_agent_music_tools.py @@ -19,8 +19,8 @@ from app.agent.tools.impl.query_media_detail import ( QueryMediaDetailInput, QueryMediaDetailTool, ) -from app.agent.tools.impl.query_subscribe_shares import QuerySubscribeSharesTool from app.agent.tools.impl.query_subscribe_history import QuerySubscribeHistoryTool +from app.agent.tools.impl.query_subscribe_shares import QuerySubscribeSharesTool from app.agent.tools.impl.recognize_media import RecognizeMediaTool from app.agent.tools.impl.scrape_metadata import ScrapeMetadataTool from app.agent.tools.impl.search_media import SearchMediaTool @@ -422,16 +422,18 @@ def test_add_download_preserves_album_context_and_full_coverage_marker(): submitted_contexts.append(context) return "download-1", None - tool = AddDownloadTasksTool(session_id="session-1", user_id="10001") + site_repository = SimpleNamespace( + async_get_by_name=AsyncMock(return_value=site) + ) + tool = AddDownloadTasksTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace(sites=site_repository), + ) with patch.object( AddDownloadTasksTool, "_async_resolve_cached_context", new=AsyncMock(return_value=cached_context), - ), patch( - "app.agent.tools.impl.add_download_tasks.get_agent_site_port", - return_value=SimpleNamespace( - async_get_by_name=AsyncMock(return_value=site) - ), ), patch.object( AddDownloadTasksTool, "_download_single_sync", @@ -480,11 +482,11 @@ def test_query_subscribe_history_uses_database_media_values_and_music_fields(mon calls.append((mtype, page, count)) return [record] if mtype == MediaType.MUSIC.value else [] - monkeypatch.setattr( - "app.agent.tools.impl.query_subscribe_history.get_agent_subscribe_history_port", - FakeHistoryOper, + tool = QuerySubscribeHistoryTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace(subscription_history=FakeHistoryOper()), ) - tool = QuerySubscribeHistoryTool(session_id="session-1", user_id="10001") result = asyncio.run(tool.run(media_type="all")) @@ -514,11 +516,11 @@ def test_music_history_filter_excludes_video_records(monkeypatch): """仅为电影类型返回记录。""" return [movie_record] if mtype == MediaType.MOVIE.value else [] - monkeypatch.setattr( - "app.agent.tools.impl.query_subscribe_history.get_agent_subscribe_history_port", - FakeHistoryOper, + tool = QuerySubscribeHistoryTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace(subscription_history=FakeHistoryOper()), ) - tool = QuerySubscribeHistoryTool(session_id="session-1", user_id="10001") result = asyncio.run( tool.run(media_type="all", music_type="recording") diff --git a/tests/test_agent_plugin_tools.py b/tests/test_agent_plugin_tools.py index fa8f6ed70..f0bb1841d 100644 --- a/tests/test_agent_plugin_tools.py +++ b/tests/test_agent_plugin_tools.py @@ -16,13 +16,13 @@ from app.agent.tools.impl.query_market_plugins import QueryMarketPluginsTool from app.agent.tools.impl.query_plugin_config import QueryPluginConfigTool from app.agent.tools.impl.query_plugin_data import QueryPluginDataTool from app.agent.tools.impl.reload_plugin import ReloadPluginTool -from app.schemas.plugin import PluginRuntimeStatus from app.agent.tools.impl.uninstall_plugin import UninstallPluginTool from app.agent.tools.impl.update_plugin_config import UpdatePluginConfigTool from app.runtime.extensions.plugin.admission import ( PluginMutationAdmission, PluginMutationRejectedError, ) +from app.schemas.plugin import PluginRuntimeStatus def _plugin_snapshot(state: bool = True) -> dict: @@ -439,22 +439,22 @@ def test_query_plugin_data_truncates_large_payload() -> None: """ 查询插件数据会截断超长内容并返回预览。 """ - tool = QueryPluginDataTool(session_id="session-1", user_id="10001") plugin_data_oper = MagicMock() - plugin_data_oper.async_get_data_all = AsyncMock(return_value=[ - SimpleNamespace(key="payload", value={"text": "x" * 5000}) - ]) + plugin_data_oper.list = AsyncMock( + return_value={"payload": {"text": "x" * 5000}} + ) with ( patch( "app.agent.tools.impl.query_plugin_data.get_plugin_snapshot", return_value=_plugin_snapshot(), ), - patch( - "app.agent.tools.impl.query_plugin_data.get_agent_plugin_data_port", - return_value=plugin_data_oper, - ), ): + tool = QueryPluginDataTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace(plugin_data=plugin_data_oper), + ) result = asyncio.run(tool.run(plugin_id="DemoPlugin", max_chars=200)) payload = json.loads(result) diff --git a/tests/test_agent_query_download_tasks_tool.py b/tests/test_agent_query_download_tasks_tool.py index c3be862dc..71daacb3c 100644 --- a/tests/test_agent_query_download_tasks_tool.py +++ b/tests/test_agent_query_download_tasks_tool.py @@ -1,9 +1,19 @@ import asyncio import json +from types import SimpleNamespace from unittest.mock import MagicMock, patch from app.agent.tools.impl.query_download_tasks import QueryDownloadTasksTool -from app.schemas import DownloaderTorrent +from app.schemas.transfer import DownloaderTorrent + + +def _tool() -> QueryDownloadTasksTool: + """构造带显式下载历史端口的查询工具。""" + return QueryDownloadTasksTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace(download_history=MagicMock()), + ) def test_completed_status_returns_qbittorrent_and_transmission_completed_states(): @@ -41,7 +51,7 @@ def test_completed_status_returns_qbittorrent_and_transmission_completed_states( "_load_history_map", return_value={}, ): - result = QueryDownloadTasksTool._query_downloads_sync(status="completed") + result = _tool()._query_downloads_sync(status="completed") assert result["downloads"] == completed_torrents download_chain.list_torrents.assert_called_once_with( @@ -126,7 +136,7 @@ def test_hash_query_loads_trackers_for_matching_task(): "_load_history_map", return_value={}, ): - result = QueryDownloadTasksTool._query_downloads_sync(hash_value="a" * 40) + result = _tool()._query_downloads_sync(hash_value="a" * 40) assert result["downloads"][0].trackers == ["https://tracker.example/announce"] download_chain.get_torrent_trackers.assert_called_once_with( @@ -161,7 +171,7 @@ def test_include_all_tags_passes_scope_to_downloader_query(): "_load_history_map", return_value={}, ): - result = QueryDownloadTasksTool._query_downloads_sync( + result = _tool()._query_downloads_sync( status="all", include_all_tags=True, ) @@ -199,7 +209,7 @@ def test_include_all_tags_downloading_status_uses_list_torrents(): "_load_history_map", return_value={}, ): - result = QueryDownloadTasksTool._query_downloads_sync( + result = _tool()._query_downloads_sync( status="downloading", include_all_tags=True, ) @@ -238,7 +248,7 @@ def test_include_all_tags_false_string_keeps_builtin_tag_scope(): "_load_history_map", return_value={}, ): - result = QueryDownloadTasksTool._query_downloads_sync( + result = _tool()._query_downloads_sync( status="completed", include_all_tags="false", ) diff --git a/tests/test_agent_query_subscribes.py b/tests/test_agent_query_subscribes.py index 6256aaacc..24bfc811f 100644 --- a/tests/test_agent_query_subscribes.py +++ b/tests/test_agent_query_subscribes.py @@ -1,7 +1,7 @@ import asyncio import json from types import SimpleNamespace -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock from app.agent.tools.impl.query_subscribes import QuerySubscribesTool from app.db.models.subscribe import Subscribe @@ -22,17 +22,16 @@ def test_agent_query_subscribes_returns_manual_total_episode(): state="P", ) - with patch( - "app.agent.tools.impl.query_subscribes.get_agent_subscribe_port", - return_value=SimpleNamespace( - async_list=AsyncMock(return_value=[subscribe]) - ), - ): - result = asyncio.run( - QuerySubscribesTool(session_id="session-1", user_id="10001").run( - tmdb_id=224839, - ) + repository = SimpleNamespace(async_list=AsyncMock(return_value=[subscribe])) + result = asyncio.run( + QuerySubscribesTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace(subscriptions=repository), + ).run( + tmdb_id=224839, ) + ) _, result_json = result.split("\n\n", maxsplit=1) payload = json.loads(result_json) diff --git a/tests/test_agent_resource_flow_permissions.py b/tests/test_agent_resource_flow_permissions.py index a78238571..7e18c873f 100644 --- a/tests/test_agent_resource_flow_permissions.py +++ b/tests/test_agent_resource_flow_permissions.py @@ -7,6 +7,7 @@ import json from types import SimpleNamespace from unittest.mock import AsyncMock, patch +from app.agent import MoviePilotAgent from app.agent.tools.catalog import ToolCatalogSnapshot from app.agent.tools.factory import MoviePilotToolFactory from app.agent.tools.impl.edit_file import EditFileTool @@ -17,13 +18,11 @@ from app.agent.tools.impl.query_system_settings import QuerySystemSettingsTool from app.agent.tools.impl.read_file import ReadFileTool from app.agent.tools.impl.write_file import WriteFileTool from app.agent.tools.manager import MoviePilotToolsManager -from app.agent import MoviePilotAgent -from app.runtime.config import settings from app.modules.feishu import FeishuModule from app.modules.telegram import TelegramModule +from app.runtime.config import settings from app.schemas.types import NotificationChannel - # 渠道模块在导入时注册管理员解析器,权限回查测试需显式加载对应模块。 _REGISTERED_CHANNEL_MODULES = (FeishuModule, TelegramModule) @@ -89,7 +88,6 @@ def test_non_admin_manager_hides_admin_only_send_local_file_tool(): def test_query_sites_hides_only_sensitive_fields_for_non_admin_user(): """普通用户查询站点时只隐藏 Cookie、API Key、Token 和 RSS。""" - tool = QuerySitesTool(session_id="session-1", user_id="10001") site = SimpleNamespace( id=1, name="TestSite", @@ -114,11 +112,13 @@ def test_query_sites_hides_only_sensitive_fields_for_non_admin_user(): downloader="qb", ) - with patch( - "app.agent.tools.impl.query_sites.get_agent_site_port" - ) as site_oper: - site_oper.return_value.async_list = AsyncMock(return_value=[site]) - result = asyncio.run(tool.run()) + repository = SimpleNamespace(async_list=AsyncMock(return_value=[site])) + tool = QuerySitesTool( + session_id="session-1", + user_id="10001", + data=SimpleNamespace(sites=repository), + ) + result = asyncio.run(tool.run()) payload = json.loads(result) assert payload == [ @@ -150,8 +150,6 @@ def test_query_sites_hides_only_sensitive_fields_for_non_admin_user(): def test_query_sites_keeps_full_fields_for_admin_context(): """管理员查询站点时保留完整配置视图。""" - tool = QuerySitesTool(session_id="session-1", user_id="admin") - tool.set_agent_context({"is_admin": True}) site = SimpleNamespace( id=1, name="TestSite", @@ -176,11 +174,14 @@ def test_query_sites_keeps_full_fields_for_admin_context(): downloader="qb", ) - with patch( - "app.agent.tools.impl.query_sites.get_agent_site_port" - ) as site_oper: - site_oper.return_value.async_list = AsyncMock(return_value=[site]) - result = asyncio.run(tool.run()) + repository = SimpleNamespace(async_list=AsyncMock(return_value=[site])) + tool = QuerySitesTool( + session_id="session-1", + user_id="admin", + data=SimpleNamespace(sites=repository), + ) + tool.set_agent_context({"is_admin": True}) + result = asyncio.run(tool.run()) payload = json.loads(result) assert payload[0]["cookie"] == "uid=1; passkey=secret" @@ -361,66 +362,58 @@ def test_query_downloaders_keeps_full_fields_for_admin_context(): def test_channel_agent_admin_user_id_does_not_bypass_user_lookup(): """渠道用户 ID 恰好为 admin 时,不应绕过真实系统用户权限判断。""" + users = SimpleNamespace( + async_get_by_name=AsyncMock(return_value=SimpleNamespace(is_superuser=False)) + ) agent = MoviePilotAgent( session_id="session-1", user_id="admin", channel=NotificationChannel.Telegram.value, source="telegram-main", username="normal-user", + data=SimpleNamespace(users=users), ) - - with patch("app.agent.orchestrator.get_agent_user_port") as user_oper: - user_oper.return_value.async_get_by_name.return_value = SimpleNamespace( - is_superuser=False - ) - context = asyncio.run( - agent._build_tool_context(should_dispatch_reply=True) - ) + context = asyncio.run(agent._build_tool_context(should_dispatch_reply=True)) assert context["is_admin"] is False def test_channel_agent_rejects_local_admin_username_without_trusted_principal(): """外部显示名与本地管理员同名时,不得获得 Agent 管理员权限。""" + users = SimpleNamespace(async_get_by_name=AsyncMock()) agent = MoviePilotAgent( session_id="session-1", user_id="10002", channel=NotificationChannel.Telegram.value, source="telegram-main", username="admin", + data=SimpleNamespace(users=users), ) agent.is_channel_admin = False - with patch("app.agent.orchestrator.get_agent_user_port") as user_oper: - user_oper.return_value.async_get_by_name = AsyncMock( - return_value=SimpleNamespace(is_superuser=True) - ) - context = asyncio.run( - agent._build_tool_context(should_dispatch_reply=True) - ) + context = asyncio.run(agent._build_tool_context(should_dispatch_reply=True)) assert context["is_admin"] is False - user_oper.return_value.async_get_by_name.assert_not_awaited() + users.async_get_by_name.assert_not_awaited() def test_channel_agent_accepts_trusted_admin_principal_without_local_user(): """宿主确认的渠道管理员应直接获得 Agent 管理员权限。""" + users = SimpleNamespace(async_get_by_name=AsyncMock()) agent = MoviePilotAgent( session_id="session-1", user_id="10001", channel=NotificationChannel.Telegram.value, source="telegram-main", username="renamed-user", + data=SimpleNamespace(users=users), ) agent.is_channel_admin = True - with patch("app.agent.orchestrator.get_agent_user_port") as user_oper: - context = asyncio.run( - agent._build_tool_context(should_dispatch_reply=True) - ) + context = asyncio.run(agent._build_tool_context(should_dispatch_reply=True)) assert context["is_admin"] is True - user_oper.return_value.async_get_by_name.assert_not_called() + users.async_get_by_name.assert_not_called() def test_tool_explicit_non_admin_context_does_not_fallback_to_channel_lookup(): diff --git a/tests/test_agent_scheduled_tasks.py b/tests/test_agent_scheduled_tasks.py index 7cbce8e09..e71eb2cdd 100644 --- a/tests/test_agent_scheduled_tasks.py +++ b/tests/test_agent_scheduled_tasks.py @@ -38,13 +38,14 @@ from app.agent.tools.impl.update_agent_task import ( UpdateAgentTaskTool, ) from app.agent.tools.tags import ToolTag -from app.runtime.config import settings from app.db import SessionFactory -from app.db.oper.agenttask import AgentTaskOper +from app.db.adapters.agent import TransactionalAgentTaskRepository from app.db.models.agenttask import AgentTask -from app.schemas import ScheduleInfo -from app.scheduler import Scheduler +from app.db.oper.agenttask import AgentTaskOper +from app.runtime.config import settings from app.runtime.scheduling import TimerUtils +from app.scheduler import Scheduler +from app.schemas import ScheduleInfo class _FakeAgentTaskScheduler: @@ -139,6 +140,7 @@ def _build_agent_task_scheduler(reconcile: bool = False) -> Scheduler: scheduler._active_job_generations = {} scheduler._agent_task_reservations = {} scheduler._agent_task_interruptions_reconciled = False + scheduler._agent_tasks = TransactionalAgentTaskRepository(SessionFactory) if reconcile: scheduler._reconcile_agent_task_interruptions() return scheduler @@ -146,7 +148,14 @@ def _build_agent_task_scheduler(reconcile: bool = False) -> Scheduler: def _build_tool(tool_class, user_id: str): """构造带当前用户消息上下文的 Agent 工具。""" - tool = tool_class(session_id=f"session-{user_id}", user_id=user_id) + tool = tool_class( + session_id=f"session-{user_id}", + user_id=user_id, + data=SimpleNamespace( + tasks=TransactionalAgentTaskRepository(SessionFactory), + chat=SimpleNamespace(get_sync=lambda **_kwargs: None), + ), + ) tool.set_message_attr( channel="Telegram", source="telegram-test", @@ -329,6 +338,7 @@ def test_scheduler_registers_and_removes_agent_task_job() -> None: scheduler._job_generations = {} scheduler._active_job_generations = {} scheduler._agent_task_reservations = {} + scheduler._agent_tasks = TransactionalAgentTaskRepository(SessionFactory) next_run_at = scheduler.update_agent_task_job(task.id) job_id = scheduler._get_agent_task_job_id(task.id) diff --git a/tests/test_agent_search_subscribe.py b/tests/test_agent_search_subscribe.py index 5a922fd53..1123de983 100644 --- a/tests/test_agent_search_subscribe.py +++ b/tests/test_agent_search_subscribe.py @@ -5,7 +5,6 @@ import json from types import SimpleNamespace from unittest.mock import AsyncMock, call -from app.agent.tools.impl import search_subscribe as search_subscribe_module from app.agent.tools.impl.search_subscribe import SearchSubscribeTool from app.application.subscription.contract import SubscriptionPatch @@ -48,7 +47,6 @@ def test_search_subscribe_uses_async_data_port(monkeypatch) -> None: raise AssertionError("async 工具不应调用同步订阅更新") port = _AsyncSubscribePort() - monkeypatch.setattr(search_subscribe_module, "get_agent_subscribe_port", lambda: port) async def _run_blocking(*_args, **_kwargs): await asyncio.sleep(0) @@ -56,7 +54,11 @@ def test_search_subscribe_uses_async_data_port(monkeypatch) -> None: monkeypatch.setattr(SearchSubscribeTool, "run_blocking", _run_blocking) result = asyncio.run( - SearchSubscribeTool(session_id="test", user_id="1").run( + SearchSubscribeTool( + session_id="test", + user_id="1", + data=SimpleNamespace(subscriptions=port), + ).run( subscribe_id=record.id, filter_groups=["default"], ) @@ -80,12 +82,15 @@ def test_search_subscribe_rejects_paused_subscription_without_search(monkeypatch async_update = AsyncMock() port = _AsyncSubscribePort() - monkeypatch.setattr(search_subscribe_module, "get_agent_subscribe_port", lambda: port) run_blocking = AsyncMock() monkeypatch.setattr(SearchSubscribeTool, "run_blocking", run_blocking) result = asyncio.run( - SearchSubscribeTool(session_id="test", user_id="1").run( + SearchSubscribeTool( + session_id="test", + user_id="1", + data=SimpleNamespace(subscriptions=port), + ).run( subscribe_id=record.id, ) ) diff --git a/tests/test_agent_task_runs.py b/tests/test_agent_task_runs.py index 388c19312..985215ac0 100644 --- a/tests/test_agent_task_runs.py +++ b/tests/test_agent_task_runs.py @@ -1,6 +1,7 @@ import json from concurrent.futures import ThreadPoolExecutor from threading import Event, Thread, current_thread +from types import SimpleNamespace from uuid import uuid4 import pytest @@ -9,14 +10,14 @@ from sqlalchemy.exc import IntegrityError from app.agent.orchestrator import AgentManager from app.agent.tools.impl.query_agent_tasks import QueryAgentTasksTool -from app.db.engine import get_engine from app.db import base as db_base -from app.db.oper.agenttask import AgentTaskOper +from app.db.adapters.agent import TransactionalAgentTaskRepository +from app.db.engine import get_engine from app.db.models.agenttask import AgentTask from app.db.models.agenttaskrun import AgentTaskRun +from app.db.oper.agenttask import AgentTaskOper from app.db.session import SessionFactory - Engine = get_engine() @@ -40,7 +41,13 @@ def _add_task(prefix: str, *, trigger_type: str = "cron") -> AgentTask: def _build_query_tool(user_id: str) -> QueryAgentTasksTool: """构造绑定当前 owner 的任务查询工具。""" - tool = QueryAgentTasksTool(session_id=f"session-{user_id}", user_id=user_id) + tool = QueryAgentTasksTool( + session_id=f"session-{user_id}", + user_id=user_id, + data=SimpleNamespace( + tasks=TransactionalAgentTaskRepository(SessionFactory) + ), + ) tool._message_context = {"username": "admin"} return tool diff --git a/tests/test_architecture_dependencies.py b/tests/test_architecture_dependencies.py index 3e56fc477..7898a7229 100644 --- a/tests/test_architecture_dependencies.py +++ b/tests/test_architecture_dependencies.py @@ -253,6 +253,21 @@ def _compat_symbol_references(tree: ast.AST) -> set[tuple[int, str]]: return references +def _class_annotations(path: Path, class_name: str) -> dict[str, str]: + """返回指定类的源码级字段注解。""" + tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) + class_node = next( + node + for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == class_name + ) + return { + node.target.id: ast.unparse(node.annotation) + for node in class_node.body + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) + } + + def test_legacy_roots_contain_no_python_sources(): """旧目录只能作为运行时虚拟包存在,仓库中不得重新出现源码。""" leftovers = sorted( @@ -374,30 +389,6 @@ def test_workflow_execution_chain_uses_single_application_owned_port(): "reset": "bool", } - data_path = APP_ROOT / "application" / "chain" / "data.py" - data_tree = ast.parse( - data_path.read_text(encoding="utf-8"), - filename=str(data_path), - ) - data_class = next( - node - for node in data_tree.body - if isinstance(node, ast.ClassDef) and node.name == "ChainDataPorts" - ) - data_fields = { - node.target.id - for node in data_class.body - if isinstance(node, ast.AnnAssign) - and isinstance(node.target, ast.Name) - } - data_functions = { - node.name - for node in data_tree.body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - } - assert "workflow" not in data_fields - assert "get_chain_workflow_port" not in data_functions - chain_source = (APP_ROOT / "chain" / "workflow.py").read_text(encoding="utf-8") startup_source = ( APP_ROOT / "startup" / "initializers" / "modules.py" @@ -408,70 +399,30 @@ def test_workflow_execution_chain_uses_single_application_owned_port(): assert "workflow=lambda:" not in startup_source -def test_chain_registry_has_no_dynamic_proxies_or_dead_context_injection(): - """Chain registry 不得恢复零消费者动态代理或失效 data_ports 伪注入。""" - data_path = APP_ROOT / "application" / "chain" / "data.py" - data_tree = ast.parse( - data_path.read_text(encoding="utf-8"), - filename=str(data_path), +def test_chain_runtime_context_owns_typed_repository_instances(): + """Chain 数据能力必须作为明确类型的实例字段进入运行时上下文。""" + annotations = _class_annotations( + APP_ROOT / "application" / "chain" / "context.py", + "ChainRuntimeContext", ) - proxy_classes = { - node.name - for node in data_tree.body - if isinstance(node, ast.ClassDef) - and (node.name.endswith("PortProxy") or node.name == "_PortProxyMeta") + expected = { + "site_repository": "SiteRepository", + "subscription_repository": "SubscriptionRepository", + "download_history_repository": "DownloadHistoryRepository", + "transfer_history_repository": "TransferHistoryRepository", + "transfer_admission_repository": "TransferAdmissionRepository", + "transfer_execution_repository": "TransferExecutionRepository", + "media_server_repository": "MediaServerRepository", + "download_failure_repository": "DownloadFailureRepository", + "user_repository": "ChainUserRepository", } - dynamic_getters = { - node.name - for node in ast.walk(data_tree) - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == "__getattr__" - } - assert proxy_classes == set() - assert dynamic_getters == set() + assert {name: annotations[name] for name in expected} == expected - context_source = ( - APP_ROOT / "application" / "chain" / "context.py" - ).read_text(encoding="utf-8") chain_base_source = (APP_ROOT / "chain" / "__init__.py").read_text( - encoding="utf-8" + encoding="utf-8-sig" ) - startup_source = ( - APP_ROOT / "startup" / "initializers" / "modules.py" - ).read_text(encoding="utf-8") - assert "data_ports" not in context_source - assert "self.data_ports" not in chain_base_source - assert "data_ports=" not in startup_source - - -def test_download_failure_and_mediaserver_ports_are_typed_and_detached(): - """下载失败与媒体库缓存端口不得退回 raw Oper、Any 或 ORM 投影。""" - data_path = APP_ROOT / "application" / "chain" / "data.py" - data_tree = ast.parse( - data_path.read_text(encoding="utf-8"), - filename=str(data_path), - ) - data_class = next( - node - for node in data_tree.body - if isinstance(node, ast.ClassDef) and node.name == "ChainDataPorts" - ) - annotations = { - node.target.id: ast.unparse(node.annotation) - for node in data_class.body - if isinstance(node, ast.AnnAssign) - and isinstance(node.target, ast.Name) - } - returns = { - node.name: ast.unparse(node.returns) - for node in data_tree.body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.returns is not None - } - assert annotations["download_failure"] == "DownloadFailureRepositoryFactory" - assert annotations["media_server"] == "MediaServerRepositoryFactory" - assert returns["get_chain_download_failure_port"] == "DownloadFailureRepository" - assert returns["get_chain_media_server_port"] == "MediaServerRepository" + for field_name in expected: + assert f"self.{field_name} = context.{field_name}" in chain_base_source download_source = (APP_ROOT / "chain" / "download.py").read_text( encoding="utf-8" @@ -491,6 +442,73 @@ def test_download_failure_and_mediaserver_ports_are_typed_and_detached(): assert "TransactionalMediaServerRepository(SessionFactory)" in startup_source +def test_startup_composes_typed_chain_and_agent_data_contexts(): + """组合根必须一次性构造 Chain 与 Agent 的类型化数据上下文。""" + context_specs = { + "ChainRuntimeContext": ( + APP_ROOT / "application" / "chain" / "context.py", + { + "site_repository", + "subscription_repository", + "download_history_repository", + "transfer_history_repository", + "transfer_admission_repository", + "transfer_execution_repository", + "media_server_repository", + "download_failure_repository", + "user_repository", + }, + ), + "AgentDataContext": ( + APP_ROOT / "application" / "agent.py", + { + "chat", + "chat_persistence", + "tasks", + "users", + "sites", + "subscriptions", + "subscription_history", + "transfer_history", + "transfer_execution", + "download_history", + "plugin_data", + }, + ), + } + startup_path = APP_ROOT / "startup" / "initializers" / "modules.py" + startup_tree = ast.parse( + startup_path.read_text(encoding="utf-8-sig"), + filename=str(startup_path), + ) + + for class_name, (context_path, expected_fields) in context_specs.items(): + annotations = _class_annotations(context_path, class_name) + assert expected_fields <= annotations.keys() + assert all( + "Any" not in annotations[field_name] + and "Oper" not in annotations[field_name] + and "Callable" not in annotations[field_name] + for field_name in expected_fields + ) + + constructors = [ + node + for node in ast.walk(startup_tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == class_name + ] + assert len(constructors) == 1 + values = { + keyword.arg: keyword.value + for keyword in constructors[0].keywords + if keyword.arg is not None + } + assert expected_fields <= values.keys() + assert all(not isinstance(values[field_name], ast.Lambda) for field_name in expected_fields) + + def test_download_history_ports_are_typed_detached_and_canonically_injected(): """下载历史宿主调用面只能消费冻结快照和显式事务 adapter。""" history_path = APP_ROOT / "application" / "history.py" @@ -532,38 +550,16 @@ def test_download_history_ports_are_typed_detached_and_canonically_injected(): assert annotations assert all("Any" not in annotation for annotation in annotations) - data_path = APP_ROOT / "application" / "chain" / "data.py" - data_tree = ast.parse(data_path.read_text(encoding="utf-8"), filename=str(data_path)) - data_class = next( - node - for node in data_tree.body - if isinstance(node, ast.ClassDef) and node.name == "ChainDataPorts" + chain_annotations = _class_annotations( + APP_ROOT / "application" / "chain" / "context.py", + "ChainRuntimeContext", ) - annotations = { - node.target.id: ast.unparse(node.annotation) - for node in data_class.body - if isinstance(node, ast.AnnAssign) - and isinstance(node.target, ast.Name) - } - returns = { - node.name: ast.unparse(node.returns) - for node in ast.walk(data_tree) - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.returns is not None - } - agent_tree = ast.parse( - (APP_ROOT / "application" / "agentdata.py").read_text(encoding="utf-8") + agent_annotations = _class_annotations( + APP_ROOT / "application" / "agent.py", + "AgentDataContext", ) - agent_return = next( - ast.unparse(node.returns) - for node in ast.walk(agent_tree) - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == "get_agent_download_history_port" - and node.returns is not None - ) - assert annotations["download_history"] == "DownloadHistoryRepositoryFactory" - assert returns["get_chain_download_history_port"] == "DownloadHistoryRepository" - assert agent_return == "DownloadHistoryRepository" + assert chain_annotations["download_history_repository"] == "DownloadHistoryRepository" + assert agent_annotations["download_history"] == "DownloadHistoryRepository" consumer_paths = ( APP_ROOT / "chain" / "_transfer.py", @@ -672,13 +668,14 @@ def test_canonical_workflow_oper_has_no_legacy_writer_or_duplicate_exports(): def test_agent_data_ports_do_not_duplicate_workflow_query_capability(): - """Agent 数据聚合器不得重新暴露无类型工作流读取入口。""" - source = (APP_ROOT / "application" / "agentdata.py").read_text( - encoding="utf-8" + """Agent 显式数据上下文不得重复拥有工作流查询能力。""" + annotations = _class_annotations( + APP_ROOT / "application" / "agent.py", + "AgentDataContext", ) - assert "WorkflowPort" not in source - assert "get_agent_workflow_port" not in source + assert "workflow" not in annotations + assert "workflow_query" not in annotations def test_host_uses_canonical_workflow_manager_name(): @@ -831,80 +828,18 @@ def test_host_code_uses_explicit_runtime_facade_getters(): assert violations == [] -def test_workflow_domain_uses_explicit_chain_data_port_getters(): - """工作流域不得重新使用迁移期 PortProxy 冒充数据库 Oper。""" - paths = [APP_ROOT / "chain" / "workflow.py"] - paths.extend((APP_ROOT / "workflow").rglob("*.py")) - violations: list[str] = [] - for path in paths: - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - for node in ast.walk(tree): - if not isinstance(node, ast.ImportFrom): - continue - if node.module != "app.application.chain.data": - continue - for alias in node.names: - if alias.name.endswith("PortProxy"): - violations.append( - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}:{alias.name}" - ) - - assert violations == [] - - -def test_user_and_messaging_chains_use_explicit_data_port_getters(): - """用户、交互和消息链不得把迁移期 UserPortProxy 伪装成 UserOper。""" - paths = [ - APP_ROOT / "chain" / "user.py", - APP_ROOT / "chain" / "interaction.py", - APP_ROOT / "chain" / "_messaging.py", - ] - violations: list[str] = [] - for path in paths: - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - for node in ast.walk(tree): - if not isinstance(node, ast.ImportFrom): - continue - if node.module != "app.application.chain.data": - continue - for alias in node.names: - if alias.name == "UserPortProxy": - violations.append( - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}" - ) - - assert violations == [] - - def test_user_chain_and_agent_ports_are_typed_and_orm_free(): """用户 Chain、Agent 与宿主模块只能消费 Application 用户端口。""" - chain_data = ast.parse( - (APP_ROOT / "application" / "chain" / "data.py").read_text( - encoding="utf-8-sig" - ) + chain_annotations = _class_annotations( + APP_ROOT / "application" / "chain" / "context.py", + "ChainRuntimeContext", ) - agent_data = ast.parse( - (APP_ROOT / "application" / "agentdata.py").read_text( - encoding="utf-8-sig" - ) - ) - - def return_annotation(tree: ast.AST, function_name: str) -> str | None: - """返回指定函数的源码级返回注解。""" - function = next( - node - for node in ast.walk(tree) - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == function_name - ) - return ast.unparse(function.returns) if function.returns else None - - assert return_annotation(chain_data, "get_chain_user_port") == "ChainUserRepository" - assert return_annotation(agent_data, "get_agent_user_port") == "ChainUserRepository" - assert not any( - isinstance(node, ast.ClassDef) and node.name == "UserPort" - for node in ast.walk(agent_data) + agent_annotations = _class_annotations( + APP_ROOT / "application" / "agent.py", + "AgentDataContext", ) + assert chain_annotations["user_repository"] == "ChainUserRepository" + assert agent_annotations["users"] == "ChainUserRepository" production_paths = [ APP_ROOT / "chain" / "user.py", @@ -937,122 +872,6 @@ def test_startup_injects_user_adapter_instead_of_raw_oper(): assert "user=lambda: UserOper()" not in source -def test_music_chain_uses_explicit_subscribe_data_port_getter(): - """音乐订阅链不得把 SubscribePortProxy 伪装成 SubscribeOper。""" - path = APP_ROOT / "chain" / "_music.py" - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - violations = [ - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}" - for node in ast.walk(tree) - if isinstance(node, ast.ImportFrom) - and node.module == "app.application.chain.data" - and any(alias.name == "SubscribePortProxy" for alias in node.names) - ] - - assert violations == [] - - -def test_site_chains_use_explicit_site_data_port_getter(): - """站点与种子链不得把 SitePortProxy 伪装成 SiteOper。""" - paths = [APP_ROOT / "chain" / "site.py", APP_ROOT / "chain" / "torrents.py"] - violations: list[str] = [] - for path in paths: - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - for node in ast.walk(tree): - if not isinstance(node, ast.ImportFrom): - continue - if node.module != "app.application.chain.data": - continue - if any(alias.name == "SitePortProxy" for alias in node.names): - violations.append( - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}" - ) - - assert violations == [] - - -def test_mediaserver_chain_uses_explicit_data_port_getter(): - """媒体服务器链不得把 MediaServerPortProxy 伪装成 MediaServerOper。""" - path = APP_ROOT / "chain" / "mediaserver.py" - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - violations = [ - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}" - for node in ast.walk(tree) - if isinstance(node, ast.ImportFrom) - and node.module == "app.application.chain.data" - and any(alias.name == "MediaServerPortProxy" for alias in node.names) - ] - - assert violations == [] - - -def test_download_chain_uses_explicit_data_port_getters(): - """下载链不得把三个迁移期 PortProxy 伪装成数据库 Oper。""" - path = APP_ROOT / "chain" / "download.py" - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - forbidden = { - "DownloadFailurePortProxy", - "DownloadHistoryPortProxy", - "MediaServerPortProxy", - } - violations = [ - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}:{alias.name}" - for node in ast.walk(tree) - if isinstance(node, ast.ImportFrom) - and node.module == "app.application.chain.data" - for alias in node.names - if alias.name in forbidden - ] - - assert violations == [] - - -def test_subscribe_chain_uses_explicit_data_port_getters(): - """订阅链不得把三个迁移期 PortProxy 伪装成数据库 Oper。""" - path = APP_ROOT / "chain" / "subscribe.py" - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - forbidden = { - "DownloadHistoryPortProxy", - "SitePortProxy", - "SubscribePortProxy", - } - violations = [ - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}:{alias.name}" - for node in ast.walk(tree) - if isinstance(node, ast.ImportFrom) - and node.module == "app.application.chain.data" - for alias in node.names - if alias.name in forbidden - ] - - assert violations == [] - - -def test_transfer_chains_use_explicit_data_port_getters(): - """整理主链与 mixin 不得把迁移期 PortProxy 伪装成数据库 Oper。""" - paths = [APP_ROOT / "chain" / "transfer.py", APP_ROOT / "chain" / "_transfer.py"] - forbidden = { - "DownloadHistoryPortProxy", - "TransferHistoryPortProxy", - "TransferPendingPortProxy", - } - violations: list[str] = [] - for path in paths: - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - for node in ast.walk(tree): - if not isinstance(node, ast.ImportFrom): - continue - if node.module != "app.application.chain.data": - continue - for alias in node.names: - if alias.name in forbidden: - violations.append( - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}:{alias.name}" - ) - - assert violations == [] - - def test_transfer_pending_oper_import_is_confined_to_database_boundary(): """宿主仅允许事务适配器和兼容导出直接导入整理待处理 Oper。""" allowed_paths = { @@ -1102,77 +921,35 @@ def test_startup_injects_transactional_transfer_admission_repository(): ) for node in ast.walk(tree) ) - transfer_pending_factories = [ - keyword.value + chain_context_calls = [ + node for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) - and node.func.id == "configure_chain_data_ports" - for keyword in node.keywords - if keyword.arg == "transfer_pending" + and node.func.id == "ChainRuntimeContext" ] assert imports_repository is True - assert len(transfer_pending_factories) == 1 - assert any( - isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "TransactionalTransferAdmissionRepository" - for node in ast.walk(transfer_pending_factories[0]) + assert len(chain_context_calls) == 1 + keywords = { + keyword.arg: keyword.value + for keyword in chain_context_calls[0].keywords + if keyword.arg is not None + } + admission = keywords["transfer_admission_repository"] + assert isinstance(admission, ast.Call) + assert isinstance(admission.func, ast.Name) + assert admission.func.id == "TransactionalTransferAdmissionRepository" + + +def test_transfer_admission_chain_context_field_is_typed(): + """整理准入仓储必须以明确 Protocol 注入 Chain 上下文。""" + annotations = _class_annotations( + APP_ROOT / "application" / "chain" / "context.py", + "ChainRuntimeContext", ) - -def test_transfer_pending_chain_port_is_typed_without_legacy_proxy(): - """整理准入端口必须返回明确 Protocol,且旧 Proxy 不得重新出现。""" - path = APP_ROOT / "application" / "chain" / "data.py" - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - class_names = { - node.name - for node in tree.body - if isinstance(node, ast.ClassDef) - } - getters = [ - node - for node in tree.body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == "get_chain_transfer_pending_port" - ] - - assert "TransferPendingPortProxy" not in class_names - assert len(getters) == 1 - assert getters[0].returns is not None - assert ast.unparse(getters[0].returns) == "TransferAdmissionRepository" - - -def test_agent_consumers_use_explicit_data_port_getters(): - """Agent 生产模块不得把兼容数据端口代理重新伪装成数据库 Oper。""" - forbidden = { - "AgentChatPort", - "AgentTaskPort", - "DownloadHistoryPort", - "PluginDataPort", - "SitePort", - "SubscribeHistoryPort", - "SubscribePort", - "TransferHistoryPort", - "UserPort", - "WorkflowPort", - } - violations: list[str] = [] - for path in (APP_ROOT / "agent").rglob("*.py"): - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - for node in ast.walk(tree): - if not isinstance(node, ast.ImportFrom): - continue - if node.module != "app.application.agentdata": - continue - for alias in node.names: - if alias.name in forbidden: - violations.append( - f"{path.relative_to(PROJECT_ROOT).as_posix()}:{node.lineno}:{alias.name}" - ) - - assert violations == [] + assert annotations["transfer_admission_repository"] == "TransferAdmissionRepository" def test_scheduler_does_not_depend_on_database_implementation(): @@ -1185,20 +962,6 @@ def test_scheduler_does_not_depend_on_database_implementation(): } == set() -def test_agent_task_async_execution_uses_application_service(): - """AgentTask async 执行不得经动态数据端口隐藏同步 Oper 调用。""" - path = APP_ROOT / "agent" / "orchestrator.py" - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - violations = [ - node.lineno - for node in ast.walk(tree) - if isinstance(node, ast.ImportFrom) - and node.module == "app.application.agentdata" - and any(alias.name == "get_agent_task_port" for alias in node.names) - ] - assert violations == [] - - def test_monitor_dispatcher_uses_explicit_history_port_getter(): """监控分发器不得把兼容 TransferHistoryPort 伪装成数据库 Oper。""" path = APP_ROOT / "monitor" / "dispatcher.py" diff --git a/tests/test_bluray.py b/tests/test_bluray.py index 0c18b647c..4c71fff46 100644 --- a/tests/test_bluray.py +++ b/tests/test_bluray.py @@ -6,13 +6,13 @@ from unittest import TestCase from unittest.mock import patch from app import schemas +from app.application.history import TransferHistorySnapshot from app.chain.scraping import ScrapingChain from app.chain.storage import StorageChain from app.chain.transfer import TransferChain from app.domain.context import MediaInfo -from app.runtime.events import Event from app.domain.metainfo import MetaInfoPath -from app.db.models.transferhistory import TransferHistory +from app.runtime.events import Event from app.runtime.log import logger from app.schemas.types import EventType from tests.cases.files import bluray_files @@ -175,8 +175,7 @@ class BluRayTest(TestCase): __test_scrape_metadata("/FOLDER", excepted_nfo_count=2) @patch("app.chain.scraping.ScrapingChain.metadata_img", return_value=None) # 避免获取图片 - @patch("app.chain.ChainBase.__init__", return_value=None) # 避免不必要的模块初始化 - @patch("app.db.oper.transferhistory.TransferHistoryOper.get_by_src") + @patch("app.chain._transfer.resolve_history") @patch("app.chain.storage.StorageChain.list_files") @patch("app.chain.storage.StorageChain.get_parent_item") @patch("app.chain.storage.StorageChain.get_file_item") @@ -185,7 +184,7 @@ class BluRayTest(TestCase): mock_get_file_item, mock_get_parent_item, mock_list_files, - mock_get_by_src, + mock_resolve_history, *_, ): def get_file_item(storage: str, path: Path): @@ -208,16 +207,18 @@ class BluRayTest(TestCase): else: return fileitem.children - def get_by_src(src: str, storage: Optional[str] = None): + def resolve_history( + src: str, + storage: Optional[str] = None, + transfer_history_oper=None, + ): self.__history.append(src) - result = TransferHistory() - result.status = True - return result + return TransferHistorySnapshot(id=1, status=True) mock_get_file_item.side_effect = get_file_item mock_get_parent_item.side_effect = get_parent_item mock_list_files.side_effect = list_files - mock_get_by_src.side_effect = get_by_src + mock_resolve_history.side_effect = resolve_history self._test_do_transfer() diff --git a/tests/test_chain_rate_limit.py b/tests/test_chain_rate_limit.py index 8f2e49cbd..511d03723 100644 --- a/tests/test_chain_rate_limit.py +++ b/tests/test_chain_rate_limit.py @@ -1,3 +1,7 @@ +"""Chain 本地限流行为测试。""" + +# ruff: noqa: E402 - 可选下载器模块必须在导入 Chain 前完成隔离。 + import asyncio import sys import unittest @@ -9,10 +13,10 @@ setattr(sys.modules["qbittorrentapi"], "TorrentFilesList", list) sys.modules.setdefault("transmission_rpc", ModuleType("transmission_rpc")) setattr(sys.modules["transmission_rpc"], "File", object) -from app.chain import ChainBase from app.application.chain.context import ChainRuntimeContext +from app.chain import ChainBase from app.runtime.extensions.module.dispatcher import ModuleInvocationDispatcher -from app.schemas import RateLimitExceededException +from app.schemas.exception import RateLimitExceededException class _LimitedModule: @@ -68,6 +72,15 @@ class ChainRateLimitTest(unittest.TestCase): async_file_cache=Mock(), message_queue_factory=lambda _callback: Mock(), module_dispatcher_factory=ModuleInvocationDispatcher, + site_repository=Mock(), + subscription_repository=Mock(), + download_history_repository=Mock(), + transfer_history_repository=Mock(), + transfer_admission_repository=Mock(), + transfer_execution_repository=Mock(), + media_server_repository=Mock(), + download_failure_repository=Mock(), + user_repository=Mock(), ) ) return chain diff --git a/tests/test_chain_runtime_context.py b/tests/test_chain_runtime_context.py index 6d7cc410c..e6e7918c9 100644 --- a/tests/test_chain_runtime_context.py +++ b/tests/test_chain_runtime_context.py @@ -5,7 +5,6 @@ from unittest.mock import Mock import pytest from app.application.chain import context as chain_context -from app.application.chain import data as chain_data from app.application.chain.context import ChainRuntimeContext from app.application.configuration import ChainRuntimeConfig from app.chain import ChainBase @@ -24,6 +23,15 @@ def _context() -> ChainRuntimeContext: async_file_cache=Mock(), message_queue_factory=Mock(return_value=Mock()), module_dispatcher_factory=ModuleInvocationDispatcher, + site_repository=Mock(), + subscription_repository=Mock(), + download_history_repository=Mock(), + transfer_history_repository=Mock(), + transfer_admission_repository=Mock(), + transfer_execution_repository=Mock(), + media_server_repository=Mock(), + download_failure_repository=Mock(), + user_repository=Mock(), configuration=ChainRuntimeConfig(media_extensions=(".mkv",)), durable_event_writer=Mock(), ) @@ -68,28 +76,13 @@ def test_chain_runtime_context_rejects_unconfigured_provider(monkeypatch) -> Non chain_context.get_chain_runtime_context() -def test_chain_data_registry_rejects_unconfigured_and_returns_factories( - monkeypatch, -) -> None: - """数据 registry 未配置时拒绝访问,配置后按字段返回工厂实例。""" - monkeypatch.setattr(chain_data, "_ports", None) +def test_chain_keeps_explicit_typed_repositories() -> None: + """Chain 实例必须直接保存组合根注入的数据端口,不再查找全局注册表。""" + context = _context() - with pytest.raises(RuntimeError, match="Chain 数据端口尚未配置"): - chain_data.get_chain_data_ports() + chain = ChainBase(context) - media_server = Mock() - user = Mock() - chain_data.configure_chain_data_ports( - site=Mock, - subscribe=Mock, - download_history=Mock, - transfer_history=Mock, - transfer_pending=Mock, - transfer_execution=Mock, - media_server=lambda: media_server, - download_failure=Mock, - user=lambda: user, - ) - - assert chain_data.get_chain_media_server_port() is media_server - assert chain_data.get_chain_user_port() is user + assert chain.site_repository is context.site_repository + assert chain.subscription_repository is context.subscription_repository + assert chain.transfer_execution_repository is context.transfer_execution_repository + assert chain.user_repository is context.user_repository diff --git a/tests/test_data_locator_architecture.py b/tests/test_data_locator_architecture.py new file mode 100644 index 000000000..e68e98666 --- /dev/null +++ b/tests/test_data_locator_architecture.py @@ -0,0 +1,144 @@ +"""Chain 与 Agent 数据依赖显式注入的架构门禁。""" + +import ast +from pathlib import Path + +PROJECT_ROOT = Path(__file__).parents[1] +APP_ROOT = PROJECT_ROOT / "app" +RETIRED_MODULES = { + "app.application.agentdata", + "app.application.chain.data", +} +RETIRED_GETTERS = { + "get_agent_chat_port", + "get_agent_download_history_port", + "get_agent_plugin_data_port", + "get_agent_site_port", + "get_agent_subscribe_history_port", + "get_agent_subscribe_port", + "get_agent_task_port", + "get_agent_transfer_history_port", + "get_agent_user_port", + "get_chain_download_failure_port", + "get_chain_download_history_port", + "get_chain_media_server_port", + "get_chain_site_port", + "get_chain_subscribe_port", + "get_chain_transfer_execution_port", + "get_chain_transfer_history_port", + "get_chain_transfer_pending_port", + "get_chain_user_port", +} + + +def _canonical_paths() -> list[Path]: + """返回排除插件副本与兼容实现后的宿主 Python 文件。""" + return [ + path + for path in sorted(APP_ROOT.rglob("*.py")) + if "plugins" not in path.relative_to(APP_ROOT).parts + and path.relative_to(APP_ROOT).parts[:2] != ("runtime", "compat") + and path.relative_to(APP_ROOT).parts[:2] != ("sdk", "_legacy") + ] + + +def _class_fields(path: Path, class_name: str) -> dict[str, str]: + """读取指定数据上下文的源码级字段注解。""" + tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) + class_node = next( + node + for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == class_name + ) + return { + node.target.id: ast.unparse(node.annotation) + for node in class_node.body + if isinstance(node, ast.AnnAssign) + and isinstance(node.target, ast.Name) + } + + +def test_retired_data_locator_modules_and_getters_cannot_return() -> None: + """Canonical 宿主不得复活全局数据注册表、导入或动态 getter 调用。""" + assert not (APP_ROOT / "application" / "agentdata.py").exists() + assert not (APP_ROOT / "application" / "chain" / "data.py").exists() + + violations: list[str] = [] + for path in _canonical_paths(): + tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) + relative = path.relative_to(PROJECT_ROOT).as_posix() + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module in RETIRED_MODULES: + violations.append(f"{relative}:{node.lineno}:import:{node.module}") + elif isinstance(node, ast.Import): + for alias in node.names: + if alias.name in RETIRED_MODULES: + violations.append(f"{relative}:{node.lineno}:import:{alias.name}") + elif ( + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name in RETIRED_GETTERS + ): + violations.append(f"{relative}:{node.lineno}:definition:{node.name}") + elif ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id in RETIRED_GETTERS + ): + violations.append(f"{relative}:{node.lineno}:call:{node.func.id}") + + assert violations == [] + + +def test_internal_data_locators_do_not_gain_sdk_or_compat_abi() -> None: + """被删除的宿主注册表没有插件合同,不得转存到 SDK 或 Compat。""" + compatibility_source = ( + APP_ROOT / "runtime" / "compat" / "manifest.py" + ).read_text(encoding="utf-8-sig") + sdk_sources = "\n".join( + path.read_text(encoding="utf-8-sig") + for path in sorted((APP_ROOT / "sdk").rglob("*.py")) + ) + + assert all(module not in compatibility_source for module in RETIRED_MODULES) + assert all(name not in sdk_sources for name in RETIRED_GETTERS) + + +def test_injected_data_contexts_use_owned_typed_ports() -> None: + """Chain 与 Agent 的持久化字段必须由明确 Port 注解拥有,不得用 Any 遮蔽。""" + chain_fields = _class_fields( + APP_ROOT / "application" / "chain" / "context.py", + "ChainRuntimeContext", + ) + agent_fields = _class_fields( + APP_ROOT / "application" / "agent.py", + "AgentDataContext", + ) + expected_chain_fields = { + "site_repository", + "subscription_repository", + "download_history_repository", + "transfer_history_repository", + "transfer_admission_repository", + "transfer_execution_repository", + "media_server_repository", + "download_failure_repository", + "user_repository", + } + expected_agent_fields = { + "chat", + "chat_persistence", + "tasks", + "users", + "sites", + "subscriptions", + "subscription_history", + "transfer_history", + "transfer_execution", + "download_history", + "plugin_data", + } + + assert expected_chain_fields <= chain_fields.keys() + assert expected_agent_fields <= agent_fields.keys() + assert all("Any" not in chain_fields[name] for name in expected_chain_fields) + assert all("Any" not in agent_fields[name] for name in expected_agent_fields) diff --git a/tests/test_delete_transfer_history_tool.py b/tests/test_delete_transfer_history_tool.py index 015433fb1..0b6aa0164 100644 --- a/tests/test_delete_transfer_history_tool.py +++ b/tests/test_delete_transfer_history_tool.py @@ -2,8 +2,20 @@ import asyncio import threading from types import SimpleNamespace -from app.agent.tools.impl.delete_transfer_history import DeleteTransferHistoryTool from app.agent.prompt.transfer_redo import build_manual_redo_template_context +from app.agent.tools.impl.delete_transfer_history import DeleteTransferHistoryTool + + +def _tool(history_repository, execution_repository=None): + """构造显式注入整理仓储的工具。""" + return DeleteTransferHistoryTool( + session_id="redo-session", + user_id="10001", + data=SimpleNamespace( + transfer_history=history_repository, + transfer_execution=execution_repository or SimpleNamespace(), + ), + ) def test_delete_transfer_history_tool_removes_old_dest_file_before_history(monkeypatch): @@ -40,16 +52,12 @@ def test_delete_transfer_history_tool_removes_old_dest_file_before_history(monke calls.append(("delete_dest", fileitem.path)) return True - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - FakeTransferHistoryOper, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history.StorageChain", FakeStorageChain, ) - tool = DeleteTransferHistoryTool(session_id="redo-session", user_id="10001") + tool = _tool(FakeTransferHistoryOper()) result = asyncio.run(tool.run(history_id=7)) assert "已删除整理历史记录" in result @@ -95,16 +103,12 @@ def test_delete_transfer_history_tool_keeps_history_when_old_dest_delete_fails(m calls.append(("delete_dest", fileitem.path)) return False - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - FakeTransferHistoryOper, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history.StorageChain", FakeStorageChain, ) - tool = DeleteTransferHistoryTool(session_id="redo-session", user_id="10001") + tool = _tool(FakeTransferHistoryOper()) result = asyncio.run(tool.run(history_id=8)) assert "旧媒体库文件删除失败" in result @@ -149,16 +153,12 @@ def test_delete_transfer_history_tool_deletes_history_when_old_dest_is_missing(m calls.append(("delete_dest", fileitem.path)) return False - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - FakeTransferHistoryOper, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history.StorageChain", FakeStorageChain, ) - tool = DeleteTransferHistoryTool(session_id="redo-session", user_id="10001") + tool = _tool(FakeTransferHistoryOper()) result = asyncio.run(tool.run(history_id=13)) assert "已删除整理历史记录" in result @@ -204,16 +204,12 @@ def test_delete_transfer_history_tool_keeps_successful_move_dest_as_reorganize_s calls.append(("delete_dest", fileitem.path)) return True - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - FakeTransferHistoryOper, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history.StorageChain", FakeStorageChain, ) - tool = DeleteTransferHistoryTool(session_id="redo-session", user_id="10001") + tool = _tool(FakeTransferHistoryOper()) result = asyncio.run(tool.run(history_id=9)) assert "已删除整理历史记录" in result @@ -257,16 +253,12 @@ def test_delete_transfer_history_tool_only_treats_exact_move_as_reorganize_sourc calls.append(("delete_dest", fileitem.path)) return True - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - FakeTransferHistoryOper, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history.StorageChain", FakeStorageChain, ) - tool = DeleteTransferHistoryTool(session_id="redo-session", user_id="10001") + tool = _tool(FakeTransferHistoryOper()) result = asyncio.run(tool.run(history_id=11)) assert "已删除旧媒体库文件" in result @@ -312,20 +304,13 @@ def test_delete_transfer_history_storage_work_runs_outside_event_loop(monkeypatc storage_threads.append(threading.get_ident()) return True - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - FakeTransferHistoryOper, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history.StorageChain", FakeStorageChain, ) result = asyncio.run( - DeleteTransferHistoryTool( - session_id="redo-session", - user_id="10001", - ).run(history_id=15) + _tool(FakeTransferHistoryOper()).run(history_id=15) ) assert "已删除整理历史记录" in result @@ -370,10 +355,6 @@ def test_delete_transfer_history_cancellation_keeps_history_record(monkeypatch): finished.set() return True - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - FakeTransferHistoryOper, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history.StorageChain", FakeStorageChain, @@ -381,10 +362,7 @@ def test_delete_transfer_history_cancellation_keeps_history_record(monkeypatch): async def scenario(): task = asyncio.create_task( - DeleteTransferHistoryTool( - session_id="redo-session", - user_id="10001", - ).run(history_id=16) + _tool(FakeTransferHistoryOper()).run(history_id=16) ) assert await asyncio.to_thread(started.wait, 1) task.cancel() diff --git a/tests/test_download_chain.py b/tests/test_download_chain.py index 34c523cd6..ffa5934d8 100644 --- a/tests/test_download_chain.py +++ b/tests/test_download_chain.py @@ -163,14 +163,10 @@ def test_download_single_submits_download_added_to_background(monkeypatch): lambda _self: _download_dirs(), ) monkeypatch.setattr(download_module, "ThreadHelper", _FakeThreadHelper) - monkeypatch.setattr( - download_module, - "get_chain_download_history_port", - _FakeDownloadHistoryOper, - ) monkeypatch.setattr(download_module, "TorrentHelper", _FakeTorrentHelper) chain = DownloadChain.__new__(DownloadChain) + chain.download_history_repository = _FakeDownloadHistoryOper() chain.download = MagicMock(return_value=("qb", "hash123", "Original", "添加下载成功")) chain.download_added = MagicMock() chain.download_site_subtitles = MagicMock() @@ -289,14 +285,10 @@ def test_download_single_persists_custom_words_snapshot(monkeypatch): lambda _self: _download_dirs(), ) monkeypatch.setattr(download_module, "ThreadHelper", _FakeThreadHelper) - monkeypatch.setattr( - download_module, - "get_chain_download_history_port", - _CapturingDownloadHistoryOper, - ) monkeypatch.setattr(download_module, "TorrentHelper", _FakeTorrentHelper) chain = DownloadChain.__new__(DownloadChain) + chain.download_history_repository = _CapturingDownloadHistoryOper() chain.download = MagicMock(return_value=("qb", "hash123", "Original", "添加下载成功")) chain.download_added = MagicMock() chain.download_site_subtitles = MagicMock() @@ -829,14 +821,10 @@ def test_download_single_records_failure_cooldown_when_downloader_rejects(monkey lambda _self: _download_dirs(), ) monkeypatch.setattr(download_module, "TorrentHelper", _FakeTorrentHelper) - monkeypatch.setattr( - download_module, - "get_chain_download_failure_port", - _CapturingDownloadFailureOper, - ) monkeypatch.setattr(download_module.eventmanager, "send_event", lambda *args, **kwargs: None) chain = DownloadChain.__new__(DownloadChain) + chain.download_failure_repository = _CapturingDownloadFailureOper() chain.eventmanager = MagicMock() chain.eventmanager.send_event.return_value = None error_msg = "添加种子任务失败:无法读取种子文件" @@ -882,20 +870,19 @@ def test_download_single_records_failure_cooldown_when_downloader_rejects(monkey def test_download_failure_query_skips_non_subscribe_sources(monkeypatch): """非订阅下载不得读取失败冷却,避免改变手工下载行为。""" - get_repository = MagicMock(side_effect=AssertionError("unexpected query")) - monkeypatch.setattr( - download_module, - "get_chain_download_failure_port", - get_repository, + query = MagicMock(side_effect=AssertionError("unexpected query")) + repository = SimpleNamespace( + get_active_by_fingerprints=query, ) chain = DownloadChain.__new__(DownloadChain) + chain.download_failure_repository = repository assert chain._active_download_failure_fingerprints( contexts=[_build_tv_context()], source="Manual", ) == {} - get_repository.assert_not_called() + query.assert_not_called() def test_download_failure_query_failure_is_fail_open(monkeypatch): @@ -915,14 +902,10 @@ def test_download_failure_query_failure_is_fail_open(monkeypatch): raise RuntimeError("query failed") error = MagicMock() - monkeypatch.setattr( - download_module, - "get_chain_download_failure_port", - _FailingDownloadFailureRepository, - ) monkeypatch.setattr(download_module.logger, "error", error) chain = DownloadChain.__new__(DownloadChain) + chain.download_failure_repository = _FailingDownloadFailureRepository() assert chain._active_download_failure_fingerprints( contexts=[_build_tv_context()], @@ -943,14 +926,10 @@ def test_download_failure_write_failure_is_fail_open(monkeypatch): raise RuntimeError("write failed") error = MagicMock() - monkeypatch.setattr( - download_module, - "get_chain_download_failure_port", - _FailingDownloadFailureRepository, - ) monkeypatch.setattr(download_module.logger, "error", error) context = _build_tv_context() chain = DownloadChain.__new__(DownloadChain) + chain.download_failure_repository = _FailingDownloadFailureRepository() fingerprint = chain._record_download_failure( context=context, @@ -1058,13 +1037,8 @@ def test_batch_download_skips_failed_subscription_resource_and_tries_next(monkey ) } - monkeypatch.setattr( - download_module, - "get_chain_download_failure_port", - _ActiveDownloadFailureOper, - ) - chain = DownloadChain.__new__(DownloadChain) + chain.download_failure_repository = _ActiveDownloadFailureOper() chain.eventmanager = MagicMock() chain.eventmanager.send_event.return_value = None chain.download_single = MagicMock(return_value="hash") @@ -1309,10 +1283,8 @@ def test_downloading_includes_media_type_and_source_site(monkeypatch): ) chain = DownloadChain.__new__(DownloadChain) monkeypatch.setattr(chain, "list_torrents", lambda **_kwargs: [torrent]) - monkeypatch.setattr( - download_module, - "get_chain_download_history_port", - lambda: SimpleNamespace(get_by_hashes=lambda _hashes: {torrent.hash: history}), + chain.download_history_repository = SimpleNamespace( + get_by_hashes=lambda _hashes: {torrent.hash: history} ) result = chain.downloading(name="qb-main") diff --git a/tests/test_history_ai_retry_gate.py b/tests/test_history_ai_retry_gate.py index c858ca903..dfcc728f9 100644 --- a/tests/test_history_ai_retry_gate.py +++ b/tests/test_history_ai_retry_gate.py @@ -84,15 +84,10 @@ def _retry_result( def _install_retry_command(monkeypatch, results: dict[str, TransferRetryRequestResult]) -> object: - """安装不会接触真实数据库的 execution 端口和命令替身。""" + """构造不会接触真实数据库的 execution 端口并安装命令替身。""" repository = object() _RetryCommand.calls = [] _RetryCommand.results = results - monkeypatch.setattr( - history_endpoint, - "get_chain_transfer_execution_port", - lambda: repository, - ) monkeypatch.setattr(history_endpoint, "TransferExecutionCommand", _RetryCommand) return repository @@ -162,6 +157,7 @@ def test_single_ai_redo_requests_durable_retry_without_agent(monkeypatch) -> Non query=_HistoryQuery([TransferHistory(id=11, transfer_task_id="task-11")]), runtime_config=_runtime(ai_enabled=False), task_registry=object(), + execution_repository=repository, _=object(), ) ) @@ -185,7 +181,7 @@ def test_single_ai_redo_requests_durable_retry_without_agent(monkeypatch) -> Non def test_single_ai_redo_reports_manual_review_rejection(monkeypatch) -> None: """人工复核状态必须原样拒绝,且不得回退到破坏性 Agent 流程。""" - _install_retry_command( + repository = _install_retry_command( monkeypatch, { "task-12": _retry_result( @@ -209,6 +205,7 @@ def test_single_ai_redo_reports_manual_review_rejection(monkeypatch) -> None: query=_HistoryQuery([TransferHistory(id=12, transfer_task_id="task-12")]), runtime_config=_runtime(), task_registry=object(), + execution_repository=repository, _=object(), ) ) @@ -219,7 +216,7 @@ def test_single_ai_redo_reports_manual_review_rejection(monkeypatch) -> None: def test_batch_ai_redo_returns_completed_progress_for_durable_tasks(monkeypatch) -> None: """全 durable 批量接受后保留前端既有 progress_key 协议。""" - _install_retry_command( + repository = _install_retry_command( monkeypatch, { "task-18": _retry_result( @@ -257,6 +254,7 @@ def test_batch_ai_redo_returns_completed_progress_for_durable_tasks(monkeypatch) ]), runtime_config=_runtime(ai_enabled=False), task_registry=object(), + execution_repository=repository, _=object(), ) ) @@ -272,7 +270,7 @@ def test_batch_ai_redo_reports_each_rejection_without_starting_legacy_agent( monkeypatch, ) -> None: """混合批量逐 task 返回拒绝,避免同时产生无人监听的旧 Agent 任务。""" - _install_retry_command( + repository = _install_retry_command( monkeypatch, { "task-21": _retry_result( @@ -311,6 +309,7 @@ def test_batch_ai_redo_reports_each_rejection_without_starting_legacy_agent( query=_HistoryQuery(histories), runtime_config=_runtime(), task_registry=object(), + execution_repository=repository, _=object(), ) ) @@ -332,7 +331,7 @@ def test_batch_ai_redo_sends_only_legacy_records_after_durable_acceptance( monkeypatch, ) -> None: """混合批量全接受时 durable 只登记重试,旧历史才进入 Agent。""" - _install_retry_command( + repository = _install_retry_command( monkeypatch, { "task-24": _retry_result( @@ -364,6 +363,7 @@ def test_batch_ai_redo_sends_only_legacy_records_after_durable_acceptance( ]), runtime_config=_runtime(), task_registry=object(), + execution_repository=repository, _=object(), ) ) @@ -397,13 +397,9 @@ def test_agent_delete_tool_requests_retry_before_any_destructive_action(monkeypa delete_calls.append(history_id) retry_calls: list[dict] = [] - monkeypatch.setattr( - "app.agent.tools.impl.delete_transfer_history.get_agent_transfer_history_port", - _HistoryPort, - ) monkeypatch.setattr( "app.agent.tools.impl.delete_transfer_history._request_transfer_retry", - lambda **kwargs: retry_calls.append(kwargs) + lambda _repository, **kwargs: retry_calls.append(kwargs) or _retry_result( accepted=False, state=TransferExecutionState.MANUAL_REVIEW, @@ -421,6 +417,10 @@ def test_agent_delete_tool_requests_retry_before_any_destructive_action(monkeypa DeleteTransferHistoryTool( session_id="redo-session", user_id="10001", + data=SimpleNamespace( + transfer_history=_HistoryPort(), + transfer_execution=SimpleNamespace(), + ), ).run(history_id=31) ) diff --git a/tests/test_host_runtime_context.py b/tests/test_host_runtime_context.py index 61cc9d6a8..95ff8fa4f 100644 --- a/tests/test_host_runtime_context.py +++ b/tests/test_host_runtime_context.py @@ -14,6 +14,7 @@ from app.api.context import ( get_agent_chat_transaction, ) from app.api.dependencies.agent import get_agent_chat_persistence +from app.application.agent import AgentDataContext from app.application.configuration import ( ApiRuntimeConfig, ChainRuntimeConfig, @@ -133,6 +134,19 @@ def _runtime() -> HostRuntime: yield object() return HostRuntime( + agent=AgentDataContext( + chat=SimpleNamespace(), + chat_persistence=_AgentChatPersistence(), + tasks=SimpleNamespace(), + users=SimpleNamespace(), + sites=SimpleNamespace(), + subscriptions=SimpleNamespace(), + subscription_history=SimpleNamespace(), + transfer_history=SimpleNamespace(), + transfer_execution=SimpleNamespace(), + download_history=SimpleNamespace(), + plugin_data=SimpleNamespace(), + ), agent_chat=AgentChatRuntime( async_session=async_session, repository=_Repository, @@ -157,6 +171,7 @@ def _runtime() -> HostRuntime: transfer_repository=_Repository, transfer_mutation_repository=_Repository, media_server_repository=_Repository, + transfer_execution_repository=_Repository(object()), ), site=SiteRuntime( repository=_Repository, diff --git a/tests/test_manual_transfer_history.py b/tests/test_manual_transfer_history.py index 79fc944dd..2e0363b6a 100644 --- a/tests/test_manual_transfer_history.py +++ b/tests/test_manual_transfer_history.py @@ -70,19 +70,12 @@ def _patch_transfer_planning(monkeypatch, chain, fileitem, history, planned, del get_by_dest=lambda dest, storage=None: None, delete=lambda history_id: deleted.append(("history", history_id)), ) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: history_oper, - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: history_oper) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), + chain.transfer_history_repository = history_oper + chain.download_history_repository = SimpleNamespace( + get_by_hash=lambda download_hash: None, + get_file_by_fullpath=lambda fullpath: None, + get_files_by_savepath=lambda savepath: [], + get_by_path=lambda path: None, ) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", @@ -294,8 +287,10 @@ def test_successful_move_history_is_found_by_current_destination(): status=True, )) try: + chain = make_transfer_chain() + chain.transfer_history_repository = transfer_history_oper histories = TransferChain.get_manual_transfer_histories( - make_transfer_chain(), + chain, [destination], ) diff --git a/tests/test_mediaserver_sync_incremental.py b/tests/test_mediaserver_sync_incremental.py index 1a1f1116b..b02177bf5 100644 --- a/tests/test_mediaserver_sync_incremental.py +++ b/tests/test_mediaserver_sync_incremental.py @@ -100,12 +100,9 @@ def test_sync_persists_music_without_querying_tv_episodes(database): ] ) chain.episodes = lambda *_args, **_kwargs: pytest.fail("音乐条目不应查询电视剧分集") + chain.media_server_repository = TransactionalMediaServerRepository(database) with patch.object( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - lambda: TransactionalMediaServerRepository(database), - ), patch.object( MEDIA_SERVER_CHAIN_MODULE, "get_mediaserver_configs", return_value=[SimpleNamespace(name="navidrome", enabled=True, sync_libraries=["all"])], @@ -139,12 +136,9 @@ def test_sync_normalizes_incomplete_tv_episode_rows(database): schemas.MediaServerSeasonInfo(season=None, episodes=[99]), schemas.MediaServerSeasonInfo(season=1, episodes=None), ] + chain.media_server_repository = TransactionalMediaServerRepository(database) with patch.object( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - lambda: TransactionalMediaServerRepository(database), - ), patch.object( MEDIA_SERVER_CHAIN_MODULE, "get_mediaserver_configs", return_value=[SimpleNamespace(name="plex", enabled=True, sync_libraries=["all"])], @@ -228,12 +222,9 @@ def test_sync_updates_rows_and_removes_stale_entries(database): ] ) chain.episodes = lambda *_args, **_kwargs: [] + chain.media_server_repository = TransactionalMediaServerRepository(database) with patch.object( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - lambda: TransactionalMediaServerRepository(database), - ), patch.object( MEDIA_SERVER_CHAIN_MODULE, "get_mediaserver_configs", return_value=[SimpleNamespace(name="plex", enabled=True, sync_libraries=["movies"])], @@ -310,12 +301,9 @@ def test_sync_queries_counts_before_items_and_reports_media_progress(database): chain.items_count = lambda **_kwargs: pytest.fail("整服同步不应逐库重复计数") chain.items = items chain.episodes = lambda *_args, **_kwargs: [] + chain.media_server_repository = TransactionalMediaServerRepository(database) with patch.object( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - lambda: TransactionalMediaServerRepository(database), - ), patch.object( MEDIA_SERVER_CHAIN_MODULE, "get_mediaserver_configs", return_value=[ @@ -366,11 +354,7 @@ def test_sync_targets_one_server_without_excluding_other_enabled_servers(monkeyp excluded_server_calls.append(servers) chain.librarys = lambda server: library_calls.append(server) or [] - monkeypatch.setattr( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - FakeMediaServerOper, - ) + chain.media_server_repository = FakeMediaServerOper() monkeypatch.setattr( MEDIA_SERVER_CHAIN_MODULE, "get_mediaserver_configs", @@ -446,11 +430,7 @@ def test_sync_partial_commit_preserves_stale_rows_until_next_run( chain.items = lambda **_kwargs: iter(items) chain.episodes = lambda *_args, **_kwargs: [] repository = FailingMediaServerRepository() - monkeypatch.setattr( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - lambda: repository, - ) + chain.media_server_repository = repository monkeypatch.setattr( MEDIA_SERVER_CHAIN_MODULE, "get_mediaserver_configs", @@ -468,11 +448,7 @@ def test_sync_partial_commit_preserves_stale_rows_until_next_run( item.item_id for item in session.query(MediaServerItem).all() } == {"movie-1", "stale"} - monkeypatch.setattr( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - lambda: transactional, - ) + chain.media_server_repository = transactional chain.sync() with database() as session: @@ -498,11 +474,7 @@ def test_sync_stops_without_emitting_completion_after_stop_signal(monkeypatch): global_vars.stop_system() return 0, 0 - monkeypatch.setattr( - MEDIA_SERVER_CHAIN_MODULE, - "get_chain_media_server_port", - FakeMediaServerOper, - ) + chain.media_server_repository = FakeMediaServerOper() monkeypatch.setattr( chain, "_prepare_sync_contexts", diff --git a/tests/test_music_download.py b/tests/test_music_download.py index 9afe53708..ead7d5325 100644 --- a/tests/test_music_download.py +++ b/tests/test_music_download.py @@ -4,8 +4,8 @@ from app.api.endpoints.download import add, download from app.chain.download import DownloadChain from app.domain.context import MUSIC_ENTITY_ALBUM, Context, MusicInfo from app.domain.meta.metamusic import MetaMusic -from app.schemas import ExistMediaInfo from app.schemas.context import TorrentInfo +from app.schemas.mediaserver import ExistMediaInfo from app.schemas.music import MusicInfo as MusicInfoSchema from app.schemas.types import MediaType @@ -217,14 +217,11 @@ def test_music_library_exists_uses_atomic_album_lookup(): mediaserver = Mock() mediaserver.get_item_id.return_value = "album-item-1" - with patch( - "app.chain.download.get_chain_media_server_port", - return_value=mediaserver, - ): - exists, no_exists = chain.get_no_exists_info( - meta=MetaMusic.from_music_info(album), - mediainfo=album, - ) + chain.media_server_repository = mediaserver + exists, no_exists = chain.get_no_exists_info( + meta=MetaMusic.from_music_info(album), + mediainfo=album, + ) assert exists is True assert no_exists == {} diff --git a/tests/test_music_subscribe.py b/tests/test_music_subscribe.py index 74de6e9a2..1c057d12d 100644 --- a/tests/test_music_subscribe.py +++ b/tests/test_music_subscribe.py @@ -131,12 +131,13 @@ def test_music_subscribe_reuses_search_download_and_finish_flow(): chain.finish_subscribe_or_not = Mock() chain.check_and_handle_existing_media = Mock(return_value=(False, {})) chain.filter_torrents = Mock(side_effect=lambda **kwargs: kwargs["torrent_list"]) + subscribe_oper = Mock() + subscribe_oper.get.return_value = subscribe + chain.subscription_repository = subscribe_oper with patch.object(SubscribeChain, "_recognize_music_subscribe", return_value=target), \ patch("app.chain._music.SearchChain", return_value=search_chain), \ - patch("app.chain._music.DownloadChain", return_value=download_chain), \ - patch("app.chain._music.get_chain_subscribe_port") as subscribe_oper: - subscribe_oper.return_value.get.return_value = subscribe + patch("app.chain._music.DownloadChain", return_value=download_chain): chain._search_music_subscribe(subscribe) search_chain.search_by_title.assert_any_call( @@ -240,9 +241,9 @@ def test_music_best_version_persists_downloaded_rule_priority(): subscribe_oper.update.return_value = updated chain = SubscribeChain() chain.finish_subscribe_or_not = Mock() + chain.subscription_repository = subscribe_oper - with patch("app.chain._music.DownloadChain", return_value=download_chain), \ - patch("app.chain._music.get_chain_subscribe_port", return_value=subscribe_oper): + with patch("app.chain._music.DownloadChain", return_value=download_chain): chain._download_music_subscribe(subscribe, _music_info(), [downloaded]) subscribe_oper.update.assert_called_once_with( @@ -345,9 +346,9 @@ def test_album_best_version_requires_confirmed_full_coverage(): subscribe_oper = Mock() subscribe_oper.get.return_value = subscribe chain = SubscribeChain() + chain.subscription_repository = subscribe_oper with patch("app.chain.subscribe.DownloadChain", return_value=download_chain), \ - patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ patch.object(chain, "_SubscribeChain__finish_subscribe") as finish: chain._download_music_subscribe(subscribe, album, [downloaded]) @@ -440,12 +441,11 @@ def test_music_rss_match_reuses_cached_context_without_second_site_search(): chain.get_params = Mock(return_value={}) chain.filter_torrents = Mock(side_effect=lambda **kwargs: kwargs["torrent_list"]) chain.finish_subscribe_or_not = Mock() + chain.subscription_repository = subscribe_oper torrent_helper = Mock() torrent_helper.filter_torrent.return_value = True with patch.object(SubscribeChain, "_recognize_music_subscribe", return_value=target), \ - patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ - patch("app.chain._music.get_chain_subscribe_port", return_value=subscribe_oper), \ patch("app.chain._music.TorrentHelper", return_value=torrent_helper), \ patch("app.chain._music.DownloadChain", return_value=download_chain), \ patch("app.chain.subscribe.SearchChain") as search_chain, \ @@ -644,8 +644,9 @@ def test_recording_target_sync_clears_stale_album_track_count(): updated = _subscribe(total_tracks=None) subscribe_oper.update.return_value = updated - with patch("app.chain._music.get_chain_subscribe_port", return_value=subscribe_oper): - result = SubscribeChain._sync_music_subscribe_target(subscribe, _music_info()) + chain = SubscribeChain() + chain.subscription_repository = subscribe_oper + result = chain._sync_music_subscribe_target(subscribe, _music_info()) subscribe_oper.update.assert_called_once_with( subscribe.id, @@ -672,8 +673,9 @@ def test_album_target_sync_does_not_clear_stable_track_count(): ) subscribe_oper = Mock() - with patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper): - SubscribeChain._sync_music_subscribe_target(subscribe, album) + chain = SubscribeChain() + chain.subscription_repository = subscribe_oper + chain._sync_music_subscribe_target(subscribe, album) subscribe_oper.update.assert_not_called() assert subscribe.total_tracks == 11 @@ -711,13 +713,11 @@ def test_subscribe_add_music_uses_explicit_entity_recognize(): target = _music_info() media_chain = Mock() media_chain.recognize_media = Mock(return_value=target) - subscribe_oper = Mock() # 落库入口已迁到 application/subscription/write.py,链路层能截到的接缝是 add_subscribe, # 它收到的正是链路交给写入路径的那份字段 add_subscribe = Mock(return_value=(1, "")) with patch("app.chain.subscribe.MediaChain", return_value=media_chain), \ - patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ patch("app.chain.subscribe.add_subscribe", add_subscribe), \ patch("app.chain.subscribe.MoviePilotServerHelper"), \ patch("app.chain.subscribe.eventmanager"): @@ -765,11 +765,9 @@ def test_subscribe_add_music_routes_new_album_sources( ) media_chain = Mock() media_chain.recognize_media = Mock(return_value=target) - subscribe_oper = Mock() add_subscribe = Mock(return_value=(1, "")) with patch("app.chain.subscribe.MediaChain", return_value=media_chain), \ - patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ patch("app.chain.subscribe.add_subscribe", add_subscribe), \ patch("app.chain.subscribe.MoviePilotServerHelper"), \ patch("app.chain.subscribe.eventmanager"): @@ -798,11 +796,9 @@ def test_subscribe_add_rejects_music_entity_mismatch_before_database_write(): """请求专辑却识别为单曲时必须中止,不能创建完成语义错误的订阅。""" media_chain = Mock() media_chain.recognize_media.return_value = _music_info() - subscribe_oper = Mock() add_subscribe = Mock() with patch("app.chain.subscribe.MediaChain", return_value=media_chain), \ - patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ patch("app.chain.subscribe.add_subscribe", add_subscribe): sid, err_msg = SubscribeChain().add( title="叶惠美", @@ -825,11 +821,9 @@ def test_subscribe_add_music_fails_fast_on_offline_fallback(): offline = MusicInfo(title="未知曲目", artists=["未知艺术家"]) media_chain = Mock() media_chain.recognize_by_meta = Mock(return_value=offline) - subscribe_oper = Mock() add_subscribe = Mock(return_value=(1, "")) with patch("app.chain.subscribe.MediaChain", return_value=media_chain), \ - patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ patch("app.chain.subscribe.add_subscribe", add_subscribe): sid, err_msg = SubscribeChain().add( title="未知曲目", @@ -862,15 +856,16 @@ def test_follow_preserves_album_entity_and_track_count(): system_config = Mock() system_config.get.return_value = ["follow-user"] - with patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ - patch("app.chain.subscribe.get_configured_system_config", return_value=system_config), \ + chain = SubscribeChain() + chain.subscription_repository = subscribe_oper + with patch("app.chain.subscribe.get_configured_system_config", return_value=system_config), \ patch( "app.chain.subscribe.MoviePilotServerHelper.get_subscribe_shares", return_value=[share], ), \ patch("app.chain.subscribe.MetaInfo") as video_meta, \ patch.object(SubscribeChain, "add", return_value=(1, "")) as add: - SubscribeChain.follow() + chain.follow(repository=subscribe_oper) video_meta.assert_not_called() identity = SubscriptionIdentity( @@ -891,11 +886,11 @@ def test_refresh_enables_music_entry_fetch_when_music_subscribe_exists(): subscribe_oper = Mock() # get_subscribed_sites 不带状态查询,has_music_subscribe 按可搜索状态查询 subscribe_oper.list.side_effect = lambda state=None: [_subscribe(state="R")] + chain.subscription_repository = subscribe_oper torrents_chain = Mock() torrents_chain.refresh.return_value = {} - with patch("app.chain.subscribe.get_chain_subscribe_port", return_value=subscribe_oper), \ - patch("app.chain.subscribe.get_configured_system_config") as system_config, \ + with patch("app.chain.subscribe.get_configured_system_config") as system_config, \ patch("app.chain.subscribe.TorrentsChain", return_value=torrents_chain): system_config.return_value.get.return_value = [] chain.refresh() diff --git a/tests/test_music_transfer.py b/tests/test_music_transfer.py index 67909863c..f96fc0d38 100644 --- a/tests/test_music_transfer.py +++ b/tests/test_music_transfer.py @@ -550,11 +550,7 @@ def test_success_file_aggregation_is_isolated_between_music_jobs_in_same_directo need_notify=True, ) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace()) + chain.transfer_history_repository = SimpleNamespace() monkeypatch.setattr( "app.chain.transfer.add_transfer_success", lambda **kwargs: SimpleNamespace(id=1), @@ -795,9 +791,8 @@ def test_downloader_process_forwards_music_history_type(tmp_path, monkeypatch): ) ], ) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace(get_by_hash=lambda download_hash: history), + chain.download_history_repository = SimpleNamespace( + get_by_hash=lambda download_hash: history ) monkeypatch.setattr( chain, diff --git a/tests/test_release_group.py b/tests/test_release_group.py index 80b6e1e01..b12a8be25 100644 --- a/tests/test_release_group.py +++ b/tests/test_release_group.py @@ -1,6 +1,6 @@ -from tests.cases.groups import release_group_cases from app.domain.meta import releasegroup as releasegroup_module from app.domain.meta.releasegroup import ReleaseGroupsMatcher +from tests.cases.groups import release_group_cases def test_release_group(): @@ -27,3 +27,8 @@ def test_custom_release_group_matches_multiple_adjacent_groups(monkeypatch): ) assert release_group == "DMG@VCB-Studio" + + +def test_release_group_ignores_empty_title(): + """空标题不应进入制作组正则匹配。""" + assert ReleaseGroupsMatcher().match("") == "" diff --git a/tests/test_rule_group_media.py b/tests/test_rule_group_media.py index d60bc09de..435f0e1f1 100644 --- a/tests/test_rule_group_media.py +++ b/tests/test_rule_group_media.py @@ -115,14 +115,11 @@ def test_reconcile_rule_group_references_removes_all_dangling_bindings(monkeypat update=lambda subscribe_id, payload: updates.append((subscribe_id, payload)), ) monkeypatch.setattr(subscribe_module, "_system_config", lambda: Config()) - monkeypatch.setattr( - subscribe_module, - "get_chain_subscribe_port", - lambda: subscribe_port, - ) + chain = object.__new__(SubscribeChain) + chain.subscription_repository = subscribe_port SubscribeChain.reconcile_rule_group_references( - object.__new__(SubscribeChain), + chain, Event( EventType.ConfigChanged, ConfigChangeEventData( diff --git a/tests/test_site_architecture.py b/tests/test_site_architecture.py index fa385acf6..1203f2b7a 100644 --- a/tests/test_site_architecture.py +++ b/tests/test_site_architecture.py @@ -226,37 +226,24 @@ def test_site_adapter_public_surface_has_no_any_annotations() -> None: assert violations == [] -def test_site_chain_and_agent_getters_return_typed_repository() -> None: - """Chain 与 Agent 只能通过返回 SiteRepository 的明确 getter 取站点端口。""" - paths = ( - APP_ROOT / "application" / "chain" / "data.py", - APP_ROOT / "application" / "agentdata.py", +def test_chain_runtime_context_owns_typed_site_repository() -> None: + """Chain 站点仓储必须由显式运行上下文注入,旧数据 locator 不得存在。""" + path = APP_ROOT / "application" / "chain" / "context.py" + tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) + context = next( + node + for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == "ChainRuntimeContext" ) - expected_getters = {"get_chain_site_port", "get_agent_site_port"} - returns: dict[str, str] = {} - retired_classes: list[str] = [] - - for path in paths: - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - for node in tree.body: - if isinstance(node, ast.ClassDef) and node.name in { - "SitePort", - "SitePortProxy", - }: - retired_classes.append(f"{path.name}:{node.name}:{node.lineno}") - if ( - isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name in expected_getters - ): - assert node.returns is not None - returns[node.name] = ast.unparse(node.returns) - - assert retired_classes == [] - assert returns == { - "get_chain_site_port": "SiteRepository", - "get_agent_site_port": "SiteRepository", + annotations = { + node.target.id: ast.unparse(node.annotation) + for node in context.body + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) } + assert annotations["site_repository"] == "SiteRepository" + assert not (APP_ROOT / "application" / "chain" / "data.py").exists() + def test_site_files_use_single_word_owners_without_package_reexports() -> None: """Site contract 与 adapter 使用单词文件,应用包根不得复制宿主导出面。""" diff --git a/tests/test_slash_command_interactions.py b/tests/test_slash_command_interactions.py index e316558b6..50d4a7b57 100644 --- a/tests/test_slash_command_interactions.py +++ b/tests/test_slash_command_interactions.py @@ -1,3 +1,7 @@ +"""斜杠命令交互路由测试。""" + +# ruff: noqa: E402 - 可选运行时依赖必须在导入消息 Chain 前完成隔离。 + import unittest from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -10,13 +14,13 @@ ensure_optional_stub("psutil") ensure_optional_stub("aioshutil") ensure_optional_stub("pyquery", PyQuery=object) -from app.chain.message import MessageChain from app.application.messaging.interaction import InteractionContext -from app.chain.site import SiteChain from app.application.messaging.site import site_interaction_manager from app.application.messaging.skill import skill_interaction_manager -from app.chain.subscribe import SubscribeChain from app.application.messaging.subscribe import subscribe_interaction_manager +from app.chain.message import MessageChain +from app.chain.site import SiteChain +from app.chain.subscribe import SubscribeChain from app.schemas.types import NotificationChannel @@ -209,12 +213,8 @@ class TestSlashCommandInteractions(unittest.TestCase): ) ] - with patch( - "app.chain.site.get_chain_site_port", - return_value=SimpleNamespace(list=lambda: fake_sites), - ), patch.object( - chain, "post_message" - ) as post_message: + chain.site_repository = SimpleNamespace(list=lambda: fake_sites) + with patch.object(chain, "post_message") as post_message: chain.remote_list(channel=NotificationChannel.Web, userid="u1", source="web") notification = post_message.call_args[0][0] @@ -237,10 +237,8 @@ class TestSlashCommandInteractions(unittest.TestCase): ] subscribe_port = SimpleNamespace(list=lambda: fake_subscribes) - with patch( - "app.chain.subscribe.get_chain_subscribe_port", - return_value=subscribe_port, - ), patch.object(chain, "post_message") as post_message: + chain.subscription_repository = subscribe_port + with patch.object(chain, "post_message") as post_message: chain.remote_list(channel=NotificationChannel.Web, userid="u1", source="web") notification = post_message.call_args[0][0] diff --git a/tests/test_subscribe_chain.py b/tests/test_subscribe_chain.py index ccb43a441..a8f4fc0c7 100644 --- a/tests/test_subscribe_chain.py +++ b/tests/test_subscribe_chain.py @@ -5,7 +5,7 @@ import types from dataclasses import replace from pathlib import Path from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pytest @@ -37,8 +37,11 @@ def _load_subscribe_chain_class(): chain_module = ensure_module("app.chain", types.ModuleType("app.chain")) class _ChainBase: + subscription_repository = SimpleNamespace() + def __init__(self): self.messagehelper = SimpleNamespace(put=lambda *args, **kwargs: None) + self.subscription_repository = type(self).subscription_repository def post_message(self, *args, **kwargs): return None @@ -597,10 +600,10 @@ class TestSubscribeChain: return [subscribe] chain = SubscribeChain() + chain.subscription_repository = _SubscribeOper() chain.check_and_handle_existing_media = lambda **kwargs: (False, {}) with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port", _SubscribeOper), patch.object( SUBSCRIBE_CHAIN_MODULE, "TorrentHelper", @@ -681,6 +684,7 @@ class TestSubscribeChain: return [context], {} chain = SubscribeChain() + chain.subscription_repository = _SubscribeOper() chain.check_and_handle_existing_media = lambda **kwargs: (False, {}) chain.get_sub_sites = lambda *_args, **_kwargs: [] chain.get_params = lambda *_args, **_kwargs: {} @@ -688,7 +692,6 @@ class TestSubscribeChain: chain.finish_subscribe_or_not = lambda **_kwargs: None with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port", _SubscribeOper), patch.object( SUBSCRIBE_CHAIN_MODULE, "TorrentHelper", @@ -853,9 +856,10 @@ class TestSubscribeChain: with ( patch.object(SUBSCRIBE_CHAIN_MODULE, "DownloadChain", _DownloadChain), patch.object( - SUBSCRIBE_CHAIN_MODULE, - "get_chain_subscribe_port", - _SubscribeOper, + SubscribeChain, + "subscription_repository", + _SubscribeOper(), + create=True, ), ): satisfied, no_exists = chain.resolve_subscribe_missing( @@ -1079,7 +1083,7 @@ class TestSubscribeChain: return SimpleNamespace(name=title, begin_season=None, episode_list=[]) with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port", _SubscribeOper), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( SUBSCRIBE_CHAIN_MODULE, "get_configured_system_config", @@ -1101,7 +1105,7 @@ class TestSubscribeChain: _add, ), ): - SubscribeChain.follow() + SubscribeChain().follow() assert len(added_calls) == 1 assert added_calls[0]["season"] == 0 @@ -1721,17 +1725,17 @@ class TestSubscribeChain: meta_episodes=[2, 3, 4], ) chain = SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper mediainfo = SimpleNamespace(title_year="Test Show (2026)") - with patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port") as subscribe_oper_cls: - subscribe_oper = subscribe_oper_cls.return_value - subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) + subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) - snapshot = chain._SubscribeChain__record_subscribe_download_facts( - subscribe=subscribe, - mediainfo=mediainfo, - downloads=[download], - ) + snapshot = chain._SubscribeChain__record_subscribe_download_facts( + subscribe=subscribe, + mediainfo=mediainfo, + downloads=[download], + ) subscribe_oper.update.assert_called_once() payload = subscribe_oper.update.call_args.args[1].to_payload() @@ -1756,13 +1760,13 @@ class TestSubscribeChain: self._build_download(priority=100, selected_episodes=[3]), ] chain = SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper mediainfo = SimpleNamespace(title_year="Test Show (2026)") with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port") as subscribe_oper_cls, patch.object(SUBSCRIBE_CHAIN_MODULE, "logger") as logger_mock, ): - subscribe_oper = subscribe_oper_cls.return_value subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) chain._SubscribeChain__record_subscribe_download_facts( @@ -1788,17 +1792,17 @@ class TestSubscribeChain: ) download = self._build_download(priority=100, selected_episodes=[], meta_episodes=[]) chain = SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper mediainfo = SimpleNamespace(title_year="Test Show (2026)") - with patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port") as subscribe_oper_cls: - subscribe_oper = subscribe_oper_cls.return_value - subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) + subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) - snapshot = chain._SubscribeChain__record_subscribe_download_facts( - subscribe=subscribe, - mediainfo=mediainfo, - downloads=[download], - ) + snapshot = chain._SubscribeChain__record_subscribe_download_facts( + subscribe=subscribe, + mediainfo=mediainfo, + downloads=[download], + ) assert snapshot["episodes"] == [] subscribe_oper.update.assert_not_called() @@ -1815,17 +1819,17 @@ class TestSubscribeChain: download = self._build_download(priority=100, selected_episodes=[], meta_episodes=[]) download.confirmed_full_coverage = True chain = SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper mediainfo = SimpleNamespace(title_year="Test Show (2026)") - with patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port") as subscribe_oper_cls: - subscribe_oper = subscribe_oper_cls.return_value - subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) + subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) - chain._SubscribeChain__record_subscribe_download_facts( - subscribe=subscribe, - mediainfo=mediainfo, - downloads=[download], - ) + chain._SubscribeChain__record_subscribe_download_facts( + subscribe=subscribe, + mediainfo=mediainfo, + downloads=[download], + ) payload = subscribe_oper.update.call_args.args[1].to_payload() assert payload["episode_priority"] == {"1": 100, "2": 100, "3": 100} @@ -1846,17 +1850,17 @@ class TestSubscribeChain: self._build_download(priority=100, selected_episodes=[3]), ] chain = SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper meta = SimpleNamespace(type=MediaType.TV) mediainfo = SimpleNamespace(title_year="Test Show (2026)") with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port") as subscribe_oper_cls, patch.object( SubscribeChain, "_SubscribeChain__finish_subscribe", ) as finish_mock, ): - subscribe_oper = subscribe_oper_cls.return_value subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) chain.finish_subscribe_or_not( @@ -1882,6 +1886,8 @@ class TestSubscribeChain: lack_episode=0, ) chain = SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper mediainfo = SimpleNamespace( seasons={1: [1, 2, 3, 4, 5]}, title="Test Show", @@ -1900,10 +1906,8 @@ class TestSubscribeChain: ) with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port") as subscribe_oper_cls, _patch_media_recognize(SUBSCRIBE_CHAIN_MODULE, mediainfo), ): - subscribe_oper = subscribe_oper_cls.return_value subscribe_oper.list.return_value = [subscribe] subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) @@ -2118,8 +2122,8 @@ class TestSubscribeNoteTracking: def get(self, *args, **kwargs): return subscribe + chain.subscription_repository = _SubscribeOper() with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port", _SubscribeOper), patch.object( SubscribeChain, "_SubscribeChain__update_movie_download_priority", @@ -2163,8 +2167,8 @@ class TestSubscribeNoteTracking: def get(self, *args, **kwargs): return subscribe + chain.subscription_repository = _SubscribeOper() with ( - patch.object(SUBSCRIBE_CHAIN_MODULE, "get_chain_subscribe_port", _SubscribeOper), patch.object( SubscribeChain, "_SubscribeChain__is_best_version_complete", @@ -2296,7 +2300,7 @@ class TestSubscribeProgressEntrypoint: updates.append((subscribe_id, payload.to_payload())) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): summary = self.SubscribeChain().backfill_existing_episodes( subscribe, [1, 2, 3, 9, "bad"], @@ -2324,7 +2328,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): summary = self.SubscribeChain().backfill_existing_episodes( subscribe, [1, 2, 3], @@ -2347,7 +2351,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): invalid = self.SubscribeChain().backfill_existing_episodes( subscribe, [1, 2], @@ -2395,7 +2399,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): summary = self.SubscribeChain().backfill_existing_episodes( subscribe, [1], @@ -2418,7 +2422,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): summary = self.SubscribeChain().backfill_existing_episodes( subscribe, [1], @@ -2442,7 +2446,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): summary = self.SubscribeChain().backfill_existing_episodes( subscribe, [1, 2, 3, 4, 5], @@ -2469,7 +2473,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): summary = self.SubscribeChain().backfill_existing_episodes( subscribe, [3], @@ -2493,8 +2497,8 @@ class TestSubscribeProgressEntrypoint: return replace(subscribe, **payload.to_payload()) chain = self.SubscribeChain() + chain.subscription_repository = _SubscribeOper() with ( - patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()), patch.object( chain, "refresh_subscribe_progress", @@ -2538,7 +2542,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): summary = self.SubscribeChain()._SubscribeChain__refresh_subscribe_progress_with_no_exists( subscribe=subscribe, no_exists={}, @@ -2565,7 +2569,7 @@ class TestSubscribeProgressEntrypoint: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): self.SubscribeChain()._SubscribeChain__refresh_subscribe_progress_with_no_exists( subscribe=subscribe, no_exists={}, @@ -2593,7 +2597,7 @@ class TestSubscribeProgressEntrypoint: return replace(subscribe, **payload.to_payload()) with ( - patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), _patch_media_recognize(self.module, mediainfo), patch.object( self.SubscribeChain, "resolve_subscribe_missing", return_value=(False, no_exists) @@ -2630,7 +2634,7 @@ class TestSubscribeProgressEntrypoint: raise AssertionError("resolve failure must not write progress") with ( - patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), _patch_media_recognize(self.module, mediainfo), patch.object(self.SubscribeChain, "resolve_subscribe_missing", return_value=(False, {})), ): @@ -2648,7 +2652,7 @@ class TestSubscribeProgressEntrypoint: raise AssertionError("recognition failure must not write progress") with ( - patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), _patch_media_recognize(self.module, None), ): summary = self.SubscribeChain().refresh_subscribe_progress(subscribe, scene="unit") @@ -2673,7 +2677,7 @@ class TestSubscribeProgressEntrypoint: return replace(subscribe, **payload.to_payload()) with ( - patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object(self.SubscribeChain, "_SubscribeChain__finish_subscribe"), ): self.SubscribeChain().finish_subscribe_or_not( @@ -2796,7 +2800,7 @@ class TestSubscribeProgressConsolidation: updates.append((subscribe_id, payload.to_payload())) return replace(subscribe, **payload.to_payload()) - with patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): updated = SubscribeChain()._SubscribeChain__refresh_total_episode_before_completion( subscribe, mediainfo, @@ -2846,7 +2850,7 @@ class TestSubscribeProgressConsolidation: chain.resolve_subscribe_missing = _resolve_missing with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( module, "eventmanager", @@ -2893,7 +2897,7 @@ class TestSubscribeProgressConsolidation: return replace(subscribe, **payload.to_payload()) with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( module, "eventmanager", @@ -3028,7 +3032,7 @@ class TestSubscribeProgressConsolidation: return replace(subscribe, **payload.to_payload()) with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( module, "eventmanager", @@ -3078,7 +3082,7 @@ class TestSubscribeProgressConsolidation: return replace(subscribe, **payload.to_payload()) with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( module, "eventmanager", @@ -3128,7 +3132,7 @@ class TestSubscribeProgressConsolidation: return replace(subscribe, **payload.to_payload()) with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( module, "eventmanager", @@ -3174,7 +3178,7 @@ class TestSubscribeProgressConsolidation: raise AssertionError("manual total episode must not be updated") with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( module, "eventmanager", @@ -3218,7 +3222,7 @@ class TestSubscribeProgressConsolidation: raise AssertionError("non-tv subscribe must not be updated") with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object( module, "eventmanager", @@ -3265,9 +3269,9 @@ class TestSubscribeProgressConsolidation: return replace(subscribe, **payload.to_payload()) chain = SubscribeChain() + chain.subscription_repository = _SubscribeOper() with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), _patch_media_recognize(module, lambda **_kwargs: self._mediainfo(total_episode=5)), ): chain.check() @@ -3311,9 +3315,9 @@ class TestSubscribeProgressConsolidation: return replace(subscribe, **payload.to_payload()) chain = SubscribeChain() + chain.subscription_repository = _SubscribeOper() with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), patch.object( module, "eventmanager", @@ -3361,6 +3365,7 @@ class TestSubscribeProgressConsolidation: return replace(subscribe, **payload.to_payload()) chain = SubscribeChain() + chain.subscription_repository = _SubscribeOper() chain.resolve_subscribe_missing = lambda **kwargs: ( False, { @@ -3377,7 +3382,6 @@ class TestSubscribeProgressConsolidation: ) with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), patch.object( module, "eventmanager", @@ -3430,9 +3434,9 @@ class TestSubscribeProgressConsolidation: raise AssertionError("non-tv subscribe must not ask external refresh") chain = SubscribeChain() + chain.subscription_repository = _SubscribeOper() with ( - patch.object(module, "get_chain_subscribe_port", return_value=_SubscribeOper()), patch.object( module, "eventmanager", @@ -3590,7 +3594,7 @@ class TestSubscribeDownloadFacts: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): snapshot = self.SubscribeChain()._SubscribeChain__record_subscribe_download_facts( subscribe, mediainfo=SimpleNamespace(title_year="下载事实剧 (2026)"), @@ -3612,7 +3616,7 @@ class TestSubscribeDownloadFacts: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): snapshot = self.SubscribeChain()._SubscribeChain__record_subscribe_download_facts( subscribe, mediainfo=SimpleNamespace(title_year="下载事实剧 (2026)"), @@ -3640,7 +3644,7 @@ class TestSubscribeDownloadFacts: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): snapshot = self.SubscribeChain()._SubscribeChain__record_subscribe_download_facts( subscribe, mediainfo=SimpleNamespace(title_year="下载事实剧 (2026)"), @@ -3661,7 +3665,7 @@ class TestSubscribeDownloadFacts: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): snapshot = self.SubscribeChain()._SubscribeChain__record_subscribe_download_facts( subscribe, mediainfo=SimpleNamespace(title_year="下载事实剧 (2026)"), @@ -3689,14 +3693,14 @@ class TestSubscribeDownloadFacts: episode_priority={"1": 60}, ) - with patch.object(self.module, "get_chain_subscribe_port") as subscribe_oper_cls: + with patch.object(self.SubscribeChain, "subscription_repository", create=True) as subscribe_oper: self.SubscribeChain()._SubscribeChain__record_subscribe_download_facts( subscribe, mediainfo=SimpleNamespace(title_year="下载事实剧 (2026)"), downloads=[self._download(episodes=[1], pri_order=90, confirmed_full_coverage=False)], ) - payload = subscribe_oper_cls.return_value.update.call_args.args[1].to_payload() + payload = subscribe_oper.update.call_args.args[1].to_payload() assert subscribe.current_priority == 82 assert "current_priority" not in payload @@ -3709,7 +3713,7 @@ class TestSubscribeDownloadFacts: updates.append(payload.to_payload()) return replace(subscribe, **payload.to_payload()) - with patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()): + with patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True): snapshot = self.SubscribeChain()._SubscribeChain__record_subscribe_download_facts( subscribe, mediainfo=SimpleNamespace(title_year="下载事实剧 (2026)"), @@ -3758,7 +3762,7 @@ class TestSubscribeDownloadFacts: return replace(subscribe, **payload.to_payload()) with ( - patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()), + patch.object(self.SubscribeChain, "subscription_repository", _SubscribeOper(), create=True), patch.object(self.SubscribeChain, "_SubscribeChain__finish_subscribe"), ): self.SubscribeChain().finish_subscribe_or_not( @@ -3797,13 +3801,13 @@ class TestSubscribeDownloadFacts: ) download.meta_info = SimpleNamespace(episode_list=[], season_list=[]) chain = self.SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper with ( - patch.object(self.module, "get_chain_subscribe_port") as subscribe_oper_cls, patch.object(chain, "_SubscribeChain__refresh_subscribe_progress_with_no_exists") as refresh_mock, patch.object(chain, "_SubscribeChain__finish_subscribe"), ): - subscribe_oper = subscribe_oper_cls.return_value subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) chain.finish_subscribe_or_not( @@ -3839,13 +3843,13 @@ class TestSubscribeDownloadFacts: ) download.meta_info = SimpleNamespace(episode_list=[], season_list=[]) chain = self.SubscribeChain() + subscribe_oper = MagicMock() + chain.subscription_repository = subscribe_oper with ( - patch.object(self.module, "get_chain_subscribe_port") as subscribe_oper_cls, patch.object(chain, "_SubscribeChain__refresh_subscribe_progress_with_no_exists") as refresh_mock, patch.object(chain, "_SubscribeChain__finish_subscribe"), ): - subscribe_oper = subscribe_oper_cls.return_value subscribe_oper.update.side_effect = lambda _sid, payload: replace(subscribe, **payload.to_payload()) chain.finish_subscribe_or_not( @@ -3889,12 +3893,12 @@ class TestSubscribeDownloadFacts: return replace(subscribe, **payload.to_payload()) chain = self.SubscribeChain() + chain.subscription_repository = _SubscribeOper() def finish_probe(subscribe, **_kwargs): finished.append(subscribe.current_priority) with ( - patch.object(self.module, "get_chain_subscribe_port", return_value=_SubscribeOper()), patch.object(chain, "_SubscribeChain__finish_subscribe", side_effect=finish_probe), ): chain.finish_subscribe_or_not( diff --git a/tests/test_subscribe_files_info.py b/tests/test_subscribe_files_info.py index 33f551ffa..1eda57418 100644 --- a/tests/test_subscribe_files_info.py +++ b/tests/test_subscribe_files_info.py @@ -5,7 +5,7 @@ from unittest.mock import MagicMock, patch from app.application.subscription.contract import SubscriptionSnapshot from app.chain.subscribe import SubscribeChain -from app.modules.filemanager import FileManagerModule +from app.modules.filemanager.module import FileManagerModule from app.schemas.mediaserver import ExistMediaInfo from app.schemas.types import MediaType @@ -86,15 +86,15 @@ def test_subscribe_files_info_merges_multiple_mediaservers(): media_chain.recognize_media.return_value = mediainfo chain = SubscribeChain() + chain.download_history_repository = MagicMock() + chain.download_history_repository.get_by_mediaid.return_value = [] with ( - patch("app.chain.subscribe.get_chain_download_history_port") as download_oper, patch("app.chain.subscribe.MediaChain", return_value=media_chain), patch.object(chain, "media_files", return_value=None), patch.object(chain, "media_exists", side_effect=_media_exists_side_effect), patch("app.chain.subscribe.MediaServerHelper", return_value=helper), patch("app.chain.subscribe.MediaServerChain", return_value=mediaserver_chain), ): - download_oper.return_value.get_by_mediaid.return_value = [] result = chain.subscribe_files_info(subscribe) library = result.episodes[1].library @@ -133,15 +133,15 @@ def test_subscribe_files_info_uses_season_zero_for_tv(): media_chain.recognize_media.return_value = mediainfo chain = SubscribeChain() + chain.download_history_repository = MagicMock() + chain.download_history_repository.get_by_mediaid.return_value = [] with ( - patch("app.chain.subscribe.get_chain_download_history_port") as download_oper, patch("app.chain.subscribe.MediaChain", return_value=media_chain), patch.object(chain, "media_files", return_value=None), patch.object(chain, "media_exists", side_effect=_media_exists_side_effect), patch("app.chain.subscribe.MediaServerHelper", return_value=helper), patch("app.chain.subscribe.MediaServerChain", return_value=mediaserver_chain), ): - download_oper.return_value.get_by_mediaid.return_value = [] result = chain.subscribe_files_info(subscribe) assert captured_seasons == [0] diff --git a/tests/test_subscribe_search_state.py b/tests/test_subscribe_search_state.py index 5bf4a5b54..2a7d30e41 100644 --- a/tests/test_subscribe_search_state.py +++ b/tests/test_subscribe_search_state.py @@ -73,11 +73,10 @@ def test_new_subscribe_search_keeps_state_when_recently_created(monkeypatch) -> """ _SubscribeOper.subscribe = _new_subscribe(datetime.now()) _SubscribeOper.updates = [] - monkeypatch.setattr(subscribe_module, "get_chain_subscribe_port", _SubscribeOper) - media_chain_class = Mock() with patch.object(subscribe_module, "MediaChain", media_chain_class): chain = object.__new__(SubscribeChain) + chain.subscription_repository = _SubscribeOper() chain.search(state="N", manual=False) media_chain_class.assert_not_called() @@ -90,12 +89,11 @@ def test_new_subscribe_search_marks_state_after_attempt(monkeypatch) -> None: """ _SubscribeOper.subscribe = _new_subscribe(datetime.now() - timedelta(minutes=2)) _SubscribeOper.updates = [] - monkeypatch.setattr(subscribe_module, "get_chain_subscribe_port", _SubscribeOper) - media_chain = Mock() media_chain.recognize_media.return_value = None with patch.object(subscribe_module, "MediaChain", return_value=media_chain): chain = object.__new__(SubscribeChain) + chain.subscription_repository = _SubscribeOper() chain.search(state="N", manual=False) media_chain.recognize_media.assert_called_once() @@ -118,16 +116,12 @@ def test_targeted_batch_searches_all_ids_without_state_scan(monkeypatch) -> None subscribes = {first.id: first, second.id: second} subscribe_oper = Mock() subscribe_oper.get.side_effect = subscribes.get - monkeypatch.setattr( - subscribe_module, - "get_chain_subscribe_port", - lambda: subscribe_oper, - ) media_chain = Mock() media_chain.recognize_media.return_value = None with patch.object(subscribe_module, "MediaChain", return_value=media_chain): chain = object.__new__(SubscribeChain) + chain.subscription_repository = subscribe_oper chain.search(sids=(31, 32), state=None, manual=False) assert [item.args for item in subscribe_oper.get.call_args_list] == [(31,), (32,)] @@ -139,10 +133,10 @@ def test_subscribe_search_aborts_when_lock_times_out(monkeypatch) -> None: """订阅搜索锁超时后必须中止,不能在无锁状态下继续访问订阅。""" monkeypatch.setattr(SubscribeChain, "_rlock", _TimedOutLock()) subscribe_oper = Mock() - monkeypatch.setattr(subscribe_module, "get_chain_subscribe_port", subscribe_oper) progress = Mock() chain = object.__new__(SubscribeChain) + chain.subscription_repository = subscribe_oper chain.search(state="N", progress_callback=progress) subscribe_oper.assert_not_called() diff --git a/tests/test_subscription_architecture.py b/tests/test_subscription_architecture.py index 61d5fea98..cbd0ed02b 100644 --- a/tests/test_subscription_architecture.py +++ b/tests/test_subscription_architecture.py @@ -219,35 +219,26 @@ def test_subscription_callers_do_not_alias_snapshot_to_any() -> None: assert violations == [] -def test_subscription_getters_return_typed_repositories() -> None: - """Chain 与 Agent 订阅 getter 不得保留动态代理或 Any 返回值。""" - paths = ( - APP_ROOT / "application" / "chain" / "data.py", - APP_ROOT / "application" / "agentdata.py", +def test_chain_runtime_context_owns_typed_subscription_repository() -> None: + """Chain 订阅仓储必须由显式运行上下文注入,旧数据 locator 不得存在。""" + context_path = APP_ROOT / "application" / "chain" / "context.py" + tree = ast.parse( + context_path.read_text(encoding="utf-8-sig"), + filename=str(context_path), ) - expected = { - "get_chain_subscribe_port": "SubscriptionRepository", - "get_agent_subscribe_port": "SubscriptionRepository", - "get_agent_subscribe_history_port": "SubscriptionHistoryQueryPort", + context = next( + node + for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == "ChainRuntimeContext" + ) + annotations = { + node.target.id: ast.unparse(node.annotation) + for node in context.body + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) } - returns: dict[str, str] = {} - retired: list[str] = [] - for path in paths: - tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) - for node in tree.body: - if isinstance(node, ast.ClassDef) and node.name in { - "SubscribePort", - "SubscribeHistoryPort", - "SubscriptionPortProxy", - }: - retired.append(f"{path.name}:{node.name}:{node.lineno}") - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in expected: - assert node.returns is not None - returns[node.name] = ast.unparse(node.returns) - - assert retired == [] - assert returns == expected + assert annotations["subscription_repository"] == "SubscriptionRepository" + assert not (APP_ROOT / "application" / "chain" / "data.py").exists() def test_subscription_adapters_implement_typed_public_surface() -> None: diff --git a/tests/test_transfer_durable_retry_owner.py b/tests/test_transfer_durable_retry_owner.py index 5d10e02cb..09beb0af1 100644 --- a/tests/test_transfer_durable_retry_owner.py +++ b/tests/test_transfer_durable_retry_owner.py @@ -32,7 +32,7 @@ class _RetryCommand: def _install_retry_port(monkeypatch) -> object: - """安装不会接触数据库的 execution 端口与命令替身。""" + """构造不会接触数据库的 execution 端口并安装命令替身。""" repository = object() _RetryCommand.calls = [] _RetryCommand.result = TransferRetryRequestResult( @@ -41,10 +41,6 @@ def _install_retry_port(monkeypatch) -> object: retry_generation=2, message="整理任务已登记重试", ) - monkeypatch.setattr( - "app.chain._transfer.get_chain_transfer_execution_port", - lambda: repository, - ) monkeypatch.setattr( "app.chain._transfer.TransferExecutionCommand", _RetryCommand, @@ -60,10 +56,6 @@ def test_durable_history_redo_only_requests_persistent_retry(monkeypatch): transfer_task_id="transfer-task-81", src="/missing/source.mkv", ) - monkeypatch.setattr( - "app.chain._transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get=lambda history_id: history), - ) monkeypatch.setattr( "app.chain._transfer.Path.exists", lambda _path: (_ for _ in ()).throw( @@ -71,6 +63,10 @@ def test_durable_history_redo_only_requests_persistent_retry(monkeypatch): ), ) chain = object.__new__(TransferChain) + chain.transfer_execution_repository = repository + chain.transfer_history_repository = SimpleNamespace( + get=lambda history_id: history + ) monkeypatch.setattr( chain, "do_transfer", @@ -97,7 +93,7 @@ def test_durable_history_redo_only_requests_persistent_retry(monkeypatch): def test_durable_manual_cleanup_keeps_target_history_and_failure_budget(monkeypatch): """手动重整命中 durable 历史时不得先删目标、历史或失败计数。""" - _install_retry_port(monkeypatch) + repository = _install_retry_port(monkeypatch) history = SimpleNamespace( id=82, transfer_task_id="transfer-task-82", @@ -129,6 +125,7 @@ def test_durable_manual_cleanup_keeps_target_history_and_failure_budget(monkeypa ), ) chain = object.__new__(TransferChain) + chain.transfer_execution_repository = repository state, message = chain._delete_manual_transfer_history( history=history, @@ -142,12 +139,8 @@ def test_durable_manual_cleanup_keeps_target_history_and_failure_budget(monkeypa def test_durable_ai_button_bypasses_agent_and_requests_scheduler(monkeypatch): """AI 按钮命中 durable 历史时也只能登记调度重试。""" - _install_retry_port(monkeypatch) + repository = _install_retry_port(monkeypatch) history = SimpleNamespace(id=83, transfer_task_id="transfer-task-83") - monkeypatch.setattr( - "app.chain._transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get=lambda history_id: history), - ) monkeypatch.setattr( "app.chain._transfer.build_manual_redo_prompt", lambda _history: (_ for _ in ()).throw( @@ -162,6 +155,10 @@ def test_durable_ai_button_bypasses_agent_and_requests_scheduler(monkeypatch): ) messages = [] chain = object.__new__(TransferChain) + chain.transfer_execution_repository = repository + chain.transfer_history_repository = SimpleNamespace( + get=lambda history_id: history + ) chain.runtime_config = SimpleNamespace( ai_agent_enable=False, history_url="/history", @@ -183,7 +180,7 @@ def test_durable_ai_button_bypasses_agent_and_requests_scheduler(monkeypatch): def test_durable_manual_review_rejection_does_not_fall_back_to_legacy(monkeypatch): """人工复核任务被拒绝后不得回退到旧识别和重整流程。""" - _install_retry_port(monkeypatch) + repository = _install_retry_port(monkeypatch) _RetryCommand.result = TransferRetryRequestResult( accepted=False, state=TransferExecutionState.MANUAL_REVIEW, @@ -195,10 +192,6 @@ def test_durable_manual_review_rejection_does_not_fall_back_to_legacy(monkeypatc transfer_task_id="transfer-task-84", src="/downloads/source.mkv", ) - monkeypatch.setattr( - "app.chain._transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get=lambda history_id: history), - ) monkeypatch.setattr( "app.chain._transfer.Path.exists", lambda _path: (_ for _ in ()).throw( @@ -206,6 +199,10 @@ def test_durable_manual_review_rejection_does_not_fall_back_to_legacy(monkeypatc ), ) chain = object.__new__(TransferChain) + chain.transfer_execution_repository = repository + chain.transfer_history_repository = SimpleNamespace( + get=lambda history_id: history + ) state, message = chain._re_transfer(logid=84) diff --git a/tests/test_transfer_failed_retry_buttons.py b/tests/test_transfer_failed_retry_buttons.py index a3d6a3f94..f3658199a 100644 --- a/tests/test_transfer_failed_retry_buttons.py +++ b/tests/test_transfer_failed_retry_buttons.py @@ -1,9 +1,8 @@ -import unittest import asyncio import sys +import unittest from dataclasses import replace -from types import ModuleType -from types import SimpleNamespace +from types import ModuleType, SimpleNamespace from unittest.mock import Mock, patch sys.modules.setdefault("qbittorrentapi", ModuleType("qbittorrentapi")) @@ -12,12 +11,12 @@ sys.modules.setdefault("transmission_rpc", ModuleType("transmission_rpc")) setattr(sys.modules["transmission_rpc"], "File", object) sys.modules.setdefault("psutil", ModuleType("psutil")) -from app.chain.message import MessageChain -from app.chain.transfer import TransferChain -from app.application.messaging.interaction import InteractionContext -from app.runtime.config import global_vars, settings -from app.runtime.tasks import TaskRegistry -from app.schemas.types import NotificationChannel +from app.application.messaging.interaction import InteractionContext # noqa: E402 +from app.chain.message import MessageChain # noqa: E402 +from app.chain.transfer import TransferChain # noqa: E402 +from app.runtime.config import global_vars, settings # noqa: E402 +from app.runtime.tasks import TaskRegistry # noqa: E402 +from app.schemas.types import NotificationChannel # noqa: E402 class TestTransferFailedRetryButtons(unittest.TestCase): @@ -128,6 +127,9 @@ class TestTransferFailedRetryButtons(unittest.TestCase): media_id="123", errmsg="未识别到媒体信息", ) + chain.transfer_history_repository = SimpleNamespace( + get=lambda history_id: history + ) async_messages = [] @@ -146,8 +148,6 @@ class TestTransferFailedRetryButtons(unittest.TestCase): settings, "AI_AGENT_ENABLE", True ): with patch( - "app.chain._transfer.get_chain_transfer_history_port" - ) as history_oper_cls, patch( "app.chain._transfer.build_manual_redo_prompt", return_value="retry transfer prompt", ), patch( @@ -156,7 +156,6 @@ class TestTransferFailedRetryButtons(unittest.TestCase): get_registry.return_value.submit_threadsafe.side_effect = ( _run_pending_coro ) - history_oper_cls.return_value.get.return_value = history with patch.object(chain, "async_post_message", side_effect=_capture_message): chain.handle_failed_transfer_callback( callback_data="transfer_ai_retry_34", @@ -183,6 +182,9 @@ class TestTransferFailedRetryButtons(unittest.TestCase): chain = TransferChain() chain.runtime_config = replace(chain.runtime_config, ai_agent_enable=True) history = SimpleNamespace(id=34) + chain.transfer_history_repository = SimpleNamespace( + get=lambda history_id: history + ) registry = TaskRegistry() asyncio.run(registry.shutdown(timeout_seconds=0.01)) loop = Mock(**{"is_running.return_value": True, "is_closed.return_value": False}) @@ -190,8 +192,6 @@ class TestTransferFailedRetryButtons(unittest.TestCase): with patch.object(global_vars, "CURRENT_EVENT_LOOP", loop), patch.object( settings, "AI_AGENT_ENABLE", True ), patch( - "app.chain._transfer.get_chain_transfer_history_port" - ) as history_port, patch( "app.chain._transfer.build_manual_redo_prompt", return_value="retry transfer prompt", ), patch( @@ -201,8 +201,6 @@ class TestTransferFailedRetryButtons(unittest.TestCase): ) as logger, patch.object( chain, "post_message" ) as post_message: - history_port.return_value.get.return_value = history - chain.handle_failed_transfer_callback( callback_data="transfer_ai_retry_34", channel=NotificationChannel.Telegram, @@ -224,12 +222,13 @@ class TestTransferFailedRetryButtons(unittest.TestCase): chain = TransferChain() chain.runtime_config = replace(chain.runtime_config, ai_agent_enable=True) history = SimpleNamespace(id=34) + chain.transfer_history_repository = SimpleNamespace( + get=lambda history_id: history + ) with patch.object(global_vars, "CURRENT_EVENT_LOOP", None), patch.object( settings, "AI_AGENT_ENABLE", True ), patch( - "app.chain._transfer.get_chain_transfer_history_port" - ) as history_port, patch( "app.chain._transfer.build_manual_redo_prompt", return_value="retry transfer prompt", ), patch( @@ -239,8 +238,6 @@ class TestTransferFailedRetryButtons(unittest.TestCase): ) as logger, patch.object( chain, "post_message" ) as post_message: - history_port.return_value.get.return_value = history - chain.handle_failed_transfer_callback( callback_data="transfer_ai_retry_34", channel=NotificationChannel.Telegram, @@ -290,6 +287,9 @@ class TestTransferFailedRetryButtons(unittest.TestCase): media_id="123", errmsg=None, ) + chain.transfer_history_repository = SimpleNamespace( + get=lambda history_id: history + ) def _run_pending_coro(coro, *args, **kwargs): asyncio.run(coro) @@ -312,8 +312,6 @@ class TestTransferFailedRetryButtons(unittest.TestCase): settings, "AI_AGENT_ENABLE", True ): with patch( - "app.chain._transfer.get_chain_transfer_history_port" - ) as history_oper_cls, patch( "app.chain._transfer.build_manual_redo_prompt", side_effect=build_manual_redo_prompt, ), patch( @@ -323,7 +321,6 @@ class TestTransferFailedRetryButtons(unittest.TestCase): get_registry.return_value.submit_threadsafe.side_effect = ( _run_pending_coro ) - history_oper_cls.return_value.get.return_value = history with patch.object(chain, "post_message"), patch.object( chain, "async_post_message", side_effect=fake_async_post_message ): diff --git a/tests/test_transfer_job_manager.py b/tests/test_transfer_job_manager.py index f73bff5f5..0a6723cca 100644 --- a/tests/test_transfer_job_manager.py +++ b/tests/test_transfer_job_manager.py @@ -162,6 +162,9 @@ def make_task(episode: int, season: int = 1) -> TransferTask: def make_transfer_chain() -> TransferChain: """构造带内存 durable admission 契约的整理链测试骨架。""" chain = object.__new__(TransferChain) + chain.transfer_history_repository = MagicMock() + chain.download_history_repository = MagicMock() + chain.transfer_execution_repository = MagicMock() chain.jobview = JobManager() chain._media_exts = settings.RMT_MEDIAEXT chain._subtitle_exts = settings.RMT_SUBEXT @@ -617,10 +620,9 @@ class TransferJobManagerTest(unittest.TestCase): need_notify=False, ) bind_terminal_checkpoint(task, transferinfo) + chain.transfer_history_repository = SimpleNamespace() with patch( - "app.chain.transfer.get_chain_transfer_history_port", return_value=SimpleNamespace() - ), patch( "app.chain.transfer.add_transfer_success", lambda **kwargs: SimpleNamespace(id=1), ): @@ -664,10 +666,10 @@ class TransferJobManagerTest(unittest.TestCase): get_by_path=lambda path: None, ) system_config_oper = SimpleNamespace(get=lambda key: None) + chain.transfer_history_repository = transfer_history_oper + chain.download_history_repository = download_history_oper - with patch("app.chain.transfer.get_chain_transfer_history_port", return_value=transfer_history_oper), \ - patch("app.chain.transfer.get_chain_download_history_port", return_value=download_history_oper), \ - patch("app.chain.transfer.get_configured_system_config", return_value=system_config_oper), \ + with patch("app.chain.transfer.get_configured_system_config", return_value=system_config_oper), \ patch("app.chain.transfer.MetaInfoPath", lambda *args, **kwargs: FakeMeta(14)): state, errmsg = chain.do_transfer( fileitem=source_fileitem, @@ -838,11 +840,9 @@ class TransferJobManagerTest(unittest.TestCase): get_success_by_src=lambda src, storage=None: history, ) system_config_oper = SimpleNamespace(get=lambda key: None) + chain.transfer_history_repository = transfer_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=system_config_oper, ): @@ -906,14 +906,10 @@ class TransferJobManagerTest(unittest.TestCase): system_config_oper = SimpleNamespace(get=lambda key: None) _reset_failed_retries(fileitem.path, fileitem.storage) + chain.transfer_history_repository = transfer_history_oper + chain.download_history_repository = download_history_oper try: with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( - "app.chain.transfer.get_chain_download_history_port", - return_value=download_history_oper, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=system_config_oper, ): @@ -986,13 +982,9 @@ class TransferJobManagerTest(unittest.TestCase): settings, "TRANSFER_MAX_FAILED_RETRIES", 1, ): record_transfer_failure(fileitem.path, fileitem.storage) + chain.transfer_history_repository = transfer_history_oper + chain.download_history_repository = download_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( - "app.chain.transfer.get_chain_download_history_port", - return_value=download_history_oper, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=system_config_oper, ): @@ -1043,10 +1035,8 @@ class TransferJobManagerTest(unittest.TestCase): ) bind_terminal_checkpoint(task, failed_transferinfo) failed_history_oper = SimpleNamespace() + chain.transfer_history_repository = failed_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=failed_history_oper, - ), patch( "app.chain.transfer.add_transfer_fail", lambda **kwargs: SimpleNamespace(id=1), ), patch( @@ -1084,9 +1074,8 @@ class TransferJobManagerTest(unittest.TestCase): need_notify=False, ) bind_terminal_checkpoint(task, success_transferinfo) + chain.transfer_history_repository = SimpleNamespace() with patch( - "app.chain.transfer.get_chain_transfer_history_port", return_value=SimpleNamespace() - ), patch( "app.chain.transfer.add_transfer_success", lambda **kwargs: SimpleNamespace(id=2), ): @@ -1114,11 +1103,9 @@ class TransferJobManagerTest(unittest.TestCase): self.assertTrue(chain.jobview.add_task(task)) transfer_history_oper = SimpleNamespace() + chain.transfer_history_repository = transfer_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( "app.chain.transfer.add_transfer_fail", lambda **kwargs: SimpleNamespace(id=1), ), patch( @@ -1155,11 +1142,9 @@ class TransferJobManagerTest(unittest.TestCase): task.downloader = "qbittorrent" task.download_hash = "abc123" self.assertTrue(chain.jobview.add_task(task)) + chain.transfer_history_repository = SimpleNamespace() with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=SimpleNamespace(), - ), patch( "app.chain.transfer.add_transfer_fail", lambda **kwargs: None, ), patch( @@ -1190,11 +1175,9 @@ class TransferJobManagerTest(unittest.TestCase): task.downloader = "qbittorrent" task.download_hash = "abc123" self.assertTrue(chain.jobview.add_task(task)) + chain.transfer_history_repository = SimpleNamespace() with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=SimpleNamespace(), - ), patch( "app.chain.transfer.add_transfer_fail", lambda **kwargs: SimpleNamespace(id=77), ), patch( @@ -1252,14 +1235,10 @@ class TransferJobManagerTest(unittest.TestCase): subtitle_fileitem, ], ) + chain.transfer_history_repository = transfer_history_oper + chain.download_history_repository = download_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( - "app.chain.transfer.get_chain_download_history_port", - return_value=download_history_oper, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=system_config_oper, ), patch( @@ -1351,14 +1330,10 @@ class TransferJobManagerTest(unittest.TestCase): ) system_config_oper = SimpleNamespace(get=lambda key: None) storage_chain = SimpleNamespace(get_item=lambda fileitem: subtitle_fileitem) + chain.transfer_history_repository = transfer_history_oper + chain.download_history_repository = download_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( - "app.chain.transfer.get_chain_download_history_port", - return_value=download_history_oper, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=system_config_oper, ), patch( @@ -1432,14 +1407,10 @@ class TransferJobManagerTest(unittest.TestCase): subtitle_fileitem, ], ) + chain.transfer_history_repository = transfer_history_oper + chain.download_history_repository = download_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( - "app.chain.transfer.get_chain_download_history_port", - return_value=download_history_oper, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=system_config_oper, ), patch( @@ -1537,14 +1508,10 @@ class TransferJobManagerTest(unittest.TestCase): get_parent_item=lambda fileitem: parent_fileitem, list_files=fake_list_files, ) + chain.transfer_history_repository = transfer_history_oper + chain.download_history_repository = download_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( - "app.chain.transfer.get_chain_download_history_port", - return_value=download_history_oper, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=system_config_oper, ), patch( @@ -1635,10 +1602,9 @@ class TransferJobManagerTest(unittest.TestCase): need_notify=False, ), ] + chain.transfer_history_repository = SimpleNamespace() with patch( - "app.chain.transfer.get_chain_transfer_history_port", return_value=SimpleNamespace() - ), patch( "app.chain.transfer.add_transfer_success", lambda **kwargs: SimpleNamespace(id=1), ), patch( @@ -1703,10 +1669,9 @@ class TransferJobManagerTest(unittest.TestCase): need_notify=False, ) bind_terminal_checkpoint(task, transferinfo) + chain.transfer_history_repository = SimpleNamespace() with patch( - "app.chain.transfer.get_chain_transfer_history_port", return_value=SimpleNamespace() - ), patch( "app.chain.transfer.add_transfer_success", lambda **kwargs: SimpleNamespace(id=1), ), patch( diff --git a/tests/test_transfer_legacy_terminal_compat.py b/tests/test_transfer_legacy_terminal_compat.py index a86586ab2..1fad69788 100644 --- a/tests/test_transfer_legacy_terminal_compat.py +++ b/tests/test_transfer_legacy_terminal_compat.py @@ -2,7 +2,7 @@ import threading from types import SimpleNamespace -from unittest.mock import Mock, patch +from unittest.mock import Mock from app.application.history import TransferHistorySnapshot from app.application.transfer.execution import ( @@ -55,6 +55,10 @@ def _result(task, *, success: bool, overwrite_skipped: bool = False) -> Transfer def _compat_chain(result_factory): """构造只执行旧同步命令和 task-aware 结算的 TransferChain 骨架。""" chain = object.__new__(TransferChain) + chain.transfer_history_repository = SimpleNamespace( + get_by_src=lambda _src, storage=None: None + ) + chain.transfer_execution_repository = Mock() chain._worker_owner_id = "compat-owner" chain._owned_leases = {} chain._queued_lease_tokens = set() @@ -234,11 +238,8 @@ def test_legacy_overwrite_skip_binds_existing_success_in_atomic_writer() -> None history_port = SimpleNamespace( get_by_src=lambda _src, storage=None: success_history, ) - with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=history_port, - ): - returned = _invoke(chain, _fileitem()) + chain.transfer_history_repository = history_port + returned = _invoke(chain, _fileitem()) assert returned.success is False assert returned.overwrite_skipped is True @@ -261,12 +262,8 @@ def test_legacy_overwrite_skip_without_success_history_settles_failed() -> None: history_port = SimpleNamespace( get_by_src=lambda _src, storage=None: None, ) - - with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=history_port, - ): - returned = _invoke(chain, _fileitem()) + chain.transfer_history_repository = history_port + returned = _invoke(chain, _fileitem()) assert returned.success is False assert returned.overwrite_skipped is True diff --git a/tests/test_transfer_manual_review_api.py b/tests/test_transfer_manual_review_api.py index 111c5b5d1..9ad91359b 100644 --- a/tests/test_transfer_manual_review_api.py +++ b/tests/test_transfer_manual_review_api.py @@ -42,15 +42,10 @@ class _ManualReviewCommand: def _install_command(monkeypatch) -> object: - """安装不接触数据库的人工复核命令替身。""" + """构造不接触数据库的人工复核仓储并安装命令替身。""" repository = object() _ManualReviewCommand.calls = [] _ManualReviewCommand.error = None - monkeypatch.setattr( - transfer_endpoint, - "get_chain_transfer_execution_port", - lambda: repository, - ) monkeypatch.setattr( transfer_endpoint, "TransferExecutionCommand", @@ -124,6 +119,7 @@ def test_manual_review_applied_wraps_result_and_hides_internal_state( result_payload={"dest_exists": True, "hash_match": True}, ), current_user=SimpleNamespace(name=" admin ", username="other", id=7), + repository=repository, ) assert _ManualReviewCommand.calls == [ @@ -155,7 +151,7 @@ def test_manual_review_applied_wraps_result_and_hides_internal_state( def test_manual_review_not_applied_uses_username_fallback(monkeypatch) -> None: """名称为空时应稳定回退到 username,并允许安全重新调度。""" - _install_command(monkeypatch) + repository = _install_command(monkeypatch) _ManualReviewCommand.result = SimpleNamespace( task_id="task-2", operation_id="op-2", @@ -172,6 +168,7 @@ def test_manual_review_not_applied_uses_username_fallback(monkeypatch) -> None: reason="确认源文件仍存在", ), current_user=SimpleNamespace(name="", username="reviewer", id=8), + repository=repository, ) assert _ManualReviewCommand.calls[0][1]["actor"] == "reviewer" @@ -182,7 +179,7 @@ def test_manual_review_not_applied_uses_username_fallback(monkeypatch) -> None: def test_manual_review_conflict_returns_http_409(monkeypatch) -> None: """重复或过期人工判定必须返回资源冲突而非伪成功。""" - _install_command(monkeypatch) + repository = _install_command(monkeypatch) _ManualReviewCommand.error = TransferExecutionConflictError("步骤已被判定") with pytest.raises(HTTPException) as error: @@ -194,6 +191,7 @@ def test_manual_review_conflict_returns_http_409(monkeypatch) -> None: reason="重复判定", ), current_user=SimpleNamespace(name=None, username=None, id=11), + repository=repository, ) assert error.value.status_code == 409 diff --git a/tests/test_transfer_manual_review_discovery.py b/tests/test_transfer_manual_review_discovery.py index f6f33eae7..5bf960253 100644 --- a/tests/test_transfer_manual_review_discovery.py +++ b/tests/test_transfer_manual_review_discovery.py @@ -199,17 +199,12 @@ def test_unknown_manual_review_is_discoverable_and_resumes_via_api( review_store, task_id=f"task-{decision}", ) - monkeypatch.setattr( - transfer_endpoint, - "get_chain_transfer_execution_port", - lambda: repository, - ) - listed = transfer_endpoint.list_transfer_manual_reviews( state_filter="manual_review", page=1, page_size=10, current_user=object(), + repository=repository, ) assert listed.data is not None assert listed.data.total == 1 @@ -239,6 +234,7 @@ def test_unknown_manual_review_is_discoverable_and_resumes_via_api( detail = transfer_endpoint.get_transfer_manual_review( task_id=f"task-{decision}", current_user=object(), + repository=repository, ) assert detail.data == discovered @@ -251,6 +247,7 @@ def test_unknown_manual_review_is_discoverable_and_resumes_via_api( result_payload=result_payload, ), current_user=SimpleNamespace(name="admin"), + repository=repository, ) assert resolved.data is not None assert resolved.data.state == "retry_wait" @@ -259,6 +256,7 @@ def test_unknown_manual_review_is_discoverable_and_resumes_via_api( waiting = transfer_endpoint.get_transfer_manual_review( task_id=f"task-{decision}", current_user=object(), + repository=repository, ) assert waiting.data is not None assert waiting.data.state == "retry_wait" @@ -268,6 +266,7 @@ def test_unknown_manual_review_is_discoverable_and_resumes_via_api( page=1, page_size=10, current_user=object(), + repository=repository, ) assert retry_page.data is not None assert [item.task_id for item in retry_page.data.items] == [f"task-{decision}"] diff --git a/tests/test_transfer_movie_collection.py b/tests/test_transfer_movie_collection.py index c412f27cd..4d33aad7a 100644 --- a/tests/test_transfer_movie_collection.py +++ b/tests/test_transfer_movie_collection.py @@ -106,11 +106,9 @@ def test_conflicting_download_history_recognizes_movie_by_file_meta(monkeypatch) migrate_task=lambda task: False, try_remove_job=lambda task: None, ) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_type_tmdbid=lambda **kwargs: None), + chain.transfer_history_repository = SimpleNamespace( + get_by_type_tmdbid=lambda **kwargs: None ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_type_tmdbid=lambda **kwargs: None)) monkeypatch.setattr( "app.chain.transfer.MediaChain", lambda: SimpleNamespace( @@ -189,12 +187,10 @@ def test_movie_collection_conflict_only_drops_automatic_media( return True, "" chain._TransferChain__handle_transfer = fake_handle_transfer - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), + chain.transfer_history_repository = SimpleNamespace( + get_by_src=lambda src, storage=None: None ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr("app.chain.transfer.get_chain_download_history_port", lambda: history_oper) + chain.download_history_repository = history_oper monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), diff --git a/tests/test_transfer_overwrite_declined.py b/tests/test_transfer_overwrite_declined.py index 2e8a622ce..9ba43e035 100644 --- a/tests/test_transfer_overwrite_declined.py +++ b/tests/test_transfer_overwrite_declined.py @@ -242,11 +242,9 @@ def test_default_callback_skips_history_and_notification_when_overwrite_declined need_notify=False, ) bind_terminal_checkpoint(task, transferinfo) + chain.transfer_history_repository = transfer_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( "app.chain.transfer.add_transfer_fail", make_fail_recorder(add_fail_calls), ), patch( @@ -289,11 +287,9 @@ def test_default_callback_keeps_original_failure_semantics_without_success_histo need_notify=False, ) bind_terminal_checkpoint(task, transferinfo) + chain.transfer_history_repository = transfer_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( "app.chain.transfer.add_transfer_fail", make_fail_recorder(add_fail_calls), ), patch( @@ -350,10 +346,8 @@ def test_durable_callback_settles_overwrite_skip_without_history_as_failed(): ) chain.durable_event_writer.transfer_result.side_effect = durable_transfer_result + chain.transfer_history_repository = transfer_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( "app.chain.transfer.add_transfer_fail", make_fail_recorder(add_fail_calls), ), patch( @@ -405,10 +399,8 @@ def test_default_callback_delegates_primary_failure_to_durable_writer(): ) chain.durable_event_writer.transfer_result.side_effect = durable_transfer_result + chain.transfer_history_repository = transfer_history_oper with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=transfer_history_oper, - ), patch( "app.chain.transfer.add_transfer_fail", make_fail_recorder(add_fail_calls), ), patch( diff --git a/tests/test_transfer_planning_checkpoint.py b/tests/test_transfer_planning_checkpoint.py index 79296548d..51765eadf 100644 --- a/tests/test_transfer_planning_checkpoint.py +++ b/tests/test_transfer_planning_checkpoint.py @@ -335,6 +335,8 @@ class _ExecutionRepositoryStub: def _chain(*, repository=None, checkpoint=None, result=None) -> TransferChain: """构造只保留规划编排依赖的 TransferChain 骨架。""" chain = object.__new__(TransferChain) + chain.transfer_history_repository = Mock() + chain.transfer_execution_repository = Mock() chain._transfer_admissions = repository or Mock() chain._transfer_executions = _ExecutionRepositoryStub() chain.durable_event_writer = Mock() @@ -1558,10 +1560,7 @@ def test_accepted_replay_restores_explicit_context_without_online_lookup( execution_chain.eventmanager.send_event.return_value = None execution_chain.runtime_config = SimpleNamespace(scrape_follow_tmdb=True) execution_chain._TransferChain__finish_scrape_batch_task = Mock() - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: Mock(), - ) + execution_chain.transfer_history_repository = Mock() monkeypatch.setattr( "app.chain.transfer.MediaChain", Mock(side_effect=AssertionError("accepted replay 不应重新在线识别")), @@ -1655,10 +1654,7 @@ def test_accepted_replay_with_explicit_empty_episodes_stays_offline( execution_chain.eventmanager.send_event.return_value = None execution_chain.runtime_config = SimpleNamespace(scrape_follow_tmdb=True) execution_chain._TransferChain__finish_scrape_batch_task = Mock() - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: Mock(), - ) + execution_chain.transfer_history_repository = Mock() monkeypatch.setattr( "app.chain.transfer.MediaChain", Mock(side_effect=AssertionError("accepted replay 不应重新在线识别")), @@ -1771,10 +1767,7 @@ def test_pre_checkpoint_recognition_failure_records_retryable_error(monkeypatch) media_chain = Mock() media_chain.recognize_by_meta.return_value = None monkeypatch.setattr("app.chain.transfer.MediaChain", lambda: media_chain) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(), - ) + chain.transfer_history_repository = SimpleNamespace() record_transfer_failure = Mock() add_transfer_fail = Mock() monkeypatch.setattr( @@ -1820,10 +1813,7 @@ def test_recognition_rejection_without_writer_has_zero_terminal_side_effects( media_chain = Mock() media_chain.recognize_by_meta.return_value = None monkeypatch.setattr("app.chain.transfer.MediaChain", lambda: media_chain) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(), - ) + chain.transfer_history_repository = SimpleNamespace() record_transfer_failure = Mock() add_transfer_fail = Mock() monkeypatch.setattr( diff --git a/tests/test_transfer_queue_service.py b/tests/test_transfer_queue_service.py index 057625b85..8914f42b9 100644 --- a/tests/test_transfer_queue_service.py +++ b/tests/test_transfer_queue_service.py @@ -201,14 +201,10 @@ def test_do_transfer_reports_durable_admission_failure(): get_files_by_savepath=lambda _path: [], get_by_path=lambda _path: None, ) + chain.transfer_history_repository = no_history + chain.download_history_repository = no_download with patch( - "app.chain.transfer.get_chain_transfer_history_port", - return_value=no_history, - ), patch( - "app.chain.transfer.get_chain_download_history_port", - return_value=no_download, - ), patch( "app.chain.transfer.get_configured_system_config", return_value=SimpleNamespace(get=lambda _key: None), ): diff --git a/tests/test_transfer_sync_extra_files.py b/tests/test_transfer_sync_extra_files.py index 0c9947066..f88a8ffbb 100644 --- a/tests/test_transfer_sync_extra_files.py +++ b/tests/test_transfer_sync_extra_files.py @@ -54,6 +54,19 @@ def make_transfer_chain() -> TransferChain: return chain +def bind_empty_history_repositories(chain: TransferChain) -> None: + """为整理链绑定不命中任何记录的测试历史仓储。""" + chain.transfer_history_repository = SimpleNamespace( + get_by_src=lambda src, storage=None: None + ) + chain.download_history_repository = SimpleNamespace( + get_by_hash=lambda download_hash: None, + get_file_by_fullpath=lambda fullpath: None, + get_files_by_savepath=lambda savepath: [], + get_by_path=lambda path: None, + ) + + def make_fileitem(path: str) -> FileItem: """ 根据路径构造文件项。 @@ -134,20 +147,7 @@ def test_sync_extra_subtitle_inherits_matching_video_episode(monkeypatch): return FakeMeta(1) monkeypatch.setattr(chain, "_TransferChain__handle_transfer", fake_handle_transfer) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), - ) + bind_empty_history_repositories(chain) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), @@ -225,20 +225,7 @@ def test_single_subtitle_transfer_reuses_same_name_video_episode(monkeypatch): return FakeMeta(1) monkeypatch.setattr(chain, "_TransferChain__handle_transfer", fake_handle_transfer) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), - ) + bind_empty_history_repositories(chain) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), @@ -334,20 +321,7 @@ def test_single_video_transfer_lists_parent_once_for_same_name_extra(monkeypatch ] monkeypatch.setattr(chain, "_TransferChain__handle_transfer", fake_handle_transfer) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), - ) + bind_empty_history_repositories(chain) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), @@ -426,20 +400,7 @@ def test_episode_format_filters_extra_files_before_sync_planning(monkeypatch): return True, "" monkeypatch.setattr(chain, "_TransferChain__handle_transfer", fake_handle_transfer) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), - ) + bind_empty_history_repositories(chain) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), @@ -507,20 +468,7 @@ def test_episode_format_keeps_matching_extra_files_following_main(monkeypatch): return True, "" monkeypatch.setattr(chain, "_TransferChain__handle_transfer", fake_handle_transfer) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), - ) + bind_empty_history_repositories(chain) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), @@ -597,20 +545,7 @@ def test_single_matching_subtitle_uses_unmatched_video_only_as_context(monkeypat return FakeMeta(1) monkeypatch.setattr(chain, "_TransferChain__handle_transfer", fake_handle_transfer) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), - ) + bind_empty_history_repositories(chain) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), @@ -691,20 +626,7 @@ def test_cleanup_dest_fileitem_is_checkpointed_only_after_allowed_items_exist(mo return True, "" monkeypatch.setattr(chain, "_TransferChain__handle_transfer", fake_handle_transfer) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace(get_by_src=lambda src, storage=None: None)) - monkeypatch.setattr( - "app.chain.transfer.get_chain_download_history_port", - lambda: SimpleNamespace( - get_by_hash=lambda download_hash: None, - get_file_by_fullpath=lambda fullpath: None, - get_files_by_savepath=lambda savepath: [], - get_by_path=lambda path: None, - ), - ) + bind_empty_history_repositories(chain) monkeypatch.setattr( "app.chain.transfer.get_configured_system_config", lambda: SimpleNamespace(get=lambda key: None), diff --git a/tests/test_transfer_tmdb_category.py b/tests/test_transfer_tmdb_category.py index 0e811ffdc..293173728 100644 --- a/tests/test_transfer_tmdb_category.py +++ b/tests/test_transfer_tmdb_category.py @@ -116,11 +116,7 @@ def test_transfer_stops_when_automatic_category_has_no_tmdb_result(monkeypatch) chain._TransferChain__build_durable_step_runner = Mock( return_value=step_runner ) - monkeypatch.setattr( - "app.chain.transfer.get_chain_transfer_history_port", - lambda: SimpleNamespace(), - ) - monkeypatch.setattr("app.chain._transfer.get_chain_transfer_history_port", lambda: SimpleNamespace()) + chain.transfer_history_repository = SimpleNamespace() monkeypatch.setattr( "app.chain.transfer.MediaChain", lambda: SimpleNamespace( diff --git a/tests/test_workflow_runtime_config.py b/tests/test_workflow_runtime_config.py index 265165b4a..3b9f67d07 100644 --- a/tests/test_workflow_runtime_config.py +++ b/tests/test_workflow_runtime_config.py @@ -107,6 +107,12 @@ def test_add_subscribe_uses_superuser_from_chain_snapshot(monkeypatch): class FakeSubscribeChain: """记录订阅新增参数的测试替身。""" + subscription_repository = SimpleNamespace(get=lambda _sid: SimpleNamespace(to_dict=lambda: { + "id": 42, + "name": "Example", + "type": MediaType.MOVIE.value, + })) + def exists(self, _mediainfo): return False @@ -121,16 +127,6 @@ def test_add_subscribe_uses_superuser_from_chain_snapshot(monkeypatch): lambda: _runtime_config(superuser="snapshot-owner"), ) monkeypatch.setattr(add_subscribe_module.runtime_stop_state, "is_workflow_stopped", lambda _: False) - monkeypatch.setattr( - add_subscribe_module, - "get_chain_subscribe_port", - lambda: SimpleNamespace(get=lambda _sid: SimpleNamespace(to_dict=lambda: { - "id": 42, - "name": "Example", - "type": MediaType.MOVIE.value, - })), - ) - AddSubscribeAction("subscribe").execute( workflow_id=1, params={},