-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathpatch.diff
More file actions
710 lines (696 loc) · 37.9 KB
/
patch.diff
File metadata and controls
710 lines (696 loc) · 37.9 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
diff --git a/client/electron/services/knowledgeBaseService.cjs b/client/electron/services/knowledgeBaseService.cjs
index dd3eadb..39cf472 100644
--- a/client/electron/services/knowledgeBaseService.cjs
+++ b/client/electron/services/knowledgeBaseService.cjs
@@ -744,6 +744,51 @@ function createKnowledgeBaseService({ app, aiService, configStore, knowledgeBase
return recovered;
}
+ function isSamePath(a, b) {
+ return path.resolve(String(a || '')).toLowerCase() === path.resolve(String(b || '')).toLowerCase();
+ }
+
+ function getStep(documentId, stepKey) {
+ return knowledgeBaseStore.getDocumentStep(documentId, stepKey);
+ }
+
+ function stepCanReuse(step, hasArtifact) {
+ return Boolean(hasArtifact && (!step || step.status === 'success'));
+ }
+
+ function getStepItems(documentId, stepKey) {
+ const result = getStep(documentId, stepKey)?.result;
+ return Array.isArray(result?.items) ? result.items : null;
+ }
+
+ function isSameStringList(a, b) {
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
+ return a.every((value, index) => String(value) === String(b[index]));
+ }
+
+ function isRecoveryStepResult(value) {
+ return Boolean(value
+ && Array.isArray(value.items)
+ && Array.isArray(value.matches)
+ && Array.isArray(value.discarded)
+ && Array.isArray(value.system_discarded)
+ && Array.isArray(value.recovery_attempts));
+ }
+
+ async function runDocumentStep(documentId, stepKey, worker) {
+ knowledgeBaseStore.saveDocumentStep(documentId, stepKey, { status: 'running' });
+ try {
+ const result = await worker();
+ knowledgeBaseStore.saveDocumentStep(documentId, stepKey, { status: 'success', result });
+ debugLog(documentId, `step:${stepKey}:success`);
+ return result;
+ } catch (error) {
+ knowledgeBaseStore.saveDocumentStep(documentId, stepKey, { status: 'error', error: error.message || String(error) });
+ debugLog(documentId, `step:${stepKey}:error`, { message: error.message || String(error) });
+ throw error;
+ }
+ }
+
async function prepareDocument(documentId, sourceFilePath, webContents) {
if (activePreparations.has(documentId)) {
debugLog(documentId, 'prepare:skip-active');
@@ -758,93 +803,184 @@ function createKnowledgeBaseService({ app, aiService, configStore, knowledgeBase
const documentDir = fromRelative(baseDir, document.document_dir);
const sourcePath = fromRelative(baseDir, document.source_path);
const markdownPath = fromRelative(baseDir, document.markdown_path);
+ let markdown = fs.existsSync(markdownPath) ? fs.readFileSync(markdownPath, 'utf-8').trim() : '';
+ let blocks = knowledgeBaseStore.readBlocks(documentId);
+ let filteredBlocks = knowledgeBaseStore.readFilteredBlocks(documentId);
+ let firstItems = getStepItems(documentId, 'extract_first_items');
+ let supplementItems = getStepItems(documentId, 'extract_supplement_items');
+ let candidateItems = knowledgeBaseStore.readCandidateItems(documentId);
+
+ const copyStep = getStep(documentId, 'copy_source');
+ if (stepCanReuse(copyStep, fs.existsSync(sourcePath))) {
+ if (!copyStep) knowledgeBaseStore.saveDocumentStep(documentId, 'copy_source', { status: 'success', result: { source_path: document.source_path } });
+ debugLog(documentId, 'prepare:reuse-source', { source_path: sourcePath });
+ } else {
+ if (!fs.existsSync(sourceFilePath)) {
+ throw new Error('原始文件不存在,请重新上传');
+ }
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'copy_source');
+ updateDocument(documentId, { status: 'copying', progress: 5, message: '正在复制原始文件', error: null }, webContents);
+ await runDocumentStep(documentId, 'copy_source', async () => {
+ ensureDir(documentDir);
+ if (!isSamePath(sourceFilePath, sourcePath)) {
+ await fsp.copyFile(sourceFilePath, sourcePath);
+ }
+ debugLog(documentId, 'prepare:copied-source', { source_path: sourcePath });
+ return { source_path: document.source_path };
+ });
+ }
- updateDocument(documentId, { status: 'copying', progress: 5, message: '正在复制原始文件' }, webContents);
- ensureDir(documentDir);
- await fsp.copyFile(sourceFilePath, sourcePath);
- debugLog(documentId, 'prepare:copied-source', { source_path: sourcePath });
-
- updateDocument(documentId, { status: 'converting', progress: 15, message: '正在转换为 Markdown' }, webContents);
- const markdown = stripMarkdownFence((await parseDocumentWithConfig(app, sourcePath, config, { assetScope: `knowledge-${documentId}`, preserveImages: false })).trim());
- if (!markdown) throw new Error('文档未解析出有效 Markdown 内容');
- await fsp.writeFile(markdownPath, `${markdown}\n`, 'utf-8');
- knowledgeBaseStore.updateMarkdownMetadata(documentId, markdown);
- debugLog(documentId, 'prepare:converted-markdown', { markdown_path: markdownPath, markdown_chars: markdown.length });
-
- const rawBlocks = createRawBlocks(markdown);
- const semanticBlocks = mergeSemanticBlocks(rawBlocks);
- const { blocks, filtered_blocks: filteredBlocks } = filterBlocks(semanticBlocks);
- if (!blocks.length) throw new Error('筛选后没有可分析的正文内容');
- knowledgeBaseStore.saveBlocks(documentId, blocks, filteredBlocks);
- debugLog(documentId, 'prepare:blocks-ready', {
- raw_block_count: rawBlocks.length,
- semantic_block_count: semanticBlocks.length,
- block_count: blocks.length,
- filtered_block_count: filteredBlocks.length,
- block_text_chars: renderBlocksForPrompt(blocks).length,
- filtered_reasons: filteredBlocks.reduce((acc, block) => {
- acc[block.reason] = (acc[block.reason] || 0) + 1;
- return acc;
- }, {}),
- });
+ const convertStep = getStep(documentId, 'convert_markdown');
+ if (stepCanReuse(convertStep, Boolean(markdown))) {
+ if (!convertStep) knowledgeBaseStore.saveDocumentStep(documentId, 'convert_markdown', { status: 'success', result: { markdown_chars: markdown.length } });
+ debugLog(documentId, 'prepare:reuse-markdown', { markdown_chars: markdown.length });
+ } else {
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'convert_markdown');
+ blocks = [];
+ filteredBlocks = [];
+ firstItems = null;
+ supplementItems = null;
+ candidateItems = [];
+ updateDocument(documentId, { status: 'converting', progress: 15, message: '正在转换为 Markdown', error: null }, webContents);
+ const result = await runDocumentStep(documentId, 'convert_markdown', async () => {
+ const parsedMarkdown = stripMarkdownFence((await parseDocumentWithConfig(app, sourcePath, config, { assetScope: `knowledge-${documentId}`, preserveImages: false })).trim());
+ if (!parsedMarkdown) throw new Error('文档未解析出有效 Markdown 内容');
+ await fsp.writeFile(markdownPath, `${parsedMarkdown}\n`, 'utf-8');
+ knowledgeBaseStore.updateMarkdownMetadata(documentId, parsedMarkdown);
+ debugLog(documentId, 'prepare:converted-markdown', { markdown_path: markdownPath, markdown_chars: parsedMarkdown.length });
+ return { markdown_chars: parsedMarkdown.length };
+ });
+ markdown = fs.readFileSync(markdownPath, 'utf-8').trim();
+ if (!result?.markdown_chars || !markdown) throw new Error('文档未解析出有效 Markdown 内容');
+ }
+
+ const blockStep = getStep(documentId, 'build_blocks');
+ if (stepCanReuse(blockStep, blocks.length > 0)) {
+ if (!blockStep) knowledgeBaseStore.saveDocumentStep(documentId, 'build_blocks', { status: 'success', result: { block_count: blocks.length, filtered_block_count: filteredBlocks.length } });
+ debugLog(documentId, 'prepare:reuse-blocks', { block_count: blocks.length, filtered_block_count: filteredBlocks.length });
+ } else {
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'build_blocks');
+ firstItems = null;
+ supplementItems = null;
+ candidateItems = [];
+ const result = await runDocumentStep(documentId, 'build_blocks', async () => {
+ const rawBlocks = createRawBlocks(markdown);
+ const semanticBlocks = mergeSemanticBlocks(rawBlocks);
+ const filtered = filterBlocks(semanticBlocks);
+ if (!filtered.blocks.length) throw new Error('筛选后没有可分析的正文内容');
+ knowledgeBaseStore.saveBlocks(documentId, filtered.blocks, filtered.filtered_blocks);
+ debugLog(documentId, 'prepare:blocks-ready', {
+ raw_block_count: rawBlocks.length,
+ semantic_block_count: semanticBlocks.length,
+ block_count: filtered.blocks.length,
+ filtered_block_count: filtered.filtered_blocks.length,
+ block_text_chars: renderBlocksForPrompt(filtered.blocks).length,
+ filtered_reasons: filtered.filtered_blocks.reduce((acc, block) => {
+ acc[block.reason] = (acc[block.reason] || 0) + 1;
+ return acc;
+ }, {}),
+ });
+ return { block_count: filtered.blocks.length, filtered_block_count: filtered.filtered_blocks.length };
+ });
+ blocks = knowledgeBaseStore.readBlocks(documentId);
+ filteredBlocks = knowledgeBaseStore.readFilteredBlocks(documentId);
+ updateDocument(documentId, { block_count: result.block_count, filtered_block_count: result.filtered_block_count }, webContents);
+ }
const blockText = renderBlocksForPrompt(blocks);
- updateDocument(documentId, {
- status: 'extracting',
- progress: 35,
- message: 'AI 正在首次提取知识条目',
- block_count: blocks.length,
- filtered_block_count: filteredBlocks.length,
- }, webContents);
- const firstMessages = buildInitialItemMessages(document.file_name, blockText);
- debugLog(documentId, 'ai:first-items:start', {
- prompt: getPromptSummary(firstMessages),
- });
- const first = await aiService.collectJsonResponse({
- messages: firstMessages,
- temperature: 0.2,
- response_format: { type: 'json_object' },
- logTitle: `知识库条目提取-${document.file_name}`,
- normalizer: (value) => ({ items: normalizeCandidateItems(value) }),
- validator: validateCandidateItems,
- failureMessage: '知识库条目提取失败,AI 未返回有效 JSON',
- progressLabel: '知识库条目提取',
- });
- const firstItems = Array.isArray(first?.items) ? first.items : [];
- debugLog(documentId, 'ai:first-items:done', {
- item_count: firstItems.length,
- sample: getItemSample(firstItems),
- });
+ if (candidateItems.length > 0
+ && !getStep(documentId, 'extract_first_items')
+ && !getStep(documentId, 'extract_supplement_items')
+ && !getStep(documentId, 'merge_candidates')) {
+ const legacyItems = candidateItems.map(({ title, summary }) => ({ title, summary }));
+ firstItems = legacyItems;
+ supplementItems = [];
+ knowledgeBaseStore.saveDocumentStep(documentId, 'extract_first_items', { status: 'success', result: { items: firstItems } });
+ knowledgeBaseStore.saveDocumentStep(documentId, 'extract_supplement_items', { status: 'success', result: { items: supplementItems } });
+ knowledgeBaseStore.saveDocumentStep(documentId, 'merge_candidates', { status: 'success', result: { candidate_item_count: candidateItems.length } });
+ debugLog(documentId, 'prepare:reuse-legacy-candidates', { candidate_item_count: candidateItems.length });
+ }
+ const firstStep = getStep(documentId, 'extract_first_items');
+ if (stepCanReuse(firstStep, Array.isArray(firstItems))) {
+ if (!firstStep) knowledgeBaseStore.saveDocumentStep(documentId, 'extract_first_items', { status: 'success', result: { items: firstItems } });
+ debugLog(documentId, 'prepare:reuse-first-items', { item_count: firstItems.length });
+ } else {
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'extract_first_items');
+ supplementItems = null;
+ candidateItems = [];
+ updateDocument(documentId, {
+ status: 'extracting',
+ progress: 35,
+ message: 'AI 正在首次提取知识条目',
+ block_count: blocks.length,
+ filtered_block_count: filteredBlocks.length,
+ error: null,
+ }, webContents);
+ const result = await runDocumentStep(documentId, 'extract_first_items', async () => {
+ const firstMessages = buildInitialItemMessages(document.file_name, blockText);
+ debugLog(documentId, 'ai:first-items:start', { prompt: getPromptSummary(firstMessages) });
+ const first = await aiService.collectJsonResponse({
+ messages: firstMessages,
+ temperature: 0.2,
+ response_format: { type: 'json_object' },
+ logTitle: `知识库条目提取-${document.file_name}`,
+ normalizer: (value) => ({ items: normalizeCandidateItems(value) }),
+ validator: validateCandidateItems,
+ failureMessage: '知识库条目提取失败,AI 未返回有效 JSON',
+ progressLabel: '知识库条目提取',
+ });
+ const items = Array.isArray(first?.items) ? first.items : [];
+ debugLog(documentId, 'ai:first-items:done', { item_count: items.length, sample: getItemSample(items) });
+ return { items };
+ });
+ firstItems = result.items;
+ }
- updateDocument(documentId, { status: 'extracting', progress: 55, message: 'AI 正在补充遗漏知识条目' }, webContents);
- const supplementMessages = buildSupplementItemMessages(document.file_name, blockText, firstItems);
- debugLog(documentId, 'ai:supplement-items:start', {
- first_item_count: firstItems.length,
- prompt: getPromptSummary(supplementMessages),
- });
- const supplement = await aiService.collectJsonResponse({
- messages: supplementMessages,
- temperature: 0.2,
- response_format: { type: 'json_object' },
- logTitle: `知识库条目补充-${document.file_name}`,
- normalizer: (value) => ({ items: normalizeCandidateItems(value) }),
- validator: validateCandidateItems,
- failureMessage: '知识库条目补充失败,AI 未返回有效 JSON',
- progressLabel: '知识库条目补充',
- });
- const supplementItems = Array.isArray(supplement?.items) ? supplement.items : [];
- debugLog(documentId, 'ai:supplement-items:done', {
- item_count: supplementItems.length,
- sample: getItemSample(supplementItems),
- });
+ const supplementStep = getStep(documentId, 'extract_supplement_items');
+ if (stepCanReuse(supplementStep, Array.isArray(supplementItems))) {
+ if (!supplementStep) knowledgeBaseStore.saveDocumentStep(documentId, 'extract_supplement_items', { status: 'success', result: { items: supplementItems } });
+ debugLog(documentId, 'prepare:reuse-supplement-items', { item_count: supplementItems.length });
+ } else {
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'extract_supplement_items');
+ candidateItems = [];
+ updateDocument(documentId, { status: 'extracting', progress: 55, message: 'AI 正在补充遗漏知识条目', error: null }, webContents);
+ const result = await runDocumentStep(documentId, 'extract_supplement_items', async () => {
+ const supplementMessages = buildSupplementItemMessages(document.file_name, blockText, firstItems);
+ debugLog(documentId, 'ai:supplement-items:start', { first_item_count: firstItems.length, prompt: getPromptSummary(supplementMessages) });
+ const supplement = await aiService.collectJsonResponse({
+ messages: supplementMessages,
+ temperature: 0.2,
+ response_format: { type: 'json_object' },
+ logTitle: `知识库条目补充-${document.file_name}`,
+ normalizer: (value) => ({ items: normalizeCandidateItems(value) }),
+ validator: validateCandidateItems,
+ failureMessage: '知识库条目补充失败,AI 未返回有效 JSON',
+ progressLabel: '知识库条目补充',
+ });
+ const items = Array.isArray(supplement?.items) ? supplement.items : [];
+ debugLog(documentId, 'ai:supplement-items:done', { item_count: items.length, sample: getItemSample(items) });
+ return { items };
+ });
+ supplementItems = result.items;
+ }
+
+ const mergeStep = getStep(documentId, 'merge_candidates');
+ if (stepCanReuse(mergeStep, candidateItems.length > 0)) {
+ if (!mergeStep) knowledgeBaseStore.saveDocumentStep(documentId, 'merge_candidates', { status: 'success', result: { candidate_item_count: candidateItems.length } });
+ debugLog(documentId, 'prepare:reuse-candidates', { candidate_item_count: candidateItems.length });
+ } else {
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'merge_candidates');
+ const result = await runDocumentStep(documentId, 'merge_candidates', async () => {
+ const mergedItems = mergeCandidateItems(firstItems, supplementItems);
+ if (!mergedItems.length) throw new Error('AI 未提取出可用知识条目');
+ knowledgeBaseStore.saveCandidateItems(documentId, mergedItems);
+ debugLog(documentId, 'prepare:candidates-saved', { candidate_item_count: mergedItems.length, sample: getItemSample(mergedItems) });
+ return { candidate_item_count: mergedItems.length };
+ });
+ candidateItems = knowledgeBaseStore.readCandidateItems(documentId);
+ if (!result?.candidate_item_count || !candidateItems.length) throw new Error('AI 未提取出可用知识条目');
+ }
- const candidateItems = mergeCandidateItems(firstItems, supplementItems);
- if (!candidateItems.length) throw new Error('AI 未提取出可用知识条目');
- knowledgeBaseStore.saveCandidateItems(documentId, candidateItems);
- debugLog(documentId, 'prepare:candidates-saved', {
- candidate_item_count: candidateItems.length,
- sample: getItemSample(candidateItems),
- });
updateDocument(documentId, {
status: 'ready_for_matching',
progress: 65,
@@ -869,17 +1005,21 @@ function createKnowledgeBaseService({ app, aiService, configStore, knowledgeBase
}
}
- async function matchDocument(documentId, batchSize, webContents) {
+ async function matchDocument(documentId, batchSize, webContents, options = {}) {
if (activeMatches.has(documentId)) {
debugLog(documentId, 'match:skip-active');
return;
}
activeMatches.add(documentId);
- debugLog(documentId, 'match:start', { requested_batch_size: batchSize });
+ const force = Boolean(options.force);
+ debugLog(documentId, 'match:start', { requested_batch_size: batchSize, force });
try {
const document = getDocument(documentId);
const normalizedBatchSize = Math.max(1, Math.min(100, Math.floor(Number(batchSize) || 1)));
+ if (force) {
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'match_batches');
+ }
const blocks = knowledgeBaseStore.readBlocks(documentId);
const filteredBlocks = knowledgeBaseStore.readFilteredBlocks(documentId);
const initialItems = knowledgeBaseStore.readCandidateItems(documentId);
@@ -894,7 +1034,7 @@ function createKnowledgeBaseService({ app, aiService, configStore, knowledgeBase
const blockText = renderBlocksForPrompt(blocks);
const blockOrder = getBlockOrder(blocks);
- const itemIds = new Set(initialItems.map((item) => item.id));
+ const candidateItemIds = new Set(initialItems.map((item) => item.id));
const batches = [];
for (let index = 0; index < initialItems.length; index += normalizedBatchSize) {
batches.push(initialItems.slice(index, index + normalizedBatchSize));
@@ -902,144 +1042,202 @@ function createKnowledgeBaseService({ app, aiService, configStore, knowledgeBase
const matches = [];
const matchBatches = [];
+ knowledgeBaseStore.saveDocumentStep(documentId, 'match_batches', { status: 'running' });
updateDocument(documentId, { status: 'matching', progress: 66, message: `开始匹配段落,共 ${batches.length} 批`, last_batch_size: normalizedBatchSize }, webContents);
for (let index = 0; index < batches.length; index += 1) {
+ const batchIndex = index + 1;
+ const batchItemIds = batches[index].map((item) => item.id);
+ const savedBatch = force ? null : knowledgeBaseStore.getMatchBatch(documentId, batchIndex);
+ if (savedBatch?.status === 'success' && isSameStringList(savedBatch.item_ids, batchItemIds) && Array.isArray(savedBatch.matches)) {
+ debugLog(documentId, 'match:reuse-batch', { batch_index: batchIndex, match_count: savedBatch.matches.length });
+ const batchResult = { batch_index: batchIndex, item_ids: batchItemIds, matches: savedBatch.matches };
+ matchBatches.push(batchResult);
+ matches.push(...savedBatch.matches);
+ continue;
+ }
+
const progress = Math.min(88, 66 + Math.round(((index + 1) / batches.length) * 22));
- updateDocument(documentId, { status: 'matching', progress, message: `AI 正在匹配段落 ${index + 1}/${batches.length}` }, webContents);
+ updateDocument(documentId, { status: 'matching', progress, message: `AI 正在匹配段落 ${batchIndex}/${batches.length}` }, webContents);
+ knowledgeBaseStore.saveMatchBatch(documentId, batchIndex, { status: 'running', itemIds: batchItemIds, matches: [] });
const matchMessages = buildMatchMessages(document.file_name, blockText, batches[index]);
debugLog(documentId, 'ai:match-batch:start', {
- batch_index: index + 1,
+ batch_index: batchIndex,
batch_count: batches.length,
- item_ids: batches[index].map((item) => item.id),
+ item_ids: batchItemIds,
prompt: getPromptSummary(matchMessages),
});
- const parsed = await aiService.collectJsonResponse({
- messages: matchMessages,
- temperature: 0.1,
- response_format: { type: 'json_object' },
- logTitle: `知识库段落匹配-${document.file_name}-第${index + 1}批`,
- normalizer: (value) => normalizeMatchResult(value, itemIds, blocks, blockOrder),
- validator: validateMatchResult,
- failureMessage: '知识库段落匹配失败,AI 未返回有效 JSON',
- progressLabel: '知识库段落匹配',
+ try {
+ const parsed = await aiService.collectJsonResponse({
+ messages: matchMessages,
+ temperature: 0.1,
+ response_format: { type: 'json_object' },
+ logTitle: `知识库段落匹配-${document.file_name}-第${batchIndex}批`,
+ normalizer: (value) => normalizeMatchResult(value, candidateItemIds, blocks, blockOrder),
+ validator: validateMatchResult,
+ failureMessage: '知识库段落匹配失败,AI 未返回有效 JSON',
+ progressLabel: '知识库段落匹配',
+ });
+ knowledgeBaseStore.saveMatchBatch(documentId, batchIndex, { status: 'success', itemIds: batchItemIds, matches: parsed.matches });
+ debugLog(documentId, 'ai:match-batch:done', {
+ batch_index: batchIndex,
+ match_count: parsed.matches.length,
+ matches: getMatchSummary(parsed.matches),
+ });
+ const batchResult = { batch_index: batchIndex, item_ids: batchItemIds, matches: parsed.matches };
+ matchBatches.push(batchResult);
+ matches.push(...parsed.matches);
+ } catch (error) {
+ knowledgeBaseStore.saveMatchBatch(documentId, batchIndex, { status: 'error', itemIds: batchItemIds, error: error.message || String(error) });
+ knowledgeBaseStore.saveDocumentStep(documentId, 'match_batches', { status: 'error', error: error.message || String(error) });
+ throw error;
+ }
+ }
+ knowledgeBaseStore.saveDocumentStep(documentId, 'match_batches', { status: 'success', result: { batch_size: normalizedBatchSize, batch_count: batches.length } });
+
+ let recoveryResult = getStep(documentId, 'recover_missing')?.result;
+ if (!force && isRecoveryStepResult(recoveryResult)) {
+ debugLog(documentId, 'recovery:reuse', {
+ item_count: recoveryResult.items.length,
+ match_count: recoveryResult.matches.length,
+ recovery_attempt_count: recoveryResult.recovery_attempts.length,
});
- debugLog(documentId, 'ai:match-batch:done', {
- batch_index: index + 1,
- match_count: parsed.matches.length,
- matches: getMatchSummary(parsed.matches),
+ } else {
+ knowledgeBaseStore.clearDocumentProcessingFromStep(documentId, 'recover_missing');
+ recoveryResult = await runDocumentStep(documentId, 'recover_missing', async () => {
+ const items = [...initialItems];
+ const recoveredMatches = [...matches];
+ const discarded = [];
+ const systemDiscarded = [];
+ const recoveryAttempts = [];
+
+ for (let attempt = 0; attempt < recoveryMaxAttempts; attempt += 1) {
+ const missingBlocks = getMissingBlocks(blocks, recoveredMatches, discarded, systemDiscarded);
+ debugLog(documentId, 'recovery:missing-check', {
+ attempt: attempt + 1,
+ missing_block_count: missingBlocks.length,
+ });
+ if (!missingBlocks.length) break;
+
+ updateDocument(documentId, {
+ status: 'recovering',
+ progress: Math.min(96, 90 + attempt * 3),
+ message: `AI 正在补漏遗漏段落 ${attempt + 1}/${recoveryMaxAttempts},剩余 ${missingBlocks.length} 个 block`,
+ }, webContents);
+ const currentItemIds = new Set(items.map((item) => item.id));
+ const recoveryMessages = buildRecoveryMessages(document.file_name, items, missingBlocks);
+ debugLog(documentId, 'ai:recovery:start', {
+ attempt: attempt + 1,
+ missing_block_count: missingBlocks.length,
+ item_count: items.length,
+ prompt: getPromptSummary(recoveryMessages),
+ });
+ const parsed = await aiService.collectJsonResponse({
+ messages: recoveryMessages,
+ temperature: 0.1,
+ response_format: { type: 'json_object' },
+ logTitle: `知识库遗漏补漏-${document.file_name}-第${attempt + 1}轮`,
+ normalizer: (value) => normalizeRecoveryResult(value, currentItemIds, blocks, blockOrder),
+ validator: validateRecoveryResult,
+ failureMessage: '知识库遗漏段落补漏失败,AI 未返回有效 JSON',
+ progressLabel: '知识库遗漏补漏',
+ });
+ debugLog(documentId, 'ai:recovery:done', {
+ attempt: attempt + 1,
+ match_count: parsed.matches.length,
+ new_item_count: parsed.new_items.length,
+ discarded_group_count: parsed.discarded.length,
+ matches: getMatchSummary(parsed.matches),
+ });
+
+ const newItemsWithIds = parsed.new_items.map((item) => {
+ const id = nextKnowledgeItemId(items);
+ const next = { id, title: item.title, summary: item.summary };
+ items.push(next);
+ recoveredMatches.push({ id, ranges: item.ranges, block_ids: item.block_ids });
+ return { ...next, ranges: item.ranges, block_ids: item.block_ids };
+ });
+ recoveredMatches.push(...parsed.matches);
+ discarded.push(...parsed.discarded.map((item) => ({ ...item, source: `recovery_${attempt + 1}` })));
+ recoveryAttempts.push({
+ attempt: attempt + 1,
+ missing_before_count: missingBlocks.length,
+ matches: parsed.matches,
+ new_items: newItemsWithIds,
+ discarded: parsed.discarded,
+ });
+ }
+
+ const remaining = getMissingBlocks(blocks, recoveredMatches, discarded, systemDiscarded);
+ debugLog(documentId, 'match:remaining-after-recovery', { remaining_block_count: remaining.length });
+ if (remaining.length) {
+ systemDiscarded.push({
+ block_ids: remaining.map((block) => block.id),
+ reason: 'system_discarded_after_retry',
+ });
+ }
+
+ return {
+ items,
+ matches: recoveredMatches,
+ discarded,
+ system_discarded: systemDiscarded,
+ recovery_attempts: recoveryAttempts,
+ };
});
- const batchResult = { batch_index: index + 1, item_ids: batches[index].map((item) => item.id), matches: parsed.matches };
- matchBatches.push(batchResult);
- matches.push(...parsed.matches);
}
- const items = [...initialItems];
- const discarded = [];
- const systemDiscarded = [];
- const recoveryAttempts = [];
-
- for (let attempt = 0; attempt < recoveryMaxAttempts; attempt += 1) {
- const missingBlocks = getMissingBlocks(blocks, matches, discarded, systemDiscarded);
- debugLog(documentId, 'recovery:missing-check', {
- attempt: attempt + 1,
- missing_block_count: missingBlocks.length,
- });
- if (!missingBlocks.length) break;
-
+ const savedItems = knowledgeBaseStore.readItems(documentId);
+ const saveStep = getStep(documentId, 'save_result');
+ if (!force && saveStep?.status === 'success' && savedItems.length) {
+ debugLog(documentId, 'save:reuse', { item_count: savedItems.length });
updateDocument(documentId, {
- status: 'recovering',
- progress: Math.min(96, 90 + attempt * 3),
- message: `AI 正在补漏遗漏段落 ${attempt + 1}/${recoveryMaxAttempts},剩余 ${missingBlocks.length} 个 block`,
+ status: 'success',
+ progress: 100,
+ message: `整理完成,共 ${savedItems.length} 条`,
+ item_count: savedItems.length,
}, webContents);
- const currentItemIds = new Set(items.map((item) => item.id));
- const recoveryMessages = buildRecoveryMessages(document.file_name, items, missingBlocks);
- debugLog(documentId, 'ai:recovery:start', {
- attempt: attempt + 1,
- missing_block_count: missingBlocks.length,
- item_count: items.length,
- prompt: getPromptSummary(recoveryMessages),
- });
- const parsed = await aiService.collectJsonResponse({
- messages: recoveryMessages,
- temperature: 0.1,
- response_format: { type: 'json_object' },
- logTitle: `知识库遗漏补漏-${document.file_name}-第${attempt + 1}轮`,
- normalizer: (value) => normalizeRecoveryResult(value, currentItemIds, blocks, blockOrder),
- validator: validateRecoveryResult,
- failureMessage: '知识库遗漏段落补漏失败,AI 未返回有效 JSON',
- progressLabel: '知识库遗漏补漏',
- });
- debugLog(documentId, 'ai:recovery:done', {
- attempt: attempt + 1,
- match_count: parsed.matches.length,
- new_item_count: parsed.new_items.length,
- discarded_group_count: parsed.discarded.length,
- matches: getMatchSummary(parsed.matches),
- });
-
- const newItemsWithIds = parsed.new_items.map((item) => {
- const id = nextKnowledgeItemId(items);
- const next = { id, title: item.title, summary: item.summary };
- items.push(next);
- matches.push({ id, ranges: item.ranges, block_ids: item.block_ids });
- return { ...next, ranges: item.ranges, block_ids: item.block_ids };
- });
- matches.push(...parsed.matches);
- discarded.push(...parsed.discarded.map((item) => ({ ...item, source: `recovery_${attempt + 1}` })));
- recoveryAttempts.push({
- attempt: attempt + 1,
- missing_before_count: missingBlocks.length,
- matches: parsed.matches,
- new_items: newItemsWithIds,
- discarded: parsed.discarded,
- });
- }
-
- const remaining = getMissingBlocks(blocks, matches, discarded, systemDiscarded);
- debugLog(documentId, 'match:remaining-after-recovery', { remaining_block_count: remaining.length });
- if (remaining.length) {
- systemDiscarded.push({
- block_ids: remaining.map((block) => block.id),
- reason: 'system_discarded_after_retry',
- });
+ return;
}
updateDocument(documentId, { status: 'saving', progress: 98, message: '正在回填正文并保存知识条目' }, webContents);
- const finalItems = createFinalItems(items, matches, blocks, document.file_name);
- const report = createReport({
- blocks,
- filteredBlocks,
- candidateItems: items,
- finalItems,
- matches,
- discarded,
- systemDiscarded,
- recoveryAttempts,
- batchSize: normalizedBatchSize,
- });
- const matchResult = {
- candidate_items: items,
- match_batches: matchBatches,
- recovery_attempts: recoveryAttempts,
- final_matches: matches,
- discarded,
- system_discarded_after_retry: systemDiscarded,
- report,
- };
+ const saveResult = await runDocumentStep(documentId, 'save_result', async () => {
+ const finalItems = createFinalItems(recoveryResult.items, recoveryResult.matches, blocks, document.file_name);
+ const report = createReport({
+ blocks,
+ filteredBlocks,
+ candidateItems: recoveryResult.items,
+ finalItems,
+ matches: recoveryResult.matches,
+ discarded: recoveryResult.discarded,
+ systemDiscarded: recoveryResult.system_discarded,
+ recoveryAttempts: recoveryResult.recovery_attempts,
+ batchSize: normalizedBatchSize,
+ });
+ const matchResult = {
+ candidate_items: recoveryResult.items,
+ match_batches: matchBatches,
+ recovery_attempts: recoveryResult.recovery_attempts,
+ final_matches: recoveryResult.matches,
+ discarded: recoveryResult.discarded,
+ system_discarded_after_retry: recoveryResult.system_discarded,
+ report,
+ };
- knowledgeBaseStore.saveMatchResult(documentId, { candidateItems: items, matchResult, report, finalItems });
- debugLog(documentId, 'match:saved', {
- final_item_count: finalItems.length,
- report,
+ knowledgeBaseStore.saveMatchResult(documentId, { candidateItems: recoveryResult.items, matchResult, report, finalItems });
+ debugLog(documentId, 'match:saved', {
+ final_item_count: finalItems.length,
+ report,
+ });
+ return { final_item_count: finalItems.length, report };
});
updateDocument(documentId, {
status: 'success',
progress: 100,
- message: `整理完成,共 ${finalItems.length} 条,覆盖率 ${Math.round(report.coverage_rate * 100)}%`,
- item_count: finalItems.length,
- candidate_item_count: items.length,
- discarded_block_count: report.discarded_blocks_count,
- system_discarded_after_retry_count: report.system_discarded_after_retry_count,
+ message: `整理完成,共 ${saveResult.final_item_count} 条,覆盖率 ${Math.round(saveResult.report.coverage_rate * 100)}%`,
+ item_count: saveResult.final_item_count,
+ candidate_item_count: recoveryResult.items.length,
+ discarded_block_count: saveResult.report.discarded_blocks_count,
+ system_discarded_after_retry_count: saveResult.report.system_discarded_after_retry_count,
}, webContents);
} catch (error) {
debugLog(documentId, 'match:error', {
@@ -1165,6 +1363,25 @@ function createKnowledgeBaseService({ app, aiService, configStore, knowledgeBase
return { success: Boolean(created.length), message: created.length ? `已加入 ${created.length} 个文档处理任务` : '未选择支持的文档类型', documents: created };
},
+ retryDocument(documentId, webContents) {
+ const document = getDocument(documentId);
+ debugLog(documentId, 'ipc:retry-document', { current_status: document.status });
+ if (activePreparations.has(documentId) || activeMatches.has(documentId)) {
+ return { success: false, message: '该文档正在处理中', document };
+ }
+ if (document.status !== 'error') {
+ return { success: false, message: '只有解析失败的文档可以重试', document };
+ }
+
+ const sourcePath = fromRelative(baseDir, document.source_path);
+ if (!fs.existsSync(sourcePath)) {
+ return { success: false, message: '原始文件不存在,请重新上传', document };
+ }
+
+ prepareDocument(documentId, sourcePath, webContents);
+ return { success: true, message: '已重新开始解析', document: getDocument(documentId) };
+ },
+
startMatching(documentId, batchSize, webContents) {
const document = getDocument(documentId);
debugLog(documentId, 'ipc:start-matching', { batch_size: batchSize, current_status: document.status });
@@ -1174,7 +1391,7 @@ function createKnowledgeBaseService({ app, aiService, configStore, knowledgeBase
if (!['ready_for_matching', 'success', 'error'].includes(document.status)) {
return { success: false, message: '请等待候选知识条目提取完成', document };
}
- matchDocument(documentId, batchSize, webContents);
+ matchDocument(documentId, batchSize, webContents, { force: document.status === 'success' });
return { success: true, message: '已开始分批匹配段落', document };
},