Skill: ntaffffff/prompt-optimizer-v3 (version 3.2.0)

# 🚀 Prompt Optimizer <p align="center"> <img src="https://img.shields.io/badge/OpenClaw-技能包-blue?style=for-the-badge&logo=rocket" alt="OpenClaw"> <img src="https://img.shields.io/badge/版本-3.2-green?style=for-the-badge" alt="Version"> <img src="https://img.shields.io/badge/Python-3.12+-yellow?style=for-the-badge" alt="Python"> <img src="https://img.shields.io/badge/测试-57个通过-green?style=for-the-badge" alt="Tests"> </p> > [!TIP] > AI 任务处理器 - 先优化 Prompt，再精准执行 --- ## ✨ 一句话介绍 **一个能把您的模糊需求自动翻译成 AI 能精准执行的指令的工具！** --- ## 🎯 能做什么？ ### 原始需求 → 精准指令 | 您说 | 优化后 | |------|--------| | "帮我写个排序" | "你是一个专业工程师。帮我写个排序。请用 Markdown 格式输出..." | | "查下天气" | "请提供准确、全面的信息，标注信息来源。查下天气。用 Markdown..." | | "帮我debug报错" | "你是一个资深调试专家。请分析问题原因，提供完整的错误分析..." | | "帮我写个测试用例" | "你是一个资深测试工程师。请编写完整的测试用例，覆盖主要场景..." | --- ## 🚀 快速开始 ### 安装 ```bash cp -r prompt-optimizer/ ~/.openclaw/workspace/skills/ ``` ### 使用 ```bash # 基本用法 python prompt_optimizer.py "帮我写个排序" # JSON 输出 python prompt_optimizer.py "帮我写个排序" --json # YAML 输出 python prompt_optimizer.py "帮我写个排序" --yaml # 从文件批量处理 python prompt_optimizer.py --file input.txt # 查看版本 python prompt_optimizer.py --version ``` --- ## 📖 CLI 用法 ``` 用法: python prompt_optimizer.py [options] [prompt] 选项: -f, --file FILE 从文件读取 prompt（每行一个） -o, --output FILE 输出文件路径 -j, --json 输出 JSON 格式 -y, --yaml 输出 YAML 格式 -v, --verbose 显示详细信息 -q, --quiet 静默模式 --stats 显示统计信息 -t, --types 显示支持的任务类型 --cache / --no-cache 启用/禁用缓存 --clear-cache 清空缓存 -c, --config FILE 配置文件路径 --version 显示版本号 -h, --help 显示帮助信息 ``` --- ## 📋 支持的任务类型 (20种) - v3.2 新增 7 种 | 类型 | 关键词示例 | 新增 | |------|-----------|------| | 写代码 | "帮我写个排序" | | | 代码审查 | "审查这段代码" | | | 改写代码 | "重构这段代码" | | | 写文档 | "帮我写个文档" | | | 写文案 | "写一段推广文案" | | | 总结摘要 | "帮我总结一下" | | | 翻译 | "翻译成英文" | | | 查资料 | "查一下深圳天气" | | | 数据分析 | "分析一下这份数据" | | | 头脑风暴 | "给我几个创业想法" | | | 生成内容 | "生成一张图片" | | | 数学计算 | "计算 123+456" | | | 对话聊天 | "聊聊AI的发展" | | | 处理文件 | "处理文件" | | | **写测试用例** | "帮我写测试用例" | 🆕 | | **代码调试** | "帮我debug报错" | 🆕 | | **性能优化** | "优化代码性能" | 🆕 | | **安全检查** | "做安全检查" | 🆕 | | **API设计** | "设计一个API" | 🆕 | | **数据结构设计** | "用什么数据结构" | 🆕 | --- ## 🎨 新功能 (v3.2) ### ✨ 新增任务类型 (7种) - **写测试用例** - 单元测试、集成测试 - **代码调试** - Bug 分析与修复 - **性能优化** - 性能瓶颈分析与优化 - **安全检查** - OWASP 安全审计 - **API设计** - RESTful 接口设计 - **数据结构设计** - 算法与数据结构选择 ### 📄 多格式输出支持 - **Markdown** (默认) - **JSON** - `--json` 参数 - **YAML** - `--yaml` 参数 - **XML** - 自动检测 - **表格** - 自动检测 - **PlantUML** - 自动检测 ### 👥 目标受众识别 (7种) - 技术人员 → 包含代码实现细节 - 产品经理 → 从业务角度分析 - 管理者 → 简洁清晰，决策要点 - 运维人员 → 部署和运维便利性 - 设计师 → 视觉和用户体验 - 初学者 → 通俗易懂，逐步引导 - 普通用户 → 简单直白 ### 📏 约束条件支持 - **字数限制** - 简短(100字)、中等(300字)、详细(500+字) - **条数限制** - 少量(3-5条)、中等(5-10条)、大量(10+条) ### 🎭 风格识别 (8种) - 专业正式 - 轻松幽默 - 简洁明了 - 详细全面 - 技术风格 - 口语化 - 学术风格 - 教程风格 --- ## 📝 使用示例 ### 1. 基本优化 ```bash $ python prompt_optimizer.py "帮我写个排序" 你是一个专业工程师。 帮我写个排序。 请用 Markdown 格式输出，包含代码块和必要说明 请包含详细的代码注释 请注意代码性能和可读性 ``` ### 2. 指定输出格式 ```bash $ python prompt_optimizer.py "查天气" --json ``` ### 3. 带约束条件 ```bash $ python prompt_optimizer.py "给我5个创业想法，200字以内" ``` ### 4. 指定目标受众 ```bash $ python prompt_optimizer.py "解释什么是AI，给初学者看" ``` --- ## 📦 项目结构 ``` prompt-optimizer/ ├── prompt_optimizer.py # 主程序 (v3.2) ├── config_data.py # 配置数据 (独立) ├── test_prompt_optimizer.py # 测试用例 ├── config.yaml.example # 配置示例 └── SKILL.md # 文档 ``` --- ## 🧪 测试 ```bash python test_prompt_optimizer.py # 结果 📊 测试结果: 57 通过, 0 失败 ``` --- ## ⚙️ 配置自定义 创建 `config.yaml` 文件： ```yaml cache: maxsize: 256 enabled: true llm: enabled: false provider: openai model: gpt-4 task_patterns: 自定义任务: keywords: ["关键词1", "关键词2"] priority: 10 enhancements: - "你是专家" - "请详细说明" ``` 然后运行： ```bash python prompt_optimizer.py -c config.yaml "你的prompt" ``` --- ## 📝 更新日志 ### v3.2 (2026-04-14) - ✅ **新增 7 种任务类型** - 写测试用例、代码调试、性能优化、安全检查、API设计、数据结构设计 - ✅ **输出格式支持** - JSON、YAML、XML、表格、PlantUML - ✅ **目标受众识别** - 技术人员、产品经理、管理者、运维、设计师、初学者、普通用户 - ✅ **风格识别** - 8 种风格自动检测 - ✅ **约束条件** - 字数限制、条数限制 - ✅ **57 个测试** - 全部通过 ### v3.1 (2026-04-07) - ✅ 配置分离 - ✅ LRU 缓存 - ✅ 配置文件支持 --- <p align="center"> <sub>Made with ❤️ by dxx</sub> </p>

