@waterwx/dsh-novel-forge 1.2.1-alpha → 1.3.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +4 -5
  2. package/lib/client.js +2470 -858
  3. package/lib/index.js +2155 -388
  4. package/lib/types/action-guard.d.ts +1 -1
  5. package/lib/types/assets.d.ts +7 -7
  6. package/lib/types/client/api.d.ts +31 -1
  7. package/lib/types/client/llmLive.d.ts +12 -14
  8. package/lib/types/client/panel/LiveFeedLog.d.ts +5 -0
  9. package/lib/types/client/panel/ModelManager.d.ts +2 -2
  10. package/lib/types/client/panel/PromptSlotsView.d.ts +11 -0
  11. package/lib/types/client/panel/TensionView.d.ts +14 -0
  12. package/lib/types/client/panel/TimelineView.d.ts +14 -0
  13. package/lib/types/engine.d.ts +40 -2
  14. package/lib/types/index.d.ts +4 -0
  15. package/lib/types/llm-live.d.ts +65 -34
  16. package/lib/types/llm-retry.d.ts +38 -0
  17. package/lib/types/market-radar-sources.d.ts +1 -1
  18. package/lib/types/prompt-slots.d.ts +57 -0
  19. package/lib/types/prompting.d.ts +2 -2
  20. package/lib/types/protocol.d.ts +283 -3
  21. package/lib/types/snapshots.d.ts +46 -0
  22. package/lib/types/stage-contract.d.ts +1 -1
  23. package/lib/types/tension.d.ts +65 -0
  24. package/lib/types/timeline.d.ts +37 -0
  25. package/package.json +3 -2
  26. package/src/action-guard.ts +1 -1
  27. package/src/assets.ts +300 -268
  28. package/src/assistant.ts +45 -29
  29. package/src/client/api.ts +76 -2
  30. package/src/client/llmLive.ts +26 -16
  31. package/src/client/panel/AssetsTab.tsx +2 -2
  32. package/src/client/panel/LiveFeedLog.tsx +204 -67
  33. package/src/client/panel/ModelManager.tsx +2 -2
  34. package/src/client/panel/NovelPanel.tsx +127 -13
  35. package/src/client/panel/PromptSlotsView.tsx +97 -0
  36. package/src/client/panel/SettingsView.tsx +35 -0
  37. package/src/client/panel/TensionView.tsx +196 -0
  38. package/src/client/panel/TimelineView.tsx +192 -0
  39. package/src/engine.ts +549 -108
  40. package/src/index.ts +12 -0
  41. package/src/llm-live.ts +260 -68
  42. package/src/llm-retry.ts +77 -0
  43. package/src/market-radar-sources.ts +173 -173
  44. package/src/prompt-slots.ts +125 -0
  45. package/src/prompting.ts +8 -8
  46. package/src/protocol.ts +314 -3
  47. package/src/routes.ts +325 -6
  48. package/src/run.ts +4 -0
  49. package/src/snapshots.ts +174 -0
  50. package/src/stage-contract.ts +189 -189
  51. package/src/tension.ts +240 -0
  52. package/src/timeline.ts +159 -0
