"""FastAPI 入口。"""

from __future__ import annotations

import asyncio
import contextvars
import json
import logging
import os
import re
import time
from collections import OrderedDict
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
from typing import TYPE_CHECKING

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api import chat, config, system
from app.config import settings
from app.core.exceptions import MoFixException
from app.middleware.error_handler import mofix_exception_handler
from app.services.chat_cancellation import current_chat_cancellation, user_interrupt_requested
from app.services.execution_outcome import explicit_failure_output
from commands.registry import Command, TriggerMode, cmd_registry

if TYPE_CHECKING:
    from app.tools.workflow import WorkflowExecutor

logger = logging.getLogger(__name__)


async def _drain_realtime_evaluation_tasks(timeout: float = 15.0) -> None:
    """关闭服务前等待终态评分及回调,避免进程退出时丢失最后一帧。"""
    from app.services import realtime_scorer

    deadline = asyncio.get_running_loop().time() + timeout
    while True:
        pending = {
            task for task in (
                *chat._finalize_tasks,
                *chat._failed_report_tasks,
                *realtime_scorer._scorer_tasks,
            ) if not task.done()
        }
        if not pending:
            return
        remaining = deadline - asyncio.get_running_loop().time()
        if remaining <= 0:
            logger.warning("realtime evaluation shutdown drain timed out: %d tasks pending", len(pending))
            return
        await asyncio.wait(pending, timeout=remaining, return_when=asyncio.FIRST_COMPLETED)


# 8s 心跳照常保活;正文长时间无新内容时每分钟显示一次实际执行状态。
_WORKFLOW_HEARTBEAT_RE = re.compile(r"> Claude Code 正在执行中\.\.\.(已等待 \d+s)")
_WORKFLOW_VISIBLE_HEARTBEAT_INTERVAL = 60.0


def _contains_not_implemented_json(obj, depth: int = 0) -> bool:
    """嵌套结构(PARALLEL/LOOP 的 list 结果)里搜 JSON 骨架 status 字段。"""
    if depth > 4:
        return False
    if isinstance(obj, dict):
        return obj.get("status") == "not_implemented" or any(
            _contains_not_implemented_json(v, depth + 1) for v in obj.values()
        )
    if isinstance(obj, (list, tuple)):
        return any(_contains_not_implemented_json(v, depth + 1) for v in obj)
    if isinstance(obj, str):
        try:
            parsed = json.loads(obj)
        except Exception:
            return False
        return _contains_not_implemented_json(parsed, depth + 1)
    return False


# 标记后的 claude_skill 内容是面向用户的最终结果
_CLAUDE_SKILL_FINAL_RESULT_MARKER = "**最终结果**:"


def _extract_claude_skill_final_result(result: object) -> str:
    """从 claude_skill 步骤结果里取「**最终结果**:」之后的交付正文;无标记返回空。"""
    if not isinstance(result, str):
        result = str(result)
    idx = result.rfind(_CLAUDE_SKILL_FINAL_RESULT_MARKER)
    if idx < 0:
        return ""
    text = result[idx + len(_CLAUDE_SKILL_FINAL_RESULT_MARKER):].strip()
    return text


# workflow 协作式中断路由:c_id → 运行中的 WorkflowExecutor,interrupt 找到后走正常收尾
_workflow_interrupt_registry: dict[str, "WorkflowExecutor"] = {}


def _workflow_interrupt_targets() -> dict[str, "WorkflowExecutor"]:
    """/v1/chat/interrupt 分派用;隔离为函数避免 api↔main 循环导入。"""
    return _workflow_interrupt_registry


# 并发 /workflow 各链路读到自己的中断旗标(contextvar 隔离,替代旧模块级 global)
_last_workflow_interrupted: contextvars.ContextVar = contextvars.ContextVar(
    "last_workflow_interrupted", default=False,
)


def _stream_cancel_reason() -> str:
    """读取聊天流外层超时标记;主服务单独运行时回退为连接中断。"""
    try:
        from app.services.chat_service import _stream_cancel_reason as reason

        return reason()
    except Exception:
        return "连接中断"


