dsh-sixlayer-memory 0.0.0-stage → 2.0.2
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/CHANGELOG.md +106 -0
- package/README.md +286 -3
- package/catalog/.index.json +111704 -0
- package/catalog/parts.json +8808 -0
- package/cordis.patch.yml +8 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +51 -0
- package/docs//347/224/237/345/221/275/345/221/250/346/234/237-/350/207/252/345/212/250/345/217/254/345/233/236/344/270/216/345/200/231/351/200/211.md +103 -0
- package/icon.svg +8 -0
- package/lib/client.js +1209 -0
- package/lib/index.js +741 -0
- package/lib/memory/affect-alert.js +60 -0
- package/lib/memory/affect-events.js +201 -0
- package/lib/memory/affect-report.js +61 -0
- package/lib/memory/api.js +194 -0
- package/lib/memory/crypto.js +68 -0
- package/lib/memory/detail.js +43 -0
- package/lib/memory/embed.js +394 -0
- package/lib/memory/emotion.js +99 -0
- package/lib/memory/explain.js +207 -0
- package/lib/memory/importer.js +215 -0
- package/lib/memory/inject.js +193 -0
- package/lib/memory/ledger.js +101 -0
- package/lib/memory/lifecycle.js +491 -0
- package/lib/memory/notify.js +164 -0
- package/lib/memory/policy.js +182 -0
- package/lib/memory/qq-official.js +196 -0
- package/lib/memory/qq.js +326 -0
- package/lib/memory/recorder.js +241 -0
- package/lib/memory/redact.js +120 -0
- package/lib/memory/scanners.js +142 -0
- package/lib/memory/schema.js +205 -0
- package/lib/memory/service-plugin.js +69 -0
- package/lib/memory/service.js +123 -0
- package/lib/memory/shadow.js +133 -0
- package/lib/memory/store.js +1138 -0
- package/lib/memory/timeline.js +74 -0
- package/lib/memory/tokenize.js +66 -0
- package/lib/memory/tools.js +1371 -0
- package/lib/memory/util.js +129 -0
- package/lib/parts/index.js +154 -0
- package/lib/parts/installer.js +294 -0
- package/lib/parts/jobs.js +91 -0
- package/lib/parts/library.js +91 -0
- package/lib/probe-plugin.js +38 -0
- package/lib/voice/board-asr.js +31 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +114 -3
- package/tools/backfill-affect.mjs +82 -0
- package/tools/eval.mjs +88 -0
- package/tools/p1.mjs +108 -0
- package/tools/p10.mjs +36 -0
- package/tools/p11.mjs +51 -0
- package/tools/p12.mjs +53 -0
- package/tools/p13.mjs +65 -0
- package/tools/p14.mjs +66 -0
- package/tools/p15.mjs +43 -0
- package/tools/p16.mjs +42 -0
- package/tools/p17.mjs +29 -0
- package/tools/p18.mjs +48 -0
- package/tools/p19.mjs +50 -0
- package/tools/p2.mjs +59 -0
- package/tools/p20.mjs +54 -0
- package/tools/p21.mjs +42 -0
- package/tools/p22.mjs +32 -0
- package/tools/p23.mjs +43 -0
- package/tools/p24.mjs +40 -0
- package/tools/p25.mjs +151 -0
- package/tools/p26.mjs +113 -0
- package/tools/p27.mjs +89 -0
- package/tools/p28.mjs +60 -0
- package/tools/p3.mjs +54 -0
- package/tools/p4.mjs +73 -0
- package/tools/p5.mjs +117 -0
- package/tools/p6.mjs +122 -0
- package/tools/p8.mjs +50 -0
- package/tools/p9.mjs +35 -0
- package/tools/phase2.mjs +159 -0
- package/tools/preflight.mjs +320 -0
- package/tools/quarterly.mjs +129 -0
- package/tools/refresh-catalog.mjs +60 -0
- package/tools/register-bundle.mjs +38 -0
- package/tools/review.mjs +156 -0
- package/tools/selfcheck.mjs +80 -0
- package/tools/smoke.mjs +112 -0
- package/tools/testset-v1.json +70 -0
- package/tools/validate-tools.mjs +150 -0
- package/tools/verify-all.mjs +39 -0
- package/tools/write-chain.mjs +139 -0
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* embed.js — 可选语义召回(向量)+ 零依赖同义词扩展。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要有这一层:FTS5 bigram 只能命中"字面相同"的查询。
|
|
5
|
+
* 「上次那个内存占用的问题」找不到「RSS 峰值排查」——这是与市场竞品最大的功能差。
|
|
6
|
+
*
|
|
7
|
+
* 三条设计约束(不能破):
|
|
8
|
+
* 1. **默认关**:没配 embedding 服务的人,一分延迟都不加,行为与 2.0 完全一致。
|
|
9
|
+
* 2. **永远兜底**:embed 超时/报错/没索引 → 退回纯词法,召回照常。
|
|
10
|
+
* 3. **永不外发正文**:S 级与 tainted 不进索引;provider 指向本机时全程不出网。
|
|
11
|
+
*
|
|
12
|
+
* 索引存在 sidecar 文件(db/embeddings.json),不动 SQLite schema —— 不上迁移、不锁库。
|
|
13
|
+
*/
|
|
14
|
+
import fs from 'node:fs'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import { sha256, ensureDir } from './util.js'
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_SEMANTIC = {
|
|
19
|
+
enabled: false,
|
|
20
|
+
provider: 'ollama', // ollama | openai
|
|
21
|
+
endpoint: '',
|
|
22
|
+
model: 'bge-m3',
|
|
23
|
+
timeoutMs: 1500,
|
|
24
|
+
weight: 0.55, // 混合分里向量占的权重
|
|
25
|
+
minScore: 0.2,
|
|
26
|
+
maxIndexPerRun: 200,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function resolveSemanticConfig(raw) {
|
|
30
|
+
const cfg = raw && typeof raw === 'object' ? raw : {}
|
|
31
|
+
const merged = { ...DEFAULT_SEMANTIC, ...cfg }
|
|
32
|
+
if (!merged.endpoint) {
|
|
33
|
+
merged.endpoint =
|
|
34
|
+
merged.provider === 'openai'
|
|
35
|
+
? 'http://127.0.0.1:1234/v1/embeddings'
|
|
36
|
+
: 'http://127.0.0.1:11434/api/embeddings'
|
|
37
|
+
}
|
|
38
|
+
return merged
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ---------- 向量数学 ----------
|
|
42
|
+
|
|
43
|
+
export function normalizeVector(vec) {
|
|
44
|
+
let norm = 0
|
|
45
|
+
for (const x of vec) norm += x * x
|
|
46
|
+
norm = Math.sqrt(norm)
|
|
47
|
+
if (!norm) return vec.map(() => 0)
|
|
48
|
+
return vec.map((x) => x / norm)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function cosine(a, b) {
|
|
52
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length) return 0
|
|
53
|
+
let dot = 0
|
|
54
|
+
let na = 0
|
|
55
|
+
let nb = 0
|
|
56
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
57
|
+
dot += a[i] * b[i]
|
|
58
|
+
na += a[i] * a[i]
|
|
59
|
+
nb += b[i] * b[i]
|
|
60
|
+
}
|
|
61
|
+
if (!na || !nb) return 0
|
|
62
|
+
return dot / Math.sqrt(na * nb)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------- 同义词扩展(零依赖,永远可用) ----------
|
|
66
|
+
|
|
67
|
+
/** 词表:一条 = 一组可互换说法。刻意只收高频开发词,宁缺毋滥。 */
|
|
68
|
+
const ALIASES = [
|
|
69
|
+
['数据库', 'database', 'db', 'sql'],
|
|
70
|
+
['报错', '错误', '异常', 'exception', 'error'],
|
|
71
|
+
['部署', '发布', '上线', 'deploy'],
|
|
72
|
+
['记忆', 'memory', '回忆'],
|
|
73
|
+
['配置', '设置', 'config', 'setting'],
|
|
74
|
+
['测试', 'test', 'spec', '单测'],
|
|
75
|
+
['日志', 'log', 'logs'],
|
|
76
|
+
['性能', '卡顿', '变慢', '慢', 'perf', 'latency'],
|
|
77
|
+
['接口', 'api', 'endpoint'],
|
|
78
|
+
['删除', '删掉', '清理', 'remove', 'delete'],
|
|
79
|
+
['修改', '改成', 'update', 'edit'],
|
|
80
|
+
['插件', 'plugin', '扩展'],
|
|
81
|
+
['仓库', 'repo', 'repository', 'git'],
|
|
82
|
+
['构建', '打包', 'build', 'compile'],
|
|
83
|
+
['依赖', 'deps', 'dependency', '包'],
|
|
84
|
+
['文档', 'doc', 'docs', 'readme'],
|
|
85
|
+
['视频', 'video', '录像'],
|
|
86
|
+
['语音', 'voice', 'tts', '音频'],
|
|
87
|
+
['模型', 'model', 'llm'],
|
|
88
|
+
['密钥', 'token', 'key', '凭证'],
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 把查询扩成"原查询 + 命中词的别名"。
|
|
93
|
+
* @returns {string} 扩展后的查询(原始查询始终在前)
|
|
94
|
+
*/
|
|
95
|
+
export function expandQuery(query, { maxExtra = 6 } = {}) {
|
|
96
|
+
const text = String(query ?? '').toLowerCase()
|
|
97
|
+
if (!text) return ''
|
|
98
|
+
const extra = []
|
|
99
|
+
for (const group of ALIASES) {
|
|
100
|
+
const hit = group.find((word) => text.includes(word.toLowerCase()))
|
|
101
|
+
if (!hit) continue
|
|
102
|
+
for (const word of group) {
|
|
103
|
+
if (word.toLowerCase() === hit.toLowerCase()) continue
|
|
104
|
+
if (text.includes(word.toLowerCase())) continue
|
|
105
|
+
if (extra.includes(word)) continue
|
|
106
|
+
extra.push(word)
|
|
107
|
+
if (extra.length >= maxExtra) break
|
|
108
|
+
}
|
|
109
|
+
if (extra.length >= maxExtra) break
|
|
110
|
+
}
|
|
111
|
+
return extra.length ? `${query} ${extra.join(' ')}` : String(query ?? '')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---------- 嵌入索引(sidecar 文件) ----------
|
|
115
|
+
|
|
116
|
+
export class EmbedIndex {
|
|
117
|
+
constructor({ dataDir, log = () => {} }) {
|
|
118
|
+
this.file = path.join(dataDir, 'db', 'embeddings.json')
|
|
119
|
+
this.log = log
|
|
120
|
+
this.map = new Map() // record_id -> { m: model, h: hash, v: number[] }
|
|
121
|
+
this.dirty = false
|
|
122
|
+
this.timer = null
|
|
123
|
+
this.load()
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
load() {
|
|
127
|
+
try {
|
|
128
|
+
const raw = JSON.parse(fs.readFileSync(this.file, 'utf8'))
|
|
129
|
+
for (const [id, item] of Object.entries(raw?.items ?? {})) {
|
|
130
|
+
if (item && Array.isArray(item.v) && item.v.length > 0) this.map.set(id, item)
|
|
131
|
+
}
|
|
132
|
+
} catch {
|
|
133
|
+
/* 没有文件就是空索引 */
|
|
134
|
+
}
|
|
135
|
+
return this
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
get(id, model) {
|
|
139
|
+
const item = this.map.get(String(id))
|
|
140
|
+
if (!item) return null
|
|
141
|
+
if (model && item.m !== model) return null
|
|
142
|
+
return item.v
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
has(id, model) {
|
|
146
|
+
return this.get(id, model) !== null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
put(id, model, vec, textHash) {
|
|
150
|
+
if (!Array.isArray(vec) || vec.length === 0) return
|
|
151
|
+
this.map.set(String(id), { m: model, h: textHash ?? '', v: vec })
|
|
152
|
+
this.dirty = true
|
|
153
|
+
this.schedule()
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
schedule() {
|
|
157
|
+
if (this.timer) return
|
|
158
|
+
this.timer = setTimeout(() => {
|
|
159
|
+
this.timer = null
|
|
160
|
+
this.save()
|
|
161
|
+
}, 800)
|
|
162
|
+
this.timer.unref?.()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
save() {
|
|
166
|
+
if (!this.dirty) return { saved: false }
|
|
167
|
+
try {
|
|
168
|
+
ensureDir(path.dirname(this.file))
|
|
169
|
+
const items = Object.fromEntries(this.map)
|
|
170
|
+
const tmp = `${this.file}.tmp-${process.pid}`
|
|
171
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: 1, items }), 'utf8')
|
|
172
|
+
fs.renameSync(tmp, this.file)
|
|
173
|
+
this.dirty = false
|
|
174
|
+
return { saved: true, size: this.map.size }
|
|
175
|
+
} catch (error) {
|
|
176
|
+
this.log('embed: save failed ' + (error?.message ?? String(error)))
|
|
177
|
+
return { saved: false }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
stats() {
|
|
182
|
+
return { size: this.map.size, file: this.file }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
get size() {
|
|
186
|
+
return this.map.size
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ---------- 嵌入器(HTTP,fail-open) ----------
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* @param {ReturnType<typeof resolveSemanticConfig>} cfg
|
|
194
|
+
* @param {{fetchImpl?: Function, log?: Function}} [deps]
|
|
195
|
+
*/
|
|
196
|
+
export function createEmbedder(cfg, deps = {}) {
|
|
197
|
+
const fetchImpl = deps.fetchImpl ?? globalThis.fetch
|
|
198
|
+
const log = deps.log ?? (() => {})
|
|
199
|
+
let broken = false
|
|
200
|
+
|
|
201
|
+
async function embed(text) {
|
|
202
|
+
if (cfg.enabled !== true) return null
|
|
203
|
+
if (broken) return null
|
|
204
|
+
if (typeof fetchImpl !== 'function') return null
|
|
205
|
+
const input = String(text ?? '').trim()
|
|
206
|
+
if (!input) return null
|
|
207
|
+
|
|
208
|
+
const controller = new AbortController()
|
|
209
|
+
const timer = setTimeout(() => controller.abort(), Math.max(100, Number(cfg.timeoutMs) || 1500))
|
|
210
|
+
timer.unref?.()
|
|
211
|
+
try {
|
|
212
|
+
const body =
|
|
213
|
+
cfg.provider === 'openai'
|
|
214
|
+
? { model: cfg.model, input: input.slice(0, 8000) }
|
|
215
|
+
: { model: cfg.model, prompt: input.slice(0, 8000) }
|
|
216
|
+
const res = await fetchImpl(cfg.endpoint, {
|
|
217
|
+
method: 'POST',
|
|
218
|
+
headers: { 'content-type': 'application/json' },
|
|
219
|
+
body: JSON.stringify(body),
|
|
220
|
+
signal: controller.signal,
|
|
221
|
+
})
|
|
222
|
+
if (!res || !res.ok) throw new Error(`HTTP ${res?.status ?? 'no-response'}`)
|
|
223
|
+
const json = await res.json()
|
|
224
|
+
const vec =
|
|
225
|
+
cfg.provider === 'openai'
|
|
226
|
+
? json?.data?.[0]?.embedding
|
|
227
|
+
: (json?.embedding ?? json?.embeddings?.[0])
|
|
228
|
+
if (!Array.isArray(vec) || vec.length === 0) throw new Error('empty embedding')
|
|
229
|
+
return normalizeVector(vec.map(Number))
|
|
230
|
+
} catch (error) {
|
|
231
|
+
// 一次失败不代表永远坏,但避免每轮都等超时:本轮之后标记为坏,由调用方决定何时重试。
|
|
232
|
+
broken = true
|
|
233
|
+
log('embed: failed ' + (error?.message ?? String(error)))
|
|
234
|
+
return null
|
|
235
|
+
} finally {
|
|
236
|
+
clearTimeout(timer)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
embed,
|
|
242
|
+
reset() {
|
|
243
|
+
broken = false
|
|
244
|
+
},
|
|
245
|
+
get broken() {
|
|
246
|
+
return broken
|
|
247
|
+
},
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ---------- 混合检索 ----------
|
|
252
|
+
|
|
253
|
+
function lexicalToScore(rank, total) {
|
|
254
|
+
if (total <= 1) return 1
|
|
255
|
+
return 1 - rank / total
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 词法 → 同义词二次pass → 向量合并,全程 fail-open。
|
|
260
|
+
*
|
|
261
|
+
* @param {{store:any, query:string, topK?:number, semantic?:object, index?:EmbedIndex, embedder?:any}} input
|
|
262
|
+
* @returns {Promise<{items:Array, mode:'lexical'|'expanded'|'hybrid', embedded:number}>}
|
|
263
|
+
*/
|
|
264
|
+
export async function searchHybrid({ store, query, topK = 3, semantic, index, embedder } = {}) {
|
|
265
|
+
const q = String(query ?? '').trim()
|
|
266
|
+
const limit = Math.max(1, Math.min(Number(topK) || 3, 10))
|
|
267
|
+
if (!q) return { items: [], mode: 'lexical', embedded: 0 }
|
|
268
|
+
|
|
269
|
+
let items = safeSearch(store, q, limit)
|
|
270
|
+
let mode = 'lexical'
|
|
271
|
+
let expanded = false
|
|
272
|
+
|
|
273
|
+
if (items.length === 0) {
|
|
274
|
+
const wider = expandQuery(q)
|
|
275
|
+
if (wider && wider !== q) {
|
|
276
|
+
const again = safeSearch(store, wider, limit)
|
|
277
|
+
if (again.length > 0) {
|
|
278
|
+
items = again
|
|
279
|
+
mode = 'expanded'
|
|
280
|
+
expanded = true
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const cfg = semantic ? resolveSemanticConfig(semantic) : null
|
|
286
|
+
if (!cfg || cfg.enabled !== true || !index || !embedder) {
|
|
287
|
+
return { items: items.slice(0, limit), mode, embedded: 0 }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const queryVec = await embedder.embed(q)
|
|
291
|
+
if (!queryVec) return { items: items.slice(0, limit), mode, embedded: 0 }
|
|
292
|
+
|
|
293
|
+
// 候选池:词法命中 + 全库有向量的记录(已过滤 S/tainted)
|
|
294
|
+
const pool = new Map()
|
|
295
|
+
items.forEach((item, i) => {
|
|
296
|
+
pool.set(item.record_id, { item, lex: lexicalToScore(i, items.length) })
|
|
297
|
+
})
|
|
298
|
+
const rows = index.map
|
|
299
|
+
let embedded = 0
|
|
300
|
+
for (const [recordId, entry] of rows) {
|
|
301
|
+
if (cfg.model && entry.m !== cfg.model) continue
|
|
302
|
+
const sim = cosine(queryVec, entry.v)
|
|
303
|
+
if (sim < Number(cfg.minScore ?? 0.2)) continue
|
|
304
|
+
embedded += 1
|
|
305
|
+
const existing = pool.get(recordId)
|
|
306
|
+
if (existing) existing.vec = sim
|
|
307
|
+
else pool.set(recordId, { record_id: recordId, vec: sim, lex: 0 })
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (embedded === 0) return { items: items.slice(0, limit), mode, embedded: 0 }
|
|
311
|
+
|
|
312
|
+
// 缺元数据的向量命中,回库补摘要
|
|
313
|
+
const enriched = []
|
|
314
|
+
for (const [, entry] of pool) {
|
|
315
|
+
const item = entry.item ?? loadItem(store, entry.record_id)
|
|
316
|
+
if (!item) continue
|
|
317
|
+
const vec = Number(entry.vec ?? 0)
|
|
318
|
+
const lex = Number(entry.lex ?? 0)
|
|
319
|
+
const score = Number(cfg.weight) * vec + (1 - Number(cfg.weight)) * lex
|
|
320
|
+
enriched.push({
|
|
321
|
+
...item,
|
|
322
|
+
score,
|
|
323
|
+
semantic: vec,
|
|
324
|
+
lexical: lex,
|
|
325
|
+
why: vec > 0 && lex > 0 ? 'both' : vec > 0 ? 'vector' : 'lexical',
|
|
326
|
+
})
|
|
327
|
+
}
|
|
328
|
+
enriched.sort((a, b) => b.score - a.score)
|
|
329
|
+
return { items: enriched.slice(0, limit), mode: 'hybrid', embedded, expanded }
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function safeSearch(store, query, limit) {
|
|
333
|
+
try {
|
|
334
|
+
const rows = store.search({ query, topK: Math.max(limit * 4, limit) })
|
|
335
|
+
return Array.isArray(rows) ? rows : []
|
|
336
|
+
} catch {
|
|
337
|
+
return []
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function loadItem(store, recordId) {
|
|
342
|
+
try {
|
|
343
|
+
const row = store.db
|
|
344
|
+
.prepare(
|
|
345
|
+
`SELECT record_id, layer, summary, sad_level, trust_level, source_channel, project_id,
|
|
346
|
+
created_at, content_hash, alpha, beta, scored
|
|
347
|
+
FROM records WHERE record_id = ? AND status = 'active'
|
|
348
|
+
AND sad_level != 'S' AND trust_level != 'tainted'`,
|
|
349
|
+
)
|
|
350
|
+
.get(String(recordId))
|
|
351
|
+
if (!row) return null
|
|
352
|
+
return { ...row, snippet: row.summary }
|
|
353
|
+
} catch {
|
|
354
|
+
return null
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* 给"还没算过向量"的记录补索引。只取 active、非 S、非 tainted。
|
|
360
|
+
* @returns {Promise<{indexed:number, skipped:number}>}
|
|
361
|
+
*/
|
|
362
|
+
export async function indexRecords({ store, index, embedder, semantic, limit = 200 } = {}) {
|
|
363
|
+
const cfg = resolveSemanticConfig(semantic)
|
|
364
|
+
if (cfg.enabled !== true || !index || !embedder) return { indexed: 0, skipped: 0 }
|
|
365
|
+
let rows = []
|
|
366
|
+
try {
|
|
367
|
+
rows = store.db
|
|
368
|
+
.prepare(
|
|
369
|
+
`SELECT record_id, content, content_hash FROM records
|
|
370
|
+
WHERE status = 'active' AND sad_level != 'S' AND trust_level != 'tainted'
|
|
371
|
+
ORDER BY created_at DESC LIMIT ?`,
|
|
372
|
+
)
|
|
373
|
+
.all(Math.max(1, Math.min(Number(limit) || 200, 2000)))
|
|
374
|
+
} catch {
|
|
375
|
+
return { indexed: 0, skipped: 0 }
|
|
376
|
+
}
|
|
377
|
+
let indexed = 0
|
|
378
|
+
let skipped = 0
|
|
379
|
+
for (const row of rows) {
|
|
380
|
+
if (index.has(row.record_id, cfg.model)) {
|
|
381
|
+
skipped += 1
|
|
382
|
+
continue
|
|
383
|
+
}
|
|
384
|
+
const vec = await embedder.embed(row.content)
|
|
385
|
+
if (!vec) {
|
|
386
|
+
skipped += 1
|
|
387
|
+
continue // 嵌入器坏了就别继续排队等超时
|
|
388
|
+
}
|
|
389
|
+
index.put(row.record_id, cfg.model, vec, row.content_hash ?? sha256(String(row.content ?? '')))
|
|
390
|
+
indexed += 1
|
|
391
|
+
}
|
|
392
|
+
if (indexed > 0) index.save()
|
|
393
|
+
return { indexed, skipped }
|
|
394
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* emotion.js — 确定性情绪标注(零依赖、不调模型)。
|
|
3
|
+
*
|
|
4
|
+
* 认知层的第一块:给每条记忆打上效价(好/坏)和唤醒度(强度),
|
|
5
|
+
* 写入时算一次,之后用于重要性、联想和注入排序。
|
|
6
|
+
*
|
|
7
|
+
* 只做可解释的规则,不做“心理诊断”:
|
|
8
|
+
* label neutral / positive / negative / urgent
|
|
9
|
+
* valence -1..1(负→正)
|
|
10
|
+
* arousal 0..1(平静→激动)
|
|
11
|
+
* intensity 0..1(|valence| 与 arousal 的较大者)
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const POSITIVE = [
|
|
15
|
+
'感谢', '谢谢', '很好', '不错', '成功', '通过', '完成', '喜欢', '稳定', '修复', '解决',
|
|
16
|
+
'顺利', '满意', '开心', '棒', '赞', '优秀', '可爱', '放心', '一致', '正常', '恢复',
|
|
17
|
+
'thanks', 'thank', 'great', 'good', 'nice', 'success', 'fixed', 'works', 'done', 'ok',
|
|
18
|
+
'开心', '高兴', '爽', '棒', '喜欢', '期待', '激动', '放心', '舒服', '满意',
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
const NEGATIVE = [
|
|
22
|
+
'失败', '报错', '崩溃', '异常', '错误', '卡住', '丢失', '丢了', '坏了', '不行', '无法',
|
|
23
|
+
'拒绝', '担心', '焦虑', '生气', '讨厌', '垃圾', '麻烦', '失望', '难受', '危险', '风险',
|
|
24
|
+
'bug', 'error', 'fail', 'crash', 'broken', 'lost', 'wrong', 'blocked', 'missing', 'bad',
|
|
25
|
+
'难过', '不开心', '心情', '烦', '累', '压力', '焦虑', '难受', '委屈', '生气', '火大', '崩溃', '烦死', '好累',
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
const URGENT = [
|
|
29
|
+
'急', '马上', '立刻', '紧急', '尽快', '赶紧', '现在就要', '火速', '救命',
|
|
30
|
+
'urgent', 'asap', 'immediately', 'critical', 'now',
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
function clamp(value, min, max) {
|
|
34
|
+
return Math.min(max, Math.max(min, value))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function round2(value) {
|
|
38
|
+
return Math.round(value * 100) / 100
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {string} text
|
|
43
|
+
* @returns {{label: string, valence: number, arousal: number, intensity: number, hits: {positive: number, negative: number, urgent: number}}}
|
|
44
|
+
*/
|
|
45
|
+
export function analyzeAffect(text) {
|
|
46
|
+
const body = String(text ?? '').toLowerCase()
|
|
47
|
+
const hits = { positive: 0, negative: 0, urgent: 0 }
|
|
48
|
+
const words = []
|
|
49
|
+
|
|
50
|
+
for (const word of POSITIVE) {
|
|
51
|
+
if (body.includes(word)) {
|
|
52
|
+
hits.positive += 1
|
|
53
|
+
words.push(word)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const word of NEGATIVE) {
|
|
57
|
+
if (body.includes(word)) {
|
|
58
|
+
hits.negative += 1
|
|
59
|
+
words.push(word)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
for (const word of URGENT) {
|
|
63
|
+
if (body.includes(word)) {
|
|
64
|
+
hits.urgent += 1
|
|
65
|
+
words.push(word)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 感叹号与重复标点也是唤醒信号(最多加 2)
|
|
70
|
+
const bangs = (body.match(/[!!]/g) ?? []).length
|
|
71
|
+
const shout = Math.min(2, bangs)
|
|
72
|
+
|
|
73
|
+
const valence = clamp((hits.positive - hits.negative) / 3, -1, 1)
|
|
74
|
+
const arousal = clamp((Math.abs(hits.positive - hits.negative) + hits.urgent * 2 + shout) / 6, 0, 1)
|
|
75
|
+
|
|
76
|
+
let label = 'neutral'
|
|
77
|
+
if (hits.urgent > 0 && hits.negative >= hits.positive) label = 'urgent'
|
|
78
|
+
else if (hits.positive > hits.negative) label = 'positive'
|
|
79
|
+
else if (hits.negative > hits.positive) label = 'negative'
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
label,
|
|
83
|
+
valence: round2(valence),
|
|
84
|
+
arousal: round2(arousal),
|
|
85
|
+
intensity: round2(Math.max(Math.abs(valence), arousal)),
|
|
86
|
+
hits,
|
|
87
|
+
words,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 综合重要性:写入时的初值,后续 mem_judge 会用 beta 继续修正。
|
|
93
|
+
* 0.35 基线 + 情绪 0.35 + 唤醒 0.15 + 层级加成(L2 及以上更“像知识”)。
|
|
94
|
+
*/
|
|
95
|
+
export function initialImportance(affect, layer = 'L1') {
|
|
96
|
+
const depthBonus = /^L([2-5])$/.test(String(layer)) ? 0.15 : 0
|
|
97
|
+
const value = 0.35 + 0.35 * Math.abs(affect.valence) + 0.15 * affect.arousal + depthBonus
|
|
98
|
+
return round2(clamp(value, 0, 1))
|
|
99
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* explain.js — 把一条记忆翻译成「普通人看得懂的一句话」。
|
|
3
|
+
*
|
|
4
|
+
* 记忆库里存的是工程语言:record_id、层级、`/proc/<pid>/io`、`wchar=0`、
|
|
5
|
+
* 版本号、脚本路径。给用户看的卡片不能原样端上去。
|
|
6
|
+
*
|
|
7
|
+
* 这一层只做**压缩与去术语**,不做改写、不加事实:
|
|
8
|
+
* - 去掉代码块、内联代码、绝对路径、长哈希、版本号尾巴
|
|
9
|
+
* - 把「(2026-10-26 实测有效,免拔插)」这类括号里的关键信息提成一句人话
|
|
10
|
+
* - 按内容分个类(修过的坑 / 定下的规则 / 怎么做 / 聊过的话 / 记下的事实)
|
|
11
|
+
*
|
|
12
|
+
* 纯函数,零依赖,可离线回归(tools/p27.mjs)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const KINDS = [
|
|
16
|
+
{ id: 'chat', label: '聊过的话', test: (t) => /角色[::]/.test(t) && /用户[::]/.test(t) },
|
|
17
|
+
{ id: 'fix', label: '修过的坑', test: (t) => /(症状|卡死|报错|崩溃|异常|故障|修好|复位|失效|不工作|失败)/.test(t) },
|
|
18
|
+
{ id: 'rule', label: '定下的规则', test: (t) => /(一律|统一|默认|以后|今后|禁止|必须|不要|别再|约定|口径|规范)/.test(t) },
|
|
19
|
+
{ id: 'howto', label: '怎么做', test: (t) => /(启动|安装|配置|步骤|脚本|命令|接入|部署|流程|用法)/.test(t) },
|
|
20
|
+
{ id: 'pref', label: '你的偏好', test: (t) => /(我习惯|我喜欢|我讨厌|我偏好|我一般|我不喜欢)/.test(t) },
|
|
21
|
+
{ id: 'fact', label: '记下的事实', test: () => true },
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
/** 去掉行首的装饰符(★ ☆ · • - * > 编号)。 */
|
|
25
|
+
function stripMarks(text) {
|
|
26
|
+
return String(text ?? '')
|
|
27
|
+
.replace(/^[\s★☆·•●○\-*>#>]+/, '')
|
|
28
|
+
.replace(/^\d+[.、)]\s*/, '')
|
|
29
|
+
.trim()
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 去术语:代码块 / 内联代码 / 绝对路径 / 长哈希 / URL / 邮箱 / 文件名 / ASCII 标识符。 */
|
|
33
|
+
export function cleanText(text) {
|
|
34
|
+
let s = String(text ?? '')
|
|
35
|
+
s = s.replace(/```[\s\S]*?```/g, ' ')
|
|
36
|
+
s = s.replace(/`([^`]*)`/g, (_, code) => (String(code).length > 24 ? ' ' : String(code)))
|
|
37
|
+
// 工程文件名:wifi_push.py / start.ps1 / config.yaml
|
|
38
|
+
s = s.replace(/\b[\w-]+\.(?:py|ps1|sh|json|ya?ml|md|js|mjs|cjs|ts|log|db|sqlite|exe|bat|ini|conf|txt|csv)\b/gi, ' ')
|
|
39
|
+
// 绝对路径与 Windows 盘符路径
|
|
40
|
+
s = s.replace(/\b[A-Za-z]:\\[^\s,。;、))]+/g, ' ')
|
|
41
|
+
s = s.replace(/(?:^|[\s((])\/[\w.\-/<>]{8,}/g, ' ')
|
|
42
|
+
s = s.replace(/\bhttps?:\/\/\S+/g, ' ')
|
|
43
|
+
s = s.replace(/\b[\w.+-]+@[\w-]+\.[\w.]+\b/g, ' ')
|
|
44
|
+
s = s.replace(/\b[A-Z0-9]{12,}\b/g, ' ')
|
|
45
|
+
s = s.replace(/\s{2,}/g, ' ')
|
|
46
|
+
s = s.replace(/[((]\s*[))]/g, '')
|
|
47
|
+
s = s.replace(/\s+([,。;、])/g, '$1')
|
|
48
|
+
return s.trim()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const DATE_RE = /(\d{4})-(\d{1,2})-(\d{1,2})/g
|
|
52
|
+
|
|
53
|
+
function fmtDate(y, m, d) {
|
|
54
|
+
return `${Number(m)}月${Number(d)}日`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 相对时间:今天 / 昨天 / N 天前 / 2026 年 10 月 26 日。 */
|
|
58
|
+
export function relativeWhen(iso, now = Date.now()) {
|
|
59
|
+
const t = Date.parse(String(iso ?? ''))
|
|
60
|
+
if (!Number.isFinite(t)) return ''
|
|
61
|
+
const day = 86400_000
|
|
62
|
+
const a = new Date(t)
|
|
63
|
+
const b = new Date(now)
|
|
64
|
+
const startOf = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()
|
|
65
|
+
const diff = Math.round((startOf(b) - startOf(a)) / day)
|
|
66
|
+
if (diff <= 0) return '今天'
|
|
67
|
+
if (diff === 1) return '昨天'
|
|
68
|
+
if (diff < 7) return `${diff} 天前`
|
|
69
|
+
if (diff < 30) return `${Math.floor(diff / 7)} 周前`
|
|
70
|
+
if (a.getFullYear() === b.getFullYear()) return fmtDate(a.getFullYear(), a.getMonth() + 1, a.getDate())
|
|
71
|
+
return `${a.getFullYear()}年${a.getMonth() + 1}月${a.getDate()}日`
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 把括号里的"关键补充"提出来:
|
|
76
|
+
* 「(2026-10-26 实测有效,免拔插)」→ 「10 月 26 日实测有效,免拔插」
|
|
77
|
+
* 只保留含日期/验证/口径这类信息的括号,其它括号(多半是实现细节)丢掉。
|
|
78
|
+
*/
|
|
79
|
+
function extractNotes(text) {
|
|
80
|
+
const notes = []
|
|
81
|
+
const body = String(text ?? '').replace(/[((]([^()()]{2,60})[))]/g, (whole, inner) => {
|
|
82
|
+
const hasDate = DATE_RE.test(inner)
|
|
83
|
+
DATE_RE.lastIndex = 0
|
|
84
|
+
// 去掉日期之后还剩什么?只有「(2026-10-26)」这种纯日期括号不算补充说明
|
|
85
|
+
const rest = cleanText(inner.replace(DATE_RE, '')).replace(/[,,;;\s]/g, '')
|
|
86
|
+
const meaningful = hasDate || /(实测|验证|定稿|有效|免|口径|注意|默认|必须)/.test(inner)
|
|
87
|
+
if (!meaningful || rest.length === 0) return ' '
|
|
88
|
+
let note = inner.replace(DATE_RE, (_, y, m, d) => fmtDate(y, m, d))
|
|
89
|
+
note = cleanText(note).replace(/\s+/g, '')
|
|
90
|
+
if (note) notes.push(note)
|
|
91
|
+
return ' '
|
|
92
|
+
})
|
|
93
|
+
return { body, notes }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 收紧空格:中文两侧不留空格,但两个拉丁词之间保留一个。 */
|
|
97
|
+
function tighten(text) {
|
|
98
|
+
return String(text ?? '')
|
|
99
|
+
.replace(/\s*([\u4e00-\u9fff(),。;、:!?])\s*/g, '$1')
|
|
100
|
+
.replace(/\s{2,}/g, ' ')
|
|
101
|
+
.trim()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 句子里找一个自然的截断点。 */
|
|
105
|
+
function clamp(text, max) { const s = String(text ?? '').trim()
|
|
106
|
+
if (s.length <= max) return s
|
|
107
|
+
const head = s.slice(0, max)
|
|
108
|
+
const cut = Math.max(head.lastIndexOf(','), head.lastIndexOf(';'), head.lastIndexOf('。'), head.lastIndexOf('、'))
|
|
109
|
+
return (cut > max * 0.5 ? head.slice(0, cut) : head) + '…'
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 分类。 */
|
|
113
|
+
export function detectKind(text) {
|
|
114
|
+
const s = String(text ?? '')
|
|
115
|
+
const hit = KINDS.find((k) => k.test(s))
|
|
116
|
+
return hit ?? KINDS[KINDS.length - 1]
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 对话类:用户:X 角色:Y → 说清了"你说过什么、当时怎么回的"。 */
|
|
120
|
+
function explainChat(text) {
|
|
121
|
+
const user = text.match(/用户[::]\s*([^\n]+?)(?:\s*角色[::]|$)/)
|
|
122
|
+
const reply = text.match(/角色[::]\s*([^\n]+)/)
|
|
123
|
+
const trimPunct = (s) => String(s ?? '').replace(/[。!?!?;;,,\s]+$/g, '')
|
|
124
|
+
const u = trimPunct(cleanText(user?.[1] ?? '')).slice(0, 40)
|
|
125
|
+
const r = trimPunct(cleanText(reply?.[1] ?? '')).slice(0, 40)
|
|
126
|
+
if (!u && !r) return null
|
|
127
|
+
// 太短的搭话("对"、"六六六")不配当标题,归成"随口聊了一句"
|
|
128
|
+
if (u.length < 4) {
|
|
129
|
+
return {
|
|
130
|
+
title: '随口聊了一句',
|
|
131
|
+
plain: r ? `你说了「${u || '几句'}」,回的是「${clamp(r, 26)}」。` : '你说了一句很短的话。',
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
title: `你说过:${clamp(u, 26)}`,
|
|
136
|
+
plain: r ? `它回你:「${clamp(r, 30)}」。` : '',
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 主入口:一条记录 → 给人看的展示信息。
|
|
142
|
+
* title 当标题,plain 只放"补充说明",不重复标题。
|
|
143
|
+
* @param {{summary?:string, content?:string, created_at?:string, layer?:string}} row
|
|
144
|
+
* @returns {{kind:string, kindId:string, title:string, plain:string, when:string, technical:string}}
|
|
145
|
+
*/
|
|
146
|
+
export function explainRecord(row, { now = Date.now() } = {}) {
|
|
147
|
+
const raw = String(row?.summary ?? row?.content ?? '').trim()
|
|
148
|
+
const kind = detectKind(raw)
|
|
149
|
+
const fallback = {
|
|
150
|
+
kind: kind.label,
|
|
151
|
+
kindId: kind.id,
|
|
152
|
+
title: clamp(cleanText(raw), 30) || '(没有摘要)',
|
|
153
|
+
plain: '',
|
|
154
|
+
when: relativeWhen(row?.created_at, now),
|
|
155
|
+
technical: raw,
|
|
156
|
+
}
|
|
157
|
+
if (!raw) return fallback
|
|
158
|
+
|
|
159
|
+
if (kind.id === 'chat') {
|
|
160
|
+
const chat = explainChat(raw)
|
|
161
|
+
if (chat) return { ...fallback, ...chat }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const stripped = stripMarks(raw)
|
|
165
|
+
const { body, notes } = extractNotes(stripped)
|
|
166
|
+
const clean = cleanText(body)
|
|
167
|
+
|
|
168
|
+
// 「标题:正文」结构:冒号前就是这件事的名字
|
|
169
|
+
const idx = clean.search(/[::]/)
|
|
170
|
+
const head = idx > 3 ? clean.slice(0, idx) : clean
|
|
171
|
+
const tail = idx > 3 ? clean.slice(idx + 1) : ''
|
|
172
|
+
|
|
173
|
+
const title = clamp(head.replace(/[,,。;;]\s*$/, ''), 30) || fallback.title
|
|
174
|
+
const noteText = notes.slice(0, 2).join(',')
|
|
175
|
+
// 尾巴里的实现细节(一堆标识符/符号)就不给用户看了:
|
|
176
|
+
// 去术语后如果掉了太多字、或留下"中文 空格 中文"这种断口,就整段不放。
|
|
177
|
+
const tailClean = cleanText(tail)
|
|
178
|
+
const originalLen = Math.max(1, tail.replace(/\s/g, '').length)
|
|
179
|
+
const keptRatio = tailClean.replace(/\s/g, '').length / originalLen
|
|
180
|
+
const hasSeam = /[\u4e00-\u9fff]\s+[\u4e00-\u9fff]/.test(tailClean)
|
|
181
|
+
const tooCodelike = /[\w/]{18,}/.test(tailClean)
|
|
182
|
+
const tailText =
|
|
183
|
+
keptRatio >= 0.5 && !hasSeam && !tooCodelike && tailClean.replace(/\s/g, '').length > 6
|
|
184
|
+
? clamp(tighten(tailClean), 52)
|
|
185
|
+
: ''
|
|
186
|
+
const plain = [noteText, tailText].filter(Boolean).join(';')
|
|
187
|
+
|
|
188
|
+
return { ...fallback, title, plain: plain ? `${plain}。` : '', when: relativeWhen(row?.created_at, now) }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 批量:给 RPC 返回的行挂上 display。 */
|
|
192
|
+
export function decorateRows(rows, options) {
|
|
193
|
+
if (!Array.isArray(rows)) return rows
|
|
194
|
+
return rows.map((row) => {
|
|
195
|
+
if (!row || typeof row !== 'object') return row
|
|
196
|
+
try {
|
|
197
|
+
return { ...row, display: explainRecord(row, options) }
|
|
198
|
+
} catch {
|
|
199
|
+
return row
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 节点式(graph.all 的 nodes)。 */
|
|
205
|
+
export function decorateNodes(nodes, options) {
|
|
206
|
+
return decorateRows(nodes, options)
|
|
207
|
+
}
|