dsh-aurorix-agentbook 1.12.1 → 1.13.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/README.md CHANGED
@@ -26,23 +26,15 @@ Harness Web 上,顶部右侧那组操作按钮里会多一个记忆库按钮
26
26
 
27
27
  面板用 iframe 装:页面自己的样式和宿主的互不污染。页面本身允许同源 framing,接口仍然是 `frame-ancestors 'none'`。
28
28
 
29
- ## 每轮自动带上的东西
29
+ ## 自动记忆注入
30
30
 
31
- 插件会往提示词里注入两段:
31
+ 第一条模型请求自动带上完整的分层快照。这里的「全量」是指这份快照,不是整个记忆库的正文:
32
32
 
33
- 1. **协议段落**——告诉模型读用 `aurorix_recall`、写用 `aurorix_remember`,以及什么该写进哪个平面。
34
- 2. **分层快照**——把库压成一段能放进上下文的文本:
35
- - 常驻层(soul / profile / explicit)永久全量正文;
36
- - `rules` 永远逐条列标题:规则名本身就是索引,折成一个词等于把硬约束藏起来;
37
- - `long_term` / `episodic` 按「平面基准 + 使用加成 − 时间衰减」排序,标题交给
38
- `abook memory themes` 聚成主题簇,同一主题的若干条折成一个标签加条数;
39
- - 没折进簇的条目逐条列标题,一条都不会消失。
33
+ - `soul` / `profile` / `explicit` 提供常驻正文;`rules` 保留逐条标题。
34
+ - `long_term` / `episodic` 用 A++ 标题句云折叠,未折叠的记录仍按其平面给出标题。
35
+ - 记忆库未变时不会追加记忆消息。库变化后只追加新增、替换和移除的部分。若压缩后当前上下文丢了完整基线或必要的更新,则自动补一份当前快照,摘要中引用的旧标识不算基线。
40
36
 
41
- 快照里每个主题带短编号,展开命令也印在同一份快照里。把其中的「编号」替换成 `#` 后的数字,交给 `aurorix_abook`。它精确返回该簇的成员,不走关键词召回;若快照已变更,旧编号会明确报失效。
42
-
43
- 在默认配置下,主题簇直接替换模型快照里的一组标题,不需要另开面板。跨平面的主题放在共同的句云区;未折叠的记录仍在各自平面逐条列出。主题过时或使用不带该能力的自定义后端时,可用普通召回找原文。
44
-
45
- 分组只在库变化时重算;库没变就复用快照。
37
+ 正常使用不需要手动刷新。`/memory` 和 `/memory refresh` 仍可查看状态、重读本机库。句云按快照里的编号精确展开;主题已失效时可直接召回标题或重新获取主题。
46
38
 
47
39
  ## 后端二进制
48
40
 