path: _meta.json
content: {
  "slug": "prompt-optimizer-dxx",
  "name": "Prompt Optimizer",
  "version": "3.2.0",
  "description": "AI 任务处理器 - 将模糊需求自动翻译成 AI 能精准执行的指令",
  "author": "dxx",
  "tags": ["prompt", "optimizer", "ai", "task-processor"],
  "homepage": "https://github.com/ntaffffff/openclaw-skills/tree/master/skills/prompt-optimizer"
}

path: config_data.py
content: """
Prompt Optimizer 配置数据
从主程序分离出来的配置，便于维护和扩展
"""

# ============ 版本信息 ============
__version__ = "3.2.0"
__author__ = "dxx"
__description__ = "AI 任务处理器 - 先优化 Prompt，再精准执行"


# ============ 任务类型配置 ============
TASK_PATTERNS = {
    "写文档": {
        "keywords": ["文档", "说明文档", "技术文档", "readme", "写个文档", "写说明", "写篇文档"],
        "priority": 10,
        "enhancements": [
            "你是一个技术文档专家。",
            "请使用清晰的结构，用 Markdown 格式输出",
            "包含概述、使用方法、参数说明、示例等部分",
        ]
    },
    "写文案": {
        "keywords": ["文案", "广告文案", "宣传文案", "推广文案", "软文", "营销文案", "文案"],
        "priority": 10,
        "enhancements": [
            "你是一个资深文案策划。",
            "请用吸引人的风格，突出产品卖点",
            "输出可以直接使用的文案",
        ]
    },
    "总结摘要": {
        "keywords": ["总结", "摘要", "概括", "提炼", "核心要点", "汇总", "归纳"],
        "priority": 10,
        "enhancements": [
            "请提取核心要点，用简洁的中文概括",
            "用 Markdown 列表格式输出",
            "控制在前 N 字以内（根据原文长度）",
        ]
    },
    "翻译": {
        "keywords": ["翻译成", "翻译为", "译成", "translate", "英译中", "中译英", "翻译"],
        "priority": 10,
        "enhancements": [
            "你是一个专业翻译。",
            "请保持原文风格和语气",
            "输出翻译后的内容，必要时保留专业术语的原文",
        ]
    },
    "写代码": {
        "keywords": ["写代码", "帮我写", "编程", "写个程序", "实现功能", "开发程序", "写个函数", "写个算法", "写一个", "写接口", "写个api"],
        "priority": 8,
        "enhancements": [
            "你是一个专业工程师。",
            "请用 Markdown 格式输出，包含代码块和必要说明",
            "请包含详细的代码注释",
            "请注意代码性能和可读性",
        ]
    },
    "代码审查": {
        "keywords": ["审查代码", "代码审查", "审查这段", "审查下", "检查代码", "review代码", "代码review", "审计代码"],
        "priority": 9,
        "enhancements": [
            "你是一个资深代码审查专家。",
            "请从安全性、性能、可维护性、代码规范等多个维度审查",
            "用 Markdown 格式输出审查报告，包含问题描述和修复建议",
            "请标注问题的严重程度（高/中/低）",
        ]
    },
    "改写代码": {
        "keywords": ["重构", "优化代码", "改写代码", "重写代码", "refactor", "代码重构", "优化这段"],
        "priority": 9,
        "enhancements": [
            "你是一个代码重构专家。",
            "在保持功能不变的前提下优化代码",
            "用 Markdown 输出重构前后的对比",
        ]
    },
    "数据分析": {
        "keywords": ["分析数据", "数据分析", "分析一下", "统计数据", "数据统计", "分析这份"],
        "priority": 8,
        "enhancements": [
            "你是一个数据分析师。",
            "请从多维度分析，用数据说话",
            "用 Markdown 表格或图表展示关键数据",
        ]
    },
    "查资料": {
        "keywords": ["查一下", "帮我查", "搜索", "查找", "了解一下", "查资料", "search", "query", "查下"],
        "priority": 7,
        "enhancements": [
            "请提供准确、全面的信息，标注信息来源",
            "用 Markdown 格式输出，包含要点和详情",
            "如果不确定，请注明",
        ]
    },
    "头脑风暴": {
        "keywords": ["想法", "创意", "脑洞", "建议", "有什么想法", "给点建议", "创业想法", "点子"],
        "priority": 7,
        "enhancements": [
            "请提供多个创意想法，数量不少于 X 个",
            "每个想法请简短说明优势和适用场景",
            "用 Markdown 列表格式输出",
        ]
    },
    "生成内容": {
        "keywords": ["生成", "创建", "制作", "输出", "帮我生成", "生成一个", "做一个"],
        "priority": 6,
        "enhancements": [
            "请直接输出最终内容，不要解释过程",
            "内容要完整、可直接使用",
            "用合适的格式输出",
        ]
    },
    "数学计算": {
        "keywords": ["计算", "等于多少", "求解", "数学", "算一下", "帮我算"],
        "priority": 7,
        "enhancements": [
            "请给出详细的计算步骤",
            "如果涉及公式，请说明公式来源",
            "最后给出明确答案",
        ]
    },
    "对话聊天": {
        "keywords": ["聊聊", "聊天", "对话", "谈谈", "说说你", "有什么看法", "怎么看"],
        "priority": 6,
        "enhancements": [
            "请用友好、耐心的方式回复",
            "根据对话内容适当调整语气",
        ]
    },
    "处理文件": {
        "keywords": ["处理文件", "读取文件", "解析", "提取内容", "处理下"],
        "priority": 5,
        "enhancements": [
            "请说明处理步骤和结果格式",
            "如果涉及文件操作，请注意路径和权限",
        ]
    },
    # ============ v3.2 新增任务类型 ============
    "写测试用例": {
        "keywords": ["写测试", "测试用例", "unittest", "pytest", "测试代码", "单元测试", "集成测试", "写个测试", "测试覆盖", "coverage"],
        "priority": 9,
        "enhancements": [
            "你是一个资深测试工程师。",
            "请编写完整的测试用例，覆盖主要场景和边界条件",
            "使用主流测试框架（如 pytest/unittest），输出可直接运行的测试代码",
            "包含正向用例、负向用例、边界条件测试",
        ]
    },
    "代码调试": {
        "keywords": ["调试", "debug", "报错", "错误", "bug", "修复", "问题", "崩溃", "闪退", "异常", "failed", "error", "exception"],
        "priority": 10,
        "enhancements": [
            "你是一个资深调试专家。",
            "请分析问题原因，提供完整的错误分析和解决方案",
            "用 Markdown 格式输出，包含：错误信息 → 原因分析 → 解决方案 → 验证步骤",
            "如果需要，请提供可执行的修复代码",
        ]
    },
    "性能优化": {
        "keywords": ["性能优化", "优化代码", "提升性能", "慢", "卡顿", "优化", "performance", "优化速度", "加速", "效率"],
        "priority": 9,
        "enhancements": [
            "你是一个性能优化专家。",
            "请分析代码的性能瓶颈，提供具体的优化方案",
            "用 Markdown 输出，包含：性能分析 → 瓶颈定位 → 优化方案 → 预期提升",
            "提供优化后的代码和 benchmark 对比",
        ]
    },
    "安全检查": {
        "keywords": ["安全检查", "安全审计", "漏洞", "注入", "xss", "sql注入", "csrf", "权限", "加密", "security", "渗透测试", "审计"],
        "priority": 10,
        "enhancements": [
            "你是一个安全专家。",
            "请从 OWASP Top 10 等安全标准进行全面审查",
            "用 Markdown 格式输出安全报告，包含：漏洞类型 → 风险等级 → 修复建议 → 参考链接",
            "标注每个问题的严重程度（高/中/低）",
        ]
    },
    "API设计": {
        "keywords": ["api设计", "接口设计", "设计api", "restful", "接口规范", "openapi", "swagger", "接口文档", "定义接口", "帮我设计接口", "设计个api", "帮我设计一个api", "帮我设计个api"],
        "priority": 10,  # 提高优先级
        "enhancements": [
            "你是一个 API 设计专家。",
            "请设计清晰、规范的 API 接口",
            "使用 RESTful 规范，包含完整的请求/响应示例",
            "用 Markdown 输出，包含：接口路径、请求方法、参数说明、响应格式、错误码",
        ]
    },
    "数据结构设计": {
        "keywords": ["数据结构", "设计数据结构", "选什么结构", "用什么数据结构", "树", "图", "hash", "堆", "队列", "栈"],
        "priority": 8,
        "enhancements": [
            "你是一个算法专家。",
            "请根据场景选择最优的数据结构",
            "用 Markdown 输出，包含：问题分析 → 方案对比 → 推荐方案 → 复杂度分析",
            "对比多种方案的优劣",
        ]
    },
}


