@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/backfill-child.js +12 -6
- package/cordis.patch.yml +7 -0
- package/dedupe.js +101 -0
- package/egress.js +3 -1
- package/embed-child.js +11 -1
- package/index.js +1 -0
- package/migrate.js +3 -2
- package/package.json +23 -3
- package/providers.js +786 -0
- package/query-window.js +3 -2
- package/recall-stages.js +150 -0
- package/recall-trivium.js +67 -24
- package/recall.js +22 -6
- package/remove-legacy.mjs +3 -3
- package/retention-sweep.js +124 -0
- package/store-trivium.js +5 -2
- package/tools.js +91 -7
- package/trivium-runtime.js +115 -9
package/backfill-child.js
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
import { EMBEDDING_DIM } from './contract.js'
|
|
24
24
|
import { createEmbedder, MAX_RSS_MB, peakRssMb } from './embed.js'
|
|
25
25
|
import { PASSAGE_PREFIX } from './recall-trivium.js'
|
|
26
|
+
import { createEmbeddingProvider } from './providers.js'
|
|
26
27
|
import { embedTextOf, MEMORY_KIND } from './trivium-runtime.js'
|
|
27
28
|
|
|
28
29
|
const CONFIG_ENV = 'KANABO_BACKFILL_CHILD'
|
|
@@ -65,9 +66,10 @@ if (config === null || typeof config.path !== 'string' || config.path.length ===
|
|
|
65
66
|
failFast(`${CONFIG_ENV} 缺失或不是合法 JSON(需要 { path, scope, dim, batchSize, maxNodes, deadline })`, 'KANABO_MEMORY_BACKFILL_CONFIG')
|
|
66
67
|
}
|
|
67
68
|
const dim = Number.isInteger(config.dim) && config.dim > 0 ? config.dim : EMBEDDING_DIM
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
69
|
+
const passagePrefix = typeof config.passagePrefix === 'string' ? config.passagePrefix : PASSAGE_PREFIX
|
|
70
|
+
const apiProvider = config.provider !== null && typeof config.provider === 'object' && config.provider.kind === 'api'
|
|
71
|
+
? config.provider
|
|
72
|
+
: null
|
|
71
73
|
const batchSize = Number.isInteger(config.batchSize) && config.batchSize > 0 ? config.batchSize : 16
|
|
72
74
|
const maxNodes = Number.isInteger(config.maxNodes) && config.maxNodes > 0 ? config.maxNodes : 200
|
|
73
75
|
const pageSize = Number.isInteger(config.pageSize) && config.pageSize > 0 ? config.pageSize : 500
|
|
@@ -122,7 +124,7 @@ function isZeroVector(vector) {
|
|
|
122
124
|
return true
|
|
123
125
|
}
|
|
124
126
|
|
|
125
|
-
/**
|
|
127
|
+
/** 写回前的最后一道闸:维度必须等于本次 profile 的宽度、全部有限、不是全零。 */
|
|
126
128
|
function isRealEmbedding(vector) {
|
|
127
129
|
if (vector === null || vector === undefined || typeof vector.length !== 'number' || vector.length !== dim) return false
|
|
128
130
|
let nonZero = false
|
|
@@ -191,7 +193,11 @@ async function main() {
|
|
|
191
193
|
const { createDeterministicEmbedder } = await import('./migrate.js')
|
|
192
194
|
return createDeterministicEmbedder({ dim })
|
|
193
195
|
})()
|
|
194
|
-
: createEmbedder({
|
|
196
|
+
: createEmbedder({
|
|
197
|
+
dim,
|
|
198
|
+
timeoutMs: 60_000,
|
|
199
|
+
...(apiProvider === null ? {} : { provider: createEmbeddingProvider(apiProvider, { apiKey: apiProvider.apiKey }) }),
|
|
200
|
+
})
|
|
195
201
|
|
|
196
202
|
let updated = 0
|
|
197
203
|
let attempted = 0
|
|
@@ -208,7 +214,7 @@ async function main() {
|
|
|
208
214
|
break
|
|
209
215
|
}
|
|
210
216
|
const chunk = picks.slice(start, start + batchSize)
|
|
211
|
-
const results = await embedder.embedBatch(chunk.map((item) => item.text), { prefix:
|
|
217
|
+
const results = await embedder.embedBatch(chunk.map((item) => item.text), { prefix: passagePrefix })
|
|
212
218
|
attempted += chunk.length
|
|
213
219
|
let wrote = 0
|
|
214
220
|
let allDegraded = true
|
package/cordis.patch.yml
ADDED
package/dedupe.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 写入期的 decision 去重:Hindsight consolidation 的 `restates` 分流,落到本项目的 `remember` 上。
|
|
3
|
+
*
|
|
4
|
+
* Hindsight 在 retain → consolidation 链路上先用判定模型把「新事实重复了某条既有 observation」与
|
|
5
|
+
* 「新事实改变 / 是新的」分开,重复的只追加证据、不进 LLM(`consolidation/triage.py` 注释算过
|
|
6
|
+
* 约 40% 的调用节省)。本项目没有 observation 层,但有等价的决策点:**新条目是否与既有条目
|
|
7
|
+
* 说的是同一件事**。判为重复就不发新节点、直接返回既有 id,于是库里不会出现两条同义记忆。
|
|
8
|
+
*
|
|
9
|
+
* 三条边界:
|
|
10
|
+
* - 先向量近邻(默认 minScore 0.8)把候选压到 ≤3 条,再逐对让判定模型回答;判定模型不做检索。
|
|
11
|
+
* - 只问「B 是否重复 A」(`DEDUP_INSTRUCTIONS` 原文),不问「是不是闲聊」——本项目「每个回合都
|
|
12
|
+
* 值得记住」是既有契约,去重不能变相变成丢记忆。
|
|
13
|
+
* - 任何失败(未配置 / 超时 / 形状不对)都返回 `null`,调用方照常写入:最佳努力,绝不阻断写入。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { DEDUP_INSTRUCTIONS } from './providers.js'
|
|
17
|
+
|
|
18
|
+
const MAX_CANDIDATES = 3
|
|
19
|
+
const MIN_VECTOR_SCORE = 0.8
|
|
20
|
+
const REPEAT_THRESHOLD = 0.5
|
|
21
|
+
|
|
22
|
+
function roundMs(value) {
|
|
23
|
+
return Math.round(value * 10) / 10
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {object} options
|
|
28
|
+
* @param {object|null} options.judge `providers.createDecisionClient()` 的返回对象
|
|
29
|
+
* @param {(vector:number[], options:object) => Promise<object>} options.search 向量近邻搜索(注入,便于探针)
|
|
30
|
+
* @param {number[]|null} options.vector 新条目的向量
|
|
31
|
+
* @param {string} options.text 新条目的正文
|
|
32
|
+
* @param {number} [options.minScore] 近邻的最低余弦,默认 0.8
|
|
33
|
+
* @param {number} [options.threshold] 判「重复」的最低概率,默认 0.5
|
|
34
|
+
* @returns {Promise<{id:string, text:string, score:number, probability:number, ms:number}|null>}
|
|
35
|
+
*/
|
|
36
|
+
function textOfPayload(payload) {
|
|
37
|
+
if (payload === null || typeof payload !== 'object') return ''
|
|
38
|
+
const fromEnvelope = payload.envelope !== null && typeof payload.envelope === 'object' ? payload.envelope.text : null
|
|
39
|
+
for (const value of [fromEnvelope, payload.text, payload.scene_description, payload.topic]) {
|
|
40
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim()
|
|
41
|
+
}
|
|
42
|
+
return ''
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function findRestatingMemory(options = {}) {
|
|
46
|
+
const judge = options.judge ?? null
|
|
47
|
+
const vector = Array.isArray(options.vector) ? options.vector : null
|
|
48
|
+
const text = typeof options.text === 'string' ? options.text.trim() : ''
|
|
49
|
+
if (judge === null || judge.enabled !== true) return null
|
|
50
|
+
if (vector === null || vector.length === 0 || text === '') return null
|
|
51
|
+
if (typeof options.search !== 'function') return null
|
|
52
|
+
|
|
53
|
+
const started = performance.now()
|
|
54
|
+
let found
|
|
55
|
+
try {
|
|
56
|
+
found = await options.search(vector, {
|
|
57
|
+
topK: MAX_CANDIDATES,
|
|
58
|
+
expandDepth: 0,
|
|
59
|
+
minScore: Number.isFinite(options.minScore) ? options.minScore : MIN_VECTOR_SCORE,
|
|
60
|
+
})
|
|
61
|
+
} catch {
|
|
62
|
+
return null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const candidates = (Array.isArray(found?.hits) ? found.hits : [])
|
|
66
|
+
.map((hit) => ({
|
|
67
|
+
id: String(hit?.payload?.legacy_id ?? hit?.payload?.id ?? hit?.id ?? ''),
|
|
68
|
+
text: textOfPayload(hit?.payload),
|
|
69
|
+
score: Number(hit?.score) || 0,
|
|
70
|
+
}))
|
|
71
|
+
.filter((row) => row.id !== '' && row.text !== '' && row.text !== text)
|
|
72
|
+
.slice(0, MAX_CANDIDATES)
|
|
73
|
+
if (candidates.length === 0) return null
|
|
74
|
+
|
|
75
|
+
const questions = candidates.map((row, index) => ({
|
|
76
|
+
key: `d${index}`,
|
|
77
|
+
instructions: { task: DEDUP_INSTRUCTIONS, memory_a: row.text, memory_b: text },
|
|
78
|
+
}))
|
|
79
|
+
|
|
80
|
+
let verdict
|
|
81
|
+
try {
|
|
82
|
+
verdict = await judge.judge('Question: Which existing memory does the new memory repeat?', questions)
|
|
83
|
+
} catch {
|
|
84
|
+
return null
|
|
85
|
+
}
|
|
86
|
+
if (verdict?.ok !== true) return null
|
|
87
|
+
|
|
88
|
+
const threshold = Number.isFinite(options.threshold) ? options.threshold : REPEAT_THRESHOLD
|
|
89
|
+
let best = null
|
|
90
|
+
for (let index = 0; index < questions.length; index += 1) {
|
|
91
|
+
const probability = Number(verdict.probabilities?.[questions[index].key])
|
|
92
|
+
if (!Number.isFinite(probability) || probability < threshold) continue
|
|
93
|
+
const candidate = candidates[index]
|
|
94
|
+
if (candidate === undefined) continue
|
|
95
|
+
if (best === null || probability > best.probability) best = { ...candidate, probability }
|
|
96
|
+
}
|
|
97
|
+
if (best === null) return null
|
|
98
|
+
return { id: best.id, text: best.text, score: best.score, probability: best.probability, ms: roundMs(performance.now() - started) }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export default findRestatingMemory
|
package/egress.js
CHANGED
|
@@ -58,6 +58,7 @@ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSyn
|
|
|
58
58
|
import { basename, dirname, join, resolve } from 'node:path'
|
|
59
59
|
|
|
60
60
|
import { EMBEDDING_DIM } from './contract.js'
|
|
61
|
+
import { activeEmbeddingDim, activeProfile, profileSuffix } from './providers.js'
|
|
61
62
|
import { MEMORY_KIND, SESSION_NODE_KIND, entryOf, restoreSnapshot } from './trivium-runtime.js'
|
|
62
63
|
import { createTriviumStore } from './store-trivium.js'
|
|
63
64
|
|
|
@@ -649,7 +650,8 @@ function settingsOf(options) {
|
|
|
649
650
|
...located,
|
|
650
651
|
snapshotRoot: resolve(options.snapshotRoot ?? located.snapshotRoot),
|
|
651
652
|
timeoutMs: positiveInt(options.timeoutMs, 60_000),
|
|
652
|
-
dim: positiveInt(options.dim,
|
|
653
|
+
dim: positiveInt(options.dim, activeEmbeddingDim()),
|
|
654
|
+
suffix: typeof options.suffix === 'string' ? options.suffix : profileSuffix(activeProfile()),
|
|
653
655
|
auditPath: options.auditPath,
|
|
654
656
|
}
|
|
655
657
|
}
|
package/embed-child.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
*/
|
|
22
22
|
import { EMBEDDING_DIM } from './contract.js'
|
|
23
23
|
import { createEmbedder, peakRssMb } from './embed.js'
|
|
24
|
+
import { createEmbeddingProvider } from './providers.js'
|
|
24
25
|
|
|
25
26
|
const CONFIG_ENV = 'KANABO_EMBED_CHILD'
|
|
26
27
|
|
|
@@ -61,7 +62,16 @@ function isRealEmbedding(vector) {
|
|
|
61
62
|
let embedder = null
|
|
62
63
|
|
|
63
64
|
function embedderOf() {
|
|
64
|
-
if (embedder === null)
|
|
65
|
+
if (embedder === null) {
|
|
66
|
+
const api = config.provider !== null && typeof config.provider === 'object' && config.provider.kind === 'api'
|
|
67
|
+
? createEmbeddingProvider(config.provider, { apiKey: config.provider.apiKey })
|
|
68
|
+
: null
|
|
69
|
+
embedder = createEmbedder({
|
|
70
|
+
dim,
|
|
71
|
+
timeoutMs: Number.isInteger(config.timeoutMs) ? config.timeoutMs : undefined,
|
|
72
|
+
...(api === null ? {} : { provider: api }),
|
|
73
|
+
})
|
|
74
|
+
}
|
|
65
75
|
return embedder
|
|
66
76
|
}
|
|
67
77
|
|
package/index.js
CHANGED
|
@@ -27,6 +27,7 @@ const PATHS = [
|
|
|
27
27
|
{ module: 'serve', file: './serve.js', register: 'registerServe' },
|
|
28
28
|
{ module: 'extract', file: './extract.js', register: 'registerExtract' },
|
|
29
29
|
{ module: 'sweep', file: './sweep.js', register: 'startSweeper' },
|
|
30
|
+
{ module: 'retention-sweep', file: './retention-sweep.js', register: 'registerEgress' },
|
|
30
31
|
]
|
|
31
32
|
|
|
32
33
|
/** 安全写一行:日志本身出错也绝不冒泡(记忆故障不得让用户的回合失败)。 */
|
package/migrate.js
CHANGED
|
@@ -469,6 +469,7 @@ async function withFacade(options, scope, run) {
|
|
|
469
469
|
workspace: scope,
|
|
470
470
|
dir: options.triviumDir,
|
|
471
471
|
dim: EMBEDDING_DIM,
|
|
472
|
+
suffix: '',
|
|
472
473
|
idleMs: options.idleMs ?? 15_000,
|
|
473
474
|
requestTimeoutMs: options.requestTimeoutMs,
|
|
474
475
|
})
|
|
@@ -1096,7 +1097,7 @@ function scopeReportBase(plan) {
|
|
|
1096
1097
|
|
|
1097
1098
|
/** 只算路径、不 open:文件级租约不允许顺手开一个「看看有没有」的句柄。 */
|
|
1098
1099
|
function dbInfo(options, scope) {
|
|
1099
|
-
const path = createTriviumStore({ workspace: scope, dir: options.triviumDir, dim: EMBEDDING_DIM, idleMs: 1 }).path
|
|
1100
|
+
const path = createTriviumStore({ workspace: scope, dir: options.triviumDir, dim: EMBEDDING_DIM, suffix: '', idleMs: 1 }).path
|
|
1100
1101
|
const exists = existsSync(path)
|
|
1101
1102
|
return { path, exists, sizeBytes: exists ? statSync(path).size : 0 }
|
|
1102
1103
|
}
|
|
@@ -1504,7 +1505,7 @@ export async function writeDualEntry(entry, options = {}) {
|
|
|
1504
1505
|
try {
|
|
1505
1506
|
let facade = options.trivium ?? null
|
|
1506
1507
|
if (facade === null) {
|
|
1507
|
-
facade = createTriviumStore({ workspace: scope, dir: options.triviumDir, dim: EMBEDDING_DIM })
|
|
1508
|
+
facade = createTriviumStore({ workspace: scope, dir: options.triviumDir, dim: EMBEDDING_DIM, suffix: '' })
|
|
1508
1509
|
ownedFacade = facade
|
|
1509
1510
|
}
|
|
1510
1511
|
const envelope = fromLegacyEntry(written)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onigeya/dsh-kanabo-memory",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "金棒记忆:按 workspace 分域的临时记忆、召回与对话保留,独立于 bundle 的 DSH 插件。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -10,10 +10,17 @@
|
|
|
10
10
|
"./embed.js": "./embed.js",
|
|
11
11
|
"./store-trivium.js": "./store-trivium.js",
|
|
12
12
|
"./recall-trivium.js": "./recall-trivium.js",
|
|
13
|
+
"./recall-stages.js": "./recall-stages.js",
|
|
14
|
+
"./providers.js": "./providers.js",
|
|
15
|
+
"./dedupe.js": "./dedupe.js",
|
|
13
16
|
"./query-window.js": "./query-window.js",
|
|
14
17
|
"./trivium-runtime.js": "./trivium-runtime.js",
|
|
15
18
|
"./backfill-vectors.js": "./backfill-vectors.js",
|
|
16
|
-
"./migrate.js": "./migrate.js"
|
|
19
|
+
"./migrate.js": "./migrate.js",
|
|
20
|
+
"./egress.js": "./egress.js",
|
|
21
|
+
"./retention-sweep.js": "./retention-sweep.js",
|
|
22
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
23
|
+
"./package.json": "./package.json"
|
|
17
24
|
},
|
|
18
25
|
"files": [
|
|
19
26
|
"index.js",
|
|
@@ -24,11 +31,14 @@
|
|
|
24
31
|
"store-trivium.js",
|
|
25
32
|
"store-trivium-child.js",
|
|
26
33
|
"trivium-runtime.js",
|
|
34
|
+
"recall-trivium.js",
|
|
35
|
+
"recall-stages.js",
|
|
36
|
+
"providers.js",
|
|
37
|
+
"dedupe.js",
|
|
27
38
|
"backfill-vectors.js",
|
|
28
39
|
"backfill-child.js",
|
|
29
40
|
"embed-child.js",
|
|
30
41
|
"migrate.js",
|
|
31
|
-
"recall-trivium.js",
|
|
32
42
|
"query-window.js",
|
|
33
43
|
"tools.js",
|
|
34
44
|
"recall.js",
|
|
@@ -39,11 +49,21 @@
|
|
|
39
49
|
"serve.js",
|
|
40
50
|
"persona.js",
|
|
41
51
|
"egress.js",
|
|
52
|
+
"retention-sweep.js",
|
|
53
|
+
"cordis.patch.yml",
|
|
42
54
|
"remove-legacy.mjs"
|
|
43
55
|
],
|
|
56
|
+
"dsh": {
|
|
57
|
+
"bundle": {
|
|
58
|
+
"patch": "./cordis.patch.yml"
|
|
59
|
+
}
|
|
60
|
+
},
|
|
44
61
|
"publishConfig": {
|
|
45
62
|
"access": "public"
|
|
46
63
|
},
|
|
64
|
+
"engines": {
|
|
65
|
+
"dsh": ">=0.2.2-0 <0.3.0-0"
|
|
66
|
+
},
|
|
47
67
|
"dependencies": {
|
|
48
68
|
"@huggingface/transformers": "^3.8.1",
|
|
49
69
|
"triviumdb": "0.9.3"
|