Repository navigation
Expand file tree
/
Copy pathKnowledgeBaseManager.js
More file actions
3905 lines (3665 loc) · 160 KB
/
Copy pathKnowledgeBaseManager.js
File metadata and controls
3905 lines (3665 loc) · 160 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 { AsyncLocalStorage } = require('node:async_hooks');
// 单轮请求拥有共享观测;异步读出只借用句柄,不得提前释放。
const memoObservationScope = new AsyncLocalStorage();
const { getEmbeddingsBatch } = require('./EmbeddingUtils');
const ResultDeduplicator = require('./ResultDeduplicator'); // ✅ Tagmemo v4 requirement
const TagMemoEngine = require('./TagMemoEngine');
const TagMemoV10Engine = require('./TagMemoV10Engine');
const RiverMemoEngine = require('./RiverMemoEngine');
const { decodeVectorBlob } = require('./modules/knowledgeBase/vectorCodec');
const { stableSerialize } = require('./modules/tagmemoV10/immutable');
const {
prepareTextForEmbedding,
extractTags
} = require('./modules/knowledgeBase/textPreprocessor');
const {
estimateVexusIndexBytes,
safeIndexStats,
buildMemoryProfile,
captureMemoryStage
} = require('./modules/knowledgeBase/memoryProfiler');
const DiaryMetadataCache = require('./modules/knowledgeBase/diaryMetadataCache');
const IndexRepository = require('./modules/knowledgeBase/indexRepository');
const DatabaseCoordinator = require('./modules/knowledgeBase/databaseCoordinator');
const KnowledgeBaseFileWatcher = require('./modules/knowledgeBase/fileWatcher');
const IngestionPipeline = require('./modules/knowledgeBase/ingestionPipeline');
const SearchService = require('./modules/knowledgeBase/searchService');
const TagConsistencyService = require('./modules/knowledgeBase/tagConsistencyService');
// 尝试加载 Rust Vexus 引擎
let VexusIndex = null;
let NativeKnowledgeRuntime = null;
try {
const vexusModule = require('./rust-vexus-lite');
VexusIndex = vexusModule.VexusIndex;
NativeKnowledgeRuntime = vexusModule.NativeKnowledgeRuntime || null;
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) || 1000,
maxBatchSize: parseInt(process.env.KNOWLEDGEBASE_MAX_BATCH_SIZE, 10) || 50,
sqliteBusyTimeoutMs: (() => {
const value = Number(process.env.KNOWLEDGEBASE_SQLITE_BUSY_TIMEOUT_MS);
return Number.isFinite(value) && value >= 0
? Math.floor(value)
: 10000;
})(),
sqliteBusyRetryDelayMs: (() => {
const value = Number(process.env.KNOWLEDGEBASE_SQLITE_BUSY_RETRY_DELAY_MS);
return Number.isFinite(value) && value >= 0
? Math.floor(value)
: 1000;
})(),
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,
migrationCacheTtlMs: parseInt(process.env.KNOWLEDGEBASE_MIGRATION_CACHE_TTL_MS, 10) || 2 * 60 * 1000,
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,
lightMemoIndexIdleTTL: Math.max(1, Math.min(0xffffffff,
parseInt(process.env.KNOWLEDGEBASE_LIGHTMEMO_IDLE_TTL_MS, 10) || 10 * 60 * 1000)),
indexIdleSweepInterval: parseInt(process.env.KNOWLEDGEBASE_INDEX_IDLE_SWEEP_MS, 10) || 10 * 60 * 1000,
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),
maxTagsPerFile: (() => {
const value = parseInt(process.env.KNOWLEDGEBASE_MAX_TAGS_PER_FILE, 10);
return Number.isFinite(value) && value > 0 ? value : 50;
})(),
fullScanOnStartup: (process.env.KNOWLEDGEBASE_FULL_SCAN_ON_STARTUP || 'true').trim().toLowerCase() === 'true',
// 语言置信度补偿配置
langConfidenceEnabled: (process.env.LANG_CONFIDENCE_GATING_ENABLED || 'true').toLowerCase() === 'true',
// Undefined means inherit hot parameters; explicit zero is valid.
langPenaltyUnknown: this._readOptionalPenalty(process.env.LANG_PENALTY_UNKNOWN),
langPenaltyCrossDomain: this._readOptionalPenalty(process.env.LANG_PENALTY_CROSS_DOMAIN),
// Native River 联合查询是 RiverMemo 的默认生产范式。Memo observation
// 仍由统一管线生成,ANN/合并/向量 hydrate/语义去重/Topology V3
// 收敛为一次 NativeKnowledgeRuntime 调用。仅显式 false 时紧急关闭。
nativeRiverQueryEnabled:
(process.env.KNOWLEDGEBASE_NATIVE_RIVER_QUERY_ENABLED || 'true')
.toLowerCase() !== 'false',
nativeRiverQueryFallbackToLegacy:
(process.env.KNOWLEDGEBASE_NATIVE_RIVER_QUERY_FALLBACK_TO_LEGACY || 'true')
.toLowerCase() !== 'false',
nativeRiverQueryPerIndexK: (() => {
const value = Number(
process.env.KNOWLEDGEBASE_NATIVE_RIVER_QUERY_PER_INDEX_K
);
return Number.isFinite(value) && value > 0
? Math.floor(value)
: 300;
})(),
nativeRiverQueryCandidateK: (() => {
const value = Number(
process.env.KNOWLEDGEBASE_NATIVE_RIVER_QUERY_CANDIDATE_K
);
return Number.isFinite(value) && value > 0
? Math.floor(value)
: 300;
})(),
nativeRiverQuerySemanticThreshold: (() => {
const value = Number(
process.env.KNOWLEDGEBASE_NATIVE_RIVER_QUERY_SEMANTIC_THRESHOLD
);
return Number.isFinite(value)
? Math.max(-1, Math.min(1, value))
: 0.92;
})(),
// Tag 快照只用于加速恢复,原向量始终以 SQLite 为准。
// 历史 always/布尔值仅兼容解析,不能绕过累计差异阈值;
// 只有显式 generational 授予无文件、无 SQL 签名时的首代创建许可。
tagIndexPersistenceMode: (() => {
const raw = String(
process.env.KNOWLEDGEBASE_PERSIST_TAG_INDEX
|| 'generational'
).trim().toLowerCase();
if (raw === 'always' || raw === 'true') return 'always';
if (raw === 'generational' || raw === 'false') {
return 'generational';
}
console.warn(
`[KnowledgeBase] Invalid KNOWLEDGEBASE_PERSIST_TAG_INDEX="${raw}"; ` +
'falling back to recommended mode "generational".'
);
return 'generational';
})(),
tagIndexAllowInitial:
String(process.env.KNOWLEDGEBASE_PERSIST_TAG_INDEX || '').trim().toLowerCase() === 'generational',
chunkIndexAllowInitial:
String(process.env.KNOWLEDGEBASE_PERSIST_CHUNK_INDEX || '').trim().toLowerCase() === 'generational',
tagIndexBaselineDeltaRatio: (() => {
const value = Number(
process.env.KNOWLEDGEBASE_TAG_INDEX_BASELINE_DELTA_RATIO
);
return Number.isFinite(value) && value > 0 && value <= 1
? value
: 0.05;
})(),
// 兼容仍读取该字段的旧代码;两种枚举模式都表示启用 Tag 索引落地。
// Agent/日记与全局 Chunk 快照共用发布策略:
// 累计差异达到阈值才发布,显式 generational 才授权首代;
// none/off 禁止发布。全局 Chunk 另须默认范围或 global_chunks 白名单。
chunkIndexPersistenceMode: (() => {
const raw = String(
process.env.KNOWLEDGEBASE_PERSIST_CHUNK_INDEX
|| 'generational'
).trim().toLowerCase();
if (raw === 'always' || raw === 'true') return 'always';
if (raw === 'none' || raw === 'off') return 'none';
if (raw === 'generational' || raw === 'false' || !raw) {
return 'generational';
}
console.warn(
`[KnowledgeBase] Invalid KNOWLEDGEBASE_PERSIST_CHUNK_INDEX="${raw}"; ` +
'falling back to recommended mode "generational".'
);
return 'generational';
})(),
chunkIndexBaselineDeltaRatio: (() => {
const value = Number(
process.env.KNOWLEDGEBASE_CHUNK_INDEX_BASELINE_DELTA_RATIO
);
return Number.isFinite(value) && value > 0 && value <= 1
? value
: 0.05;
})(),
persistTagIndex: 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.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.nativeKnowledgeRuntime = null;
this.nativeDiaryIndexGenerations = new Map();
this.watcher = null;
this.initialized = false;
this.eventLoopWatchdogTimer = null;
this._lastEventLoopWatchdogAt = 0;
this.diaryNameVectorCache = new Map();
// 🌟 日记时间索引缓存:随日记本向量索引加载/卸载生命周期维护,供 RAG ::Time 直接查询。
// diaryName -> [{ relativePath, date }]
this.diaryDateIndexCache = new Map();
this.pendingFiles = new Set();
this.fileRetryCount = new Map(); // 🛡️ 文件重试计数器,防止无限循环
// Rust watcher 稳定事件代际:同一路径只接受严格更新的 generation。
this.watcherPathGenerations = new Map();
this.staleWatcherEventsDropped = 0;
this.batchTimer = null;
this.isProcessing = false;
this.saveTimers = new Map();
this.pendingDeletes = new Set();
this.deleteBatchTimer = null;
this.isProcessingDeletes = false;
this.tagMemoEngine = null;
this.tagMemoV10Engine = null;
this.riverMemoEngine = null;
this.resultDeduplicator = null; // ✅ Tagmemo v4
this.ragParams = {}; // ✅ 新增:用于存储热调控参数
this.ragParamsWatcher = null;
this.ragParamsWatcherPoller = null;
this.ragParamsWatcherType = null;
this.lastActivityAt = Date.now();
// 🧭 外部文件写入协调器(DailyNote 等常驻服务使用)
// 文件变更本身不直接写 SQLite,但必须与 watcher 批处理、Rust SQLite 恢复形成单一时序。
this.externalMutationActive = false;
this.externalMutationOwner = null;
this.externalMutationQueueLength = 0;
// 索引收集窗口在长耗时外部变更期间到期时,只设置闩锁;
// 变更提交后立即补刷,避免复用 Rust 冷却时间或创建重复定时器。
this.externalMutationBatchDeferred = false;
this.externalMutationDeleteBatchDeferred = false;
this._externalMutationTail = Promise.resolve();
// 🛡️ 同一时刻只允许一个 Rust recoverFromSqlite 打开知识库。
// diaryIndexLoadPromises 去重同一日记本;_indexRecoveryTail 串行化不同日记本。
this.diaryIndexLoadPromises = new Map();
this.indexRecoveryActive = false;
this._indexRecoveryTail = Promise.resolve();
// 中央库健康状态由 NativeKnowledgeRuntime 管理。摄取链路只依赖
// 下方稳定的错误分类门面,不再通过 JS 健康管理器重绑数据库连接。
this.diaryMetadataCache = new DiaryMetadataCache({
getNativeRuntime: () => this.nativeKnowledgeRuntime,
getDbPath: () => this.dbPath,
dimension: this.config.dimension,
getEmbeddingsBatch,
getEmbeddingConfig: () => ({
apiKey: this.config.apiKey,
apiUrl: this.config.apiUrl,
model: this.config.model
}),
nameVectorCache: this.diaryNameVectorCache,
dateIndexCache: this.diaryDateIndexCache
});
this.indexRepository = new IndexRepository({
config: this.config,
VexusIndex,
getDbPath: () => this.dbPath,
getNativeRuntime: () => this.nativeKnowledgeRuntime,
waitForCoordinatorIdle: options => this._waitForDatabaseCoordinatorIdle(options),
ensureDiaryDateIndex: diaryName => this._ensureDiaryDateIndexCached(diaryName),
invalidateDiaryDateIndex: diaryName => this.invalidateDiaryDateIndex(diaryName),
onDiaryIndexPublished: (diaryName, index) =>
this._registerNativeDiaryIndex(diaryName, index),
onDiaryIndexRemoved: diaryName =>
this._unregisterNativeDiaryIndex(diaryName),
onRecoveryStateChange: active => {
this.indexRecoveryActive = active;
if (active) {
this.touchActivity();
}
},
onRecoveryTailChange: tail => {
this._indexRecoveryTail = tail;
},
diaryIndices: this.diaryIndices,
lastUsed: this.diaryIndexLastUsed,
loadPromises: this.diaryIndexLoadPromises,
saveTimers: this.saveTimers
});
this.databaseCoordinator = new DatabaseCoordinator({
owner: this
});
this.fileWatcher = new KnowledgeBaseFileWatcher({
owner: this,
VexusIndex,
loadVexusModule: () => require('./rust-vexus-lite')
});
this.ingestionPipeline = new IngestionPipeline(this);
this.searchService = new SearchService(this);
this.tagConsistencyService = new TagConsistencyService(this, {
VexusIndex
});
}
_readOptionalPenalty(raw) {
if (raw === undefined || raw === null || String(raw).trim() === '') return undefined;
const value = Number(raw);
return Number.isFinite(value) && value >= 0 && value <= 1 ? value : undefined;
}
async initialize() {
if (this.initialized) return;
this._captureMemoryStage('initialize:begin');
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;
console.log(
'[KnowledgeBaseProbe] Central SQLite ownership is delegated to ' +
'NativeKnowledgeRuntime; JavaScript does not open or initialize the database.'
);
// 1. 先创建空的全局 Tag 索引作为 MemoRuntime 所有权根。
// 基线恢复必须在 Rust Store 和启动清理之后执行,避免把已删除事实
// 发布到活动索引;此处的空索引只用于构造 NativeKnowledgeRuntime。
const tagCapacity = 50000;
this.tagIndex = new VexusIndex(
this.config.dimension,
tagCapacity
);
this.indexRepository.tagIndex = this.tagIndex;
// 2. 先打开 Rust Store,再执行所有启动期中央库清理。
if (!NativeKnowledgeRuntime) {
throw new Error(
'[KnowledgeBase] NativeKnowledgeRuntime ABI unavailable; ' +
'rebuild rust-vexus-lite before starting KBM.'
);
}
try {
this.nativeKnowledgeRuntime = new NativeKnowledgeRuntime(
this.tagIndex
);
if (typeof this.nativeKnowledgeRuntime.capabilities !== 'function') {
const error = new Error(
'NativeKnowledgeRuntime capability handshake is unavailable; ' +
'rebuild rust-vexus-lite before starting KBM.'
);
error.code = 'NATIVE_STORAGE_ABI_UNAVAILABLE';
throw error;
}
const capabilities = this.nativeKnowledgeRuntime.capabilities();
const requiredCapabilities = [
'sqlite.storage-engine.v1',
'sqlite.write-actor.v1',
'sqlite.read-pool.v1',
'sqlite.schema-init.v1',
'sqlite.ingestion-commit.v1',
'sqlite.delete-commit.v1',
'sqlite.tag-consistency.v1',
'text.preparation.v1',
'index.async-restore.v1',
'index.dual-slot-checkpoint.v1',
'index.tdb-vec.v1',
'index.sql-authoritative-generational.v1',
'index.cosine-score.v1',
'watcher.runtime-owned.v1',
'memo.native-artifact.v1',
'river.native-query.v1'
];
const missingCapabilities = requiredCapabilities.filter(
capability => !Array.isArray(capabilities?.capabilities)
|| !capabilities.capabilities.includes(capability)
);
if (
Number(capabilities?.abiVersion) !== 2
|| Number(capabilities?.dimension) !== this.config.dimension
|| missingCapabilities.length > 0
) {
const error = new Error(
'NativeKnowledgeRuntime capability handshake failed: '
+ JSON.stringify({
expectedAbiVersion: 2,
actualAbiVersion: capabilities?.abiVersion ?? null,
expectedDimension: this.config.dimension,
actualDimension: capabilities?.dimension ?? null,
missingCapabilities
})
);
error.code = 'NATIVE_STORAGE_ABI_MISMATCH';
throw error;
}
if (
typeof this.nativeKnowledgeRuntime.openAndInitStore !== 'function'
|| typeof this.nativeKnowledgeRuntime.storeState !== 'function'
|| typeof this.nativeKnowledgeRuntime.healthCheck !== 'function'
|| typeof this.nativeKnowledgeRuntime.cleanupDatabaseOrphans !== 'function'
|| typeof this.nativeKnowledgeRuntime.getKvVector !== 'function'
|| typeof this.nativeKnowledgeRuntime.setKvVector !== 'function'
|| typeof this.nativeKnowledgeRuntime.listKvVectors !== 'function'
|| typeof this.nativeKnowledgeRuntime.getDiaryChunkCount !== 'function'
|| typeof this.nativeKnowledgeRuntime.prepareText !== 'function'
|| typeof this.nativeKnowledgeRuntime.getTagVectorByName !== 'function'
|| typeof this.nativeKnowledgeRuntime.getTagConsistencySnapshot !== 'function'
|| typeof this.nativeKnowledgeRuntime.commitTagConsistency !== 'function'
|| typeof this.nativeKnowledgeRuntime.getNativeMemoManifest !== 'function'
|| typeof this.nativeKnowledgeRuntime.pruneNativeMemoArtifacts !== 'function'
|| typeof this.nativeKnowledgeRuntime.searchGlobalTags !== 'function'
|| typeof this.nativeKnowledgeRuntime.cancelPreparedPlan !== 'function'
|| typeof this.nativeKnowledgeRuntime.listIndexedFilePaths !== 'function'
|| typeof this.nativeKnowledgeRuntime.reconcileWatchWithPaths !== 'function'
|| typeof this.nativeKnowledgeRuntime.restoreGlobalTagIndex !== 'function'
|| typeof this.nativeKnowledgeRuntime.restoreDiaryIndex !== 'function'
|| typeof this.nativeKnowledgeRuntime.checkpointGlobalTagIndex !== 'function'
|| typeof this.nativeKnowledgeRuntime.checkpointDiaryIndex !== 'function'
|| typeof this.nativeKnowledgeRuntime.checkpointGlobalChunkIndex !== 'function'
) {
throw new Error(
'NativeKnowledgeRuntime storage ABI unavailable; rebuild rust-vexus-lite'
);
}
const storeState = this.nativeKnowledgeRuntime.openAndInitStore(
dbPath,
JSON.stringify({
readPoolSize: Number(
process.env.KNOWLEDGEBASE_RUST_READ_POOL_SIZE
) || 4,
mmapSize: (() => {
const raw = process.env.KNOWLEDGEBASE_RUST_MMAP_SIZE;
const value = Number(raw);
return raw !== undefined && raw.trim() !== ''
&& Number.isSafeInteger(value) && value >= 0
? value
: 64 * 1024 * 1024;
})(),
busyTimeoutMs: this.config.sqliteBusyTimeoutMs,
schemaVersion: 2
})
);
console.log(
'[KnowledgeBase] 🦀 NativeKnowledgeRuntime ready; ' +
`Rust Store opened at generation=${storeState.databaseGeneration}.`
);
} catch (error) {
try {
this.nativeKnowledgeRuntime?.shutdown?.();
} catch (_) {}
this.nativeKnowledgeRuntime = null;
throw new Error(
'[KnowledgeBase] NativeKnowledgeRuntime storage initialization failed: '
+ (error.message || error)
);
}
this._captureMemoryStage('store:opened');
const tOrphan0 = Date.now();
await this._cleanupDatabaseOrphansNative();
console.log(
`[KnowledgeBaseProbe] ⏱️ Rust orphan cleanup complete in ` +
`${Date.now() - tOrphan0}ms.`
);
this._captureMemoryStage('store:orphans-cleaned');
// 3. 初始化全局 Tag 索引。
// tags 是唯一权威真相;磁盘 .vec 只是经 SQL 背书、允许落后的双槽基线。
// 活动槽加载、成员差分回放和无基线重建全部由 Rust Runtime 后台执行。
let indexReady = false;
console.log(
'[KnowledgeBase] 🚀 Restoring Global Tag Index through NativeKnowledgeRuntime...'
);
try {
const restored = await this.nativeKnowledgeRuntime.restoreGlobalTagIndex(
dbPath,
path.join(this.config.storePath, 'index_global_tags_a.vec'),
this.config.modelSig,
tagCapacity
);
const parsed = typeof restored === 'string'
? JSON.parse(restored)
: restored;
if (!parsed || parsed.restored !== true) {
throw new Error('Invalid Rust global Tag restore receipt');
}
console.log(
`[KnowledgeBase] ✅ Global Tag Index ready. ` +
`${Number(parsed.vectorCount) || 0} vectors indexed, ` +
`generation=${Number(parsed.generation) || 0}, ` +
`slot=${parsed.slot || 'none'}.`
);
indexReady = true;
} catch (e) {
console.error(
`[KnowledgeBase] ❌ Global Tag Index recovery failed: ` +
e.message
);
}
if (!indexReady) {
throw new Error(
'[KnowledgeBase] Global Tag Index recovery failed after startup cleanup.'
);
}
this._captureMemoryStage('tags:restored');
// 3. 通过 Rust Read Pool 异步预热日记本名称向量缓存。
// 启动阶段不再在 Node.js 主线程直接扫描中央 kv_store。
await this._hydrateDiaryNameCache();
// 🧹 初始化 KBM 通用结果去重器。
// 向量补水统一通过 NativeKnowledgeRuntime,生产路径不持有中央数据库连接。
this.resultDeduplicator = new ResultDeduplicator({
dimension: this.config.dimension,
hydrateChunksByIds: chunkIds => this.hydrateChunksByIds(chunkIds)
});
await this.loadRagParams();
// 初始化生产 V9.2 控制面;中央数据库所有权归 Rust Runtime。
this.tagMemoEngine = new TagMemoEngine(
null,
this.tagIndex,
this.config,
this.ragParams,
this
);
await this.tagMemoEngine.initialize();
// V10/RiverMemo 仅保留轻量控制面;完整图、CSR 与 Provenance 归属
// VexusIndex.memoRuntime,不再从 V9 JavaScript Map 编译或读取中央 SQL。
this.tagMemoV10Engine = new TagMemoV10Engine(
null,
this.tagIndex,
this.config,
this.ragParams,
{
v9Engine: this.tagMemoEngine,
getNativeRuntime: () => this.nativeKnowledgeRuntime
}
);
// 已停用旧 JS exact derived asset 启动审计。
// RiverMemo Topology V3 现由 Rust 从原始向量计算并按 artifact 签名持有
// 原生运行时缓存;v10_vector_metrics / v10_chunk_tag_geometry 仅供已退休的
// JS 路径使用。保留下方旧入口注释,便于兼容性回滚,不再在启动时重建。
// try {
// this.tagMemoV10Engine.ensureExactDerivedAssets();
// } catch (error) {
// console.error(
// '[KnowledgeBase] ⚠️ Legacy V10 exact derived asset audit failed:',
// error.message || error
// );
// }
const riverMemoConfig =
this.ragParams?.KnowledgeBaseManager?.riverMemo || {};
this.riverMemoEngine = new RiverMemoEngine(
this.tagMemoV10Engine,
{ config: riverMemoConfig }
);
// 冷启动只读取 SQLite 清单元数据,绝不在 JS 解压/恢复完整资产。
// 命中严格兼容清单后,首次查询由 Rust 懒加载并原子发布 Arc;
// 未命中则由 post-startup 原生 bootstrap 构建。
let nativeMemoRestored = false;
try {
const restored = await this._restoreNativeMemoControlHandles();
nativeMemoRestored = !!restored;
if (!nativeMemoRestored) {
console.warn(
'[KnowledgeBase] 🧊 No compatible native Memo artifact manifest; ' +
'native bootstrap will be queued immediately after System Ready.'
);
}
} catch (error) {
console.error(
'[KnowledgeBase] ⚠️ Native Memo control-handle restore failed; ' +
'native bootstrap will be queued immediately after System Ready:',
error.message || error
);
}
this._captureMemoryStage('memo:manifest-checked');
this._startWatcher();
this._startRagParamsWatcher();
this._startIdleSweep(); // 🌟 启动空闲索引自动卸载
this._startEventLoopWatchdog(); // 🛡️ 运行期无日志卡死定位:记录主线程长阻塞
this.initialized = true;
this.startupCompletedAt = Date.now();
this._captureMemoryStage('initialize:ready');
console.log('[KnowledgeBase] ✅ System Ready');
if (this.tagMemoEngine && typeof this.tagMemoEngine.schedulePostStartupDerivedRefresh === 'function') {
// 原生资产存在时,5 分钟窗口仅执行可选热自检;首次查询可由 Rust
// 从 SQLite payload 懒加载 MemoRuntime Arc。若清单缺失,则必需资产
// 必须立即进入 bootstrap 队列,不能让查询在冷却期内持续失败。
const derivedRefreshDelayMs = nativeMemoRestored
? this.config.derivedStartupCooldownMs
: 0;
this.tagMemoEngine.schedulePostStartupDerivedRefresh(derivedRefreshDelayMs);
}
}
/**
* ✅ 新增:加载 RAG 热调控参数
*/
async loadRagParams() {
const paramsPath = path.join(__dirname, 'rag_params.json');
try {
const data = await fs.readFile(paramsPath, 'utf-8');
const parsed = JSON.parse(data);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new TypeError('rag_params.json root must be a JSON object');
}
if (
parsed.KnowledgeBaseManager !== undefined
&& (
!parsed.KnowledgeBaseManager
|| typeof parsed.KnowledgeBaseManager !== 'object'
|| Array.isArray(parsed.KnowledgeBaseManager)
)
) {
throw new TypeError('rag_params.json KnowledgeBaseManager must be an object');
}
// 解析和基础结构校验全部通过后再一次性发布,避免编辑中的短暂坏 JSON
// 覆盖仍在工作的最后健康配置。
this.ragParams = require('./modules/knowledgeBase/memoConfig').cleanRagParams(parsed);
console.log('[KnowledgeBase] ✅ RAG 热调控参数已加载');
if (this.resultDeduplicator) {
this.resultDeduplicator.updateConfig(
this.ragParams.KnowledgeBaseManager?.resultDeduplication || {}
);
}
if (this.tagMemoEngine) this.tagMemoEngine.updateRagParams(this.ragParams);
if (this.tagMemoV10Engine) this.tagMemoV10Engine.updateRagParams(this.ragParams);
if (this.riverMemoEngine) {
this.riverMemoEngine.updateConfig(
this.ragParams.KnowledgeBaseManager?.riverMemo || {}
);
}
return true;
} catch (e) {
console.error('[KnowledgeBase] ❌ 加载 rag_params.json 失败,继续使用最后健康配置:', e.message);
if (!this.ragParams || typeof this.ragParams !== 'object') {
this.ragParams = { KnowledgeBaseManager: {} };
}
return false;
}
}
/**
* 启动参数监听器。
*
* KBM 生产路径统一使用 Rust notify;这里单独创建一个原生 watcher
* 监听项目根目录中的 JSON 事件,再精确筛选 rag_params.json。
*/
_startRagParamsWatcher() {
const paramsPath = path.resolve(__dirname, 'rag_params.json');
if (this.ragParamsWatcher) return;
const vexusModule = require('./rust-vexus-lite');
if (typeof vexusModule.VexusWatcher !== 'function') {
throw new Error(
'VexusWatcher native class is unavailable; rebuild rust-vexus-lite'
);
}
const watcher = new vexusModule.VexusWatcher();
const startWatch = watcher.startWatch || watcher.start_watch;
const drainEvents = watcher.drainEvents || watcher.drain_events;
if (
typeof startWatch !== 'function'
|| typeof drainEvents !== 'function'
) {
throw new Error(
'VexusWatcher queue ABI is unavailable; rebuild rust-vexus-lite'
);
}
let refreshInFlight = false;
let refreshQueued = false;
const refresh = async () => {
if (refreshInFlight) {
refreshQueued = true;
return;
}
refreshInFlight = true;
try {
console.log(
'[KnowledgeBase] 🔄 检测到 rag_params.json 变更,正在重新加载...'
);
await this.loadRagParams();
} catch (error) {
console.error(
'[KnowledgeBase] Failed to reload rag_params.json:',
error
);
} finally {
refreshInFlight = false;
if (refreshQueued) {
refreshQueued = false;
void refresh();
}
}
};
startWatch.call(watcher, {
rootPath: __dirname,
ignoreFolders: ['node_modules', '.git', 'dist', 'target', 'image'],
ignorePrefixes: [],
ignoreSuffixes: [],
extensions: ['json'],
debounceMs: parseInt(
process.env.KNOWLEDGEBASE_RAG_PARAMS_WATCH_DEBOUNCE_MS,
10
) || 350,
stabilityMs: parseInt(
process.env.KNOWLEDGEBASE_RAG_PARAMS_WATCH_STABILITY_MS,
10
) || 150,
stabilityRetries: parseInt(
process.env.KNOWLEDGEBASE_RAG_PARAMS_WATCH_STABILITY_RETRIES,
10
) || 6,
initialScan: false
});
const poller = setInterval(() => {
let events;
try {
events = drainEvents.call(watcher, 128) || [];
} catch (error) {
console.warn(
'[KnowledgeBase] Failed to drain rag_params watcher events:',
error.message || error
);
return;
}
for (const payload of events) {
const eventPath = path.resolve(String(payload?.path || ''));
if (
eventPath === paramsPath
&& ['add', 'change'].includes(payload?.event)
&& payload?.stable === true
) {
void refresh();
}
}
}, 100);
if (typeof poller.unref === 'function') poller.unref();
this.ragParamsWatcher = watcher;
this.ragParamsWatcherPoller = poller;
this.ragParamsWatcherType = 'rust-queue';
}
_buildNativeMemoEffectiveConfig() {
const kbConfig = JSON.parse(JSON.stringify(
this.ragParams?.KnowledgeBaseManager || {}
));
const memoControlConfig =
this.tagMemoV10Engine?.getEffectiveConfig?.() || {};
return JSON.parse(JSON.stringify({
...kbConfig,
...memoControlConfig,
orderedCooccurrence: kbConfig.orderedCooccurrence || {},
v9: kbConfig.v9 || {},
spikeRouting: kbConfig.spikeRouting || {}
}));
}
_computeNativeMemoConfigHash(effectiveConfig) {
// 跨语言持久化契约必须使用规范 JSON。Rust 的 serde_json::Map 在当前
// 构建中按键有序序列化;普通 JSON.stringify 依赖 JS 对象插入顺序,
// 会让同一配置在重启恢复时产生不同 hash 并错误拒绝健康资产。
return crypto.createHash('sha256')
.update(stableSerialize(effectiveConfig))
.digest('hex')
.slice(0, 32);
}
async _restoreNativeMemoControlHandles() {
if (!this.tagMemoEngine || !this.tagMemoV10Engine) return null;
if (
!this.nativeKnowledgeRuntime
|| typeof this.nativeKnowledgeRuntime.getNativeMemoManifest !== 'function'
) {
const error = new Error(
'NativeKnowledgeRuntime Memo manifest ABI is unavailable'
);
error.code = 'NATIVE_STORAGE_ABI_UNAVAILABLE';
throw error;
}
const effectiveConfig = this._buildNativeMemoEffectiveConfig();
const configHash = this._computeNativeMemoConfigHash(effectiveConfig);
const raw = await this.nativeKnowledgeRuntime.getNativeMemoManifest(
this.dbPath,
this.tagMemoEngine.modelSig,
configHash
);
const row = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!row || typeof row !== 'object') return null;
const nativeResult = {
success: true,
artifactSig: String(row.artifactSig || ''),
sourceArtifactSig: String(row.sourceArtifactSig || ''),
graphGeneration: String(row.sourceGraphGeneration || ''),
sourceGraphGeneration: String(row.sourceGraphGeneration || ''),
databaseGeneration: String(row.databaseGeneration || ''),
provenanceGeneration: String(row.provenanceGeneration || ''),
modelSig: String(row.modelSig || ''),
configHash: String(row.configHash || ''),
algorithmVersion: String(row.algorithmVersion || ''),
generation: null,
nodeCount: Math.max(0, Number(row.nodeCount) || 0),
edgeCount: Math.max(0, Number(row.edgeCount) || 0),
persisted: true,
resident: false
};
if (
!nativeResult.artifactSig
|| nativeResult.algorithmVersion !== 'memo.native-artifact-v2-binary'
|| nativeResult.modelSig !== this.tagMemoEngine.modelSig
|| nativeResult.configHash !== configHash
|| !/^(?:0|[1-9]\d*)$/.test(nativeResult.databaseGeneration)
) {
return null;
}
const v9Handle = this.tagMemoEngine.publishNativeArtifactHandle(
nativeResult,
effectiveConfig
);
const artifact = this.tagMemoV10Engine.publishNativeArtifactHandle(
nativeResult,
{
effectiveConfig,
publishedAt: Math.max(0, Number(row.publishedAt) || Date.now())
}
);
console.log(
`[KnowledgeBase] ♻️ Native Memo manifest restored without JS payload decode: ` +
`artifact=${artifact.artifactSig}, sourceV9=${v9Handle.artifactSig}, ` +
`nodes=${artifact.nodeCount}, edges=${artifact.edgeCount}.`
);
return artifact;
}
/**
* Rust 已完成构建、持久化与 MemoRuntime Arc 发布后的控制面回调。
* 本方法只发布轻量句柄,禁止编译 JS CSR、解压 payload 或清空原生 runtime。
*/
async onNativeMemoArtifactPublished(nativeResult, v9Handle = null) {
if (!this.tagMemoV10Engine) return null;
const effectiveConfig = this._buildNativeMemoEffectiveConfig();
const artifact = this.tagMemoV10Engine.publishNativeArtifactHandle(
nativeResult,
{ effectiveConfig }
);
console.log(
`[KnowledgeBase] 🌊 Native Memo generation ready: ` +
`artifact=${artifact.artifactSig}, sourceV9=` +
`${v9Handle?.artifactSig || artifact.sourceArtifactSig}, ` +
`nativeGeneration=${artifact.nativeGeneration ?? 'unknown'}.`
);
try {
if (
!this.nativeKnowledgeRuntime
|| typeof this.nativeKnowledgeRuntime.pruneNativeMemoArtifacts
!== 'function'
) {
throw new Error(
'NativeKnowledgeRuntime Memo artifact prune ABI is unavailable'
);
}
const rawPruneResult =
await this.nativeKnowledgeRuntime.pruneNativeMemoArtifacts(
this.dbPath,
2,
7 * 24 * 60 * 60 * 1000
);
const pruneResult = typeof rawPruneResult === 'string'
? JSON.parse(rawPruneResult)
: rawPruneResult;
if (
pruneResult
&& (
Number(pruneResult.retired) > 0
|| Number(pruneResult.deleted) > 0
)
) {
console.log(
`[KnowledgeBase] 🧹 Native Memo lifecycle prune complete: ` +
`retired=${Number(pruneResult.retired) || 0}, ` +
`deleted=${Number(pruneResult.deleted) || 0}.`
);
}
} catch (pruneError) {
console.warn(
'[KnowledgeBase] ⚠️ Native Memo artifact prune warning:',
pruneError.message || pruneError
);
}
return artifact;
}
/**
* 退休兼容入口:旧 JS 图发布不得再触发生产伴生编译。
*/
onTagMemoArtifactPublished(sourceBundle) {
console.warn(
`[KnowledgeBase] Ignored retired JS Memo artifact publication ` +
`${sourceBundle?.artifactSig || 'unknown'}; native rebuild is required.`
);
return null;
}
_isSqliteCorruptionError(error) {
const code = String(error?.code || '').toUpperCase();
const message = String(error?.message || error || '');
return code === 'SQLITE_CORRUPT'
|| code === 'SQLITE_NOTADB'
|| code === 'KNOWLEDGE_STORE_CORRUPT'
|| /database disk image is malformed|file is not a database|database corruption|SQLite quick_check returned|KNOWLEDGE_STORE_CORRUPT/i
.test(message);
}
_isSqliteBusyError(error) {
const code = String(error?.code || '').toUpperCase();
const message = String(error?.message || error || '');
return code === 'SQLITE_BUSY'
|| code.startsWith('SQLITE_BUSY_')
|| code === 'SQLITE_LOCKED'
|| code.startsWith('SQLITE_LOCKED_')
|| code === 'KNOWLEDGE_STORE_BUSY'
|| /database (?:is )?locked|database table is locked|KNOWLEDGE_STORE_BUSY/i
.test(message);
}
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) {
await this.fileWatcher.stop();
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 this.databaseCoordinator.delay(ms);
}
touchActivity() {
this.lastActivityAt = Date.now();
}