dsh-aurorix-agentbook 1.9.6 → 1.10.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/lib/host.js CHANGED
@@ -55,6 +55,7 @@ import {
55
55
  DEFAULT_PROTOCOL,
56
56
  resolveStatePath,
57
57
  librarySignature,
58
+ makeAnchorProbe,
58
59
  } from './snapshot.js'
59
60
  import { GUIDE, GUIDE_INDEX } from './guide.js'
60
61
  import { CURATION_MANUAL } from './curation.js'
@@ -150,6 +151,9 @@ export function attachHost(ctx, deps) {
150
151
 
151
152
  const doRefresh = async (current) => {
152
153
  try {
154
+ // 主题簇验证要按锚点词跑检索,单次约 0.5 秒。库没变时结果必然相同,
155
+ // 所以按库指纹缓存到磁盘:同一份库只在第一次花这几秒,之后直接复用。
156
+ const probeAnchor = makeAnchorProbe(backend, librarySignature(libraryRoot()))
153
157
  const built = await buildSnapshot((plane) => backend.list(plane, { limit: 2000, full: true }), {
154
158
  indexCount: current.indexCount,
155
159
  residentLimit: current.residentLimit,
@@ -157,7 +161,9 @@ export function attachHost(ctx, deps) {
157
161
  accessBoost: current.accessBoost,
158
162
  maxContextBytes: current.maxContextBytes,
159
163
  access,
164
+ probeAnchor,
160
165
  })
166
+ if (typeof probeAnchor?.save === 'function') probeAnchor.save()
161
167
  snapshot.text = built.text
162
168
  snapshot.stats = built.stats
163
169
  snapshot.error = ''
package/lib/snapshot.js CHANGED
@@ -1,8 +1,13 @@
1
1
  // 分层快照:把记忆库压成一段能进提示词的文本。
2
2
  //
3
- // 规则:常驻层(soul/profile/explicit)永久全量;其余按“平面基准 + 使用加成 -
4
- // 时间衰减”排序,按名次分三档(全量正文 / 摘要 / 仅标题)。注入条数固定,
5
- // 所以库再大也不会撑爆上下文;没进快照的原文都还在,用检索取回。
3
+ // 两档:常驻层(soul/profile/explicit)永久给全量正文;下三层(rules/long_term/
4
+ // episodic)只给标题,正文一律按 ID 取。
5
+ //
6
+ // 下三层的标题会先按「主题簇」折叠:同一主题的若干条只留一个锚点词加条数,
7
+ // 想看那一簇就用锚点词检索——检索能把这些条目全部找回来,所以不丢信息。
8
+ //
9
+ // 折叠的前提是可验证:只有当锚点词检索确实覆盖该簇全部条目(召回 >= 80%)时
10
+ // 才折叠;否则原样列出。宁可多占几百字节,也不让模型以为「库里没有这条」。
6
11
  import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
7
12
  import { dirname, join } from 'node:path'
8
13
 
@@ -18,6 +23,13 @@ const PLANE_LABEL = {
18
23
  episodic: 'episodic 事件与过程',
19
24
  }
20
25
 
26
+ // 下三层各自的索引渲染方式。
27
+ //
28
+ // rules 是规则类:标题就是规则的索引名,折叠成锚点词会让人看不出是哪几条规则,
29
+ // 等于把硬约束藏进一个词后面。所以规则永远纯标题,逐条列出。
30
+ // 另外两层是经验与过程记录,按主题折叠收益最大。
31
+ const PLANE_INDEX_MODE = { rules: 'titles', long_term: 'cluster', episodic: 'cluster' }
32
+
21
33
  // 排序基准:身份/规则/偏好在最前,经验其次,过程记录最轻。
22
34
  const PLANE_BASE = { soul: 1000, rules: 900, profile: 800, explicit: 700, long_term: 300, episodic: 120 }
23
35
 
@@ -247,6 +259,162 @@ export function librarySignature(root) {
247
259
  * 读全库并压成快照文本。
248
260
  * @param {(plane: string) => Promise<{ ok: boolean, items?: object[], reason?: string }>} listPlane
249
261
  */
262
+ /**
263
+ * 主题簇折叠的检索探针,按库指纹缓存到磁盘。
264
+ *
265
+ * 验证一个锚点要跑一次检索(约 0.5 秒),锚点几十个就是几秒。库没变时验证结果
266
+ * 必然相同,所以同一份库只该验证一次。缓存里存「锚点 → 命中的记录 ID」。
267
+ *
268
+ * 库指纹一变整份作废——宁可重算,也不拿旧指纹的结论去折叠新库:那会让模型
269
+ * 搜不到本来存在的条目。
270
+ */
271
+ export function makeAnchorProbe(backend, signature, cachePath) {
272
+ if (typeof backend?.search !== 'function') return null
273
+ if (!signature) return null
274
+
275
+ const file = cachePath || join(dirname(resolveStatePath('')), `clusters-${signature}.json`)
276
+ let cache = {}
277
+ try {
278
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
279
+ // 指纹对不上就整份丢掉。
280
+ if (raw && raw.signature === signature && raw.anchors && typeof raw.anchors === 'object') cache = raw.anchors
281
+ } catch {
282
+ cache = {}
283
+ }
284
+ const inFlight = new Map()
285
+
286
+ const probe = async (anchor) => {
287
+ const key = String(anchor).toLowerCase()
288
+ if (cache[key]) return new Set(cache[key])
289
+ if (inFlight.has(key)) return inFlight.get(key) // 同轮同锚点只查一次
290
+ const task = (async () => {
291
+ const result = await backend.search(key, 60)
292
+ // 两种形状都要认:插件 backend.search 返回 {ok,items},裸 abook JSON 是 {items,total}。
293
+ // 只看 ok 会在后者上永远判成失败,折叠静默归零——这正是最初把折叠数做成 0 的原因。
294
+ const items = Array.isArray(result?.items) ? result.items : []
295
+ const ok = result?.ok !== false && items.length >= 0 && Array.isArray(result?.items)
296
+ const ids = ok ? items.map((x) => String(x.id ?? '')).filter(Boolean) : []
297
+ if (ok) cache[key] = ids
298
+ return new Set(ids)
299
+ })()
300
+ inFlight.set(key, task)
301
+ try {
302
+ return await task
303
+ } finally {
304
+ inFlight.delete(key)
305
+ }
306
+ }
307
+
308
+ // 构建结束后由调用方落盘:避免每个锚点都写一次文件。
309
+ probe.save = () => {
310
+ try {
311
+ mkdirSync(dirname(file), { recursive: true })
312
+ const tmp = `${file}.tmp`
313
+ writeFileSync(tmp, JSON.stringify({ signature, anchors: cache }), 'utf8')
314
+ renameSync(tmp, file)
315
+ } catch {
316
+ // 缓存写不进去不影响正确性,下次重算而已。
317
+ }
318
+ }
319
+ return probe
320
+ }
321
+
322
+ // 主题簇折叠。
323
+ //
324
+ // 只认「具体技术实体」当锚点:`abook`、`zygisk`、`xqdk` 这类词检索起来能精准命中
325
+ // 同一批记录;`验证`、`必须`、`android` 这类泛词不行——实测 android 只能召回 19%,
326
+ // 拿它当锚点等于告诉模型「去搜这个词」然后什么也找不到。
327
+ //
328
+ // 判定可验证:锚点词检索回来必须覆盖该簇至少 80% 的条目。达不到就整簇放弃、原样列出。
329
+ const CLUSTER_MIN_RECALL = 0.8
330
+ const CLUSTER_MIN_SIZE = 2
331
+ // 验证成本 = 锚点数 × 单次检索耗时(约 0.5 秒)。这两个上限把最坏情况压到
332
+ // 「几十次检索、几秒」,而不是「几百次、几十秒」。
333
+ const CLUSTER_MAX_ANCHORS = 60
334
+ const CLUSTER_CONCURRENCY = 6
335
+
336
+ // 不当作锚点的英文虚词。
337
+ const EN_STOP = new Set(['the', 'and', 'for', 'with', 'that', 'this', 'from', 'not', 'are', 'was', 'you', 'can', 'all', 'any', 'but', 'how', 'why'])
338
+
339
+ function latinAnchors(title) {
340
+ const out = []
341
+ for (const m of String(title).matchAll(/[A-Za-z][A-Za-z0-9_.\-]{2,}/g)) {
342
+ const key = m[0].toLowerCase()
343
+ if (!EN_STOP.has(key)) out.push(key)
344
+ }
345
+ return [...new Set(out)]
346
+ }
347
+
348
+ /**
349
+ * @param {{id:string,title:string}[]} records 下三层记录
350
+ * @param {(anchor:string) => Promise<Set<string>>} probe 用锚点词检索,返回命中的记录 ID 集合
351
+ * @returns {Promise<{clusters:{anchor:string,count:number}[], ownerOf:Map<string,string>, folded:number}>}
352
+ */
353
+ export async function clusterTitles(records, probe) {
354
+ const byAnchor = new Map()
355
+ for (const r of records) {
356
+ for (const a of latinAnchors(r.title)) {
357
+ if (!byAnchor.has(a)) byAnchor.set(a, [])
358
+ const list = byAnchor.get(a)
359
+ if (!list.includes(r.id)) list.push(r.id)
360
+ }
361
+ }
362
+
363
+ // 先按成员数从大到小验证,让大簇优先占住自己的成员。
364
+ // 每个锚点要跑一次检索,单次约 0.5 秒。锚点上百个串行就是几十秒,
365
+ // 所以按固定并发度并行;上限压住是为了不和正在跑的其它 abook 调用抢资源。
366
+ const candidates = [...byAnchor]
367
+ .filter(([, ids]) => ids.length >= CLUSTER_MIN_SIZE)
368
+ .sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]))
369
+ .slice(0, CLUSTER_MAX_ANCHORS) // 只验证最可能成簇的那些,剩下的本来也不值得折叠
370
+
371
+ // 验证结果先按键存进 Map,最后再按 candidates 的原顺序取回。
372
+ // 直接用 push 收集会让顺序取决于哪个 worker 先跑完——同一份库两次构建
373
+ // 可能折出不同结果,快照文本一变宿主就在历史里多留一份副本。
374
+ const passed = new Map()
375
+ let cursor = 0
376
+ const worker = async () => {
377
+ while (cursor < candidates.length) {
378
+ const [anchor, ids] = candidates[cursor++]
379
+ let hit
380
+ try {
381
+ hit = await probe(anchor)
382
+ } catch {
383
+ continue // 检索失败就当这个锚点不可用,宁可不成簇
384
+ }
385
+ if (!hit || hit.size === 0) continue
386
+ const covered = ids.filter((id) => hit.has(id)).length
387
+ if (covered / ids.length >= CLUSTER_MIN_RECALL) passed.set(anchor, ids)
388
+ }
389
+ }
390
+ // 注意:worker 数量超过 1 时 probe 会被并发调用,调用方必须能承受并发
391
+ // (插件侧走的是 async 子进程,不是 execFileSync)。
392
+ await Promise.all(Array.from({ length: Math.min(CLUSTER_CONCURRENCY, candidates.length) }, worker))
393
+
394
+ // 按原顺序(成员数从多到少,同数按锚点字典序)重放,确保确定性。
395
+ const verified = candidates
396
+ .filter(([anchor]) => passed.has(anchor))
397
+ .map(([anchor, ids]) => ({ anchor, ids }))
398
+
399
+ const ownerOf = new Map()
400
+ for (const { anchor, ids } of verified) {
401
+ for (const id of ids) if (!ownerOf.has(id)) ownerOf.set(id, anchor)
402
+ }
403
+ // 贪心分配后可能剩单条成员(成员被更大的簇抢走了)。只剩一条的簇没有折叠价值,
404
+ // 把它列出来反而让模型以为「去搜这个词能拿到好几条」,所以退回标题列表。
405
+ const counts = new Map()
406
+ for (const anchor of ownerOf.values()) counts.set(anchor, (counts.get(anchor) || 0) + 1)
407
+ for (const [anchor, count] of [...counts]) {
408
+ if (count >= CLUSTER_MIN_SIZE) continue
409
+ for (const [id, a] of [...ownerOf]) if (a === anchor) ownerOf.delete(id)
410
+ counts.delete(anchor)
411
+ }
412
+ const clusters = [...counts]
413
+ .map(([anchor, count]) => ({ anchor, count }))
414
+ .sort((a, b) => b.count - a.count || a.anchor.localeCompare(b.anchor))
415
+ return { clusters, ownerOf, folded: ownerOf.size }
416
+ }
417
+
250
418
  export async function buildSnapshot(listPlane, options = {}) {
251
419
  const {
252
420
  indexCount = 0, // 0 = 全部标题,不截断
@@ -254,6 +422,9 @@ export async function buildSnapshot(listPlane, options = {}) {
254
422
  decayHalfLifeDays = 30,
255
423
  accessBoost = 80,
256
424
  access = { records: () => ({}) },
425
+ // 主题簇折叠用的检索探针。不传就不折叠,标题原样列出。
426
+ probeAnchor = null,
427
+ cluster = true,
257
428
  } = options
258
429
 
259
430
  const records = []
@@ -298,22 +469,53 @@ export async function buildSnapshot(listPlane, options = {}) {
298
469
  // 而输入顺序一变快照就变、又会让上下文多一份副本。ID 是稳定的。
299
470
  .sort((a, b) => b.score - a.score || String(a.record.id).localeCompare(String(b.record.id)))
300
471
 
301
- const indexByPlane = new Map()
472
+ // 按平面分别渲染索引。
473
+ //
474
+ // 每个平面怎么渲染由 PLANE_INDEX_MODE 决定,不是一刀切:
475
+ // - rules 是「规则类」,规则标题本身就是规则的索引,折叠成 `aurorix×3`
476
+ // 会让人看不出是哪三条规则——等于把硬约束藏起来。所以规则一律纯标题。
477
+ // - long_term / episodic 是经验与过程记录,按主题折叠收益最大,用锚点词。
478
+ //
479
+ // 分组全部在构建时算出来,不落库、不依赖谁事先预处理:同一份库每次算出的
480
+ // 结果都一样,新增一条记录下一次构建就自动归进对应主题。
481
+ let foldedTotal = 0
482
+ const clusterLines = []
483
+ const perPlane = new Map()
302
484
  for (const entry of decay) {
303
- const record = entry.record
304
- if (!indexByPlane.has(record.plane)) indexByPlane.set(record.plane, [])
305
- indexByPlane.get(record.plane).push(record.title || '(无标题)')
485
+ const plane = entry.record.plane
486
+ if (!perPlane.has(plane)) perPlane.set(plane, [])
487
+ perPlane.get(plane).push(entry.record)
306
488
  }
307
489
 
308
- const indexBlock = DECAY_PLANES
309
- .filter((plane) => indexByPlane.has(plane))
310
- .map((plane) => {
311
- const titles = indexByPlane.get(plane)
490
+ for (const plane of DECAY_PLANES) {
491
+ const rows = perPlane.get(plane) || []
492
+ if (rows.length === 0) continue
493
+ const mode = PLANE_INDEX_MODE[plane] || 'cluster'
494
+ const wantCluster = cluster && mode === 'cluster' && typeof probeAnchor === 'function'
495
+
496
+ if (!wantCluster) {
497
+ const titles = rows.map((r) => r.title || '(无标题)')
312
498
  const shown = indexCount > 0 ? titles.slice(0, indexCount) : titles
313
499
  const rest = titles.length - shown.length
314
- return `**${PLANE_LABEL[plane]}**(${titles.length} 条):${shown.join(' | ')}${rest > 0 ? ` …另有 ${rest} 条` : ''}`
315
- })
316
- .join('\n')
500
+ clusterLines.push(`**${PLANE_LABEL[plane]}**(${titles.length} 条):${shown.join(' | ')}${rest > 0 ? ` …另有 ${rest} 条` : ''}`)
501
+ continue
502
+ }
503
+
504
+ const { clusters, ownerOf, folded } = await clusterTitles(rows, probeAnchor)
505
+ foldedTotal += folded
506
+ // 未成簇的条目按原排序列出;它们没有可靠的检索锚点,必须逐条给标题。
507
+ const rest = rows.filter((r) => !ownerOf.has(r.id)).map((r) => r.title || '(无标题)')
508
+ const shownRest = indexCount > 0 ? rest.slice(0, indexCount) : rest
509
+ const restNote = rest.length - shownRest.length
510
+ const clusterNote = clusters.length
511
+ ? `;主题簇 ${clusters.map((c) => `${c.anchor}×${c.count}`).join(' ')}(用该词检索可取回)`
512
+ : ''
513
+ const body = shownRest.length ? `:${shownRest.join(' | ')}` : ''
514
+ const tail = restNote > 0 ? ` …另有 ${restNote} 条` : ''
515
+ clusterLines.push(`**${PLANE_LABEL[plane]}**(${rows.length} 条${clusterNote})${body}${tail}`)
516
+ }
517
+
518
+ const indexBlock = clusterLines.join('\n')
317
519
 
318
520
  const parts = [
319
521
  '### 常驻层(永久全量:soul / profile / explicit)',
@@ -328,6 +530,7 @@ export async function buildSnapshot(listPlane, options = {}) {
328
530
  total: records.length,
329
531
  resident: records.filter((r) => RESIDENT_PLANES.includes(r.plane)).length,
330
532
  index: records.filter((r) => DECAY_PLANES.includes(r.plane)).length,
533
+ folded: foldedTotal,
331
534
  },
332
535
  }
333
536
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aurorix-agentbook",
3
- "version": "1.9.6",
3
+ "version": "1.10.1",
4
4
  "description": "dsh-aurorix-agentbook:给 dsh-go 与 Harness Web 接通 Aurorix 记忆库——原生界面(状态条/胶囊/菜单/面板/保险箱)与 Web 顶栏槽位面板,加宿主侧提示词注入、分层快照与八个工具。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",