dsh-macro-memory 0.0.0-stage → 0.3.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.
Files changed (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +457 -2
  3. package/cordis.patch.yml +6 -0
  4. package/lib/client.js +3623 -0
  5. package/lib/index.js +469 -0
  6. package/lib/macro/brand.js +82 -0
  7. package/lib/macro/bridge.js +158 -0
  8. package/lib/macro/chain.js +206 -0
  9. package/lib/macro/contract.js +471 -0
  10. package/lib/macro/cost.js +164 -0
  11. package/lib/macro/defs/admin.js +439 -0
  12. package/lib/macro/defs/dream.js +24 -0
  13. package/lib/macro/defs/link.js +257 -0
  14. package/lib/macro/defs/project.js +25 -0
  15. package/lib/macro/defs/read.js +145 -0
  16. package/lib/macro/defs/remember.js +213 -0
  17. package/lib/macro/defs/search.js +661 -0
  18. package/lib/macro/defs/update.js +161 -0
  19. package/lib/macro/dreamledger.js +1398 -0
  20. package/lib/macro/facade.js +135 -0
  21. package/lib/macro/fusion.js +182 -0
  22. package/lib/macro/linkflow.js +391 -0
  23. package/lib/macro/links.js +448 -0
  24. package/lib/macro/neighbor.js +209 -0
  25. package/lib/macro/panel.js +96 -0
  26. package/lib/macro/prompt.js +139 -0
  27. package/lib/macro/provenance.js +148 -0
  28. package/lib/macro/render.js +35 -0
  29. package/lib/macro/revisions.js +253 -0
  30. package/lib/macro/shared.js +113 -0
  31. package/lib/macro/store.js +103 -0
  32. package/lib/macro/tokencost.js +90 -0
  33. package/lib/macro/tools.js +67 -0
  34. package/package.json +54 -4
  35. package/vendor/VENDOR.json +23 -0
  36. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  37. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  38. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  39. package/vendor/dsh-memory-nebula/README.md +253 -0
  40. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  41. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  42. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  43. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  44. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  45. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  46. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +317 -0
  47. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  48. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  49. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  50. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  51. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  52. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  53. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  54. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  55. package/vendor/dsh-memory-nebula/lib/host/graph.js +1663 -0
  56. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +282 -0
  57. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  58. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  59. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  60. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  61. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  62. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  63. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  64. package/vendor/dsh-memory-nebula/lib/host/recall.js +451 -0
  65. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  66. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  67. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  68. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  69. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  70. package/vendor/dsh-memory-nebula/lib/index.js +759 -0
  71. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  72. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  73. package/vendor/dsh-memory-nebula/lib/web/app.js +4159 -0
  74. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  75. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  76. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  77. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  78. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  79. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  80. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  81. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  82. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  83. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  84. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  85. package/vendor/dsh-memory-nebula/package.json +87 -0
  86. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  87. package/vendor/meow-memory/LICENSE +21 -0
  88. package/vendor/meow-memory/README.en.md +192 -0
  89. package/vendor/meow-memory/README.md +174 -0
  90. package/vendor/meow-memory/README.pt-br.md +180 -0
  91. package/vendor/meow-memory/cordis.patch.yml +7 -0
  92. package/vendor/meow-memory/lib/client.js +3344 -0
  93. package/vendor/meow-memory/lib/client.js.map +7 -0
  94. package/vendor/meow-memory/lib/index.js +9567 -0
  95. package/vendor/meow-memory/lib/index.js.map +7 -0
  96. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  97. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  98. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  99. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  100. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  101. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  102. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  103. package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
  104. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  105. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  106. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  107. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  108. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  109. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  110. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  111. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  112. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  113. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  114. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
  115. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  116. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  117. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  118. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  119. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  120. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  121. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  122. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  123. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  124. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  125. package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
  126. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  127. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  128. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  129. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  130. package/vendor/meow-memory/package.json +64 -0
@@ -0,0 +1,759 @@
1
+ /**
2
+ * 宏记忆 · 星图 · 宿主插件 [macro-fusion 0.2.11]
3
+ *
4
+ * 干三件事:
5
+ * 1. 以只读方式把各处记忆库(meow-memory 等)抽出来,建一张带证据的连接图;
6
+ * 2. 在左侧栏给主人一个能看、能点的星云界面(同源 iframe);
7
+ * 3. 把这张图接进 AI 的检索路径:工具 + 每轮「邻域提示」,
8
+ * 让别的记忆插件检索到 A 的时候,能顺带读出与 A 相连的 B。
9
+ *
10
+ * 只写自己的目录:$DSH_HOME/memory-nebula/
11
+ */
12
+ import { registerRoutes, PREFIX, VERSION } from './host/http.js'
13
+ import { LiveEngine, liveFacade } from './host/live.js'
14
+ import { HUB_CAP } from './host/nebula.js'
15
+ import { nebulaHome } from './host/sources.js'
16
+ import { readFileSync, existsSync, appendFileSync, mkdirSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import { clip, cut } from './host/text.js'
19
+
20
+ /** 插件自己的日志(引擎还没起来时也能写)。 */
21
+ function appendLog(line) {
22
+ try {
23
+ const home = nebulaHome()
24
+ mkdirSync(home, { recursive: true })
25
+ appendFileSync(join(home, 'nebula.log'), `[${new Date().toISOString()}] ${line}\n`)
26
+ } catch {
27
+ /* 日志失败不影响主流程 */
28
+ }
29
+ }
30
+
31
+ export const name = 'memory-nebula'
32
+ export const version = VERSION
33
+ export const inject = ['tools', 'systemPrompt', 'webServer', 'connection']
34
+
35
+ /** 每轮注入的稳定部分(进 prompt 缓存前缀,越短越好)。 */
36
+ const RULE = [
37
+ '【宏记忆 · 星图 memory-nebula】你有一张跨工作区记忆网络(不同项目的记忆之间已经算好并验证过关联)。',
38
+ '- 想找记忆时用 nebula_recall(query=…):它从命中点沿关联扩散,会带回别的项目里真正相关的记忆,每条都给出关联证据。',
39
+ '- 别的记忆工具(meow-memory / hindsight / openviking 等)返回了记忆 id 时,把 id 传给 nebula_recall(memory_ids=[…]),星图会把与它们相连的记忆一并读出——这是「检索 A 连带读出 B」的用法。',
40
+ '- 不确定两条记忆为什么相连:用 nebula_path(a, b) 看它们之间的最短证据链,每一步都带连接类型和权重;这条路走不通就说明它们没有关系。',
41
+ '- 想确认某条记忆的全部上下文(正文、关键词、邻居与每条边的证据、写它时主人说的原话),用 nebula_inspect(id)。',
42
+ '- 发现关联是错的:`nebula_link(action="mute", a, b)` 屏蔽它(重建也不会再连),比 unlink 更彻底;撤销用 action="unmute"。',
43
+ '- 想查记忆库自己的毛病(重复、该更新、关系凑数、超重、没人读、孤立)用 nebula_hygiene();它只诊断,改不改由你或主人定。',
44
+ '- 别的插件刚喂过记忆、你想补上下文又不想重复:nebula_bridge(memory_ids=[…]) 会挑出强相关但还没读过的邻居。要接新记忆库先看 nebula_sources 的指南;远端记忆服务可用 nebula_ingest 推进来。',
45
+ ].join('\n')
46
+
47
+ /** 数字对齐,纯文本表格。 */
48
+ function pad(text, width) {
49
+ const s = String(text ?? '')
50
+ let w = 0
51
+ for (const ch of s) w += ch.charCodeAt(0) > 127 ? 2 : 1
52
+ return s + ' '.repeat(Math.max(0, width - w))
53
+ }
54
+
55
+ /**
56
+ * [macro-fusion 0.2.57] 数值参数不许被 `Number(x) || 默认值` 吃掉。
57
+ *
58
+ * 老写法把「Number(args.x) 后面接 `|| 默认值`」塞进 Math.min/Math.max 三层里,有三个坑,而且都不吭声:
59
+ * ① 显式给的 **0** 是 falsy —— `min_weight: 0`(明确要求「不过滤权重」)会被换成 0.5,
60
+ * 于是结果里有东西被滤掉,回执还说「把 min_weight 调低一点」,用户明明已经调到最低了;
61
+ * `hops: 0` 同样被换成默认跳数。
62
+ * ② 越界值被 Math.min/max 夹住,回执一个字都不说 —— 用户拿着被改过的条件读结论,
63
+ * 而「30 条就是全部命中」这句话在夹过的 limit 下是假的。
64
+ * ③ 非数字(`limit: "十"`)静默退回默认。
65
+ * 三次都只是「参数没生效」,但读者会把它读成「结果就是这样」。所以这里统一出口:
66
+ * 合规就原样照办(0 也照办),不合规就夹/退回默认 **并且带一句话** 出来。
67
+ * @returns {{value:number, note:string}} note 为空 = 不需要解释
68
+ */
69
+ function numParam(name, raw, { min, max, def }) {
70
+ if (raw === void 0 || raw === null || String(raw).trim() === '') return { value: def, note: '' }
71
+ const n = Number(raw)
72
+ if (!Number.isFinite(n)) {
73
+ return { value: def, note: `${name} 给的是「${String(raw)}」,不是数字——这次按默认 ${def} 算,不是你给的那个值。` }
74
+ }
75
+ const clamped = Math.max(min, Math.min(max, n))
76
+ if (clamped === n) return { value: n, note: '' }
77
+ return { value: clamped, note: `${name} 给的是「${n}」,超出 ${min}–${max},这次按 ${clamped} 算——结果是被改过的条件算出来的,不是你给的那个。` }
78
+ }
79
+
80
+ /**
81
+ * 把命中结果排成给模型看的文本。
82
+ * @param {{hits:any[], query:string, scanned?:number}} res
83
+ * @param {string} [note]
84
+ */
85
+ function formatHits(res, note = '') {
86
+ const hits = res?.hits || []
87
+ if (hits.length === 0) {
88
+ // [macro-fusion 0.2.39] 空结果有两种:图里真没有,和图还没建完(空图 / 重建中)。
89
+ // 以前两种都回一句「星图里没有匹配」,于是重建期的零命中被读成「确认没有这条记忆」。
90
+ // 扫描条数是 recall 本来就算好的数(scanned),只是空命中时被丢掉了——这里不许再丢。
91
+ const total = Number(res?.nodes ?? -1)
92
+ const q = res?.query || ''
93
+ const head =
94
+ total === 0
95
+ ? 'nebula_recall: 星图里还没有节点(图是空的),这一问等于没算。'
96
+ : `nebula_recall: 星图里没有匹配「${q}」的记忆(图里 ${total < 0 ? '若干' : total} 条节点,一条都对不上)。`
97
+ const unknown = Array.isArray(res?.unknown) ? res.unknown.filter(Boolean) : []
98
+ const tail = unknown.length ? `这些词星图里一次都没出现:${unknown.slice(0, 6).join('、')}` : ''
99
+ return [head, note, tail].filter(Boolean).join('\n')
100
+ }
101
+ const lines = []
102
+ lines.push(`nebula_recall「${res.query || ''}」→ ${hits.length} 条(扫描 ${res.scanned || 0} 条候选${note ? ';' + note : ''})`)
103
+ hits.forEach((h, i) => {
104
+ lines.push(
105
+ `${i + 1}. [${h.level}] ${pad(h.ws, 12)} 强度 ${String(h.score).padEnd(5)} ${clip(h.label || h.title || h.id, 46)}`,
106
+ )
107
+ lines.push(` id: ${h.id}`)
108
+ if (h.why) lines.push(` 为什么:${h.why}`)
109
+ if (h.preview) lines.push(` 摘要:${clip(h.preview, 150)}`)
110
+ })
111
+ return lines.join('\n')
112
+ }
113
+
114
+ /**
115
+ * [macro-fusion 0.2.74] 列表被截断时的那一句尾注。
116
+ *
117
+ * 体检的每个列表有两道闸:引擎每类最多留 40 条(payload 有上限),参数 `limit` 再截一道。
118
+ * 用户能看见的只有正文里那几行,所以「列了几条、还剩几条」必须按**正文实际列出的条数**
119
+ * (printed)算,不能按任何一种内部账:
120
+ * - 按引擎那本账(items.length=40)算,会出现「只列前 40 条」底下只有 6 行;
121
+ * - 按参数 limit 算,会出现正文 6 行 + 「还有 94 条」= 100,而别的类别数字又对不上。
122
+ *
123
+ * 返回空串表示没截断(一条不少),调用方别加空行。
124
+ */
125
+ export function listTail(n, printed, limit) {
126
+ const total = Math.max(0, Math.trunc(Number(n) || 0))
127
+ const shown = Math.max(0, Math.trunc(Number(printed) || 0))
128
+ const cap = Math.max(1, Math.trunc(Number(limit) || 1))
129
+ const left = total - shown
130
+ if (left <= 0) return ''
131
+ return ` …还有 ${left} 条(每类最多列 ${cap} 条,要看更多把 limit 调大;上面的计数是全量,没列的不代表不存在)`
132
+ }
133
+
134
+ /**
135
+ * [macro-fusion 0.2.75] 枢纽榜被截断时的那一句尾注。
136
+ *
137
+ * 枢纽是**按连接度排在最前的一小撮**,不是「全图删掉这一小撮」:剩下的绝大多数是只有
138
+ * 一两条边、甚至一条边都没有的记忆。旧写法把 `s.nodes - top.length` 当成「还有多少条没列」,
139
+ * 读者读到的意思是「还有 2988 个枢纽没给你看」;它自己也知道这句话站不住,才紧跟着再补一句
140
+ * 安抚——那句补丁等于当场承认前一个数字不成立。
141
+ *
142
+ * 现在只报读者能数到的三个数:这一段列了几条、够格参评的有几条(有连接的记忆)、
143
+ * 参数能要到几条(上限)。三个数都来自「读者看得见的东西」,不掺引擎的内部计数。
144
+ * 没截断就返回空串。
145
+ */
146
+ export function hubTail(printed, pool, cap) {
147
+ const shown = Math.max(0, Math.trunc(Number(printed) || 0))
148
+ const cand = Math.max(0, Math.trunc(Number(pool) || 0))
149
+ const limit = Math.max(1, Math.trunc(Number(cap) || 1))
150
+ if (cand - shown <= 0) return ''
151
+ return ` 全图 ${cand} 条记忆彼此有连接,这里只取排在最前的 ${shown} 条(hubs 上限 ${limit});没进前 ${shown} 的不是「没有连接」,只是没排上来。`
152
+ }
153
+
154
+ export function apply(ctx) {
155
+ const live = new LiveEngine({ onLog: appendLog })
156
+ const nebula = liveFacade(live)
157
+ const log = appendLog
158
+
159
+ // ---------- 启动:后台建图 + 12s 巡检(引擎热载也在 LiveEngine 里) ----------
160
+ live
161
+ .ensure()
162
+ .then(() => log('首次建图完成'))
163
+ .catch((err) => log('首次建图失败:' + (err?.stack || err)))
164
+
165
+ ctx.effect(() => {
166
+ return () => {
167
+ try {
168
+ nebula.stopWatching()
169
+ } catch {
170
+ /* ignore */
171
+ }
172
+ }
173
+ }, 'memory-nebula:cleanup')
174
+
175
+ // ---------- HTTP + 页面 ----------
176
+ try {
177
+ registerRoutes(ctx.webServer, nebula, log, { mode: 'host', connection: ctx.connection })
178
+ log(`已挂载 ${PREFIX}(页面 ${PREFIX}/app)`)
179
+ } catch (err) {
180
+ log('挂载 webServer 失败:' + (err?.stack || err))
181
+ }
182
+
183
+ // ---------- 工具 ----------
184
+ const render = (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
185
+ const out = { schema: { type: 'string' }, render }
186
+
187
+ ctx.effect(() =>
188
+ ctx.tools.register({
189
+ name: 'nebula_recall',
190
+ description:
191
+ '在「宏记忆 · 星图」里检索记忆:先按语义/关键词命中,再沿已算好的关联(同一实体、同项目、同关键词、共激活、语义相似)向外扩散,把别的项目里真正相关的记忆一起带回来,并给出每一层的关联证据。适合跨项目回忆、找「和这件事有关但记在别处」的东西。',
192
+ parameters: {
193
+ type: 'object',
194
+ properties: {
195
+ query: { type: 'string', description: '自然语言描述或关键词。只给 memory_ids 时可以为空。' },
196
+ memory_ids: {
197
+ type: 'array',
198
+ items: { type: 'string' },
199
+ description: '别的记忆工具刚返回的记忆 id(meow 的 id 或星图的完整 id),用来从这些点向外交扩散。',
200
+ },
201
+ limit: { type: 'number', description: '返回条数,默认 10,上限 30。' },
202
+ hops: { type: 'number', description: '扩散跳数,默认 2;1=只看直接邻居,2=邻居的邻居。' },
203
+ },
204
+ required: [],
205
+ additionalProperties: false,
206
+ },
207
+ output: out,
208
+ async execute(args = {}) {
209
+ if (!nebula.graph || nebula.graph.nodes.length === 0) await nebula.refresh()
210
+ const query = String(args.query || '').trim()
211
+ const ids = Array.isArray(args.memory_ids) ? args.memory_ids.filter((x) => typeof x === 'string' && x.trim()) : []
212
+ if (!query && ids.length === 0) return 'nebula_recall 需要 query 或 memory_ids 至少一个。'
213
+ const pLimit = numParam('limit', args.limit, { min: 1, max: 30, def: 10 })
214
+ const pHops = numParam('hops', args.hops, { min: 0, max: 3, def: 2 })
215
+ const notes = [pLimit.note, pHops.note].filter(Boolean)
216
+ const res = await nebula.recallAsync(query, { limit: pLimit.value, hops: pHops.value, seedIds: ids })
217
+ const base = formatHits(res, ids.length ? `种子来自你给的 ${ids.length} 条记忆 id` : '')
218
+ return notes.length ? `${base}\n${notes.join('\n')}` : base
219
+ },
220
+ }),
221
+ )
222
+
223
+ ctx.effect(() =>
224
+ ctx.tools.register({
225
+ name: 'nebula_inspect',
226
+ description:
227
+ '看一条记忆在星图里的完整上下文:全文、项目、关键词,以及它连接到的每一条记忆和「为什么相连」的证据。用来验证关联是否可信,或顺着一条记忆摸清一整片。',
228
+ parameters: {
229
+ type: 'object',
230
+ properties: {
231
+ id: { type: 'string', description: '记忆 id(星图完整 id,或 meow-memory 的裸 id)。' },
232
+ neighbors: { type: 'number', description: '最多列出多少条邻居,默认 12。' },
233
+ },
234
+ required: ['id'],
235
+ additionalProperties: false,
236
+ },
237
+ output: out,
238
+ async execute(args = {}) {
239
+ const id = String(args.id || '').trim()
240
+ if (!id) return 'nebula_inspect 需要 id。'
241
+ const d = nebula.detail(id)
242
+ // [macro-fusion 0.2.42] 这一句在两种情况下都会出现,而两种情况下用户该做的事相反:
243
+ // 图是空的(这次问等于没算)/ 图里有东西但没有这一条(可能刚写还没入图,也可能 id 不对)。
244
+ // 前者被读成「这条记忆没了」→ 去还原备份。所以空图必须自己说清楚,并给出节点总数。
245
+ if (!d) {
246
+ const total = nebula.graph?.nodes?.length ?? 0
247
+ if (total === 0) {
248
+ return '星图里还没有节点(图是空的),这次 nebula_inspect 等于没算——这不是「这条记忆不存在」。等星图建起来(约 12s 一轮巡检)再查一次;记忆本身没受影响。'
249
+ }
250
+ return `星图里没有 id=${id} 的记忆。这不等于「记忆没了」:图里现有 ${total} 条节点,可能是刚写还没入图(约 12s 一轮巡检),也可能是 id 不对(裸 id 给前 12 位就够)。可以先用 nebula_recall 搜关键词确认。`
251
+ }
252
+ const pNb = numParam('neighbors', args.neighbors, { min: 1, max: 40, def: 12 })
253
+ const max = pNb.value
254
+ const lines = [
255
+ `# ${d.title || d.label}`,
256
+ `层级 ${d.level} · 工作区 ${d.wsTitle} · 项目 ${d.project || '—'} · 重要性 ${d.importance} · 连接 ${d.degree || (d.neighbors || []).length}`,
257
+ `id: ${d.id}`,
258
+ '',
259
+ clip(d.content, 1600),
260
+ '',
261
+ ]
262
+ if ((d.keywords || []).length) lines.push('关键词:' + d.keywords.join('、'), '')
263
+ const nbrs = (d.neighbors || []).slice(0, max)
264
+ lines.push(`## 连接到的记忆(${nbrs.length}/${(d.neighbors || []).length})`)
265
+ for (const n of nbrs) {
266
+ lines.push(`- [${n.type} ${(n.weight ?? n.w ?? 0).toFixed(2)}] ${n.label} · ${n.ws} · ${n.level}`)
267
+ lines.push(` id: ${n.id}`)
268
+ if (n.why) lines.push(` 证据:${n.why}`)
269
+ }
270
+ if (pNb.note) lines.push('', pNb.note)
271
+ return lines.join('\n')
272
+ },
273
+ }),
274
+ )
275
+
276
+ ctx.effect(() =>
277
+ ctx.tools.register({
278
+ name: 'nebula_link',
279
+ description:
280
+ '人工校正星图连接:action="link" 把两条记忆固化成一条手工连线(永不剪掉);action="unlink" 断开一条手工连线;' +
281
+ 'action="mute" 屏蔽一条**推断错了**的自动关联(记进黑名单,之后每次重建都不会再连它);action="unmute" 撤销屏蔽。' +
282
+ '改动只写进星图自己的库,不会动任何原记忆。',
283
+ parameters: {
284
+ type: 'object',
285
+ properties: {
286
+ action: {
287
+ type: 'string',
288
+ enum: ['link', 'unlink', 'mute', 'unmute'],
289
+ description: 'link=固化连线;unlink=断开手工连线;mute=屏蔽错误的自动关联;unmute=撤销屏蔽',
290
+ },
291
+ a: { type: 'string', description: '记忆 A 的 id' },
292
+ b: { type: 'string', description: '记忆 B 的 id' },
293
+ note: { type: 'string', description: '理由(可选,建议写,方便以后回看为什么连/为什么屏蔽)' },
294
+ },
295
+ required: ['action', 'a', 'b'],
296
+ additionalProperties: false,
297
+ },
298
+ output: out,
299
+ async execute(args = {}) {
300
+ const action = String(args.action || '').trim()
301
+ const a = String(args.a || '').trim()
302
+ const b = String(args.b || '').trim()
303
+ if (!a || !b) return '需要 a 和 b 两条记忆 id。'
304
+ try {
305
+ if (action === 'link') {
306
+ const r = nebula.link(a, b, String(args.note || ''))
307
+ // 就地生效:冻结 now 下策展一条与全量重建逐边相同(正好 +1 条),不重建
308
+ return `已固化连线:${r.a} ↔ ${r.b}${r.note ? '(' + r.note + ')' : ''}`
309
+ }
310
+ if (action === 'unlink') {
311
+ const ok = nebula.unlink(a, b)
312
+ return ok ? `已断开:${a} ✕ ${b}` : '没有找到这条手工连线(可能本来就是断的,或 id 不对)。'
313
+ }
314
+ if (action === 'mute') {
315
+ const r = nebula.mute(a, b, String(args.note || ''))
316
+ // 就地删掉这一条;剪枝腾出的空位不补,下次重建时补位
317
+ return `已屏蔽这条关联:${r.a} ✕ ${r.b}(以后重建不会再连;要撤销用 action="unmute")`
318
+ }
319
+ if (action === 'unmute') {
320
+ const ok = nebula.unmute(a, b)
321
+ if (ok && nebula.takeRebuildFlag()) await nebula.refresh({ force: true })
322
+ return ok ? `已撤销屏蔽:${a} ↔ ${b}(下次重建会重新按证据连)` : '这一对本来就没有被屏蔽。'
323
+ }
324
+ return 'action 只能是 link / unlink / mute / unmute。'
325
+ } catch (err) {
326
+ // id 不存在、或者引擎还在建图:把原因说清楚,别把异常丢给宿主
327
+ return `nebula_link 没做成:${err?.message || err}`
328
+ }
329
+ },
330
+ }),
331
+ )
332
+
333
+ ctx.effect(() =>
334
+ ctx.tools.register({
335
+ name: 'nebula_path',
336
+ description:
337
+ '解释两条记忆之间「到底怎么连上的」:在星图里找一条代价最小的证据链(优先走权重高的边),' +
338
+ '逐步列出每一步的连接类型、权重和证据。找不到就说明这两条在星图里没有关系——不会硬凑。' +
339
+ '用来核对推断是否合理,或回答「这条记忆和那个项目有什么干系」。',
340
+ parameters: {
341
+ type: 'object',
342
+ properties: {
343
+ a: { type: 'string', description: '起点记忆 id' },
344
+ b: { type: 'string', description: '终点记忆 id' },
345
+ maxHops: { type: 'number', description: '最多几跳,默认 6' },
346
+ },
347
+ required: ['a', 'b'],
348
+ additionalProperties: false,
349
+ },
350
+ output: out,
351
+ async execute(args = {}) {
352
+ const a = String(args.a || '').trim()
353
+ const b = String(args.b || '').trim()
354
+ if (!a || !b) return '需要 a 和 b 两个 id。'
355
+ const pMh = numParam('maxHops', args.maxHops, { min: 1, max: 12, def: 6 })
356
+ const r = await nebula.path(a, b, { maxHops: pMh.value })
357
+ if (!r || !r.found) {
358
+ // [macro-fusion 0.2.45] 原来这里把四种情况压成一句
359
+ // 「这两条记忆在星图里没有连上(<原因>)。没有关系就不编关系。」
360
+ // 其中三种根本不是关系结论:图是空的、引擎还没带路径搜索、节点还没入图。
361
+ // 这是这一族里代价最高的错误——「没有关系」会让人停止追问,而且它出现在
362
+ // 提示词里教模型「用 nebula_path 核对推断」的地方。
363
+ const totalP = nebula.graph?.nodes?.length ?? 0
364
+ const hopsP = pMh.value
365
+ if (totalP === 0) {
366
+ return '星图里还没有节点(图是空的),这次 nebula_path 等于没算——这不是「这两条记忆没有关系」。等星图建起来(约 12s 一轮巡检)再问一次;记忆本身没受影响。'
367
+ }
368
+ if (r?.error) {
369
+ if (String(r.error).includes('还没带上路径搜索')) {
370
+ return `这次没算成:${r.error}。这不是「这两条记忆没有关系」——重启宿主后再问一次就行,记忆本身没受影响。`
371
+ }
372
+ return `这次没算成:${r.error}(图里现在有 ${totalP} 条节点)。这不等于「这两条记忆没有关系」——可能是刚写还没入图(约 12s 一轮巡检),也可能 id 不对(裸 id 给前 12 位就够)。等一轮再问一次就行。`
373
+ }
374
+ return `这两条记忆在星图里确实没有连上:${hopsP} 跳以内一条可走的边都没有(图里现有 ${totalP} 条节点)。没有关系就不编关系。${pMh.note ? '\n' + pMh.note : ''}`
375
+ }
376
+ if (!r.hops) return '是同一条记忆。'
377
+ const lines = [`${r.nodes[0].label} ⇢ ${r.nodes[r.nodes.length - 1].label}:${r.hops} 跳,链强度 ${r.score}`, '']
378
+ for (let i = 0; i < r.edges.length; i += 1) {
379
+ const e = r.edges[i]
380
+ const from = r.nodes[i]
381
+ const to = r.nodes[i + 1]
382
+ lines.push(`${i + 1}. ${from.label}`)
383
+ lines.push(` ↳ [${e.t}] ${e.w} · ${e.why}`)
384
+ lines.push(` → ${to.label}`)
385
+ }
386
+ lines.push('', '每一步都来自建图时算出的边;如果某一步你觉得不该连,用 nebula_link(action="mute") 把它按掉。')
387
+ if (pMh.note) lines.push('', pMh.note)
388
+ return lines.join('\n')
389
+ },
390
+ }),
391
+ )
392
+
393
+ ctx.effect(() =>
394
+ ctx.tools.register({
395
+ name: 'nebula_stats',
396
+ description: '看宏记忆 · 星图的整体状况:多少条记忆、多少条连接、各工作区分布、连接类型分布、以及连接最多的枢纽记忆。',
397
+ parameters: {
398
+ type: 'object',
399
+ properties: {
400
+ // [macro-fusion 0.2.71] 上限必须写在这句话里,因为它是真的上限(以前实现写死 12,这句话形同虚设)
401
+ // [macro-fusion 0.2.75] 上限只剩一个数(HUB_CAP):夹参数、正文尾注、这句描述都读它。
402
+ // 再写成字面量,就等于又把同一个上限抄了一遍——改一处漏两处。
403
+ hubs: { type: 'number', description: `列多少个枢纽,默认 10,上限 ${HUB_CAP};没列完的会在正文说清「这一段列了几条、够格参评的有几条」。` },
404
+ },
405
+ required: [],
406
+ additionalProperties: false,
407
+ },
408
+ output: out,
409
+ async execute(args = {}) {
410
+ if (!nebula.graph || nebula.graph.nodes.length === 0) await nebula.refresh()
411
+ // [macro-fusion 0.2.71] hubs 先算完再取概览:以前 `slice(0, 12)` 写死,
412
+ // 给 20 也只出 12 条,且正文不说到没说完——「枢纽就这几个」是读者自己补的结论。
413
+ // [macro-fusion 0.2.75] 夹参数的一个数、正文里那句上限、schema 里那句上限原来各写一遍,
414
+ // 现在都读 HUB_CAP,一处改、三处一起动。
415
+ const pHubs = numParam('hubs', args.hubs, { min: 1, max: HUB_CAP, def: 10 })
416
+ const o = await nebula.overviewAsync({ hubs: pHubs.value })
417
+ const s = o.stats || {}
418
+ const top = o.hubs
419
+ // [macro-fusion 0.2.41] 「0 条记忆」是最容易被读成「记忆丢了」的一行数字。
420
+ // 同一句「0 条」既是「还没建起来」也是「来源读不出来」也是「真的一条都没有」——
421
+ // 前两种情况下人第一反应是「数据没了」,然后去翻备份。必须当场把原因说出来。
422
+ if ((nebula.graph?.nodes?.length ?? 0) === 0) {
423
+ const bad = (o.readErrors || []).map((e) => e.title || e.key).filter(Boolean)
424
+ const stores = (o.sources || []).length
425
+ const why = bad.length
426
+ ? `有 ${bad.length} 个来源读不出来(${bad.join(' / ')})——这不是「记忆丢了」,是没读到。`
427
+ : stores === 0
428
+ ? '一个记忆来源都没接上(用 nebula_sources 看配置)——这不是「记忆丢了」。'
429
+ : '来源都连着,但目前一条都没读进图里(建图一轮约 12s,建完再问一次)——这不是「记忆丢了」。'
430
+ return [
431
+ '宏记忆 · 星图现在还是空的:0 条记忆 / 0 条连接。',
432
+ why,
433
+ o.lastError ? `最近一次错误:${o.lastError}` : '',
434
+ '记忆本身没受影响:这里只是「图里没有节点」,不等于库里没有记忆。',
435
+ ]
436
+ .filter(Boolean)
437
+ .join('\n')
438
+ }
439
+ // [macro-fusion 0.2.71] 列表被截断时必须说:全图有几条、这里列了几条。
440
+ // 一排 12 行写在「枢纽记忆:」下面,读者补的结论是「枢纽就这 12 个」——
441
+ // 而它其实只是「按连接度 × 重要性排的前 12 条」,剩下的 200 条一个字没提。
442
+ // [macro-fusion 0.2.75] 但「剩下的 200 条」不等于「还有 200 个枢纽」:那 200 条里
443
+ // 大多是只有一两条边、甚至一条边都没有的记忆。旧写法 `s.nodes - top.length`
444
+ // 把孤立记忆也算成「没列出的枢纽」,还要再补一句安抚话打圆场。
445
+ // 现在抬头不报数,尾注由 hubTail() 一处说清:列了几条 / 有连接的共几条 / 上限几条。
446
+ const pool = Math.max(0, (s.nodes || 0) - (s.orphans || 0))
447
+ const lines = [
448
+ `宏记忆 · 星图:${s.nodes} 条记忆 / ${s.edges} 条连接 / ${s.workspaces} 个工作区 / ${s.sessions} 个会话账本`,
449
+ `平均连接度 ${(s.avgDegree || 0).toFixed(2)},孤立记忆 ${s.orphans} 条,构建耗时 ${o.buildMs}ms`,
450
+ '',
451
+ '工作区:' + o.workspaces.map((w) => `${w.name}(${w.count})`).join(' '),
452
+ '层级:' + Object.entries(o.levels || {}).map(([k, v]) => `${k}(${v})`).join(' '),
453
+ '连接类型:' + Object.entries(o.edgeTypes || {}).map(([k, v]) => `${k}(${v})`).join(' '),
454
+ '',
455
+ '枢纽记忆(按连接度 × 重要性排):',
456
+ ]
457
+ for (const h of top) lines.push(`- [${h.level}] ${h.label} · ${h.ws} · 连接 ${h.degree} · 重要性 ${h.importance}`)
458
+ const hubNote = hubTail(top.length, pool, HUB_CAP)
459
+ if (hubNote) lines.push(hubNote)
460
+ if (o.lastError) lines.push('', '最近一次错误:' + o.lastError)
461
+ if (pHubs.note) lines.push('', pHubs.note)
462
+ return lines.join('\n')
463
+ },
464
+ }),
465
+ )
466
+
467
+ ctx.effect(() =>
468
+ ctx.tools.register({
469
+ name: 'nebula_hygiene',
470
+ description:
471
+ '记忆体检:把六类失效模式查出来给你——疑似重复、该更新了、关系是凑的、超重、没人读过、孤立。只诊断不改任何记忆;要不要合并、删掉、补连接由你或主人决定。',
472
+ parameters: {
473
+ type: 'object',
474
+ properties: {
475
+ kind: {
476
+ type: 'string',
477
+ enum: ['dup', 'stale', 'thin', 'oversize', 'unread', 'orphan'],
478
+ description: '只看某一类;不传就返回全部概览。',
479
+ },
480
+ limit: { type: 'number', description: '每类最多列多少条,默认 6。' },
481
+ },
482
+ required: [],
483
+ additionalProperties: false,
484
+ },
485
+ output: out,
486
+ async execute(args = {}) {
487
+ if (!nebula.graph || nebula.graph.nodes.length === 0) await nebula.refresh()
488
+ const h = await nebula.hygieneAsync()
489
+ // [macro-fusion 0.2.40] 空图时「共 0 项」会被读成「很干净」——那其实是没算。
490
+ // 凭据只能用「图里有多少节点」:h.total 是「查出多少毛病」,两种情况下都可能是 0。
491
+ if ((nebula.graph?.nodes?.length ?? 0) === 0) {
492
+ return '记忆体检:星图里还没有节点(图是空的),这次体检等于没算——「0 项」不是「很干净」。等星图建起来(约 12s 一轮巡检)再查一次;记忆本身没受影响。'
493
+ }
494
+ const items = h.items || {}
495
+ const pLim = numParam('limit', args.limit, { min: 1, max: 20, def: 6 })
496
+ const limit = pLim.value
497
+ const NAME = {
498
+ dup: '疑似重复',
499
+ stale: '该更新了',
500
+ thin: '关系是凑的',
501
+ oversize: '超重',
502
+ unread: '没人读过',
503
+ orphan: '孤立',
504
+ }
505
+ const kinds = args.kind ? [args.kind] : Object.keys(NAME)
506
+ // [macro-fusion 0.2.64] 不认识的类别不许打成「undefined(0)」:那行看起来像
507
+ // 「这一类是 0 条」,真实是「这一类根本不在体检范围内」。融合层已经按白名单挡过,
508
+ // 这层是给直接用 nebula_hygiene 的宿主兜底——名字取不到就把键原样打出来。
509
+ const labelOf = (k) => NAME[k] ?? String(k)
510
+ const counts = h.counts || {}
511
+ const lines = [`记忆体检:共 ${h.total} 项(只诊断,不动任何记忆)`]
512
+ for (const k of kinds) {
513
+ const arr = items[k] || []
514
+ const n = counts[k] || arr.length
515
+ if (!n) {
516
+ lines.push('', `${labelOf(k)}(0)`)
517
+ continue
518
+ }
519
+ // [macro-fusion 0.2.74] 一个列表被两处截断(引擎每类最多留 40 条 + 参数 limit),
520
+ // 正文却只在抬头报了一处,而且报的是**引擎那本账**:counts=100、items 已截到 40、
521
+ // limit=6 时抬头写「这里只列前 40 条」,正文其实只有 6 行,尾注「还有 94 条」。
522
+ // 三个数字各说各的,读者拿哪个都算不对。现在只报一处:抬头只给全量计数,
523
+ // 真正的「列了几条 / 还剩几条」由 listTail() 统一说。
524
+ const printed = Math.min(limit, arr.length)
525
+ lines.push('', `${labelOf(k)}(${n})`)
526
+ for (const it of arr.slice(0, printed)) {
527
+ if (k === 'dup' && it.a && it.b) {
528
+ lines.push(`- ${cut(it.a.label || '', 40)} ⇄ ${cut(it.b.label || '', 40)}(相似 ${it.sim})`)
529
+ lines.push(` A: ${it.a.id}`)
530
+ lines.push(` B: ${it.b.id}`)
531
+ continue
532
+ }
533
+ const extra = k === 'oversize' ? ` · ${it.size} 字` : k === 'thin' ? ` · 度 ${it.degree} 均权 ${it.avg}` : ''
534
+ lines.push(`- [${it.level || ''}] ${cut(it.label || '', 50)} · ${it.ws || ''}${extra}`)
535
+ lines.push(` ${it.id}`)
536
+ }
537
+ const tail = listTail(n, printed, limit)
538
+ if (tail) lines.push(tail)
539
+ }
540
+ lines.push('', '要动手就按 id 来:合并/改写属于别人的记忆库,先问主人;星图这边只提供 nebula_link(action="mute") 断掉错误关联。')
541
+ if (pLim.note) lines.push('', pLim.note)
542
+ return lines.join('\n')
543
+ },
544
+ }),
545
+ )
546
+
547
+ // ---------- 跨插件协同:补充包 / 来源体检 / 外部推送 ----------
548
+ ctx.effect(() =>
549
+ ctx.tools.register({
550
+ name: 'nebula_bridge',
551
+ description:
552
+ '跨记忆插件的「补充包」。把别的记忆插件刚注入或刚检索到的记忆 id 交给星图,它沿已算好的关联扩散一跳,去掉已经注入过的,按预算挑出 2~4 条「强相关但还没讲过」的记忆。适合:你刚用 meow-memory / hindsight / openviking 检索过,想知道还有什么该一起读;或你只想补上下文,不想重复读同一批。',
553
+ parameters: {
554
+ type: 'object',
555
+ properties: {
556
+ memory_ids: {
557
+ type: 'array',
558
+ items: { type: 'string' },
559
+ description: '种子记忆 id(任意插件的完整 id 或裸 id 都行)。',
560
+ },
561
+ query: { type: 'string', description: '没有 memory_ids 时,用查询词找种子。' },
562
+ limit: { type: 'number', description: '最多返回几条,默认 4。' },
563
+ chars: { type: 'number', description: '文本预算(字符),默认 900。' },
564
+ min_weight: { type: 'number', description: '最低关联权重,默认 0.5。' },
565
+ hops: { type: 'number', description: '扩散跳数,默认 1。' },
566
+ },
567
+ required: [],
568
+ additionalProperties: false,
569
+ },
570
+ output: out,
571
+ async execute(args = {}) {
572
+ if (!nebula.graph || nebula.graph.nodes.length === 0) await nebula.refresh()
573
+ const ids = Array.isArray(args.memory_ids) ? args.memory_ids.filter((x) => typeof x === 'string' && x.trim()) : []
574
+ const query = String(args.query || '').trim()
575
+ if (ids.length === 0 && !query) return 'nebula_bridge 需要 memory_ids 或 query 至少一个。'
576
+ const pLim = numParam('limit', args.limit, { min: 1, max: 12, def: 4 })
577
+ const pChars = numParam('chars', args.chars, { min: 200, max: 4000, def: 900 })
578
+ const pWeight = numParam('min_weight', args.min_weight, { min: 0, max: 1, def: 0.5 })
579
+ const pHops = numParam('hops', args.hops, { min: 0, max: 2, def: 1 })
580
+ const notes = [pLim.note, pChars.note, pWeight.note, pHops.note].filter(Boolean)
581
+ const res = nebula.bridge({
582
+ ids,
583
+ query,
584
+ mark: true,
585
+ budget: {
586
+ maxItems: pLim.value,
587
+ maxChars: pChars.value,
588
+ minWeight: pWeight.value,
589
+ hops: pHops.value,
590
+ },
591
+ })
592
+ if (!res || !res.items?.length) {
593
+ // [macro-fusion 0.2.44] 原来这里只有一句「种子 N 条、候选 M 条都已读过或在冷却期」,
594
+ // 也在背两意:种子 0 条根本不是「都读过」,是「一条都没在图里找到」——
595
+ // 图还没建起来、id 写错、刚写还没入图,全都落进这句话。四种情况分开说。
596
+ const totalB = nebula.graph?.nodes?.length ?? 0
597
+ const seedsB = res?.stats?.seedCount ?? 0
598
+ const consideredB = res?.stats?.considered ?? 0
599
+ const askedB = ids.length ? `你给的 ${ids.length} 个 id` : `查询「${query}」`
600
+ const whyB =
601
+ totalB === 0
602
+ ? '星图里还没有节点(图是空的),这次 nebula_bridge 等于没算(不是「没有相关记忆」)。等星图建起来(约 12s 一轮巡检)再问一次;记忆本身没受影响。'
603
+ : seedsB === 0
604
+ ? `${askedB}一条都没在图里找到种子——可能是刚写还没入图(约 12s 一轮巡检),也可能 id 不对(裸 id 给前 12 位就够)。先用 memory_search 确认 id 再问。`
605
+ : consideredB === 0
606
+ ? `有 ${seedsB} 条种子,但邻居都被过滤掉了(已读过 / 冷却期 / 权重低于 min_weight / 归档)。把 min_weight 调低一点,或换一条没读过的种子。`
607
+ : `候选 ${consideredB} 条,但没有一条进得了预算(可能都在同一工作区、已被 seen 标记,或字符预算太小)。加一点 chars 再试。`
608
+ return ['nebula_bridge:这次没补到东西。', ` ${whyB}`, '这不是「图里没有相关记忆」。', ...notes].join('\n')
609
+ }
610
+ return [
611
+ `nebula_bridge:从 ${res.stats.seedCount} 条种子扩散,候选 ${res.stats.considered} 条,选出 ${res.items.length} 条(${res.stats.chars} 字)`,
612
+ res.text,
613
+ ...notes,
614
+ ].join('\n')
615
+ },
616
+ }),
617
+ )
618
+
619
+ ctx.effect(() =>
620
+ ctx.tools.register({
621
+ name: 'nebula_sources',
622
+ description:
623
+ '记忆来源体检 + 接入指南。列出星图现在接了哪些记忆库(meow / 笔记目录 / 任意 SQLite / 外部推送)、各自读到多少条、配置文件在哪、有哪些适配器可用。要接入一个新的记忆插件时先调它,按返回的 hint 填配置即可;改完再调一次确认。',
624
+ parameters: {
625
+ type: 'object',
626
+ properties: {
627
+ verbose: { type: 'boolean', description: '是否列出每个适配器的配置字段说明,默认 false。' },
628
+ },
629
+ required: [],
630
+ additionalProperties: false,
631
+ },
632
+ output: out,
633
+ async execute(args = {}) {
634
+ const r = nebula.sourcesReport ? await nebula.sourcesReport() : null
635
+ if (!r) return '星图引擎还没起来(等宿主重启后生效)。'
636
+ const lines = []
637
+ lines.push(`配置:${r.config.path}${r.config.exists ? '' : '(还没有,可新建)'}${r.config.error ? ' · 读坏了:' + r.config.error : ''}`)
638
+ lines.push(`自动探测:${r.config.autoDetect ? '开' : '关'}`)
639
+ lines.push('')
640
+ // [macro-fusion 0.2.43] 「已接入 0 个来源,共读到 0 条记忆」这句话也背两个意思:
641
+ // 一个是「真的没接」(配置没建 / 探测关着),一个是「接了没读到」(读失败 / 还没扫)。
642
+ // 用户读到第一行的第一反应是「记忆没了」,所以这里要把这次具体是哪一种说出来。
643
+ if (r.live.stores.length === 0) {
644
+ const bad = (r.live.errors || []).map((e) => e.store || e.adapter).filter(Boolean)
645
+ const why = bad.length
646
+ ? `有 ${bad.length} 处读失败(${bad.join(' / ')})——不是「没有记忆」,是没读到(下面列了原因)。`
647
+ : r.config.exists === false
648
+ ? `配置文件还没建(${r.config.path})——所以一个来源都没接上。这不等于「记忆没了」。`
649
+ : r.config.autoDetect === false
650
+ ? '自动探测关着(autoDetect: false),也没有手写来源——是「没接」,不是「没记忆」。'
651
+ : '配置在、自动探测也开着,但这次一个来源都没扫到——可能刚启动还没扫完(一轮约 12s),过一会儿再问一次;这不等于「记忆没了」。'
652
+ lines.push('已接入 0 个来源,共读到 0 条记忆——这句有两种意思:')
653
+ lines.push(` ${why}`)
654
+ } else {
655
+ lines.push(`已接入 ${r.live.stores.length} 个来源,共读到 ${r.live.nodes} 条记忆:`)
656
+ for (const s of r.live.stores) {
657
+ lines.push(`- [${s.adapter}] ${s.title} · ${s.size ? Math.round(s.size / 1024) + 'KB' : '—'}${s.hasSessions ? ' · 有会话账本' : ''}`)
658
+ lines.push(` ${s.path}`)
659
+ }
660
+ // [macro-fusion 0.2.43] 来源接上了但 0 条:空库与路径写错长得一样,得说一句。
661
+ if (r.live.nodes === 0) lines.push(' (来源接上了,但一条记忆都没读到:可能是库真是空的,也可能是路径指错了。)')
662
+ }
663
+ if (r.graph) {
664
+ lines.push('')
665
+ lines.push(`星图:${r.graph.nodes} 节点 / ${r.graph.edges} 边 / ${r.graph.workspaces} 工作区 / ${r.graph.sessions} 会话`)
666
+ }
667
+ if (r.live.errors?.length) {
668
+ lines.push('')
669
+ lines.push('读取失败:')
670
+ for (const e of r.live.errors) lines.push(`- ${e.store || e.adapter}:${e.error}`)
671
+ }
672
+ lines.push('')
673
+ lines.push('可用适配器:')
674
+ for (const a of r.adapters) {
675
+ lines.push(`- ${a.id}(${a.kind})${a.name}:${a.description}`)
676
+ if (args.verbose !== false && a.config && Object.keys(a.config).length > 0) {
677
+ for (const [k, v] of Object.entries(a.config)) lines.push(` ${k}: ${v}`)
678
+ }
679
+ }
680
+ lines.push('')
681
+ lines.push(r.hint)
682
+ return lines.join('\n')
683
+ },
684
+ }),
685
+ )
686
+
687
+ ctx.effect(() =>
688
+ ctx.tools.register({
689
+ name: 'nebula_ingest',
690
+ description:
691
+ '把外部记忆推入星图。给「记忆不在本地落盘」的服务用(远端 hindsight / openviking / 或任何 API-only 记忆插件):把条目推过来,它们就进同一张图,和 meow 的记忆一起参与关联与注入。同 uid 后写覆盖,重复推送不会长重影。',
692
+ parameters: {
693
+ type: 'object',
694
+ properties: {
695
+ provider: { type: 'string', description: '来源名,例如 hindsight / openviking / my-memory。' },
696
+ items: {
697
+ type: 'array',
698
+ description: '记忆条目。至少给 title 或 content。',
699
+ items: {
700
+ type: 'object',
701
+ properties: {
702
+ uid: { type: 'string', description: '稳定 id;不给就按内容哈希。' },
703
+ title: { type: 'string' },
704
+ content: { type: 'string' },
705
+ level: { type: 'string', description: 'soul / user / project / fact / lesson / topic / rules / note' },
706
+ keywords: { type: 'array', items: { type: 'string' } },
707
+ project: { type: 'string' },
708
+ importance: { type: 'number' },
709
+ status: { type: 'string' },
710
+ ws: { type: 'string', description: '归属工作区名(展示用)。' },
711
+ createdAt: { type: 'number', description: '毫秒时间戳。' },
712
+ },
713
+ additionalProperties: true,
714
+ },
715
+ },
716
+ },
717
+ required: ['provider', 'items'],
718
+ additionalProperties: false,
719
+ },
720
+ output: out,
721
+ async execute(args = {}) {
722
+ const provider = String(args.provider || '').trim()
723
+ const items = Array.isArray(args.items) ? args.items : []
724
+ if (!provider) return 'nebula_ingest 需要 provider。'
725
+ if (items.length === 0) return 'nebula_ingest 需要至少一条 items。'
726
+ const res = await nebula.ingest(provider, items)
727
+ if (res.error) return `没有写成任何一条:${res.error}`
728
+ return [
729
+ `已推入 ${res.written} 条 → ${res.file}` + (res.note ? `(${res.note})` : ''),
730
+ res.graph ? `星图现在是 ${res.graph.nodes} 节点 / ${res.graph.edges} 边` : '重建未完成(下次请求时生效)',
731
+ ].join('\n')
732
+ },
733
+ }),
734
+ )
735
+
736
+ // ---------- 常驻注入:只放一段稳定规则 ----------
737
+ //
738
+ // 这里原来每轮会额外注入「本会话该被连带读出的邻居」:读 meow 账本当种子 → bridge 沿星图
739
+ // 扩散 → 挑 ≤maxItems 条、≤maxChars 字,最多 maxRounds 批。
740
+ //
741
+ // 2026-11-18 移除这段自动注入,三条理由:
742
+ // 1. 缓存:system prompt 在请求最前面,它一变,它后面整段对话历史都从前缀缓存里掉出来
743
+ // 重新 prefill —— 代价 ≈ 当前上下文 token 数,而换回来的信息只有几百字符(约 36:1)。
744
+ // 而且第 2 批会顶掉第 1 批,模型上一轮刚看到的邻居下一轮就没了。
745
+ // 2. 位置:注入不是唯一出口。真要邻居的时候,模型正在查记忆,让它调工具拿更准。
746
+ // 3. 可控:自动注入的收益无法度量,成本却每轮都在付。
747
+ //
748
+ // 邻域能力没有删,只是改成按需:nebula_recall(memory_ids=[…]) 与 nebula_bridge(…) 仍在,
749
+ // 走同一套 bridge 逻辑,结果落在工具返回里(会话尾部,不伤前缀缓存)。
750
+ ctx.effect(() =>
751
+ ctx.systemPrompt.context({
752
+ name: 'memory-nebula:rules',
753
+ order: 960,
754
+ text: () => RULE,
755
+ }),
756
+ )
757
+
758
+ log(`宏记忆 · 星图已启动:${live.instance?.stores?.length ?? 0} 个记忆库候选`)
759
+ }