# ============ 编程语言配置 ============
LANGUAGE_PATTERNS = {
    "Python": ["python", "py", "python3", "pandas", "django", "flask", "pygame", "pytorch", "tensorflow"],
    "JavaScript": ["javascript", "js", "node", "react", "vue", "前端", "nodejs"],
    "TypeScript": ["typescript", "ts", "ts-node"],
    "Go": ["go", "golang", "go语言"],
    "Java": ["java", "spring", "后端", "springboot"],
    "Rust": ["rust", "rs", "rustlang"],
    "C++": ["c++", "cpp", "c语言"],
    "C#": ["c#", "csharp", ".net"],
    "PHP": ["php", "laravel"],
    "Ruby": ["ruby", "rails"],
    "Swift": ["swift", "ios", "apple"],
    "Kotlin": ["kotlin", "android"],
    "SQL": ["sql", "数据库", "mysql", "postgresql", "mongodb"],
    "Shell": ["shell", "bash", "脚本", "linux", "sh"],
    "HTML/CSS": ["html", "css", "前端", "网页"],
}


# ============ 输出格式配置 ============
FORMAT_PATTERNS = {
    "Markdown": ["markdown", "md", "文档格式", "md格式", "md格式输出"],
    "JSON": ["json", "接口", "返回json", "json格式", "api", "json输出"],
    "YAML": ["yaml", "yml", "yaml格式", "yml格式"],
    "XML": ["xml", "xml格式"],
    "表格": ["表格", "table", "excel", "csv"],
    "代码块": ["代码", "code", "源代码", "代码块"],
    "纯文本": ["文本", "text", "纯文字", "txt"],
    "列表": ["列表", "list", "罗列"],
    "流程图": ["流程图", "流程", "步骤", "mermaid"],
    "SQL": ["sql", "sql语句", "数据库查询"],
    "PlantUML": ["plantuml", "uml", "类图", "时序图"],
}


# ============ 风格配置 ============
STYLE_PATTERNS = {
    "专业正式": ["专业", "正式", "严肃", "商务", "正规"],
    "轻松幽默": ["轻松", "幽默", "有趣", "搞笑", "活泼", "俏皮"],
    "简洁明了": ["简洁", "简单", "明了", "简短", "精炼", "干练"],
    "详细全面": ["详细", "全面", "完整", "细致", "充分", "详尽"],
    "技术风格": ["技术", "极客", "程序员", "geek", "硬核"],
    "口语化": ["口语", "随意", "大白话", "通俗", "接地气"],
    "学术风格": ["学术", "论文", "研究", "严谨", "理论"],
    "教程风格": ["教程", "教学", "一步一步", "一步步", "手把手"],
}


# ============ 目标受众配置 ============
AUDIENCE_PATTERNS = {
    "技术人员": ["程序员", "开发", "工程师", "技术", "代码", "dev", "开发人员", "技术人"],
    "产品经理": ["产品", "pm", "产品经理", "需求", "产品人", "业务"],
    "管理者": ["管理", "老板", "领导", "决策", "管理层", "总监", "ceo"],
    "运维人员": ["运维", "部署", "运维人", "sre", "dba"],
    "设计师": ["设计", "设计师", "ui", "ux", "设计人"],
    "初学者": ["入门", "初学", "小白", "新手", "基础", "教程"],
    "普通用户": ["普通", "用户", "大众", "日常"],
}


# ============ 约束条件配置 ============
CONSTRAINT_PATTERNS = {
    "字数限制": {
        "简短": ["50字", "100字", "200字", "精简", "简要"],
        "中等": ["300字", "500字", "中等"],
        "详细": ["1000字", "2000字", "详细", "全面"],
    },
    "条数限制": {
        "大量": ["20个", "多个"],  # 先匹配更具体的
        "中等": ["10个", "10条", "5-10"],
        "少量": ["3条", "5个", "3-5"],
    },
}


# ============ 默认配置 ============
DEFAULT_CONFIG = {
    "task_patterns": TASK_PATTERNS,
    "language_patterns": LANGUAGE_PATTERNS,
    "format_patterns": FORMAT_PATTERNS,
    "style_patterns": STYLE_PATTERNS,
    "audience_patterns": AUDIENCE_PATTERNS,
    "constraint_patterns": CONSTRAINT_PATTERNS,
    "cache": {
        "enabled": True,
        "maxsize": 128
    },
    "logging": {
        "level": "INFO"
    },
    "llm": {
        "enabled": False,
        "provider": "openai",
        "model": "gpt-4"
    }
}

path: prompt_optimizer.py
content: #!/usr/bin/env python3
"""
Prompt Optimizer Skill - Prompt 优化器 v3.1 (重构版)
支持全类型任务优化 + 配置文件 + LRU 缓存 + 日志系统

CLI 用法:
    python prompt_optimizer.py "帮我写个排序"
    python prompt_optimizer.py --json "帮我写个排序"
    python prompt_optimizer.py --file input.txt
    python -m prompt_optimizer "帮我写个排序"

Python 调用:
    from prompt_optimizer import PromptOptimizer
    optimizer = PromptOptimizer()
    result = optimizer.optimize("帮我写个排序")
"""

import re
import sys
import json
import logging
import argparse
from pathlib import Path
from typing import Dict, List, Optional, Union
from dataclasses import dataclass, asdict
from datetime import datetime
from collections import OrderedDict

# 导入配置数据
from config_data import (
    __version__,
    DEFAULT_CONFIG,
    TASK_PATTERNS,
    LANGUAGE_PATTERNS,
    FORMAT_PATTERNS,
    STYLE_PATTERNS,
    AUDIENCE_PATTERNS,
    CONSTRAINT_PATTERNS,
)


# ============ 版本信息 ============
__all__ = ["__version__", "PromptOptimizer", "OptimizationResult", "optimize_prompt"]


# ============ 日志配置 ============