package/lib/curation.js CHANGED
@@ -1,105 +1,37 @@
1
- // 记忆整理范式:专门给「整理/瘦身/清理/合并记忆」这类作业用。
2
- // 与日常写入分开——日常写入不做质检,整理才做。
3
- export const CURATION_MANUAL = [
4
- "# 记忆库整理手册",
5
- "",
6
- "这份手册面向**一次专门的整理作业**:把记忆库从「堆着」变成「能用」。不是日常写入,是定期维护。",
7
- "",
8
- "## 什么时候该整理",
9
- "",
10
- "命中任一再动手,否则别动——日常使用中看到的乱,多半是正常的:",
11
- "",
12
- "- 用户明确要求整理、瘦身、清理、合并记忆",
13
- "- 常驻层(soul / profile / explicit)明显变大,每轮注入成本上升",
14
- "- 发现同一条事实在多个平面重复,或两条互相矛盾",
15
- "- 检索时明明有相关记录却排不上来(标题不准确)",
16
- "- 明确知道某条记录已过时",
17
- "",
18
- "**不该整理的信号**:库里有重复、粗糙、互相矛盾的条目是正常状态,看到不等于要清。没有明确触发时,不要顺手整理。",
19
- "",
20
- "## 整理前必须先读完",
21
- "",
22
- "不做这一步就动手,等于把用户的资产按猜测重排。",
23
- "",
24
- "1. 看整体:`aurorix_abook` 跑 `state`,记下各平面条数与一致性状态",
25
- "2. 通读常驻层:`soul` / `profile` / `explicit` 全量(快照里已有),逐条看内容与长度",
26
- "3. 摸下三层:`rules` / `long_term` / `episodic` 用 `aurorix_abook` 跑 `memory list --plane <p> --limit 200 --json`,不要只凭标题判断",
27
- "4. 标记候选:哪些超大、哪些放错平面、哪些内容重复、哪些过期",
28
- "",
29
- "读不完整理完,不算整理完。",
30
- "",
31
- "## 三阶段",
32
- "",
33
- "### 阶段一:常驻层减重",
34
- "",
35
- "常驻层每轮全量注入,它涨一点,每轮成本涨一点。",
36
- "",
37
- "- 找出 `explicit` 里超过 ~500 字的记录:多半是「用户说要记住」,结果把整段经过塞进来了",
38
- "- 处理:短关键点留在 `explicit`,完整经过用 `aurorix_remember` 写进 `long_term` 或 `episodic`,然后删掉 `explicit` 里的长正文",
39
- "- `soul` 里混进任务细节、`profile` 里混进一次性事件的,同样迁走",
40
- "- 迁完确认:常驻层每条都该是「长期成立的短句」",
41
- "",
42
- "### 阶段二:下三层梳理",
43
- "",
44
- "- **重复**:同一件事多条。合并(`memory merge`),保留信息最全的那条,把其余的有用细节并进去",
45
- "- **矛盾**:两条说法冲突。先判断哪条有更新的证据;能判就合并并写明「后来的判断是 X,早期记的是 Y」;判不了就保留两条并在正文里标明分歧,不要擅自选一个删掉另一个",
46
- "- **过时**:明确知道已失效的。不要硬删,改写成历史记录(「曾用 A 方案,X 之后改成 B」),保留演进痕迹",
47
- "- **放错平面**:工作原则在 `long_term` → 提到 `soul`;用户偏好散在 `long_term` → 提到 `profile`;单次事件在 `long_term` → 移到 `episodic`",
48
- "- **标题不准**:标题只概括这条记录在讲什么,用白话。不写用途、不写适用场景、不写「何时该读」",
49
- "",
50
- "### 阶段三:提纯反哺",
51
- "",
52
- "只把**跨任务稳定**的结论提炼上去:",
53
- "",
54
- "- 反复验证过的 AI 行为原则 → `soul`",
55
- "- 稳定的用户偏好、称呼、环境事实 → `profile`",
56
- "- 一次性事件、未验证的推测 → 不上提",
57
- "",
58
- "上提时写短:一条原则一段话,超过 300 字说明提得太细,还在描述过程而非原则。",
59
- "",
60
- "## 具体命令",
61
- "",
62
- "全部通过 `aurorix_abook` 跑,或 `aurorix_remember` 写:",
63
- "",
64
- "```",
65
- "list memory list --plane <平面> --limit 200 --json 看一圈(别只看标题)",
66
- "read memory read <id> 读全文",
67
- "update memory update <id> --expect-revision N 改标题/正文/字段",
68
- "merge memory merge <主> <被并入> --expect-revision A --expect-into-revision B",
69
- "move_plane memory move_plane <id> --to-plane <平面> --expect-revision N",
70
- "split memory split <id> --separator <分隔符> --expect-revision N",
71
- "delete memory delete <id> --expect-revision N 软删,可恢复",
72
- "restore memory restore <id> --expect-revision N",
73
- "state / reconcile / doctor 改完核对",
74
- "```",
75
- "",
76
- "**先读后改,带 `--expect-revision`**:不带的话,两个动作之间别人改了库,你的写入会盖掉它。",
77
- "",
78
- "## 安全边界",
79
- "",
80
- "- 删除一律走软删(`memory delete`),**不做物理删除**。墓碑保留,能恢复",
81
- "- 合并只在正文一致或能明确判断时才做;拿不准就保留两条并标注关系",
82
- "- 一次只处理一个平面,改完立刻核对,别攒一大批最后一起改",
83
- "- 动手前先跑一次 `state` 记下基线条数,整理完对照,数字对不上要查",
84
- "- **不碰凭据平面**:`credentials` 走专用入口,不进普通整理",
85
- "",
86
- "## 验收",
87
- "",
88
- "整理完逐项核对,缺一项不算完成:",
89
- "",
90
- "1. `state` 的一致性通过,条数变化能解释(合并少了 N 条、软删 M 条、迁移没变数量)",
91
- "2. 常驻层没有超长记录、没有混入整段经过",
92
- "3. 被合并/移动的记录 ID 都还在(软删可恢复)",
93
- "4. 抽查 5 条改过的记录,读全文确认内容没丢",
94
- "5. 向用户报告:**结构变化**(哪些平面增减)、**处置明细**(合并/迁移/软删各多少)、**矛盾怎么裁决的**",
95
- "",
96
- "报告不能只报数量。用户要看的是「你动了什么、为什么」。",
97
- "",
98
- "## 常见错误",
99
- "",
100
- "- **只凭标题判断**:标题只有几十字,正文可能完全不同的事",
101
- "- **顺手整理**:没有明确触发就动手,把用户熟悉的记录改得认不出来",
102
- "- **硬删**:直接物理删除,用户想恢复时找不到",
103
- "- **一次改太多**:出问题时无法定位是哪一步搞坏的",
104
- "- **把摘要当正文**:列表给的是 preview,改之前必须 `read` 全文",
105
- ].join('\n')
1
+ // 按需工具入口;整理规则不进入每轮提示词正文。
2
+ export const CURATION_MANUAL = `# 记忆整理规范
3
+
4
+ ## 触发与范围
5
+
6
+ 仅在用户或其外部自动任务明确要求「记忆整理」「整理记忆库」或同等操作时执行。正常聊天、注入或发现重复不触发整理,不代建或修改调度。用户指定范围优先。默认全量复核活跃的 soul、profile、explicit;下三层 rules、long_term、episodic 只审用户时区内昨天与今天的新增活跃条目。按 created_at 和自然日判定(昨天零点含、明天零点不含),不按最近 48 小时、更新时间或文件时间。窗口外只查相关的重复、冲突、引用,不顺手改写;范围不明的项目记录先保留。
7
+
8
+ ## 读库与基线
9
+
10
+ 用 state 记下各平面活动条数,以及常驻标题和正文的字节量。用 memory list --plane <平面> --limit 50 --offset <偏移> --full --json,按 total 翻完所需清单;逐条核对正文和创建时间。改前用 memory read --id <ID> --json 回读最新版与修订号,不把摘要或提示词快照当原文。
11
+
12
+ ## 阶段一:常驻全量复核
13
+
14
+ - soul:助手跨任务稳定的身份、风格、工作原则。
15
+ - profile:反复有用的稳定用户偏好、称呼、环境事实。
16
+ - explicit:用户明确点名要记住的短要点、决策、约定;用户明确锁定完整原话时保留原话。
17
+
18
+ 错层则迁到正确平面,混合条目拆分。重复原则熔成一条最短可执行表达;不同条件、优先级或例外不是重复,不删独有信息。无独立价值、引用、证据或用户保留要求的填充内容可软删;有价值但不必每轮读的,拆到下三层:硬约束正本归 rules、可复用知识归 long_term、事件经过和证据归 episodic。先验证去处和引用,再处置旧条。拿不准就保留。
19
+
20
+ ## 阶段二:新增筛查与凭据归位
21
+
22
+ 读下三层窗口内每条正文,决定保留、改写或合并、凭据迁入、提炼候选。只合并同一事实;标题同名不等于事实同一。冲突先看版本、设备、适用条件和证据;确有改判时保留原判断与原因,不能裁决则标明分歧。标题自然、准确,只概括主题,不替读者判断何时召回。
23
+
24
+ 真实口令、私钥、令牌、恢复码、含认证的连接串进独立保险箱;普通配置、公共标识和占位符不进。用 vault ls 查标识与用途,同名归属不明时不覆盖。用 vault put <标识> --purpose <用途> --stdin 安全写入,并用受控 vault get 回读、比对,只对外给验证结果。成功后将普通条目中的明文替换为标识和用途,保留非秘密事实,检查标题、正文、附件与索引;纯凭据条也先去明文再考虑软删。回读无法验证时不移除唯一原件,记录阻断;已有同一正本不重复写。软删不等于清除明文;不在回复、报告、临时文件或新增备份里复制凭据,历史残留另行标记。
25
+
26
+ ## 阶段三:严格上提
27
+
28
+ 同时满足才进入常驻层:严格符合目标平面、证据清楚且长期稳定、跨任务反复影响决策、按需召回不足、没有被现有常驻条目覆盖。explicit 还须用户明确点名。优先更新已有短结论,只写每轮必须看到的内容,证据、示例和经过留在原层。一次性事件、未经验证的推测和仅对一个项目有用的细节不上提;本轮没有合格候选就不新增。
29
+
30
+ ## 具体命令与安全边界
31
+
32
+ 通过 aurorix_abook 调用六平面接口,不用旧候选/晋升流程。更新用 memory update --id <ID> --expect-revision N;迁移用 memory move-plane --id <ID> --to-plane <平面> --expect-revision N;合并用 memory merge --id <源ID> --into <目标ID> --expect-revision A --expect-into-revision B(合并后回读,重排正文而不是简单拼接);删除只用 memory delete --id <ID> --expect-revision N 软删。先读后写、小批复核;修订冲突则回读再判,不照旧参数强行重试。保护用户锁定条目、原始证据、附件和引用。
33
+
34
+ ## 验收
35
+
36
+ 用 state、reconcile 对账。复读常驻全文,核对职责正确、必要限定与锁定原文未丢;检查移动后的 ID、正文、附件与链接,合并的保留条和源条状态,及凭据回读与普通层去明文结果。汇报时区与范围、各平面条数及常驻体积的前后变化,说明合并、错层迁移、下放、上提、软删、凭据迁入、未处置和分歧的依据,不报凭据值。体积持平或增长要说明原因,不为减字丢信息。实际整理结束后留一条不含秘密的 episodic 摘要。
37
+ `.trim()
package/lib/host.js CHANGED
@@ -9,6 +9,7 @@ import { spawn } from 'node:child_process'
9
9
  import { delimiter, dirname, join } from 'node:path'