async def _stream_workflow_progress(
    execution_task: asyncio.Task,
    progress_queue: asyncio.Queue[dict],
) -> AsyncIterator[str]:
    """Stream workflow progress and cancel the DAG when the client disconnects."""
    last_visible_at = time.monotonic()
    try:
        while not execution_task.done() or not progress_queue.empty():
            try:
                event = await asyncio.wait_for(progress_queue.get(), timeout=0.5)
                event_type = event["event"]
                if event_type == "step_start":
                    last_visible_at = time.monotonic()
                    yield (
                        f"\n**[RUNNING] {event['step']}** "
                        f"(id: {event['id']}, type: {event['type']})\n"
                    )
                elif event_type == "step_output":
                    # 子代理输出全量进正文;长时间无正文时稀疏显示真实心跳。
                    chunk = event.get("chunk", "")
                    if event.get("kind") == "progress" and _WORKFLOW_HEARTBEAT_RE.fullmatch(chunk.strip()):
                        now = time.monotonic()
                        if now - last_visible_at >= _WORKFLOW_VISIBLE_HEARTBEAT_INTERVAL:
                            last_visible_at = now
                            yield chunk
                        continue
                    if not chunk:
                        yield ": wf-activity\n\n"
                        continue
                    last_visible_at = time.monotonic()
                    yield chunk
                elif event_type in {"tool_event", "plan_updated"}:
                    yield ": wf-activity\n\n"
                elif event_type == "step_end":
                    last_visible_at = time.monotonic()
                    ok = event["status"] == "completed"
                    icon = "PASS" if ok else "FAIL"
                    tail = "完成" if ok else f"失败: {event.get('error', '')}"
                    step_id = f" (id: {event['id']})" if event.get("id") else ""
                    yield f"\n**[{icon}] {event['step']}**{step_id} {tail}\n"
                elif event_type == "step_retry":
                    last_visible_at = time.monotonic()
                    yield (
                        f"**[RETRY] {event['step']}** (id: {event['id']}) "
                        f"第{event['attempt']}次重试\n"
                    )
            except asyncio.TimeoutError:
                pass
    finally:
        if not execution_task.done():
            execution_task.cancel()
            try:
                await execution_task
            except asyncio.CancelledError:
                pass


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期:注册命令、启动时初始化、关闭时清理。"""
    realtime_scorer_recovery_task: asyncio.Task | None = None
    if settings.realtime_eval_enabled is True:
        from app.services.realtime_scorer import recover_realtime_scorer

        realtime_scorer_recovery_task = asyncio.create_task(recover_realtime_scorer())

    # settings 是看板配置的唯一来源,覆盖镜像中的遗留环境变量
    os.environ["WORKFLOW_DASHBOARD_ENABLED"] = str(settings.workflow_dashboard_enabled).lower()
    os.environ["WORKFLOW_DASHBOARD_HOST"] = settings.workflow_dashboard_host
    os.environ["WORKFLOW_DASHBOARD_HTTP_PORT"] = str(settings.workflow_dashboard_http_port)
    os.environ["WORKFLOW_DASHBOARD_WS_PORT"] = str(settings.workflow_dashboard_ws_port)
    os.environ["WORKFLOW_DASHBOARD_WS_CONNECT"] = settings.workflow_dashboard_ws_connect
    os.environ["WORKFLOW_DASHBOARD_MAX_SNAPSHOT"] = str(settings.workflow_dashboard_max_snapshot)
    if settings.workflow_dashboard_history_dir:
        os.environ["WORKFLOW_DASHBOARD_HISTORY_DIR"] = settings.workflow_dashboard_history_dir
    if settings.workflow_dashboard_token:
        os.environ["WORKFLOW_DASHBOARD_TOKEN"] = settings.workflow_dashboard_token

    # 主服务启动即拉起看板,避免容器重启后的懒启动空窗;lifespan 退出时同步释放
    dashboard_server = None
    dashboard_start_task: asyncio.Task | None = None
    if settings.workflow_dashboard_enabled:
        from app.model_agent.dashboard.config import DashboardConfig
        from app.model_agent.dashboard.server import DashboardServer

        dashboard_server = DashboardServer.get_instance(DashboardConfig.from_env())

        async def _start_dashboard() -> None:
            try:
                start = getattr(dashboard_server, "start_background", dashboard_server.start)
                await start()
            except Exception as exc:
                print(f"[dashboard] 启动失败(不影响主服务): {exc}")

        dashboard_start_task = asyncio.create_task(_start_dashboard())

    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools.claude_tools import (
        CommandOutput,
        stream_claude_skill,
        stream_claude_skill_output,
    )

    async def _relay(gen: AsyncIterator) -> AsyncIterator:
        """外层 aclose 不传导内层,靠 GC 关会让 finish 延迟、看板停在 running。"""
        try:
            async for chunk in gen:
                yield chunk
        finally:
            await gen.aclose()

    interrupted_results: OrderedDict[tuple[str, int], tuple[float, str]] = OrderedDict()

    def _cache_interrupted_result(invocation, result: str) -> None:
        if invocation is None:
            return
        now = time.monotonic()
        for key, (saved_at, _) in list(interrupted_results.items()):
            if now - saved_at > 3600:
                interrupted_results.pop(key, None)
        key = (invocation.c_id, invocation.generation)
        interrupted_results[key] = (now, result)
        interrupted_results.move_to_end(key)
        while len(interrupted_results) > 128:
            interrupted_results.popitem(last=False)

    def _claim_interrupted_result(command_name: str, c_id: str | None, args: str):
        session = direct_command_sessions.get_for_continuation(c_id, args)
        if session is None or session.command_name != command_name:
            return None
        claimed = direct_command_sessions.claim_for_continuation(c_id, args, command_name)
        if claimed is None:
            return None
        key = (claimed.c_id, claimed.generation)
        cached = interrupted_results.get(key)
        result = cached[1] if cached is not None and time.monotonic() - cached[0] <= 3600 else None
        return claimed, result, key

    def _release_when_worker_finishes(worker: asyncio.Task, release, collect=None) -> None:
        def _settled(done: asyncio.Task) -> None:
            try:
                if collect is not None:
                    collect(done)
                else:
                    done.result()
            except asyncio.CancelledError:
                pass
            except Exception:
                logger.exception("Detached command worker failed")
            try:
                release()
            except Exception:
                logger.exception("Detached command session cleanup failed")

        worker.add_done_callback(_settled)

    async def _invoke_blocking_tool(
        tool, payload: dict, on_cancel=None, on_settled=None, on_late_result=None,
    ) -> str:
        """Cancel the response promptly while retaining a live worker's session."""
        worker = asyncio.create_task(asyncio.to_thread(tool.invoke, payload))
        try:
            return await asyncio.shield(worker)
        except asyncio.CancelledError:
            _release_when_worker_finishes(
                worker, on_settled or (lambda: None), on_late_result,
            )
            if on_cancel is not None:
                try:
                    on_cancel()
                except Exception:
                    logger.exception("Blocking command cancellation reporting failed")
            raise

    async def _stream_resumable_command(
        command_name: str,
        skill_name: str,
        args: str,
        c_id: str | None,
    ) -> AsyncIterator[str | CommandOutput]:
        """Run or resume one direct Claude command without sharing user state.

        A new slash command replaces the prior entry for its ``c_id``. An exact
        continuation request reuses the SDK session ID captured from the first
        turn. The store is TTL/capacity bounded and never contains response or
        tool-output history.
        """
        continuation = direct_command_sessions.get_for_continuation(c_id, args)
        if continuation is not None and continuation.command_name == command_name:
            invocation = direct_command_sessions.claim_for_continuation(
                c_id, args, command_name,
            )
            if invocation is None:
                yield CommandOutput(
                    content=f"/{command_name} 当前仍在执行,请等待本轮完成。",
                    is_error=True,
                )
                return
            if not invocation.session_id:
                direct_command_sessions.release(
                    c_id, command_name, invocation.generation,
                )
                yield CommandOutput(
                    content=(
                        f"上次 /{command_name} 未获得可恢复的 Claude 会话,"
                        f"为避免重复执行,请重新发送完整 /{command_name} 命令。"
                    ),
                    is_error=True,
                )
                return
            effective_skill = invocation.skill_name
            resume_session_id = invocation.session_id
        else:
            invocation = direct_command_sessions.begin(
                c_id, command_name, skill_name, task_digest=args,
            )
            if c_id and invocation is None:
                yield CommandOutput(
                    content=f"/{command_name} 当前仍在执行,已拒绝并发启动同一会话的新任务。",
                    is_error=True,
                )
                return
            effective_skill = skill_name
            resume_session_id = None

        def _remember_session(session_id: str) -> None:
            if invocation is None:
                return
            direct_command_sessions.update_session_id(
                c_id,
                command_name,
                invocation.generation,
                session_id,
            )

        try:
            from app.services.command_dashboard import safe_report_command as report_command
            # Continuation text is a control signal, not a new task title.  Keep
            # the original bounded digest so the dashboard/history stays tied to
            # the real request instead of showing titles such as "继续(续)".
            digest = args if resume_session_id is None else (continuation.task_digest or args)
            reporter = report_command(
                command_name,
                digest,
                c_id=c_id or "",
                continuation_input=args if resume_session_id is not None else "",
            )
        except Exception:
            logger.exception("Command dashboard initialization failed")
            reporter = None

        err: str | None = None
        awaiting_user = False
        awaiting_resume = False
        dashboard_output_failed = False
        skill_stream = stream_claude_skill_output(
            effective_skill,
            args,
            resume_session_id=resume_session_id,
            on_session_id=_remember_session if invocation is not None else None,
        )
        try:
            async for chunk in skill_stream:
                if invocation is not None:
                    direct_command_sessions.refresh_execution(
                        c_id, command_name, invocation.generation,
                    )
                if reporter is not None and not dashboard_output_failed:
                    try:
                        reporter.on_output(chunk)
                    except Exception:
                        logger.exception("Command dashboard output reporting failed")
                        dashboard_output_failed = True
                # 只认 AskUserQuestion 提问帧锚(正文含"需要补充"四字会误伤正常成功收尾)
                if isinstance(chunk, CommandOutput) and (
                    "需要补充以下信息" in chunk.content or "需要补充信息" in chunk.content
                ):
                    awaiting_user = True
                if isinstance(chunk, CommandOutput) and chunk.requires_resume:
                    awaiting_resume = True
                elif isinstance(chunk, CommandOutput) and chunk.is_error and err is None:
                    err = chunk.content or "命令执行失败"
                yield chunk
        except (asyncio.CancelledError, GeneratorExit):
            err = "用户中断" if user_interrupt_requested() else "连接中断"
            raise
        except Exception as e:
            err = str(e)
            raise
        finally:
            try:
                await skill_stream.aclose()
            finally:
                try:
                    if reporter is not None:
                        if awaiting_resume:
                            reporter.finish(
                                err,
                                awaiting_user=awaiting_user,
                                awaiting_resume=True,
                            )
                        else:
                            reporter.finish(err, awaiting_user=awaiting_user)
                except Exception:
                    logger.exception("Command dashboard finalization failed")
                finally:
                    if invocation is not None:
                        direct_command_sessions.release(
                            c_id, command_name, invocation.generation,
                        )

    # 注册 /claude 命令
    async def claude_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        from app.tools.claude_tools import _resolve_skill_name

        continuation = direct_command_sessions.get_for_continuation(c_id, args)
        if continuation is not None and continuation.command_name != "claude":
            continuation = None
        parts = args.split(maxsplit=1)
        if continuation:
            skill_name, prompt = continuation.skill_name, args
        elif parts and _resolve_skill_name(parts[0]) is not None:
            skill_name, prompt = parts[0], parts[1] if len(parts) > 1 else ""
        else:
            skill_name, prompt = "", args
        inner = _relay(_stream_resumable_command(
            "claude", skill_name, prompt, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[claude-code] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="claude",
            description="调用 Claude Code Skill 执行昇腾模型适配、验证、优化等深度任务",
            trigger_modes=[
                TriggerMode.USER_TRIGGER,
                TriggerMode.LLM_RECOMMEND,
                TriggerMode.LLM_AUTO,
            ],
            handler=claude_handler,
            example="/claude verify-agent 帮我验证 Qwen3-8B 在 A2 上的适配",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /verify 命令:固定调用 verify-agent skill
    async def verify_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_stream_resumable_command(
            "verify", "verify-agent", args, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[verify] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="verify",
            description="调用 Claude Code verify-agent Skill 执行昇腾模型适配验证",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=verify_handler,
            example="/verify 帮我验证 Qwen3-8B 在 A2 上的适配",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /adapt 命令:固定调用 adapt-agent skill
    async def adapt_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_stream_resumable_command(
            "adapt", "adapt-agent", args, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[adapt] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="adapt",
            description="调用 Claude Code adapt-agent Skill 执行昇腾模型适配",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=adapt_handler,
            example="/adapt 帮我适配 Qwen3-8B 到 A2 并使用 vLLM-Ascend",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /optimize 命令:固定调用 optimizer-agent skill
    async def optimize_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_stream_resumable_command(
            "optimize", "optimizer-agent", args, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[optimize] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="optimize",
            description="调用 Claude Code optimizer-agent Skill 执行 vLLM-Ascend 性能调优",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=optimize_handler,
            example="/optimize 帮我优化 Qwen3-8B 在 A2 上的推理性能",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /quantify 命令:固定调用 quantify-agent skill
    async def quantify_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_stream_resumable_command(
            "quantify", "quantify-agent", args, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[quantify] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="quantify",
            description="调用 Claude Code quantify-agent Skill 执行昇腾推理工具链量化",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=quantify_handler,
            example="/quantify 帮我量化 Qwen3-8B 用于昇腾推理",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /commit 命令:固定调用 gitcode-publish skill
    async def commit_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_stream_resumable_command(
            "commit", "gitcode-publish", args, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[commit] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="commit",
            description="调用 Claude Code gitcode-publish Skill 执行代码发布与提交",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=commit_handler,
            example="/commit 帮我发布当前代码变更到 GitCode",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /search 命令:调用 search_tools
    from app.tools.search_tools import search_ascend_models

    async def search_handler(args: str, c_id: str | None = None) -> AsyncIterator[str]:
        from app.services.command_dashboard import safe_report_command as report_command

        # /search 携带明确 Skill 调用时,按用户指定的执行任务处理。
        if re.search(r"(?:请调用|调用|call|invoke|please)\s*[`'\"]?invoke_claude_skill\b", args, re.IGNORECASE):
            match = re.search(r"\bskill_name\s*=\s*['\"]?([A-Za-z][A-Za-z0-9_-]*)", args, re.IGNORECASE)
            if match:
                from app.tools.claude_tools import _resolve_skill_name

                skill_name = _resolve_skill_name(match.group(1))
                if skill_name is not None:
                    inner = _relay(_stream_resumable_command("search", skill_name, args, c_id))
                    try:
                        async for chunk in inner:
                            yield chunk
                    finally:
                        await inner.aclose()
                    return

        continued = _claim_interrupted_result("search", c_id, args)
        if continued is not None:
            previous, result, key = continued
            delivered = False
            try:
                if result is None:
                    yield "上次 /search 的执行结果已过期,请重新发送完整搜索命令。"
                    return
                reporter = report_command(
                    "search", previous.task_digest or args,
                    c_id=c_id or "", continuation_input=args,
                )
                if reporter is not None:
                    reporter.on_output(result)
                yield result
                if reporter is not None:
                    reporter.finish(error=explicit_failure_output(result) or None)
                delivered = True
                return
            finally:
                direct_command_sessions.release(c_id, "search", previous.generation)
                if delivered or result is None:
                    interrupted_results.pop(key, None)
                    direct_command_sessions.clear_if_idle(c_id)

        invocation = direct_command_sessions.begin(
            c_id, "search", "search", task_digest=args,
        )
        if c_id and invocation is None:
            yield "/search 当前仍在执行,请等待本轮结束后重试。"
            return
        detached = False

        def _release() -> None:
            if invocation is not None:
                direct_command_sessions.release(c_id, "search", invocation.generation)
                if not detached:
                    direct_command_sessions.clear_if_idle(c_id)

        try:
            reporter = report_command("search", args, c_id=c_id or "")
        except Exception:
            _release()
            raise
        error = None
        cancel_reported = False

        def _report_cancel() -> None:
            nonlocal cancel_reported
            if reporter is not None and not cancel_reported:
                cancel_reported = True
                reporter.finish(error=_stream_cancel_reason())

        def _on_worker_cancel() -> None:
            nonlocal detached
            detached = True
            _report_cancel()

        def _collect_late_result(done: asyncio.Task) -> None:
            try:
                result = done.result()
            except Exception as e:
                result = f"[search] 调用失败:{type(e).__name__}: {e}"
            _cache_interrupted_result(invocation, result)

        try:
            result = await _invoke_blocking_tool(
                search_ascend_models, {"input": args}, _on_worker_cancel, _release,
                _collect_late_result,
            )
        except (asyncio.CancelledError, GeneratorExit):
            _report_cancel()
            raise
        except Exception as e:
            error = f"[search] 调用失败:{type(e).__name__}: {e}"
            result = error
        finally:
            if not detached:
                _release()
        error = error or explicit_failure_output(result) or None
        if reporter is not None:
            reporter.on_output(result)
            reporter.finish(error=error)
        yield result

    cmd_registry.register(
        Command(
            name="search",
            description="调用 search-agent 从 GitCode 昇腾模型库搜索已适配模型",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=search_handler,
            example="/search Qwen3-14B 在 A2 上的适配",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /ai4s 命令:固定调用 ai4s-main skill
    async def ai4s_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_stream_resumable_command(
            "ai4s", "ai4s-main", args, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[ai4s] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="ai4s",
            description="调用 Claude Code ai4s-main Skill 处理 AI for Science 昇腾 NPU 任务(精度对齐、Profiling、性能调优、模型迁移等)",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=ai4s_handler,
            example="/ai4s 帮我将 Boltz2 模型迁移到昇腾 NPU 并做精度对齐",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /torch 命令:调用 PTA Helper,支持基于 c_id 的多轮对话记忆
    from app.tools.pta_tools import stream_pta_query

    async def pta_handler(args: str, c_id: str | None = None) -> AsyncIterator[str]:
        # 显式「继续」复用既有条目(不覆盖原任务摘要);新任务走 begin 替换。
        invocation = direct_command_sessions.claim_for_continuation(
            c_id, args, "torch",
        )
        resuming = invocation is not None
        if invocation is None:
            invocation = direct_command_sessions.begin(
                c_id, "torch", "torch", task_digest=args,
            )
            if c_id and invocation is None:
                yield CommandOutput(
                    content="/torch 当前仍在执行,已拒绝并发启动同一会话的新任务。",
                    is_error=True,
                )
                return

        def _release() -> None:
            if invocation is not None:
                direct_command_sessions.release(c_id, "torch", invocation.generation)

        detached = False

        def _on_worker_detached(worker: asyncio.Task) -> None:
            nonlocal detached
            detached = True
            _release_when_worker_finishes(worker, _release)

        cancellation = current_chat_cancellation.get()

        def _on_helper_started() -> None:
            if cancellation is not None:
                cancellation.execution_started = True

        # 将 c_id(会话 ID)透传给 stream_pta_query,使 PTA Helper 能读取并保存该会话的历史上下文。
        inner = _relay(stream_pta_query(
            args,
            thread_id=c_id,
            dashboard_task_digest=(invocation.task_digest if invocation is not None else "") or args,
            dashboard_continuation=resuming,
            on_worker_detached=_on_worker_detached,
            on_execution_started=_on_helper_started,
        ))
        try:
            async for chunk in inner:
                _on_helper_started()
                if invocation is not None:
                    direct_command_sessions.refresh_execution(
                        c_id, "torch", invocation.generation,
                    )
                yield chunk
        except Exception as e:
            yield f"[torch] 调用失败:{type(e).__name__}: {e}"
        finally:
            await inner.aclose()
            if not detached:
                # 完成后仅置 idle:保留条目与任务摘要供后续续跑/普通聊天桥接(get_recent_task_context);换话题由普通聊天路径 clear_if_idle 清除。
                _release()

    cmd_registry.register(
        Command(
            name="torch",
            description="TorchNPU 问题接口:执行 PyTorch-Ascend (torch_npu) 流式问答,支持同一会话多轮记忆",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=pta_handler,
            example="/torch torchair 编译流程是什么",
            requires_args=True,
            # PTA Helper 按 session_id 自带多轮记忆,显式「继续」可安全重入
            supports_continuation=True,
        )
    )

    # 注册 /deploy 命令:直接通过 Claude 执行部署相关 prompt
    async def deploy_handler(args: str, c_id: str | None = None) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_stream_resumable_command(
            "deploy", "", args, c_id,
        ))
        try:
            async for chunk in inner:
                yield chunk
        except Exception as e:
            yield CommandOutput(
                content=f"[deploy] 调用失败:{type(e).__name__}: {e}",
                is_error=True,
            )
        finally:
            await inner.aclose()

    cmd_registry.register(
        Command(
            name="deploy",
            description="直接通过 Claude 执行部署相关的 prompt",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=deploy_handler,
            example="/deploy 帮我部署 Boltz2 到昇腾 NPU",
            supports_continuation=True,
            requires_args=True,
        )
    )

    # 注册 /doc 命令:优先调用 doc-agent 工具,未匹配时回退到 Claude
    from app.tools.doc_tools import (
        doc_agent_example_qwen3_8b,
        doc_agent_example_qwen35_flow,
        doc_agent_generate_local,
        doc_agent_one_click_generate,
        doc_agent_sglang_adapter_docs,
        doc_agent_verl_adapter_docs,
        doc_agent_vllm_adapter_docs,
    )

    async def doc_handler(args: str, c_id: str | None = None) -> AsyncIterator[str]:
        from app.services.command_dashboard import safe_report_command as report_command

        continued = _claim_interrupted_result("doc", c_id, args)
        if continued is not None:
            previous, result, key = continued
            delivered = False
            reporter = None
            try:
                if result is None:
                    yield "上次 /doc 的执行结果已过期,请检查已有文件后重新发送完整命令。"
                    return
                reporter = report_command(
                    "doc", previous.task_digest or args,
                    c_id=c_id or "", continuation_input=args,
                )
                for line in result.splitlines(keepends=True):
                    if reporter is not None:
                        reporter.on_output(line)
                    yield line
                if reporter is not None:
                    reporter.finish(error=explicit_failure_output(result) or None)
                delivered = True
            except (asyncio.CancelledError, GeneratorExit):
                if reporter is not None:
                    reporter.finish(error=_stream_cancel_reason())
                raise
            finally:
                direct_command_sessions.release(c_id, "doc", previous.generation)
                if delivered or result is None:
                    interrupted_results.pop(key, None)
                    direct_command_sessions.clear_if_idle(c_id)
            return

        invocation = direct_command_sessions.begin(
            c_id, "doc", "doc", task_digest=args,
        )
        if c_id and invocation is None:
            yield "/doc 当前仍在执行,请等待本轮结束后重试。"
            return
        detached = False

        def _release() -> None:
            if invocation is not None:
                direct_command_sessions.release(c_id, "doc", invocation.generation)
                if not detached:
                    direct_command_sessions.clear_if_idle(c_id)

        try:
            reporter = report_command("doc", args, c_id=c_id or "")
        except Exception:
            _release()
            raise
        parts = args.strip().split(maxsplit=1)
        sub = parts[0].lower() if parts else ""
        rest = parts[1] if len(parts) > 1 else ""

        result = ""
        error = None
        cancel_reported = False

        def _report_cancel() -> None:
            nonlocal cancel_reported
            if reporter is not None and not cancel_reported:
                cancel_reported = True
                reporter.finish(error=_stream_cancel_reason())

        def _on_worker_cancel() -> None:
            nonlocal detached
            detached = True
            _report_cancel()

        def _collect_late_result(done: asyncio.Task) -> None:
            try:
                result = done.result()
            except Exception as e:
                result = f"[doc] 调用失败:{type(e).__name__}: {e}"
            _cache_interrupted_result(invocation, result)

        try:
            try:
                if sub in ("vllm", "vllm-ascend"):
                    result = await _invoke_blocking_tool(doc_agent_vllm_adapter_docs, {}, _on_worker_cancel, _release, _collect_late_result)
                elif sub in ("sglang",):
                    result = await _invoke_blocking_tool(doc_agent_sglang_adapter_docs, {}, _on_worker_cancel, _release, _collect_late_result)
                elif sub in ("verl",):
                    result = await _invoke_blocking_tool(doc_agent_verl_adapter_docs, {}, _on_worker_cancel, _release, _collect_late_result)
                elif sub in ("qwen3-8b", "qwen3_8b", "qwen38b"):
                    result = await _invoke_blocking_tool(doc_agent_example_qwen3_8b, {}, _on_worker_cancel, _release, _collect_late_result)
                elif sub in ("qwen3.5-27b", "qwen35", "qwen3.5"):
                    result = await _invoke_blocking_tool(doc_agent_example_qwen35_flow, {}, _on_worker_cancel, _release, _collect_late_result)
                elif sub in ("generate", "local"):
                    manifest = rest.strip() or "manifest.discovered.yaml"
                    result = await _invoke_blocking_tool(
                        doc_agent_generate_local, {"manifest_filename": manifest}, _on_worker_cancel, _release, _collect_late_result,
                    )
                elif sub in ("discover", "one-click", "one_click"):
                    result = await _invoke_blocking_tool(
                        doc_agent_one_click_generate, {"extra_args": rest}, _on_worker_cancel, _release, _collect_late_result,
                    )
                else:
                    # 不认识的子命令已在 chat_service 层透传给 LLM,此处不会走到
                    result = f"[doc] 未知子命令 `{sub}`。可用:vllm、sglang、verl、qwen3-8b、qwen3.5-27b、generate、discover"
            except Exception as e:
                error = f"[doc] 调用失败:{type(e).__name__}: {e}"
                result = error

            error = error or explicit_failure_output(result) or None
            # 同步结果需要模拟流式输出(按行分段)
            for line in result.splitlines(keepends=True):
                if reporter is not None:
                    reporter.on_output(line)
                yield line
        except (asyncio.CancelledError, GeneratorExit):
            _report_cancel()
            raise
        else:
            if reporter is not None:
                reporter.finish(error=error)
        finally:
            if not detached:
                _release()

    cmd_registry.register(
        Command(
            name="doc",
            description="调用 doc-agent 工具执行文档生成与查询:vllm/sglang/verl/qwen3-8b/qwen3.5-27b/generate/discover",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND, TriggerMode.LLM_AUTO],
            handler=doc_handler,
            example="/doc vllm    | /doc qwen3-8b    | /doc generate    | /doc discover --only Qwen3.5-27B",
            supports_continuation=True,
        )
    )

    # 注册 /workflow 命令:使用 Dynamic Workflow Engine(LLM 规划 + DAG 执行)
    from app.tools.workflow import DynamicPlanner, WorkflowExecutor
    from app.tools.workflow.types import ExecutionContext, WorkflowPlan

    async def _format_plan_text(plan) -> str:
        """将 WorkflowPlan 格式化为可读文本。"""
        lines = [
            f"## Dynamic Workflow Plan",
            f"",
            f"**Goal**: {plan.goal or 'N/A'}",
            f"**Steps**: {len(plan.steps)}",
            f"**Max Concurrency**: {plan.max_concurrency}",
            f"**Verify Enabled**: {plan.verify_enabled}",
            f"",
            f"### Execution DAG ({len(plan.steps)} steps)",
            f"",
        ]
        for i, step in enumerate(plan.steps, 1):
            deps = ", ".join(step.depends_on) or "none"
            lines.append(f"  {i}. `{step.id}` **{step.name}** ({step.type.value})")
            lines.append(f"     → skill: `{step.skill_name or 'N/A'}`")
            lines.append(f"     → depends_on: [{deps}]")
            if step.type.value == "mcp_tool":
                mcp_server = step.params.get("mcp_server", "?")
                lines.append(f"     → mcp_server: `{mcp_server}`")
            if step.type.value == "parallel" and step.parallel_steps:
                for ps in step.parallel_steps:
                    lines.append(f"       · {ps.id}: {ps.name} ({ps.skill_name or 'N/A'})")
        return "\n".join(lines)

    async def _run_workflow(
        args: str, c_id: str | None = None, generation: int | None = None,
    ) -> AsyncIterator[str | CommandOutput]:
        # 每个请求持有自己的桥接与计划,后台图由服务端按 workflow_id 隔离。
        planning_plan = WorkflowPlan(intent=args, goal=args)
        from app.services.dashboard_bridge import DashboardBridge

        bridge = DashboardBridge()
        await bridge.start_planning(planning_plan.workflow_id, args, c_id=c_id)
        try:
            # Step 1: LLM 规划工作流
            yield "**AI 正在分析您的需求并规划工作流...**\n\n"
            planner = DynamicPlanner()
            bind_workflow_id = getattr(planner, "bind_workflow_id", None)
            if callable(bind_workflow_id):
                bind_workflow_id(planning_plan.workflow_id)
            plan = await planner.aplan(args)
        except (asyncio.CancelledError, GeneratorExit):
            bridge.finish_sync(
                planning_plan,
                user=user_interrupt_requested(),
                reason=_stream_cancel_reason(),
            )
            raise
        except Exception as exc:
            bridge.finish_sync(
                planning_plan,
                reason=f"工作流规划失败:{type(exc).__name__}: {exc}",
            )
            raise
        if generation is not None:
            direct_command_sessions.update_workflow_id(
                c_id, generation, plan.workflow_id,
            )
        await bridge.attach(plan, c_id=c_id)

        # attach 之后任何提前退出(断连 aclose)都必须收尾终帧,否则看板停在运行中
        try:
            # Step 2: 展示计划
            plan_text = await _format_plan_text(plan)
            yield plan_text
            yield "\n\n---\n\n"

            if not plan.steps:
                yield "未能生成工作流步骤,将直接处理您的需求。\n\n"
                try:
                    async for chunk in stream_claude_skill("", args):
                        yield chunk
                except (asyncio.CancelledError, GeneratorExit):
                    bridge.finish_sync(
                        plan,
                        user=user_interrupt_requested(),
                        reason=_stream_cancel_reason(),
                    )
                    raise
                except Exception as exc:
                    bridge.finish_sync(
                        plan,
                        reason=f"工作流回退执行失败:{type(exc).__name__}: {exc}",
                    )
                    raise
                await bridge.finish(
                    plan,
                    ExecutionContext(workflow_id=plan.workflow_id),
                )
                return

            # Step 3: DAG 执行(带进度回调,实时推送 SSE)
            yield "**开始执行工作流...**\n\n"

            progress_queue: asyncio.Queue[dict] = asyncio.Queue()

            async def _on_progress(event: dict):
                if generation is not None:
                    direct_command_sessions.refresh_execution(
                        c_id, "workflow", generation,
                    )
                await progress_queue.put(event)
                await bridge.on_progress(event)

            executor = WorkflowExecutor()
            # 注册到中断路由:interrupt 端点按 c_id 找到本执行器下协作式旗标
            if c_id:
                _workflow_interrupt_registry[c_id] = executor
                plan.ctx_c_id = c_id  # checkpoint 记录归属会话,续跑按 c_id 精确匹配

            # 启动后台执行任务
            cancellation = current_chat_cancellation.get()
            if cancellation is not None:
                cancellation.execution_started = True
            execution_task = asyncio.create_task(
                executor.execute(plan, _on_progress)
            )
        except (asyncio.CancelledError, GeneratorExit):
            bridge.finish_sync(
                plan,
                user=user_interrupt_requested(),
                reason=_stream_cancel_reason(),
            )
            raise
        except Exception as exc:
            bridge.finish_sync(
                plan,
                reason=f"执行异常:{type(exc).__name__}",
            )
            raise

        try:
            async for progress_chunk in _stream_workflow_progress(
                execution_task,
                progress_queue,
            ):
                yield progress_chunk
            ctx = await execution_task
        except (asyncio.CancelledError, GeneratorExit):
            # 断连/停止收尾;旗标已请求的归用户中断,其余异常中断
            if not execution_task.done():
                execution_task.cancel()
                try:
                    await execution_task
                except (asyncio.CancelledError, Exception):
                    pass
            bridge.finish_sync(
                plan,
                user=executor.interrupt_requested,
                reason=_stream_cancel_reason(),
            )
            raise
        except Exception as exc:
            # executor 自身异常时 execution_task 已 done,进度流 finally 不会取消它;必须显式补 workflow.failed,否则节点会永久挂起
            bridge.finish_sync(
                plan,
                user=False,
                reason=f"执行异常:{type(exc).__name__}",
            )
            raise
        finally:
            _last_workflow_interrupted.set(executor.interrupt_requested)
            # 仅清本人条目,不误删他人在册执行器
            if c_id and _workflow_interrupt_registry.get(c_id) is executor:
                _workflow_interrupt_registry.pop(c_id, None)

        await bridge.finish(plan, ctx, interrupted=executor.interrupt_requested)

        # 协作中断未跑完:静默收尾,恢复走 checkpoint+会话条目
        if executor.interrupt_requested and not plan.is_complete():
            return

        # 输出交付文本:步骤结果随状态行展示(占位结果另行点名)
        for step in plan.steps:
            if step.status.value == "completed" and step.id in ctx.step_results:
                yield f"\n[PASS] **{step.name}** (id: {step.id}) 完成\n\n"
                result = ctx.step_results[step.id]
                if step.type.value == "verify":
                    if isinstance(result, dict):
                        passed = result.get("passed", False)
                        yield f"**验证结果**: {'[PASS] 通过' if passed else '[FAIL] 未通过'}\n"
                        yield f"**详情**: {result.get('verdict', '')[:500]}\n"
                    else:
                        yield f"{str(result)[:1000]}\n"
                elif step.type.value in ("llm_tool", "mcp_tool"):
                    result_text = result if isinstance(result, str) else str(result)
                    if len(result_text) > 3000:
                        result_text = result_text[:3000] + "\n\n...(输出已截断)"
                    if step.type.value == "mcp_tool":
                        yield f"**MCP 调用**: {step.skill_name} ({step.params.get('mcp_server', 'N/A')})\n"
                    yield f"{result_text}\n"
                else:
                    # 占位判定锚 _skeleton_reply 形态:「[skill] 暂未接入」或 JSON status=not_implemented
                    result_text = result if isinstance(result, str) else str(result)
                    is_placeholder = bool(
                        re.search(r"\[[^\]\n]{1,40}\]\s*暂未接入", result_text)
                    )
                    if not is_placeholder:
                        is_placeholder = _contains_not_implemented_json(result)
                    if is_placeholder:
                        yield (
                            f"⚠️ 注意:该步骤的工具调用返回「暂未接入」占位,"
                            f"未产生真实执行结果,不能视为验证/执行通过。\n"
                        )
                    if len(result_text) > 3000:
                        result_text = result_text[:3000] + "\n\n...(输出已截断)"
                    yield f"{result_text}\n"
            elif step.status.value == "failed":
                yield f"\n[FAIL] **{step.name}** (id: {step.id}) 失败: {step.error}\n\n"
            elif step.status.value == "skipped":
                yield f"\n[SKIP] **{step.name}** (id: {step.id}) 已跳过\n\n"

        # Step 5: 端到端报告
        total = len(plan.steps)
        completed = sum(1 for s in plan.steps if s.status.value == "completed")
        failed = sum(1 for s in plan.steps if s.status.value == "failed")
        skipped = sum(1 for s in plan.steps if s.status.value == "skipped")

        yield "\n\n---\n\n"
        yield "## 📊 端到端工作流执行报告\n\n"

        # 总体摘要
        yield f"| 指标 | 值 |\n"
        yield f"|------|-----|\n"
        yield f"| **工作流目标** | {plan.goal} |\n"
        yield f"| **总步骤数** | {total} |\n"
        yield f"| **成功完成** | {completed} |\n"
        if failed:
            yield f"| **失败** | {failed} |\n"
        if skipped:
            yield f"| **已跳过** | {skipped} |\n"
        yield f"| **最大并发** | {plan.max_concurrency} |\n"
        yield "\n"

        # 步骤详情表
        yield "### 步骤执行详情\n\n"
        yield f"| 步骤ID | 名称 | 类型 | 状态 | 说明 |\n"
        yield f"|--------|------|------|------|------|\n"
        for step in plan.steps:
            status_icon = {
                "completed": "[PASS]",
                "failed": "[FAIL]",
                "skipped": "[SKIP]",
                "pending": "[PEND]",
                "running": "[RUN]",
            }.get(step.status.value, step.status.value)
            desc = (step.description or step.name)[:60]
            yield f"| {step.id} | {step.name} | {step.type.value} | {status_icon} | {desc} |\n"
        yield "\n"

        # 详细结果:各类步骤均透出结果文本(截断 3000)
        yield "### 详细结果\n\n"
        for step in plan.steps:
            if step.status.value == "completed" and step.id in ctx.step_results:
                yield f"#### ✅ {step.name} (id: {step.id})\n\n"
                result = ctx.step_results[step.id]
                if step.type.value == "verify":
                    if isinstance(result, dict):
                        passed = result.get("passed", False)
                        yield f"**验证结果**: {'[PASS] 通过' if passed else '[FAIL] 未通过'}\n"
                        yield f"**详情**: {str(result.get('verdict', ''))[:500]}\n\n"
                    else:
                        yield f"{str(result)[:2000]}\n\n"
                elif step.type.value in ("llm_tool", "mcp_tool"):
                    if step.type.value == "mcp_tool":
                        yield f"**MCP 调用**: {step.skill_name} ({step.params.get('mcp_server', 'N/A')})\n\n"
                    result_str = str(result)
                    if len(result_str) > 3000:
                        result_str = result_str[:3000] + "\n\n...(输出过长已截断,关键结论如上)"
                    yield f"{result_str}\n\n"
                else:
                    result_text = result if isinstance(result, str) else str(result)
                    if len(result_text) > 3000:
                        result_text = result_text[:3000] + "\n\n...(输出已截断)"
                    yield f"{result_text}\n\n"
            elif step.status.value == "failed":
                yield f"#### ❌ {step.name} (id: {step.id})\n\n"
                yield f"**错误**: {step.error}\n\n"
            elif step.status.value == "skipped":
                yield f"#### ⏭️ {step.name} (id: {step.id})\n\n"
                yield f"步骤已跳过。\n\n"

        # 终帧
        yield "---\n"
        yield f"**工作流执行完毕**: {completed}/{total} 步骤完成"
        if failed:
            yield f",{failed} 步骤失败"
        yield "\n"
        if failed:
            # 保留报告正文,协议终帧同步真实失败结果。
            yield CommandOutput(content="", is_error=True)

    async def workflow_handler(
        args: str,
        c_id: str | None = None,
    ) -> AsyncIterator[str | CommandOutput]:
        inner = _relay(_yield_workflow(args, c_id))
        try:
            async for chunk in inner:
                yield chunk
        finally:
            await inner.aclose()

    async def _yield_workflow(
        args: str,
        c_id: str | None,
    ) -> AsyncIterator[str | CommandOutput]:
        invocation = direct_command_sessions.begin(
            c_id,
            "workflow",
            "workflow",
            task_digest=args,
        )
        if c_id and invocation is None:
            yield CommandOutput(
                content="/workflow 当前仍在执行,已拒绝并发启动同一会话的新任务。",
                is_error=True,
            )
            return

        # 协作中断收尾=正常完成但条目须保留给「继续」续跑,断连/异常才清
        completed = False
        try:
            inner = _relay(_run_workflow(
                args, c_id, invocation.generation if invocation else None,
            ))
            try:
                async for chunk in inner:
                    yield chunk
            finally:
                await inner.aclose()
            completed = True
        finally:
            if invocation is not None:
                direct_command_sessions.release(
                    c_id,
                    "workflow",
                    invocation.generation,
                )
                if completed and not _last_workflow_interrupted.get():
                    direct_command_sessions.clear_if_idle(c_id)

    cmd_registry.register(
        Command(
            name="workflow",
            description="使用 Dynamic Workflow Engine 解析意图并自动执行多步骤工作流(LLM 规划 + DAG 执行)",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=workflow_handler,
            example="/workflow 验证并优化 Qwen3-8B 在 A2 上的适配",
            requires_args=True,
            supports_continuation=True,
        )
    )

    # ── 注册 /experience 命令 ─────────────────────────────────────
    async def experience_handler(args: str) -> AsyncIterator[str]:
        """查询和管理 Hermes 自演进引擎的经验数据。"""
        from app.services.command_dashboard import safe_report_command as report_command

        parts = args.strip().split()
        sub = parts[0].lower() if parts else "stats"

        reporter = report_command("experience", args, c_id="")

        error = None
        try:
            from app.tools.experience.store import ExperienceStore
            store = ExperienceStore()

            if sub == "stats":
                mem_count = store.count_memories()
                skills = store.get_all_skills()
                insights = store.get_pending_insights()
                output = f"**Hermes Experience Stats**\n\n"
                output += f"- 记忆: {mem_count}/{settings.hermes_memory_capacity}\n"
                output += f"- Skills: {len(skills)}/{settings.hermes_skill_capacity}\n"
                output += f"- 待处理 Insight: {len(insights)}\n"
                if skills:
                    output += f"\n**Registered Skills:**\n"
                    for s in skills:
                        output += f"- `{s['name']}`: {s.get('description', '')[:80]}\n"
                if reporter is not None:
                    reporter.on_output(output)
                yield output
            elif sub == "memory":
                memories = store.get_memories(limit=10)
                output = ""
                if not memories:
                    output = "暂无记忆。\n"
                for m in memories:
                    output += f"- [{m.get('timestamp','')[:10]}] {m.get('intent','')[:60]} → {m.get('result','')}\n"
                if reporter is not None:
                    reporter.on_output(output)
                yield output
            elif sub == "skills":
                skills = store.get_all_skills()
                output = ""
                if not skills:
                    output = "暂无 Skill。\n"
                for s in skills:
                    steps_str = " → ".join(
                        step.get("skill_name", step.get("type", "?"))[:20]
                        for step in s.get("steps", [])
                    )
                    output += f"- `{s['name']}` (x{s.get('success_count',1)}): {steps_str}\n"
                if reporter is not None:
                    reporter.on_output(output)
                yield output
            elif sub == "insights":
                insights = store.get_insights(limit=10)
                output = ""
                if not insights:
                    output = "暂无 Insight。\n"
                for i in insights:
                    status = "[已应用]" if i.get("applied") else "[待处理]"
                    output += f"- {status} {i.get('description','')[:80]}\n"
                if reporter is not None:
                    reporter.on_output(output)
                yield output
            elif sub == "forget":
                if "all" in args:
                    import shutil
                    import os
                    for f in ["memory.jsonl", "skills.json", "insights.jsonl"]:
                        p = Path.home() / ".mofix" / "experience" / f
                        if p.exists():
                            os.remove(p)
                    output = "所有 Hermes 经验数据已清除。\n"
                    if reporter is not None:
                        reporter.on_output(output)
                    yield output
            else:
                output = f"未知子命令: {sub}。可用: stats, memory, skills, insights, forget\n"
                if reporter is not None:
                    reporter.on_output(output)
                yield output
        except (asyncio.CancelledError, GeneratorExit):
            error = _stream_cancel_reason()
            raise
        except Exception as exc:
            error = f"{type(exc).__name__}: {exc}"
            raise
        finally:
            if reporter is not None:
                reporter.finish(error=error)

    cmd_registry.register(
        Command(
            name="experience",
            description="查询和管理 Hermes 自演进引擎的经验数据 (stats/memory/skills/insights/forget)",
            trigger_modes=[TriggerMode.USER_TRIGGER],
            handler=experience_handler,
            example="/experience stats",
        )
    )

    # ── 注册 /learn 命令 ──────────────────────────────────────────
    import uuid
    from datetime import datetime, timezone

    async def learn_handler(args: str) -> AsyncIterator[str]:
        """教导 Hermes 记住一个经验。"""
        from app.services.command_dashboard import safe_report_command as report_command

        reporter = report_command("learn", args, c_id="")

        error = None
        try:
            from app.tools.experience.store import ExperienceStore
            store = ExperienceStore()
            memory = {
                "id": f"mem_{uuid.uuid4().hex[:8]}",
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "intent": args[:200],
                "source": "user_teach",
                "result": "success",
            }
            store.append_memory(memory)
            output = f"[Hermes] 已记住: {args[:100]}...\n"
            if reporter is not None:
                reporter.on_output(output)
            yield output
        except (asyncio.CancelledError, GeneratorExit):
            error = _stream_cancel_reason()
            raise
        except Exception as exc:
            error = f"{type(exc).__name__}: {exc}"
            raise
        finally:
            if reporter is not None:
                reporter.finish(error=error)

    cmd_registry.register(
        Command(
            name="learn",
            description="教导 Hermes 记住一个适配经验,下次相似任务时自动参考",
            trigger_modes=[TriggerMode.USER_TRIGGER, TriggerMode.LLM_RECOMMEND],
            handler=learn_handler,
            example="/learn 适配 Qwen3-8B 到 A2 需要使用 ascendc-op-develop 开发 rms_norm 算子",
            requires_args=True,
        )
    )

    # 启动时初始化 MCP 管理器
    from app.tools.workflow.mcp_integration import init_mcp_manager, shutdown_mcp_manager

    async def _init_mcp() -> None:
        if settings.mcp_auto_start:
            try:
                manager = await init_mcp_manager(settings.mcp_servers)
                tools = manager.get_all_tools()
                if tools:
                    print(f"[MCP] 已加载 {len(tools)} 个工具,来自 {len(manager.active_servers)} 台服务器: {', '.join(manager.active_servers)}")
                else:
                    print(f"[MCP] 已连接 {len(manager.active_servers)} 台服务器,但未发现工具")
            except Exception as e:
                print(f"[MCP] 初始化异常:{type(e).__name__}: {e}")

    asyncio.create_task(_init_mcp())

    # Hermes 引擎初始化
    if settings.hermes_enabled:
        try:
            from app.tools.experience.store import ExperienceStore
            store = ExperienceStore()
            mem_count = store.count_memories()
            skill_count = len(store.get_all_skills())
            if mem_count > 0 or skill_count > 0:
                print(f"[Hermes] 已加载 {mem_count} 条记忆, {skill_count} 个可复用 Skill")
            else:
                print(f"[Hermes] 引擎就绪(尚无经验数据)")
        except Exception as e:
            print(f"[Hermes] 初始化异常: {e}")

    # 启动时异步检查 doc-agent 环境(后台任务,不阻塞启动)
    from app.tools.doc_tools import resolve_doc_agent_root, check_doc_agent_environment

    async def _check_doc_env() -> None:
        try:
            root = resolve_doc_agent_root()
            issues = await asyncio.to_thread(check_doc_agent_environment, root)
            if issues:
                print(f"[doc-agent] 环境检查未通过:{' / '.join(issues)}")
            else:
                print(f"[doc-agent] 环境就绪:{root}")
        except Exception as e:
            print(f"[doc-agent] 启动检查异常:{type(e).__name__}: {e}")

    asyncio.create_task(_check_doc_env())

    # 启动 Claude Code 历史记录监控上传(后台任务,不阻塞启动)
    from app.services.claude_history_uploader import HistoryWatcher

    _history_watcher: HistoryWatcher | None = None

    async def _start_history_watcher() -> None:
        global _history_watcher
        if not settings.claude_history_enabled:
            return
        try:
            _history_watcher = HistoryWatcher()
            asyncio.create_task(_history_watcher.start())
        except Exception as e:
            print(f"[claude-history] 启动监控异常:{type(e).__name__}: {e}")

    asyncio.create_task(_start_history_watcher())

    try:
        yield
    finally:
        await _drain_realtime_evaluation_tasks()
        if realtime_scorer_recovery_task is not None:
            if not realtime_scorer_recovery_task.done():
                realtime_scorer_recovery_task.cancel()
            try:
                await realtime_scorer_recovery_task
            except asyncio.CancelledError:
                pass
        if isinstance(dashboard_start_task, asyncio.Task):
            if not dashboard_start_task.done():
                dashboard_start_task.cancel()
            try:
                await dashboard_start_task
            except asyncio.CancelledError:
                pass
        if dashboard_server is not None:
            try:
                await dashboard_server.stop()
            except Exception as exc:
                print(f"[dashboard] 停止失败(继续清理主服务): {exc}")

    # Graceful shutdown 时显式清空 memory-only 会话元数据,不让可续跑标识泄漏出 teardown 钩子。
    direct_command_sessions.clear_all()
    from app.services.chat_service import _auto_confirmed_sessions
    _auto_confirmed_sessions.clear()

    # 停止历史记录监控
    if _history_watcher:
        await _history_watcher.stop()

    # 关闭 MCP 连接
    await shutdown_mcp_manager()
    print("[MCP] 管理器已关闭")

    # 关闭时刷日志
    from lts_logger import lts_logger
    await lts_logger.shutdown()


app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    lifespan=lifespan,
)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 异常处理
app.add_exception_handler(MoFixException, mofix_exception_handler)

# 路由
app.include_router(chat.router)
app.include_router(config.router)
app.include_router(system.router)
# 看板同源入口:页面、静态资源、历史和实时事件统一挂在 /workflow 下
if settings.workflow_dashboard_enabled:
    from app.api import dashboard

    app.include_router(dashboard.router)
    dashboard.mount_assets(app)