@onigeya/dsh-kanabo-memory 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/query-window.js CHANGED
@@ -63,6 +63,7 @@
63
63
  * 是可断言的事实,而不是靠调用方自觉。
64
64
  */
65
65
  import { EMBEDDING_DIM, SOURCE_TYPES } from './contract.js'
66
+ import { activeEmbeddingDim } from './providers.js'
66
67
  import { createTriviumStore } from './store-trivium.js'
67
68
 
68
69
  /** 时间窗覆盖的两种信封类型:场景/片段与字幕/音轨切片。 */
@@ -387,7 +388,7 @@ export function createWindowQuery(options = {}) {
387
388
  store = createTriviumStore({
388
389
  workspace: options.workspace,
389
390
  dir: options.dir,
390
- dim: Number.isInteger(options.dim) && options.dim > 0 ? options.dim : EMBEDDING_DIM,
391
+ dim: Number.isInteger(options.dim) && options.dim > 0 ? options.dim : activeEmbeddingDim(),
391
392
  idleMs: options.idleMs,
392
393
  requestTimeoutMs: options.requestTimeoutMs,
393
394
  })
@@ -540,7 +541,7 @@ export function createWindowQuery(options = {}) {
540
541
  return { ...result, owned: true }
541
542
  },
542
543
  stats() {
543
- return { ...counters, opened, ownsStore, closed, dim: ownsStore ? (options.dim ?? EMBEDDING_DIM) : null }
544
+ return { ...counters, opened, ownsStore, closed, dim: ownsStore ? (options.dim ?? activeEmbeddingDim()) : null }
544
545
  },
545
546
  }
546
547
  }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * 召回融合之后的两级判定:重排(cross-encoder)与 decision 模型(Hindsight 的 ranker 用法)。