10
10
  // 二进制真实存在的 attach 子命令只有这五个:sync/refs 是别处的命令,放这里会静默出错。
11
11
  const ATTACH_ACTIONS = ['list', 'add', 'get', 'rm', 'path', 'check']
12
+ const SNAPSHOT_SECTION = 'aurorix-memory-snapshot'
12
13
  const describeCache = { at: 0, value: undefined }
13
14
 
14
15
  /** 能力地图:可只取一组,也可取全部。 */
@@ -57,6 +58,7 @@ import {
57
58
  librarySignature,
58
59
  } from './snapshot.js'
59
60
  import { createThemeClient, SNAPSHOT_THEME_ARGS } from './theme.js'
61
+ import { expandThemeId, memoryContribution, MEMORY_CONTEXT } from './memory-context.js'
60
62
  import { GUIDE, GUIDE_INDEX } from './guide.js'
61
63
  import { CURATION_MANUAL } from './curation.js'
62
64
  import { COMMAND_GROUPS, capabilityText, describeAll, driftOf } from './capability.js'
@@ -150,6 +152,7 @@ export function attachHost(ctx, deps) {
150
152
  }
151
153
 
152
154
  const doRefresh = async (current) => {
155
+ const startSignature = librarySignature(libraryRoot())
153
156
  try {
154
157
  // 主题簇由二进制算(`memory themes`),插件不再自己按锚点词跑几十次检索。
155
158
  // 只在库变化重建时跑一次,约半秒;库没变时整条刷新链根本不会走到这里。
@@ -168,11 +171,12 @@ export function attachHost(ctx, deps) {
168
171
  })
169
172
  snapshot.text = built.text
170
173
  snapshot.stats = built.stats
174
+ snapshot.projection = built.projection
171
175
  snapshot.themeRefs = built.themeRefs
172
176
  snapshot.error = ''
173
177
  snapshot.fetchedAt = Date.now()
174
- // 记下这份文本对应的库指纹:下次库没变就不用重建。
175
- snapshot.signature = librarySignature(libraryRoot())
178
+ // 不把构建途中写入的新版指纹贴到先前读到的内容上。
179
+ snapshot.signature = startSignature
176
180
  } catch (error) {
177
181
  snapshot.error = String(error?.message ?? error)
178
182
  }
