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

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

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
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295

     /**
     * 改写优化节点（rewriteNode）
     *
     * 当质量校验不通过时，根据校验报告的问题对不合格章节进行针对性改写。
     * 改写后回到 quality_check 重新校验，形成质量闭环。
     *
     * 与 quality-check.node.ts 配对使用：
     *   quality_check → (不通过) → rewrite → quality_check → ... → (通过) → continuity_edit
     */

    import { GraphState } from '../graph';
    import { bookStore } from '../book-generator.store';
    import { callLLMWithMessages, ChatMessage } from '../../../services/llm';
    import { callLLMWithRetry, executeNodeWithTimeout, FAULT_TOLERANCE_CONFIG } from '../fault-tolerance';
    import { REWRITE_CHAPTER_SYSTEM_PROMPT } from '../prompts/templates';
    import { PROGRESS } from '../utils';
    import { prisma } from '../../../models';
    import { FailedChapter, QualityCheckResult } from './quality-check.node';
    import { regenerateChapter } from '../stage-manager';

    // ============ 核心逻辑 ============

    /**
     * 从 state 解析上次质量校验结果
     */
    function parseQualityResultFromState(raw: string | undefined): QualityCheckResult | null {
      if (!raw) return null;
      try {
        const data = JSON.parse(raw);
        if (!data.failedChapters || data.failedChapters.length === 0) return null;
        return data as QualityCheckResult;
      } catch {
        return null;
      }
    }

    /**
     * 构建单个章节的改写消息
     */
    function buildRewriteChapterMessages(
      bookTitle: string,
      chapterNumber: number,
      chapterTitle: string,
      originalContent: string,
      failedInfo: FailedChapter
    ): ChatMessage[] {
      // 构建问题清单
      const issuesText = failedInfo.issues
        .map((issue, i) =>
          `${i + 1}. [${issue.severity === 'high' ? '严重' : issue.severity === 'medium' ? '中等' : '轻微'}] ${issue.dimension}：${issue.description}\n   位置：${issue.location}\n   建议：${issue.suggestion}`
        )
        .join('\n\n');

      const scoreText = `通顺:${failedInfo.scores.fluency}/25 | 逻辑:${failedInfo.scores.logic}/25 | 跑题:${failedInfo.scores.relevance}/25 | 达标:${failedInfo.scores.completeness}/25 | 总分:${failedInfo.totalScore}/100`;

      return [
        { role: 'system', content: REWRITE_CHAPTER_SYSTEM_PROMPT },
        {
          role: 'user',
          content: `书名：《${bookTitle}》
    ## 第${chapterNumber}章：${chapterTitle}

    ### 质量评分
    ${scoreText}

    ### 重写方向
    ${failedInfo.rewriteInstructions}

    ### 发现的问题
    ${issuesText}

    ### 原始内容
    ${originalContent}

    请根据以上反馈，改写本章内容并输出完整结果。`,
        },
      ];
    }

    /**
     * 解析改写响应
     */
    function parseRewriteResponse(response: string): { title: string; rewrittenContent: string; changesSummary: string } | 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) {
          // 如果 AI 直接输出了内容（非 JSON），当作完整改写内容返回
          if (cleaned.length > 200) {
            return { title: '', rewrittenContent: cleaned, changesSummary: '直接输出改写内容' };
          }
          return null;
        }

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

        // 支持单章和多章格式
        if (Array.isArray(chapters) && chapters.length > 0) {
          return {
            title: chapters[0].title || '',
            rewrittenContent: chapters[0].rewrittenContent || chapters[0].content || '',
            changesSummary: chapters[0].changesSummary || '',
          };
        }

        // 单章直接格式
        if (data.rewrittenContent || data.content) {
          return {
            title: data.title || '',
            rewrittenContent: data.rewrittenContent || data.content || '',
            changesSummary: data.changesSummary || '',
          };
        }

        return null;
      } catch (err) {
        console.error('[Rewrite] 解析响应失败:', err);
        return null;
      }
    }

    /**
     * 改写单个章节
     * 返回改写后的内容，失败则返回 null
     */
    async function rewriteSingleChapter(
      bookTitle: string,
      chapterId: number,
      chapterNumber: number,
      chapterTitle: string,
      originalContent: string,
      failedInfo: FailedChapter
    ): Promise<string | null> {
      try {
        console.log(`[Rewrite] 改写第${chapterNumber}章「${chapterTitle}」...`);

        const messages = buildRewriteChapterMessages(
          bookTitle, chapterNumber, chapterTitle, originalContent, failedInfo
        );

        const response = await callLLMWithRetry(
          messages,
          undefined,
          { bookId: String(chapterId), nodeId: 'rewrite', attempt: 0, maxAttempts: FAULT_TOLERANCE_CONFIG.aiRetry.maxRetries }
        );

        const parsed = parseRewriteResponse(response);
        if (!parsed || !parsed.rewrittenContent) {
          console.warn(`[Rewrite] 第${chapterNumber}章改写结果为空`);
          return null;
        }

        // 更新数据库
        await bookStore.updateChapterById(chapterId, {
          content: parsed.rewrittenContent,
        });

        console.log(`[Rewrite] 第${chapterNumber}章改写完成: ${parsed.changesSummary}`);
        return parsed.rewrittenContent;
      } catch (error) {
        console.error(`[Rewrite] 第${chapterNumber}章改写失败:`, error);
        return null;
      }
    }

    /**
     * 改写优化节点
     *
     * 读取质量校验结果，对不合格章节逐一改写。
     * 改写完成后返回 quality_check 重新校验。
     */
    export async function rewriteNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
      const currentCount = state.rewriteCount;
      const maxCount = state.maxRewriteCount;

      console.log(`[Rewrite] 开始改写优化 (第${currentCount + 1}/${maxCount}轮), bookId:`, state.bookId);

      // 超过最大重写次数 → 智能降级：保留所有轮次中评分最高的版本
      if (currentCount >= maxCount) {
        console.warn(`[Rewrite] 已达最大重写次数(${maxCount})，执行智能降级...`);

        // 从 state.qualityResult 中解析历史评分，找出最优版本
        const qualityResult = parseQualityResultFromState(state.qualityResult);
        const bestChapterInfo = qualityResult?.failedChapters?.[0];

        let degradeMsg = `改写已达${maxCount}轮上限，`;
        if (bestChapterInfo && bestChapterInfo.totalScore > 0) {
          degradeMsg += `保留第${bestChapterInfo.chapterNumber}章最佳版本（评分${bestChapterInfo.totalScore}/100），`;
        }
        degradeMsg += '建议人工审核。';

        console.warn(`[Rewrite] ${degradeMsg}`);

        // 持久化降级标记到书籍记录
        try {
          await bookStore.update(state.bookId, {
            errorMsg: `[改写降级] ${degradeMsg}`,
          } as any);
        } catch { /* 记录日志失败不阻塞流程 */ }

        return {
          qualityPassed: true,       // 让流程继续（不高亮失败）
          progress: PROGRESS.CONTENT_END,
          // 不清除 qualityResult，前端可据此展示"需人工审核"提示
        };
      }

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

        const bookIdNum = parseInt(state.bookId);

        // 从 state 读取上次的质量校验结果
        const qualityResult = parseQualityResultFromState(state.qualityResult);
        if (!qualityResult || qualityResult.failedChapters.length === 0) {
          console.log('[Rewrite] 无不合格章节，跳过');
          return { qualityPassed: true, progress: state.progress };
        }

        console.log(`[Rewrite] 需要改写 ${qualityResult.failedChapters.length} 个章节`);

        let successCount = 0;
        let failCount = 0;

        for (const failedInfo of qualityResult.failedChapters) {
          // 从数据库获取对应章节
          const chapter = await prisma.bookChapter.findFirst({
            where: {
              bookId: bookIdNum,
              number: failedInfo.chapterNumber,
              level: 1, // 查找 level=1 的章
            },
            select: { id: true, title: true, content: true },
          });

          if (!chapter || !chapter.content) {
            console.warn(`[Rewrite] 未找到第${failedInfo.chapterNumber}章，跳过`);
            failCount++;
            continue;
          }

          // 先回退状态，允许重新写入
          await regenerateChapter(chapter.id, 'content_generating');

          // 改写
          const result = await rewriteSingleChapter(
            book.title,
            chapter.id,
            failedInfo.chapterNumber,
            chapter.title,
            chapter.content,
            failedInfo
          );

          if (result) {
            // 改写成功，标记为 content_completed
            await bookStore.updateChapterById(chapter.id, {
              genStage: 'content_completed',
            } as any);
            successCount++;
          } else {
            failCount++;
          }
        }

        console.log(`[Rewrite] 改写完成: ${successCount} 成功, ${failCount} 失败`);

        // 持久化改写记录
        await bookStore.update(state.bookId, {
          errorMsg: `[改写优化] 第${currentCount + 1}轮：${successCount}个成功，${failCount}个失败`,
        } as any);

        return {
          rewriteCount: 1, // 累加到 state，由 reducer 处理
          qualityPassed: false, // 重置，让 quality_check 重新判断
          progress: Math.min(state.progress + 2, PROGRESS.CONTENT_END - 3),
        };
      } catch (error) {
        console.error('[Rewrite] 改写失败:', error);
        return {
          rewriteCount: 1, // 累加到 state
          qualityPassed: true, // 容错：失败时通过，避免死循环
          progress: PROGRESS.CONTENT_END,
        };
      }
    }