3
+ *
4
+ * 为什么分成独立的纯函数:融合(`fuseArms`)是可解释的、确定性的 RRF;这两级是**外部模型**,
5
+ * 会超时、会 401、会返回形状不对的东西。把「网络失败」与「排序数学」分开,才能让探针在没有
6
+ * 网络时断言「失败也保持原顺序」,在有网络时断言「确实改变了顺序」。
7
+ *
8
+ * 顺序与 Hindsight 一致:RRF → rerank(CE) → decision(judge)。Hindsight 在配置了 decision
9
+ * reranker 时会让 CE 的 recency 加成失效(`decision_reranker.py` 顶部注释:order is final),
10
+ * 这里保持同一语义:judge 存在时,它的顺序就是最终顺序,CE 只决定「judge 之前」的顺序。
11
+ */
12
+
13
+ import { keepQuestion, rankAnswers } from './providers.js'
14
+
15
+ function stageError(code, message, detail) {
16
+ const error = new Error(message)
17
+ error.code = code
18
+ if (detail !== undefined) error.details = detail
19
+ return error
20
+ }
21
+
22
+ const idsOf = (list) => list.map((hit) => hit.id)
23
+
24
+ /**
25
+ * 重排:只对前 `maxCandidates` 条问 CE,尾部不动。
26
+ * 最终分 = `weight × ce + (1 - weight) × rrfNorm`,平分时保持原 RRF 顺序(稳定排序)。
27
+ * 失败(无配置/超时/HTTP 错误)一律返回原列表 + `applied:false` 的阶段报告,绝不抛。
28
+ */
29
+ export async function applyRerank(fused, query, options = {}) {
30
+ const client = options.client ?? null
31
+ const base = { provider: 'rerank', model: client?.model ?? null }
32
+ if (client === null || client.enabled !== true) return { list: fused, stage: { ...base, applied: false, reason: 'not-configured' } }
33
+ if (fused.length === 0) return { list: fused, stage: { ...base, applied: false, reason: 'empty' } }
34
+ const max = Math.max(1, Math.min(options.maxCandidates ?? 24, fused.length))
35
+ const weight = Number.isFinite(options.weight) ? Math.max(0, Math.min(1, options.weight)) : 0.6
36
+ const head = fused.slice(0, max)
37
+ const tail = fused.slice(max)
38
+ let result
39
+ try {
40
+ result = await client.score(query, head.map((hit) => (hit.text === '' ? '(empty)' : hit.text)))
41
+ } catch (error) {
42
+ result = { ok: false, ms: 0, error: { code: 'KANABO_RERANK_THREW', message: String(error?.message ?? error) } }
43
+ }
44
+ if (result?.ok !== true) {
45
+ return {
46
+ list: fused,
47
+ stage: { ...base, applied: false, candidates: max, ms: result?.ms ?? 0, degraded: result?.error ?? { code: 'KANABO_RERANK', message: '重排没有结果' } },
48
+ }
49
+ }
50
+ const maxRrf = head.reduce((best, hit) => Math.max(best, Number(hit.rrf) || 0), 0) || 1
51
+ const scored = head.map((hit, index) => {
52
+ const ce = Math.max(0, Math.min(1, Number(result.scores[index]) || 0))
53
+ const rrfNorm = Math.max(0, Math.min(1, (Number(hit.rrf) || 0) / maxRrf))
54
+ const combined = weight * ce + (1 - weight) * rrfNorm
55
+ return { hit, ce, rrfNorm, combined, index }
56
+ })
57
+ scored.sort((left, right) => right.combined - left.combined || left.index - right.index)
58
+ const ranked = scored.map((row) => ({
59
+ ...row.hit,
60
+ score: row.combined,
61
+ why: { ...row.hit.why, rerank: { ce: row.ce, rrfNorm: row.rrfNorm, combined: row.combined, weight } },
62
+ }))
63
+ const list = [...ranked, ...tail]
64
+ const before = idsOf(fused).slice(0, max)
65
+ const after = idsOf(ranked)
66
+ return {
67
+ list,
68
+ stage: {
69
+ ...base,
70
+ applied: true,
71
+ candidates: max,
72
+ ms: result.ms ?? 0,
73
+ weight,
74
+ changed: before.some((id, index) => id !== after[index]),
75
+ top1: after[0] ?? null,
76
+ scores: scored.map((row) => ({ id: row.hit.id, ce: row.ce, combined: row.combined })),
77
+ },
78
+ }
79
+ }
80
+
81
+ /**
82
+ * decision 模型:对前 `maxCandidates` 条逐条问 KEEP 题(一次批量请求),按答案排名并剪除。
83
+ * 分数是名次而不是置信度(与 Hindsight 一致),最佳候选永远保留。
84
+ *
85
+ * `required:true` 时失败即抛 `KANABO_RECALL_JUDGE`——此时它**是** ranker,rank 坏了排序就是假的;
86
+ * 默认 `required:false`,失败只记 `degraded` 并保持上一级顺序。
87
+ */
88
+ export async function applyJudge(list, query, options = {}) {
89
+ const client = options.client ?? null
90
+ const base = { provider: 'decision', model: client?.model ?? null, protocol: client?.protocol ?? null }
91
+ if (client === null || client.enabled !== true) return { list, stage: { ...base, applied: false, reason: 'not-configured' } }
92
+ if (list.length === 0) return { list, stage: { ...base, applied: false, reason: 'empty' } }
93
+ const max = Math.max(1, Math.min(options.maxCandidates ?? 12, list.length))
94
+ const head = list.slice(0, max)
95
+ const tail = list.slice(max)
96
+ const questions = head.map((hit, index) => ({ ...keepQuestion(index, hit.text === '' ? '(empty)' : hit.text), type: 'noul' }))
97
+ let result
98
+ try {
99
+ result = await client.judge(options.state ?? `Question: ${String(query ?? '')}`, questions)
100
+ } catch (error) {
101
+ result = { ok: false, ms: 0, error: { code: 'KANABO_DECISION_THREW', message: String(error?.message ?? error) } }
102
+ }
103
+ if (result?.ok !== true) {
104
+ if (options.required === true) {
105
+ throw stageError(
106
+ 'KANABO_RECALL_JUDGE',
107
+ `decision 模型被配置为必需(required),但这次判定失败:${result?.error?.message ?? '未知错误'}`,
108
+ { model: client?.model ?? null, error: result?.error ?? null })
109
+ }
110
+ return {
111
+ list,
112
+ stage: { ...base, applied: false, candidates: max, ms: result?.ms ?? 0, degraded: result?.error ?? { code: 'KANABO_DECISION', message: '判定没有结果' } },
113
+ }
114
+ }
115
+ const keys = questions.map((question) => question.key)
116
+ const rank = rankAnswers(result.probabilities, keys, {
117
+ minProbability: options.minProbability,
118
+ keepBest: options.keepBest,
119
+ })
120
+ const judged = rank.kept.map((index) => ({
121
+ ...head[index],
122
+ why: {
123
+ ...head[index].why,
124
+ judge: {
125
+ probability: result.probabilities?.[keys[index]] ?? 0,
126
+ position: rank.scores[index],
127
+ },
128
+ },
129
+ }))
130
+ const finalList = [...judged, ...tail]
131
+ const before = idsOf(list).slice(0, max)
132
+ const after = idsOf(judged)
133
+ return {
134
+ list: finalList,
135
+ stage: {
136
+ ...base,
137
+ applied: true,
138
+ candidates: max,
139
+ ms: result.ms ?? 0,
140
+ floor: rank.floor,
141
+ best: rank.best,
142
+ kept: judged.length,
143
+ pruned: rank.dropped.length,
144
+ changed: before.length !== after.length || before.some((id, index) => id !== after[index]),
145
+ probabilities: keys.map((key) => ({ id: head[keys.indexOf(key)]?.id ?? null, probability: result.probabilities?.[key] ?? null })),
146
+ },
147
+ }
148
+ }
149
+
150
+ export default applyRerank
package/recall-trivium.js CHANGED
@@ -10,7 +10,8 @@
10
10
  * 半衰期是显式参数(默认 30 天),乘法作用在融合分上。