@@ -212,6 +216,17 @@ export function attachHost(ctx, deps) {
212
216
  void refresh()
213
217
  }
214
218
 
219
+ const prepareSnapshot = async () => {
220
+ // 加入预热中的刷新。一次刷新期间如果又有写入,再尝试读取新版本;
221
+ // 避免持续并发写入把正常对话永久挂住。
222
+ if (!backend || disposed || !cfg().enabled || !cfg().injectSnapshot) return
223
+ if (inflight || !snapshot.text || snapshot.signature !== librarySignature(libraryRoot())) {
224
+ await (inflight ?? refresh())
225
+ if (disposed || snapshot.error || !cfg().enabled || !cfg().injectSnapshot) return
226
+ if (snapshot.signature !== librarySignature(libraryRoot())) await refresh()
227
+ }
228
+ }
229
+
215
230
  const snapshotText = () => {
216
231
  const current = cfg()
217
232
  if (!current.enabled || !current.injectSnapshot) return ''
@@ -261,25 +276,69 @@ export function attachHost(ctx, deps) {
261
276
  text: () => (cfg().enabled ? cfg().manual : ''),
262
277
  })
263
278
  : undefined
264
- // 快照走 section 而不是 context:
265
- // 宿主的 context 是「追加一条 user/message」,只有文本完全不变才不追加,
266
- // 所以快照一变就在对话里永久多出一份。实测一个长会话里累积了 35 份 × 60KB,
267
- // 每次请求都把 2MB 陈年副本重发一遍。
268
- // section 进的是 system/message,宿主用 replace 原地覆盖,永远只保留一份。
279
+ const hasSurface = (context) => typeof context?.agent?.session?.deriveMessages === 'function'
280
+ const historySupported = typeof scope.systemPrompt.context === 'function'
281
+ && typeof scope.systemPrompt.refreshContext === 'function' && typeof scope.on === 'function'
282
+ const acceptedOthers = new WeakMap()
283
+ const currentOthers = (context) => {
284
+ const accepted = acceptedOthers.get(context.agent)
285
+ if (!accepted) return undefined
286
+ // Refresh only other contributions. Ours is optional, so the host will
287
+ // not add it back and this cannot recurse into our own provider.
288
+ const { contexts } = scope.systemPrompt.refreshContext(accepted, context)
289
+ const others = []
290
+ for (const { name, text, interpolate } of contexts) {
291
+ if (!text) continue
292
+ if (interpolate !== false && text.includes('{{')) return undefined
293
+ others.push({ name, text })
294
+ }
295
+ return others
296
+ }
297
+ const offHistory = cfg().injectSnapshot && historySupported
298
+ ? scope.systemPrompt.context({
299
+ name: MEMORY_CONTEXT,
300
+ order: 900,
301
+ interpolate: false,
302
+ text: (context) => {
303
+ if (!hasSurface(context) || !cfg().enabled || !cfg().injectSnapshot || !snapshot.projection) return ''
304
+ // Host re-evaluates this at admission, after pressure/model-switch/retry compaction.
305
+ return memoryContribution(context.agent.session.deriveMessages(), snapshot.projection, () => currentOthers(context))
306
+ },
307
+ })
308
+ : undefined
269
309
  const offContext = cfg().injectSnapshot
