# 策略类型定义与接口规范

<cite>
**本文档引用的文件**
- [strategies/types.ts](file://server/src/modules/book-generator/strategies/types.ts)
- [strategies/base.ts](file://server/src/modules/book-generator/strategies/base.ts)
- [strategies/selector.ts](file://server/src/modules/book-generator/strategies/selector.ts)
- [strategies/sequential.strategy.ts](file://server/src/modules/book-generator/strategies/sequential.strategy.ts)
- [strategies/one-step-outline.strategy.ts](file://server/src/modules/book-generator/strategies/one-step-outline.strategy.ts)
- [strategies/per-chapter.strategy.ts](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts)
- [strategies/deep-plan-parallel.strategy.ts](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts)
- [graph.ts](file://server/src/modules/book-generator/graph.ts)
- [book-generator.types.ts](file://server/src/modules/book-generator/book-generator.types.ts)
- [book-generator.store.ts](file://server/src/modules/book-generator/book-generator.store.ts)
- [fault-tolerance.ts](file://server/src/modules/book-generator/fault-tolerance.ts)
- [stage-manager.ts](file://server/src/modules/book-generator/stage-manager.ts)
- [book-generator.controller.ts](file://server/src/modules/book-generator/book-generator.controller.ts)
- [book-generator.service.ts](file://server/src/modules/book-generator/book-generator.service.ts)
</cite>

## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖关系分析](#依赖关系分析)
7. [性能考虑](#性能考虑)
8. [故障排查指南](#故障排查指南)
9. [结论](#结论)
10. [附录](#附录)

## 简介
本文件面向策略类型定义与接口规范，系统化阐述书籍生成策略的类型体系、接口契约、执行上下文与状态管理、异常处理与日志规范，并提供扩展指南与最佳实践。策略系统基于 LangGraph 工作流，通过统一的 IBookGenerationStrategy 接口抽象不同生成路径，结合容错层与阶段管理器确保稳定性与可观测性。

## 项目结构
策略相关代码集中在 server/src/modules/book-generator/strategies 下，配合 graph.ts 的状态定义、store.ts 的持久化、stage-manager.ts 的线性阶段管理、fault-tolerance.ts 的容错能力，以及编排服务与控制器对外暴露生成流程。

```mermaid
graph TB
subgraph "策略层"
Types["strategies/types.ts<br/>策略接口与类型"]
Base["strategies/base.ts<br/>基础执行与容错集成"]
Selector["strategies/selector.ts<br/>策略选择器"]
Seq["sequential.strategy.ts"]
OneStep["one-step-outline.strategy.ts"]
PerChapter["per-chapter.strategy.ts"]
DeepPlan["deep-plan-parallel.strategy.ts"]
end
subgraph "执行与状态"
Graph["graph.ts<br/>LangGraph 状态定义"]
Store["book-generator.store.ts<br/>持久化与阶段计算"]
StageMgr["stage-manager.ts<br/>线性阶段管理"]
FT["fault-tolerance.ts<br/>容错与监控"]
end
subgraph "编排与接口"
Ctrl["book-generator.controller.ts<br/>批量生成API"]
Service["book-generator.service.ts<br/>编排与进度推送"]
end
Types --> Seq
Types --> OneStep
Types --> PerChapter
Types --> DeepPlan
Base --> Seq
Base --> OneStep
Base --> PerChapter
Base --> DeepPlan
Selector --> Seq
Selector --> OneStep
Selector --> PerChapter
Selector --> DeepPlan
Seq --> Graph
OneStep --> Graph
PerChapter --> Graph
DeepPlan --> Graph
Graph --> Store
Store --> StageMgr
Base --> FT
Ctrl --> Service
Service --> Store
```

图表来源
- [strategies/types.ts:1-29](file://server/src/modules/book-generator/strategies/types.ts#L1-L29)
- [strategies/base.ts:1-73](file://server/src/modules/book-generator/strategies/base.ts#L1-L73)
- [strategies/selector.ts:1-81](file://server/src/modules/book-generator/strategies/selector.ts#L1-L81)
- [graph.ts:1-83](file://server/src/modules/book-generator/graph.ts#L1-L83)
- [book-generator.store.ts:1-1073](file://server/src/modules/book-generator/book-generator.store.ts#L1-L1073)
- [stage-manager.ts:1-202](file://server/src/modules/book-generator/stage-manager.ts#L1-L202)
- [fault-tolerance.ts:1-387](file://server/src/modules/book-generator/fault-tolerance.ts#L1-L387)
- [book-generator.controller.ts:1-199](file://server/src/modules/book-generator/book-generator.controller.ts#L1-L199)
- [book-generator.service.ts:1-549](file://server/src/modules/book-generator/book-generator.service.ts#L1-L549)

章节来源
- [strategies/types.ts:1-29](file://server/src/modules/book-generator/strategies/types.ts#L1-L29)
- [strategies/base.ts:1-73](file://server/src/modules/book-generator/strategies/base.ts#L1-L73)
- [strategies/selector.ts:1-81](file://server/src/modules/book-generator/strategies/selector.ts#L1-L81)
- [graph.ts:1-83](file://server/src/modules/book-generator/graph.ts#L1-L83)
- [book-generator.store.ts:1-1073](file://server/src/modules/book-generator/book-generator.store.ts#L1-L1073)
- [stage-manager.ts:1-202](file://server/src/modules/book-generator/stage-manager.ts#L1-L202)
- [fault-tolerance.ts:1-387](file://server/src/modules/book-generator/fault-tolerance.ts#L1-L387)
- [book-generator.controller.ts:1-199](file://server/src/modules/book-generator/book-generator.controller.ts#L1-L199)
- [book-generator.service.ts:1-549](file://server/src/modules/book-generator/book-generator.service.ts#L1-L549)

## 核心组件
- IBookGenerationStrategy 接口：统一策略入口，定义 generate(bookId, topic, bookScale, genLevel) 方法与只读 name/description。
- 策略枚举 StrategyName：'sequential' | 'one-step-outline' | 'per-chapter' | 'deep-plan-parallel'。
- 基础执行 runGraphWorkflow：封装 LangGraph 编译、流式执行、进度与最终态更新、失败回退与发布逻辑。
- 策略选择器 StrategySelector：集中注册与切换策略，支持运行时切换。
- LangGraph 状态 GraphState：统一的只增进度、章节完成与失败列表等状态字段。
- 容错层 FaultTolerance：AI重试、节点超时、进度监控、自动恢复与用户通知。
- 阶段管理器 StageManager：线性阶段索引与转移矩阵，安全状态推进与回退。
- 存储层 BookStore：数据库持久化、阶段计算、发布与音频/视频生成集成。
- 编排服务与控制器：批量生成编排、取消与状态查询、进度推送。

章节来源
- [strategies/types.ts:8-29](file://server/src/modules/book-generator/strategies/types.ts#L8-L29)
- [strategies/base.ts:26-73](file://server/src/modules/book-generator/strategies/base.ts#L26-L73)
- [strategies/selector.ts:14-81](file://server/src/modules/book-generator/strategies/selector.ts#L14-L81)
- [graph.ts:23-83](file://server/src/modules/book-generator/graph.ts#L23-L83)
- [fault-tolerance.ts:17-51](file://server/src/modules/book-generator/fault-tolerance.ts#L17-L51)
- [stage-manager.ts:12-67](file://server/src/modules/book-generator/stage-manager.ts#L12-L67)
- [book-generator.store.ts:19-60](file://server/src/modules/book-generator/book-generator.store.ts#L19-L60)
- [book-generator.service.ts:45-143](file://server/src/modules/book-generator/book-generator.service.ts#L45-L143)

## 架构概览
策略系统采用“接口抽象 + 策略实现 + 统一执行框架”的分层设计。所有策略共享 runGraphWorkflow 的执行骨架，仅在工作流图结构上差异；通过 GraphState 统一状态，借助 Store 与 StageMgr 实现持久化与线性阶段演进；FaultTolerance 提供重试、超时与监控；编排服务负责跨步骤的进度与状态协调。

```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "控制器"
participant Orchestrator as "编排器"
participant StrategySel as "策略选择器"
participant Strategy as "具体策略"
participant Base as "基础执行"
participant Graph as "LangGraph"
participant Store as "存储层"
Client->>Controller : "POST /books/ : id/batch-generate"
Controller->>Orchestrator : "创建编排器并执行"
Orchestrator->>StrategySel : "获取当前策略"
StrategySel-->>Orchestrator : "返回策略实例"
Orchestrator->>Strategy : "generate(bookId, topic, scale, level)"
Strategy->>Base : "runGraphWorkflow(bookId, initialState, workflow)"
Base->>Graph : "compile() + stream()"
Graph-->>Base : "流式步骤输出"
Base->>Store : "更新进度/阶段/错误"
Base-->>Strategy : "完成或失败"
Strategy-->>Orchestrator : "返回"
Orchestrator-->>Controller : "返回执行结果"
Controller-->>Client : "任务状态/进度"
```

图表来源
- [book-generator.controller.ts:24-119](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L119)
- [book-generator.service.ts:96-143](file://server/src/modules/book-generator/book-generator.service.ts#L96-L143)
- [strategies/selector.ts:61-77](file://server/src/modules/book-generator/strategies/selector.ts#L61-L77)
- [strategies/sequential.strategy.ts:33-58](file://server/src/modules/book-generator/strategies/sequential.strategy.ts#L33-L58)
- [strategies/base.ts:35-72](file://server/src/modules/book-generator/strategies/base.ts#L35-L72)
- [graph.ts:18-44](file://server/src/modules/book-generator/graph.ts#L18-L44)
- [book-generator.store.ts:402-428](file://server/src/modules/book-generator/book-generator.store.ts#L402-L428)

## 详细组件分析

### IBookGenerationStrategy 接口规范
- 角色：定义所有生成策略的统一契约，屏蔽具体工作流细节。
- 关键字段
  - name: 策略名称（只读，枚举值之一）
  - description: 策略描述（只读）
- 关键方法
  - generate(bookId, topic, bookScale, genLevel): Promise<void>
    - 输入：书籍标识、主题/描述、书籍规模 key、大纲层级（已解析为数值）
    - 输出：Promise<void>，通过 runGraphWorkflow 统一处理进度与最终态
- 参数类型
  - bookId: string
  - topic: string
  - bookScale: string
  - genLevel: number
- 返回值结构
  - 无显式返回值；通过状态更新与发布逻辑反映结果

章节来源
- [strategies/types.ts:8-22](file://server/src/modules/book-generator/strategies/types.ts#L8-L22)

### 策略参数类型与返回值结构
- 策略名称枚举 StrategyName：'sequential' | 'one-step-outline' | 'per-chapter' | 'deep-plan-parallel'
- 策略配置 StrategyConfig：current: StrategyName
- generate 方法签名与语义
  - 语义：驱动 LangGraph 工作流，按策略构建节点与边，初始化 GraphState，交由 runGraphWorkflow 执行
  - 无返回值；通过 Store 更新书籍/章节阶段与进度

章节来源
- [strategies/types.ts:5-29](file://server/src/modules/book-generator/strategies/types.ts#L5-L29)
- [strategies/sequential.strategy.ts:25-58](file://server/src/modules/book-generator/strategies/sequential.strategy.ts#L25-L58)
- [strategies/one-step-outline.strategy.ts:25-54](file://server/src/modules/book-generator/strategies/one-step-outline.strategy.ts#L25-L54)
- [strategies/per-chapter.strategy.ts:25-55](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L25-L55)
- [strategies/deep-plan-parallel.strategy.ts:36-72](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L36-L72)

### 执行上下文与 GraphState
- GraphState 字段（只增/累加语义）
  - bookId, userId, topic, bookScale, description: 字符串或数字，reducer 保留更新值
  - genLevel: number，默认2，代表章→节→小节层级
  - bookPlan: string | undefined，规划结果
  - currentChapter: number，当前处理章节号（只增）
  - completedChapters: number[]，已完成章节号列表（累加）
  - finished: boolean
  - error: string | undefined
  - progress: number，0-100，只增不减
  - failedChapters: number[]，失败章节列表（累加）
- 进度与阶段更新
  - runGraphWorkflow 在流式执行后读取最终书籍状态，更新 progress 与 genStage
  - 若最终阶段为 video_completed，自动发布专辑

章节来源
- [graph.ts:23-83](file://server/src/modules/book-generator/graph.ts#L23-L83)
- [strategies/base.ts:31-61](file://server/src/modules/book-generator/strategies/base.ts#L31-L61)

### 策略执行生命周期与状态传递
- 生命周期
  - 初始化：构建 StateGraph，添加节点与边，设置入口节点
  - 执行：compile() + stream() 流式消费步骤输出
  - 收尾：读取最终书籍状态，更新 progress/genStage，必要时发布
- 状态传递
  - 通过 GraphState 在节点间传递 bookId/topic/scale/level 等上下文
  - Store 作为最终落库点，StageMgr 保证线性阶段合法演进
- 并发与并行
  - sequential：严格串行
  - one-step-outline：先大纲后内容并行
  - per-chapter：先章大纲后每章独立并行
  - deep-plan-parallel：深度规划→富大纲→并发内容→连贯性编辑

章节来源
- [strategies/sequential.strategy.ts:33-58](file://server/src/modules/book-generator/strategies/sequential.strategy.ts#L33-L58)
- [strategies/one-step-outline.strategy.ts:33-54](file://server/src/modules/book-generator/strategies/one-step-outline.strategy.ts#L33-L54)
- [strategies/per-chapter.strategy.ts:33-55](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L33-L55)
- [strategies/deep-plan-parallel.strategy.ts:44-72](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L44-L72)
- [strategies/base.ts:35-72](file://server/src/modules/book-generator/strategies/base.ts#L35-L72)

### 策略异常处理机制与错误码
- 容错层 FaultTolerance
  - AI调用重试：最多3次，指数退避，记录失败日志并通知用户
  - 节点超时：按节点类型配置超时阈值，超时后通知并触发恢复
  - 进度监控：超过最大空闲时间发出警告，多次无响应后自动恢复
  - 自动恢复：重新入队任务，限制最大恢复次数
- 错误码与日志
  - 错误码：统一使用字符串错误消息；容错层记录到书籍 errorMsg 字段
  - 日志：控制台输出关键事件（重试、超时、恢复、失败）
- 失败回退
  - runGraphWorkflow 捕获异常，将书籍 genStage 设为 failed，记录失败阶段与错误信息

章节来源
- [fault-tolerance.ts:68-123](file://server/src/modules/book-generator/fault-tolerance.ts#L68-L123)
- [fault-tolerance.ts:131-180](file://server/src/modules/book-generator/fault-tolerance.ts#L131-L180)
- [fault-tolerance.ts:188-261](file://server/src/modules/book-generator/fault-tolerance.ts#L188-L261)
- [fault-tolerance.ts:268-323](file://server/src/modules/book-generator/fault-tolerance.ts#L268-L323)
- [strategies/base.ts:62-69](file://server/src/modules/book-generator/strategies/base.ts#L62-L69)

### 日志记录规范
- 控制台日志
  - 策略开始/结束、LangGraph 步骤、进度更新、失败与恢复
- 用户通知
  - 通过通知类型区分：ai_retry/ai_failed/node_start/node_complete/node_timeout/progress_warning/progress_critical/auto_recovery/recovery_success/recovery_failed/recovery_error
- 失败记录
  - 将每次失败与尝试次数写入书籍 errorMsg 字段，便于追踪

章节来源
- [fault-tolerance.ts:343-345](file://server/src/modules/book-generator/fault-tolerance.ts#L343-L345)
- [fault-tolerance.ts:352-364](file://server/src/modules/book-generator/fault-tolerance.ts#L352-L364)
- [strategies/sequential.strategy.ts:31](file://server/src/modules/book-generator/strategies/sequential.strategy.ts#L31)
- [strategies/one-step-outline.strategy.ts:31](file://server/src/modules/book-generator/strategies/one-step-outline.strategy.ts#L31)
- [strategies/per-chapter.strategy.ts:31](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L31)
- [strategies/deep-plan-parallel.strategy.ts:42](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L42)

### 扩展指南与自定义策略开发模板
- 开发步骤
  - 实现 IBookGenerationStrategy 接口（name/description/ generate）
  - 在 StateGraph 中添加节点与边，设置入口节点
  - 初始化 GraphState 初始状态（bookId/topic/scale/level/currentChapter/finished/progress 等）
  - 调用 runGraphWorkflow(bookId, initialState, workflow)
- 注册与切换
  - 在 selector.ts 的 STRATEGIES 映射中注册新策略
  - 通过 setCurrentStrategy 或修改 DEFAULT_STRATEGY 生效
- 兼容性保证
  - 保持 generate 方法签名不变
  - 通过 GraphState 传递上下文，避免破坏既有节点契约
  - 使用容错层与进度监控，确保新策略具备稳定性

章节来源
- [strategies/types.ts:8-22](file://server/src/modules/book-generator/strategies/types.ts#L8-L22)
- [strategies/selector.ts:14-56](file://server/src/modules/book-generator/strategies/selector.ts#L14-L56)
- [strategies/sequential.strategy.ts:21-58](file://server/src/modules/book-generator/strategies/sequential.strategy.ts#L21-L58)
- [strategies/base.ts:26-73](file://server/src/modules/book-generator/strategies/base.ts#L26-L73)

### 类型安全检查、编译时验证与运行时校验
- 类型安全
  - 使用 TypeScript 枚举与只读属性，确保 name/description 不被意外修改
  - GraphState 使用 Annotation.Root 定义字段与 reducer，避免状态污染
- 编译时验证
  - 接口契约强制 generate 方法签名一致
  - 策略名称枚举限制可选值，减少运行期错误
- 运行时校验
  - 策略选择器对未知策略进行降级与告警
  - 容错层对 AI 调用与节点执行进行超时与重试
  - 阶段管理器对状态转移进行合法性校验与乐观锁写入

章节来源
- [strategies/types.ts:5-29](file://server/src/modules/book-generator/strategies/types.ts#L5-L29)
- [graph.ts:23-83](file://server/src/modules/book-generator/graph.ts#L23-L83)
- [strategies/selector.ts:49-56](file://server/src/modules/book-generator/strategies/selector.ts#L49-L56)
- [fault-tolerance.ts:78-123](file://server/src/modules/book-generator/fault-tolerance.ts#L78-L123)
- [stage-manager.ts:100-147](file://server/src/modules/book-generator/stage-manager.ts#L100-L147)

## 依赖关系分析

```mermaid
classDiagram
class GenerationStrategy {
+name : StrategyName
+description : string
+generate(bookId, topic, bookScale, genLevel) Promise~void~
}
class SequentialStrategy {
+name : "sequential"
+description : string
+generate(...)
}
class OneStepOutlineStrategy {
+name : "one-step-outline"
+description : string
+generate(...)
}
class PerChapterStrategy {
+name : "per-chapter"
+description : string
+generate(...)
}
class DeepPlanParallelStrategy {
+name : "deep-plan-parallel"
+description : string
+generate(...)
}
class StrategySelector {
+getCurrentStrategyName() StrategyName
+setCurrentStrategy(name) void
+getCurrentStrategy() GenerationStrategy
+getAllStrategies() GenerationStrategy[]
+getStrategy(name) GenerationStrategy
}
GenerationStrategy <|.. SequentialStrategy
GenerationStrategy <|.. OneStepOutlineStrategy
GenerationStrategy <|.. PerChapterStrategy
GenerationStrategy <|.. DeepPlanParallelStrategy
StrategySelector --> GenerationStrategy : "管理与切换"
```

图表来源
- [strategies/types.ts:8-29](file://server/src/modules/book-generator/strategies/types.ts#L8-L29)
- [strategies/sequential.strategy.ts:21-58](file://server/src/modules/book-generator/strategies/sequential.strategy.ts#L21-L58)
- [strategies/one-step-outline.strategy.ts:21-54](file://server/src/modules/book-generator/strategies/one-step-outline.strategy.ts#L21-L54)
- [strategies/per-chapter.strategy.ts:21-55](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L21-L55)
- [strategies/deep-plan-parallel.strategy.ts:32-72](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L32-L72)
- [strategies/selector.ts:61-81](file://server/src/modules/book-generator/strategies/selector.ts#L61-L81)

章节来源
- [strategies/types.ts:8-29](file://server/src/modules/book-generator/strategies/types.ts#L8-L29)
- [strategies/selector.ts:14-81](file://server/src/modules/book-generator/strategies/selector.ts#L14-L81)

## 性能考虑
- 并行化策略
  - per-chapter 与 deep-plan-parallel 通过并行生成提升吞吐
  - 并行数量与资源限制需结合队列与并发策略配置
- 进度与监控
  - 只增进度避免回退带来的重复计算
  - 进度监控与超时控制降低卡死风险
- 存储与阶段计算
  - 通过章节阶段映射计算书籍阶段，避免全量扫描
  - upsert 创建章节避免重复与竞态

章节来源
- [strategies/per-chapter.strategy.ts:8-11](file://server/src/modules/book-generator/strategies/per-chapter.strategy.ts#L8-L11)
- [strategies/deep-plan-parallel.strategy.ts:8-21](file://server/src/modules/book-generator/strategies/deep-plan-parallel.strategy.ts#L8-L21)
- [graph.ts:12](file://server/src/modules/book-generator/graph.ts#L12)
- [fault-tolerance.ts:188-261](file://server/src/modules/book-generator/fault-tolerance.ts#L188-L261)
- [book-generator.store.ts:470-509](file://server/src/modules/book-generator/book-generator.store.ts#L470-L509)

## 故障排查指南
- 常见问题定位
  - 生成卡住：检查进度监控告警与节点超时配置
  - AI调用失败：查看重试次数与最终失败原因
  - 状态异常：确认阶段转移矩阵与乐观锁写入是否冲突
- 操作建议
  - 使用策略选择器切换到更稳定的策略（如 sequential）
  - 清理取消标志后重新发起任务
  - 检查书籍 errorMsg 字段中的失败记录

章节来源
- [fault-tolerance.ts:214-250](file://server/src/modules/book-generator/fault-tolerance.ts#L214-L250)
- [fault-tolerance.ts:100-123](file://server/src/modules/book-generator/fault-tolerance.ts#L100-L123)
- [stage-manager.ts:100-147](file://server/src/modules/book-generator/stage-manager.ts#L100-L147)
- [book-generator.service.ts:24-40](file://server/src/modules/book-generator/book-generator.service.ts#L24-L40)

## 结论
策略类型定义与接口规范提供了清晰的扩展点与稳定执行框架。通过统一的 IBookGenerationStrategy、GraphState 与 runGraphWorkflow，策略系统实现了高内聚、低耦合的生成能力；结合容错层与阶段管理器，确保了可靠性与可观测性。遵循本文档的扩展指南与最佳实践，可在保证兼容性的前提下快速迭代新的生成策略。

## 附录
- API 与编排
  - 批量生成 API：启动/取消/查询状态，编排器按步骤顺序执行并推送进度
  - 编排器支持取消标志与步骤间检查，确保可控性

章节来源
- [book-generator.controller.ts:24-199](file://server/src/modules/book-generator/book-generator.controller.ts#L24-L199)
- [book-generator.service.ts:45-536](file://server/src/modules/book-generator/book-generator.service.ts#L45-L536)