11
11
  *
12
12
  * 三个必须守住的契约:
13
- * 1. **向量宽度 = `EMBEDDING_DIM`(384)**。`store-trivium.js` 的 `DEFAULT_DIM` 是 1536 的占位,
13
+ * 1. **向量宽度 = 当前 profile 的维度**(未配置 API 时为契约值 `EMBEDDING_DIM` = 384,配置 bge-m3 时为 1024)。
14
+ * `store-trivium.js` 的 `DEFAULT_DIM` 是 1536 的占位,
14
15
  * 调用方必须显式传 384;本模块在构造时断言(`stats().dim`)与 `embedder.dim` 都等于 384,不符即
15
16
  * `KANABO_RECALL_DIMENSION`,绝不 pad/截断。
16
17
  * 2. **查询用 `query: ` 前缀、入库文本用 `passage: ` 前缀**(e5 的训练口径)。本模块只负责查询侧;
@@ -26,6 +27,8 @@
26
27
  * 引擎不支持 `a.id IN [...]`(实测 `TDB_QUERY_PARSE`),所以这里拼 OR 串并对前沿设上限。
27
28
  */
28
29
  import { EDGE_LABELS, EMBEDDING_DIM } from './contract.js'
30
+ import { activeEmbeddingDim, activeEmbeddingPrefixes, judgeState } from './providers.js'
31
+ import { applyJudge, applyRerank } from './recall-stages.js'
29
32
  import { createTriviumStore } from './store-trivium.js'
30
33
 
31
34
  /** 三臂名字:关掉其中任意两个必须改变结果集,这是验收 (a)。 */
@@ -188,11 +191,11 @@ async function vectorArm(store, query, limit, embedder, options) {
188
191
  return { hits: [], degraded: embedded?.reason ?? DEGRADED.VECTOR_UNAVAILABLE }
189
192
  }
190
193
  const vector = Array.from(embedded.vector)
191
- if (vector.length !== EMBEDDING_DIM) {
194
+ if (vector.length !== options.dim) {
192
195
  throw recallError(
193
196
  'KANABO_RECALL_DIMENSION',
194
- `查询向量是 ${vector.length} 维,契约 EMBEDDING_DIM 是 ${EMBEDDING_DIM};拒绝查询。`,
195
- { details: { expected: EMBEDDING_DIM, received: vector.length } })
197
+ `查询向量是 ${vector.length} 维,当前 profile 是 ${options.dim} 维;拒绝查询。`,
198
+ { details: { expected: options.dim, received: vector.length } })
196
199
  }
197
200
  const top = Math.max(1, Math.min(200, Math.floor(limit)))
