whale-memory-core 0.22.0 → 0.24.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 CHANGED
@@ -1,4 +1,5 @@
1
1
  export * as selfExperience from './lib/self-experience.js'
2
+ export * as hybridRecall from './lib/hybrid-recall.js'
2
3
  export * as selfMemory from './lib/self-memory.js'
3
4
  export { recallDetail } from './lib/detail-recall.js'
4
5
  export * as waking from './lib/waking.js'
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'
@@ -29,6 +29,10 @@ export interface Chapter {
29
29
  export function eventsFile(memDir: string): string
30
30
  export function readAll(memDir: string): { rows: ChapterEvent[]; bad: number }
31
31
  export function chapters(memDir: string, opts?: { until?: number | null }): Chapter[]
32
+ /** 同 chapters,但输入是已经读出的行(不碰文件) */
33
+ export function chapterRows(rows: ChapterEvent[], opts?: { until?: number | null }): Chapter[]
34
+ /** 一行算不算合格的章节事件(文件与 SQLite 同一条判据) */
35
+ export function isValid(row: unknown): boolean
32
36
  /** 这一天落在哪些章节里(章节可以重叠) */
33
37
  export function chaptersOn(list: Chapter[], day: string): Chapter[]
34
38
  /** from 默认今天;同名同起点重复提交是 noop */
@@ -6,7 +6,9 @@ import { createLog, stamp } from './event-log.js'
6
6
  import { before, parseAsOf } from './as-of.js'
7
7
 
8
8
  export const ACTIONS = new Set(['open', 'rename', 'close'])
9
- const log = createLog('chapter-events.jsonl', { valid: (r) => Boolean(r.id && ACTIONS.has(r.action)) })
9
+ // 一行算不算合格的章节事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
10
+ export const isValid = (r) => Boolean(r && r.id && ACTIONS.has(r.action))
11
+ const log = createLog('chapter-events.jsonl', { valid: isValid })
10
12
  export const eventsFile = log.eventsFile
11
13
  export const readAll = log.readAll
12
14
  export const internals = { FILE: log.FILE }
@@ -30,8 +32,13 @@ function checkDay(v, label) {
30
32
 
31
33
  // 重放事件,得到每个章节现在(或截至 until)的样子
32
34
  export function chapters(memDir, { until = null } = {}) {
35
+ return chapterRows(readAll(memDir).rows, { until })
36
+ }
37
+
38
+ // 同上,但输入是已经读出来的行(不碰文件):SQLite 后端走这里
39
+ export function chapterRows(rows, { until = null } = {}) {
33
40
  const map = new Map()
34
- for (const r of readAll(memDir).rows) {
41
+ for (const r of rows) {
35
42
  if (!before(r, until)) continue
36
43
  if (r.action === 'open') map.set(r.id, { id: r.id, name: r.name, names: [r.name], from: r.from, to: r.to || '', note: r.note || '', openedAt: r.at })
37
44
  const c = map.get(r.id)
@@ -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
+ }
@@ -17,6 +17,11 @@ export function readAll(memDir: string): { rows: LaterEvent[]; bad: number }
17
17
  /** until:只要这一刻(毫秒时间戳)之前(含)的后记 */
18
18
  export function groupByExp(memDir: string, opts?: { until?: number | null }): Map<string, LaterEvent[]>
19
19
 
20
+ /** 同 groupByExp,但输入是已经读出的行(不碰文件) */
21
+ export function groupRows(rows: LaterEvent[], opts?: { until?: number | null }): Map<string, LaterEvent[]>
22
+ /** 一行算不算合格的后记事件(文件与 SQLite 同一条判据) */
23
+ export function isValid(row: unknown): boolean
24
+
20
25
  export function list(memDir: string, opts?: { id?: string; limit?: number }): LaterEvent[]
21
26
 
22
27
  export const internals: { FILE: string }
@@ -62,16 +62,25 @@ export function readAll(memDir) {
62
62
  if (!line.trim()) continue
63
63
  try {
64
64
  const r = JSON.parse(line)
65
- if (r && r.id && r.thought) rows.push(r)
65
+ if (isValid(r)) rows.push(r)
66
66
  else bad += 1
67
67
  } catch { bad += 1 }
68
68
  }
69
69
  return { rows, bad }
70
70
  }
71
71
 
72
+ // 一行算不算合格的后记事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
73
+ export function isValid(r) {
74
+ return Boolean(r && r.id && r.thought)
75
+ }
76
+
72
77
  // until:只要这一刻之前(含)写下的后记,「翻回那天的自己」用
73
78
  export function groupByExp(memDir, { until = null } = {}) {
74
- const { rows } = readAll(memDir)
79
+ return groupRows(readAll(memDir).rows, { until })
80
+ }
81
+
82
+ // 同上,但输入是已经读出来的行(不碰文件):SQLite 后端从库里读出事件后走这里
83
+ export function groupRows(rows, { until = null } = {}) {
75
84
  const map = new Map()
76
85
  for (const r of rows) {
77
86
  if (!before(r, until)) continue
@@ -12,4 +12,8 @@ export function readAll(memDir: string): { rows: LinkEvent[]; bad: number }
12
12
  export function link(memDir: string, opts: { from: string; to: string; reason: string }, lockOpts?: Record<string, unknown>): { row: LinkEvent | null; noop: boolean }
13
13
  /** 每条经历连着哪些(两头都有);until 用于翻回那天 */
14
14
  export function linksByExp(memDir: string, opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
15
+ /** 同 linksByExp,但输入是已经读出的行(不碰文件) */
16
+ export function linksRows(rows: LinkEvent[], opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
17
+ /** 一行算不算合格的联想事件(文件与 SQLite 同一条判据) */
18
+ export function isValid(row: unknown): boolean
15
19
  export const internals: { FILE: string }
@@ -4,7 +4,9 @@
4
4
  import { createLog, stamp } from './event-log.js'
5
5
  import { before } from './as-of.js'
6
6
 
7
- const log = createLog('link-events.jsonl', { valid: (r) => Boolean(r.from && r.to && r.reason) })
7
+ // 一行算不算合格的联想事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
8
+ export const isValid = (r) => Boolean(r && r.from && r.to && r.reason)
9
+ const log = createLog('link-events.jsonl', { valid: isValid })
8
10
  export const eventsFile = log.eventsFile
9
11
  export const readAll = log.readAll
10
12
  export const internals = { FILE: log.FILE }
@@ -22,9 +24,14 @@ export function link(memDir, { from, to, reason }, opts = {}) {
22
24
 
23
25
  // 每条经历连着哪些:不分方向,两头都能看到;until 用于翻回那天
24
26
  export function linksByExp(memDir, { until = null } = {}) {
27
+ return linksRows(readAll(memDir).rows, { until })
28
+ }
29
+
30
+ // 同上,但输入是已经读出来的行(不碰文件):SQLite 后端走这里
31
+ export function linksRows(rows, { until = null } = {}) {
25
32
  const map = new Map()
26
33
  const push = (id, other, r) => map.set(id, [...(map.get(id) || []), { other, reason: r.reason, at: r.at, day: r.day }])
27
- for (const r of readAll(memDir).rows) {
34
+ for (const r of rows) {
28
35
  if (!before(r, until)) continue
29
36
  push(r.from, r.to, r)
30
37
  push(r.to, r.from, r)
@@ -20,6 +20,11 @@ export function readAll(memDir: string): { rows: RecallEvent[]; bad: number }
20
20
  /** until:只数这一刻(毫秒时间戳)之前(含)的想起 */
21
21
  export function countByExp(memDir: string, opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
22
22
 
23
+ /** 同 countByExp,但输入是已经读出的行(不碰文件、不走缓存) */
24
+ export function countRows(rows: RecallEvent[], opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
25
+ /** 一行算不算合格的想起事件(文件与 SQLite 同一条判据) */
26
+ export function isValid(row: unknown): boolean
27
+
23
28
  export function list(memDir: string, opts?: { id?: string; limit?: number }): RecallEvent[]
24
29
 
25
30
  export const internals: { FILE: string }
@@ -65,13 +65,18 @@ export function readAll(memDir) {
65
65
  if (!line.trim()) continue
66
66
  try {
67
67
  const r = JSON.parse(line)
68
- if (r && r.id) rows.push(r)
68
+ if (isValid(r)) rows.push(r)
69
69
  else bad += 1
70
70
  } catch { bad += 1 }
71
71
  }
72
72
  return { rows, bad }
73
73
  }
74
74
 
75
+ // 一行算不算合格的想起事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
76
+ export function isValid(r) {
77
+ return Boolean(r && r.id)
78
+ }
79
+
75
80
  // 进程内缓存:同一进程里连续 recall 不再重复解析整个事件文件
76
81
  const memo = new Map()
77
82
 
@@ -83,7 +88,13 @@ export function countByExp(memDir, { until = null } = {}) {
83
88
  const hit = until === null ? memo.get(memDir) : null
84
89
  if (hit && hit.stamp === stamp) return hit.map
85
90
 
86
- const { rows } = readAll(memDir)
91
+ const map = countRows(readAll(memDir).rows, { until })
92
+ if (until === null) memo.set(memDir, { stamp, map })
93
+ return map
94
+ }
95
+
96
+ // 同上,但输入是已经读出来的行(不碰文件、不走缓存):SQLite 后端走这里
97
+ export function countRows(rows, { until = null } = {}) {
87
98
  const map = new Map()
88
99
  for (const r of rows) {
89
100
  if (!before(r, until)) continue
@@ -92,7 +103,6 @@ export function countByExp(memDir, { until = null } = {}) {
92
103
  if (String(r.at || '') > cur.lastAt) cur.lastAt = String(r.at || '')
93
104
  map.set(r.id, cur)
94
105
  }
95
- if (until === null) memo.set(memDir, { stamp, map })
96
106
  return map
97
107
  }
98
108
 
@@ -22,4 +22,8 @@ export function decide(memDir: string, opts: { id: string; action: SealAction; n
22
22
  export function readAll(memDir: string): { rows: SealEvent[]; bad: number }
23
23
  /** 现在(或截至 until)仍封存着的经历;strict 时坏行会抛 SEAL_EVENTS_CORRUPT */
24
24
  export function sealedByExp(memDir: string, opts?: { until?: number | null; strict?: boolean }): Map<string, SealedInfo>
25
+ /** 同 sealedByExp,但输入是已经读出的 { rows, bad }(不碰文件);strict 时坏行同样抛 */
26
+ export function sealedFrom(read: { rows: SealEvent[]; bad: number }, opts?: { until?: number | null; strict?: boolean }): Map<string, SealedInfo>
27
+ /** 一行算不算合格的封存事件(文件与 SQLite 同一条判据) */
28
+ export function isValid(row: unknown): boolean
25
29
  export const internals: { FILE: string }
@@ -72,18 +72,27 @@ export function readAll(memDir) {
72
72
  if (!line.trim()) continue
73
73
  try {
74
74
  const r = JSON.parse(line)
75
- if (r && r.id && ACTIONS.has(r.action)) rows.push(r)
75
+ if (isValid(r)) rows.push(r)
76
76
  else bad += 1
77
77
  } catch { bad += 1 }
78
78
  }
79
79
  return { rows, bad }
80
80
  }
81
81
 
82
+ // 一行算不算合格的封存事件。文件和 SQLite 两个容器用同一条判据,坏行的口径才一致
83
+ export function isValid(r) {
84
+ return Boolean(r && r.id && ACTIONS.has(r.action))
85
+ }
86
+
82
87
  // 每个经历 id 现在是否封存着:只收最后一次是 seal 的;until 用于翻回那天(那时还没封存就不算)
83
88
  // strict:展示路径用。日志里有坏行时"某条经历唯一一次封存"可能正好坏掉,
84
89
  // 这时不能默认可见——把"状态未知"抛给调用方(fail closed)。
85
90
  export function sealedByExp(memDir, { until = null, strict = false } = {}) {
86
- const { rows, bad } = readAll(memDir)
91
+ return sealedFrom(readAll(memDir), { until, strict })
92
+ }
93
+
94
+ // 同上,但输入是已经读出来的 { rows, bad }(不碰文件):SQLite 后端走这里,坏行同样 fail closed
95
+ export function sealedFrom({ rows, bad }, { until = null, strict = false } = {}) {
87
96
  if (strict && bad > 0) {
88
97
  const error = new Error('封存日志有 ' + bad + ' 行无法解析,封存状态不确定')
89
98
  error.code = 'SEAL_EVENTS_CORRUPT'
@@ -83,7 +83,10 @@ export interface Experience {
83
83
 
84
84
  export const LIMITS: Record<string, number>
85
85
 
86
- export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean }): Experience[]
86
+ /** 读哪个容器:file(默认,JSONL)或 sqlite(memory.sqlite;拿不到 node:sqlite、没迁移、迁移后 JSONL 又变过都会抛错,不静默退回 file) */
87
+ export type StorageBackendName = 'file' | 'sqlite'
88
+
89
+ export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean; allowCorrupt?: boolean; backend?: StorageBackendName }): Experience[]
87
90
 
88
91
  /** 经历文件里解析不了的行数:展示路径遇到坏行会 fail closed,这个用于诊断和"先备份再修复" */
89
92
  export function badLines(dir: string): number
@@ -114,7 +117,7 @@ export function reviseExperience(dir: string, opts: { id: string; thought: strin
114
117
 
115
118
  export function markRecalled(dir: string, id: string): boolean
116
119
 
117
- export function currentView(dir: string, id: string, opts?: { asOf?: AsOf }): Experience | null
120
+ export function currentView(dir: string, id: string, opts?: { asOf?: AsOf; backend?: StorageBackendName }): Experience | null
118
121
 
119
122
  export function recall(dir: string, query: string, opts?: {
120
123
  limit?: number
@@ -128,6 +131,13 @@ export function recall(dir: string, query: string, opts?: {
128
131
  includeSealed?: boolean
129
132
  /** strict 用哪套门槛:cover(默认,0.17 起)或 legacy(0.16 及以前,结果逐条一致) */
130
133
  gate?: 'cover' | 'legacy'
134
+ /** 读哪个容器(默认 file)。sqlite 下不能 mark:写路径还在 JSONL 上 */
135
+ backend?: StorageBackendName
136
+ /** 匹配/排序方式:literal(默认,0.23.0 及以前的行为不变;null/undefined 也按 literal)或 hybrid(BM25 + 字符 n-gram + 小同义词表,实验性)。
137
+ * hybrid 下 mode / minOverlap / minRatio / gate 都不参与,空查询返回空。 */
138
+ ranker?: 'literal' | 'hybrid' | null
139
+ /** 上一轮查询(字符串或数组),给多轮追问用;字面检索拼到查询前面,混合检索只用它排序 */
140
+ context?: string | string[] | null
131
141
  }): Experience[]
132
142
 
133
143
  /** 事后联想:两条都必须存在、必须写理由;同一对(不分方向)只连一次 */
@@ -178,7 +188,7 @@ export interface RecallContextItem {
178
188
  raw: Experience
179
189
  }
180
190
 
181
- /** 宿主拿用户原话自动召回用;默认 gate 为 legacy,升级不改变自动递回的行为 */
191
+ /** 宿主拿用户原话自动召回用;默认 gate 为 cover(0.17 起),升级不改变自动递回的行为 */
182
192
  export function recallForContext(dir: string, query: string, opts?: { max?: number; gate?: 'cover' | 'legacy' }): RecallContextItem[]
183
193
 
184
194
  export const internals: { WEIGHTS: Set<Weight>; FILE: string }