@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/tools.js CHANGED
@@ -38,8 +38,8 @@ function toolError(code, message) {
38
38
  */
39
39
  async function embedSafely(runtime, text) {
40
40
  try {
41
- const { PASSAGE_PREFIX } = await import('./recall-trivium.js')
42
- const result = await runtime.embedTexts([text], { prefix: PASSAGE_PREFIX })
41
+ const { activeEmbeddingPrefixes } = await import('./providers.js')
42
+ const result = await runtime.embedTexts([text], { prefix: activeEmbeddingPrefixes().passage })
43
43
  const vector = result.vectors?.[0] ?? null
44
44
  if (vector === null) return { vector: null, reason: result.reason ?? 'vector_unavailable', ms: result.ms }
45
45
  return { vector, reason: null, ms: result.ms }
@@ -174,6 +174,52 @@ function attachPersona(envelope, rawPersona, log) {
174
174
  }
175
175
  }
176
176
 
177
+ /**
178
+ * `remember` 的写入前去重(Hindsight consolidation 的 `restates` 分支):近邻 + 判定模型都说
179
+ * 「与既有条目同一件事」就返回既有 id、不写新节点。未配置判定模型、类为未建库、任何调用失败
180
+ * 都返回 null,调用方照原样写入——去重是优化,不是写入的前置条件。
181
+ */
182
+ /**
183
+ * remember 的写入前去重(Hindsight consolidation 的 restates 分支):近邻 + 判定模型都说
184
+ * 「与既有条目同一件事」就返回既有 id、不写新节点。未配置判定模型、任何调用失败都返回 null,
185
+ * 调用方照原样写入——去重是优化,不是写入的前置条件。
186
+ */
187
+ /**
188
+ * remember 的写入前去重(Hindsight consolidation 的 restates 分支):近邻 + 判定模型都判
189
+ * 「与既有条目同一件事」就返回既有 id、不写新节点。未配置判定模型或任何调用失败都返回 null,
190
+ * 调用方照原样写入——去重是优化,不是写入的前置条件。
191
+ */
192
+ async function findDuplicate({ runtime, scope, vector, text, log }) {
193
+ if (vector === null || vector === undefined) return null
194
+ try {
195
+ const { createModelClients } = await import('./providers.js')
196
+ const { findRestatingMemory } = await import('./dedupe.js')
197
+ const clients = createModelClients()
198
+ const judge = clients.decision
199
+ if (judge === null || judge.enabled !== true) return null
200
+ if (clients.config.decision?.dedupe === false) return null
201
+ const found = await findRestatingMemory({
202
+ judge,
203
+ vector,
204
+ text,
205
+ minScore: clients.config.decision?.dedupeMinScore,
206
+ threshold: clients.config.decision?.dedupeThreshold,
207
+ search: (queryVector, options) => runtime.withFacade(scope, (facade) => facade.search({
208
+ vector: queryVector,
209
+ topK: options.topK,
210
+ expandDepth: 0,
211
+ minScore: options.minScore,
212
+ })),
213
+ })
214
+ if (found === null) return null
215
+ log(`remember: 与既有条目 ${found.id} 重复(p=${found.probability.toFixed(3)}),未新增节点`)
216
+ return found
217
+ } catch (error) {
218
+ log(`remember: 去重判定降级(${error?.code ?? 'error'}: ${error?.message ?? String(error)});照常写入`)
219
+ return null
220
+ }
221
+ }
222
+
177
223
  export function registerTools(ctx, deps) {
178
224
  if (ctx?.tools === undefined || typeof ctx.tools.register !== 'function') {
179
225
  throw toolError(
@@ -182,6 +228,7 @@ export function registerTools(ctx, deps) {
182
228
  }
183
229
  const runtime = deps?.runtime ?? defaultRuntime
184
230
  const log = typeof deps?.log === 'function' ? deps.log : () => {}
231
+ const recallStagesLogged = new Set()
185
232
 
186
233
  const remember = {
187
234
  name: 'remember',
@@ -218,12 +265,15 @@ export function registerTools(ctx, deps) {
218
265
  bytes: { type: 'integer', description: 'text 的 UTF-8 字节数' },
219
266
  totalEntries: { type: 'integer', description: '该 workspace 存储中的总条目数' },
220
267
  storePath: { type: 'string', description: '存储文件路径;降级到内存镜像时以 memory: 开头' },
268
+ duplicate: { type: 'boolean', description: '本次是否为重复条目:为 true 时 id 是既有条目的 id,没有新写入' },
221
269
  },
222
270
  },
223
271
  render(_args, value) {
224
272
  return [{
225
273
  type: 'text',
226
- text: `已记住 ${value.bytes} 字节(topic=${value.topic || '无'},当前共 ${value.totalEntries} 条)→ ${value.storePath}`,
274
+ text: value.duplicate === true
275
+ ? `与既有记忆重复,未新增(id=${value.id},当前共 ${value.totalEntries} 条)→ ${value.storePath}`
276
+ : `已记住 ${value.bytes} 字节(topic=${value.topic || '无'},当前共 ${value.totalEntries} 条)→ ${value.storePath}`,
227
277
  }]
228
278
  },
229
279
  },
@@ -254,13 +304,22 @@ export function registerTools(ctx, deps) {
254
304
  }
255
305
  const written = await runtime.withLock(scope, async () => {
256
306
  const scan = await runtime.scanWorkspace(scope)
307
+ const duplicate = await findDuplicate({ runtime, scope, vector: embedded.vector, text, log })
308
+ if (duplicate !== null) return { total: scan.count, duplicate }
257
309
  runtime.assertQuota({ count: scan.count, bytes: scan.bytes }, { entries: 1, bytes })
258
310
  await runtime.appendEnvelopes(scope, [envelope], {
259
311
  vectors: embedded.vector === null ? undefined : [embedded.vector],
260
312
  })
261
- return { total: scan.count + 1 }
313
+ return { total: scan.count + 1, duplicate: null }
262
314
  })
263
- return { id: envelope.id, topic, bytes, totalEntries: written.total, storePath: runtime.dbPathOf(scope) }
315
+ return {
316
+ id: written.duplicate === null ? envelope.id : written.duplicate.id,
317
+ topic,
318
+ bytes,
319
+ totalEntries: written.total,
320
+ storePath: runtime.dbPathOf(scope),
321
+ ...(written.duplicate === null ? {} : { duplicate: true }),
322
+ }
264
323
  },
265
324
  }
266
325
 
@@ -309,10 +368,35 @@ export function registerTools(ctx, deps) {
309
368
  return { entries, total: scan.count, truncated: scan.count > entries.length }
310
369
  }
311
370
  const { createTriviumRecall } = await import('./recall-trivium.js')
371
+ const { createModelClients } = await import('./providers.js')
372
+ const clients = createModelClients()
373
+ const decision = clients.config.decision
312
374
  const runRecall = async (arms, embedder, timeoutMs = RECALL_TIMEOUT_MS) => runtime.withFacade(scope, async (facade) => {
313
- const recall = createTriviumRecall({ store: facade, arms, embedder, timeoutMs })
375
+ const recall = createTriviumRecall({
376
+ store: facade,
377
+ arms,
378
+ embedder,
379
+ timeoutMs,
380
+ reranker: clients.rerank,
381
+ judge: clients.decision,
382
+ judgeOptions: {
383
+ maxCandidates: decision?.maxCandidates,
384
+ minProbability: decision?.minProbability,
385
+ keepBest: decision?.keepBest,
386
+ required: decision?.required,
387
+ },
388
+ })
314
389
  try {
315
- return await recall.recall(query, { limit, budgetChars: Number.MAX_SAFE_INTEGER })
390
+ const result = await recall.recall(query, { limit, budgetChars: Number.MAX_SAFE_INTEGER })
391
+ const rerankOn = result.stages?.rerank?.applied === true
392
+ const judgeOn = result.stages?.judge?.applied === true
393
+ const signature = 'rerank=' + String(rerankOn) + ' judge=' + String(judgeOn)
394
+ if (!recallStagesLogged.has(signature)) {
395
+ recallStagesLogged.add(signature)
396
+ log('recall: stages ' + signature + '(rerank=' + (clients.config.rerank?.model ?? 'off')
397
+ + ' judge=' + (clients.config.decision?.model ?? 'off') + ')')
398
+ }
399
+ return result
316
400
  } finally {
317
401
  await recall.close()
318
402
  }
@@ -37,6 +37,7 @@
37
37
  import { spawn } from 'node:child_process'
38
38
  import { createHash } from 'node:crypto'
39
39
  import {
40
+ appendFileSync,
40
41
  existsSync,
41
42
  mkdirSync,
42
43
  readFileSync,
@@ -51,6 +52,7 @@ import { realpathSync } from 'node:fs'
51
52
  import { fileURLToPath } from 'node:url'
52
53
 
53
54
  import { EMBEDDING_DIM } from './contract.js'
55
+ import { activeEmbeddingDim, activeEmbeddingPrefixes, embeddingTransport } from './providers.js'
54
56
  import { MAX_ENTRY_BYTES, scopeOf } from './store.js'
55
57
  import { createTriviumStore, dbPathFor, triviumDir } from './store-trivium.js'
56
58
 
@@ -95,6 +97,12 @@ export const BACKFILL_PREEMPT_GRACE_MS = 150
95
97
  export const BACKFILL_MAX_NODES = 200
96
98
  /** 回填进度文件(只作遥测,绝不作为「已回填」的真相来源):落在库目录旁,不进仓库。 */
97
99
  export const BACKFILL_STATE_FILE = 'backfill-state.json'
100
+ /**
101
+ * workspace 索引:库文件名由 scope 清洗而来(不可逆),保留期清扫要拿**原始** scope 才能
102
+ * 按 `n.workspace` 过滤,所以写入路径顺手记一份 scope 清单。它只是索引,库才是真相:
103
+ * 清扫前仍用 `dbPathOf(scope)` 存在性复核;文件丢了就按「没有已知 workspace」处理,不猜。
104
+ */
105
+ export const WORKSPACE_INDEX_FILE = 'workspaces.jsonl'
98
106
  /**
99
107
  * 单次向量请求的硬期限:冷启动要加载模型(实测 2.4–2.8s),所以给足;超时即杀服务并降级,绝不挂起工具调用。
100
108
  * 这是「工具路径的嵌入预算」——remember 与 recall 都受它约束。
@@ -134,6 +142,33 @@ function positiveInt(value, fallback) {
134
142
  return Number.isInteger(number) && number > 0 ? number : fallback
135
143
  }
136
144
 
145
+ /**
146
+ * 进程当前使用的向量宽度。未配置 API 时恒为契约值 384;API 模式取配置/已知表/探针缓存,
147
+ * 取不到就退回 384 并只警告一次——这样文本与图臂照常工作,向量臂以「维度不符」降级,
148
+ * 而不是让整个记忆系统在打开库之前就死掉。
149
+ */
150
+ let DIM_WARNED = false
151
+ function effectiveDim(options) {
152
+ if (Number.isInteger(options?.dim) && options.dim > 0) return options.dim
153
+ try {
154
+ return activeEmbeddingDim()
155
+ } catch (error) {
156
+ if (!DIM_WARNED) {
157
+ DIM_WARNED = true
158
+ writeWarning(`记忆:${error?.message ?? String(error)};本次以 ${EMBEDDING_DIM} 维继续,向量臂将降级。`)
159
+ }
160
+ return EMBEDDING_DIM
161
+ }
162
+ }
163
+
164
+ function writeWarning(text) {
165
+ try {
166
+ process.stderr.write(`kanabo-memory: ${text}\n`)
167
+ } catch {
168
+ // stderr 不可写时沉默是唯一安全的动作。
169
+ }
170
+ }
171
+
137
172
  /** 配额从环境读(每次调用重读,探针可以在同一进程里改),非法值退回默认。 */
138
173
  export function quotaLimits() {
139
174
  return {
@@ -148,7 +183,7 @@ export function quotaLimits() {
148
183
 
149
184
  /** 分域键 → 绝对库路径;与 `store-trivium.js` 的 `dbPathFor` 完全同一实现(含「不得进仓库」断言)。 */
150
185
  export function dbPathOf(scope, options = {}) {
151
- return dbPathFor(scope, { dir: options.dir })
186
+ return dbPathFor(scope, { dir: options.dir, suffix: options.suffix })
152
187
  }
153
188
 
154
189
  /**
@@ -349,7 +384,7 @@ function recordFor(scope, options) {
349
384
  const path = dbPathOf(scope, { dir })
350
385
  const existing = REGISTRY.get(path)
351
386
  if (existing !== undefined) return existing
352
- const dim = positiveInt(options?.dim, EMBEDDING_DIM)
387
+ const dim = positiveInt(options?.dim, effectiveDim())
353
388
  const facade = createTriviumStore({
354
389
  workspace: scope,
355
390
  dir,
@@ -635,6 +670,48 @@ export async function readByNodeIds(scope, nodeIds, options = {}) {
635
670
  */
636
671
  const ANCHOR_CACHE = new Map()
637
672
 
673
+ /** 已经写进 workspace 索引的 scope(进程内去重,避免每条记忆都追加一行)。 */
674
+ const INDEXED_SCOPES = new Set()
675
+
676
+ /**
677
+ * 已见过的 workspace(保留期清扫用)。文件名的清洗不可逆,所以扫描 `.tdb` 文件不能反推
678
+ * 原始 scope;写入路径在这里追加一行 `{scope, at}`,清扫按这份索引逐域调用 `expireBefore`。
679
+ * 读失败/行损坏一律跳过——索引只是优化,库才是真相。
680
+ */
681
+ export function knownWorkspaces(options = {}) {
682
+ const file = join(options.dir ?? triviumDir(), WORKSPACE_INDEX_FILE)
683
+ let raw
684
+ try {
685
+ raw = readFileSync(file, 'utf8')
686
+ } catch {
687
+ return []
688
+ }
689
+ const scopes = new Set()
690
+ for (const line of raw.split('\n')) {
691
+ const trimmed = line.trim()
692
+ if (trimmed === '') continue
693
+ try {
694
+ const row = JSON.parse(trimmed)
695
+ if (typeof row?.scope === 'string' && row.scope.length > 0) scopes.add(row.scope)
696
+ } catch {
697
+ // 半行(写到一半被杀)不影响其它行。
698
+ }
699
+ }
700
+ return [...scopes]
701
+ }
702
+
703
+ function rememberWorkspace(scope) {
704
+ if (INDEXED_SCOPES.has(scope)) return
705
+ INDEXED_SCOPES.add(scope)
706
+ try {
707
+ const file = join(triviumDir(), WORKSPACE_INDEX_FILE)
708
+ mkdirSync(dirname(file), { recursive: true })
709
+ appendFileSync(file, `${JSON.stringify({ scope, at: Date.now() })}\n`)
710
+ } catch {
711
+ // 索引写失败只影响下一次清扫的覆盖面,绝不能让记忆写入失败。
712
+ }
713
+ }
714
+
638
715
  function anchorCacheOf(path) {
639
716
  let cache = ANCHOR_CACHE.get(path)
640
717
  if (cache === undefined) {
@@ -668,7 +745,7 @@ async function ensureSessionAnchors(facade, path, scope, sessionIds, ts) {
668
745
  cache.set(sessionId, node.nodeId)
669
746
  }
670
747
  }
671
- const zero = new Array(EMBEDDING_DIM).fill(0)
748
+ const zero = new Array(effectiveDim()).fill(0)
672
749
  const inserts = []
673
750
  const insertedFor = []
674
751
  for (const sessionId of missing) {
@@ -796,6 +873,7 @@ export async function appendEnvelopes(scope, envelopes, options = {}) {
796
873
  edges = edgeFailure(error)
797
874
  }
798
875
  }
876
+ if (ids.length > 0) rememberWorkspace(scope)
799
877
  return { ids, count: Number(result?.count ?? ids.length), edges }
800
878
  }, options)
801
879
  }
@@ -1290,6 +1368,13 @@ export async function backfillVectors(scopeOrOptions = {}, options = {}) {
1290
1368
  if (!existsSync(path)) return { ran: false, why: 'no-database', ...base }
1291
1369
 
1292
1370
  const timeoutMs = positiveInt(settings.timeoutMs, BACKFILL_TIMEOUT_MS)
1371
+ const transport = (() => {
1372
+ try {
1373
+ return embeddingTransport()
1374
+ } catch {
1375
+ return null
1376
+ }
1377
+ })()
1293
1378
  const reservation = createBackfillReservation(timeoutMs)
1294
1379
  BACKFILL.set(path, reservation)
1295
1380
  ACTIVE_BACKFILL = path
@@ -1307,7 +1392,15 @@ export async function backfillVectors(scopeOrOptions = {}, options = {}) {
1307
1392
  const config = {
1308
1393
  path,
1309
1394
  scope,
1310
- dim: positiveInt(record?.dim, positiveInt(settings.dim, EMBEDDING_DIM)),
1395
+ dim: positiveInt(record?.dim, positiveInt(settings.dim, effectiveDim())),
1396
+ passagePrefix: (() => {
1397
+ try {
1398
+ return activeEmbeddingPrefixes().passage
1399
+ } catch {
1400
+ return 'passage: '
1401
+ }
1402
+ })(),
1403
+ ...(transport === null ? {} : { provider: transport }),
1311
1404
  batchSize: positiveInt(settings.batchSize, 16),
1312
1405
  maxNodes: positiveInt(settings.maxNodes, BACKFILL_MAX_NODES),
1313
1406
  pageSize: positiveInt(settings.pageSize, 500),
@@ -1392,8 +1485,8 @@ export async function backfillVectors(scopeOrOptions = {}, options = {}) {
1392
1485
  * 零向量守卫(唯一实现):只有 384 维、全部有限、非全零的数组才算真实嵌入。
1393
1486
  * 召回入参、写入向量、服务回包三处都走它——全零向量永远不能冒充嵌入。
1394
1487
  */
1395
- export function realVectorOrNull(vector) {
1396
- if (!Array.isArray(vector) || vector.length !== EMBEDDING_DIM) return null
1488
+ export function realVectorOrNull(vector, dim = effectiveDim()) {
1489
+ if (!Array.isArray(vector) || vector.length !== dim) return null
1397
1490
  let nonZero = false
1398
1491
  for (const value of vector) {
1399
1492
  const number = Number(value)
@@ -1447,9 +1540,22 @@ function failPending(service, error) {
1447
1540
  }
1448
1541
 
1449
1542
  function spawnEmbedService() {
1543
+ const transport = (() => {
1544
+ try {
1545
+ return embeddingTransport()
1546
+ } catch {
1547
+ return null
1548
+ }
1549
+ })()
1450
1550
  const child = spawn(process.execPath, [EMBED_CHILD], {
1451
1551
  stdio: ['pipe', 'pipe', 'pipe'],
1452
- env: { ...process.env, KANABO_EMBED_CHILD: JSON.stringify({ dim: EMBEDDING_DIM }) },
1552
+ env: {
1553
+ ...process.env,
1554
+ KANABO_EMBED_CHILD: JSON.stringify({
1555
+ dim: effectiveDim(),
1556
+ ...(transport === null ? {} : { provider: transport }),
1557
+ }),
1558
+ },
1453
1559
  })
1454
1560
  const service = {
1455
1561
  child,
@@ -1655,7 +1761,7 @@ export async function embedTexts(texts, options = {}) {
1655
1761
  /** `recall-trivium.js` 的 `embedder` 形状(`{ dim, embed(text, {prefix}) }`),背后是上面的服务。 */
1656
1762
  export function createServiceEmbedder(options = {}) {
1657
1763
  return {
1658
- dim: EMBEDDING_DIM,
1764
+ dim: effectiveDim(options),
1659
1765
  async embed(text, callOptions = {}) {
1660
1766
  const prefix = typeof callOptions.prefix === 'string' ? callOptions.prefix : ''
1661
1767
  const result = await embedTexts([text], { prefix, timeoutMs: options.timeoutMs, idleMs: options.idleMs })
@@ -1686,7 +1792,7 @@ async function helperMain(argv) {
1686
1792
  }
1687
1793
  mkdirSync(dirname(destination), { recursive: true })
1688
1794
  const db = new trivium.TriviumDB(path, {
1689
- dim: EMBEDDING_DIM,
1795
+ dim: effectiveDim(),
1690
1796
  loadTextIndex: true,
1691
1797
  storageMode: 'mmap',
1692
1798
  syncMode: 'normal',