# All files / modules/book-generator/nodes continuity-edit.node.ts

0% Statements 0/114
0% Branches 0/1
0% Functions 0/1
0% Lines 0/114

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186

     /**
     * 连贯性编辑节点（continuityEditNode）
     *
     * 在所有内容并行生成完后，执行一次全局编辑：
     * - 检查章节过渡是否自然
     * - 检查内容重复
     * - 术语统一
     * - 风格一致性
     * - 交叉引用正确性
     *
     * 输出评估报告和修正后的内容。
     */

    import { GraphState } from '../graph';
    import { bookStore } from '../book-generator.store';
    import { callLLMWithMessages, ChatMessage } from '../../../services/llm';
    import { CONTINUITY_EDIT_SYSTEM_PROMPT } from '../prompts/templates';
    import { PROGRESS } from '../utils';
    import { prisma } from '../../../models';

    export interface ContinuityEditResult {
      overallAssessment: string;
      issues: Array<{
        type: 'transition' | 'duplicate' | 'terminology' | 'style' | 'crossref';
        location: string;
        description: string;
        suggestion: string;
        severity: 'high' | 'medium' | 'low';
      }>;
      fixedContent: Record<string, string>;
    }

    /**
     * 构建连贯性编辑消息
     */
    function buildContinuityEditMessages(
      bookTitle: string,
      chapterContents: Array<{ title: string; content: string }>
    ): ChatMessage[] {
      const chaptersText = chapterContents
        .map((ch, i) => `### 第${i + 1}章：${ch.title}\n\n${ch.content}`)
        .join('\n\n---\n\n');

      return [
        { role: 'system', content: CONTINUITY_EDIT_SYSTEM_PROMPT },
        {
          role: 'user',
          content: `书名：《${bookTitle}》

    以下是全书各章节的完整内容，请检查并修复连贯性问题：

    ${chaptersText}

    请输出 JSON 格式的评估报告和修正内容。`,
        },
      ];
    }

    /**
     * 解析连贯性编辑结果
     */
    function parseContinuityEditResponse(response: string): ContinuityEditResult | null {
      try {
        let cleaned = response.trim();
        const thinkEnd = cleaned.indexOf('</think>');
        if (thinkEnd !== -1) cleaned = cleaned.substring(thinkEnd + 8).trim();
        const match = cleaned.match(/\{[\s\S]*\}/);
        if (!match) return null;

        const data = JSON.parse(match[0]);

        return {
          overallAssessment: data.overallAssessment || '',
          issues: data.issues || [],
          fixedContent: data.fixedContent || {},
        };
      } catch {
        return null;
      }
    }

    /**
     * 连贯性编辑节点
     */
    export async function continuityEditNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
      console.log('[ContinuityEdit] 开始连贯性编辑, bookId:', state.bookId);

      try {
        const book = await bookStore.getById(state.bookId);
        if (!book) {
          console.log('[ContinuityEdit] 书籍不存在，跳过');
          return { progress: PROGRESS.CONTENT_END };
        }

        const bookIdNum = parseInt(state.bookId);

        // 获取所有已完成内容的叶节点
        const leafChapters = await prisma.bookChapter.findMany({
          where: {
            bookId: bookIdNum,
            genStage: 'content_completed',
            content: { not: '' },
          },
          orderBy: { number: 'asc' },
        });

        if (leafChapters.length === 0) {
          console.log('[ContinuityEdit] 无已完成内容的章节，跳过');
          return { progress: PROGRESS.CONTENT_END };
        }

        // 只取 level=1 的章进行编辑（避免内容重复）
        const topChapters = await prisma.bookChapter.findMany({
          where: {
            bookId: bookIdNum,
            level: 1,
            genStage: 'content_completed',
            content: { not: '' },
          },
          orderBy: { number: 'asc' },
        });

        if (topChapters.length < 2) {
          console.log('[ContinuityEdit] 少于2章，无需连贯性编辑');
          return { progress: PROGRESS.CONTENT_END };
        }

        console.log(`[ContinuityEdit] 编辑 ${topChapters.length} 章内容`);

        const chapterInfos = topChapters.map(ch => ({
          title: ch.title,
          content: ch.content,
        }));

        const messages = buildContinuityEditMessages(book.title, chapterInfos);
        const response = await callLLMWithMessages(messages);
        const result = parseContinuityEditResponse(response);

        if (result) {
          console.log(`[ContinuityEdit] 评估: ${result.overallAssessment}`);
          console.log(`[ContinuityEdit] 问题数: ${result.issues.length}`);

          // 记录高严重性问题
          const highIssues = result.issues.filter(i => i.severity === 'high');
          if (highIssues.length > 0) {
            console.warn(`[ContinuityEdit] ⚠️ ${highIssues.length} 个高严重性问题:`);
            highIssues.forEach(i => console.warn(`  - [${i.type}] ${i.location}: ${i.description}`));
          }

          // 应用修正内容（如果有）
          const fixedKeys = Object.keys(result.fixedContent).filter(k => result.fixedContent[k]);
          if (fixedKeys.length > 0) {
            console.log(`[ContinuityEdit] 应用 ${fixedKeys.length} 处修正`);
            // 注意：这里简化处理，fixedContent 的 key 映射到章节索引
            for (const key of fixedKeys) {
              const match = key.match(/\d+/);
              if (match) {
                const chapterIdx = parseInt(match[0]) - 1;
                if (chapterIdx >= 0 && chapterIdx < topChapters.length) {
                  const chapterId = topChapters[chapterIdx].id;
                  await bookStore.updateChapterById(chapterId, {
                    content: result.fixedContent[key],
                  });
                }
              }
            }
          }

          // 持久化评估报告
          await bookStore.update(state.bookId, {
            errorMsg: `[连贯性编辑] ${result.overallAssessment} | 问题: ${result.issues.length}个`,
          } as any);
        } else {
          console.warn('[ContinuityEdit] 解析结果失败，跳过编辑');
        }

        console.log('[ContinuityEdit] 连贯性编辑完成');
        return { progress: PROGRESS.CONTENT_END };
      } catch (error) {
        console.error('[ContinuityEdit] 编辑失败:', error);
        await bookStore.update(state.bookId, { errorMsg: `连贯性编辑失败: ${error instanceof Error ? error.message : '未知'}` } as any);
        // 不阻塞流程
        return { progress: PROGRESS.CONTENT_END, error: '连贯性编辑失败' };
      }
    }