270
310
  ? scope.systemPrompt.section({
271
- name: 'aurorix-memory-snapshot',
272
- // 排在最后:改它只会让系统提示词的尾部失效,前面的大段前缀仍可命中缓存。
311
+ name: SNAPSHOT_SECTION,
273
312
  order: 900,
274
313
  interpolate: false,
275
- text: () => {
314
+ text: (context) => {
315
+ if (offHistory && hasSurface(context)) return ''
276
316
  refreshIfStale()
277
317
  return snapshotText()
278
318
  },
279
319
  })
280
320
  : undefined
321
+ // section.text 是同步的;宿主组装提示词的事件才会等待异步工作。
322
+ const offPrepare = offContext && typeof scope.on === 'function'
323
+ ? scope.on('system-prompt/assemble', async (assembly, _context, next) => {
324
+ const rendered = await next()
325
+ if (!rendered.sections.some((section) => section.name === SNAPSHOT_SECTION)) return rendered
326
+ await prepareSnapshot()
327
+ _context.signal?.throwIfAborted()
328
+ if (offHistory && hasSurface(_context)) {
329
+ acceptedOthers.set(_context.agent, { ...rendered, contexts: rendered.contexts.filter((section) => section.name !== MEMORY_CONTEXT) })
330
+ return rendered
331
+ }
332
+ return {
333
+ ...rendered,
334
+ sections: rendered.sections.map((section) => section.name === SNAPSHOT_SECTION
335
+ ? { ...section, text: snapshotText() }
336
+ : section),
337
+ }
338
+ })
339
+ : undefined
281
340
  return () => {
282
- for (const dispose of [offSection, offManual, offContext]) {
341
+ for (const dispose of [offPrepare, offSection, offManual, offContext, offHistory]) {
283
342
  try {
284
343
  if (typeof dispose === 'function') dispose()
285
344
  } catch {
@@ -453,6 +512,11 @@ export function attachHost(ctx, deps) {
453
512
  // `capability` 不是 abook 的子命令,是插件的内置能力地图:
454
513
  // 直接调用会被 abook 判成未知命令,所以在这里先拦下来。
455
514
  let argv = Array.isArray(args.argv) ? args.argv.map((x) => String(x)) : []
515
+ if (argv[0] === 'theme-open-id') {
516
+ const id = argv.length === 2 ? expandThemeId(argv[1]) : ''
517
+ if (!id) return { code: 2, text: '用法:theme-open-id <句云展开编号>' }
518
+ argv = ['theme-members', ...SNAPSHOT_THEME_ARGS, '--cluster', id, '--json']
519
+ }
456
520
  if (argv[0] === 'theme-open') {
457
521
  const refs = snapshot.themeRefs
458
522
  if (argv.length !== 3 || !/^[1-9][0-9]*$/.test(argv[2])) {
@@ -523,6 +587,8 @@ export function attachHost(ctx, deps) {
523
587
  return { text: '找不到 abook,取不了规范。确认 ~/AgentsBook/abook 存在。' }
524
588
  }
525
589
  const name = typeof args.name === 'string' ? args.name.trim() : ''
590
+ // 与 aurorix_curate 共用同一份;用户自带旧版 abook 时也不退回旧整理约定。
591
+ if (name === 'curation') return { text: CURATION_MANUAL }
526
592
  const result = await backend.raw(name === '' ? ['spec'] : ['spec', name])
527
593
  if (result.ok === false && result.reason !== undefined) {
528
594
  return { text: `拒绝执行:${result.reason}` }
@@ -0,0 +1,145 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ export const MEMORY_CONTEXT = 'aurorix-memory-history'
4
+ const schema = 1
5
+ const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 24)
6
+ const key = (row) => JSON.stringify(row.slice(0, 2))
7
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0
8
+ const ordered = (map) => Array.from(map.values()).sort((a, b) => compare(key(a), key(b)))
9
+ const versionOf = (map) => digest(ordered(map))
10
+ const rowKinds = new Set(['soul', 'profile', 'explicit', 'rules', 'long_term', 'episodic', 'theme', 'status'])
11
+ const contextFormat = '记忆数据不属于用户新消息。只用最新全量及其后同一基线的差量;其他运行时消息不会清除或取代记忆。put/drop 按平面分组:以每条首项为键,drop 删,put 新增或替换,未变照旧。soul/profile/explicit 含标题和正文;rules/long_term/episodic 为标题(同名条数省略即 1);theme 为句云,可用 aurorix_abook ["theme-open-id","编号"] 展开。'
12
+
13
+ /** Use only the host-owned contribution from messages actually retained for this request. */
14
+ function frames(messages) {
15
+ const found = []
16
+ for (const message of messages) {
17
+ if (message?.role !== 'user' || message.source?.kind !== 'runtime-context') continue
18
+ const sections = message.source.sections
19
+ if (!Array.isArray(sections)) continue
20
+ for (const section of sections) {
21
+ if (section.name !== MEMORY_CONTEXT || typeof section.text !== 'string') continue
22
+ // Section provenance alone is not enough if a projection redacted its contents.
23
+ if (!message.content?.some((part) => part.type === 'text' && part.text.includes(section.text))) continue
24
+ const [header, payload] = section.text.split('\n', 2)
25
+ const m = /^\[aurorix-memory (full|delta) ([0-9a-f]{24})\]$/.exec(header)
26
+ if (!m || !payload) continue
27
+ try {
28
+ const data = JSON.parse(payload)
29
+ if (data?.schema === schema) found.push({ mode: m[1], revision: m[2], data })
30
+ } catch { /* 不完整的帧不是注入证据。 */ }
31
+ }
32
+ }
33
+ return found
34
+ }
35
+
36
+ const group = (rows, drop = false) => Object.fromEntries([...rowKinds].flatMap((plane) => {
37
+ const entries = rows.filter((row) => row[0] === plane).map((row) => drop ? row[1] : row.slice(1))
38
+ return entries.length === 0 ? [] : [[plane, entries]]
39
+ }))
40
+
41
+ function apply(map, { put, drop }) {
42
+ if (!put || Array.isArray(put) || typeof put !== 'object' || !drop || Array.isArray(drop) || typeof drop !== 'object') return false
43
+ for (const [plane, keys] of Object.entries(drop)) {
44
+ if (!rowKinds.has(plane) || !Array.isArray(keys)) return false
45
+ for (const id of keys) {
46
+ if (typeof id !== 'string' || !map.delete(JSON.stringify([plane, id]))) return false
47
+ }
48
+ }
49
+ for (const [plane, entries] of Object.entries(put)) {
50
+ if (!rowKinds.has(plane) || !Array.isArray(entries)) return false
51
+ for (const entry of entries) {
52
+ if (!Array.isArray(entry) || entry.length === 0 || typeof entry[0] !== 'string') return false
53
+ const row = [plane, ...entry]
54
+ map.set(key(row), row)
55
+ }
56
+ }
57
+ return true
58
+ }
59
+
60
+ function retained(messages) {
61
+ const available = frames(messages)
62
+ const start = available.findLastIndex((frame) => frame.mode === 'full')
63
+ if (start < 0) return null
64
+ let version = available[start].revision
65
+ const baseline = version
66
+ const rows = new Map()
67
+ const full = available[start].data
68
+ if (!apply(rows, full) || versionOf(rows) !== version) return null
69
+ let lastDelta
70
+ for (const { data, revision } of available.slice(start + 1)) {
71
+ const frame = JSON.stringify([revision, data])
72
+ if (frame === lastDelta) continue
73
+ if (data.base !== baseline || data.from !== version || !apply(rows, data) || versionOf(rows) !== revision) return null
74
+ version = revision
75
+ lastDelta = frame
76
+ }
77
+ return { rows, baseline, version }
78
+ }
79
+
80
+ function renderFull({ rows, revision }) {
81
+ return `[aurorix-memory full ${revision}]\n${JSON.stringify({ schema, put: group(ordered(rows)), drop: {} })}\n${contextFormat}`
82
+ }
83
+
84
+ export function memoryFrame(messages, projection) {
85
+ const previous = retained(messages)
86
+ const { rows, revision } = projection
87
+ if (previous?.version === revision) return ''
88
+ if (!previous) return renderFull(projection)
89
+ const drop = ordered(previous.rows).filter((row) => !rows.has(key(row)))
90
+ const put = ordered(rows).filter((row) => JSON.stringify(row) !== JSON.stringify(previous.rows.get(key(row))))
91
+ return `[aurorix-memory delta ${revision}]\n${JSON.stringify({ schema, base: previous.baseline, from: previous.version, put: group(put), drop: group(drop, true) })}`
92
+ }
93
+
94
+ // DSH compares the combined context against its last retained message. Returning
95
+ // blank for an unchanged contribution would create a second, "cleared" message.
96
+ // Reuse the exact old text only when it will leave the whole envelope unchanged.
97
+ export function memoryContribution(messages, projection, currentOthers) {
98
+ const pending = memoryFrame(messages, projection)
99
+ if (pending) return pending
100
+ const tail = messages.findLast((message) => message?.source?.kind === 'runtime-context')
101
+ const sections = tail?.source?.sections
102
+ if (!Array.isArray(sections)) return ''
103
+ const old = sections.find((section) => section.name === MEMORY_CONTEXT)
104
+ if (!old?.text || !tail.content?.some((block) => block.type === 'text' && block.text.includes(old.text))) return ''
105
+ const others = sections.filter((section) => section.name !== MEMORY_CONTEXT)
106
+ const current = currentOthers()
107
+ if (!current || JSON.stringify(others) !== JSON.stringify(current)) return ''
108
+ return old.text
109
+ }
110
+
111
+ const stableResidentKey = (id) => createHash('sha256').update(String(id)).digest().subarray(0, 9).toString('base64url')
112
+ export function projectMemory({ resident, titles, themes, status, maxContextBytes = 96000 }) {
113
+ const rows = resident.map((r) => [r.plane, stableResidentKey(r.id), r.title || '(无标题)', String(r.content || '').trim()])
114
+ for (const [name, text] of status) rows.push(['status', name, text])
115
+ for (const { id, phrase } of themes) {
116
+ if (/^theme-[a-f0-9]{12}$/.test(id)) rows.push(['theme', Buffer.from(id.slice(6), 'hex').toString('base64url'), phrase])
117
+ }
118
+ for (const [plane, shown] of titles) {
119
+ const counts = new Map()
120
+ for (const title of shown) counts.set(title, (counts.get(title) ?? 0) + 1)
121
+ for (const [title, count] of counts) rows.push(count === 1 ? [plane, title] : [plane, title, count])
122
+ }
123
+ const projected = (chosen) => {
124
+ const byKey = new Map(chosen.map((row) => [key(row), row]))
125
+ return { rows: byKey, revision: versionOf(byKey) }
126
+ }
127
+ const full = projected(rows)
128
+ if (Buffer.byteLength(renderFull(full)) <= maxContextBytes) return full
129
+
130
+ // 遵守快照预算但不切断任何 JSON/正文;缺少部分显式说明仍可召回。
131
+ const limited = (n) => projected([...rows.slice(0, n), ['status', 'budget', '索引达到注入上限;未显示的内容可检索。']])
132
+ let low = 0
133
+ let high = rows.length
134
+ while (high - low > 1) {
135
+ const mid = Math.floor((low + high) / 2)
136
+ if (Buffer.byteLength(renderFull(limited(mid))) <= maxContextBytes) low = mid
137
+ else high = mid
138
+ }
139
+ return limited(low)
140
+ }
141
+
142
+ export function expandThemeId(code) {
143
+ if (!/^[A-Za-z0-9_-]{8}$/.test(code)) return ''
144
+ return `theme-${Buffer.from(code, 'base64url').toString('hex')}`
145
+ }
package/lib/snapshot.js CHANGED
@@ -11,6 +11,7 @@
11
11
  import { createHash } from 'node:crypto'
12
12
  import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
13
13
  import { dirname, join } from 'node:path'
14
+ import { projectMemory } from './memory-context.js'
14
15
 
15
16
  export const RESIDENT_PLANES = ['soul', 'profile', 'explicit']
16
17
  export const DECAY_PLANES = ['rules', 'long_term', 'episodic']
@@ -92,7 +93,7 @@ export const DEFAULT_MANUAL = [
92
93
  "",
93
94
  "### 关于下面那份快照",
94
95
  "",
95
- "它每轮重发、不留在历史里,所以对话被压缩之后照样在。",
96
+ "新对话自动附上完整的分层快照;有完整基线时仅附记忆变化。压缩后若基线或必要更新不在当前上下文,会自动补全。没有新记忆消息时,继续使用仍在上下文中的基线和更新。",
96
97
  "",
97
98
  "常驻层保留正文,规则逐条列标题。长期经验和事件的标题按句云折叠,未折叠的标题仍单列。句云按快照中的命令展开,其他标题可用 `aurorix_recall` 找记录,再读正文。采用前核对正文里的版本与适用范围。",
98
99
  ].join('\n')
@@ -334,8 +335,9 @@ export async function buildSnapshot(listPlane, options = {}) {
334
335
  const now = Math.floor(Date.now() / 1000)
335
336
 
336
337
  // 常驻层:全量正文。这几层是身份、画像和用户明确交代的短要点,每轮都该看得见全文。
338
+ const residentRows = RESIDENT_PLANES.flatMap((plane) => records.filter((r) => r.plane === plane).slice(0, residentLimit))
337
339
  const resident = RESIDENT_PLANES.map((plane) => {
338
- const rows = records.filter((r) => r.plane === plane).slice(0, residentLimit)
340
+ const rows = residentRows.filter((r) => r.plane === plane)
339
341
  if (rows.length === 0) return ''
340
342
  const body = rows.map((r) => `- 【${r.title || '(无标题)'}】${String(r.content || '').trim()}`).join('\n')
341
343
  return `**${PLANE_LABEL[plane]}**(${rows.length} 条)\n${body}`
@@ -394,7 +396,25 @@ export async function buildSnapshot(listPlane, options = {}) {
394
396
  indexBlock,
395
397
  ].filter((part) => part && part.length > 0)
396
398
 
399
+ const covered = useFolded ? selected.ownerOf : new Map()
400
+ const projectionTitles = []
401
+ const projectionStatus = []
402
+ for (const [plane, rows] of perPlane) {
403
+ const all = rows.filter((r) => !covered.has(String(r.id))).map((r) => r.title || '(无标题)')
404
+ const shown = indexCount > 0 ? all.slice(0, indexCount) : all
405
+ projectionTitles.push([plane, shown])
406
+ if (shown.length < all.length) projectionStatus.push([plane, `另有 ${all.length - shown.length} 条,可检索`])
407
+ }
408
+ if (failure) projectionStatus.push(['theme', failure])
409
+
397
410
  return {
411
+ projection: projectMemory({
412
+ resident: residentRows,
413
+ titles: projectionTitles,
414
+ themes: useFolded ? selected.folds : [],
415
+ status: projectionStatus,
416
+ maxContextBytes: options.maxContextBytes,
417
+ }),
398
418
  themeRefs: useFolded ? { stamp, ids } : null,
399
419
  text: clampBytes(parts.join('\n\n'), options.maxContextBytes ?? 96000),
400
420
  stats: {
package/lib/words.js CHANGED
@@ -50,7 +50,7 @@ export const WORDS = {
50
50
  injectRefresh: '立即重建',
51
51
  injectCopied: '已复制本份注入全文',
52
52
  injectDetail: '查看注入全文',
53
- injectHint: '这份内容作为对话尾部的一条快照消息送给模型,不进系统提示词前缀;内容没变就不会追加新消息,缓存不会被顶掉。',
53
+ injectHint: '没有全量基线时自动补快照;基线仍在时只发送记忆变化。',
54
54
  injectNoteOnTurn: (kb) => `记忆注入 ${kb} KB`,
55
55
  copied: '已复制',
56
56
  copy: '复制正文',
@@ -177,7 +177,7 @@ export const WORDS = {
177
177
  injectRefresh: 'Rebuild now',
178
178
  injectCopied: 'Snapshot copied',
179
179
  injectDetail: 'View full snapshot',
180
- injectHint: 'This goes to the model as one snapshot message at the tail of the conversation, not into the system prefix; an unchanged snapshot adds no message, so the cache survives.',
180
+ injectHint: 'A full snapshot is added when its baseline is missing; otherwise only library changes are added.',
181
181
  injectNoteOnTurn: (kb) => `Memory ${kb} KB`,
182
182
  copied: 'Copied',
183
183
  copy: 'Copy body',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aurorix-agentbook",
3
- "version": "1.12.1",
3
+ "version": "1.13.0",
4
4
  "description": "dsh-aurorix-agentbook:给 dsh-go 与 Harness Web 接通 Aurorix 记忆库——原生界面(状态条/胶囊/菜单/面板/保险箱)与 Web 顶栏槽位面板,加宿主侧提示词注入、分层快照与八个工具。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",