def setup_logger(name: str = "prompt_optimizer", level: int = logging.INFO) -> logging.Logger:
    """设置日志器"""
    logger = logging.getLogger(name)
    logger.setLevel(level)
    
    if not logger.handlers:
        handler = logging.StreamHandler()
        handler.setLevel(level)
        formatter = logging.Formatter(
            "%(asctime)s │ %(levelname)-8s │ %(message)s",
            datefmt="%H:%M:%S"
        )
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    
    return logger


logger = setup_logger()


# ============ LRU 缓存 ============

class LRUCache:
    """简单的 LRU 缓存实现"""
    
    def __init__(self, maxsize: int = 128):
        self.cache: OrderedDict = OrderedDict()
        self.maxsize = maxsize
        self.hits = 0
        self.misses = 0
    
    def get(self, key: str) -> Optional[str]:
        """获取缓存"""
        if key in self.cache:
            self.hits += 1
            self.cache.move_to_end(key)
            logger.debug(f"📦 缓存命中: {key[:20]}...")
            return self.cache[key]
        self.misses += 1
        return None
    
    def set(self, key: str, value: str):
        """设置缓存"""
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.maxsize:
            self.cache.popitem(last=False)
    
    def clear(self):
        """清空缓存"""
        self.cache.clear()
        self.hits = 0
        self.misses = 0
        logger.info("🗑️ 缓存已清空")
    
    def stats(self) -> dict:
        """缓存统计"""
        total = self.hits + self.misses
        hit_rate = (self.hits / total * 100) if total > 0 else 0
        return {
            "size": len(self.cache),
            "maxsize": self.maxsize,
            "hits": self.hits,
            "misses": self.misses,
            "hit_rate": f"{hit_rate:.1f}%"
        }


# 全局缓存
_prompt_cache = LRUCache(maxsize=128)


# ============ 结果类 ============

@dataclass
class OptimizationResult:
    """优化结果"""
    original: str           # 原始 prompt
    optimized: str          # 优化后 prompt
    task_type: str          # 任务类型
    missing_info: List[str] # 缺失信息
    enhancements: List[str] # 增强项
    timestamp: str          # 时间戳
    cached: bool = False    # 是否命中缓存
    # v3.2 新增字段
    output_format: str = ""       # 输出格式
    style: str = ""               # 风格
    audience: str = ""            # 目标受众
    constraints: List[str] = None # 约束条件
    
    def __post_init__(self):
        if self.constraints is None:
            self.constraints = []
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return asdict(self)
    
    def to_json(self, indent: int = 2) -> str:
        """转换为 JSON 字符串"""
        return json.dumps(self.to_dict(), ensure_ascii=False, indent=indent)
    
    def to_yaml(self) -> str:
        """转换为 YAML 字符串"""
        try:
            import yaml
            return yaml.dump(self.to_dict(), allow_unicode=True, default_flow_style=False)
        except ImportError:
            # 如果没有 yaml，回退到 JSON
            return self.to_json()


# ============ 优化器核心 ============

