dsh-aurorix-agentbook 1.9.2 → 1.9.4

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
@@ -54,6 +54,7 @@ import {
54
54
  DEFAULT_MANUAL,
55
55
  DEFAULT_PROTOCOL,
56
56
  resolveStatePath,
57
+ librarySignature,
57
58
  } from './snapshot.js'
58
59
  import { GUIDE, GUIDE_INDEX } from './guide.js'
59
60
  import { CURATION_MANUAL } from './curation.js'
@@ -70,16 +71,20 @@ function readConfig(config) {
70
71
  }
71
72
  return {
72
73
  enabled: get('enabled', true),
73
- injectSection: get('injectSection', true),
74
+ injectSection: get('injectSection', false),
74
75
  injectSnapshot: get('injectSnapshot', true),
75
- fullCount: Number(get('fullCount', 6)) || 6,
76
- briefCount: Number(get('briefCount', 12)) || 12,
77
- indexCount: Number(get('indexCount', 120)) || 120,
76
+ // 这几个数字是「每轮重发的预算」,不是「能放多少」。
77
+ // 快照随每一轮请求重发,所以体积直接乘以轮数:原来 60KB 一份,
78
+ // 长会话里光记忆就吃掉几十万 token。默认收到能在不查库的情况下认得出
79
+ // 「库里有没有相关条目」的最小规模——认不出的部分本来就该走检索。
80
+ fullCount: Number(get('fullCount', 4)) || 0,
81
+ briefCount: Number(get('briefCount', 8)) || 0,
82
+ indexCount: Number(get('indexCount', 30)) || 0,
78
83
  residentLimit: Number(get('residentLimit', 40)) || 40,
79
- briefChars: Number(get('briefChars', 110)) || 110,
84
+ briefChars: Number(get('briefChars', 80)) || 80,
80
85
  decayHalfLifeDays: Number(get('decayHalfLifeDays', 30)),
81
86
  accessBoost: Number(get('accessBoost', 80)),
82
- maxContextBytes: Number(get('maxContextBytes', 96000)) || 96000,
87
+ maxContextBytes: Number(get('maxContextBytes', 48000)) || 48000,
83
88
  refreshMs: Number(get('refreshMs', 15000)) || 15000,
84
89
  toolEnabled: get('toolEnabled', true) !== false,
85
90
  commandEnabled: get('commandEnabled', true) !== false,
@@ -114,6 +119,8 @@ export function attachHost(ctx, deps) {
114
119
  error: '',
115
120
  loading: false,
116
121
  stats: null,
122
+ // 这份文本对应的库指纹。库没变就不重建,避免每轮往对话里追加新快照把缓存顶掉。
123
+ signature: '',
117
124
  }
118
125
  let disposed = false
119
126
  let refreshTimer
@@ -157,14 +164,42 @@ export function attachHost(ctx, deps) {
157
164
  snapshot.stats = built.stats
158
165
  snapshot.error = ''
159
166
  snapshot.fetchedAt = Date.now()
167
+ // 记下这份文本对应的库指纹:下次库没变就不用重建。
168
+ snapshot.signature = librarySignature(libraryRoot())
160
169
  } catch (error) {
161
170
  snapshot.error = String(error?.message ?? error)
162
171
  }
172
+ // 快照建好了要让界面知道:面板可能早就打开过(那时还没东西可显示),
173
+ // 不通知它就会一直停在那句「还没构建过快照」上。
174
+ try {
175
+ deps.onSnapshot?.()
176
+ } catch {
177
+ // 回调是展示用的,出错不该影响注入本身
178
+ }
179
+ }
180
+
181
+ /** 库根:优先用后端解析出来的,配置里显式给了就用配置的。 */
182
+ const libraryRoot = () => {
183
+ const declared = String(backend?.root ?? '')
184
+ return declared
163
185
  }
164
186
 
