whale-memory-core 0.23.0 → 0.25.0
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/index.d.ts +1 -0
- package/index.js +1 -0
- package/lib/hybrid-recall.d.ts +35 -0
- package/lib/hybrid-recall.js +205 -0
- package/lib/jsonl-stream.js +85 -0
- package/lib/metrics.d.ts +39 -0
- package/lib/metrics.js +116 -0
- package/lib/self-experience.d.ts +28 -1
- package/lib/self-experience.js +502 -100
- package/lib/sqlite-store.js +14 -0
- package/lib/storage/sqlite-backend.js +12 -6
- package/package.json +5 -1
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// whale-memory core:不依赖 QQ Agent 的可复用记忆内核
|
|
2
2
|
// 只放通用模块;宿主相关的工具注册与提示词拼接由使用者自己实现
|
|
3
3
|
export * as selfExperience from './lib/self-experience.js'
|
|
4
|
+
export * as hybridRecall from './lib/hybrid-recall.js'
|
|
4
5
|
export * as selfMemory from './lib/self-memory.js'
|
|
5
6
|
export { recallDetail } from './lib/detail-recall.js'
|
|
6
7
|
export * as waking from './lib/waking.js'
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// 混合检索(阶段 2)的类型声明。只有 recall({ ranker: 'hybrid' }) 会用到这些函数,
|
|
2
|
+
// 单独 import 也可以:它们都是纯函数,不读写磁盘。
|
|
3
|
+
import type { Experience } from './self-experience.js'
|
|
4
|
+
|
|
5
|
+
/** 同义词表:[a, b],两个方向都试 */
|
|
6
|
+
export const SYNONYMS: Array<[string, string]>
|
|
7
|
+
|
|
8
|
+
/** 混合检索的覆盖率门槛(字面检索是 MIN_COVER=0.7) */
|
|
9
|
+
export const HYBRID_MIN_COVER: number
|
|
10
|
+
|
|
11
|
+
/** 查询 → 同义替换的变体,原句永远在第一个 */
|
|
12
|
+
export function variantsOf(query: string): string[]
|
|
13
|
+
|
|
14
|
+
/** 索引用的词:拉丁整词 + 中文 2–3 字滑窗 */
|
|
15
|
+
export function tokensOf(text: string): string[]
|
|
16
|
+
|
|
17
|
+
export interface HybridIndex {
|
|
18
|
+
docs: Array<{ tf: Map<string, number>; len: number }>
|
|
19
|
+
df: Map<string, number>
|
|
20
|
+
n: number
|
|
21
|
+
avgdl: number
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function buildIndex(texts: string[]): HybridIndex
|
|
25
|
+
export function idfOf(index: HybridIndex, token: string): number
|
|
26
|
+
export function bm25Scores(index: HybridIndex, tokens: string[]): number[]
|
|
27
|
+
|
|
28
|
+
/** 对已经过滤好的 rows 做混合排序;返回值形状和 recall 一致,另带 hybridScore / hybridCover */
|
|
29
|
+
export function hybridRank(opts: {
|
|
30
|
+
rows: unknown[]
|
|
31
|
+
query: string
|
|
32
|
+
context?: string
|
|
33
|
+
limit?: number
|
|
34
|
+
minCover?: number
|
|
35
|
+
}): Array<Experience & { hybridScore: number; hybridCover: number }>
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// 混合检索(阶段 2):BM25(字符 2–3 字 n-gram)+ 一张小同义词表。
|
|
2
|
+
//
|
|
3
|
+
// 只在 recall({ ranker: 'hybrid' }) 时用;不传 ranker 的字面检索一个字节都没改(默认还是 literal)。
|
|
4
|
+
// 零第三方依赖、不调外部 API。
|
|
5
|
+
//
|
|
6
|
+
// 三条设计取舍(结果见 docs/eval-v2-zh.md):
|
|
7
|
+
// 1. 门禁仍用 query-match.js 的 contentUnits / coverage(防编造那套口径),只是把查询先做
|
|
8
|
+
// 同义替换再算覆盖率;所以「灯塔里的猫」这种沾边句不会被放进来 —— 猫不在,覆盖率就上不去。
|
|
9
|
+
// 2. BM25 只影响排序,不影响放行。宁可少召回,也不为了分数高就把没根据的东西递回去。
|
|
10
|
+
// 3. context(上一轮查询)只影响排序;只有追问句本身几乎没有内容词时,才用它补足门禁
|
|
11
|
+
// —— 纯代词/省略式追问单看自己没法判断在问什么,这是宿主把上下文递进来的那部分责任。
|
|
12
|
+
import { contentUnits, coverage, matchedTerms, queryTerms } from './query-match.js'
|
|
13
|
+
|
|
14
|
+
// 小同义词表:只收「换个说法还是同一件事」的日常词,不做实体消歧。
|
|
15
|
+
// 每对 [a, b] 两种方向都试(查询里出现哪一边,就把哪一边换成另一边再算一遍覆盖率)。
|
|
16
|
+
// 表小是故意的:同义词放得越宽,误召回的来源就越多;这一版先证明机制,不追求覆盖所有说法。
|
|
17
|
+
export const SYNONYMS = [
|
|
18
|
+
['外婆', '姥姥'], ['外公', '姥爷'],
|
|
19
|
+
['吵架', '拌嘴'], ['道歉', '认错'],
|
|
20
|
+
['失眠', '睡不着'], ['日落', '太阳下山'],
|
|
21
|
+
['买花', '花店'], ['照片', '相片'], ['拍照', '照相'],
|
|
22
|
+
['明信片', '卡片'], ['收音机', '电台'],
|
|
23
|
+
['话剧', '戏剧'], ['志愿者', '义工'],
|
|
24
|
+
['宿舍', '寝室'], ['食堂', '饭堂'],
|
|
25
|
+
['家教', '补课'], ['工资', '薪水'],
|
|
26
|
+
['考试周', '期末'], ['关门', '闭馆'], ['误点', '晚点'],
|
|
27
|
+
['河道', '河流'], ['变迁', '改道'],
|
|
28
|
+
['罚钱', '罚款'], ['课表', '课程表'], ['招人', '招新'],
|
|
29
|
+
['对联', '春联'], ['鞭炮', '烟花'], ['讲价', '砍价'],
|
|
30
|
+
['小鸟', '麻雀'], ['窗沿', '窗台'], ['铁盒', '铁皮盒'],
|
|
31
|
+
['新芽', '新叶'], ['冬衣', '冬天的衣服'], ['演出结束', '谢幕'],
|
|
32
|
+
['落选', '没进'], ['橘子', '桔子'], ['粥', '稀饭'],
|
|
33
|
+
['丢', '不见了'], ['小书', '小册子'], ['旧票', '门票']
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
// 一条查询最多派生出几个变体:表大了以后别让它组合爆炸
|
|
37
|
+
const MAX_VARIANTS = 8
|
|
38
|
+
// 混合检索的覆盖率门槛(字面检索是 0.7)。0.65 仍然拦得住「灯塔里的猫」(0.57)和
|
|
39
|
+
// 「明信片的邮资」(0.6)这类沾边句。这个数是看开发集定的;留出集只在最后跑一次(见 docs/eval-v2-zh.md)。
|
|
40
|
+
export const HYBRID_MIN_COVER = 0.65
|
|
41
|
+
const K1 = 1.2
|
|
42
|
+
const B = 0.75
|
|
43
|
+
// 上一轮查询在排序里的分量(只影响排序,不影响放行)
|
|
44
|
+
const CONTEXT_WEIGHT = 0.35
|
|
45
|
+
// 重要度只做轻微加权:字面检索是 3 倍乘,BM25 分数量纲不同,照搬会把排序压扁
|
|
46
|
+
const WEIGHT_FACTOR = { important: 1.5, normal: 1, minor: 0.75 }
|
|
47
|
+
|
|
48
|
+
// 只起语法作用的单字:只由它们组成的 n-gram 不进索引(和 query-match 的口径一致,但这里只是省空间)
|
|
49
|
+
const FUNCTION_CHARS = new Set([...'的了吗呢吧啊呀么着过是在里那这个些次段事就也都还又很把被给跟和与及或是有我你他她它们嘛啦哦呃'])
|
|
50
|
+
const GRAM_STOP = new Set([
|
|
51
|
+
'什么', '怎么', '这个', '那个', '我的', '你的', '我们', '他们', '她们', '自己',
|
|
52
|
+
'今天', '昨天', '明天', '后天', '现在', '刚刚', '后来', '以前', '以后', '时候',
|
|
53
|
+
'是不是', '有没有', '一点', '一些', '东西', '事情', '觉得', '知道', '记得',
|
|
54
|
+
'可能', '应该', '还是', '就是', '但是', '因为', '所以', '如果', '然后', '已经',
|
|
55
|
+
'没有', '不是', '可以', '一个', '这样', '那样', '真的', '其实', '比较', '非常',
|
|
56
|
+
'一直', '总是', '大概', '也许', '当然', '不过', '虽然', '只是', '还有', '以及'
|
|
57
|
+
])
|
|
58
|
+
const STOP_EN = new Set([
|
|
59
|
+
'the', 'and', 'for', 'with', 'what', 'did', 'was', 'were', 'you', 'your', 'she', 'her',
|
|
60
|
+
'his', 'him', 'they', 'them', 'this', 'that', 'there', 'then', 'from', 'about', 'have',
|
|
61
|
+
'has', 'had', 'yesterday', 'today', 'tomorrow', 'just', 'some', 'any', 'how', 'why',
|
|
62
|
+
'when', 'who', 'are', 'not'
|
|
63
|
+
])
|
|
64
|
+
|
|
65
|
+
// 索引用的词:拉丁整词 + 中文 2–3 字滑窗;全由虚词组成的 n-gram 丢掉
|
|
66
|
+
export function tokensOf(text) {
|
|
67
|
+
const s = String(text || '').toLowerCase()
|
|
68
|
+
const out = []
|
|
69
|
+
for (const w of s.match(/[a-z]{2,}/g) || []) if (!STOP_EN.has(w)) out.push(w)
|
|
70
|
+
for (const run of s.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
|
|
71
|
+
const chars = [...run]
|
|
72
|
+
for (let n = 2; n <= 3; n++) {
|
|
73
|
+
for (let i = 0; i + n <= chars.length; i++) {
|
|
74
|
+
const g = chars.slice(i, i + n).join('')
|
|
75
|
+
if (GRAM_STOP.has(g)) continue
|
|
76
|
+
if ([...g].every((c) => FUNCTION_CHARS.has(c))) continue
|
|
77
|
+
out.push(g)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 查询 → 同义替换的变体(原句永远在第一个)
|
|
85
|
+
export function variantsOf(query) {
|
|
86
|
+
const q = String(query || '')
|
|
87
|
+
const out = [q]
|
|
88
|
+
for (const [a, b] of SYNONYMS) {
|
|
89
|
+
for (const [from, to] of [[a, b], [b, a]]) {
|
|
90
|
+
if (!from || !q.includes(from)) continue
|
|
91
|
+
const v = q.split(from).join(to)
|
|
92
|
+
if (v !== q && !out.includes(v)) out.push(v)
|
|
93
|
+
if (out.length >= MAX_VARIANTS) return out
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return out
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 倒排索引:每条文本的 tf、长度、df、平均长度
|
|
100
|
+
export function buildIndex(texts) {
|
|
101
|
+
const docs = texts.map((text) => {
|
|
102
|
+
const tf = new Map()
|
|
103
|
+
for (const token of tokensOf(text)) tf.set(token, (tf.get(token) || 0) + 1)
|
|
104
|
+
let len = 0
|
|
105
|
+
for (const n of tf.values()) len += n
|
|
106
|
+
return { tf, len }
|
|
107
|
+
})
|
|
108
|
+
const df = new Map()
|
|
109
|
+
let total = 0
|
|
110
|
+
for (const d of docs) {
|
|
111
|
+
total += d.len
|
|
112
|
+
for (const token of d.tf.keys()) df.set(token, (df.get(token) || 0) + 1)
|
|
113
|
+
}
|
|
114
|
+
return { docs, df, n: docs.length, avgdl: total / Math.max(1, docs.length) }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function idfOf(index, token) {
|
|
118
|
+
const df = index.df.get(token) || 0
|
|
119
|
+
return Math.log(1 + (index.n - df + 0.5) / (df + 0.5))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// BM25:查询词里的重复只算一次(qtf 忽略),文档内外都按字符 n-gram 计
|
|
123
|
+
export function bm25Scores(index, tokens) {
|
|
124
|
+
const scores = new Array(index.docs.length).fill(0)
|
|
125
|
+
const seen = new Set(tokens)
|
|
126
|
+
for (const token of seen) {
|
|
127
|
+
if (!index.df.has(token)) continue
|
|
128
|
+
const idf = idfOf(index, token)
|
|
129
|
+
for (let i = 0; i < index.docs.length; i++) {
|
|
130
|
+
const tf = index.docs[i].tf.get(token)
|
|
131
|
+
if (!tf) continue
|
|
132
|
+
const dl = index.docs[i].len
|
|
133
|
+
scores[i] += idf * ((tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * dl) / index.avgdl)))
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return scores
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 一条经历的可检索文本,按字段拆开(用来标 matchedIn / matchedLater)
|
|
140
|
+
function partsOf(row) {
|
|
141
|
+
const t = (row && row.then) || {}
|
|
142
|
+
return {
|
|
143
|
+
then: [t.text, t.thought, (t.feeling || []).join(' ')].filter(Boolean).join(' '),
|
|
144
|
+
quote: t.quote ? [t.quote.text, t.quote.source].filter(Boolean).join(' ') : '',
|
|
145
|
+
later: (row.later || []).map((l) => [l.thought, Array.isArray(l.feeling) ? l.feeling.join(' ') : ''].filter(Boolean).join(' ')).join(' ')
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function markMatched(row, variants) {
|
|
150
|
+
const parts = partsOf(row)
|
|
151
|
+
const matchedIn = []
|
|
152
|
+
const terms = [...new Set(variants.flatMap((v) => [...queryTerms(v).terms]))]
|
|
153
|
+
for (const [label, text] of [['then', parts.then], ['quote', parts.quote], ['later', parts.later]]) {
|
|
154
|
+
if (text && matchedTerms(new Set(terms), text).size) matchedIn.push(label)
|
|
155
|
+
}
|
|
156
|
+
const matchedLater = (row.later || []).filter((l) => {
|
|
157
|
+
const text = [l.thought, Array.isArray(l.feeling) ? l.feeling.join(' ') : ''].filter(Boolean).join(' ')
|
|
158
|
+
return text && matchedTerms(new Set(terms), text).size
|
|
159
|
+
})
|
|
160
|
+
return { matchedIn, matchedLater }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// 对一个已经筛好的 rows(封存 / asOf / backend 都由 recall 处理完)做混合排序
|
|
164
|
+
export function hybridRank({ rows, query, context = '', limit = 3, minCover = HYBRID_MIN_COVER } = {}) {
|
|
165
|
+
const q = String(query || '')
|
|
166
|
+
const ctx = String(context || '')
|
|
167
|
+
const texts = rows.map((row) => {
|
|
168
|
+
const p = partsOf(row)
|
|
169
|
+
return [p.then, p.quote, p.later].filter(Boolean).join(' ')
|
|
170
|
+
})
|
|
171
|
+
const index = buildIndex(texts)
|
|
172
|
+
|
|
173
|
+
// 门禁:查询本身内容词太少(纯代词 / 省略式追问)时,用「上下文 + 追问」补足;
|
|
174
|
+
// 否则只按这一轮问的话算覆盖率 —— 上下文不替它放行。
|
|
175
|
+
const ownUnits = contentUnits(q)
|
|
176
|
+
// 内容单元 ≤3 的问句按字面检索的门槛(0.7):三个词里对上两个是 0.667,
|
|
177
|
+
// 0.65 会放行「桂花糕」「灯塔猫」「去北京」这类少了关键字的句子(独立复审抓到的)。
|
|
178
|
+
const gateCover = ownUnits.length <= 3 ? Math.max(minCover, 0.7) : minCover
|
|
179
|
+
const gateText = ownUnits.length <= 1 && ctx ? ctx + ' ' + q : q
|
|
180
|
+
const gateVariants = variantsOf(gateText)
|
|
181
|
+
const rankTokens = [...tokensOf(gateVariants.join(' ')), ...tokensOf(ctx)]
|
|
182
|
+
const bm = bm25Scores(index, rankTokens)
|
|
183
|
+
let maxBm = 1e-9
|
|
184
|
+
for (const score of bm) if (score > maxBm) maxBm = score
|
|
185
|
+
|
|
186
|
+
const picked = []
|
|
187
|
+
for (let i = 0; i < rows.length; i++) {
|
|
188
|
+
let best = { cover: 0, hits: 0, variant: gateText }
|
|
189
|
+
for (const variant of gateVariants) {
|
|
190
|
+
const units = contentUnits(variant)
|
|
191
|
+
const cover = coverage(units, texts[i])
|
|
192
|
+
const hits = matchedTerms(queryTerms(variant).terms, texts[i]).size
|
|
193
|
+
if (cover > best.cover || (cover === best.cover && hits > best.hits)) best = { cover, hits, variant }
|
|
194
|
+
}
|
|
195
|
+
if (best.hits < 1 || best.cover < gateCover) continue
|
|
196
|
+
const score = (0.75 * (bm[i] / maxBm) + 0.25 * best.cover) * (WEIGHT_FACTOR[rows[i].weight] || 1)
|
|
197
|
+
picked.push({ row: rows[i], score, cover: best.cover, variant: best.variant })
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
picked.sort((a, b) => b.score - a.score || String(b.row.at).localeCompare(String(a.row.at)))
|
|
201
|
+
return picked.slice(0, limit).map((p) => {
|
|
202
|
+
const matched = markMatched(p.row, [p.variant])
|
|
203
|
+
return { ...p.row, ...matched, hybridScore: Number(p.score.toFixed(6)), hybridCover: Number(p.cover.toFixed(6)) }
|
|
204
|
+
})
|
|
205
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// 逐行读 JSONL:不把整个文件读成一个字符串。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要有这个:旧写法是 readFileSync 整读 + split('\n'),十万条时同时占着
|
|
4
|
+
// 「文件字符串 + 切出来的行数组 + 解析后的对象」三份内存,峰值能到几百 MB。
|
|
5
|
+
// 这里按 64KB 块读、按字节找换行,每行单独解码、解析完就丢掉文本。
|
|
6
|
+
//
|
|
7
|
+
// 按字节找换行是安全的:0x0A 不可能出现在多字节 UTF-8 序列的内部(续字节都 ≥ 0x80),
|
|
8
|
+
// 所以「按 0x0A 切字节」和「先整体解码再按 '\n' 切字符串」得到的是同一组行。
|
|
9
|
+
// 唯一差别是文件末尾被截断在多字节字符中间时,最后一行解码成 U+FFFD——和 readFileSync 一样。
|
|
10
|
+
//
|
|
11
|
+
// 同步与异步两条读法共用 lineSplitter:切行口径只写一次。
|
|
12
|
+
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
|
|
15
|
+
export const READ_CHUNK = 64 * 1024
|
|
16
|
+
|
|
17
|
+
// 字节块 → 行。onLine(text, offset, bytes):
|
|
18
|
+
// text 这一行的原样文本(不含换行符;行尾的 \r 保留,和 split('\n') 一致)
|
|
19
|
+
// offset 这一行在文件里的起始字节位置
|
|
20
|
+
// bytes 这一行的字节长度(不含换行符)
|
|
21
|
+
// 注意:push 收到的 chunk 可能被复用,回调里不能把 chunk 存下来(存 text 没问题,它是新字符串)。
|
|
22
|
+
export function lineSplitter(onLine) {
|
|
23
|
+
let pending = Buffer.alloc(0)
|
|
24
|
+
let pendingAt = 0
|
|
25
|
+
return {
|
|
26
|
+
push(chunk, chunkAt) {
|
|
27
|
+
const buf = pending.length ? Buffer.concat([pending, chunk]) : chunk
|
|
28
|
+
let start = 0
|
|
29
|
+
for (;;) {
|
|
30
|
+
const nl = buf.indexOf(10, start)
|
|
31
|
+
if (nl === -1) break
|
|
32
|
+
onLine(buf.toString('utf8', start, nl), pendingAt + start, nl - start)
|
|
33
|
+
start = nl + 1
|
|
34
|
+
}
|
|
35
|
+
// 剩下没换行的一段留到下一块;整块都以换行结尾时 pending 清空
|
|
36
|
+
pending = start >= buf.length ? Buffer.alloc(0) : Buffer.from(buf.subarray(start))
|
|
37
|
+
pendingAt += start
|
|
38
|
+
},
|
|
39
|
+
end() {
|
|
40
|
+
if (!pending.length) return
|
|
41
|
+
const text = pending.toString('utf8')
|
|
42
|
+
const at = pendingAt
|
|
43
|
+
const bytes = pending.length
|
|
44
|
+
pending = Buffer.alloc(0)
|
|
45
|
+
onLine(text, at, bytes)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 同步逐行:调用方自己 open / close(这样"文件不存在"在打开那一步就能报出来,
|
|
51
|
+
// 不会等第一次 next() 才冒出来)。一次只留 64KB 的读缓冲和一行文本。
|
|
52
|
+
export function* readLines(fd) {
|
|
53
|
+
const buf = Buffer.allocUnsafe(READ_CHUNK)
|
|
54
|
+
let lines = []
|
|
55
|
+
const split = lineSplitter((text, offset, bytes) => lines.push({ text, offset, bytes }))
|
|
56
|
+
let at = 0
|
|
57
|
+
for (;;) {
|
|
58
|
+
const n = fs.readSync(fd, buf, 0, READ_CHUNK, null)
|
|
59
|
+
if (!n) break
|
|
60
|
+
split.push(buf.subarray(0, n), at)
|
|
61
|
+
at += n
|
|
62
|
+
for (const line of lines) yield line
|
|
63
|
+
lines = []
|
|
64
|
+
}
|
|
65
|
+
split.end()
|
|
66
|
+
for (const line of lines) yield line
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 异步逐行:同上,块读走 fs/promises,不把事件循环卡住。
|
|
70
|
+
export async function* readLinesAsync(fh) {
|
|
71
|
+
const buf = Buffer.allocUnsafe(READ_CHUNK)
|
|
72
|
+
let lines = []
|
|
73
|
+
const split = lineSplitter((text, offset, bytes) => lines.push({ text, offset, bytes }))
|
|
74
|
+
let at = 0
|
|
75
|
+
for (;;) {
|
|
76
|
+
const { bytesRead } = await fh.read(buf, 0, READ_CHUNK, null)
|
|
77
|
+
if (!bytesRead) break
|
|
78
|
+
split.push(buf.subarray(0, bytesRead), at)
|
|
79
|
+
at += bytesRead
|
|
80
|
+
for (const line of lines) yield line
|
|
81
|
+
lines = []
|
|
82
|
+
}
|
|
83
|
+
split.end()
|
|
84
|
+
for (const line of lines) yield line
|
|
85
|
+
}
|
package/lib/metrics.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** 指标快照:纯数据,可直接 JSON.stringify */
|
|
2
|
+
export interface MetricsSnapshot {
|
|
3
|
+
version: number
|
|
4
|
+
/** 起算时刻(ISO) */
|
|
5
|
+
since: string
|
|
6
|
+
/** 取快照的时刻(ISO) */
|
|
7
|
+
at: string
|
|
8
|
+
writes: { count: number; msTotal: number; msMax: number; msLast: number; msAvg: number }
|
|
9
|
+
recalls: {
|
|
10
|
+
count: number
|
|
11
|
+
hits: number
|
|
12
|
+
msTotal: number
|
|
13
|
+
msMax: number
|
|
14
|
+
msLast: number
|
|
15
|
+
msAvg: number
|
|
16
|
+
lastBackend: 'file' | 'sqlite' | 'other' | ''
|
|
17
|
+
backends: { file: number; sqlite: number; other: number }
|
|
18
|
+
}
|
|
19
|
+
badLines: { last: number; max: number; observations: number }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 记一次写入(ms:这次写入耗时,毫秒) */
|
|
23
|
+
export function recordWrite(sample?: { ms?: number }): void
|
|
24
|
+
/** 记一次召回(hits:返回条数;backend 只认 file / sqlite,其它一律记成 other) */
|
|
25
|
+
export function recordRecall(sample?: { ms?: number; hits?: number; backend?: string }): void
|
|
26
|
+
/** 记一次坏行观测(n:此刻的坏行数) */
|
|
27
|
+
export function recordBadLines(n?: number): void
|
|
28
|
+
export function snapshot(): MetricsSnapshot
|
|
29
|
+
export function reset(): void
|
|
30
|
+
export const VERSION: number
|
|
31
|
+
/** 进程内单例 */
|
|
32
|
+
export const metrics: {
|
|
33
|
+
recordWrite: typeof recordWrite
|
|
34
|
+
recordRecall: typeof recordRecall
|
|
35
|
+
recordBadLines: typeof recordBadLines
|
|
36
|
+
snapshot: typeof snapshot
|
|
37
|
+
reset: typeof reset
|
|
38
|
+
VERSION: number
|
|
39
|
+
}
|
package/lib/metrics.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// 运行时指标:给宿主定期落盘用的几个数字,不记内容。
|
|
2
|
+
//
|
|
3
|
+
// 只存数字和固定枚举(backend 只有 file / sqlite / other 三种取值)。
|
|
4
|
+
// 这里**永远不写正文、查询串、经历 id**:指标常被写进日志、监控、落盘文件,
|
|
5
|
+
// 漏一条正文进去,等于把她的记忆抄了一份到别处。要证明这一点,见
|
|
6
|
+
// tests/metrics-runtime.test.mjs:那组用例会把整份快照序列化后逐字检查。
|
|
7
|
+
//
|
|
8
|
+
// 开销:一次 record* 就是给几个数字加一次,不分配对象、不取时间(耗时由调用方量好传进来);
|
|
9
|
+
// 只有 snapshot() 取一次 Date.now() 并拼出纯对象。时间源只用 Date.now()。
|
|
10
|
+
//
|
|
11
|
+
// 单例:进程内一份(模块级状态)。宿主 fork 出去的子进程各算各的,不跨进程汇总。
|
|
12
|
+
// 叶子模块:不 import 任何其它模块,免得和 self-experience.js 之类形成循环依赖。
|
|
13
|
+
|
|
14
|
+
export const VERSION = 1
|
|
15
|
+
|
|
16
|
+
// 起算时刻:snapshot 里的 since 用它,reset() 时重设
|
|
17
|
+
let startedAt = Date.now()
|
|
18
|
+
|
|
19
|
+
// 一块扁平的数字:观测路径只做 s.x += 1 这种原地加法,不建临时对象
|
|
20
|
+
const s = {
|
|
21
|
+
writes: 0, writeMs: 0, writeMax: 0, writeLast: 0,
|
|
22
|
+
recalls: 0, recallMs: 0, recallMax: 0, recallLast: 0, hits: 0,
|
|
23
|
+
file: 0, sqlite: 0, other: 0, lastBackend: '',
|
|
24
|
+
badLast: 0, badMax: 0, badObservations: 0
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// 毫秒数:非有限值、负数一律当 0(观测错不能把汇总算成 NaN,落盘就废了)
|
|
28
|
+
function duration(v) {
|
|
29
|
+
const n = Number(v)
|
|
30
|
+
return Number.isFinite(n) && n > 0 ? n : 0
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function count(v) {
|
|
34
|
+
const n = Number(v)
|
|
35
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 记一次写入:{ ms } 是这次写入的耗时(毫秒)。 */
|
|
39
|
+
export function recordWrite({ ms } = {}) {
|
|
40
|
+
const d = duration(ms)
|
|
41
|
+
s.writes += 1
|
|
42
|
+
s.writeMs += d
|
|
43
|
+
s.writeLast = d
|
|
44
|
+
if (d > s.writeMax) s.writeMax = d
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 记一次召回:{ ms, hits, backend }。hits 是这次返回的条数,backend 只认 file / sqlite。 */
|
|
48
|
+
export function recordRecall({ ms, hits, backend } = {}) {
|
|
49
|
+
const d = duration(ms)
|
|
50
|
+
s.recalls += 1
|
|
51
|
+
s.recallMs += d
|
|
52
|
+
s.recallLast = d
|
|
53
|
+
if (d > s.recallMax) s.recallMax = d
|
|
54
|
+
s.hits += count(hits)
|
|
55
|
+
// backend 必须是固定枚举:宿主传进来一个像 id 的字符串,也只落成 'other'
|
|
56
|
+
if (backend === 'file') { s.file += 1; s.lastBackend = 'file' }
|
|
57
|
+
else if (backend === 'sqlite') { s.sqlite += 1; s.lastBackend = 'sqlite' }
|
|
58
|
+
else { s.other += 1; s.lastBackend = 'other' }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 记一次坏行观测:n 是此刻 badLines / 各类事件读出来的坏行数(0 = 这次没有坏行)。 */
|
|
62
|
+
export function recordBadLines(n) {
|
|
63
|
+
const bad = count(n)
|
|
64
|
+
s.badLast = bad
|
|
65
|
+
s.badObservations += 1
|
|
66
|
+
if (bad > s.badMax) s.badMax = bad
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const round3 = (n) => Math.round(n * 1000) / 1000
|
|
70
|
+
const avg = (total, n) => (n ? round3(total / n) : 0)
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 当前快照:纯对象(数字 + ISO 字符串),可以直接 JSON.stringify 落盘。
|
|
74
|
+
* 每次返回新对象,调用方改它不会影响内部计数。
|
|
75
|
+
*/
|
|
76
|
+
export function snapshot() {
|
|
77
|
+
return {
|
|
78
|
+
version: VERSION,
|
|
79
|
+
since: new Date(startedAt).toISOString(),
|
|
80
|
+
at: new Date().toISOString(),
|
|
81
|
+
writes: {
|
|
82
|
+
count: s.writes,
|
|
83
|
+
msTotal: round3(s.writeMs),
|
|
84
|
+
msMax: round3(s.writeMax),
|
|
85
|
+
msLast: round3(s.writeLast),
|
|
86
|
+
msAvg: avg(s.writeMs, s.writes)
|
|
87
|
+
},
|
|
88
|
+
recalls: {
|
|
89
|
+
count: s.recalls,
|
|
90
|
+
hits: s.hits,
|
|
91
|
+
msTotal: round3(s.recallMs),
|
|
92
|
+
msMax: round3(s.recallMax),
|
|
93
|
+
msLast: round3(s.recallLast),
|
|
94
|
+
msAvg: avg(s.recallMs, s.recalls),
|
|
95
|
+
lastBackend: s.lastBackend,
|
|
96
|
+
backends: { file: s.file, sqlite: s.sqlite, other: s.other }
|
|
97
|
+
},
|
|
98
|
+
badLines: {
|
|
99
|
+
last: s.badLast,
|
|
100
|
+
max: s.badMax,
|
|
101
|
+
observations: s.badObservations
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 清回刚启动的样子(测试用;宿主换会话时可以调)。 */
|
|
107
|
+
export function reset() {
|
|
108
|
+
s.writes = 0; s.writeMs = 0; s.writeMax = 0; s.writeLast = 0
|
|
109
|
+
s.recalls = 0; s.recallMs = 0; s.recallMax = 0; s.recallLast = 0; s.hits = 0
|
|
110
|
+
s.file = 0; s.sqlite = 0; s.other = 0; s.lastBackend = ''
|
|
111
|
+
s.badLast = 0; s.badMax = 0; s.badObservations = 0
|
|
112
|
+
startedAt = Date.now()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 进程内单例:`metrics.recordWrite(...)` 和单独 import 的函数是同一份状态。 */
|
|
116
|
+
export const metrics = Object.freeze({ recordWrite, recordRecall, recordBadLines, snapshot, reset, VERSION })
|
package/lib/self-experience.d.ts
CHANGED
|
@@ -88,6 +88,28 @@ export type StorageBackendName = 'file' | 'sqlite'
|
|
|
88
88
|
|
|
89
89
|
export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean; allowCorrupt?: boolean; backend?: StorageBackendName }): Experience[]
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* 逐条读:不建全量数组,内存只跟一份小索引走(id / 日子 / 前 24 字 / 封存),产出的每条与 loadAll 逐字段相同。
|
|
93
|
+
* 代价是要把经历文件读两遍(跨行字段要看"别处有哪些 id")。backend='sqlite' 时退回整库快照(结果相同,没有内存收益)。
|
|
94
|
+
* 遍历期间文件被追加 → 抛 EXPERIENCE_CHANGED(不静默少返一条)。
|
|
95
|
+
*/
|
|
96
|
+
export function iterate(dir: string, opts?: { asOf?: AsOf; backend?: StorageBackendName; allowCorrupt?: boolean; allowSealCorrupt?: boolean }): AsyncGenerator<Experience, void, unknown>
|
|
97
|
+
|
|
98
|
+
/** 分页游标:after 收上一页最后一个 id,也收 page 自己给的 { id, n }(文件里有重复 id 时才用得上 n) */
|
|
99
|
+
export type PageCursor = string | { id: string; n?: number }
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 游标分页:after 给上一页最后一个 id,不给就是第一页。
|
|
103
|
+
* 每页与 loadAll 的对应切片逐条相同;索引按文件 size+mtime+asOf 认库,连翻同一份文件只建一次。
|
|
104
|
+
* 游标找不到(库被重建过)抛 PAGE_CURSOR_UNKNOWN,不静默从头开始。
|
|
105
|
+
*/
|
|
106
|
+
export function page(dir: string, opts?: { limit?: number; after?: PageCursor | null; asOf?: AsOf; backend?: StorageBackendName }): Promise<{
|
|
107
|
+
rows: Experience[]
|
|
108
|
+
next: { id: string; n: number } | null
|
|
109
|
+
hasMore: boolean
|
|
110
|
+
total: number
|
|
111
|
+
}>
|
|
112
|
+
|
|
91
113
|
/** 经历文件里解析不了的行数:展示路径遇到坏行会 fail closed,这个用于诊断和"先备份再修复" */
|
|
92
114
|
export function badLines(dir: string): number
|
|
93
115
|
|
|
@@ -133,6 +155,11 @@ export function recall(dir: string, query: string, opts?: {
|
|
|
133
155
|
gate?: 'cover' | 'legacy'
|
|
134
156
|
/** 读哪个容器(默认 file)。sqlite 下不能 mark:写路径还在 JSONL 上 */
|
|
135
157
|
backend?: StorageBackendName
|
|
158
|
+
/** 匹配/排序方式:literal(默认,0.23.0 及以前的行为不变;null/undefined 也按 literal)或 hybrid(BM25 + 字符 n-gram + 小同义词表,实验性)。
|
|
159
|
+
* hybrid 下 mode / minOverlap / minRatio / gate 都不参与,空查询返回空。 */
|
|
160
|
+
ranker?: 'literal' | 'hybrid' | null
|
|
161
|
+
/** 上一轮查询(字符串或数组),给多轮追问用;字面检索拼到查询前面,混合检索只用它排序 */
|
|
162
|
+
context?: string | string[] | null
|
|
136
163
|
}): Experience[]
|
|
137
164
|
|
|
138
165
|
/** 事后联想:两条都必须存在、必须写理由;同一对(不分方向)只连一次 */
|
|
@@ -183,7 +210,7 @@ export interface RecallContextItem {
|
|
|
183
210
|
raw: Experience
|
|
184
211
|
}
|
|
185
212
|
|
|
186
|
-
/** 宿主拿用户原话自动召回用;默认 gate 为
|
|
213
|
+
/** 宿主拿用户原话自动召回用;默认 gate 为 cover(0.17 起),升级不改变自动递回的行为 */
|
|
187
214
|
export function recallForContext(dir: string, query: string, opts?: { max?: number; gate?: 'cover' | 'legacy' }): RecallContextItem[]
|
|
188
215
|
|
|
189
216
|
export const internals: { WEIGHTS: Set<Weight>; FILE: string }
|