package/src/engine.ts CHANGED
@@ -33,8 +33,13 @@ import { createUserMessage, BlockAssembler, ReasoningEffortId, type GenerateOpti
33
33
  import type { Context } from '@deepseek-ai/cordis'
34
34
  import { BUILTIN_GENRE_LIBRARY, BUILTIN_PROGRESSION_MODES, emptyProjectAssets, recommendStylePreset, renderAllAssets, styleEngineSystemPrompt, styleFormulaSystemPrompt } from './assets.ts'
35
35
  import { scanAiFlavor } from './ai-scan.ts'
36
- import { emitLive, nextSessionId } from './llm-live.ts'
37
- import { renderOfficialChapterWriterSkeleton } from './prompting.ts'
36
+ import { beginLiveCall, endLiveCall, markFirstToken } from './llm-live.ts'
37
+ import { shouldSwitchModel, withModelFallback } from './llm-retry.ts'
38
+ import { renderTensionBlock } from './tension.ts'
39
+ import { renderPromptSlots } from './prompt-slots.ts'
40
+ import { normalizeTimelineEvent, renderTimelineBlock, sortTimeline } from './timeline.ts'
41
+ import { createSnapshot } from './snapshots.ts'
42
+ import { renderChapterWriterSkeleton } from './prompting.ts'
38
43
  import { NovelActionError } from './action-guard.ts'
39
44
  import { buildChapterContext, renderContextBlocks } from './novel-context.ts'
40
45
  import type {
@@ -45,6 +50,9 @@ import type {
45
50
  AdaptProposeResponse,
46
51
  AuditIssue,
47
52
  AuthorReview,
53
+ ExportScope,
54
+ TimelineEvent,
55
+ TimelineIssue,
48
56
  BreakdownResponse,
49
57
  ChapterPlan,
50
58
  Foreshadow,
@@ -346,58 +354,67 @@ async function complete(
346
354
  options: { system: string; user: string; temperature?: number; maxTokens?: number; reasoning?: 'off' | 'low' | 'high' | 'max'; model?: string; liveLabel?: string },
347
355
  ): Promise<string> {
348
356
  const liveLabel = options.liveLabel ?? 'LLM 调用'
349
- const sessionId = nextSessionId()
350
- const effModel = options.model || config.model
351
- emitLive({ type: 'session_started', sessionId, label: liveLabel, model: effModel, at: new Date().toISOString(), context: { interactionId: sessionId } })
352
- emitLive({ type: 'phase_changed', sessionId, phase: 'streaming', phaseMessage: '模型正在返回内容', at: new Date().toISOString() })
353
357
  const messages: Message[] = [createUserMessage({
354
358
  content: [{ type: 'text', text: options.user }],
355
359
  source: { kind: 'plugin', plugin: 'dsh-novel-forge' },
356
360
  })]
357
- const request: GenerateOptions = {
358
- provider: config.provider,
359
- model: options.model || config.model,
360
- messages,
361
- system: options.system,
362
- maxTokens: options.maxTokens ?? config.maxTokens,
363
- temperature: options.temperature ?? 0.7,
364
- reasoningEffort: ReasoningEffortId(options.reasoning ?? config.reasoningEffort ?? 'off'),
365
- }
366
- const assembler = new BlockAssembler()
367
- for await (const chunk of ctx.llm.stream(request)) {
368
- assembler.push(chunk)
369
- }
370
- const finish = assembler.finish
371
- if (finish.kind === 'error' || finish.kind === 'aborted') {
372
- throw new Error(`LLM 调用失败(${finish.kind}): ${finish.failure.message}`)
373
- }
374
- if (finish.kind === 'max-tokens') {
375
- throw new Error('LLM 输出达到 maxTokens 上限,请增大配置后重试')
361
+ /** 用指定模型跑一次完整调用(含实况打点、token 记账与诊断日志)。 */
362
+ const runOnce = async (model: string): Promise<string> => {
363
+ const live = beginLiveCall({ label: liveLabel, model, system: options.system, user: options.user })
364
+ const request: GenerateOptions = {
365
+ provider: config.provider,
366
+ model,
367
+ messages,
368
+ system: options.system,
369
+ maxTokens: options.maxTokens ?? config.maxTokens,
370
+ temperature: options.temperature ?? 0.7,
371
+ reasoningEffort: ReasoningEffortId(options.reasoning ?? config.reasoningEffort ?? 'off'),
372
+ }
373
+ const assembler = new BlockAssembler()
374
+ for await (const chunk of ctx.llm.stream(request)) {
375
+ if (chunk.type === 'text-delta') markFirstToken(live)
376
+ assembler.push(chunk)
377
+ }
378
+ const finish = assembler.finish
379
+ if (finish.kind === 'error' || finish.kind === 'aborted') {
380
+ const message = `LLM 调用失败(${finish.kind}): ${finish.failure.message}`
381
+ endLiveCall(live, assembler, { phase: 'failed', error: message })
382
+ throw new Error(message)
383
+ }
384
+ if (finish.kind === 'max-tokens') {
385
+ const message = 'LLM 输出达到 maxTokens 上限,请增大配置后重试'
386
+ endLiveCall(live, assembler, { phase: 'failed', error: message })
387
+ throw new Error(message)
388
+ }
389
+ // Diagnostics: log the assembled block shape (reasoning-only turns yield no
390
+ // text blocks — some models answer entirely in the reasoning channel).
391
+ if (process.env.DSH_NOVEL_DEBUG === '1') {
392
+ console.error('[dsh-novel-forge] complete: finish=%j blocks=%j', JSON.stringify(finish), assembler.blocks().map(b => `${b.type}:${'text' in b ? b.text.length : '?'}`))
393
+ }
394
+ const text = textFromAssembler(assembler)
395
+ endLiveCall(live, assembler, { chars: text.length, preview: text.slice(0, 320), phase: text === '' ? 'failed' : 'completed' })
396
+ return text
376
397
  }
398
+ // 主模型失败(网络/限流/额度类)且配置了备用模型时,自动换模型重试一次。
399
+ return withModelFallback({ model: options.model || config.model, fallbackModel: config.fallbackModel }, runOnce)
400
+ }
401
+
402
+ /**
403
+ * 从 assembler 取模型文本;无文本块时回落到 reasoning 通道
404
+ * (部分模型会把答案整个放在思考通道,适配器以 reasoning 块呈现)。
405
+ */
406
+ function textFromAssembler(assembler: BlockAssembler): string {
377
407
  const blocks = assembler.blocks()
378
- // Diagnostics: log the assembled block shape (reasoning-only turns yield no
379
- // text blocks — the v4-flash model can answer entirely in the reasoning
380
- // channel, which the adapter surfaces as a reasoning block).
381
- if (process.env.DSH_NOVEL_DEBUG === '1') {
382
- console.error('[dsh-novel-forge] complete: finish=%j blocks=%j', JSON.stringify(finish), blocks.map(b => `${b.type}:${'text' in b ? b.text.length : '?'}`))
383
- }
384
408
  const textBlocks = blocks
385
409
  .filter((block): block is Extract<StreamChunk, { type: 'block-end' }>['block'] & { type: 'text' } => block.type === 'text')
386
410
  .map(block => block.text)
387
- let text = textBlocks.join('\n').trim()
388
- // v4-flash can answer entirely in the reasoning channel (the adapter
389
- // surfaces that as a 'reasoning' block). Fall back to it when no text came
390
- // back — the reasoning content is the model's actual answer here.
391
- if (text === '') {
392
- const reasoning = blocks
393
- .filter((block): block is { type: 'reasoning'; text: string } => block.type === 'reasoning')
394
- .map(block => block.text)
395
- .join('\n')
396
- .trim()
397
- if (reasoning !== '') text = reasoning
398
- }
399
- emitLive({ type: 'session_completed', sessionId, totalChars: text.length, preview: text.slice(0, 320), at: new Date().toISOString(), phase: text === '' ? 'failed' : 'completed' })
400
- return text
411
+ const text = textBlocks.join('\n').trim()
412
+ if (text !== '') return text
413
+ return blocks
414
+ .filter((block): block is { type: 'reasoning'; text: string } => block.type === 'reasoning')
415
+ .map(block => block.text)
416
+ .join('\n')
417
+ .trim()
401
418
  }
402
419
 
403
420
  /** 解析 JSON 数组;失败或为空时给模型一次修复重试(对齐上游 structuredInvokeRepair 精神)。 */
@@ -712,7 +729,7 @@ function planSystemPrompt(volumes: Volume[] | undefined): string {
712
729
  '3. 严格遵循大纲的人设、金手指规则、战力体系与世界观设定,不得自行发明冲突设定。',
713
730
  '4. 输出必须是合法的 JSON 数组,不要输出任何其他文字或 Markdown 代码块标记。',
714
731
  '5. 数组每个元素格式:{"title": "章节标题(10字以内,有网文感)", "beats": "结构化剧情要点(150-250字,必须包含四段,段间用换行分隔):\\n本章目标:本章要完成的核心推进;\\n剧情要点:主要情节的起承转合(2-4 句);\\n爽点/钩子:本章的爽点兑现或情绪钩子;\\n结尾钩子:本章结尾为下一章埋下的悬念"}',
715
- '6. 每个章节对象可额外包含以下可选字段(尽量给出,缺失则跳过):mustAdvance(数组,本章必须推进的局面/关系/信息/风险/决策变化);mustPreserve(数组,本章必须保持不破坏的项);characterHardFacts(数组,本章不可违背的人物硬事实:身份/阵营/境界/当前位置/知情度);endingHook(字符串,本章结尾钩子要求);obligation(字符串,本章义务合约一句话)。',
732
+ '6. 每个章节对象可额外包含以下可选字段(尽量给出,缺失则跳过):tension(0-100 整数:本章张力目标,对抗/揭示/抉择/代价的强度;铺垫与日常章明显偏低,与相邻章节形成起伏)、mustAdvance(数组,本章必须推进的局面/关系/信息/风险/决策变化);mustPreserve(数组,本章必须保持不破坏的项);characterHardFacts(数组,本章不可违背的人物硬事实:身份/阵营/境界/当前位置/知情度);endingHook(字符串,本章结尾钩子要求);obligation(字符串,本章义务合约一句话)。',
716
733
  '重要:beats 字段内部必须使用 \\n 转义表示换行(JSON 字符串内不得有真实换行符),其余字符串值也不得包含真实换行符,JSON 必须在一段内完整结束。',
717
734
  '重要:直接输出 JSON 结果本身,不要把思考过程或推理内容写在输出里。',
718
735
  volumeBlock,
@@ -723,7 +740,7 @@ function planSystemPrompt(volumes: Volume[] | undefined): string {
723
740
  * `targetChars` 来自每章计划(规划时快照,= 设置的每章目标字数);无则退回默认 3500。
724
741
  * 字数区间按目标动态生成(±15%,取整到百位),避免系统提示词与设置互相冲突。
725
742
  * `lengthRule` 可覆盖第 1 条字数要求(整章修订/改编时按原文长度为准)。 */
726
- function writeSystemPrompt(project: ProjectState, targetChars?: number, lengthRule?: string): string {
743
+ function writeSystemPrompt(project: ProjectState, targetChars?: number, lengthRule?: string, beforeChapter?: number): string {
727
744
  const bible = project.bible
728
745
  const sections: string[] = []
729
746
  if (bible !== undefined) {
@@ -806,7 +823,7 @@ function writeSystemPrompt(project: ProjectState, targetChars?: number, lengthRu
806
823
  sections.push('==================== 内容合规红线(平台硬性要求,最高优先级,违反即失败) ====================')
807
824
  sections.push(COMPLIANCE_REDLINES.join('\n'))
808
825
  sections.push('以上九条为硬性底线,任何情况下不得以任何形式出现或影射;若剧情确需涉及(如批判、反讽),只能以明确否定、揭露、批判的立场呈现,且不得展开细节。')
809
- sections.push(renderOfficialChapterWriterSkeleton({
826
+ sections.push(renderChapterWriterSkeleton({
810
827
  targetChars: target,
811
828
  minChars: lo,
812
829
  maxChars: hi,
@@ -815,6 +832,17 @@ function writeSystemPrompt(project: ProjectState, targetChars?: number, lengthRu
815
832
  tonePreference: '动作、对话、心理交替推进;重大信息用对话/动作/发现呈现。',
816
833
  antiAiRules: '严格遵循上方「反 AI 规则」与写法资产,避免套话与 AI 腔。',
817
834
  }))
835
+ // 故事时间线锚点:只注入本章之前的事件(回写旧章时不被后续章节剧透)。
836
+ const timelineBlock = renderTimelineBlock(project, beforeChapter ?? Number.MAX_SAFE_INTEGER)
837
+ if (timelineBlock !== '') sections.push(timelineBlock)
838
+ // 本章张力(目标值 + 参考曲线位置):写作时把握松紧。
839
+ if (beforeChapter !== undefined) {
840
+ const tensionBlock = renderTensionBlock(project, beforeChapter)
841
+ if (tensionBlock !== '') sections.push(tensionBlock)
842
+ }
843
+ // 作者自定义槽位(只影响表达方式,不覆盖道藏/红线/合规)。
844
+ const slotBlock = renderPromptSlots(project)
845
+ if (slotBlock !== '') sections.push(slotBlock)
818
846
  return sections.join('\n')
819
847
  }
820
848
 
@@ -993,6 +1021,9 @@ export async function planChapters(
993
1021
  beats,
994
1022
  targetChars: config.chapterChars,
995
1023
  status: 'pending',
1024
+ tension: typeof entry.tension === 'number' && Number.isFinite(entry.tension)
1025
+ ? Math.max(0, Math.min(100, Math.round(entry.tension)))
1026
+ : undefined,
996
1027
  mustAdvance: strArr(entry.mustAdvance).slice(0, 4),
997
1028
  mustPreserve: strArr(entry.mustPreserve).slice(0, 4),
998
1029
  characterHardFacts: strArr(entry.characterHardFacts).slice(0, 6),
@@ -1048,8 +1079,8 @@ function reviewSystemPrompt(project: ProjectState): string {
1048
1079
  '8. 呈现方式:整章是否纯内心推理铺陈(无对话/无对抗,推理全靠解说);反派是否纯背景板无行动;重要配角是否无名标签化(瘦高个/灰衣人全程代称)——命中即列为问题。',
1049
1080
  '9. 内容合规(最高优先级):逐条核对下方「内容合规红线」,任何一条命中(含影射、暗示、详细描写)必须列为 high,并给出改写建议。',
1050
1081
  '输出必须是合法 JSON 对象,不要输出任何其他文字:',
1051
- '{"score": 0-100的整数, "riskScore": 0-100的整数(越高越需人工处理,可结合本地AI味指数), "verdict": "一句话总评", "issues": [{"severity": "high|medium|low", "dimension": "character|setting|redline|writing|pacing|logic|anti-ai|presentation|compliance", "item": "问题描述", "suggestion": "修改建议", "ruleName": "命中的反AI规则名(见反AI规则清单)", "ruleType": "forbidden|risk|encourage", "category": "套话|句式|段落|心理|设定|节奏|对话|其他", "excerpt": "命中的原文摘录(不超过50字)", "reason": "判定理由", "canAutoRewrite": true|false}]}',
1052
- '维度 dimension 与上方 9 个审查维度一一对应:人设=character、设定=setting、红线=redline、文笔=writing、节奏=pacing、逻辑=logic、反AI=anti-ai、呈现=presentation、合规=compliance。每条 issue 都必须填 dimension。',
1082
+ '{"score": 0-100的整数, "riskScore": 0-100的整数(越高越需人工处理,可结合本地AI味指数), "tension": 0-100的整数(本章张力强度:对抗/揭示/抉择/代价;铺垫与日常章应明显偏低), "verdict": "一句话总评", "issues": [{"severity": "high|medium|low", "dimension": "character|setting|redline|writing|pacing|logic|anti-ai|presentation|compliance", "item": "问题描述", "suggestion": "修改建议", "ruleName": "命中的反AI规则名(见反AI规则清单)", "ruleType": "forbidden|risk|encourage", "category": "套话|句式|段落|心理|设定|节奏|对话|其他", "excerpt": "命中的原文摘录(不超过50字)", "reason": "判定理由", "canAutoRewrite": true|false}]}',
1083
+ 'tension 是本章张力强度评分(不是质量分):对决/揭秘/生死抉择偏高,铺垫章、日常章、过渡章偏低;同一本书内保持同一尺度。',
1053
1084
  '反 AI 类 issue 尽量给出 ruleName/ruleType/category/excerpt/reason/canAutoRewrite,便于统计与自动改写。',
1054
1085
  'AI 套话高频模板词示例(集中出现必须整体降密度):仿佛、似乎、极其、完美、深不见底、形成了、莫名、无法形容、难以言喻、精心雕琢、肤光胜雪、眉目如画、歌舞升平、觥筹交错、妙语连珠、不可名状、另一层真相、命运、真相。',
1055
1086
  '重要:所有字符串值内部不得包含换行符,JSON 必须在一段内完整结束。',
@@ -1105,7 +1136,7 @@ export async function reviewChapter(
1105
1136
  bodyText,
1106
1137
  ].filter(line => line !== '').join('\n')
1107
1138
  const text = await complete(ctx, config, { system: reviewSystemPrompt(project), user, temperature: 0.3, maxTokens: Math.max(config.maxTokens, 8000), reasoning: config.analysisReasoning ?? 'low', model: config.reviewModel, liveLabel: '审稿' })
1108
- const raw = parseJsonObject<{ score?: unknown; riskScore?: unknown; verdict?: unknown; issues?: unknown; resolvedIds?: unknown; unresolvedIds?: unknown }>(text)
1139
+ const raw = parseJsonObject<{ score?: unknown; riskScore?: unknown; tension?: unknown; verdict?: unknown; issues?: unknown; resolvedIds?: unknown; unresolvedIds?: unknown }>(text)
1109
1140
  const issues = Array.isArray(raw.issues)
1110
1141
  ? raw.issues
1111
1142
  .filter((v): v is Record<string, unknown> => typeof v === 'object' && v !== null)
@@ -1138,6 +1169,9 @@ export async function reviewChapter(
1138
1169
  const report: ReviewReport = {
1139
1170
  score,
1140
1171
  passed,
1172
+ tension: typeof raw.tension === 'number' && Number.isFinite(raw.tension)
1173
+ ? Math.max(0, Math.min(100, Math.round(raw.tension)))
1174
+ : undefined,
1141
1175
  verdict: typeof raw.verdict === 'string' ? raw.verdict.slice(0, 200) : '',
1142
1176
  issues,
1143
1177
  riskScore,
@@ -1798,7 +1832,7 @@ export async function suggestOutlines(
1798
1832
  }
1799
1833
 
1800
1834
  /** 拆书分析:对已写章节做结构/人物/文风/卖点四维体检。
1801
- * 两阶段管道(借鉴 AI-Novel-Writing-Assistant):
1835
+ * 两阶段管道(先抽取候选、再落库):
1802
1836
  * ① 源片段笔记:每章抽取结构化笔记(剧情/人物/设定/写法/卖点/短板信号)
1803
1837
  * ② 分节分析:按维度各跑一次 LLM,输出可读分析稿 + 结构化数据 + 证据链。
1804
1838
  * @param scope 'recent'(默认最近20章) | 'volume:N' | 'all'
@@ -2301,9 +2335,9 @@ export async function designPlotlinePlan(
2301
2335
  }
2302
2336
 
2303
2337
  /** Build the rewrite system prompt (fix review issues / instructions). */
2304
- function rewriteSystemPrompt(project: ProjectState, targetChars?: number): string {
2338
+ function rewriteSystemPrompt(project: ProjectState, targetChars?: number, beforeChapter?: number): string {
2305
2339
  // 整章修订以「与原文相当」为准,不套用目标字数区间(避免与原文长度冲突)。
2306
- const base = writeSystemPrompt(project, targetChars, '1. 输出完整的新正文(不要只输出修改片段、标题、章回名、作者的话或任何 Markdown 标记),字数与原章相当(允许 ±20%)。')
2340
+ const base = writeSystemPrompt(project, targetChars, '1. 输出完整的新正文(不要只输出修改片段、标题、章回名、作者的话或任何 Markdown 标记),字数与原章相当(允许 ±20%)。', beforeChapter)
2307
2341
  return base + '\n\n额外要求:你正在【修订】一章已写好的正文。保留原文中好的部分,只修改需要修改的地方,输出完整的新正文(不要只输出修改片段),字数与原文相当。'
2308
2342
  }
2309
2343
 
@@ -2374,7 +2408,7 @@ export async function* rewriteChapterStream(
2374
2408
  ].filter(line => line !== '').join('\n')
2375
2409
 
2376
2410
  const system = localTarget === undefined
2377
- ? rewriteSystemPrompt(project, chapter.targetChars || config.chapterChars)
2411
+ ? rewriteSystemPrompt(project, chapter.targetChars || config.chapterChars, chapter.no)
2378
2412
  : (() => {
2379
2413
  // 局部修订:补齐合规红线/本书红线/反AI规则/角色卡,加「只改表达不改情节」约束
2380
2414
  const bible = project.bible
@@ -2419,24 +2453,43 @@ export async function* rewriteChapterStream(
2419
2453
  }
2420
2454
 
2421
2455
  yield { frame: 'start' }
2422
- const assembler = new BlockAssembler()
2456
+ const primaryModel = request.model ?? config.model
2457
+ let rewritten = ''
2423
2458
  let streamError: Error | undefined
2424
- for await (const chunk of ctx.llm.stream(request)) {
2425
- assembler.push(chunk)
2426
- if (chunk.type === 'text-delta') yield { frame: 'delta', text: chunk.text }
2427
- }
2428
- const finish = assembler.finish
2429
- if (finish.kind === 'error' || finish.kind === 'aborted') {
2430
- streamError = new Error(`修订失败(${finish.kind}): ${finish.failure.message}`)
2431
- } else if (finish.kind === 'max-tokens') {
2432
- streamError = new Error('修订输出达到 maxTokens 上限,请增大配置后重试')
2433
- }
2434
- const rewritten = assembler
2435
- .blocks()
2436
- .filter((block): block is Extract<StreamChunk, { type: 'block-end' }>['block'] & { type: 'text' } => block.type === 'text')
2437
- .map(block => block.text)
2438
- .join('\n')
2439
- .trim()
2459
+ for (let attempt = 0; attempt < 2; attempt++) {
2460
+ const model = attempt === 0 ? primaryModel : (config.fallbackModel ?? '').trim()
2461
+ if (model === '') break
2462
+ const live = beginLiveCall({
2463
+ label: `修订 · 第${chapterNo}章`,
2464
+ model,
2465
+ system: request.system,
2466
+ user: messages[0]?.content !== undefined ? JSON.stringify(messages[0].content).slice(0, 2000) : undefined,
2467
+ })
2468
+ const assembler = new BlockAssembler()
2469
+ let produced = 0
2470
+ for await (const chunk of ctx.llm.stream({ ...request, model })) {
2471
+ assembler.push(chunk)
2472
+ if (chunk.type === 'text-delta') { produced += chunk.text.length; markFirstToken(live); yield { frame: 'delta', text: chunk.text } }
2473
+ }
2474
+ const finish = assembler.finish
2475
+ streamError = undefined
2476
+ if (finish.kind === 'error' || finish.kind === 'aborted') {
2477
+ streamError = new Error(`修订失败(${finish.kind}): ${finish.failure.message}`)
2478
+ } else if (finish.kind === 'max-tokens') {
2479
+ streamError = new Error('修订输出达到 maxTokens 上限,请增大配置后重试')
2480
+ }
2481
+ rewritten = assembler
2482
+ .blocks()
2483
+ .filter((block): block is Extract<StreamChunk, { type: 'block-end' }>['block'] & { type: 'text' } => block.type === 'text')
2484
+ .map(block => block.text)
2485
+ .join('\n')
2486
+ .trim()
2487
+ endLiveCall(live, assembler, streamError === undefined
2488
+ ? { chars: rewritten.length, preview: rewritten.slice(0, 320), phase: rewritten === '' ? 'failed' : 'completed' }
2489
+ : { chars: rewritten.length, phase: 'failed', error: streamError.message })
2490
+ if (streamError === undefined) break
2491
+ if (produced > 0 || !shouldSwitchModel(config.fallbackModel, model, streamError)) break
2492
+ }
2440
2493
  if (streamError !== undefined) throw streamError
2441
2494
  if (rewritten.length < 20) throw new Error('修订结果过短,可能失败,请重试')
2442
2495
 
@@ -2511,24 +2564,43 @@ export async function* polishChapterStream(
2511
2564
  reasoningEffort: ReasoningEffortId('off'),
2512
2565
  }
2513
2566
  yield { frame: 'start' }
2514
- const assembler = new BlockAssembler()
2567
+ const primaryModel = request.model ?? config.model
2568
+ let newBody = ''
2515
2569
  let streamError: Error | undefined
2516
- for await (const chunk of ctx.llm.stream(request)) {
2517
- assembler.push(chunk)
2518
- if (chunk.type === 'text-delta') yield { frame: 'delta', text: chunk.text }
2519
- }
2520
- const finish = assembler.finish
2521
- if (finish.kind === 'error' || finish.kind === 'aborted') {
2522
- streamError = new Error(`润色失败(${finish.kind}): ${finish.failure.message}`)
2523
- } else if (finish.kind === 'max-tokens') {
2524
- streamError = new Error('润色输出达到 maxTokens 上限')
2525
- }
2526
- const newBody = assembler
2527
- .blocks()
2528
- .filter((block): block is Extract<StreamChunk, { type: 'block-end' }>['block'] & { type: 'text' } => block.type === 'text')
2529
- .map(block => block.text)
2530
- .join('\n')
2531
- .trim()
2570
+ for (let attempt = 0; attempt < 2; attempt++) {
2571
+ const model = attempt === 0 ? primaryModel : (config.fallbackModel ?? '').trim()
2572
+ if (model === '') break
2573
+ const live = beginLiveCall({
2574
+ label: `去 AI 味润色 · 第${chapterNo}章`,
2575
+ model,
2576
+ system: request.system,
2577
+ user: body.slice(0, 2000),
2578
+ })
2579
+ const assembler = new BlockAssembler()
2580
+ let produced = 0
2581
+ for await (const chunk of ctx.llm.stream({ ...request, model })) {
2582
+ assembler.push(chunk)
2583
+ if (chunk.type === 'text-delta') { produced += chunk.text.length; markFirstToken(live); yield { frame: 'delta', text: chunk.text } }
2584
+ }
2585
+ const finish = assembler.finish
2586
+ streamError = undefined
2587
+ if (finish.kind === 'error' || finish.kind === 'aborted') {
2588
+ streamError = new Error(`润色失败(${finish.kind}): ${finish.failure.message}`)
2589
+ } else if (finish.kind === 'max-tokens') {
2590
+ streamError = new Error('润色输出达到 maxTokens 上限')
2591
+ }
2592
+ newBody = assembler
2593
+ .blocks()
2594
+ .filter((block): block is Extract<StreamChunk, { type: 'block-end' }>['block'] & { type: 'text' } => block.type === 'text')
2595
+ .map(block => block.text)
2596
+ .join('\n')
2597
+ .trim()
2598
+ endLiveCall(live, assembler, streamError === undefined
2599
+ ? { chars: newBody.length, preview: newBody.slice(0, 320), phase: newBody === '' ? 'failed' : 'completed' }
2600
+ : { chars: newBody.length, phase: 'failed', error: streamError.message })
2601
+ if (streamError === undefined) break
2602
+ if (produced > 0 || !shouldSwitchModel(config.fallbackModel, model, streamError)) break
2603
+ }
2532
2604
  if (streamError !== undefined) throw streamError
2533
2605
  if (newBody.length < 100) throw new Error('润色结果过短,可能失败,请重试')
2534
2606
 
@@ -2658,7 +2730,7 @@ export async function* generateChapterStream(
2658
2730
  provider: config.provider,
2659
2731
  model: config.generateModel || config.model,
2660
2732
  messages,
2661
- system: writeSystemPrompt(project, chapter.targetChars || config.chapterChars),
2733
+ system: writeSystemPrompt(project, chapter.targetChars || config.chapterChars, undefined, chapter.no),
2662
2734
  // Full-chapter output: budget generously (4000 chars ≈ 8-12k tokens,
2663
2735
  // plus the model's reasoning channel).
2664
2736
  maxTokens: Math.max(config.maxTokens, 20000),
@@ -2667,26 +2739,49 @@ export async function* generateChapterStream(
2667
2739
 
2668
2740
  yield { frame: 'start' }
2669
2741
 
2670
- const assembler = new BlockAssembler()
2742
+ const primaryModel = request.model ?? config.model
2743
+ let body = ''
2671
2744
  let streamError: Error | undefined
2672
- for await (const chunk of ctx.llm.stream(request)) {
2673
- assembler.push(chunk)
2674
- if (chunk.type === 'text-delta') {
2675
- yield { frame: 'delta', text: chunk.text }
2745
+ // 最多两次尝试:主模型 → (未产出任何文字且失败可重试时)备用模型。
2746
+ for (let attempt = 0; attempt < 2; attempt++) {
2747
+ const model = attempt === 0 ? primaryModel : (config.fallbackModel ?? '').trim()
2748
+ if (model === '') break
2749
+ const live = beginLiveCall({
2750
+ label: `正文生成 · 第${chapter.no}章`,
2751
+ model,
2752
+ system: request.system,
2753
+ user,
2754
+ })
2755
+ const assembler = new BlockAssembler()
2756
+ let produced = 0
2757
+ for await (const chunk of ctx.llm.stream({ ...request, model })) {
2758
+ assembler.push(chunk)
2759
+ if (chunk.type === 'text-delta') {
2760
+ produced += chunk.text.length
2761
+ markFirstToken(live)
2762
+ yield { frame: 'delta', text: chunk.text }
2763
+ }
2676
2764
  }
2765
+ const finish = assembler.finish
2766
+ streamError = undefined
2767
+ if (finish.kind === 'error' || finish.kind === 'aborted') {
2768
+ streamError = new Error(`生成失败(${finish.kind}): ${finish.failure.message}`)
2769
+ } else if (finish.kind === 'max-tokens') {
2770
+ streamError = new Error('达到 maxTokens 上限,正文可能不完整,请增大 maxTokens 后重试')
2771
+ }
2772
+ body = assembler
2773
+ .blocks()
2774
+ .filter((block): block is Extract<StreamChunk, { type: 'block-end' }>['block'] & { type: 'text' } => block.type === 'text')
2775
+ .map(block => block.text)
2776
+ .join('\n')
2777
+ .trim()
2778
+ endLiveCall(live, assembler, streamError === undefined
2779
+ ? { chars: body.length, preview: body.slice(0, 320), phase: body === '' ? 'failed' : 'completed' }
2780
+ : { chars: body.length, phase: 'failed', error: streamError.message })
2781
+ if (streamError === undefined) break
2782
+ // 只有「一个字都没产出」时才换模型重试——已有正文绝不能重复生成。
2783
+ if (produced > 0 || !shouldSwitchModel(config.fallbackModel, model, streamError)) break
2677
2784
  }
2678
- const finish = assembler.finish
2679
- if (finish.kind === 'error' || finish.kind === 'aborted') {
2680
- streamError = new Error(`生成失败(${finish.kind}): ${finish.failure.message}`)
2681
- } else if (finish.kind === 'max-tokens') {
2682
- streamError = new Error('达到 maxTokens 上限,正文可能不完整,请增大 maxTokens 后重试')
2683
- }
2684
- let body = assembler
2685
- .blocks()
2686
- .filter((block): block is Extract<StreamChunk, { type: 'block-end' }>['block'] & { type: 'text' } => block.type === 'text')
2687
- .map(block => block.text)
2688
- .join('\n')
2689
- .trim()
2690
2785
  if (streamError !== undefined) throw streamError
2691
2786
  if (body.length < 100) throw new Error('生成内容过短,可能失败,请重试')
2692
2787
 
@@ -2702,7 +2797,7 @@ export async function* generateChapterStream(
2702
2797
  `请承接上文继续写约 ${need} 字,不要重复已有内容,不要重写开头,不要总结前文,直接续写新情节,结尾留一个章末钩子。只输出续写的正文,不要输出标题或任何说明。`,
2703
2798
  ].join('\n')
2704
2799
  const cont = await complete(ctx, config, {
2705
- system: writeSystemPrompt(project, target) + '\n\n【续写任务】严格承接已有正文往下写,不要重复已有内容、不要重写开头、不要总结前文,直接续写新情节,并在结尾留一个章末钩子。',
2800
+ system: writeSystemPrompt(project, target, undefined, chapter.no) + '\n\n【续写任务】严格承接已有正文往下写,不要重复已有内容、不要重写开头、不要总结前文,直接续写新情节,并在结尾留一个章末钩子。',
2706
2801
  user: contUser,
2707
2802
  temperature: 0.85,
2708
2803
  maxTokens: Math.max(config.maxTokens, 12000),
@@ -2715,6 +2810,8 @@ export async function* generateChapterStream(
2715
2810
  hanzi = countHanzi(body)
2716
2811
  }
2717
2812
 
2813
+ // 覆盖前留存历史版本:重新生成把好稿改坏时可以回滚(首次生成无旧稿,不产生空快照)。
2814
+ if (chapter.file !== undefined && chapter.file !== '') createSnapshot(outputDir, chapter, '重新生成前')
2718
2815
  // Write the chapter file.
2719
2816
  const fileName = chapterFileName(chapter)
2720
2817
  mkdirSync(outputDir, { recursive: true })
@@ -4204,6 +4301,146 @@ export async function runDirectorAdvice(ctx: Context, config: NovelConfig, proje
4204
4301
  }
4205
4302
  }
4206
4303
 
4304
+ // ---------------------------------------------------------------- timeline
4305
+
4306
+ /**
4307
+ * 从一章正文抽取时间线事件(时间点 / 地点 / 参与角色 / 事件)。
4308
+ *
4309
+ * 会**替换**该章已有事件(重复抽取幂等);抽取结果按 order 递增排序后写回项目。
4310
+ * 失败时抛错,由调用方决定是否降级(自动流程用 try/catch 包住,不阻断出章)。
4311
+ *
4312
+ * @param ctx 宿主上下文。
4313
+ * @param config 运行时配置。
4314
+ * @param project 项目状态(就地更新 `project.timeline`)。
4315
+ * @param outputDir 书目录。
4316
+ * @param chapterNo 章节号。
4317
+ * @returns 本次抽取到的事件(已写入 project)。
4318
+ */
4319
+ export async function extractTimelineForChapter(
4320
+ ctx: Context,
4321
+ config: NovelConfig,
4322
+ project: ProjectState,
4323
+ outputDir: string,
4324
+ chapterNo: number,
4325
+ ): Promise<TimelineEvent[]> {
4326
+ const chapter = project.chapters.find(c => c.no === chapterNo)
4327
+ if (chapter === undefined) throw new NovelActionError('contract', `章节 ${chapterNo} 不在计划中`)
4328
+ const body = readChapterFile(outputDir, chapter)
4329
+ if (body === undefined) throw new NovelActionError('contract', `章节 ${chapterNo} 的正文文件不存在`)
4330
+ const NL = String.fromCharCode(10)
4331
+ const system = [
4332
+ '你是小说连续性编辑。任务:把一章正文压缩成「故事时间线」事件,供后续章节保持时间与地点的连续性。',
4333
+ '要求:',
4334
+ '1. 只抽取**正文里真实发生**的场景节点(3-8 条),不要抽取预告、回忆性的泛泛陈述;纯粹的回忆/插叙请在 event 里注明「(回忆)」并给出其故事内时间。',
4335
+ '2. time 用正文里的说法(如「第三日黄昏」「入宗三个月后」「同日夜」);正文没写时间就填相对说法(如「紧接上一场景」)。',
4336
+ '3. order 是本章内的先后序号,从 1 递增;跨章我会用章号排序,你只需要保证章内顺序正确。',
4337
+ '4. place 是场景地点(一处一个词,如「青云宗外门」);characters 只列**在场**的角色名(用正文里的名字,不要写「主角」)。',
4338
+ '5. event 一句话说清发生了什么(不超过 40 字)。',
4339
+ '输出必须是合法 JSON 数组,不要输出任何其他文字或 Markdown 代码块标记:',
4340
+ '[{"time":"第三日黄昏","order":1,"place":"青云宗外门","characters":["沈青"],"event":"沈青被外门弟子当众羞辱"}]',
4341
+ '重要:字符串值内部不得包含换行符;JSON 必须在一段内完整结束。',
4342
+ ].join('@NL@').replace('@NL@', NL)
4343
+ const text = await complete(ctx, config, {
4344
+ system,
4345
+ user: `第 ${chapterNo} 章《${chapter.title}》正文:@NL@@NL@${body.replace(/^#\s+.*$/m, '').trim().slice(0, 24000)}`.replace('@NL@', NL),
4346
+ temperature: 0.2,
4347
+ maxTokens: Math.max(config.maxTokens, 4000),
4348
+ model: config.auditModel || config.model,
4349
+ liveLabel: `时间线抽取 · 第${chapterNo}章`,
4350
+ })
4351
+ let parsed: unknown = []
4352
+ try {
4353
+ parsed = parseJson<unknown>(text, true)
4354
+ } catch {
4355
+ parsed = []
4356
+ }
4357
+ const rawList = Array.isArray(parsed) ? parsed : []
4358
+ const now = new Date().toISOString()
4359
+ const extracted = rawList
4360
+ .filter((item): item is Record<string, unknown> => typeof item === 'object' && item !== null)
4361
+ .map((item, index) => normalizeTimelineEvent({
4362
+ time: typeof item.time === 'string' ? item.time : '',
4363
+ order: typeof item.order === 'number' ? item.order : index + 1,
4364
+ place: typeof item.place === 'string' ? item.place : '',
4365
+ characters: Array.isArray(item.characters) ? item.characters.filter((c): c is string => typeof c === 'string') : [],
4366
+ event: typeof item.event === 'string' ? item.event : '',
4367
+ }, chapterNo, index, now))
4368
+ .filter(e => e.event !== '')
4369
+ // 保留模型给出的**叙述顺序**(不按 order 重排):时间线检查要靠这个顺序发现
4370
+ // 「自报 order 与叙述顺序打架」;渲染/注入时再用 sortTimeline 按 order 排。
4371
+ const kept = (project.timeline ?? []).filter(e => e.chapterNo !== chapterNo)
4372
+ project.timeline = [...kept, ...extracted]
4373
+ project.updatedAt = now
4374
+ return extracted
4375
+ }
4376
+
4377
+ /**
4378
+ * AI 复核时间线:在规则初筛之外,让模型找规则抓不到的时序问题
4379
+ * (年龄/季节错位、回忆与当前时间混淆、跨章跨度不合理等)。
4380
+ *
4381
+ * @param ctx 宿主上下文。
4382
+ * @param config 运行时配置。
4383
+ * @param project 项目状态。
4384
+ * @returns 模型给出的问题清单(与规则初筛结果合并由调用方决定)。
4385
+ */
4386
+ export async function reviewTimeline(
4387
+ ctx: Context,
4388
+ config: NovelConfig,
4389
+ project: ProjectState,
4390
+ ): Promise<TimelineIssue[]> {
4391
+ const events = sortTimeline(project.timeline ?? [])
4392
+ if (events.length === 0) return []
4393
+ const NL = String.fromCharCode(10)
4394
+ const lines = events.map(e => {
4395
+ const parts = [`第${e.chapterNo}章`]
4396
+ if (e.order !== undefined) parts.push(`#${e.order}`)
4397
+ if (e.time !== '') parts.push(e.time)
4398
+ if (e.place !== '') parts.push(`@${e.place}`)
4399
+ if (e.characters.length > 0) parts.push(`(${e.characters.join('、')})`)
4400
+ parts.push(e.event)
4401
+ return '- ' + parts.join(' ')
4402
+ })
4403
+ const system = [
4404
+ '你是小说连续性编辑,只做一件事:找**时间线**上的矛盾。',
4405
+ '检查项:1) 时间倒流(后一章早于前一章且没有明确插叙标注);2) 地点瞬移(同一人物无移动交代就换场景);',
4406
+ '3) 时间跨度与事件量明显不匹配(如「一日之内」发生跨越数月的剧情);4) 季节/年龄/节日前后矛盾;5) 回忆与现实混淆。',
4407
+ '只报**能在给定事件表里指认**的问题,不要臆测;没有问题就返回空数组。',
4408
+ '输出必须是合法 JSON 数组,不要任何其他文字:',
4409
+ '[{"severity":"high|medium|low","chapters":[3,7],"item":"问题一句话","suggestion":"怎么修"}]',
4410
+ '重要:字符串值内部不得包含换行符。',
4411
+ ].join(NL)
4412
+ const text = await complete(ctx, config, {
4413
+ system,
4414
+ user: `故事时间线(按章节顺序):@NL@${lines.join(NL)}`.replace('@NL@', NL),
4415
+ temperature: 0.2,
4416
+ maxTokens: Math.max(config.maxTokens, 4000),
4417
+ model: config.auditModel || config.model,
4418
+ liveLabel: '时间线复核',
4419
+ })
4420
+ let parsed: unknown = []
4421
+ try {
4422
+ parsed = parseJson<unknown>(text, true)
4423
+ } catch {
4424
+ parsed = []
4425
+ }
4426
+ if (!Array.isArray(parsed)) return []
4427
+ return parsed
4428
+ .filter((item): item is Record<string, unknown> => typeof item === 'object' && item !== null)
4429
+ .map(item => {
4430
+ const severity = item.severity === 'high' || item.severity === 'low' ? item.severity : 'medium'
4431
+ const chapters = Array.isArray(item.chapters)
4432
+ ? item.chapters.filter((c): c is number => typeof c === 'number' && Number.isFinite(c))
4433
+ : []
4434
+ return {
4435
+ severity,
4436
+ chapters,
4437
+ item: typeof item.item === 'string' ? item.item.slice(0, 300) : '',
4438
+ suggestion: typeof item.suggestion === 'string' ? item.suggestion.slice(0, 300) : '',
4439
+ } satisfies TimelineIssue
4440
+ })
4441
+ .filter(issue => issue.item !== '')
4442
+ }
4443
+
4207
4444
  // ------------------------------------------------------------------ export
4208
4445
 
4209
4446
  /** Export the whole book as one txt/md file. */
@@ -4229,3 +4466,207 @@ export function exportBook(outputDir: string, project: ProjectState, format: 'tx
4229
4466
  writeFileSync(join(outputDir, file), content, 'utf8')
4230
4467
  return { file, chars: content.length, chapters: done.length }
4231
4468
  }
4469
+
4470
+ /** 逐行渲染「- 名称:值」清单,跳过空值。 */
4471
+ function renderPairs(pairs: Array<[string, string | undefined]>): string {
4472
+ return pairs
4473
+ .filter(([, v]) => v !== undefined && v !== '')
4474
+ .map(([k, v]) => `- ${k}:${v}`)
4475
+ .join('\n')
4476
+ }
4477
+
4478
+ /** 渲染项目设定(卷首语 / 开书定盘 / 总纲 / 道藏 / 大世界 / 写作资产)。 */
4479
+ function renderSettings(project: ProjectState): string {
4480
+ const out: string[] = [`# ${project.bookName} · 项目设定`, '']
4481
+ out.push('## 卷首语 / 简介', '', project.blurb !== undefined && project.blurb !== '' ? project.blurb : '(未填写)', '')
4482
+ const c = project.bookContract
4483
+ if (c !== undefined) {
4484
+ out.push('## 开书定盘', '', renderPairs([
4485
+ ['书籍承诺', c.promise],
4486
+ ['主推进模式', c.primaryModeName],
4487
+ ['辅助推进模式', (c.secondaryModeNames ?? []).join('、')],
4488
+ ['文风基调', c.tone],
4489
+ ['目标平台', c.targetPlatform],
4490
+ ]), '')
4491
+ }
4492
+ out.push('## 总纲', '', project.outline.trim() === '' ? '(未导入)' : project.outline.trim(), '')
4493
+ const bible = project.bible
4494
+ if (bible !== undefined) {
4495
+ out.push('## 道藏', '')
4496
+ if (bible.worldRules.length > 0) out.push('### 世界规则', '', bible.worldRules.map((r, i) => `${i + 1}. ${r}`).join('\n'), '')
4497
+ if (bible.redLines.length > 0) out.push('### 写作红线', '', bible.redLines.map(r => `- ${r}`).join('\n'), '')
4498
+ if (bible.style.length > 0) out.push('### 文风', '', bible.style.map(x => `- ${x}`).join('\n'), '')
4499
+ if (bible.characters.length > 0) {
4500
+ out.push('### 角色(道藏)', '')
4501
+ for (const ch of bible.characters) {
4502
+ out.push(`- **${ch.name}**(${ch.role})`)
4503
+ if (ch.traits.length > 0) out.push(` - 标签:${ch.traits.join('、')}`)
4504
+ if (ch.goals !== '') out.push(` - 目标:${ch.goals}`)
4505
+ if (ch.relations !== '') out.push(` - 关系:${ch.relations}`)
4506
+ if ((ch.knowledge ?? []).length > 0) out.push(` - 知情:${(ch.knowledge ?? []).join(';')}`)
4507
+ }
4508
+ out.push('')
4509
+ }
4510
+ }
4511
+ const world = project.world
4512
+ if (world !== undefined) {
4513
+ out.push('## 大世界', '')
4514
+ if (world.realms.length > 0) out.push('### 境界体系', '', world.realms.map((r, i) => `${i + 1}. ${r.name}${r.description !== '' ? `:${r.description}` : ''}`).join('\n'), '')
4515
+ if (world.regions.length > 0) out.push('### 区域', '', world.regions.map(r => `- ${r.name}${r.description !== '' ? `:${r.description}` : ''}`).join('\n'), '')
4516
+ if (world.factions.length > 0) out.push('### 势力', '', world.factions.map(f => `- ${f.name}(${f.kind})${f.description !== '' ? `:${f.description}` : ''}`).join('\n'), '')
4517
+ }
4518
+ const assets = project.assets
4519
+ if (assets !== undefined) {
4520
+ const head: Array<[string, string | undefined]> = []
4521
+ if (assets.genre !== undefined) head.push(['题材', assets.genre.name])
4522
+ if (assets.primaryProgression !== undefined) head.push(['主推进', assets.primaryProgression.name])
4523
+ if ((assets.auxiliaryProgressions ?? []).length > 0) head.push(['辅助推进', assets.auxiliaryProgressions.map(a => a.name).join('、')])
4524
+ if (head.length > 0) out.push('## 写作资产', '', renderPairs(head), '')
4525
+ if ((assets.antiAiRules ?? []).length > 0) {
4526
+ out.push('### 反 AI 规则', '')
4527
+ out.push(assets.antiAiRules.map(r => `- ${r.name}:避免「${r.avoid}」→ ${r.fix}`).join('\n'), '')
4528
+ }
4529
+ if ((assets.styleAssets ?? []).length > 0) {
4530
+ out.push('### 笔法帖 / 写法资产', '')
4531
+ out.push(assets.styleAssets.map(x => `- ${x.name}`).join('\n'), '')
4532
+ }
4533
+ }
4534
+ return out.join('\n').replace(/\n(\n)+/g, '\n\n')
4535
+ }
4536
+
4537
+ /** 渲染规划(卷计划 + 章节计划)。 */
4538
+ function renderPlan(project: ProjectState): string {
4539
+ const out: string[] = [`# ${project.bookName} · 规划`, '']
4540
+ const volumes = (project.volumes ?? []).slice().sort((a, b) => a.no - b.no)
4541
+ if (volumes.length > 0) {
4542
+ out.push('## 卷计划', '')
4543
+ for (const v of volumes) {
4544
+ out.push(`### 第${v.no}卷 ${v.title}`, '')
4545
+ if (v.summary !== '') out.push(v.summary, '')
4546
+ }
4547
+ }
4548
+ out.push(`## 章节计划(共 ${project.chapters.length} 章)`, '')
4549
+ for (const c of project.chapters.slice().sort((a, b) => a.no - b.no)) {
4550
+ out.push(`### 第${c.no}章 ${c.title} [${c.status}]`, '')
4551
+ if (c.beats !== '') out.push(c.beats.trim(), '')
4552
+ const extra = renderPairs([
4553
+ ['本章必达', (c.mustAdvance ?? []).join(';')],
4554
+ ['不可破坏', (c.mustPreserve ?? []).join(';')],
4555
+ ['人物硬事实', (c.characterHardFacts ?? []).join(';')],
4556
+ ['结尾钩子', c.endingHook],
4557
+ ['义务合约', c.obligation],
4558
+ ])
4559
+ if (extra !== '') out.push(extra, '')
4560
+ if (c.summary !== undefined && c.summary !== '') out.push(`- 摘要:${c.summary}`, '')
4561
+ }
4562
+ return out.join('\n')
4563
+ }
4564
+
4565
+ /** 渲染角色(角色库 + 人物志)。 */
4566
+ function renderCharacters(project: ProjectState): string {
4567
+ const out: string[] = [`# ${project.bookName} · 角色`, '']
4568
+ const roles = project.roles ?? []
4569
+ out.push(`## 角色库(${roles.length})`, '')
4570
+ if (roles.length === 0) out.push('(空)', '')
4571
+ for (const r of roles) {
4572
+ out.push(`### ${r.name}(${r.roleLabel})`, '')
4573
+ const info = renderPairs([
4574
+ ['身份', r.identity],
4575
+ ['性格', r.traits.join('、')],
4576
+ ['目标', r.goals],
4577
+ ['关系网', r.relations.join(';')],
4578
+ ['成长线', r.arc.join(' → ')],
4579
+ ['知情度', r.knowledge.join(';')],
4580
+ ['首次出场', r.firstChapter !== undefined ? `第${r.firstChapter}章` : undefined],
4581
+ ])
4582
+ if (info !== '') out.push(info, '')
4583
+ }
4584
+ const status = project.roleStatus ?? []
4585
+ if (status.length > 0) {
4586
+ out.push('## 人物志(当前状态)', '')
4587
+ for (const card of status) {
4588
+ out.push(`- **${card.name}**(${card.role})${card.status} — 最近出场第 ${card.lastChapter} 章,累计 ${card.appearances} 次`)
4589
+ }
4590
+ }
4591
+ return out.join('\n')
4592
+ }
4593
+
4594
+ /** 渲染质检记录(逐章审稿 + 作者复盘 + 暗线 + 剧情线 + 待办)。 */
4595
+ function renderReview(project: ProjectState): string {
4596
+ const out: string[] = [`# ${project.bookName} · 质检记录`, '']
4597
+ const reviewed = project.chapters.filter(c => c.review !== undefined).slice().sort((a, b) => a.no - b.no)
4598
+ out.push(`## 审稿(${reviewed.length} / ${project.chapters.length} 章)`, '')
4599
+ for (const c of reviewed) {
4600
+ const r = c.review!
4601
+ out.push(`### 第${c.no}章 ${c.title} ${r.score} 分 · ${r.passed ? '通过' : '未过'}`, '')
4602
+ if (r.verdict !== '') out.push(r.verdict, '')
4603
+ if (r.issues.length > 0) {
4604
+ out.push(r.issues.map(i => `- [${i.severity}] ${i.item}${i.suggestion !== '' ? ` → ${i.suggestion}` : ''}`).join('\n'), '')
4605
+ }
4606
+ }
4607
+ const author = project.chapters.filter(c => c.authorReview !== undefined).slice().sort((a, b) => a.no - b.no)
4608
+ if (author.length > 0) {
4609
+ out.push('## 作者复盘', '')
4610
+ for (const c of author) {
4611
+ const a = c.authorReview!
4612
+ out.push(`### 第${c.no}章 ${c.title}`, '')
4613
+ out.push(renderPairs([
4614
+ ['上一章钩子兑现', a.hookHonored ? '是' : '否'],
4615
+ ['钩子说明', a.hookNote],
4616
+ ['结尾钩子强度', String(a.endingHook)],
4617
+ ['剧情线推进', a.plotlineProgress],
4618
+ ['连续性', a.continuity],
4619
+ ]), '')
4620
+ }
4621
+ }
4622
+ const fores = project.foreshadows ?? []
4623
+ if (fores.length > 0) {
4624
+ out.push('## 暗线 / 伏笔', '')
4625
+ out.push(fores.map(f => `- [${f.status}] ${f.description}${f.targetChapter !== undefined ? `(预计第 ${f.targetChapter} 章回收)` : ''}`).join('\n'), '')
4626
+ }
4627
+ const plotlines = project.plotlines ?? []
4628
+ if (plotlines.length > 0) {
4629
+ out.push('## 剧情线', '')
4630
+ out.push(plotlines.map(l => `- [${l.status}] ${l.name}:${l.goal}(${l.progress})`).join('\n'), '')
4631
+ }
4632
+ const todos = project.todos ?? []
4633
+ if (todos.length > 0) {
4634
+ out.push('## 编辑待办', '')
4635
+ out.push(todos.map(t => `- [${t.done ? 'x' : ' '}] ${t.text}`).join('\n'), '')
4636
+ }
4637
+ return out.join('\n')
4638
+ }
4639
+
4640
+ /**
4641
+ * 按范围导出:整本正文 / 设定 / 规划 / 角色 / 质检记录 / 项目 JSON。
4642
+ *
4643
+ * @param outputDir 书目录。
4644
+ * @param project 项目状态。
4645
+ * @param scope 导出范围。
4646
+ * @param format txt / md / json(json 只对 `project` 范围有独立含义,其余按 md 落盘)。
4647
+ * @returns 文件名、字符数与章节数。
4648
+ */
4649
+ export function exportScope(
4650
+ outputDir: string,
4651
+ project: ProjectState,
4652
+ scope: ExportScope,
4653
+ format: 'txt' | 'md' | 'json',
4654
+ ): { file: string; chars: number; chapters: number } {
4655
+ if (scope === 'book') return exportBook(outputDir, project, format === 'json' ? 'md' : format)
4656
+ if (scope === 'project') {
4657
+ const payload = { schema: 'dsh-novel-forge/project@1', exportedAt: new Date().toISOString(), project }
4658
+ const content = JSON.stringify(payload, null, 2)
4659
+ const file = `《${safeFileName(project.bookName)}》项目备份.json`
4660
+ writeFileSync(join(outputDir, file), content, 'utf8')
4661
+ return { file, chars: content.length, chapters: project.chapters.length }
4662
+ }
4663
+ const body = scope === 'settings' ? renderSettings(project)
4664
+ : scope === 'plan' ? renderPlan(project)
4665
+ : scope === 'characters' ? renderCharacters(project)
4666
+ : renderReview(project)
4667
+ const ext = format === 'json' ? 'md' : format
4668
+ const label = scope === 'settings' ? '项目设定' : scope === 'plan' ? '规划' : scope === 'characters' ? '角色' : '质检记录'
4669
+ const file = `《${safeFileName(project.bookName)}》${label}.${ext}`
4670
+ writeFileSync(join(outputDir, file), body, 'utf8')
4671
+ return { file, chars: body.length, chapters: 0 }
4672
+ }