@waterwx/dsh-novel-forge 1.3.0-alpha → 1.3.1-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.
package/src/run.ts CHANGED
@@ -1,346 +1,391 @@
1
- /**
2
- * 生产单(Production Run):批量章节生产的标准执行器。
3
- * 职责:计划补足 → 逐章生成(完整质量门)→ 被拒分级处理(豁免/修订+验证/待人工)→ 断点续跑。
4
- * 与路由层解耦:只依赖 engine 导出函数与磁盘状态,自身不碰 HTTP。
5
- * 串行纪律:单例执行器 + working 锁;每章重新从磁盘加载,写前合并易变字段。
6
- */
7
- import { existsSync, mkdirSync, readFileSync, copyFileSync, writeFileSync } from 'node:fs'
8
- import { join } from 'node:path'
9
- import type { Context } from '@deepseek-ai/cordis'
10
- import type { ChapterPlan, NovelConfig, ProjectState, ReviewReport, RunState } from './protocol.ts'
11
- import {
12
- loadProject,
13
- saveProject,
14
- mergeVolatileFromDisk,
15
- planChapters,
16
- generateChapterStream,
17
- summarizeAndExtractFacts,
18
- extractTimelineForChapter,
19
- markForeshadowPlanted,
20
- reviewChapter,
21
- reviewChapterText,
22
- authorReviewChapter,
23
- autoLinkPlotlines,
24
- readChapterFile,
25
- rewriteChapterStream,
26
- chapterFileName,
27
- } from './engine.ts'
28
- import { countHanzi } from './engine.ts'
29
- import { loadBookshelf } from './bookshelf.ts'
30
-
31
- /** 生产单 checkpoint 文件名(放在书目录下)。 */
32
- function runStateFile(outputDir: string): string {
33
- return join(outputDir, 'run-state.json')
34
- }
35
-
36
- export class ProductionRunner {
37
- private state: RunState | null = null
38
- private working = false
39
- private pauseRequested = false
40
- private stopRequested = false
41
- /** 生产单绑定目录(start 时快照;所有读写固定用它,防止运行中切书导致写错目录)。 */
42
- private bookDir: string | null = null
43
-
44
- constructor(private deps: { ctx: Context; getConfig: () => NovelConfig }) {}
45
-
46
- /** 当前生产单状态(内存优先;web 重启后从磁盘恢复)。 */
47
- status(): RunState | null {
48
- if (this.state !== null) return this.state
49
- // 重启恢复:先找当前激活书目录,再扫书架所有书目录(防切书后找不到)。
50
- const candidates: string[] = [this.deps.getConfig().outputDir]
51
- const bookshelf = loadBookshelf()
52
- for (const b of bookshelf.books) if (!candidates.includes(b.outputDir)) candidates.push(b.outputDir)
53
- for (const outputDir of candidates) {
54
- const file = runStateFile(outputDir)
55
- if (!existsSync(file)) continue
56
- try {
57
- const raw = readFileSync(file, 'utf8')
58
- const parsed = JSON.parse(raw) as RunState
59
- if (parsed?.runId === undefined) continue
60
- // 重启恢复:若之前 running,则视为可续跑(loop 未在跑)。
61
- if (parsed.status === 'running') parsed.status = 'paused'
62
- this.state = parsed
63
- this.bookDir = outputDir
64
- return this.state
65
- } catch { /* 该目录 run-state 损坏则跳过 */ }
66
- }
67
- return null
68
- }
69
-
70
- private persist(): void {
71
- if (this.state === null) return
72
- const outputDir = this.bookDir ?? this.deps.getConfig().outputDir
73
- mkdirSync(outputDir, { recursive: true })
74
- writeFileSync(runStateFile(outputDir), JSON.stringify(this.state, null, 2), 'utf8')
75
- }
76
-
77
- private log(text: string): void {
78
- if (this.state === null) return
79
- this.state.log.push({ at: new Date().toISOString(), text })
80
- if (this.state.log.length > 300) this.state.log = this.state.log.slice(-300)
81
- this.state.updatedAt = new Date().toISOString()
82
- }
83
-
84
- /** 启动/续跑生产单:startNo..endNo 区间,endNo 超出计划时先自动补计划。 */
85
- async start(startNo: number, endNo: number, runDir?: string): Promise<RunState> {
86
- const config = this.deps.getConfig()
87
- if (this.working) throw new Error('生产单正在运行中,请先暂停或停止')
88
- const outputDir = runDir ?? config.outputDir
89
- let project = loadProject(outputDir)
90
- if (project === undefined) throw new Error('输出目录中没有项目')
91
-
92
- // 计划补足:目标区间超出已有计划 → 续写规划追加。
93
- if (endNo > project.chapters.length) {
94
- const need = endNo - project.chapters.length
95
- this.log(`计划不足,追加 ${need} 章计划…`)
96
- const chapters = await planChapters(this.deps.ctx, config, project, need, undefined, outputDir)
97
- mergeVolatileFromDisk(outputDir, project)
98
- project.chapters.push(...chapters)
99
- project.updatedAt = new Date().toISOString()
100
- saveProject(outputDir, project)
101
- this.log(`计划已追加,全书 ${project.chapters.length} 章`)
102
- }
103
-
104
- this.state = {
105
- runId: `run-${Date.now().toString(36)}`,
106
- startNo,
107
- endNo,
108
- status: 'running',
109
- currentNo: startNo,
110
- stats: { generated: 0, revised: 0, exempted: 0, regenerated: 0, error: 0 },
111
- pendingManual: [],
112
- log: [],
113
- startedAt: new Date().toISOString(),
114
- updatedAt: new Date().toISOString(),
115
- }
116
- this.pauseRequested = false
117
- this.stopRequested = false
118
- // 绑定生产单目录(快照):运行期间切书不影响本单的读写目标。
119
- this.bookDir = outputDir
120
- this.working = true
121
- this.persist()
122
- void this.loop()
123
- return this.state
124
- }
125
-
126
- pause(): void { this.pauseRequested = true }
127
- resume(): void {
128
- if (this.state === null || this.state.status !== 'paused') return
129
- this.state.status = 'running'
130
- this.working = true
131
- this.pauseRequested = false
132
- this.stopRequested = false
133
- this.persist()
134
- void this.loop()
135
- }
136
- stop(): void { this.stopRequested = true }
137
-
138
- /** 是否有生产单正在执行(目录迁移等磁盘级操作前须为 false)。 */
139
- isWorking(): boolean { return this.working }
140
-
141
- /** 主循环:从 currentNo 扫描到 endNo,逐章处理;支持暂停/停止。 */
142
- private async loop(): Promise<void> {
143
- // 全部读写固定使用生产单绑定目录(bookDir),绝不跟随当前激活书。
144
- const config = this.deps.getConfig()
145
- const outputDir = this.bookDir ?? config.outputDir
146
- try {
147
- while (this.state !== null) {
148
- if (this.stopRequested) {
149
- this.stopRequested = false
150
- this.state.status = 'stopped'
151
- this.log('生产单已停止')
152
- this.persist()
153
- break
154
- }
155
- if (this.pauseRequested) {
156
- this.pauseRequested = false
157
- this.state.status = 'paused'
158
- this.log('生产单已暂停(随时可继续)')
159
- this.persist()
160
- break
161
- }
162
- const project = loadProject(outputDir)
163
- if (project === undefined) {
164
- this.state.status = 'error'
165
- this.state.error = '项目丢失'
166
- this.persist()
167
- break
168
- }
169
- // 找下一个需要处理的章(approved 快进)。
170
- let next: ChapterPlan | undefined
171
- for (let no = this.state.currentNo; no <= this.state.endNo; no++) {
172
- const ch = project.chapters.find(c => c.no === no)
173
- if (ch === undefined) continue
174
- if (ch.status === 'approved') { this.state.currentNo = no; continue }
175
- next = ch
176
- break
177
- }
178
- if (next === undefined) {
179
- this.state.status = 'done'
180
- this.log(`生产单完成:${this.state.startNo}-${this.state.endNo} 章处理完毕`)
181
- this.persist()
182
- break
183
- }
184
- this.state.currentNo = next.no
185
- await this.processChapter(project, next)
186
- this.persist()
187
- }
188
- } catch (error) {
189
- if (this.state !== null) {
190
- this.state.status = 'error'
191
- this.state.error = (error as Error).message
192
- this.log(`生产单异常:${(error as Error).message}`)
193
- this.persist()
194
- }
195
- } finally {
196
- this.working = false
197
- }
198
- }
199
-
200
- private async processChapter(project: ProjectState, chapter: ChapterPlan): Promise<void> {
201
- if (chapter.status === 'pending' || chapter.status === 'error' || chapter.status === 'written') {
202
- await this.produce(project, chapter)
203
- } else if (chapter.status === 'rejected') {
204
- await this.handleRejected(project, chapter)
205
- } else if (chapter.status === 'generating') {
206
- // 中断残留:复位重生成。
207
- chapter.status = 'pending'
208
- await this.produce(project, chapter)
209
- }
210
- }
211
-
212
- /** 完整质量门:生成 → 摘要+事实 → 伏笔标记 → 审稿 → 作者复盘。 */
213
- private async produce(project: ProjectState, chapter: ChapterPlan): Promise<void> {
214
- const { ctx, getConfig } = this.deps
215
- const config = getConfig()
216
- const outputDir = this.bookDir ?? config.outputDir
217
- const no = chapter.no
218
- const wasError = chapter.status === 'error'
219
- chapter.status = 'generating'
220
- chapter.error = undefined
221
- chapter.generatingAt = new Date().toISOString()
222
- mergeVolatileFromDisk(outputDir, project)
223
- saveProject(outputDir, project)
224
- this.log(`${wasError ? '重新生成' : '生成'} 第${no}章《${chapter.title}》…(模型 ${config.generateModel || config.model})`)
225
- try {
226
- for await (const _step of generateChapterStream(ctx, config, project, outputDir, no)) { /* drain */ }
227
- try { await summarizeAndExtractFacts(ctx, config, project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run summary/facts:', (e as Error).message) }
228
- if (config.autoTimeline ?? true) {
229
- try { await extractTimelineForChapter(ctx, config, project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run timeline:', (e as Error).message) }
230
- }
231
- try { markForeshadowPlanted(project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run foreshadow:', (e as Error).message) }
232
- if (config.autoReview ?? true) {
233
- const report = await reviewChapter(ctx, config, project, outputDir, no)
234
- if (this.state !== null) this.state.stats[wasError ? 'regenerated' : 'generated']++
235
- this.log(`第${no}章 审稿 ${report.score}分 ${report.passed ? ' 通过' : ' 被拒'}(模型 ${config.reviewModel || config.model})`)
236
- } else {
237
- chapter.status = 'approved'
238
- mergeVolatileFromDisk(outputDir, project)
239
- saveProject(outputDir, project)
240
- }
241
- if (config.autoAuthorReview ?? true) {
242
- try {
243
- const body = readChapterFile(outputDir, chapter)
244
- if (body !== undefined) {
245
- let prevTail = ''
246
- if (no > 1) {
247
- const prev = project.chapters.find(c => c.no === no - 1)
248
- if (prev !== undefined) prevTail = (readChapterFile(outputDir, prev) ?? '').replace(/^#.*$/m, '').trim().slice(-600)
249
- }
250
- const review = await authorReviewChapter(ctx, config, project, no, body, prevTail)
251
- chapter.authorReview = review
252
- if (review.advancedLines !== undefined) autoLinkPlotlines(project, no, review.advancedLines)
253
- // 结果回灌:把本章状态变化/新线索写进编年录事实库,供后续计划与整本控制用。
254
- const backfillFacts: string[] = [...(review.stateChanges ?? []), ...(review.clues ?? [])]
255
- if (backfillFacts.length > 0) {
256
- project.facts ??= []
257
- for (const text of backfillFacts) project.facts.push({ chapterNo: no, text })
258
- }
259
- mergeVolatileFromDisk(outputDir, project)
260
- saveProject(outputDir, project)
261
- }
262
- } catch (e) { console.warn('[dsh-novel-forge] run author review:', (e as Error).message) }
263
- }
264
- } catch (error) {
265
- chapter.status = 'error'
266
- chapter.error = (error as Error).message
267
- mergeVolatileFromDisk(outputDir, project)
268
- saveProject(outputDir, project)
269
- if (this.state !== null) this.state.stats.error++
270
- this.log(`第${no}章 失败:${(error as Error).message}`)
271
- }
272
- }
273
-
274
- /** 被拒分级处理:无 high 豁免;有 high 按意见修订(最多 2 轮)+ 验证模式;仍不过 → 待人工。 */
275
- private async handleRejected(project: ProjectState, chapter: ChapterPlan): Promise<void> {
276
- const { ctx, getConfig } = this.deps
277
- const config = getConfig()
278
- const outputDir = this.bookDir ?? config.outputDir
279
- const no = chapter.no
280
- const report = chapter.review
281
- const highs = (report?.issues ?? []).filter(i => i.severity === 'high')
282
- if (highs.length === 0) {
283
- chapter.status = 'approved'
284
- project.updatedAt = new Date().toISOString()
285
- saveProject(outputDir, project)
286
- if (this.state !== null) this.state.stats.exempted++
287
- this.log(`第${no}章 豁免通过(无 high)`)
288
- return
289
- }
290
- this.log(`第${no}章 修订(${highs.length} 个 high)…`)
291
- for (let round = 1; round <= 2; round++) {
292
- const instr = '按审稿意见修订(优先处理):\n' + highs.map(h => `[${h.severity}] ${h.item}${h.suggestion !== '' ? `\n建议:${h.suggestion}` : ''}`).join('\n\n')
293
- try {
294
- for await (const _step of rewriteChapterStream(ctx, config, project, outputDir, no, instr, undefined)) { /* drain */ }
295
- } catch (error) {
296
- this.log(`第${no}章 第${round}轮修订出错:${(error as Error).message}`)
297
- continue
298
- }
299
- // rewrite 已写盘(pendingDraft + saveProject),重载拿最新草稿。
300
- const fresh = loadProject(outputDir)
301
- const freshCh = fresh?.chapters.find(c => c.no === no)
302
- const draft = freshCh?.pendingDraft
303
- if (draft === undefined || draft.length < 50) {
304
- this.log(`第${no}章 第${round}轮草稿缺失,重试`)
305
- continue
306
- }
307
- const verify = await reviewChapterText(ctx, config, fresh!, draft, chapter.review)
308
- const highs2 = (verify.issues ?? []).filter(i => i.severity === 'high')
309
- if (verify.passed || highs2.length === 0) {
310
- // 应用草稿(与 draft/apply 路由同逻辑):备份原稿 → 落盘 → 定状态。
311
- this.applyDraft(fresh!, freshCh!, draft, verify)
312
- if (this.state !== null) this.state.stats.revised++
313
- this.log(`第${no}章 第${round}轮修订通过(${verify.score}分)`)
314
- return
315
- }
316
- this.log(`第${no}章 第${round}轮仍不过(${highs2.length} high)`)
317
- }
318
- if (this.state !== null) this.state.pendingManual.push(no)
319
- this.log(`第${no}章 两轮修订仍不过 → 保留草稿待人工`)
320
- }
321
-
322
- private applyDraft(project: ProjectState, chapter: ChapterPlan, draft: string, report: ReviewReport): void {
323
- const config = this.deps.getConfig()
324
- const outputDir = this.bookDir ?? config.outputDir
325
- const fileName = chapterFileName(chapter)
326
- mkdirSync(outputDir, { recursive: true })
327
- const targetPath = join(outputDir, fileName)
328
- if (existsSync(targetPath)) {
329
- copyFileSync(targetPath, join(outputDir, `${fileName.replace(/\.md$/, '')}.bak.md`))
330
- }
331
- writeFileSync(targetPath, `# 第${chapter.no}章 ${chapter.title}\n\n${draft}\n`, 'utf8')
332
- chapter.pendingDraft = undefined
333
- chapter.chars = countHanzi(draft)
334
- chapter.file = fileName
335
- if (typeof report.score === 'number') {
336
- chapter.review = report
337
- chapter.status = report.passed === true ? 'approved' : 'rejected'
338
- } else {
339
- chapter.status = 'written'
340
- chapter.review = undefined
341
- }
342
- chapter.error = undefined
343
- project.updatedAt = new Date().toISOString()
344
- saveProject(outputDir, project)
345
- }
346
- }
1
+ /**
2
+ * 生产单(Production Run):批量章节生产的标准执行器。
3
+ * 职责:计划补足 → 逐章生成(完整质量门)→ 被拒分级处理(豁免/修订+验证/待人工)→ 断点续跑。
4
+ * 与路由层解耦:只依赖 engine 导出函数与磁盘状态,自身不碰 HTTP。
5
+ * 串行纪律:单例执行器 + working 锁;每章重新从磁盘加载,写前合并易变字段。
6
+ */
7
+ import { existsSync, mkdirSync, readFileSync, copyFileSync, writeFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import type { Context } from '@deepseek-ai/cordis'
10
+ import type { ChapterPlan, NovelConfig, ProjectState, ReviewReport, RunState } from './protocol.ts'
11
+ import {
12
+ loadProject,
13
+ saveProject,
14
+ mergeVolatileFromDisk,
15
+ planChapters,
16
+ generateChapterStream,
17
+ summarizeAndExtractFacts,
18
+ extractTimelineForChapter,
19
+ markForeshadowPlanted,
20
+ reviewChapter,
21
+ reviewChapterText,
22
+ authorReviewChapter,
23
+ autoLinkPlotlines,
24
+ readChapterFile,
25
+ rewriteChapterStream,
26
+ chapterFileName,
27
+ } from './engine.ts'
28
+ import { countHanzi } from './engine.ts'
29
+ import { loadBookshelf } from './bookshelf.ts'
30
+ import { buildRevisionPlan, describeRevisionPlan, MAX_REVISION_ROUNDS, revisionTodoText } from './revision.ts'
31
+
32
+ /** 生产单 checkpoint 文件名(放在书目录下)。 */
33
+ function runStateFile(outputDir: string): string {
34
+ return join(outputDir, 'run-state.json')
35
+ }
36
+
37
+ export class ProductionRunner {
38
+ private state: RunState | null = null
39
+ private working = false
40
+ private pauseRequested = false
41
+ private stopRequested = false
42
+ /** 生产单绑定目录(start 时快照;所有读写固定用它,防止运行中切书导致写错目录)。 */
43
+ private bookDir: string | null = null
44
+
45
+ constructor(private deps: { ctx: Context; getConfig: () => NovelConfig }) {}
46
+
47
+ /** 当前生产单状态(内存优先;web 重启后从磁盘恢复)。 */
48
+ status(): RunState | null {
49
+ if (this.state !== null) return this.state
50
+ // 重启恢复:先找当前激活书目录,再扫书架所有书目录(防切书后找不到)。
51
+ const candidates: string[] = [this.deps.getConfig().outputDir]
52
+ const bookshelf = loadBookshelf()
53
+ for (const b of bookshelf.books) if (!candidates.includes(b.outputDir)) candidates.push(b.outputDir)
54
+ for (const outputDir of candidates) {
55
+ const file = runStateFile(outputDir)
56
+ if (!existsSync(file)) continue
57
+ try {
58
+ const raw = readFileSync(file, 'utf8')
59
+ const parsed = JSON.parse(raw) as RunState
60
+ if (parsed?.runId === undefined) continue
61
+ // 重启恢复:若之前 running,则视为可续跑(loop 未在跑)。
62
+ if (parsed.status === 'running') parsed.status = 'paused'
63
+ this.state = parsed
64
+ this.bookDir = outputDir
65
+ return this.state
66
+ } catch { /* 该目录 run-state 损坏则跳过 */ }
67
+ }
68
+ return null
69
+ }
70
+
71
+ private persist(): void {
72
+ if (this.state === null) return
73
+ const outputDir = this.bookDir ?? this.deps.getConfig().outputDir
74
+ mkdirSync(outputDir, { recursive: true })
75
+ writeFileSync(runStateFile(outputDir), JSON.stringify(this.state, null, 2), 'utf8')
76
+ }
77
+
78
+ private log(text: string): void {
79
+ if (this.state === null) return
80
+ this.state.log.push({ at: new Date().toISOString(), text })
81
+ if (this.state.log.length > 300) this.state.log = this.state.log.slice(-300)
82
+ this.state.updatedAt = new Date().toISOString()
83
+ }
84
+
85
+ /** 启动/续跑生产单:startNo..endNo 区间,endNo 超出计划时先自动补计划。 */
86
+ async start(startNo: number, endNo: number, runDir?: string): Promise<RunState> {
87
+ const config = this.deps.getConfig()
88
+ if (this.working) throw new Error('生产单正在运行中,请先暂停或停止')
89
+ const outputDir = runDir ?? config.outputDir
90
+ let project = loadProject(outputDir)
91
+ if (project === undefined) throw new Error('输出目录中没有项目')
92
+
93
+ // 计划补足:目标区间超出已有计划 → 续写规划追加。
94
+ if (endNo > project.chapters.length) {
95
+ const need = endNo - project.chapters.length
96
+ this.log(`计划不足,追加 ${need} 章计划…`)
97
+ const chapters = await planChapters(this.deps.ctx, config, project, need, undefined, outputDir)
98
+ mergeVolatileFromDisk(outputDir, project)
99
+ project.chapters.push(...chapters)
100
+ project.updatedAt = new Date().toISOString()
101
+ saveProject(outputDir, project)
102
+ this.log(`计划已追加,全书 ${project.chapters.length} 章`)
103
+ }
104
+
105
+ this.state = {
106
+ runId: `run-${Date.now().toString(36)}`,
107
+ startNo,
108
+ endNo,
109
+ status: 'running',
110
+ currentNo: startNo,
111
+ stats: { generated: 0, revised: 0, exempted: 0, regenerated: 0, error: 0 },
112
+ pendingManual: [],
113
+ log: [],
114
+ startedAt: new Date().toISOString(),
115
+ updatedAt: new Date().toISOString(),
116
+ }
117
+ this.pauseRequested = false
118
+ this.stopRequested = false
119
+ // 绑定生产单目录(快照):运行期间切书不影响本单的读写目标。
120
+ this.bookDir = outputDir
121
+ this.working = true
122
+ this.persist()
123
+ void this.loop()
124
+ return this.state
125
+ }
126
+
127
+ pause(): void { this.pauseRequested = true }
128
+ resume(): void {
129
+ if (this.state === null || this.state.status !== 'paused') return
130
+ this.state.status = 'running'
131
+ this.working = true
132
+ this.pauseRequested = false
133
+ this.stopRequested = false
134
+ this.persist()
135
+ void this.loop()
136
+ }
137
+ stop(): void { this.stopRequested = true }
138
+
139
+ /** 是否有生产单正在执行(目录迁移等磁盘级操作前须为 false)。 */
140
+ isWorking(): boolean { return this.working }
141
+
142
+ /** 主循环:从 currentNo 扫描到 endNo,逐章处理;支持暂停/停止。 */
143
+ private async loop(): Promise<void> {
144
+ // 全部读写固定使用生产单绑定目录(bookDir),绝不跟随当前激活书。
145
+ const config = this.deps.getConfig()
146
+ const outputDir = this.bookDir ?? config.outputDir
147
+ try {
148
+ while (this.state !== null) {
149
+ if (this.stopRequested) {
150
+ this.stopRequested = false
151
+ this.state.status = 'stopped'
152
+ this.log('生产单已停止')
153
+ this.persist()
154
+ break
155
+ }
156
+ if (this.pauseRequested) {
157
+ this.pauseRequested = false
158
+ this.state.status = 'paused'
159
+ this.log('生产单已暂停(随时可继续)')
160
+ this.persist()
161
+ break
162
+ }
163
+ const project = loadProject(outputDir)
164
+ if (project === undefined) {
165
+ this.state.status = 'error'
166
+ this.state.error = '项目丢失'
167
+ this.persist()
168
+ break
169
+ }
170
+ // 找下一个需要处理的章(approved 快进)。
171
+ let next: ChapterPlan | undefined
172
+ for (let no = this.state.currentNo; no <= this.state.endNo; no++) {
173
+ const ch = project.chapters.find(c => c.no === no)
174
+ if (ch === undefined) continue
175
+ if (ch.status === 'approved') { this.state.currentNo = no; continue }
176
+ next = ch
177
+ break
178
+ }
179
+ if (next === undefined) {
180
+ this.state.status = 'done'
181
+ this.log(`生产单完成:${this.state.startNo}-${this.state.endNo} 章处理完毕`)
182
+ this.persist()
183
+ break
184
+ }
185
+ this.state.currentNo = next.no
186
+ await this.processChapter(project, next)
187
+ this.persist()
188
+ }
189
+ } catch (error) {
190
+ if (this.state !== null) {
191
+ this.state.status = 'error'
192
+ this.state.error = (error as Error).message
193
+ this.log(`生产单异常:${(error as Error).message}`)
194
+ this.persist()
195
+ }
196
+ } finally {
197
+ this.working = false
198
+ }
199
+ }
200
+
201
+ private async processChapter(project: ProjectState, chapter: ChapterPlan): Promise<void> {
202
+ if (chapter.status === 'pending' || chapter.status === 'error' || chapter.status === 'written') {
203
+ await this.produce(project, chapter)
204
+ } else if (chapter.status === 'rejected') {
205
+ await this.handleRejected(project, chapter)
206
+ } else if (chapter.status === 'generating') {
207
+ // 中断残留:复位重生成。
208
+ chapter.status = 'pending'
209
+ await this.produce(project, chapter)
210
+ }
211
+ this.auditChapterAdvisories(chapter.no)
212
+ }
213
+
214
+ /**
215
+ * 出章即核对曲线(建议性,不阻塞):
216
+ * 规则初筛得到的时间线矛盾 + 张力曲线偏差写进运行日志;本章已完结时再落成项目待办。
217
+ * 默认**不**触发任何自动修订——要看/要改由作者在面板发起「一键按建议修订」;
218
+ * 只有当本章因审稿 high 本来就要修订时,这些问题才搭同一轮车(见 handleRejected),
219
+ * 因此不额外增加轮次,也不会出现「改完甲又违反乙」。
220
+ */
221
+ private auditChapterAdvisories(chapterNo: number): void {
222
+ const config = this.deps.getConfig()
223
+ const outputDir = this.bookDir ?? config.outputDir
224
+ const project = loadProject(outputDir)
225
+ if (project === undefined) return
226
+ const chapter = project.chapters.find(c => c.no === chapterNo)
227
+ if (chapter === undefined) return
228
+ // reviewIssues 传空数组:这里只核对曲线/时间线,审稿意见走审稿通道。
229
+ const plan = buildRevisionPlan(project, { chapterNo, reviewIssues: [], includeTimeline: true, includeTension: true })
230
+ if (plan.items.length === 0) return
231
+ this.log(`第${chapterNo}章 曲线/时间线核对:${describeRevisionPlan(plan)}——建议性提示,未自动改动`)
232
+ if (chapter.status !== 'approved') return
233
+ if (plan.counts.timeline === 0 && plan.counts.tension === 0) return
234
+ const todos = (project.todos ??= [])
235
+ const added: string[] = []
236
+ for (const item of plan.items.slice(0, 3)) {
237
+ const text = revisionTodoText(item)
238
+ if (todos.some(t => t.text === text)) continue
239
+ todos.unshift({ id: `td-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, text, source: 'risk', done: false, createdAt: new Date().toISOString() })
240
+ added.push(text)
241
+ }
242
+ if (added.length > 0) {
243
+ project.updatedAt = new Date().toISOString()
244
+ saveProject(outputDir, project)
245
+ this.log(`第${chapterNo}章 已登记 ${added.length} 条建议性待办(可在时间线/张力面板一键按建议修订)`)
246
+ }
247
+ }
248
+
249
+ /** 完整质量门:生成 → 摘要+事实 → 伏笔标记 → 审稿 → 作者复盘。 */
250
+ private async produce(project: ProjectState, chapter: ChapterPlan): Promise<void> {
251
+ const { ctx, getConfig } = this.deps
252
+ const config = getConfig()
253
+ const outputDir = this.bookDir ?? config.outputDir
254
+ const no = chapter.no
255
+ const wasError = chapter.status === 'error'
256
+ chapter.status = 'generating'
257
+ chapter.error = undefined
258
+ chapter.generatingAt = new Date().toISOString()
259
+ mergeVolatileFromDisk(outputDir, project)
260
+ saveProject(outputDir, project)
261
+ this.log(`${wasError ? '重新生成' : '生成'} 第${no}章《${chapter.title}》…(模型 ${config.generateModel || config.model})`)
262
+ try {
263
+ for await (const _step of generateChapterStream(ctx, config, project, outputDir, no)) { /* drain */ }
264
+ try { await summarizeAndExtractFacts(ctx, config, project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run summary/facts:', (e as Error).message) }
265
+ if (config.autoTimeline ?? true) {
266
+ try { await extractTimelineForChapter(ctx, config, project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run timeline:', (e as Error).message) }
267
+ }
268
+ try { markForeshadowPlanted(project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run foreshadow:', (e as Error).message) }
269
+ if (config.autoReview ?? true) {
270
+ const report = await reviewChapter(ctx, config, project, outputDir, no)
271
+ if (this.state !== null) this.state.stats[wasError ? 'regenerated' : 'generated']++
272
+ this.log(`第${no}章 审稿 ${report.score}分 ${report.passed ? ' 通过' : ' 被拒'}(模型 ${config.reviewModel || config.model})`)
273
+ } else {
274
+ chapter.status = 'approved'
275
+ mergeVolatileFromDisk(outputDir, project)
276
+ saveProject(outputDir, project)
277
+ }
278
+ if (config.autoAuthorReview ?? true) {
279
+ try {
280
+ const body = readChapterFile(outputDir, chapter)
281
+ if (body !== undefined) {
282
+ let prevTail = ''
283
+ if (no > 1) {
284
+ const prev = project.chapters.find(c => c.no === no - 1)
285
+ if (prev !== undefined) prevTail = (readChapterFile(outputDir, prev) ?? '').replace(/^#.*$/m, '').trim().slice(-600)
286
+ }
287
+ const review = await authorReviewChapter(ctx, config, project, no, body, prevTail)
288
+ chapter.authorReview = review
289
+ if (review.advancedLines !== undefined) autoLinkPlotlines(project, no, review.advancedLines)
290
+ // 结果回灌:把本章状态变化/新线索写进编年录事实库,供后续计划与整本控制用。
291
+ const backfillFacts: string[] = [...(review.stateChanges ?? []), ...(review.clues ?? [])]
292
+ if (backfillFacts.length > 0) {
293
+ project.facts ??= []
294
+ for (const text of backfillFacts) project.facts.push({ chapterNo: no, text })
295
+ }
296
+ mergeVolatileFromDisk(outputDir, project)
297
+ saveProject(outputDir, project)
298
+ }
299
+ } catch (e) { console.warn('[dsh-novel-forge] run author review:', (e as Error).message) }
300
+ }
301
+ } catch (error) {
302
+ chapter.status = 'error'
303
+ chapter.error = (error as Error).message
304
+ mergeVolatileFromDisk(outputDir, project)
305
+ saveProject(outputDir, project)
306
+ if (this.state !== null) this.state.stats.error++
307
+ this.log(`第${no}章 失败:${(error as Error).message}`)
308
+ }
309
+ }
310
+
311
+ /** 被拒分级处理:无 high 豁免;有 high 按意见修订(最多 2 轮)+ 验证模式;仍不过 → 待人工。 */
312
+ private async handleRejected(project: ProjectState, chapter: ChapterPlan): Promise<void> {
313
+ const { ctx, getConfig } = this.deps
314
+ const config = getConfig()
315
+ const outputDir = this.bookDir ?? config.outputDir
316
+ const no = chapter.no
317
+ const report = chapter.review
318
+ const highs = (report?.issues ?? []).filter(i => i.severity === 'high')
319
+ if (highs.length === 0) {
320
+ chapter.status = 'approved'
321
+ project.updatedAt = new Date().toISOString()
322
+ saveProject(outputDir, project)
323
+ if (this.state !== null) this.state.stats.exempted++
324
+ this.log(`第${no}章 豁免通过(无 high)`)
325
+ return
326
+ }
327
+ // 合并层:审稿 high + 时间线矛盾 + 张力偏差 → 一份指令,一轮改完。
328
+ // 张力/时间线本身不触发修订(建议性),只在「反正要改」时搭车,避免多通道互相覆盖。
329
+ let plan = buildRevisionPlan(project, { chapterNo: no, reviewIssues: highs, baseReport: report })
330
+ this.log(`第${no}章 修订(${describeRevisionPlan(plan)})…`)
331
+ if (plan.omitted > 0) this.log(`第${no}章 修订指令已截断 ${plan.omitted} 条(超出单轮上限,优先级低者留待下一轮)`)
332
+ for (let round = 1; round <= MAX_REVISION_ROUNDS; round++) {
333
+ const instr = plan.instruction
334
+ try {
335
+ for await (const _step of rewriteChapterStream(ctx, config, project, outputDir, no, instr, undefined)) { /* drain */ }
336
+ } catch (error) {
337
+ this.log(`第${no}章 第${round}轮修订出错:${(error as Error).message}`)
338
+ continue
339
+ }
340
+ // rewrite 已写盘(pendingDraft + saveProject),重载拿最新草稿。
341
+ const fresh = loadProject(outputDir)
342
+ const freshCh = fresh?.chapters.find(c => c.no === no)
343
+ const draft = freshCh?.pendingDraft
344
+ if (draft === undefined || draft.length < 50) {
345
+ this.log(`第${no}章 第${round}轮草稿缺失,重试`)
346
+ continue
347
+ }
348
+ // 验证基准 = 本轮实际下发的全部条目(审稿 + 时间线 + 张力):复核核对的就是「要求改的东西」。
349
+ const verify = await reviewChapterText(ctx, config, fresh!, draft, plan.baseline)
350
+ const highs2 = (verify.issues ?? []).filter(i => i.severity === 'high')
351
+ if (verify.passed || highs2.length === 0) {
352
+ // 应用草稿(与 draft/apply 路由同逻辑):备份原稿 → 落盘 → 定状态。
353
+ this.applyDraft(fresh!, freshCh!, draft, verify)
354
+ if (this.state !== null) this.state.stats.revised++
355
+ this.log(`第${no}章 第${round}轮修订通过(${verify.score}分)`)
356
+ return
357
+ }
358
+ this.log(`第${no}章 第${round}轮仍不过(${highs2.length} high)`)
359
+ // 下一轮重新合并:以本轮仍未解决的 high 为审稿来源,并重新核对时间线/张力
360
+ // (上一轮基线里已解决的条目不再下发,避免「越修越多」)。
361
+ plan = buildRevisionPlan(fresh ?? project, { chapterNo: no, reviewIssues: highs2, baseReport: verify })
362
+ }
363
+ if (this.state !== null) this.state.pendingManual.push(no)
364
+ this.log(`第${no}章 ${MAX_REVISION_ROUNDS} 轮修订仍不过 → 保留草稿待人工`)
365
+ }
366
+
367
+ private applyDraft(project: ProjectState, chapter: ChapterPlan, draft: string, report: ReviewReport): void {
368
+ const config = this.deps.getConfig()
369
+ const outputDir = this.bookDir ?? config.outputDir
370
+ const fileName = chapterFileName(chapter)
371
+ mkdirSync(outputDir, { recursive: true })
372
+ const targetPath = join(outputDir, fileName)
373
+ if (existsSync(targetPath)) {
374
+ copyFileSync(targetPath, join(outputDir, `${fileName.replace(/\.md$/, '')}.bak.md`))
375
+ }
376
+ writeFileSync(targetPath, `# 第${chapter.no}章 ${chapter.title}\n\n${draft}\n`, 'utf8')
377
+ chapter.pendingDraft = undefined
378
+ chapter.chars = countHanzi(draft)
379
+ chapter.file = fileName
380
+ if (typeof report.score === 'number') {
381
+ chapter.review = report
382
+ chapter.status = report.passed === true ? 'approved' : 'rejected'
383
+ } else {
384
+ chapter.status = 'written'
385
+ chapter.review = undefined
386
+ }
387
+ chapter.error = undefined
388
+ project.updatedAt = new Date().toISOString()
389
+ saveProject(outputDir, project)
390
+ }
391
+ }