198
201
  const result = await store.search({
@@ -493,6 +496,23 @@ export function packByBudget(hits, budgetChars = DEFAULT_BUDGET_CHARS) {
493
496
  }
494
497
 
495
498
  /** 一次召回要用的配置:默认值 + 调用方覆盖,并在构造时把不合法值夹到安全范围。 */
499
+ let DEFAULTS_RESOLVED = null
500
+ function defaultDim() {
501
+ try {
502
+ return activeEmbeddingDim()
503
+ } catch {
504
+ return EMBEDDING_DIM
505
+ }
506
+ }
507
+
508
+ function defaultQueryPrefix() {
509
+ try {
510
+ return activeEmbeddingPrefixes().query
511
+ } catch {
512
+ return QUERY_PREFIX
513
+ }
514
+ }
515
+
496
516
  function normalizeOptions(input = {}) {
497
517
  const graphInput = { ...DEFAULT_GRAPH, ...(input.graph ?? {}) }
498
518
  return {
@@ -504,7 +524,16 @@ function normalizeOptions(input = {}) {
504
524
  weights: { ...DEFAULT_WEIGHTS, ...(input.weights ?? {}) },
505
525
  halfLifeMs: Number.isFinite(input.halfLifeMs) && input.halfLifeMs > 0 ? input.halfLifeMs : DEFAULT_HALF_LIFE_MS,
506
526
  timeoutMs: Number.isFinite(input.timeoutMs) && input.timeoutMs > 0 ? input.timeoutMs : DEFAULT_TIMEOUT_MS,
507
- queryPrefix: typeof input.queryPrefix === 'string' ? input.queryPrefix : QUERY_PREFIX,
527
+ queryPrefix: typeof input.queryPrefix === 'string' ? input.queryPrefix : defaultQueryPrefix(),
528
+ dim: clampInt(input.dim, defaultDim(), 1, 16384),
529
+ reranker: input.reranker ?? null,
530
+ judge: input.judge ?? null,
531
+ rerankMaxCandidates: clampInt(input.rerank?.maxCandidates ?? input.reranker?.maxCandidates, 24, 1, 200),
532
+ rerankWeight: Number.isFinite(input.rerank?.weight) ? Math.max(0, Math.min(1, input.rerank.weight)) : 0.6,
533
+ judgeMaxCandidates: clampInt(input.judgeOptions?.maxCandidates ?? input.judge?.maxCandidates, 12, 1, 200),
534
+ judgeMinProbability: Number.isFinite(input.judgeOptions?.minProbability) ? input.judgeOptions.minProbability : 0.2,
535
+ judgeKeepBest: input.judgeOptions?.keepBest !== false,
536
+ judgeRequired: input.judgeOptions?.required === true,
508
537
  minVectorScore: Number.isFinite(input.minVectorScore) ? input.minVectorScore : 0,
509
538
  exact: input.exact === true,
510
539
  includeArmHits: input.includeArmHits === true,
@@ -545,22 +574,16 @@ function clampInt(value, fallback, min, max) {
545
574
  * @param {string} [options.dir] 库目录(默认 `triviumDir()`,落在临时目录,绝不进仓库)。
546
575
  * @param {object} [options.embedder] `embed.js` 的 `createEmbedder()`;缺省则向量臂恒为降级。
547
576
  * @param {object} [options.arms] `{ text, vector, graph }` 三个布尔开关。
548
- * @param {number} [options.dim] 期望的向量维度;只允许 `EMBEDDING_DIM`(384)。
577
+ * @param {number} [options.dim] 期望的向量维度;默认取当前 profile(本地 384 / API 模型自己的宽度)。
549
578
  */
550
579
  export function createTriviumRecall(options = {}) {
551
- const dim = options.dim ?? EMBEDDING_DIM
552
- if (dim !== EMBEDDING_DIM) {
553
- throw recallError(
554
- 'KANABO_RECALL_DIMENSION',
555
- `recall-trivium 只支持契约维度 ${EMBEDDING_DIM},收到 ${dim};换维度必须走迁移并升 CONTRACT_VERSION。`,
556
- { details: { expected: EMBEDDING_DIM, received: dim } })
557
- }
580
+ const dim = options.dim ?? defaultDim()
558
581
  const embedder = options.embedder ?? null
559
- if (embedder !== null && embedder.dim !== undefined && embedder.dim !== EMBEDDING_DIM) {
582
+ if (embedder !== null && embedder.dim !== undefined && embedder.dim !== dim) {
560
583
  throw recallError(
561
584
  'KANABO_RECALL_DIMENSION',
562
- `embedder 维度 ${embedder.dim} 与契约 ${EMBEDDING_DIM} 不符。`,
563
- { details: { expected: EMBEDDING_DIM, received: embedder.dim } })
585
+ `embedder 维度 ${embedder.dim} 与当前 profile 的 ${dim} 维不符。`,
586
+ { details: { expected: dim, received: embedder.dim } })
564
587
  }
565
588
 
566
589
  const ownsStore = options.store === undefined || options.store === null
@@ -577,7 +600,7 @@ export function createTriviumRecall(options = {}) {
577
600
  store = createTriviumStore({
578
601
  workspace: options.workspace,
579
602
  dir: options.dir,
580
- dim: EMBEDDING_DIM,
603
+ dim,
581
604
  idleMs: options.idleMs,
582
605
  requestTimeoutMs: options.requestTimeoutMs,
583
606
  })
@@ -588,12 +611,12 @@ export function createTriviumRecall(options = {}) {
588
611
  /** 维度断言放在真正用到库之前:门面的 `stats().dim` 不需要拉起子进程就能读。 */
589
612
  function assertStoreDim(handle) {
590
613
  const actual = typeof handle?.stats === 'function' ? handle.stats().dim : undefined
591
- if (actual !== undefined && actual !== EMBEDDING_DIM) {
614
+ if (actual !== undefined && actual !== dim) {
592
615
  throw recallError(
593
616
  'KANABO_RECALL_DIMENSION',
594
- `TriviumDB 库的向量维度是 ${actual},契约要求 ${EMBEDDING_DIM};`
595
- + 'store-trivium.js 的 DEFAULT_DIM 是 1536 占位,调用方必须显式传 384。',
596
- { details: { expected: EMBEDDING_DIM, received: actual } })
617
+ `TriviumDB 库的向量维度是 ${actual},当前 profile 要求 ${dim};`
618
+ + '换向量模型必须换 profile(库文件名带模型后缀),不能拿旧库硬开。',
619
+ { details: { expected: dim, received: actual } })
597
620
  }
598
621
  }
599
622
 
@@ -658,7 +681,7 @@ export function createTriviumRecall(options = {}) {
658
681
  const config = normalizeOptions({ ...options, ...callOptions })
659
682
  const handle = await open()
660
683
  const armsEnabled = config.arms
661
- const timings = { text: 0, vector: 0, graph: 0, fusion: 0, pack: 0 }
684
+ const timings = { text: 0, vector: 0, graph: 0, fusion: 0, rerank: 0, judge: 0, pack: 0 }
662
685
  const armSummary = {}
663
686
  const armHits = {}
664
687
  const meta = new Map()
@@ -779,7 +802,26 @@ export function createTriviumRecall(options = {}) {
779
802
  }
780
803
  }
781
804
 
782
- const ranked = fused.slice(0, config.limit).map((hit) => ({ ...hit, chars: charCost(hit.text) }))
805
+ const rerankAt = performance.now()
806
+ const reranked = await applyRerank(fused, query, {
807
+ client: config.reranker,
808
+ maxCandidates: config.rerankMaxCandidates,
809
+ weight: config.rerankWeight,
810
+ })
811
+ timings.rerank = roundMs(performance.now() - rerankAt)
812
+ const judgeAt = performance.now()
813
+ const judged = await applyJudge(reranked.list, query, {
814
+ client: config.judge,
815
+ maxCandidates: config.judgeMaxCandidates,
816
+ minProbability: config.judgeMinProbability,
817
+ keepBest: config.judgeKeepBest,
818
+ required: config.judgeRequired === true,
819
+ state: judgeState(query),
820
+ })
821
+ timings.judge = roundMs(performance.now() - judgeAt)
822
+ const ordered = judged.list
823
+
824
+ const ranked = ordered.slice(0, config.limit).map((hit) => ({ ...hit, chars: charCost(hit.text) }))
783
825
  if (config.includeArmHits) {
784
826
  for (const name of ARM_NAMES) {
785
827
  const arm = armHits[name]
@@ -810,6 +852,7 @@ export function createTriviumRecall(options = {}) {
810
852
  ranked: ranked.length,
811
853
  candidates: fused.length,
812
854
  arms: armSummary,
855
+ stages: { rerank: reranked.stage, judge: judged.stage },
813
856
  timings: { ...timings, total: roundMs(performance.now() - started) },
814
857
  }
815
858
  }
@@ -842,7 +885,7 @@ export function createTriviumRecall(options = {}) {
842
885
  return { ...result, owned: true }
843
886
  },
844
887
  stats() {
845
- return { ...counters, opened, ownsStore, dim: EMBEDDING_DIM }
888
+ return { ...counters, opened, ownsStore, dim }
846
889
  },
847
890
  }
848
891
  }
package/recall.js CHANGED
@@ -77,7 +77,7 @@ function describe(error) {
77
77
  * @param {string} [options.prompt] 用户提示词
78
78
  * @param {number} [options.limit] 最多召回条数(默认 8,夹到 1..MAX_INJECT_BYTES 量级)
79
79
  * @param {object} [options.runtime] 自足探针注入的运行时
80
- * @returns {Promise<{text: string, entries: number, source: 'trivium', degraded: object|null}>}
80
+ * @returns {Promise<{text: string, entries: number, source: 'trivium', degraded: object|null, stages?: object}>}
81
81
  */
82
82
  export async function getRecallContext(options = {}) {
83
83
  const runtime = options.runtime ?? defaultRuntime
@@ -93,18 +93,34 @@ export async function getRecallContext(options = {}) {
93
93
  }
94
94
  try {
95
95
  const { createTriviumRecall } = await import('./recall-trivium.js')
96
+ const { createModelClients, activeEmbeddingPrefixes } = await import('./providers.js')
97
+ const clients = createModelClients()
98
+ const embedder = clients.embeddings === null ? null : runtime.createServiceEmbedder()
96
99
  const hits = await runtime.withFacade(scope, async (facade) => {
97
- const recall = createTriviumRecall({ store: facade, arms: { text: true, vector: false, graph: true } })
100
+ const recall = createTriviumRecall({
101
+ store: facade,
102
+ arms: { text: true, vector: embedder !== null, graph: true },
103
+ embedder,
104
+ queryPrefix: activeEmbeddingPrefixes().query,
105
+ reranker: clients.rerank,
106
+ judge: clients.decision,
107
+ judgeOptions: {
108
+ maxCandidates: clients.config.decision?.maxCandidates,
109
+ minProbability: clients.config.decision?.minProbability,
110
+ keepBest: clients.config.decision?.keepBest,
111
+ required: clients.config.decision?.required,
112
+ },
113
+ })
98
114
  try {
99
115
  const result = await recall.recall(prompt, { limit, budgetChars: Number.MAX_SAFE_INTEGER })
100
- return result.hits.map((hit) => ({ text: hit.text, id: hit.id, ts: hit.ts }))
116
+ return { hits: result.hits.map((hit) => ({ text: hit.text, id: hit.id, ts: hit.ts })), stages: result.stages }
101
117
  } finally {
102
118
  await recall.close()
103
119
  }
104
120
  })
105
- const usable = hits.filter((hit) => typeof hit.text === 'string' && hit.text.trim() !== '')
106
- if (usable.length === 0) return empty()
107
- return { text: blockFor(usable), entries: usable.length, source: 'trivium', degraded: null }
121
+ const usable = hits.hits.filter((hit) => typeof hit.text === 'string' && hit.text.trim() !== '')
122
+ if (usable.length === 0) return { ...empty(), stages: hits.stages }
123
+ return { text: blockFor(usable), entries: usable.length, source: 'trivium', degraded: null, stages: hits.stages }
108
124
  } catch (error) {
109
125
  return empty({ code: typeof error?.code === 'string' ? error.code : 'KANABO_RECALL_PROVIDER', message: describe(error) })
110
126
  }
package/remove-legacy.mjs CHANGED
@@ -137,7 +137,7 @@ function e2eSignal({ repoRoot, timeoutMs, fast, workDir }) {
137
137
  return { name: 'e2e', ok: probe.ok, observable: probe.observable }
138
138
  }
139
139
 
140
- /** 41:真实跑回归矩阵,要求 14 行全绿且末尾 `RESULT: PASS`。 */
140
+ /** 41:真实跑回归矩阵,要求全行变绿且末尾 `RESULT: PASS`。 */
141
141
  function regressionSignal({ repoRoot, timeoutMs, workDir }) {
142
142
  const script = join(repoRoot, 'scripts', 'regression-matrix.mjs')
143
143
  if (!existsSync(script)) return { name: 'regression', ok: false, observable: `missing ${script}` }
@@ -354,7 +354,7 @@ export async function compareLegacyAgainstTrivium({ docs, triviumDir }) {
354
354
  cpSync(triviumDir, copy, { recursive: true })
355
355
  }
356
356
  const { createTriviumStore } = await import('./store-trivium.js')
357
- store = createTriviumStore({ workspace: scope, dir: copy ?? triviumDir, dim: EMBEDDING_DIM, idleMs: 1000 })
357
+ store = createTriviumStore({ workspace: scope, dir: copy ?? triviumDir, dim: EMBEDDING_DIM, suffix: '', idleMs: 1000 })
358
358
  const opened = await store.open({}, { timeoutMs: 20_000 })
359
359
  nodeCount = opened?.nodeCount ?? null
360
360
  const query = `FIND {kind: "kanabo-envelope", workspace: ${JSON.stringify(scope)}} RETURN *`
@@ -598,7 +598,7 @@ export async function openTrivium({ triviumDir, scope }) {
598
598
  copy = mkdtempSync(join(tmpdir(), 'kanabo-trivium-open-'))
599
599
  cpSync(triviumDir, copy, { recursive: true })
600
600
  const { createTriviumStore } = await import('./store-trivium.js')
601
- store = createTriviumStore({ workspace: scope, dir: copy, dim: 384, idleMs: 1000 })
601
+ store = createTriviumStore({ workspace: scope, dir: copy, dim: 384, suffix: '', idleMs: 1000 })
602
602
  const opened = await store.open({}, { timeoutMs: 20_000 })
603
603
  return {
604
604
  ok: true,
@@ -0,0 +1,124 @@
1
+ /**
2
+ * 保留期清扫:把 `egress.expireBefore` 从「模块能力」接到插件入口上。
3
+ *
4
+ * 启动后延迟跑一次,之后按间隔节流重跑。每个 workspace 都走**同一个进程级注册表**的门面
5
+ * (`runtime.withFacade`):TriviumDB 是文件级独占租约,另开句柄会与正在服务的门面撞
6
+ * `TDB_DATABASE_LOCKED`,所以这里绝不自己 open 库;workspace 名单来自写入路径维护的索引。
7
+ * 删除走与按来源删除**同一条**不可恢复路径。任何失败只记一行日志,绝不让插件或回合失败。
8
+ *
9
+ * 开关:`KANABO_MEMORY_EGRESS_SWEEP=0` 完全关闭;`KANABO_MEMORY_EGRESS_SWEEP_INTERVAL_MS`
10
+ * 覆盖间隔(默认 6 小时);`KANABO_MEMORY_EGRESS_SWEEP_DELAY_MS` 覆盖启动延迟(默认 2 秒,
11
+ * 验收设为 0)。审计默认写到库目录旁的 `egress-audit.jsonl`,可用
12
+ * `KANABO_MEMORY_EGRESS_AUDIT` 覆盖。
13
+ */
14
+ import { existsSync } from 'node:fs'
15
+ import { join } from 'node:path'
16
+
17
+ import { AUDIT_ENV, expireBefore } from './egress.js'
18
+ import * as defaultRuntime from './trivium-runtime.js'
19
+ import { triviumDir } from './store-trivium.js'
20
+
21
+ export const SWEEP_ENV = 'KANABO_MEMORY_EGRESS_SWEEP'
22
+ export const INTERVAL_ENV = 'KANABO_MEMORY_EGRESS_SWEEP_INTERVAL_MS'
23
+ export const DELAY_ENV = 'KANABO_MEMORY_EGRESS_SWEEP_DELAY_MS'
24
+ export const DEFAULT_INTERVAL_MS = 6 * 60 * 60 * 1000
25
+ export const DEFAULT_STARTUP_DELAY_MS = 2_000
26
+
27
+ function positiveInterval(value, fallback) {
28
+ const number = Number(value)
29
+ return Number.isInteger(number) && number > 0 ? number : fallback
30
+ }
31
+
32
+ /**
33
+ * 跑一轮清扫:对每个已知 workspace 调一次 `expireBefore`。
34
+ * @returns {Promise<{swept:number, deleted:number, errors:Array<{scope:string,code:string,message:string}>}>}
35
+ */
36
+ export async function sweepExpired({ runtime = defaultRuntime, dir = triviumDir(), log = () => {}, now = Date.now(), auditPath } = {}) {
37
+ const errors = []
38
+ let swept = 0
39
+ let deleted = 0
40
+ for (const scope of runtime.knownWorkspaces({ dir })) {
41
+ try {
42
+ // 索引可能残留已删除的库;不先确认文件存在,withFacade 会把空库重建出来。
43
+ if (!existsSync(runtime.dbPathOf(scope, { dir }))) continue
44
+ const entry = await runtime.withFacade(scope, async (facade) => await expireBefore({ facade, now, auditPath }))
45
+ swept += 1
46
+ deleted += Number(entry?.deleted?.removed ?? 0)
47
+ } catch (error) {
48
+ errors.push({ scope, code: typeof error?.code === 'string' ? error.code : 'EGRESS_SWEEP', message: String(error?.message ?? error) })
49
+ }
50
+ }
51
+ for (const error of errors) log(`egress sweep: ${error.scope} failed (${error.code}): ${error.message}`)
52
+ return { swept, deleted, errors }
53
+ }
54
+
55
+ /**
56
+ * 插件入口:启动一次(延迟、unref)+节流周期;返回 `{sweep, stop}` 供探针/宿主控制。
57
+ * `deps.enabled` / `deps.intervalMs` / `deps.startupDelayMs` / `deps.auditPath` / `deps.dir` 供验收注入。
58
+ */
59
+ export function registerEgress(ctx, deps = {}) {
60
+ const log = typeof deps?.log === 'function' ? deps.log : () => {}
61
+ const runtime = deps?.runtime ?? defaultRuntime
62
+ const dir = deps?.dir ?? triviumDir()
63
+ const auditPath = typeof deps?.auditPath === 'string'
64
+ ? deps.auditPath
65
+ : (process.env[AUDIT_ENV] ?? join(dir, 'egress-audit.jsonl'))
66
+ if (deps.enabled !== true && process.env[SWEEP_ENV] === '0') {
67
+ log('egress sweep: disabled by KANABO_MEMORY_EGRESS_SWEEP=0')
68
+ return { sweep: async () => ({ swept: 0, deleted: 0, errors: [], skipped: 'disabled' }), stop: () => {} }
69
+ }
70
+ const intervalMs = positiveInterval(deps.intervalMs ?? process.env[INTERVAL_ENV], DEFAULT_INTERVAL_MS)
71
+ const startupDelayMs = Number.isFinite(deps.startupDelayMs) && deps.startupDelayMs >= 0
72
+ ? deps.startupDelayMs
73
+ : positiveInterval(process.env[DELAY_ENV], DEFAULT_STARTUP_DELAY_MS)
74
+ let stopped = false
75
+ let timer = null
76
+ let firstTimer = null
77
+
78
+ const run = async (kind) => {
79
+ if (stopped) return { swept: 0, deleted: 0, errors: [], skipped: 'stopped' }
80
+ try {
81
+ const result = await sweepExpired({ runtime, dir, log, auditPath })
82
+ if (result.swept > 0 || result.deleted > 0) {
83
+ log(`egress sweep (${kind}): workspaces=${result.swept} deleted=${result.deleted} errors=${result.errors.length}`)
84
+ }
85
+ return result
86
+ } catch (error) {
87
+ log(`egress sweep (${kind}) failed: ${error?.message ?? String(error)}; the turn continues`)
88
+ return { swept: 0, deleted: 0, errors: [{ scope: '*', code: 'EGRESS_SWEEP', message: String(error?.message ?? error) }] }
89
+ }
90
+ }
91
+
92
+ const arm = () => {
93
+ timer = setInterval(() => {
94
+ void run('periodic')
95
+ }, intervalMs)
96
+ timer.unref?.()
97
+ }
98
+
99
+ firstTimer = setTimeout(() => {
100
+ firstTimer = null
101
+ void run('startup')
102
+ if (!stopped) arm()
103
+ }, startupDelayMs)
104
+ firstTimer.unref?.()
105
+
106
+ const stop = () => {
107
+ stopped = true
108
+ if (timer !== null) clearInterval(timer)
109
+ if (firstTimer !== null) clearTimeout(firstTimer)
110
+ timer = null
111
+ firstTimer = null
112
+ }
113
+
114
+ try {
115
+ if (typeof ctx?.effect === 'function') ctx.effect(() => stop)
116
+ else if (typeof ctx?.on === 'function') ctx.on('dispose', stop)
117
+ } catch (error) {
118
+ log(`egress sweep: cannot register cleanup (${error?.message ?? String(error)})`)
119
+ }
120
+
121
+ return { sweep: () => run('manual'), stop, intervalMs, startupDelayMs }
122
+ }
123
+
124
+ export default registerEgress
package/store-trivium.js CHANGED
@@ -87,6 +87,8 @@ function fileNameFor(workspace) {
87
87
  return name === '' || /^[.]+$/.test(name) ? 'workspace' : name
88
88
  }
89
89
 
90
+ import { activeProfile, profileSuffix } from './providers.js'
91
+
90
92
  /** 工作区分域键 → 绝对库路径(`.tdb` 主文件;`.wal/.idx/.vec/.pld/.lock` 由引擎同目录生成)。 */
91
93
  export function dbPathFor(workspace, options = {}) {
92
94
  if (typeof workspace !== 'string' || workspace.length === 0) {
@@ -94,7 +96,8 @@ export function dbPathFor(workspace, options = {}) {
94
96
  }
95
97
  const dir = resolve(options.dir ?? triviumDir())
96
98
  assertOutsideRepo(dir)
97
- const file = resolve(dir, `${fileNameFor(workspace)}.tdb`)
99
+ const suffix = typeof options.suffix === 'string' ? options.suffix : profileSuffix(activeProfile())
100
+ const file = resolve(dir, `${fileNameFor(workspace)}${suffix}.tdb`)
98
101
  if (dirname(file) !== dir) throw triviumError('KANABO_TRIVIUM_PATH', `库路径越界:${file}`)
99
102
  return file
100
103
  }
@@ -130,7 +133,7 @@ export function createTriviumStore(options = {}) {
130
133
  ? options.requestTimeoutMs
131
134
  : DEFAULT_REQUEST_TIMEOUT_MS
132
135
  const syncMode = SYNC_MODES.has(options.syncMode) ? options.syncMode : 'normal'
133
- const path = options.path ?? dbPathFor(workspace, { dir: options.dir })
136
+ const path = options.path ?? dbPathFor(workspace, { dir: options.dir, suffix: options.suffix })
134
137
 
135
138
  let child = null
136
139
  let retiring = null