README.md

# cmdc_skill_engine

**CMDC Skill 自进化引擎** — 对标 [OpenSpace Skill Evolution](https://github.com/OpenSpaceAI/OpenSpace),
对齐 *Agentic Design Patterns* 第 9 章「Learning and Adaptation」。

本库在 CMDC Core 之外运行,负责为 Agent 的 Skill 体系加上**质量追踪 +
自进化**闭环:每次会话结束后,自动更新每个 Skill 的 applied / completion /
effective / fallback 四项指标,并按 FIX / DERIVED / CAPTURED 三种动作派生
新 Skill 版本。

## 核心能力

| 模块 | 职责 |
|------|------|
| `CMDCSkillEngine.Store` | GenServer 委托到 Backend(ETS / SQLite),提供 SkillRecord CRUD + 版本 DAG + 原子计数 |
| `CMDCSkillEngine.Store.Backend.ETS` | 默认内存后端,重启丢失数据 |
| `CMDCSkillEngine.Store.Backend.SQLite` | 基于 `exqlite` 的持久化后端 (v0.2+) |
| `CMDCSkillEngine.QualityTracker` | 计算质量指标 + 趋势判定 + **自动停用低质量 Skill** |
| `CMDCSkillEngine.Analyzer` | `@behaviour CMDC.Plugin`,订阅 `session_start`/`before_prompt`/`after_response`/`after_tool`/`session_end` 产出 `ExecutionAnalysis` |
| `CMDCSkillEngine.Analyzer.LLM` | ReqLLM `generate_object/4` 结构化分析 + 失败降级 (v0.2+) |
| `CMDCSkillEngine.Evolver` | 执行 FIX / DERIVED / CAPTURED 三类进化动作,带 fix 链长度上限 (v0.2+) |
| `CMDCSkillEngine.SkillRanker` | `@behaviour CMDC.Skill.Selector`,按 `effective_rate` 排序 |
| `CMDCSkillEngine.SkillRanker.Semantic` | BM25 + quality + 可选 embedding 的混合排序 (v0.2+) |
| `CMDCSkillEngine` (facade) | `register_skill/1` / `stats/2` / `get_record/1` 等顶层 API |

## 安装

```elixir
# 在业务应用的 mix.exs
defp deps do
  [
    {:cmdc, "~> 0.2"},
    {:cmdc_skill_engine, "~> 0.2"}
  ]
end
```

Store 启动方式:

```elixir
# 使用默认 ETS backend(开发/测试)
children = [CMDCSkillEngine.Store]

# 或者 SQLite 持久化 backend
children = [
  {CMDCSkillEngine.Store,
    backend: CMDCSkillEngine.Store.Backend.SQLite,
    backend_opts: [path: "priv/skills.db"]}
]
```

## 自进化闭环

```text
  Agent 运行
     │
     ▼
  session_end ──▶ Analyzer.handle_event
                       │
                       ▼
                 build_analysis
                       │
                       ├─▶ QualityTracker.update_from_analysis
                       │        │
                       │        ▼
                       │   Store.save_record  (持久化四项指标)
                       │
                       └─▶ EvolutionSuggestion 列表
                                │
                                ▼
                          Evolver (fix/derived/captured)
                                │
                                ▼
                          Store.save_record (新版本入库)
                                │
                                ▼
                   下次会话 SkillRanker 自动选中
                   effective_rate 最高的版本
```

对应 ADP 第 9 章:

- **SL / Few-shot**:Skill 本身即 in-context guidance
- **Strategic 适应**:QualityTracker + SkillRanker 让质量差的 Skill 自动退场
- **SICA 自迭代**:Evolver 的 FIX/DERIVED 将失败路径沉淀为新 Skill

## 快速上手

```elixir
# 1) 在 Application 启动 Store
children = [CMDCSkillEngine.Store]

# 2) 装载项目 Skills
CMDC.Skill.discover(["./skills"])
|> Enum.each(&CMDCSkillEngine.register_skill/1)

# 3) 在 CMDC Agent 接入 Analyzer + SkillRanker
{:ok, session} =
  CMDC.create_agent(
    model: "qwen3-max",
    plugins: [{CMDCSkillEngine.Analyzer, [auto_evolve: false]}],
    skills_dirs: ["./skills"],
    skill_selector: CMDCSkillEngine.SkillRanker
  )

# 4) 会话结束后查看 Skill 质量
{:ok, stats} = CMDCSkillEngine.stats("my-skill-id")
# => %{
#   applied_rate: 0.85,
#   completion_rate: 0.70,
#   effective_rate: 0.60,
#   fallback_rate: 0.15,
#   trend: :improving
# }

# 5) 追溯某个 Skill 的完整演化链
{:ok, chain} = CMDCSkillEngine.version_chain("my-skill-id")
# => [%SkillRecord{origin: :imported}, %SkillRecord{origin: :fixed}, ...]
```

## Analyzer 选项

```elixir
{CMDCSkillEngine.Analyzer,
  enabled: true,                  # 主开关
  auto_evolve: false,             # true 时自动把 suggestions 交给 Evolver
  analysis_model: "openai:gpt-4o-mini", # nil/"builtin"/"rule" 走规则分析
  llm_opts: [
    analysis_timeout: 15_000,
    req_llm_opts: [temperature: 0.1]
  ]
}
```

### 分析路径

- `analysis_model` 设为 LLM spec 时:会话结束时调 `ReqLLM.generate_object/4`
  产出结构化分析,失败自动降级到规则分析。
- `analysis_model` 为 `nil / ""/ "builtin" / "manual" / "rule"`:只走规则
  分析,不联网。

## 进化类型

| 类型 | 父数 | 用途 | 旧版本处理 |
|------|-----|------|------------|
| `:fix` | 1 | 修复现有 Skill(新版本继承名称与路径) | `is_active = false` |
| `:derived` | ≥ 1 | 从多个父 Skill 合成新 Skill | 不动 |
| `:captured` | 0 | 从失败路径捕获全新 Skill | 不存在父 |

## 质量指标语义

| 指标 | 公式 | 含义 |
|------|------|------|
| `applied_rate` | `applied / selections` | Skill 被选中后是否真正被应用 |
| `completion_rate` | `completions / applied` | 应用后任务是否完成 |
| `effective_rate` | `completions / selections` | 端到端效率(Ranker 排序依据) |
| `fallback_rate` | `fallbacks / selections` | 选中但没用上的比率(Skill 不适配信号) |

## 状态

- **v0.2.0 (当前)** — SQLite 持久化后端、LLM 结构化分析、语义排序、自动停用低质量 Skill、fix 链长度上限
- v0.1 — ETS 后端 + 完整 Plugin 生命周期;单节点适用
- v0.3 计划 — Skill usage heatmap、多 Agent 间共享 Store、embedding cache、Skill 自动合并建议

## 开发

```bash
mix compile --warnings-as-errors
mix format --check-formatted
mix credo --strict
mix test
```

## 许可

Apache-2.0