forked from lioensky/VCPToolBox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnowledgeBaseManager.js
More file actions
2534 lines (2209 loc) · 115 KB
/
Copy pathKnowledgeBaseManager.js
File metadata and controls
2534 lines (2209 loc) · 115 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// KnowledgeBaseManager.js
// 🌟 架构重构修复版:多路独立索引 + 稳健的 Buffer 处理 + 同步缓存回退 + TagMemo 逻辑回归
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const crypto = require('crypto');
const Database = require('better-sqlite3');
const chokidar = require('chokidar');
const { chunkText } = require('./TextChunker');
const { getEmbeddingsBatch } = require('./EmbeddingUtils');
const ResultDeduplicator = require('./ResultDeduplicator'); // ✅ Tagmemo v4 requirement
const TagMemoEngine = require('./TagMemoEngine');
// 尝试加载 Rust Vexus 引擎
let VexusIndex = null;
try {
const vexusModule = require('./rust-vexus-lite');
VexusIndex = vexusModule.VexusIndex;
console.log('[KnowledgeBase] 🦀 Vexus-Lite Rust engine loaded');
} catch (e) {
console.error('[KnowledgeBase] ❌ Critical: Vexus-Lite not found.');
process.exit(1);
}
class KnowledgeBaseManager {
constructor(config = {}) {
this.config = {
rootPath: config.rootPath || process.env.KNOWLEDGEBASE_ROOT_PATH || path.join(__dirname, 'dailynote'),
storePath: config.storePath || process.env.KNOWLEDGEBASE_STORE_PATH || path.join(__dirname, 'VectorStore'),
apiKey: process.env.API_Key,
apiUrl: process.env.API_URL,
model: process.env.WhitelistEmbeddingModel || 'google/gemini-embedding-001',
// 向量语义空间签名:用于缓存/派生数据失效;未配置时回退到主模型名,避免破坏旧行为。
modelSig: process.env.EmbeddingModelSig || process.env.WhitelistEmbeddingModel || 'gemini-embedding-2-preview',
// ⚠️ 务必确认环境变量 VECTORDB_DIMENSION 与模型一致 (3-small通常为1536)
dimension: parseInt(process.env.VECTORDB_DIMENSION) || 3072,
batchWindow: parseInt(process.env.KNOWLEDGEBASE_BATCH_WINDOW_MS, 10) || 2000,
maxBatchSize: parseInt(process.env.KNOWLEDGEBASE_MAX_BATCH_SIZE, 10) || 50,
indexSaveDelay: parseInt(process.env.KNOWLEDGEBASE_INDEX_SAVE_DELAY, 10) || 120000,
tagIndexSaveDelay: parseInt(process.env.KNOWLEDGEBASE_TAG_INDEX_SAVE_DELAY, 10) || 300000,
deleteBatchWindow: parseInt(process.env.KNOWLEDGEBASE_DELETE_BATCH_WINDOW_MS, 10) || 1000,
maxDeleteBatchSize: parseInt(process.env.KNOWLEDGEBASE_MAX_DELETE_BATCH_SIZE, 10) || 2000,
deleteRebuildThreshold: parseInt(process.env.KNOWLEDGEBASE_DELETE_REBUILD_THRESHOLD, 10) || 5000,
migrationCacheTtlMs: parseInt(process.env.KNOWLEDGEBASE_MIGRATION_CACHE_TTL_MS, 10) || 2 * 60 * 1000,
// 🛡️ Rust 派生表写入租约:避免 rusqlite 与 better-sqlite3 双写 WAL 竞态
rustWriteLeaseGraceMs: parseInt(process.env.KNOWLEDGEBASE_RUST_WRITE_LEASE_GRACE_MS, 10) || 30000,
rustWriteLeaseCooldownMs: parseInt(process.env.KNOWLEDGEBASE_RUST_WRITE_LEASE_COOLDOWN_MS, 10) || 10000,
rustWriteLeaseCheckpointBeforeGrant: (process.env.KNOWLEDGEBASE_RUST_WRITE_LEASE_CHECKPOINT_BEFORE_GRANT || 'true').toLowerCase() === 'true',
rustWriteLeaseRetryMs: parseInt(process.env.KNOWLEDGEBASE_RUST_WRITE_LEASE_RETRY_MS, 10) || 1000,
rustWriteLeaseTtlMs: parseInt(process.env.KNOWLEDGEBASE_RUST_WRITE_LEASE_TTL_MS, 10) || 10 * 60 * 1000,
rustWriteLeaseMaxWaitMs: parseInt(process.env.KNOWLEDGEBASE_RUST_WRITE_LEASE_MAX_WAIT_MS, 10) || 30 * 60 * 1000,
rustWriteLeasePendingThreshold: parseInt(process.env.KNOWLEDGEBASE_RUST_WRITE_LEASE_PENDING_THRESHOLD, 10) || 0,
derivedStartupCooldownMs: parseInt(process.env.KNOWLEDGEBASE_DERIVED_STARTUP_COOLDOWN_MS, 10) || 5 * 60 * 1000,
// 🌟 索引空闲自动卸载:默认 2 小时未使用则从内存中卸载
indexIdleTTL: parseInt(process.env.KNOWLEDGEBASE_INDEX_IDLE_TTL_MS, 10) || 2 * 60 * 60 * 1000,
indexIdleSweepInterval: parseInt(process.env.KNOWLEDGEBASE_INDEX_IDLE_SWEEP_MS, 10) || 10 * 60 * 1000,
idleSweepLogTick: (process.env.KNOWLEDGEBASE_IDLE_SWEEP_LOG_TICK || 'false').toLowerCase() === 'true',
ignoreFolders: (process.env.IGNORE_FOLDERS || 'VCP论坛').split(',').map(f => f.trim()).filter(Boolean),
ignorePrefixes: (process.env.IGNORE_PREFIXES || process.env.IGNORE_PREFIX || '已整理').split(',').map(p => p.trim()).filter(Boolean),
ignoreSuffixes: (process.env.IGNORE_SUFFIXES || process.env.IGNORE_SUFFIX || '夜伽').split(',').map(s => s.trim()).filter(Boolean),
tagBlacklist: new Set((process.env.TAG_BLACKLIST || '').split(',').map(t => t.trim()).filter(Boolean)),
tagBlacklistSuper: (process.env.TAG_BLACKLIST_SUPER || '').split(',').map(t => t.trim()).filter(Boolean),
tagExpandMaxCount: parseInt(process.env.TAG_EXPAND_MAX_COUNT, 10) || 30,
fullScanOnStartup: (process.env.KNOWLEDGEBASE_FULL_SCAN_ON_STARTUP || 'true').toLowerCase() === 'true',
// 语言置信度补偿配置
langConfidenceEnabled: (process.env.LANG_CONFIDENCE_GATING_ENABLED || 'true').toLowerCase() === 'true',
langPenaltyUnknown: parseFloat(process.env.LANG_PENALTY_UNKNOWN) || 0.05,
// 🌟 是否默认持久化索引(建议 false,仅在内存重建以保证原子性)
// 🌟 是否持久化全局 Tag 索引
persistTagIndex: (process.env.KNOWLEDGEBASE_PERSIST_TAG_INDEX || 'false').toLowerCase() === 'true',
// 🌟 是否默认持久化索引(建议 false,仅在内存重建以保证原子性)
persistDefault: (process.env.KNOWLEDGEBASE_PERSIST_DEFAULT || 'false').toLowerCase() === 'true',
// 🌟 强制开启持久化的文件夹白名单 (支持中英文逗号)
persistFolders: new Set((process.env.KNOWLEDGEBASE_PERSIST_FOLDERS || '').split(/[,,]/).map(f => f.trim()).filter(Boolean)),
...config
};
this.db = null;
this.dbPath = null;
this.databaseCorruptionDetected = false;
this.dbHealthState = 'healthy'; // healthy | suspect | recovering | corrupt
this._recoveringDatabaseConnection = false;
this.startupCompletedAt = 0;
this.diaryIndices = new Map();
this.diaryIndexLastUsed = new Map(); // 🌟 记录每个索引的最后使用时间
this.idleSweepTimer = null;
this.tagIndex = null;
this.watcher = null;
this.initialized = false;
this.eventLoopWatchdogTimer = null;
this._lastEventLoopWatchdogAt = 0;
this.diaryNameVectorCache = new Map();
this.pendingFiles = new Set();
this.fileRetryCount = new Map(); // 🛡️ 文件重试计数器,防止无限循环
this.batchTimer = null;
this.isProcessing = false;
this.saveTimers = new Map();
this.pendingDeletes = new Set();
this.deleteBatchTimer = null;
this.isProcessingDeletes = false;
this.tagMemoEngine = null;
this.resultDeduplicator = null; // ✅ Tagmemo v4
this.ragParams = {}; // ✅ 新增:用于存储热调控参数
this.ragParamsWatcher = null;
// 🛡️ SQLite Rust 写租约门控:Rust 派生表写入前必须向 JS 主调度器申请窗口。
this.rustWriteLease = null;
this.lastJsWriteFinishedAt = 0;
this.lastRustWriteFinishedAt = 0;
this._rustLeaseWaitLogAt = 0;
}
async initialize() {
if (this.initialized) return;
console.log(`[KnowledgeBase] Initializing Multi-Index System (Dim: ${this.config.dimension})...`);
await fs.mkdir(this.config.storePath, { recursive: true });
const dbPath = path.join(this.config.storePath, 'knowledge_base.sqlite');
this.dbPath = dbPath;
this.db = this._openDatabaseWithRecovery(dbPath); // 同步连接
this._initSchema();
this._cleanupDatabaseOrphans();
// 1. 初始化全局 Tag 索引 (优先从磁盘加载或从 SQLite 重建)
const tagCapacity = 50000;
const tagIdxPath = path.join(this.config.storePath, 'index_global_tags.usearch');
let indexReady = false;
// 全局 Tag 索引持久化判定:显式开关 OR 白名单包含 'global_tags'
const shouldPersistTags = this.config.persistTagIndex || this.config.persistFolders.has('global_tags');
if (shouldPersistTags && fsSync.existsSync(tagIdxPath)) {
try {
this.tagIndex = VexusIndex.load(tagIdxPath, null, this.config.dimension, tagCapacity);
console.log('[KnowledgeBase] ✅ Global Tag Index loaded from disk.');
indexReady = true;
} catch (e) {
console.warn(`[KnowledgeBase] ⚠️ Failed to load tag index from disk: ${e.message}. Rebuilding...`);
}
}
if (!indexReady) {
console.log('[KnowledgeBase] 🚀 Building Global Tag Index from SQLite...');
this.tagIndex = new VexusIndex(this.config.dimension, tagCapacity);
try {
const count = await this.tagIndex.recoverFromSqlite(dbPath, 'tags', null);
console.log(`[KnowledgeBase] ✅ Global Tag Index ready. ${count} vectors indexed.`);
// 如果开启了持久化但文件不存在,则保存一次
if (shouldPersistTags) this._saveIndexToDisk('global_tags');
} catch (e) {
console.error(`[KnowledgeBase] ❌ Global Tag Index recovery failed: ${e.message}`);
}
}
// 2. 预热日记本名称向量缓存(同步阻塞,确保 RAG 插件启动即可用)
this._hydrateDiaryNameCacheSync();
// ✅ Tagmemo v4: 初始化结果去重器
this.resultDeduplicator = new ResultDeduplicator(this.db, {
dimension: this.config.dimension
});
await this.loadRagParams();
// 初始化浪潮引擎
this.tagMemoEngine = new TagMemoEngine(this.db, this.tagIndex, this.config, this.ragParams, this);
await this.tagMemoEngine.initialize();
this._cleanupStalePairwiseSimilarityModels();
this._startWatcher();
this._startRagParamsWatcher();
this._startIdleSweep(); // 🌟 启动空闲索引自动卸载
this._startEventLoopWatchdog(); // 🛡️ 运行期无日志卡死定位:记录主线程长阻塞
this.initialized = true;
this.startupCompletedAt = Date.now();
console.log('[KnowledgeBase] ✅ System Ready');
if (this.tagMemoEngine && typeof this.tagMemoEngine.schedulePostStartupDerivedRefresh === 'function') {
this.tagMemoEngine.schedulePostStartupDerivedRefresh(this.config.derivedStartupCooldownMs);
}
}
/**
* ✅ 新增:加载 RAG 热调控参数
*/
async loadRagParams() {
const paramsPath = path.join(__dirname, 'rag_params.json');
try {
const data = await fs.readFile(paramsPath, 'utf-8');
this.ragParams = JSON.parse(data);
console.log('[KnowledgeBase] ✅ RAG 热调控参数已加载');
if (this.tagMemoEngine) this.tagMemoEngine.updateRagParams(this.ragParams);
} catch (e) {
console.error('[KnowledgeBase] ❌ 加载 rag_params.json 失败:', e.message);
this.ragParams = { KnowledgeBaseManager: {} };
}
}
/**
* ✅ 新增:启动参数监听器
*/
_startRagParamsWatcher() {
const paramsPath = path.join(__dirname, 'rag_params.json');
if (this.ragParamsWatcher) return;
this.ragParamsWatcher = chokidar.watch(paramsPath);
this.ragParamsWatcher.on('change', async () => {
console.log('[KnowledgeBase] 🔄 检测到 rag_params.json 变更,正在重新加载...');
await this.loadRagParams();
});
}
_initSchema() {
this.db.exec(`
CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT UNIQUE NOT NULL,
diary_name TEXT NOT NULL,
checksum TEXT NOT NULL,
mtime INTEGER NOT NULL,
size INTEGER NOT NULL,
updated_at INTEGER
);
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_id INTEGER NOT NULL,
chunk_index INTEGER NOT NULL,
content TEXT NOT NULL,
vector BLOB,
FOREIGN KEY(file_id) REFERENCES files(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
vector BLOB
);
CREATE TABLE IF NOT EXISTS file_tags (
file_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (file_id, tag_id),
FOREIGN KEY(file_id) REFERENCES files(id) ON DELETE CASCADE,
FOREIGN KEY(tag_id) REFERENCES tags(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS tag_intrinsic_residuals (
tag_id INTEGER PRIMARY KEY,
residual_energy REAL NOT NULL,
neighbor_count INTEGER NOT NULL,
computed_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- 🌟 TagMemo V8.2: 持久化的 Tag 对语义距离 (Pairwise Cosine Similarity)
-- 与 tag_intrinsic_residuals 平级,构成"节点质量 + 边距离"的物理量底座。
CREATE TABLE IF NOT EXISTS tag_pair_similarity (
tag_a INTEGER NOT NULL,
tag_b INTEGER NOT NULL, -- 约定 tag_a < tag_b,消除重复
similarity REAL NOT NULL, -- [-1, 1] 余弦,不预归一化
model_sig TEXT NOT NULL, -- embedding 模型签名 (含维度),跨模型自动失效
computed_at INTEGER NOT NULL,
PRIMARY KEY (tag_a, tag_b),
FOREIGN KEY (tag_a) REFERENCES tags(id) ON DELETE CASCADE,
FOREIGN KEY (tag_b) REFERENCES tags(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_pair_sim_model ON tag_pair_similarity(model_sig);
CREATE TABLE IF NOT EXISTS kv_store (
key TEXT PRIMARY KEY,
value TEXT,
vector BLOB
);
-- 🧳 文件移动墓碑缓存:删除事件先到时,短期保留 chunk 向量供新路径复用。
CREATE TABLE IF NOT EXISTS migration_deleted_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
old_path TEXT NOT NULL,
old_diary_name TEXT NOT NULL,
checksum TEXT NOT NULL,
size INTEGER NOT NULL,
chunk_count INTEGER NOT NULL,
deleted_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS migration_deleted_chunks (
cache_file_id INTEGER NOT NULL,
chunk_index INTEGER NOT NULL,
vector BLOB NOT NULL,
PRIMARY KEY (cache_file_id, chunk_index),
FOREIGN KEY(cache_file_id) REFERENCES migration_deleted_files(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_files_diary ON files(diary_name);
CREATE INDEX IF NOT EXISTS idx_chunks_file ON chunks(file_id);
CREATE INDEX IF NOT EXISTS idx_file_tags_tag ON file_tags(tag_id);
CREATE INDEX IF NOT EXISTS idx_file_tags_composite ON file_tags(tag_id, file_id);
CREATE INDEX IF NOT EXISTS idx_migration_deleted_lookup ON migration_deleted_files(checksum, size, expires_at);
CREATE INDEX IF NOT EXISTS idx_migration_deleted_expiry ON migration_deleted_files(expires_at);
`);
// 🛠️ 核心修复:由于 db.exec 不支持动态执行 SELECT 返回的 SQL,我们手动补丁
try {
this.db.prepare("ALTER TABLE file_tags ADD COLUMN position INTEGER NOT NULL DEFAULT 0").run();
} catch (e) {
// 如果列已存在,SQLite 会报错,忽略即可
}
this._cleanupExpiredMigrationCache();
}
_openDatabaseWithRecovery(dbPath) {
let db = new Database(dbPath);
try {
this._configureDatabaseConnection(db);
this._assertDatabaseIntegrity(db);
return db;
} catch (e) {
if (!this._isSqliteCorruptionError(e)) {
try { db.close(); } catch (_) { }
throw e;
}
console.error('[KnowledgeBase] ❌ SQLite database corruption detected during startup.');
console.error(`[KnowledgeBase] Corruption details: ${e.message || e}`);
try { db.close(); } catch (_) { }
const backupBase = this._quarantineSqliteDatabase(dbPath, 'startup-corrupt');
console.warn(
`[KnowledgeBase] 🧯 Corrupt SQLite database quarantined as "${path.basename(backupBase)}*". ` +
'A fresh database will be created and rebuilt from dailynote files.'
);
db = new Database(dbPath);
this._configureDatabaseConnection(db);
this._assertDatabaseIntegrity(db);
return db;
}
}
_configureDatabaseConnection(db) {
db.pragma('journal_mode = WAL');
db.pragma('synchronous = NORMAL');
// 🛡️ SQLite 默认不启用外键;必须显式开启,避免文件删除后 chunks/file_tags 残留。
db.pragma('foreign_keys = ON');
}
_assertDatabaseIntegrity(db) {
const row = db.prepare('PRAGMA quick_check').get();
const result = row ? Object.values(row)[0] : 'ok';
if (result !== 'ok') {
const error = new Error(`SQLite quick_check failed: ${result}`);
error.code = 'SQLITE_CORRUPT';
throw error;
}
}
checkpointAndAssertDatabaseHealthy(reason = 'manual-checkpoint') {
if (!this.db) return false;
try {
this.db.pragma('wal_checkpoint(TRUNCATE)');
this._assertDatabaseIntegrity(this.db);
this.dbHealthState = 'healthy';
return true;
} catch (e) {
if (!this._isSqliteCorruptionError(e)) {
console.error(`[KnowledgeBase] 🚨 SQLite checkpoint/quick_check failed after ${reason}: ${e.message || e}`);
return false;
}
// 🛡️ better-sqlite3 与 rusqlite 跨连接 WAL/SHM 交接后,旧连接偶发看到
// "database disk image is malformed" 的瞬态视图;先按 suspect 处理,只有二阶段
// 重开连接复检失败才升级为真正 corruption,避免把可恢复误报打成 ERROR。
console.warn(`[KnowledgeBase] 🩺 SQLite checkpoint/quick_check reported suspect state after ${reason}: ${e.message || e}`);
this.dbHealthState = 'suspect';
return this._recoverSuspectDatabaseConnection(reason, e);
}
}
_rebindDatabaseConnection(db) {
this.db = db;
if (this.tagMemoEngine) {
this.tagMemoEngine.db = db;
if (this.tagMemoEngine.epa) this.tagMemoEngine.epa.db = db;
if (this.tagMemoEngine.residualPyramid) this.tagMemoEngine.residualPyramid.db = db;
}
if (this.resultDeduplicator) {
this.resultDeduplicator.db = db;
if (this.resultDeduplicator.epa) this.resultDeduplicator.epa.db = db;
if (this.resultDeduplicator.residualCalculator) this.resultDeduplicator.residualCalculator.db = db;
}
}
_recoverSuspectDatabaseConnection(reason, firstError) {
if (!this.dbPath || this._recoveringDatabaseConnection) return false;
this._recoveringDatabaseConnection = true;
this.dbHealthState = 'recovering';
const oldDb = this.db;
try {
console.warn(`[KnowledgeBase] 🩺 SQLite suspect state after ${reason}; reopening connection for second-stage verification...`);
try { oldDb?.close(); } catch (closeErr) {
console.warn(`[KnowledgeBase] ⚠️ Failed to close suspect SQLite connection cleanly: ${closeErr.message}`);
}
const reopened = new Database(this.dbPath);
this._configureDatabaseConnection(reopened);
reopened.pragma('wal_checkpoint(TRUNCATE)');
this._assertDatabaseIntegrity(reopened);
this._rebindDatabaseConnection(reopened);
this.dbHealthState = 'healthy';
this.databaseCorruptionDetected = false;
console.warn('[KnowledgeBase] ✅ SQLite suspect verification passed after reopen; treating as transient WAL/SHM view issue.');
return true;
} catch (secondError) {
console.error(`[KnowledgeBase] 🚨 SQLite second-stage verification failed after ${reason}: ${secondError.message || secondError}`);
console.error(`[KnowledgeBase] First-stage failure was: ${firstError?.message || firstError}`);
this.dbHealthState = 'corrupt';
this.databaseCorruptionDetected = true;
return false;
} finally {
this._recoveringDatabaseConnection = false;
}
}
_isSqliteCorruptionError(e) {
const message = String(e?.message || e || '');
return e?.code === 'SQLITE_CORRUPT' ||
e?.code === 'SQLITE_NOTADB' ||
/database disk image is malformed|file is not a database|database corruption|quick_check failed/i.test(message);
}
_quarantineSqliteDatabase(dbPath, reason = 'corrupt') {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupBase = `${dbPath}.${reason}.${timestamp}.bak`;
const relatedFiles = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`];
for (const file of relatedFiles) {
if (!fsSync.existsSync(file)) continue;
const suffix = file === dbPath ? '' : path.basename(file).slice(path.basename(dbPath).length);
const target = `${backupBase}${suffix}`;
try {
fsSync.renameSync(file, target);
console.warn(`[KnowledgeBase] 🧯 Quarantined "${path.basename(file)}" -> "${path.basename(target)}"`);
} catch (err) {
console.error(`[KnowledgeBase] ❌ Failed to quarantine "${file}": ${err.message}`);
throw err;
}
}
return backupBase;
}
async _handleRuntimeSqliteCorruption(error, batchFiles = []) {
if (this.databaseCorruptionDetected) return;
this.databaseCorruptionDetected = true;
console.error('[KnowledgeBase] 🚨 SQLite database corruption detected at runtime; batch processing is paused.');
console.error(`[KnowledgeBase] Runtime corruption details: ${error?.message || error}`);
console.error(
'[KnowledgeBase] Recovery: stop the process, backup VectorStore, then restart. ' +
'On restart the corrupt knowledge_base.sqlite will be quarantined and rebuilt from dailynote files.'
);
if (batchFiles.length > 0) {
console.error(
`[KnowledgeBase] 🛡️ ${batchFiles.length} file(s) were NOT marked as permanently failed because the failure is database-level, not file-level.`
);
}
if (this.batchTimer) {
clearTimeout(this.batchTimer);
this.batchTimer = null;
}
this.pendingFiles.clear();
this.fileRetryCount.clear();
try {
if (this.watcher) {
if (this.watcherType === 'rust') {
const stopWatch = this.watcher.stopWatch || this.watcher.stop_watch;
if (typeof stopWatch === 'function') stopWatch.call(this.watcher);
} else if (typeof this.watcher.close === 'function') {
await this.watcher.close();
}
this.watcher = null;
console.error('[KnowledgeBase] 🛑 File watcher stopped to prevent retry storms against a corrupt SQLite database.');
}
} catch (watchErr) {
console.warn(`[KnowledgeBase] ⚠️ Failed to stop watcher after SQLite corruption: ${watchErr.message}`);
}
}
_delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
_startEventLoopWatchdog() {
if (this.eventLoopWatchdogTimer) return;
const intervalMs = parseInt(process.env.KNOWLEDGEBASE_EVENT_LOOP_WATCHDOG_MS, 10) || 5000;
const warnLagMs = parseInt(process.env.KNOWLEDGEBASE_EVENT_LOOP_WATCHDOG_WARN_LAG_MS, 10) || 2000;
this._lastEventLoopWatchdogAt = Date.now();
this.eventLoopWatchdogTimer = setInterval(() => {
const now = Date.now();
const expected = this._lastEventLoopWatchdogAt + intervalMs;
const lag = now - expected;
this._lastEventLoopWatchdogAt = now;
if (lag >= warnLagMs) {
console.warn(
`[KnowledgeBase] 🧯 Event loop lag detected: ${lag}ms. ` +
`state: pendingFiles=${this.pendingFiles.size}, pendingDeletes=${this.pendingDeletes.size}, ` +
`isProcessing=${this.isProcessing}, isProcessingDeletes=${this.isProcessingDeletes}, ` +
`rustLease=${this.rustWriteLease?.owner || 'none'}, loadedIndices=${this.diaryIndices.size}, ` +
`saveTimers=${this.saveTimers.size}, dbHealth=${this.dbHealthState}`
);
}
}, intervalMs);
if (this.eventLoopWatchdogTimer.unref) this.eventLoopWatchdogTimer.unref();
console.log(`[KnowledgeBase] 🧯 Event loop watchdog started (interval=${intervalMs}ms, warnLag=${warnLagMs}ms).`);
}
_isRustWriteLeaseExpired(now = Date.now()) {
return this.rustWriteLease &&
now - this.rustWriteLease.startedAt > (this.rustWriteLease.ttlMs || this.config.rustWriteLeaseTtlMs);
}
_canGrantRustWriteLease(options = {}) {
if (this.databaseCorruptionDetected || this.dbHealthState === 'corrupt') return { ok: false, reason: 'database-corruption' };
if (this.dbHealthState !== 'healthy') return { ok: false, reason: `database-${this.dbHealthState}` };
const now = Date.now();
if (this.startupCompletedAt > 0) {
const sinceStartupReady = now - this.startupCompletedAt;
if (sinceStartupReady < this.config.derivedStartupCooldownMs) {
return { ok: false, reason: `startup-cooldown:${this.config.derivedStartupCooldownMs - sinceStartupReady}ms` };
}
}
if (this._isRustWriteLeaseExpired(now)) {
console.error(
`[KnowledgeBase] 🚨 Rust write lease "${this.rustWriteLease.owner}" exceeded TTL; force-releasing stale lease.`
);
this.rustWriteLease = null;
this.lastRustWriteFinishedAt = now;
}
if (this.rustWriteLease) return { ok: false, reason: `rust-lease-active:${this.rustWriteLease.owner}` };
if (this.isProcessing) return { ok: false, reason: 'js-batch-processing' };
if (this.isProcessingDeletes) return { ok: false, reason: 'js-delete-processing' };
if (this.pendingDeletes.size > 0) return { ok: false, reason: `pending-deletes:${this.pendingDeletes.size}` };
const threshold = options.pendingThreshold ?? this.config.rustWriteLeasePendingThreshold;
if (threshold >= 0 && this.pendingFiles.size > threshold) {
return { ok: false, reason: `pending-files:${this.pendingFiles.size}>${threshold}` };
}
const graceMs = options.graceMs ?? this.config.rustWriteLeaseGraceMs;
const sinceJsWrite = now - this.lastJsWriteFinishedAt;
if (this.lastJsWriteFinishedAt > 0 && sinceJsWrite < graceMs) {
return { ok: false, reason: `js-write-cooldown:${graceMs - sinceJsWrite}ms` };
}
const sinceRustWrite = now - this.lastRustWriteFinishedAt;
if (this.lastRustWriteFinishedAt > 0 && sinceRustWrite < this.config.rustWriteLeaseCooldownMs) {
return { ok: false, reason: `rust-write-cooldown:${this.config.rustWriteLeaseCooldownMs - sinceRustWrite}ms` };
}
return { ok: true, reason: 'ok' };
}
async requestRustWriteLease(owner, options = {}) {
const startedWaitAt = Date.now();
const retryMs = options.retryMs ?? this.config.rustWriteLeaseRetryMs;
const maxWaitMs = options.maxWaitMs ?? this.config.rustWriteLeaseMaxWaitMs;
const ttlMs = options.ttlMs ?? this.config.rustWriteLeaseTtlMs;
while (true) {
const decision = this._canGrantRustWriteLease(options);
if (decision.ok) {
if (this.config.rustWriteLeaseCheckpointBeforeGrant) {
const healthy = this.checkpointAndAssertDatabaseHealthy(`granting Rust lease "${owner}"`);
if (!healthy) {
console.error(`[KnowledgeBase] 🦀🚫 Rust SQLite write lease "${owner}" denied because database health check failed.`);
return null;
}
}
this.rustWriteLease = {
owner,
startedAt: Date.now(),
ttlMs
};
console.log(`[KnowledgeBase] 🦀🔐 Rust SQLite write lease granted to "${owner}".`);
return {
owner,
release: () => this.releaseRustWriteLease(owner)
};
}
if (Date.now() - startedWaitAt >= maxWaitMs) {
console.warn(
`[KnowledgeBase] 🦀⏳ Rust SQLite write lease "${owner}" timed out after ${maxWaitMs}ms; last reason=${decision.reason}.`
);
return null;
}
const now = Date.now();
if (now - this._rustLeaseWaitLogAt > 30000) {
this._rustLeaseWaitLogAt = now;
console.log(
`[KnowledgeBase] 🦀⏳ Rust SQLite write lease "${owner}" waiting: ${decision.reason}. ` +
`pendingFiles=${this.pendingFiles.size}, pendingDeletes=${this.pendingDeletes.size}`
);
}
await this._delay(retryMs);
}
}
releaseRustWriteLease(owner) {
if (!this.rustWriteLease) return;
if (this.rustWriteLease.owner !== owner) {
console.warn(
`[KnowledgeBase] ⚠️ Ignored Rust write lease release from "${owner}"; active owner is "${this.rustWriteLease.owner}".`
);
return;
}
this.rustWriteLease = null;
this.lastRustWriteFinishedAt = Date.now();
console.log(`[KnowledgeBase] 🦀🔓 Rust SQLite write lease released by "${owner}".`);
if (!this.databaseCorruptionDetected) {
if (this.pendingDeletes.size > 0) {
setTimeout(() => this._flushDeleteBatch(), this.config.rustWriteLeaseCooldownMs);
}
if (this.pendingFiles.size > 0) {
setTimeout(() => this._flushBatch(), this.config.rustWriteLeaseCooldownMs);
}
}
}
_deferBatchForRustLease(type = 'batch') {
const owner = this.rustWriteLease?.owner || 'unknown';
const delay = this.config.rustWriteLeaseCooldownMs;
console.log(`[KnowledgeBase] 🦀⏸️ Deferring ${type} while Rust SQLite write lease is active (${owner}).`);
setTimeout(() => {
if (type === 'delete') this._flushDeleteBatch();
else this._flushBatch();
}, delay);
}
_decodeVectorBlob(blob, dim, label = 'vector') {
if (blob instanceof Float32Array) {
return blob.length === dim ? blob : null;
}
if (!blob || typeof blob.length !== 'number') {
return null;
}
const expectedBytes = dim * Float32Array.BYTES_PER_ELEMENT;
if (blob.length !== expectedBytes) {
console.warn(`[KnowledgeBase] ⚠️ Invalid ${label} blob length: expected ${expectedBytes}, got ${blob.length}`);
return null;
}
if (blob.byteOffset % Float32Array.BYTES_PER_ELEMENT === 0) {
return new Float32Array(blob.buffer, blob.byteOffset, dim);
}
const copied = Buffer.from(blob);
return new Float32Array(copied.buffer, copied.byteOffset, dim);
}
_queryByChunks(sqlPrefix, values, sqlSuffix = '', chunkSize = 500) {
if (!Array.isArray(values) || values.length === 0) return [];
const rows = [];
for (let i = 0; i < values.length; i += chunkSize) {
const batch = values.slice(i, i + chunkSize);
const placeholders = batch.map(() => '?').join(',');
rows.push(...this.db.prepare(`${sqlPrefix} IN (${placeholders})${sqlSuffix}`).all(...batch));
}
return rows;
}
_cleanupStalePairwiseSimilarityModels() {
try {
if (!this.tagMemoEngine?.modelSig) return;
// 单模型缓存策略下也不能在冷启动/空库/新签名尚未产出数据时清掉旧缓存。
// 否则部分用户在模型签名变化但当前 tags 尚未恢复/尚未计算完成时,会出现“旧数据被删、新数据为 0”的真空窗口。
const currentRows = this.db.prepare(
'SELECT COUNT(*) as count FROM tag_pair_similarity WHERE model_sig = ?'
).get(this.tagMemoEngine.modelSig)?.count || 0;
if (currentRows <= 0) {
const staleRows = this.db.prepare(
'SELECT COUNT(*) as count FROM tag_pair_similarity WHERE model_sig != ?'
).get(this.tagMemoEngine.modelSig)?.count || 0;
if (staleRows > 0) {
console.warn(
`[KnowledgeBase] 🛡️ Preserved ${staleRows} stale pairwise similarity row(s): ` +
`current model_sig=${this.tagMemoEngine.modelSig} has no cached rows yet.`
);
}
return;
}
const result = this.db.prepare(
'DELETE FROM tag_pair_similarity WHERE model_sig != ?'
).run(this.tagMemoEngine.modelSig);
if (result.changes > 0) {
console.warn(`[KnowledgeBase] 🧹 Removed ${result.changes} stale pairwise similarity row(s) from old embedding model signatures.`);
}
} catch (e) {
console.warn('[KnowledgeBase] ⚠️ Failed to cleanup stale pairwise similarity model rows:', e.message);
}
}
/**
* 🧹 启动期数据库修复:
* - 清理旧版本在 foreign_keys 未开启时遗留的 chunks/file_tags 孤儿记录
* - 清理服务器关闭/重启期间漏掉 unlink 事件造成的已不存在文件记录
* - 若清理影响到持久化日记索引,删除旧索引文件,避免 stale chunk id 被再次加载
*/
_cleanupDatabaseOrphans() {
try {
const affectedDiaries = new Set();
const missingFiles = this.db.prepare('SELECT id, path, diary_name FROM files').all()
.filter(row => !fsSync.existsSync(path.join(this.config.rootPath, row.path)));
missingFiles.forEach(row => affectedDiaries.add(row.diary_name));
const orphanChunkCount = this.db.prepare(`
SELECT COUNT(*) as count
FROM chunks c
LEFT JOIN files f ON c.file_id = f.id
WHERE f.id IS NULL
`).get().count || 0;
const cleanupTransaction = this.db.transaction(() => {
for (const row of missingFiles) {
this.db.prepare('DELETE FROM file_tags WHERE file_id = ?').run(row.id);
this.db.prepare('DELETE FROM chunks WHERE file_id = ?').run(row.id);
this.db.prepare('DELETE FROM files WHERE id = ?').run(row.id);
}
this.db.prepare(`
DELETE FROM file_tags
WHERE file_id NOT IN (SELECT id FROM files)
OR tag_id NOT IN (SELECT id FROM tags)
`).run();
this.db.prepare(`
DELETE FROM chunks
WHERE file_id NOT IN (SELECT id FROM files)
`).run();
});
cleanupTransaction();
for (const diaryName of affectedDiaries) {
this._deletePersistedDiaryIndex(diaryName);
}
if (orphanChunkCount > 0) {
// 孤儿 chunks 已经丢失 diary_name,只能保守删除全部持久化日记索引,后续从 SQLite 重建。
this._deleteAllPersistedDiaryIndexes();
}
if (missingFiles.length > 0 || orphanChunkCount > 0 || affectedDiaries.size > 0) {
console.warn(`[KnowledgeBase] 🧹 Startup cleanup complete. Removed ${missingFiles.length} missing file record(s), ${orphanChunkCount} orphan chunk(s), touched ${affectedDiaries.size} diary index(es).`);
}
} catch (e) {
console.error('[KnowledgeBase] ❌ Startup database cleanup failed:', e.message || e);
}
}
_deletePersistedDiaryIndex(diaryName) {
const shouldPersist = this.config.persistDefault || this.config.persistFolders.has(diaryName) || diaryName.endsWith('簇');
if (!shouldPersist) return;
const safeName = crypto.createHash('md5').update(diaryName).digest('hex');
const idxPath = path.join(this.config.storePath, `index_diary_${safeName}.usearch`);
const tmpPath = `${idxPath}.tmp`;
try {
if (fsSync.existsSync(idxPath)) {
fsSync.unlinkSync(idxPath);
console.warn(`[KnowledgeBase] 🧹 Removed stale persisted index for diary "${diaryName}". It will be rebuilt from SQLite.`);
}
if (fsSync.existsSync(tmpPath)) fsSync.unlinkSync(tmpPath);
} catch (e) {
console.warn(`[KnowledgeBase] ⚠️ Failed to remove stale persisted index for "${diaryName}": ${e.message}`);
}
}
_deleteAllPersistedDiaryIndexes() {
try {
const files = fsSync.readdirSync(this.config.storePath);
for (const file of files) {
if (!/^index_diary_[a-f0-9]{32}\.usearch(?:\.tmp)?$/i.test(file)) continue;
fsSync.unlinkSync(path.join(this.config.storePath, file));
}
console.warn('[KnowledgeBase] 🧹 Removed all persisted diary indexes because orphan chunks had lost diary ownership metadata.');
} catch (e) {
console.warn(`[KnowledgeBase] ⚠️ Failed to remove all persisted diary indexes: ${e.message}`);
}
}
// 🏭 索引工厂
async _getOrLoadDiaryIndex(diaryName) {
// 🌟 每次访问都刷新最后使用时间
this.diaryIndexLastUsed.set(diaryName, Date.now());
if (this.diaryIndices.has(diaryName)) {
return this.diaryIndices.get(diaryName);
}
const shouldPersist = this.config.persistDefault || this.config.persistFolders.has(diaryName) || diaryName.endsWith('簇');
console.log(`[KnowledgeBase] 📂 Loading index for diary: "${diaryName}" (Persist: ${shouldPersist})`);
const safeName = crypto.createHash('md5').update(diaryName).digest('hex');
const fileName = `diary_${safeName}`;
const capacity = 50000;
let idx;
if (shouldPersist) {
idx = await this._loadOrBuildIndex(fileName, capacity, 'chunks', diaryName);
} else {
// 🚀 核心改动:非持久化文件夹直接在内存重建
idx = new VexusIndex(this.config.dimension, capacity);
await this._recoverIndexFromDB(idx, 'chunks', diaryName);
}
this.diaryIndices.set(diaryName, idx);
return idx;
}
async _loadOrBuildIndex(fileName, capacity, tableType, filterDiaryName = null) {
const idxPath = path.join(this.config.storePath, `index_${fileName}.usearch`);
let idx;
try {
if (fsSync.existsSync(idxPath)) {
idx = VexusIndex.load(idxPath, null, this.config.dimension, capacity);
} else {
console.log(`[KnowledgeBase] Index file not found for ${fileName}, rebuilding from SQLite when possible.`);
idx = new VexusIndex(this.config.dimension, capacity);
if (filterDiaryName) {
await this._recoverIndexFromDB(idx, tableType, filterDiaryName);
}
}
} catch (e) {
console.error(`[KnowledgeBase] Index load error (${fileName}): ${e.message}`);
console.warn(`[KnowledgeBase] Rebuilding index ${fileName} from DB as a fallback...`);
idx = new VexusIndex(this.config.dimension, capacity);
await this._recoverIndexFromDB(idx, tableType, filterDiaryName);
}
return idx;
}
async _recoverIndexFromDB(vexusIdx, table, diaryName) {
console.log(`[KnowledgeBase] 🔄 Recovering ${table} (Filter: ${diaryName || 'None'}) via Rust...`);
try {
const dbPath = path.join(this.config.storePath, 'knowledge_base.sqlite');
// 注意:NAPI-RS 暴露的函数名是驼峰式
const count = await vexusIdx.recoverFromSqlite(dbPath, table, diaryName || null);
console.log(`[KnowledgeBase] ✅ Recovered ${count} vectors via Rust.`);
} catch (e) {
console.error(`[KnowledgeBase] ❌ Rust recovery failed for ${table}:`, e);
}
}
// =========================================================================
// 核心搜索接口 (修复版)
// =========================================================================
async search(arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
try {
let diaryName = null;
let queryVec = null;
let k = 5;
let tagBoost = 0;
let coreTags = [];
let coreBoostFactor = 1.33; // 默认 33% 提升
let options = null; // 🌟 V8: 扩展选项(geodesicRerank 等)
if (typeof arg1 === 'string' && Array.isArray(arg2)) {
diaryName = arg1;
queryVec = arg2;
k = arg3 || 5;
tagBoost = arg4 || 0;
coreTags = arg5 || [];
// 🌟 Wave v8: 解析 tagBoost 增强语法 (兼容字符串 "0.6+")
if (typeof tagBoost === 'string' && tagBoost.endsWith('+')) {
tagBoost = parseFloat(tagBoost.slice(0, -1)) || 0;
if (!options) options = {};
options.geodesicRerank = true;
} else {
tagBoost = parseFloat(tagBoost) || 0;
}
// 🌟 V8: arg6 可以是 coreBoostFactor (number) 或 options (object)
if (typeof arg6 === 'object' && arg6 !== null && !Array.isArray(arg6)) {
options = { ...options, ...arg6 };
} else {
coreBoostFactor = arg6 || 1.33;
options = (typeof arg7 === 'object' && arg7 !== null) ? { ...options, ...arg7 } : options;
}
} else if (typeof arg1 === 'string') {
// 纯文本搜索暂略,通常插件会先向量化
return [];
} else if (Array.isArray(arg1)) {
queryVec = arg1;
k = arg2 || 5;
tagBoost = arg3 || 0;
// 🌟 Wave v8: 全局搜索路径也解析 "0.6+" 语法
if (typeof tagBoost === 'string' && tagBoost.endsWith('+')) {
tagBoost = parseFloat(tagBoost.slice(0, -1)) || 0;
if (!options) options = {};
options.geodesicRerank = true;
} else {
tagBoost = parseFloat(tagBoost) || 0;
}
}
if (!queryVec) return [];
if (diaryName) {
return await this._searchSpecificIndex(diaryName, queryVec, k, tagBoost, coreTags, coreBoostFactor, options);
} else {
return await this._searchAllIndices(queryVec, k, tagBoost, coreTags, coreBoostFactor, options);
}
} catch (e) {
console.error('[KnowledgeBase] Search Error:', e);
return [];
}
}
async _searchSpecificIndex(diaryName, vector, k, tagBoost, coreTags = [], coreBoostFactor = 1.33, options = null) {
const idx = await this._getOrLoadDiaryIndex(diaryName);
// 如果索引为空,直接返回
// 注意:vexus-lite-js 可能没有 size() 方法,用 catch 捕获
try {
const stats = idx.stats ? idx.stats() : { totalVectors: 1 };
if (stats.totalVectors === 0) return [];
} catch (e) { }
// 🛠️ 修复 1: 安全的 Float32Array 转换
let searchVecFloat;
let tagInfo = null;
let energyField = null;
try {
if (tagBoost > 0 && this.tagMemoEngine) {
// 🌟 TagMemo 逻辑回归:应用 Tag 增强 (强制使用 V6)
const boostResult = this.tagMemoEngine.applyTagBoost(new Float32Array(vector), tagBoost, coreTags, coreBoostFactor);
searchVecFloat = boostResult.vector;
tagInfo = boostResult.info;
energyField = boostResult.energyField || null;
} else {
searchVecFloat = vector instanceof Float32Array ? vector : new Float32Array(vector);
}
// ⚠️ 维度检查
if (searchVecFloat.length !== this.config.dimension) {
console.error(`[KnowledgeBase] Dimension mismatch! Expected ${this.config.dimension}, got ${searchVecFloat.length}`);
return [];
}
} catch (err) {
console.error(`[KnowledgeBase] Vector processing failed: ${err.message}`);
return [];
}
let results = [];
try {
results = idx.search(searchVecFloat, k);
} catch (e) {
// 🛠️ 修复 2: 详细的错误日志
console.error(`[KnowledgeBase] Vexus search failed for "${diaryName}":`, e.message || e);
return [];
}
// 🌟 V8: 测地线重排(只重排,不截断)— 在 hydrate 之前执行