class PromptOptimizer:
    """Prompt 优化器 - v3.2 重构版"""
    
    def __init__(self, config_path: Optional[str] = None, use_cache: bool = True):
        """
        初始化优化器
        
        Args:
            config_path: 配置文件路径（可选）
            use_cache: 是否启用缓存（默认启用）
        """
        self.config_path = config_path
        self.config = self._deep_copy(DEFAULT_CONFIG)
        self.use_cache = use_cache
        
        # 预编译模式
        self._compiled_patterns: Dict[str, List[tuple]] = {}
        self._sorted_patterns: List[tuple] = []
        
        # v3.2 新增：检测到的信息
        self._detected_format: str = ""
        self._detected_style: str = ""
        self._detected_audience: str = ""
        self._detected_constraints: List[str] = []
        
        self._load_config()
        self._compile_patterns()
        
        logger.info(f"🚀 Prompt Optimizer v{__version__} 初始化完成")
        logger.info(f"   任务类型: {len(self.config['task_patterns'])} 种")
        logger.info(f"   输出格式: {len(self.config['format_patterns'])} 种")
        logger.info(f"   目标受众: {len(self.config.get('audience_patterns', {}))} 种")
        logger.info(f"   缓存: {'启用' if use_cache else '禁用'}")
    
    @staticmethod
    def _deep_copy(data: dict) -> dict:
        """深度复制配置"""
        import copy
        return copy.deepcopy(data)
    
    def _load_config(self):
        """加载配置文件"""
        if self.config_path and Path(self.config_path).exists():
            try:
                import yaml
                with open(self.config_path, "r", encoding="utf-8") as f:
                    user_config = yaml.safe_load(f)
                
                self._merge_config(self.config, user_config)
                logger.info(f"📄 已加载配置文件: {self.config_path}")
            except ImportError:
                logger.warning("⚠️ PyYAML 未安装，使用默认配置")
            except Exception as e:
                logger.warning(f"⚠️ 配置文件加载失败: {e}, 使用默认配置")
        
        # 应用缓存设置
        if "cache" in self.config:
            global _prompt_cache
            _prompt_cache.maxsize = self.config["cache"].get("maxsize", 128)
    
    def _merge_config(self, base: dict, update: dict):
        """深度合并配置"""
        for key, value in update.items():
            if key in base and isinstance(base[key], dict) and isinstance(value, dict):
                self._merge_config(base[key], value)
            else:
                base[key] = value
    
    def _compile_patterns(self):
        """预编译关键词模式"""
        logger.debug("🔧 预编译关键词模式...")
        
        self._compiled_patterns = {}
        for task_type, config in self.config["task_patterns"].items():
            if task_type == "通用任务":
                continue
            keywords = config.get("keywords", [])
            priority = config.get("priority", 5)
            self._compiled_patterns[task_type] = [
                (priority, kw.lower(), task_type) 
                for kw in keywords
            ]
        
        all_patterns = []
        for task_type, patterns in self._compiled_patterns.items():
            all_patterns.extend(patterns)
        all_patterns.sort(key=lambda x: -x[0])
        self._sorted_patterns = all_patterns
    
    def _get_cache_key(self, prompt: str) -> str:
        """生成缓存 key"""
        import hashlib
        return hashlib.md5(prompt.strip().encode()).hexdigest()
    
    def optimize(self, prompt: str, use_cache: Optional[bool] = None) -> OptimizationResult:
        """优化 prompt"""
        # 错误处理
        if not prompt:
            raise ValueError("Prompt 不能为空")
        
        if not prompt.strip():
            raise ValueError("Prompt 不能只包含空白字符")
        
        cache_enabled = self.use_cache if use_cache is None else use_cache
        
        # 检查缓存
        if cache_enabled:
            cache_key = self._get_cache_key(prompt)
            cached_result = _prompt_cache.get(cache_key)
            if cached_result:
                task_type = self._detect_task_type(prompt.strip())
                missing_info = self._detect_missing_info(prompt.strip(), task_type)
                return OptimizationResult(
                    original=prompt.strip(),
                    optimized=cached_result,
                    task_type=task_type,
                    missing_info=missing_info,
                    enhancements=["基本格式优化"],
                    timestamp=datetime.now().isoformat(),
                    cached=True
                )
        
        original = prompt.strip()
        
        try:
            task_type = self._detect_task_type(original)
            
            # v3.2 新增：检测更多属性
            detected_format = self._detect_format(original)
            detected_style = self._detect_style(original)
            detected_audience = self._detect_audience(original)
            detected_constraints = self._detect_constraints(original)
            
            missing_info = self._detect_missing_info(original, task_type)
            optimized = self._apply_enhancements(
                original, task_type, missing_info,
                detected_format, detected_style, detected_audience, detected_constraints
            )
            enhancements = self._generate_enhancements(original, optimized)
            
            result = OptimizationResult(
                original=original,
                optimized=optimized,
                task_type=task_type,
                missing_info=missing_info,
                enhancements=enhancements,
                timestamp=datetime.now().isoformat(),
                cached=False,
                output_format=detected_format,
                style=detected_style,
                audience=detected_audience,
                constraints=detected_constraints
            )
            
            if cache_enabled:
                _prompt_cache.set(cache_key, optimized)
            
            return result
            
        except Exception as e:
            logger.error(f"❌ 优化失败: {e}")
            raise RuntimeError(f"优化失败: {str(e)}") from e
    
    def _detect_task_type(self, prompt: str) -> str:
        """检测任务类型"""
        prompt_lower = prompt.lower()
        
        for priority, keyword, task_type in self._sorted_patterns:
            if keyword in prompt_lower:
                return task_type
        
        return "通用任务"
    
    def _detect_format(self, prompt: str) -> str:
        """v3.2 新增：检测输出格式"""
        prompt_lower = prompt.lower()
        for fmt_type, keywords in self.config.get("format_patterns", {}).items():
            if any(kw in prompt_lower for kw in keywords):
                return fmt_type
        return ""
    
    def _detect_style(self, prompt: str) -> str:
        """v3.2 新增：检测风格"""
        prompt_lower = prompt.lower()
        for style_type, keywords in self.config.get("style_patterns", {}).items():
            if any(kw in prompt_lower for kw in keywords):
                return style_type
        return ""
    
    def _detect_audience(self, prompt: str) -> str:
        """v3.2 新增：检测目标受众"""
        prompt_lower = prompt.lower()
        audience_patterns = self.config.get("audience_patterns", {})
        for audience_type, keywords in audience_patterns.items():
            if any(kw in prompt_lower for kw in keywords):
                return audience_type
        return ""
    
    def _detect_constraints(self, prompt: str) -> List[str]:
        """v3.2 新增：检测约束条件"""
        constraints = []
        prompt_lower = prompt.lower()
        constraint_patterns = self.config.get("constraint_patterns", {})
        
        for constraint_type, levels in constraint_patterns.items():
            for level, keywords in levels.items():
                if any(kw in prompt_lower for kw in keywords):
                    constraints.append(f"{constraint_type}-{level}")
        
        return constraints
    
    def _detect_missing_info(self, prompt: str, task_type: str) -> List[str]:
        """检测缺失信息"""
        missing = []
        prompt_lower = prompt.lower()
        
        # 检测编程语言
        if task_type in ["写代码", "改写代码", "代码审查"]:
            all_langs = [lang for langs in self.config["language_patterns"].values() for lang in langs]
            if not any(lang in prompt_lower for lang in all_langs):
                missing.append("编程语言")
        
        # 检测输出格式
        all_formats = [fmt for fmts in self.config["format_patterns"].values() for fmt in fmts]
        if not any(fmt in prompt_lower for fmt in all_formats):
            missing.append("输出格式")
        
        # 检测风格
        all_styles = [s for styles in self.config["style_patterns"].values() for s in styles]
        if not any(s in prompt_lower for s in all_styles):
            missing.append("风格")
        
        # 检测具体细节
        if len(prompt) < 8:
            missing.append("具体需求描述")
        
        # 检测示例
        if task_type in ["写代码", "改写代码"]:
            if not any(x in prompt for x in ["例如", "比如", "示例", "输入"]):
                missing.append("输入输出示例")
        
        # 检测数量
        if task_type == "头脑风暴":
            if not any(x in prompt for x in ["个", "几条", "几个"]):
                missing.append("数量要求")
        
        # 检测字数
        if task_type in ["写文案", "总结摘要"]:
            if not any(x in prompt for x in ["字", "字数", "词"]):
                missing.append("字数要求")
        
        return missing
    
    def _apply_enhancements(
        self, 
        prompt: str, 
        task_type: str, 
        missing_info: List[str],
        detected_format: str = "",
        detected_style: str = "",
        detected_audience: str = "",
        detected_constraints: List[str] = None
    ) -> str:
        """应用增强 - v3.2 支持更多参数"""
        if detected_constraints is None:
            detected_constraints = []
            
        patterns = self.config["task_patterns"]
        config = patterns.get(task_type, patterns.get("通用任务", {
            "enhancements": ["请直接输出结果，用合适的格式"]
        }))
        enhancements = config.get("enhancements", [])
        
        enhanced_parts = []
        
        # 添加角色设定
        if enhancements:
            enhanced_parts.append(enhancements[0])
        
        # v3.2: 添加目标受众设定
        if detected_audience:
            audience_hints = {
                "技术人员": "请用技术语言，包含代码实现细节",
                "产品经理": "请从业务角度分析，突出价值和方案对比",
                "管理者": "请用简洁清晰的方式，突出决策要点",
                "运维人员": "请考虑部署和运维的便利性",
                "设计师": "请注重视觉和用户体验",
                "初学者": "请用通俗易懂的语言，逐步引导",
                "普通用户": "请用简单直白的表达",
            }
            if detected_audience in audience_hints:
                enhanced_parts.append(audience_hints[detected_audience])
        
        # 添加用户的主要需求
        enhanced_parts.append(prompt)
        
        # 添加其他增强项
        for enhancement in enhancements[1:]:
            enhanced_parts.append(enhancement)
        
        # v3.2: 根据检测到的输出格式添加要求
        format_hints = {
            "Markdown": "请用 Markdown 格式输出，包含适当的标题、列表和代码块",
            "JSON": "请输出标准的 JSON 格式，便于程序解析",
            "YAML": "请输出 YAML 格式配置",
            "XML": "请输出 XML 格式数据",
            "表格": "请用表格形式展示数据，包含表头",
            "代码块": "请用代码块输出，包含语法高亮标记",
            "PlantUML": "请用 PlantUML 语法输出",
            "SQL": "请输出可直接执行的 SQL 语句",
        }
        if detected_format and detected_format in format_hints:
            enhanced_parts.append(format_hints[detected_format])
        
        # v3.2: 根据检测到的风格添加要求
        style_hints = {
            "专业正式": "请用正式、专业的语言",
            "轻松幽默": "请用轻松幽默的风格，适度活泼",
            "简洁明了": "请用简洁精炼的语言，直击重点",
            "详细全面": "请详细展开，覆盖所有细节",
            "技术风格": "请用技术术语，体现专业性",
            "口语化": "请用通俗易懂的大白话",
            "学术风格": "请用学术严谨的表达方式",
            "教程风格": "请用教程式写法，逐步引导",
        }
        if detected_style and detected_style in style_hints:
            enhanced_parts.append(style_hints[detected_style])
        
        # 补全缺失信息（原有逻辑）
        if "输出格式" in missing_info and not detected_format:
            enhanced_parts.append("请用 Markdown 格式输出")
        
        if "编程语言" in missing_info:
            enhanced_parts.append("(请用 Python 实现)")
        
        if "输入输出示例" in missing_info:
            enhanced_parts.append("请提供一个简单的示例")
        
        if "数量要求" in missing_info:
            enhanced_parts.append("请提供至少 5 个想法")
        
        if "字数要求" in missing_info:
            enhanced_parts.append("请控制在 200 字以内")
        
        if "风格" in missing_info and not detected_style:
            enhanced_parts.append("请用简洁专业的风格")
        
        # v3.2: 添加约束条件
        for constraint in detected_constraints:
            if "字数" in constraint:
                if "简短" in constraint:
                    enhanced_parts.append("请控制在 100 字以内")
                elif "中等" in constraint:
                    enhanced_parts.append("请控制在 300 字以内")
                elif "详细" in constraint:
                    enhanced_parts.append("请详细展开，可超过 500 字")
            elif "条数" in constraint:
                if "少量" in constraint:
                    enhanced_parts.append("请提供 3-5 条")
                elif "中等" in constraint:
                    enhanced_parts.append("请提供 5-10 条")
                elif "大量" in constraint:
                    enhanced_parts.append("请提供 10 条以上")
        
        return "\n\n".join(enhanced_parts)
    
    def _generate_enhancements(self, original: str, optimized: str) -> List[str]:
        """生成增强项列表"""
        enhancements = []
        
        if len(optimized) > len(original):
            enhancements.append("添加了详细的约束条件")
        
        if "你是一个" in optimized:
            enhancements.append("添加了角色设定")
        
        if "Markdown" in optimized:
            enhancements.append("明确了输出格式")
        
        if "注释" in optimized:
            enhancements.append("添加了注释要求")
        
        if "性能" in optimized.lower():
            enhancements.append("添加了性能要求")
        
        if "步骤" in optimized:
            enhancements.append("要求详细步骤")
        
        if "示例" in optimized:
            enhancements.append("要求添加示例")
        
        if not enhancements:
            enhancements.append("基本格式优化")
        
        return enhancements
    
    def format_result(self, result: OptimizationResult) -> str:
        """格式化结果输出 - v3.2 增强版"""
        output = []
        output.append("=" * 50)
        output.append(f"🔧 Prompt 优化结果 (v{__version__})")
        if result.cached:
            output.append("📦 (来自缓存)")
        output.append("=" * 50)
        output.append("")
        output.append("📝 原始 Prompt:")
        output.append(f"   {result.original}")
        output.append("")
        output.append("✨ 优化后 Prompt:")
        output.append(f"   {result.optimized}")
        output.append("")
        output.append(f"📋 任务类型: {result.task_type}")
        
        # v3.2: 显示更多检测信息
        if result.output_format:
            output.append(f"📄 输出格式: {result.output_format}")
        if result.style:
            output.append(f"🎨 风格: {result.style}")
        if result.audience:
            output.append(f"👥 目标受众: {result.audience}")
        if result.constraints:
            output.append(f"📏 约束: {', '.join(result.constraints)}")
        
        if result.missing_info:
            output.append(f"⚠️ 缺失信息: {', '.join(result.missing_info)}")
        
        if result.enhancements:
            output.append(f"✅ 增强项: {', '.join(result.enhancements)}")
        
        output.append("=" * 50)
        
        return "\n".join(output)
    
    def format_result_compact(self, result: OptimizationResult) -> str:
        """简洁格式化（只输出优化后的 prompt）"""
        return result.optimized
    
    def format_result_json(self, result: OptimizationResult, indent: int = 2) -> str:
        """JSON 格式化"""
        return result.to_json(indent=indent)
    
    def format_result_yaml(self, result: OptimizationResult) -> str:
        """YAML 格式化"""
        return result.to_yaml()
    
    def get_supported_types(self) -> List[str]:
        """获取支持的任务类型"""
        return [k for k in self.config["task_patterns"].keys() if k != "通用任务"]
    
    def get_stats(self) -> dict:
        """获取统计信息 - v3.2 增强版"""
        return {
            "version": __version__,
            "total_task_types": len(self.config["task_patterns"]) - 1,
            "language_patterns": len(self.config["language_patterns"]),
            "format_patterns": len(self.config["format_patterns"]),
            "style_patterns": len(self.config["style_patterns"]),
            "audience_patterns": len(self.config.get("audience_patterns", {})),
            "constraint_patterns": len(self.config.get("constraint_patterns", {})),
            "cache": _prompt_cache.stats(),
        }
    
    def clear_cache(self):
        """清空缓存"""
        _prompt_cache.clear()
    
    def reload_config(self, config_path: Optional[str] = None):
        """重新加载配置"""
        if config_path:
            self.config_path = config_path
        self.config = self._deep_copy(DEFAULT_CONFIG)
        self._load_config()
        self._compile_patterns()
        logger.info("🔄 配置已重新加载")