165
187
  const refreshIfStale = () => {
166
188
  const current = cfg()
167
189
  if (disposed || snapshot.loading) return
190
+ // 指纹先判:库没变就什么都不做——重建会让宿主在对话尾部追加一条新消息,前缀缓存随之失效。
191
+ // 这一步必须在时间节流之前,否则刚写完记忆的十几秒里快照还是旧的,模型读不到新内容。
192
+ const signature = librarySignature(libraryRoot())
193
+ if (snapshot.text && snapshot.signature && snapshot.signature === signature) {
194
+ lastAttempt = Date.now()
195
+ return
196
+ }
197
+ // 库变了就立刻重建,不受 refreshMs 限制:变化的频率本来就低,缓存该换的时候就得换。
198
+ if (snapshot.signature && signature !== snapshot.signature) {
199
+ void refresh()
200
+ return
201
+ }
202
+ // 还没有可用快照(首次或上次失败)时才按 refreshMs 兜节流,避免失败时反复起子进程。
168
203
  const since = snapshot.fetchedAt || lastAttempt
169
204
  if (since && Date.now() - since < current.refreshMs) return
170
205
  void refresh()
@@ -193,8 +228,11 @@ export function attachHost(ctx, deps) {
193
228
  if (backend !== undefined && cfg().injectSnapshot) {
194
229
  void refresh()
195
230
  const interval = Math.max(5000, cfg().refreshMs * 4)
231
+ // 定时器只负责「发现库变了」,不负责重建快照。
232
+ // 直接 refresh() 会无条件重读全库并覆盖字符串:库没变也刷新 fetchedAt,
233
+ // 而快照它一变宿主就多留一份。走 refreshIfStale 才能让「库没变」真的什么都不做。
196
234
  refreshTimer = setInterval(() => {
197
- if (!disposed) void refresh()
235
+ if (!disposed) refreshIfStale()
198
236
  }, interval)
199
237
  if (typeof refreshTimer.unref === 'function') refreshTimer.unref()
200
238
  }
@@ -216,10 +254,16 @@ export function attachHost(ctx, deps) {
216
254
  text: () => (cfg().enabled ? cfg().manual : ''),
217
255
  })
218
256
  : undefined
257
+ // 快照走 section 而不是 context:
258
+ // 宿主的 context 是「追加一条 user/message」,只有文本完全不变才不追加,
259
+ // 所以快照一变就在对话里永久多出一份。实测一个长会话里累积了 35 份 × 60KB,
260
+ // 每次请求都把 2MB 陈年副本重发一遍。
261
+ // section 进的是 system/message,宿主用 replace 原地覆盖,永远只保留一份。
219
262
  const offContext = cfg().injectSnapshot
220
- ? scope.systemPrompt.context({
263
+ ? scope.systemPrompt.section({
221
264
  name: 'aurorix-memory-snapshot',
222
- order: 130,
265
+ // 排在最后:改它只会让系统提示词的尾部失效,前面的大段前缀仍可命中缓存。
266
+ order: 900,
223
267
  interpolate: false,
224
268
  text: () => {
225
269
  refreshIfStale()
@@ -795,5 +839,32 @@ export function attachHost(ctx, deps) {
795
839
  }, 'dsh-aurorix-agentbook commands')
796
840
  })
797
841
 
798
- return { refresh, snapshot: () => snapshot, access }
842
+ /**
843
+ * 注入状态快照:给界面看「这一轮往模型里放了什么」。
844
+ *
845
+ * 只报事实,不做估算:bytes 是真正那段快照的字节数,changed 是「当前库指纹是否
846
+ * 和这份快照对应的指纹不同」——为真时下一轮会重建,缓存也就会换一次。
847
+ */
848
+ const injectInfo = (locale) => {
849
+ const current = cfg()
850
+ const enabled = current.enabled !== false && current.injectSnapshot !== false
851
+ const text = snapshot.text ?? ''
852
+ const bytes = text === '' ? 0 : Buffer.byteLength(text, 'utf8')
853
+ const currentSig = librarySignature(libraryRoot())
854
+ return {
855
+ enabled,
856
+ bytes,
857
+ text,
858
+ error: snapshot.error || undefined,
859
+ stats: snapshot.stats ?? undefined,
860
+ ageSeconds: snapshot.fetchedAt ? Math.max(0, Math.round((Date.now() - snapshot.fetchedAt) / 1000)) : undefined,
861
+ changed: enabled && snapshot.signature !== '' && currentSig !== '' && currentSig !== snapshot.signature,
862
+ tierLabel: snapshot.stats
863
+ ? `${snapshot.stats.resident}常驻/${snapshot.stats.full}全量/${snapshot.stats.brief}摘要/${snapshot.stats.index}索引`
864
+ : '',
865
+ locale: typeof locale === 'string' ? locale : undefined,
866
+ }
867
+ }
868
+
869
+ return { refresh, snapshot: () => snapshot, access, injectInfo, signature: () => librarySignature(libraryRoot()) }
799
870
  }
package/lib/index.js CHANGED
@@ -46,13 +46,18 @@ export function apply(ctx, config) {
46
46
  attachWeb(ctx, { backend, root: settings.root || undefined })
47
47
 
48
48
  // 宿主层(提示词注入、工具、斜杠命令)和界面层共用这一个 backend。
49
- attachHost(ctx, {
49
+ const host = attachHost(ctx, {
50
50
  backend,
51
51
  config,
52
52
  onWrote: () => {
53
53
  // 写完之后界面上的条数也要跟上,下次打开面板就是新数字。
54
54
  for (const scope of states.keys()) publish()
55
55
  },
56
+ // 快照建好/重建后推一次:面板要看真实注入大小,回合脚注也要补发。
57
+ onSnapshot: () => {
58
+ publish()
59
+ for (const push of notePushes) push()
60
+ },
56
61
  })
57
62
 
58
63
  /** 一个面板实例的状态:分层计数、召回、保险箱、详情、草稿。只活在内存里。 */
@@ -103,6 +108,8 @@ export function apply(ctx, config) {
103
108
  /** 按会话各存一份,两个对话不会互相覆盖。 */
104
109
  const states = new Map()
105
110
  const listeners = new Set()
111
+ // 回合脚注各自的推送函数:快照建好后要重发一次,否则先打开的那轮永远是空的。
112
+ const notePushes = new Set()
106
113
 
107
114
  const keyOf = (scope) => (typeof scope?.sessionId === 'string' ? scope.sessionId : '-')
108
115
  const stateOf = (scope) => {
@@ -248,7 +255,25 @@ export function apply(ctx, config) {
248
255
  return { ok: true }
249
256
  }
250
257
 
251
- const patchOf = (scope, locale) => memoryData(stateOf(scope), { locale })
258
+ const patchOf = (scope, locale) => memoryData(withInject(scope), { locale })
259
+ /**
260
+ * 注入状态在取数那一刻同步读,不进共享状态。
261
+ *
262
+ * 早前是「写进 state 再 publish」,但那要依赖两边看到的 scope key 完全一致、
263
+ * 而且异步刷新不能把它覆盖掉;调试时好时坏就是这种时序依赖。面板数据本来就是
264
+ * 每次 emit 现算的,这里现取一个同步值最简单,也不会被别的刷新冲掉。
265
+ */
266
+ const injectNow = () => {
267
+ try {
268
+ return typeof host?.injectInfo === 'function' ? host.injectInfo() : undefined
269
+ } catch {
270
+ return undefined
271
+ }
272
+ }
273
+
274
+ /** 面板数据 = 面板状态 + 此刻的注入状态。 */
275
+ const withInject = (scope) => ({ ...stateOf(scope), inject: injectNow() })
276
+
252
277
  /** 当前详情一共有多少页:编辑态看页数组,阅读态按正文长度算。 */
253
278
  const totalPagesOf = (state) => {
254
279
  if (Array.isArray(state.detailPages) && state.detailPages.length > 0) return state.detailPages.length
@@ -268,7 +293,7 @@ export function apply(ctx, config) {
268
293
  ctx.dshGo.panel('memory-home', {
269
294
  view: (scope, caps) => memoryView(stateOf(scope), caps),
270
295
  data: (scope, emit, caps) => {
271
- const push = () => emit(memoryData(stateOf(scope), caps))
296
+ const push = () => emit(memoryData(withInject(scope), caps))
272
297
  push()
273
298
  listeners.add(push)
274
299
  if (stateOf(scope).loadedAt === undefined) {
@@ -276,6 +301,7 @@ export function apply(ctx, config) {
276
301
  refreshCounts(scope)
277
302
  refreshVault(scope)
278
303
  }
304
+ // 注入状态随每次 emit 现取,这里不用再单独刷一遍。
279
305
  return () => listeners.delete(push)
280
306
  },
281
307
  actions: {
@@ -573,6 +599,32 @@ export function apply(ctx, config) {
573
599
  return { refresh: 'memory-home' }
574
600
  },
575
601
 
602
+ // 看注入全文:单独取,不进面板数据(面板数据上限 32 KB,25 KB 的全文会把整份数据顶爆)。
603
+ 'inject-detail': (scope, event) => {
604
+ const odd = w(event?.locale)
605
+ const info = injectNow()
606
+ const text = String(info?.text ?? '')
607
+ if (text === '') return { toast: odd.injectNever }
608
+ // 走详情页:复制、翻页都是现成的,不用另做一套。
609
+ const pages = splitPages(text)
610
+ update(scope, {
611
+ detail: {
612
+ id: odd.injectTitle,
613
+ kind: 'inject',
614
+ title: odd.injectTitle,
615
+ plane: '',
616
+ readWhen: '',
617
+ updated: '',
618
+ bytes: Buffer.byteLength(text, 'utf8'),
619
+ body: text,
620
+ },
621
+ detailEditing: false,
622
+ detailPage: 0,
623
+ detailPages: pages,
624
+ })
625
+ return { refresh: 'memory-home' }
626
+ },
627
+
576
628
  'detail-copy': (scope, event) => {
577
629
  const odd = w(event?.locale)
578
630
  const detail = stateOf(scope).detail
@@ -609,6 +661,28 @@ export function apply(ctx, config) {
609
661
  return () => clearInterval(timer)
610
662
  })
611
663
 
664
+ // ── 回合脚注:每轮末尾一行,说明这轮往模型里注入了多少 ────────────
665
+ // 用户不必打开面板就知道插件在工作;注入量变了(库变化后重建)这里也能看出来。
666
+ ctx.dshGo.turnNote('memory-inject', (scope, emit, caps) => {
667
+ const show = () => {
668
+ const info = injectNow()
669
+ if (info === undefined || info.enabled !== true) return
670
+ const bytes = Number(info.bytes) || 0
671
+ if (bytes === 0) return
672
+ const kb = Math.max(1, Math.round(bytes / 1024))
673
+ const text = words(caps?.locale).injectNoteOnTurn(kb)
674
+ // 每段最多 16 字,宿主会截;这里自己先截,不让它显示半句。
675
+ if (text.length > 16) return
676
+ const turnId = typeof scope?.turnId === 'string' ? scope.turnId : ''
677
+ if (turnId === '') return
678
+ emit({ [turnId]: { text, tone: info.changed === true ? 'info' : undefined } })
679
+ }
680
+ show()
681
+ notePushes.add(show)
682
+ // 订阅取消时把自己摘掉,别让旧会话的函数一直挂在表里。
683
+ return () => notePushes.delete(show)
684
+ })
685
+
612
686
  // ── 胶囊「查记忆」:把输入框里的词拿去查,结果插回输入框 ──────────
613
687
  ctx.dshGo.on('mem-recall', (scope, event) => {
614
688
  const odd = w(event?.locale)
package/lib/snapshot.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // 规则:常驻层(soul/profile/explicit)永久全量;其余按“平面基准 + 使用加成 -
4
4
  // 时间衰减”排序,按名次分三档(全量正文 / 摘要 / 仅标题)。注入条数固定,
5
5
  // 所以库再大也不会撑爆上下文;没进快照的原文都还在,用检索取回。
6
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
6
+ import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
7
7
  import { dirname, join } from 'node:path'
8
8
 
9
9
  export const RESIDENT_PLANES = ['soul', 'profile', 'explicit']
@@ -28,112 +28,71 @@ const TIER_ORDER = { index: 0, brief: 1, full: 2 }
28
28
 
29
29
  // 每步注入的记忆说明:只在装了本插件的环境里出现。
30
30
  // 系统提示词里不再提记忆——没装插件的环境本就没有这个能力,不该被暗示。
31
+ //
32
+ // 这份文本每轮都发,所以按「每字节都要有用」来写:不解释背景、不重复下面快照里
33
+ // 已有的信息、不写礼貌过渡。曾经的 protocol/manual 两份各说一遍同一件事,
34
+ // 白占 8.4KB,现在合成这一份。
31
35
  export const DEFAULT_MANUAL = [
32
36
  "## 记忆库(Aurorix)",
33
37
  "",
34
- "你有一个跨会话的持久记忆库,由插件接好并每步注入。库根、二进制位置、安装状态都由插件持有,",
35
- "**你不需要知道它在哪、不需要确认装没装、不需要拼 shell、不需要 detect/version/install/upgrade**。",
36
- "",
37
- "### 每步自动到达",
38
- "",
39
- "每次模型调用前,插件会把**常驻层全量正文(soul / profile / explicit)+ 其余平面的分层视图**重新注入一份:",
40
- "rules / long_term / episodic 按重要度、使用频率与时间衰减排成全量正文 / 摘要 / 仅标题三档。",
41
- "这条注入**每步重发、不留在历史里**,所以对话被压缩之后它照样在,不需要谁重新触发,也不会因为轮次变多而失效。",
42
- "只列标题的条目原文都在库里,能检索回来——标题档列出的每一项都是可召回的。",
43
- "",
44
- "### 七个平面(写之前先定平面)",
38
+ "本会话直连一个跨会话记忆库,工具已接好:库根、二进制、安装状态都由插件持有。",
39
+ "**不需要确认装没装、不需要拼 shell、不需要 detect/version/install。**",
45
40
  "",
46
- "- `soul` —— 你自己的稳定身份、行为风格与工作原则",
47
- "- `rules` —— 硬规则,优先级最高,普通经验不得覆盖",
48
- "- `profile` —— 用户的画像、偏好、称呼、交互方式与稳定环境事实",
49
- "- `explicit` —— 用户明确说「记住」的短关键点、决策或约定",
50
- "- `long_term` —— 长期事实、决策、可复用经验",
51
- "- `episodic` —— 按时间记的事件、过程、证据与会话经过",
52
- "- `credentials` —— 凭据保险箱,独立存放,走专用入口,不混进普通检索",
41
+ "### 平面",
53
42
  "",
54
- "### 什么时候主动查(默认动作,不是可选项)",
43
+ "`soul` 自身原则|`rules` 硬规则(最高优先级)|`profile` 用户画像与偏好|`explicit` 用户明说的短要点|`long_term` 长期事实与可复用结论|`episodic` 事件、过程、证据|`credentials` 凭据保险箱(独立入口,不混进普通检索)",
55
44
  "",
56
- "**查记忆是本会话的默认动作:命中下面任一就直接调 `aurorix_recall`,不要先判断「值不值得查」。**",
57
- "检索一次几十毫秒,重复踩一次坑要花掉整轮;成本差着两个数量级,所以不确定时永远选查。",
45
+ "### 查记忆是默认动作,不是可选项",
58
46
  "",
59
- "必查清单:",
47
+ "命中任一条就直接调 `aurorix_recall`,不要先判断「值不值得查」——查一次几十毫秒,重复踩一次坑要花一整轮。",
60
48
  "",
61
- "1. 动手之前——写盘、改代码、改配置、跑命令、构建、发版、迁移",
62
- "2. 用户提到「以前 / 上次 / 之前 / 记得 / 记过 / 我是不是说过」",
63
- "3. 遇到陌生的库、仓库、包、设备、接口、报错原文、陌生路径",
64
- "4. 上下文被压缩过,或这是跨会话/跨任务的续接",
65
- "5. 你正准备说「应该 / 大概 / 一般来说 / 我记得」的时候(这类措辞出现,说明你在凭印象答)",
66
- "6. 要写记忆之前(先查有没有同一条,避免重复开新条)",
49
+ "1. 动手之前:写盘、改代码、改配置、跑命令、构建、发版、迁移",
50
+ "2. 用户说「以前/上次/之前/记得/我是不是说过」",
51
+ "3. 遇到陌生的库、仓库、包、设备、接口、报错原文、路径",
52
+ "4. 上下文被压缩过,或跨会话/跨任务续接",
53
+ "5. 自己要说「应该/大概/一般来说/我记得」时——这说明在凭印象答",
54
+ "6. 写记忆之前(先查有没有同一条)",
67
55
  "",
68
- "路径固定三步:**看快照 → 按话题检索 → 读命中正文**。快照里只有标题的,原文在库里。",
56
+ "**检索永远在大范围搜索之前。** 找不到东西时第一反应不能是扫全盘、`grep -r` 整个仓库或凭印象猜:记忆库里全是这台机器、这套代码、这类报错的既往结论。扫盘最贵,记忆最便宜。记忆里确实没有、或查到已过时,再去扫;扫完把结论写回去。",
69
57
  "",
70
- "禁把这几种说法当跳过理由——它们都不成立:",
58
+ "这些跳过理由都不成立:「这轮很简单」「刚聊过」(那是当前上下文,不是历史结论)「我应该记得」(印象与原文冲突时以库为准)「先做完再查」「先扫一遍再说」。",
71
59
  "",
72
- "- 「这轮很简单」:简单轮正是踩重复坑最多的地方",
73
- "- 「刚聊过」:刚聊过的是当前上下文,不是历史结论",
74
- "- 「我应该记得」:记得的是印象,库里的是原文,两者冲突时以库为准",
75
- "- 「先做完再查」:查完再做,比做完再返工便宜",
60
+ "### 写",
76
61
  "",
77
- "**做完一件有结论的事就顺手写一条**:不是因为用户要求,是因为下轮可能用得上。",
62
+ "**写入不需要任何人批准,做完一件有结论的事就顺手写一条**:宁可多写,也不要让经验随会话消失。值得写的:做了决定(尤其排除了哪些选项、为什么)、被用户纠正、踩坑并查明根因、交付了一个单元、发现某条过时、踩到平台或工具的隐蔽差异。不值得写:寒暄、无未来用途的过程日志。同一事件更新同一条。",
78
63
  "",
79
64
  "### 四个工具",
80
65
  "",
81
- "- **读**:`aurorix_recall` —— 按话题检索,可限定平面与条数。",
82
- "- **写**:`aurorix_remember` —— 按平面写入,写完回读记录 ID。",
83
- "- **任意命令 / 维护**:`aurorix_abook` —— argv 数组直传、不经 shell,能跑全部子命令。",
84
- " 例:`[\"state\"]`、`[\"doctor\"]`、`[\"reconcile\",\"--dry-run\"]`、`[\"memory\",\"list\",\"--plane\",\"rules\",\"--limit\",\"20\"]`。",
85
- " 命令面现取三层:`[\"capability\"]` 拿能力地图(按用途分组,含每组易错点与关键参数位),",
86
- " `[\"describe\",\"<命令>\"]` 拿单条契约(用法、参数面、是否分页/支持 JSON),`[\"commands\"]` 拿全部命令名。",
87
- " **禁凭名字猜命令**:`attach` 的真实子命令只有 list/add/get/rm/path/check,写 `attach sync` 会静默失败。",
88
- " `[\"drift\"]` 核对地图与当前二进制有没有漂移,升级后端后先跑一次。",
89
- "- **规范 / 手册**:`aurorix_spec` 取 plan·ulw·security·compaction·magic·skill·attach·vault·stopbudget·integrity·ui·curation·maintenance·promote;",
90
- " `aurorix_guide` 取本插件的完整手册(tools / preload / write / integrity / maintenance / root 六章)。",
66
+ "- `aurorix_recall` 按话题检索,可限定平面与条数",
67
+ "- `aurorix_remember` 按平面写入,写完回读记录 ID",
68
+ "- `aurorix_abook` 任意子命令,argv 数组直传:`[\"state\"]`、`[\"doctor\"]`、`[\"memory\",\"list\",\"--plane\",\"rules\",\"--limit\",\"20\"]`",
69
+ "- 命令面现取三层,禁凭名字猜:`[\"capability\"]` 能力地图(按用途分组,含易错点)、`[\"describe\",\"<命令>\"]` 单条契约、`[\"commands\"]` 全部命令名。`[\"drift\"]` 核对地图与二进制是否漂移",
70
+ " `attach` 的真实子命令只有 list/add/get/rm/path/check,写 `attach sync` 会静默失败。",
71
+ "- `aurorix_spec` 取规范(plan·ulw·security·compaction·magic·skill·attach·vault·stopbudget·integrity·ui·curation·maintenance·promote);`aurorix_guide` 取插件手册(tools/preload/write/integrity/maintenance/root)",
91
72
  "",
92
- "### 写入规则",
93
- "",
94
- "- 用户说「记住 / 记下来」且是短关键点 → `explicit`",
95
- "- 完整经过、根因、可复用结论 → `long_term`",
96
- "- 单次事件与证据 → `episodic`",
97
- "- 用户稳定偏好、称呼、环境事实 → `profile`",
98
- "- 你自己的稳定行为原则 → `soul`",
99
- "- 硬性约束 → `rules`",
100
- "",
101
- "写入不需要任何人批准,直接写。**宁多写一条,也不要让有用的经验随会话消失。**",
102
- "值得记的:做了决定(尤其排除了别的选项,记下为什么排除)、被用户纠正、踩坑并查明根因、交付了一个单元、发现库里某条过时、踩到平台或工具的隐蔽差异。",
103
- "不值得记的:寒暄、无未来用途的过程日志。同一事件更新同一条,不要重复开新条。",
73
+ "### 输出是证据本体",
104
74
  "",
105
- "### 整理不是随手做的事",
75
+ "`aurorix_abook` 返回的文本就是证据,不是可裁剪的展示。**禁截断**:不接 `head`/`tail`/`cut`/`sed -n 范围`,不做「只看前几行就下结论」。被截断的内容按未读论。超限时工具会整份拒收并给分页建议——改口径(`--limit`/`--page`/`--json`/单条读),不改真值。",
106
76
  "",
107
- "库里有重复、粗糙、互相矛盾的条目是**正常状态**,不是缺陷。看到矛盾要么留着,要么在明确接到整理指令时合并,",
108
- "**不要顺手清理、不要自发拆分合并改标题**。整理只在人类明确要求、或外部计划任务明确发出整理指令时才启动。",
77
+ "### 失败时",
109
78
  "",
110
- "### 输出是证据本体",
79
+ "读原文修因,禁把「我记得没这功能」当理由。**禁自行安装、禁手工拼命令、禁改 PATH、禁自行编译替代。** 确实缺能力时说明缺哪条、试过什么、错误原文是什么;说不出来就当没试过。",
111
80
  "",
112
- "`aurorix_abook` 返回的文本就是证据,不是可裁剪的展示。**禁截断**:不接 `head` / `tail` / `cut` / `sed -n 范围`,不做「只看前几行就下结论」。",
113
- "被截断读到的内容按**未读论**,不得据其下结论、判 PASS 或报真值。",
114
- "工具已强制:超过单次上限的输出会被**整份拒收**并给出分页建议,而不是切一半给你。有压力就改口径(`--limit` 更小、`--page`、`--json`、单条读),不改真值。",
81
+ "### 整理不是随手做的事",
115
82
  "",
116
- "### 失败时",
83
+ "库里有重复、粗糙、互相矛盾的条目是正常状态。看到矛盾要么留着,要么在明确接到整理指令时合并。**不要顺手清理、不要自发拆分合并改标题。**",
117
84
  "",
118
- "工具报失败 → 读原文修因,禁把「我记得没这功能」当理由。**禁自行安装、禁手工拼命令、禁改 PATH 或 shell 配置、禁自行编译替代。**",
119
- "确实缺能力时,说明缺哪一条、试过什么、错误原文是什么;说不出来就当没试过。",
85
+ "### 关于下面那份快照",
120
86
  "",
121
- "### 完整手册",
87
+ "它每轮重发、不留在历史里,所以对话被压缩之后照样在。",
122
88
  "",
123
- "上面是每步都在的硬约束。细节用 `aurorix_guide` 取:`{\"topic\":\"tools\"}` / `preload` / `write` / `integrity` / `maintenance` / `root`。不带参数返回章节目录。",
89
+ "它是分层视图,不是全库:常驻层永久全量,其余按重要度与使用热度排成全量正文/摘要/仅标题三档。只列标题的条目原文都在库里,`aurorix_recall` 能取回。快照可能有滞后,条目可能过时,采用前核对正文里的版本与适用范围。",
124
90
  ].join('\n')
125
91
 
126
- export const DEFAULT_PROTOCOL = `## 记忆库(Aurorix 原生绑定)
127
-
128
- 本会话与本机记忆库直连,库根由插件配置固定。读用 \`aurorix_recall\`,写用 \`aurorix_remember\`。
129
-
130
- **这一节是分层后的视图,不是全库。** 常驻层(soul / profile / explicit)永久全量;其余条目按重要度、最近使用和时间衰减排成三档:全量正文、摘要、仅标题。没进全量的条目原文都还在库里,用 \`aurorix_recall\` 按话题检索即可取回——标题档会列出所有可召回项,看到相关的就直接查。
131
-
132
- **读**:命中主题时先检索取记录 ID,再读正文;不要凭印象代替实读。
92
+ // 旧版把「协议段落」与「手册」分成两份注入,内容大量重复。
93
+ // 现在默认不再单独注协议;保留这个导出只为兼容还显式配了 protocol 的环境。
94
+ export const DEFAULT_PROTOCOL = ''
133
95
 
134
- **写**:用户说「记住 / 记下来」且内容是短小关键点时写 explicit;完整经过、根因、可复用结论写 long_term;单次事件与证据写 episodic。写完回读记录 ID。
135
-
136
- **边界**:快照可能有滞后,条目可能过时;采用前核对正文里的版本与适用范围。本轮记忆处于关闭态时忽略本节。`
137
96
 
138
97
  /** 字节安全截断:不留半个码点。 */
139
98
  function clampBytes(text, limit) {
@@ -163,18 +122,34 @@ function headingsOf(content) {
163
122
  .filter(Boolean)
164
123
  }
165
124
 
125
+ /**
126
+ * 排序分:按档位取整,不按连续值。
127
+ *
128
+ * 这里必须分档,不能直接用连续分。检索一次记忆就会给条目 hits+1,连续分随之改变、
129
+ * 排序跟着重排、快照文本跟着变——而快照一变,宿主就在对话里多留一份陈年副本
130
+ * (实测一个会话里堆到 35 份 × 60KB)。于是「用记忆」这个动作本身会让上下文变胖,
131
+ * 用得越勤涨得越快,是个自激励的环。
132
+ *
133
+ * 分档后,同一档内的使用量变化不改变名次,快照文本保持稳定;
134
+ * 只有跨档(真的用得多很多)才重排,那是应该发生的。
135
+ */
166
136
  function scoreOf(record, access, now, halfLifeDays, accessBoost) {
167
137
  const base = PLANE_BASE[record.plane] ?? 0
168
138
  const hits = access ? access.hits || 0 : 0
169
- const boost = Math.log1p(hits) * accessBoost
139
+ // 命中数取 2 的幂档:1-2、3-6、7-14、15-30… 各算一档。
140
+ const bucket = hits <= 0 ? 0 : Math.floor(Math.log2(hits + 1))
141
+ const boost = bucket * accessBoost
170
142
  const lastTouched = (access && access.lastTouched) || record.updated_at || record.created_at || now
171
143
  const days = Math.max(0, (now - lastTouched) / 86400)
172
- const decay = halfLifeDays > 0 ? 60 * (days / halfLifeDays) : 0
144
+ // 时间衰减同样取整到「天」档,避免同一秒内的毫秒差造成抖动。
145
+ const decay = halfLifeDays > 0 ? Math.round(days) * (60 / halfLifeDays) : 0
173
146
  return base + boost - decay
174
147
  }
175
148
 
176
149
  // 规则条数多、密度高,摘要短一点就够认出是哪条;其余平面给足上下文。
177
- const BRIEF_CHARS_BY_PLANE = { rules: 70 }
150
+ // rules 用 0 表示「摘要档只列标题」:规则标题平均 40 字节,本身已经把规则说清楚了,
151
+ // 再附一段正文摘要等于同一条信息说两遍,白占 19KB/轮。
152
+ const BRIEF_CHARS_BY_PLANE = { rules: 0 }
178
153
 
179
154
  function renderTier(record, tier, briefChars) {
180
155
  const limit = BRIEF_CHARS_BY_PLANE[record.plane] ?? briefChars
@@ -182,6 +157,8 @@ function renderTier(record, tier, briefChars) {
182
157
  const content = String(record.content || '').trim()
183
158
  if (tier === 'full') return `- 【${title}】${content}`
184
159
  if (tier === 'brief') {
160
+ // 限额为 0:标题即摘要。不附正文,也不附结构目录(同一个道理,标题已经说明是什么)。
161
+ if (limit <= 0) return `- ${title}`
185
162
  const gist = gistOf(content, limit)
186
163
  const heads = headingsOf(content)
187
164
  const structure = heads.length > 1 ? `\n └ ${heads.slice(0, 5).join(' / ')}` : ''
@@ -250,6 +227,48 @@ export function resolveStatePath(explicit) {
250
227
  return join(home, 'cache', 'dsh-aurorix-agentbook', 'access.json')
251
228
  }
252
229
 
230
+ /**
231
+ * 库指纹:所有平面记录文件的「名字 + 大小 + 修改时间」滚成一个数。
232
+ *
233
+ * 用处是决定快照要不要重建。宿主拿到的新快照只要文本变了,就会往对话尾部追加一条
234
+ * 新消息,前缀缓存跟着失效;所以「库没变就不重建」比「每 15 秒重建一次」重要得多。
235
+ *
236
+ * 只 stat 不读内容:1200 多个文件约 20 毫秒,比调 abook 读全库(300 毫秒以上)便宜一个数量级。
237
+ * 指纹对不上才值得去读全文。
238
+ */
239
+ export function librarySignature(root) {
240
+ if (typeof root !== 'string' || root === '') return ''
241
+ let hash = 2166136261
242
+ let count = 0
243
+ for (const plane of [...RESIDENT_PLANES, ...DECAY_PLANES]) {
244
+ const dir = join(root, 'planes', plane, 'records')
245
+ let files
246
+ try {
247
+ files = readdirSync(dir)
248
+ } catch {
249
+ continue
250
+ }
251
+ files.sort()
252
+ for (const file of files) {
253
+ let stat
254
+ try {
255
+ stat = statSync(join(dir, file))
256
+ } catch {
257
+ continue
258
+ }
259
+ // FNV-1a:够散、够快、不需要 crypto,跨进程稳定。
260
+ hash ^= file.length
261
+ hash = Math.imul(hash, 16777619)
262
+ hash ^= stat.size
263
+ hash = Math.imul(hash, 16777619)
264
+ hash ^= Math.floor(stat.mtimeMs)
265
+ hash = Math.imul(hash, 16777619)
266
+ count++
267
+ }
268
+ }
269
+ return count === 0 ? '0:0' : `${count}:${hash >>> 0}`
270
+ }
271
+
253
272
  /**
254
273
  * 读全库并压成快照文本。
255
274
  * @param {(plane: string) => Promise<{ ok: boolean, items?: object[], reason?: string }>} listPlane
@@ -297,7 +316,9 @@ export async function buildSnapshot(listPlane, options = {}) {
297
316
  const decay = records
298
317
  .filter((r) => DECAY_PLANES.includes(r.plane))
299
318
  .map((r) => ({ record: r, score: scoreOf(r, accessMap[r.id], now, decayHalfLifeDays, accessBoost) }))
300
- .sort((a, b) => b.score - a.score)
319
+ // 同分时必须按稳定键决出先后:只按 score 排,相等时顺序取决于输入顺序,
320
+ // 而输入顺序一变快照就变、又会让上下文多一份副本。ID 是稳定的。
321
+ .sort((a, b) => b.score - a.score || String(a.record.id).localeCompare(String(b.record.id)))
301
322
 
302
323
  const tiers = new Map()
303
324
  decay.forEach((entry, index) => {
package/lib/view.js CHANGED
@@ -171,6 +171,18 @@ export function memoryView(state, caps = {}) {
171
171
  { type: 'text', text: b('vaultDraftNote'), tone: 'muted' },
172
172
  ] },
173
173
 
174
+ // 五、注入痕迹:这一轮到底往模型里放了什么。改了库、快照重建,这里会跟着变。
175
+ { type: 'divider', size: 'S' },
176
+ { type: 'collapsible', label: w.injectTitle, expanded: false, children: [
177
+ { type: 'text', text: b('inject.note'), tone: 'muted' },
178
+ { type: 'text', text: b('inject.stats'), tone: 'muted' },
179
+ { type: 'text', text: w.injectHint, tone: 'muted' },
180
+ { type: 'actions', items: [
181
+ { label: w.injectDetail, icon: 'document', action: 'inject-detail', style: 'plain' },
182
+ ] },
183
+ ] },
184
+
185
+ { type: 'divider', size: 'S' },
174
186
  { type: 'actions', items: [
175
187
  { label: w.retry, icon: 'refresh', action: 'reload', style: 'plain' },
176
188
  ] },
@@ -183,7 +195,14 @@ function detailView(state, caps) {
183
195
  const w = words(caps?.locale)
184
196
  const d = state.detail
185
197
  const isVault = d.kind === 'vault'
186
- const meta = isVault
198
+ // 注入全文是只读的:它不是库里的一条记录,不能编辑、也不该显示平面与记录 ID。
199
+ const isInject = d.kind === 'inject'
200
+ const meta = isInject
201
+ ? [
202
+ [w.injectTitle, w.injectOn],
203
+ [w.detailBytes, `${Number(d.bytes) || 0} B`],
204
+ ]
205
+ : isVault
187
206
  ? [
188
207
  [w.detailPurpose, d.purpose === '' ? '—' : clip(d.purpose, 160)],
189
208
  [w.detailBytes, `${Number(d.bytes) || 0} B`],
@@ -259,8 +278,8 @@ function detailView(state, caps) {
259
278
  { label: w.nextPage, action: 'detail-page-next', style: 'plain' },
260
279
  ] : []),
261
280
  { label: w.detailBack, action: 'detail-back', style: 'plain' },
262
- // 既然已经点进详情页,就该能就地改——不用退回去重写一条。
263
- ...(hasForm ? [{ label: w.detailEdit, icon: 'pencil', action: 'detail-edit', style: 'plain' }] : []),
281
+ // 既然已经点进详情页,就该能就地改——不用退回去重写一条。注入全文是只读的,不给编辑。
282
+ ...(hasForm && !isInject ? [{ label: w.detailEdit, icon: 'pencil', action: 'detail-edit', style: 'plain' }] : []),
264
283
  { label: w.detailCopy, icon: 'copy', action: 'detail-copy', style: 'primary' },
265
284
  ] })
266
285
 
@@ -361,7 +380,38 @@ export function memoryData(state, caps = {}) {
361
380
  body: state.vaultDraft?.body ?? '',
362
381
  },
363
382
  vaultDraftNote: state.vaultDraftNote ?? '',
383
+ inject: injectModel(state, caps),
384
+ }
385
+ }
386
+
387
+ /**
388
+ * 注入痕迹:把「这一轮往模型里放了什么」变成面板能看到的东西。
389
+ *
390
+ * 只放摘要,不放正文:面板数据上限 32 KB,塞 25 KB 快照全文会把整份数据顶爆,
391
+ * 宿主直接拒收,面板就变成一条数据都没有——那正是「没有及时响应」的真实成因。
392
+ * 全文要看的话走 detail-inject 动作单独取。
393
+ */
394
+ function injectModel(state, caps) {
395
+ const w = words(caps?.locale)
396
+ const info = state.inject
397
+ if (info === undefined || info === null || info.enabled !== true) {
398
+ return { on: false, note: w.injectOff, stats: '', tone: 'muted' }
399
+ }
400
+ const bytes = Number(info.bytes) || 0
401
+ const stats = info.stats
402
+ ? w.injectStats(info.stats.resident, info.stats.full, info.stats.brief, info.stats.index)
403
+ : ''
404
+ if (bytes === 0) {
405
+ return { on: true, note: info.error ? `${w.injectOff}:${info.error}` : w.injectNever, stats, tone: info.error ? 'warn' : 'muted' }
364
406
  }
407
+ const kb = Math.max(1, Math.round(bytes / 1024))
408
+ const age = info.ageSeconds === undefined || info.ageSeconds === null
409
+ ? ''
410
+ : w.injectAge(Number(info.ageSeconds) || 0)
411
+ // 库有没有变:变了下一轮会重建,这是最值得看的一件事。
412
+ const drift = info.changed === true ? w.injectChanged : w.injectSame
413
+ const note = [w.injectOn, `${kb} KB`, age, drift].filter((x) => x !== '').join(' · ')
414
+ return { on: true, kb, note, stats, changed: info.changed === true, tone: info.changed === true ? 'info' : 'muted' }
365
415
  }
366
416
 
367
417
  const hitCountOf = (state) => (Array.isArray(state.hits) ? state.hits.length : 0)
package/lib/words.js CHANGED
@@ -36,6 +36,22 @@ export const WORDS = {
36
36
  unavailableMessage: '确认记忆库装在这台设备上,路径通常是 ~/AgentsBook/abook。',
37
37
  stripText: (total, planes) => `记忆 ${total} 条 · ${planes} 个平面`,
38
38
  stripUnknown: '记忆库读不到',
39
+
40
+ // 注入痕迹:给用户看「这一轮到底往模型里放了什么」
41
+ injectTitle: '本机注入',
42
+ injectOn: '正在注入',
43
+ injectOff: '未启用注入',
44
+ injectSize: (kb, tier) => `${kb} KB · ${tier}`,
45
+ injectStats: (resident, full, brief, index) => `常驻 ${resident} · 全量 ${full} · 摘要 ${brief} · 索引 ${index}`,
46
+ injectAge: (seconds) => seconds < 60 ? `${seconds} 秒前` : `${Math.round(seconds / 60)} 分钟前`,
47
+ injectNever: '还没构建过快照',
48
+ injectChanged: '库有变化,下一轮会重建',
49
+ injectSame: '库无变化,复用同一份快照',
50
+ injectRefresh: '立即重建',
51
+ injectCopied: '已复制本份注入全文',
52
+ injectDetail: '查看注入全文',
53
+ injectHint: '这份内容作为对话尾部的一条快照消息送给模型,不进系统提示词前缀;内容没变就不会追加新消息,缓存不会被顶掉。',
54
+ injectNoteOnTurn: (kb) => `记忆注入 ${kb} KB`,
39
55
  copied: '已复制',
40
56
  copy: '复制正文',
41
57
  detail: '正文',
@@ -148,6 +164,21 @@ export const WORDS = {
148
164
  unavailableMessage: 'Make sure the memory store is installed, usually ~/AgentsBook/abook.',
149
165
  stripText: (total, planes) => `Memory ${total} · ${planes} planes`,
150
166
  stripUnknown: 'Memory unreadable',
167
+
168
+ injectTitle: 'Injected',
169
+ injectOn: 'Injecting',
170
+ injectOff: 'Injection off',
171
+ injectSize: (kb, tier) => `${kb} KB · ${tier}`,
172
+ injectStats: (resident, full, brief, index) => `resident ${resident} · full ${full} · brief ${brief} · index ${index}`,
173
+ injectAge: (seconds) => seconds < 60 ? `${seconds}s ago` : `${Math.round(seconds / 60)}m ago`,
174
+ injectNever: 'No snapshot built yet',
175
+ injectChanged: 'Library changed, rebuilds next turn',
176
+ injectSame: 'Library unchanged, same snapshot reused',
177
+ injectRefresh: 'Rebuild now',
178
+ injectCopied: 'Snapshot copied',
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.',
181
+ injectNoteOnTurn: (kb) => `Memory ${kb} KB`,
151
182
  copied: 'Copied',
152
183
  copy: 'Copy body',
153
184
  detail: 'Body',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aurorix-agentbook",
3
- "version": "1.9.2",
3
+ "version": "1.9.4",
4
4
  "description": "dsh-aurorix-agentbook:给 dsh-go 与 Harness Web 接通 Aurorix 记忆库——原生界面(状态条/胶囊/菜单/面板/保险箱)与 Web 顶栏槽位面板,加宿主侧提示词注入、分层快照与八个工具。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -72,6 +72,11 @@
72
72
  ],
73
73
  "presentation": "sheet"
74
74
  }
75
+ ],
76
+ "turn.note": [
77
+ {
78
+ "id": "memory-inject"
79
+ }
75
80
  ]
76
81
  }
77
82
  },