# ============ 入口函数 ============

def optimize_prompt(
    prompt: str, 
    verbose: bool = True,
    json_output: bool = False,
    use_cache: bool = True
) -> Union[str, OptimizationResult]:
    """优化 prompt 的入口函数"""
    optimizer = PromptOptimizer(use_cache=use_cache)
    result = optimizer.optimize(prompt, use_cache=use_cache)
    
    if json_output:
        if verbose:
            print(result.to_json())
        return result
    
    if verbose:
        print(optimizer.format_result(result))
    
    return result.optimized


def optimize_from_file(
    input_file: str,
    output_file: Optional[str] = None,
    json_output: bool = False,
    use_cache: bool = True
) -> List[OptimizationResult]:
    """从文件批量优化 prompt"""
    optimizer = PromptOptimizer(use_cache=use_cache)
    results = []
    
    input_path = Path(input_file)
    if not input_path.exists():
        raise FileNotFoundError(f"输入文件不存在: {input_file}")
    
    prompts = input_path.read_text(encoding="utf-8").strip().split("\n")
    prompts = [p.strip() for p in prompts if p.strip()]
    
    for i, prompt in enumerate(prompts, 1):
        try:
            result = optimizer.optimize(prompt, use_cache=use_cache)
            results.append(result)
            cached_mark = "📦" if result.cached else "✅"
            print(f"[{i}/{len(prompts)}] {cached_mark} {prompt[:30]}...")
        except Exception as e:
            print(f"[{i}/{len(prompts)}] ❌ {prompt[:30]}... 错误: {e}")
    
    if output_file:
        output_path = Path(output_file)
        if json_output:
            output_path.write_text(
                json.dumps([r.to_dict() for r in results], ensure_ascii=False, indent=2),
                encoding="utf-8"
            )
        else:
            lines = [r.optimized for r in results]
            output_path.write_text("\n\n---\n\n".join(lines), encoding="utf-8")
        print(f"\n📁 结果已保存到: {output_file}")
    
    return results


# ============ CLI 构建函数 ============

def build_parser() -> argparse.ArgumentParser:
    """构建 CLI 参数解析器"""
    parser = argparse.ArgumentParser(
        description=f"🚀 Prompt Optimizer v{__version__} - AI 任务处理器",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  python prompt_optimizer.py "帮我写个排序"
  python prompt_optimizer.py "帮我写个排序" --json
  python prompt_optimizer.py --file input.txt
  python prompt_optimizer.py --clear-cache
  python prompt_optimizer.py --stats
  python prompt_optimizer.py --config custom.yaml
  python -m prompt_optimizer "帮我写个排序"
        """
    )
    
    parser.add_argument("prompt", nargs="?", help="要优化的 prompt")
    parser.add_argument("-f", "--file", help="从文件读取 prompt（每行一个）")
    parser.add_argument("-o", "--output", help="输出文件路径")
    parser.add_argument("-j", "--json", action="store_true", help="输出 JSON 格式")
    parser.add_argument("-v", "--verbose", action="store_true", default=True, help="显示详细信息")
    parser.add_argument("-q", "--quiet", action="store_true", help="静默模式")
    parser.add_argument("--stats", action="store_true", help="显示统计信息")
    parser.add_argument("-t", "--types", action="store_true", help="显示支持的任务类型")
    parser.add_argument("--cache", action="store_true", default=True, help="启用缓存（默认）")
    parser.add_argument("--no-cache", action="store_true", help="禁用缓存")
    parser.add_argument("--clear-cache", action="store_true", help="清空缓存")
    parser.add_argument("-c", "--config", help="配置文件路径")
    parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
    
    return parser


def handle_stats(optimizer: PromptOptimizer):
    """处理统计信息显示"""
    stats = optimizer.get_stats()
    print(f"📊 Prompt Optimizer v{__version__} 统计信息")
    print("=" * 50)
    print(f"  任务类型: {stats['total_task_types']} 种")
    print(f"  编程语言: {stats['language_patterns']} 种")
    print(f"  输出格式: {stats['format_patterns']} 种")
    print(f"  风格模式: {stats['style_patterns']} 种")
    print("")
    print("📦 缓存统计:")
    cache_stats = stats["cache"]
    print(f"  当前大小: {cache_stats['size']}/{cache_stats['maxsize']}")
    print(f"  命中/未命中: {cache_stats['hits']}/{cache_stats['misses']}")
    print(f"  命中率: {cache_stats['hit_rate']}")


def handle_types(optimizer: PromptOptimizer):
    """处理类型列表显示"""
    print("📋 支持的任务类型:")
    print("-" * 40)
    for task_type in optimizer.get_supported_types():
        print(f"  • {task_type}")


def handle_file_mode(args) -> List[OptimizationResult]:
    """处理文件模式"""
    return optimize_from_file(
        args.file, args.output, args.json, 
        use_cache=not args.no_cache
    )


def handle_prompt_mode(args, optimizer: PromptOptimizer):
    """处理单个 prompt 模式"""
    result = optimizer.optimize(args.prompt, use_cache=not args.no_cache)
    
    if args.json:
        print(result.to_json())
    else:
        print(result.optimized)
    
    if args.verbose and not args.quiet:
        cache_status = "📦 缓存命中" if result.cached else "✨ 优化完成"
        print(f"\n{cache_status} | 类型: {result.task_type}", file=sys.stderr)


def main():
    """CLI 入口 - 重构版"""
    parser = build_parser()
    args = parser.parse_args()
    
    # 静默模式
    if args.quiet:
        args.verbose = False
        logger.setLevel(logging.WARNING)
    
    # 确定是否使用缓存
    use_cache = not args.no_cache
    
    # 初始化优化器
    optimizer = PromptOptimizer(config_path=args.config, use_cache=use_cache)
    
    # 清空缓存
    if args.clear_cache:
        optimizer.clear_cache()
        return
    
    # 显示统计信息
    if args.stats:
        handle_stats(optimizer)
        return
    
    # 显示支持的类型
    if args.types:
        handle_types(optimizer)
        return
    
    # 处理输入
    try:
        if args.file:
            results = handle_file_mode(args)
            if args.json and not args.output:
                print(json.dumps([r.to_dict() for r in results], ensure_ascii=False, indent=2))
            return
        
        if args.prompt:
            handle_prompt_mode(args, optimizer)
            return
        
        parser.print_help()
        print(f"\n💡 提示: 请提供 prompt 或使用 --file 从文件读取")
        
    except (ValueError, RuntimeError) as e:
        print(f"❌ 错误: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"❌ 未知错误: {e}", file=sys.stderr)
        sys.exit(1)


# ============ __main__ 入口 ============

if __name__ == "__main__":
    main()

path: test_prompt_optimizer.py
content: #!/usr/bin/env python3
"""
Prompt Optimizer v3.1 测试用例
运行: python test_prompt_optimizer.py
"""

import sys
import time
from prompt_optimizer import PromptOptimizer, OptimizationResult, __version__


def test(name: str, condition: bool, error_msg: str = ""):
    """测试辅助函数"""
    if condition:
        print(f"  ✅ {name}")
        return True
    else:
        print(f"  ❌ {name}: {error_msg}")
        return False


def run_tests():
    """运行所有测试"""
    optimizer = PromptOptimizer(use_cache=True)
    passed = 0
    failed = 0
    
    print(f"\n🧪 Prompt Optimizer v{__version__} 测试\n")
    
    # ============ 版本测试 ============
    print("📌 版本信息测试:")
    
    if test("版本号存在", __version__ and len(__version__) > 0):
        passed += 1
    else:
        failed += 1
    
    # ============ 基础功能测试 ============
    print("\n📌 基础功能测试:")
    
    if test("基础优化", 
            len(optimizer.optimize("帮我写个排序").optimized) > 10):
        passed += 1
    else:
        failed += 1
    
    try:
        optimizer.optimize("")
        test("空 prompt 检测", False, "应该抛出异常")
        failed += 1
    except ValueError:
        test("空 prompt 检测", True)
        passed += 1
    
    try:
        optimizer.optimize("   ")
        test("空白 prompt 检测", False, "应该抛出异常")
        failed += 1
    except ValueError:
        test("空白 prompt 检测", True)
        passed += 1
    
    # ============ 任务类型测试 ============
    print("\n📌 任务类型测试:")
    
    tests = [
        ("帮我写个排序", "写代码"),
        ("审查这段代码", "代码审查"),
        ("重构这段代码", "改写代码"),
        ("帮我写个文档", "写文档"),
        ("写一段推广文案", "写文案"),
        ("帮我总结一下", "总结摘要"),
        ("翻译成英文", "翻译"),
        ("查一下深圳天气", "查资料"),
        ("分析一下这份数据", "数据分析"),
        ("给我几个创业想法", "头脑风暴"),
        ("计算 123+456", "数学计算"),
        ("聊聊AI的发展", "对话聊天"),
        ("你好", "通用任务"),
    ]
    
    for prompt, expected_type in tests:
        result = optimizer.optimize(prompt)
        if test(f"'{prompt}' → {expected_type}", 
                result.task_type == expected_type,
                f"实际: {result.task_type}"):
            passed += 1
        else:
            failed += 1
    
    # ============ 缓存功能测试 ============
    print("\n📌 缓存功能测试:")
    
    optimizer.clear_cache()
    
    prompt = "帮我写个排序"
    result1 = optimizer.optimize(prompt, use_cache=True)
    
    result2 = optimizer.optimize(prompt, use_cache=True)
    
    if test("缓存命中", result2.cached == True):
        passed += 1
    else:
        failed += 1
    
    result3 = optimizer.optimize(prompt, use_cache=False)
    if test("禁用缓存", result3.cached == False):
        passed += 1
    else:
        failed += 1
    
    stats = optimizer.get_stats()
    if test("缓存统计", "cache" in stats and stats["cache"]["hits"] >= 1):
        passed += 1
    else:
        failed += 1
    
    # ============ 增强功能测试 ============
    print("\n📌 增强功能测试:")
    
    result = optimizer.optimize("帮我写个排序")
    if test("代码任务添加角色", 
            "你是一个专业工程师" in result.optimized):
        passed += 1
    else:
        failed += 1
    
    if test("审查任务添加角色", 
            "代码审查专家" in optimizer.optimize("审查这段代码").optimized):
        passed += 1
    else:
        failed += 1
    
    result = optimizer.optimize("帮我写个排序")
    if test("检测缺失编程语言", 
            "编程语言" in result.missing_info):
        passed += 1
    else:
        failed += 1
    
    # ============ 输出格式测试 ============
    print("\n📌 输出格式测试:")
    
    result = optimizer.optimize("帮我写个排序")
    d = result.to_dict()
    if test("to_dict 转换", 
            isinstance(d, dict) and "original" in d):
        passed += 1
    else:
        failed += 1
    
    json_str = result.to_json()
    if test("to_json 转换", 
            isinstance(json_str, str) and "original" in json_str):
        passed += 1
    else:
        failed += 1
    
    # ============ 统计功能测试 ============
    print("\n📌 统计功能测试:")
    
    stats = optimizer.get_stats()
    if test("统计信息含版本", 
            "version" in stats and stats["version"] == __version__):
        passed += 1
    else:
        failed += 1
    
    if test("统计任务类型数", stats["total_task_types"] > 0):
        passed += 1
    else:
        failed += 1
    
    # ============ 缓存管理测试 ============
    print("\n📌 缓存管理测试:")
    
    optimizer.clear_cache()
    stats = optimizer.get_stats()
    if test("清空缓存", stats["cache"]["hits"] == 0 and stats["cache"]["size"] == 0):
        passed += 1
    else:
        failed += 1
    
    # ============ 性能测试 ============
    print("\n📌 性能测试:")
    
    prompts = [f"帮我写个{p}" for p in ["排序", "查找", "冒泡", "快速", "归并"]]
    
    start = time.time()
    for p in prompts:
        optimizer.optimize(p, use_cache=True)
    batch_time = time.time() - start
    
    if test("批量处理", batch_time < 1.0):
        passed += 1
    else:
        failed += 1
    
    # ============ 配置分离测试 ============
    print("\n📌 配置分离测试:")
    
    from config_data import TASK_PATTERNS, LANGUAGE_PATTERNS, FORMAT_PATTERNS
    
    if test("配置分离-task_patterns", isinstance(TASK_PATTERNS, dict) and len(TASK_PATTERNS) > 0):
        passed += 1
    else:
        failed += 1
    
    if test("配置分离-language_patterns", isinstance(LANGUAGE_PATTERNS, dict) and len(LANGUAGE_PATTERNS) > 0):
        passed += 1
    else:
        failed += 1
    
    # ============ v3.2 新增功能测试 ============
    print("\n📌 v3.2 新增任务类型测试:")
    
    new_task_tests = [
        ("帮我写个测试用例", "写测试用例"),
        ("帮我debug这个bug", "代码调试"),
        ("优化一下这段代码的性能", "性能优化"),
        ("做一下安全检查", "安全检查"),
        ("帮我设计一个API", "API设计"),
        ("用什么数据结构好", "数据结构设计"),
    ]
    
    for prompt, expected_type in new_task_tests:
        result = optimizer.optimize(prompt)
        if test(f"'{prompt}' → {expected_type}", 
                result.task_type == expected_type,
                f"实际: {result.task_type}"):
            passed += 1
        else:
            failed += 1
    
    # ============ 输出格式检测测试 ============
    print("\n📌 输出格式检测测试:")
    
    format_tests = [
        ("帮我写个排序，返回json格式", "JSON"),
        ("帮我写个排序，用yaml格式", "YAML"),
        ("帮我写个排序，输出xml", "XML"),
        ("帮我写个排序，用表格展示", "表格"),
    ]
    
    for prompt, expected_format in format_tests:
        result = optimizer.optimize(prompt)
        if test(f"格式检测: {expected_format}", 
                result.output_format == expected_format,
                f"实际: {result.output_format}"):
            passed += 1
        else:
            failed += 1
    
    # ============ 风格检测测试 ============
    print("\n📌 风格检测测试:")
    
    style_tests = [
        ("帮我写个排序，要专业正式的", "专业正式"),
        ("帮我写个排序，轻松幽默点", "轻松幽默"),
        ("帮我写个排序，简洁明了", "简洁明了"),
        ("帮我写个排序，详细全面", "详细全面"),
    ]
    
    for prompt, expected_style in style_tests:
        result = optimizer.optimize(prompt)
        if test(f"风格检测: {expected_style}", 
                result.style == expected_style,
                f"实际: {result.style}"):
            passed += 1
        else:
            failed += 1
    
    # ============ 目标受众检测测试 ============
    print("\n📌 目标受众检测测试:")
    
    audience_tests = [
        ("帮我写个排序，给程序员看", "技术人员"),
        ("帮我写个排序，给产品经理看", "产品经理"),
        ("帮我写个排序，给老板看", "管理者"),
        ("帮我写个排序，我是初学者", "初学者"),
    ]
    
    for prompt, expected_audience in audience_tests:
        result = optimizer.optimize(prompt)
        if test(f"受众检测: {expected_audience}", 
                result.audience == expected_audience,
                f"实际: {result.audience}"):
            passed += 1
        else:
            failed += 1
    
    # ============ 约束条件检测测试 ============
    print("\n📌 约束条件检测测试:")
    
    constraint_tests = [
        ("帮我写个排序，100字以内", "字数限制-简短"),
        ("帮我写个排序，300字", "字数限制-中等"),
        ("帮我写个排序，提供3条", "条数限制-少量"),
        ("帮我写个排序，提供多个", "条数限制-大量"),
    ]
    
    for prompt, expected_constraint in constraint_tests:
        result = optimizer.optimize(prompt)
        if test(f"约束检测: {expected_constraint}", 
                expected_constraint in result.constraints,
                f"实际: {result.constraints}"):
            passed += 1
        else:
            failed += 1
    
    # ============ YAML 输出测试 ============
    print("\n📌 YAML 输出测试:")
    
    result = optimizer.optimize("帮我写个排序")
    if test("to_yaml 方法存在", hasattr(result, 'to_yaml')):
        passed += 1
    else:
        failed += 1
    
    # ============ 统计增强测试 ============
    print("\n📌 统计增强测试:")
    
    stats = optimizer.get_stats()
    if test("统计含 audience_patterns", "audience_patterns" in stats):
        passed += 1
    else:
        failed += 1
    
    if test("统计含 constraint_patterns", "constraint_patterns" in stats):
        passed += 1
    else:
        failed += 1
    
    if test("任务类型 >= 18", stats["total_task_types"] >= 18):
        passed += 1
    else:
        failed += 1
    
    # ============ 汇总 ============
    print("\n" + "=" * 50)
    print(f"📊 测试结果: {passed} 通过, {failed} 失败")
    print("=" * 50)
    
    return failed == 0


if __name__ == "__main__":
    success = run_tests()
    sys.exit(0 if success else 1)

Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)