dsh-macro-memory 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +506 -2
- package/cordis.patch.yml +6 -0
- package/lib/client.js +3623 -0
- package/lib/index.js +502 -0
- package/lib/macro/brand.js +82 -0
- package/lib/macro/bridge.js +158 -0
- package/lib/macro/chain.js +206 -0
- package/lib/macro/contract.js +471 -0
- package/lib/macro/cost.js +164 -0
- package/lib/macro/defs/admin.js +442 -0
- package/lib/macro/defs/dream.js +24 -0
- package/lib/macro/defs/link.js +257 -0
- package/lib/macro/defs/project.js +25 -0
- package/lib/macro/defs/read.js +160 -0
- package/lib/macro/defs/remember.js +411 -0
- package/lib/macro/defs/search.js +871 -0
- package/lib/macro/defs/update.js +161 -0
- package/lib/macro/dreamledger.js +1398 -0
- package/lib/macro/facade.js +135 -0
- package/lib/macro/fusion.js +182 -0
- package/lib/macro/linkflow.js +391 -0
- package/lib/macro/links.js +448 -0
- package/lib/macro/neighbor.js +209 -0
- package/lib/macro/panel.js +96 -0
- package/lib/macro/prompt.js +139 -0
- package/lib/macro/provenance.js +148 -0
- package/lib/macro/render.js +35 -0
- package/lib/macro/revisions.js +253 -0
- package/lib/macro/shared.js +113 -0
- package/lib/macro/store.js +103 -0
- package/lib/macro/supersede.js +197 -0
- package/lib/macro/tokencost.js +90 -0
- package/lib/macro/tools.js +67 -0
- package/package.json +54 -4
- package/vendor/VENDOR.json +23 -0
- package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
- package/vendor/dsh-memory-nebula/LICENSE +21 -0
- package/vendor/dsh-memory-nebula/README.en.md +203 -0
- package/vendor/dsh-memory-nebula/README.md +253 -0
- package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
- package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
- package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
- package/vendor/dsh-memory-nebula/lib/client.js +105 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
- package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
- package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
- package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
- package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
- package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
- package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
- package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
- package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
- package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
- package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
- package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
- package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
- package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
- package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
- package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
- package/vendor/dsh-memory-nebula/lib/host/recall.js +524 -0
- package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
- package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
- package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
- package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
- package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
- package/vendor/dsh-memory-nebula/lib/index.js +782 -0
- package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
- package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
- package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
- package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
- package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
- package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
- package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
- package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
- package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
- package/vendor/dsh-memory-nebula/locale/en.json +7 -0
- package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
- package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
- package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
- package/vendor/dsh-memory-nebula/market/index.json +101 -0
- package/vendor/dsh-memory-nebula/package.json +87 -0
- package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
- package/vendor/meow-memory/LICENSE +21 -0
- package/vendor/meow-memory/README.en.md +192 -0
- package/vendor/meow-memory/README.md +174 -0
- package/vendor/meow-memory/README.pt-br.md +180 -0
- package/vendor/meow-memory/cordis.patch.yml +7 -0
- package/vendor/meow-memory/lib/client.js +3344 -0
- package/vendor/meow-memory/lib/client.js.map +7 -0
- package/vendor/meow-memory/lib/index.js +9802 -0
- package/vendor/meow-memory/lib/index.js.map +7 -0
- package/vendor/meow-memory/lib/prompts/README.md +65 -0
- package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
- package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
- package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
- package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
- package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
- package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
- package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
- package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
- package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
- package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
- package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
- package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
- package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
- package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
- package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
- package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
- package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
- package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
- package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
- package/vendor/meow-memory/package.json +64 -0
|
@@ -0,0 +1,2105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [macro-fusion 0.2.11] 导出 Markdown 的抬头跟着显示名改成「宏记忆 · 星图导出」。
|
|
3
|
+
*
|
|
4
|
+
* 星图的状态机:发现来源 → 只读抽取 → 建图 → 缓存 → 广播变更。
|
|
5
|
+
*
|
|
6
|
+
* 这里对「别的插件的文件」只做三件事:stat、readFile、SQLite 只读打开。
|
|
7
|
+
* 没有写操作,没有迁移,没有 mark。
|
|
8
|
+
*/
|
|
9
|
+
import { EventEmitter } from 'node:events'
|
|
10
|
+
import { existsSync, readdirSync, statSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { homedir } from 'node:os'
|
|
13
|
+
import { readInventory, nebulaHome, dshHome } from './sources.js'
|
|
14
|
+
import { cacheDir, cacheEnabled, implFingerprint, loadGraphCache, loadNewestGraphCache, saveGraphCache, sourceSetKey } from './graphcache.js'
|
|
15
|
+
import { discoverSources, scanAllAsync, probeAll, adapterCatalog } from './adapters/index.js'
|
|
16
|
+
import { appendIngest, describeSkips } from './adapters/ingest.js'
|
|
17
|
+
import { buildGraphAsync, findNode, auditHygiene, auditHygieneAsync } from './graph.js'
|
|
18
|
+
import { recall, recallAsync, resolveIds, ensureTokenCacheAsync } from './recall.js'
|
|
19
|
+
import { bridge as bridgeFn } from './bridge.js'
|
|
20
|
+
import { readLedger, markSeen, readCooldown, markCooldown, ledgerStats } from './ledger.js'
|
|
21
|
+
import {
|
|
22
|
+
addLink,
|
|
23
|
+
listLinks,
|
|
24
|
+
logEvent,
|
|
25
|
+
removeLink,
|
|
26
|
+
cacheGet,
|
|
27
|
+
cacheSet,
|
|
28
|
+
getMeta,
|
|
29
|
+
setMeta,
|
|
30
|
+
addMute,
|
|
31
|
+
listMutes,
|
|
32
|
+
removeMute,
|
|
33
|
+
storeRecovery,
|
|
34
|
+
} from './store.js'
|
|
35
|
+
import { clip, hueOf, tokenize } from './text.js'
|
|
36
|
+
import { pageOrder, selectPage } from './page.js'
|
|
37
|
+
import { DEMO_MEMORIES, DEMO_LEDGERS, DEMO_MANUAL, DEMO_INVENTORY, DEMO_SOURCES, DEMO_SIGNATURE } from './demo.js'
|
|
38
|
+
|
|
39
|
+
/** HSL → #rrggbb(固定的 72%/62% 亮度,保证深空里够亮又不刺眼)。 */
|
|
40
|
+
function hslHex(hue, sat = 72, light = 62) {
|
|
41
|
+
const h = ((hue % 360) + 360) % 360
|
|
42
|
+
const s = sat / 100
|
|
43
|
+
const l = light / 100
|
|
44
|
+
const c = (1 - Math.abs(2 * l - 1)) * s
|
|
45
|
+
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
|
|
46
|
+
const m = l - c / 2
|
|
47
|
+
let r = 0
|
|
48
|
+
let g = 0
|
|
49
|
+
let b = 0
|
|
50
|
+
if (h < 60) [r, g, b] = [c, x, 0]
|
|
51
|
+
else if (h < 120) [r, g, b] = [x, c, 0]
|
|
52
|
+
else if (h < 180) [r, g, b] = [0, c, x]
|
|
53
|
+
else if (h < 240) [r, g, b] = [0, x, c]
|
|
54
|
+
else if (h < 300) [r, g, b] = [x, 0, c]
|
|
55
|
+
else [r, g, b] = [c, 0, x]
|
|
56
|
+
const to = (v) => Math.round((v + m) * 255).toString(16).padStart(2, '0')
|
|
57
|
+
return '#' + to(r) + to(g) + to(b)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 扫描默认根:常见的工作区父目录(用来抓注册表漏掉的项目)。 */
|
|
61
|
+
function defaultRoots() {
|
|
62
|
+
const roots = []
|
|
63
|
+
const seen = new Set()
|
|
64
|
+
const candidates = [join(homedir(), 'Documents'), join(homedir(), 'document'), process.cwd()]
|
|
65
|
+
for (const c of candidates) {
|
|
66
|
+
try {
|
|
67
|
+
if (!c || seen.has(c)) continue
|
|
68
|
+
seen.add(c)
|
|
69
|
+
if (existsSync(c)) roots.push(c)
|
|
70
|
+
} catch {
|
|
71
|
+
/* ignore */
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return roots
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 找不到节点时抛的错误:带 404,接口层才不会把它当服务器故障。 */
|
|
78
|
+
function missingNodes(a, b) {
|
|
79
|
+
const err = new Error('找不到这两条记忆:' + a + ' / ' + b)
|
|
80
|
+
err.status = 404
|
|
81
|
+
return err
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 一条记忆和自己配对(连自己、屏蔽自己)。
|
|
86
|
+
* 以前这种请求会被照「成功」处理:库里多一行策展记录,图上什么都不会发生——
|
|
87
|
+
* 调用方看到 ok:true,界面上却找不到那条线(1.11.64)。
|
|
88
|
+
*/
|
|
89
|
+
function selfPair(id) {
|
|
90
|
+
const err = new Error('不能把一条记忆和它自己配成一对:' + id)
|
|
91
|
+
err.status = 400
|
|
92
|
+
return err
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 建图的阶段顺序(与 buildGraphSteps 的 yield 一一对应,含前置的 scan)。 */
|
|
96
|
+
export const BUILD_STAGES = ['scan', 'nodes', 'df', 'sig', 'postings', 'cand', 'score', 'prune', 'sources', 'cluster', 'output']
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 多大的库算「该有人提醒你一声」。
|
|
100
|
+
* 20 万条实测(1.11.34):建图 24.5 秒、堆 1.2GB、整图 JSON 106MB。
|
|
101
|
+
* 这不是硬上限——超过了照样能跑,只是该让人知道自己在等什么、机器在吃什么。
|
|
102
|
+
*/
|
|
103
|
+
export const LARGE_LIBRARY_NODES = 150000
|
|
104
|
+
|
|
105
|
+
/** 阶段的中文名:进度条上要说人话,不把内部键名丢给用户看。 */
|
|
106
|
+
const STAGE_LABELS = {
|
|
107
|
+
scan: '读来源',
|
|
108
|
+
nodes: '整理节点',
|
|
109
|
+
df: '统计词频',
|
|
110
|
+
sig: '挑签名',
|
|
111
|
+
postings: '建倒排',
|
|
112
|
+
cand: '找候选对',
|
|
113
|
+
score: '给关联打分',
|
|
114
|
+
prune: '剪掉弱连接',
|
|
115
|
+
sources: '接上来源',
|
|
116
|
+
cluster: '聚类',
|
|
117
|
+
output: '收尾',
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* [macro-fusion 0.2.71] 枢纽条数的上限:schema 写「上限 40」,实现却把列表钉死在 12 条。
|
|
122
|
+
*
|
|
123
|
+
* `nebula_stats` 的 `hubs` 参数一路传到概览这里,却被一个写死的数字截住 —— 给它 20、40,
|
|
124
|
+
* 出来的永远是最多 12 条,回执一个字不提。要「统一面板口径」,先得让参数与实现说同一句话:
|
|
125
|
+
* 上限只留一个出处(`HUB_CAP`),`overview()` 按调用方要的条数取。
|
|
126
|
+
*/
|
|
127
|
+
/**
|
|
128
|
+
* [macro-fusion 0.2.75] 枢纽榜的上限:一个数字,三个地方在说它。
|
|
129
|
+
*
|
|
130
|
+
* 0.2.71 只把「取多少条」收到 `hubSlots` 一处,可「上限是 40」还写在另外两处:
|
|
131
|
+
* `nebula_stats` 的 `numParam('hubs', …, { max: 40 })`(夹参数用)和正文里那句
|
|
132
|
+
* 「(本次 12 条,上限 40)」(说给读者听)。三处字面量,改一处忘两处就会互相撒谎——
|
|
133
|
+
* 参数放开到 80、正文仍写「上限 40」,读者会以为自己没要够。上限本身收到这里。
|
|
134
|
+
*/
|
|
135
|
+
export const HUB_CAP = 40
|
|
136
|
+
|
|
137
|
+
export function hubSlots(value, def = 12) {
|
|
138
|
+
const n = Math.trunc(Number(value))
|
|
139
|
+
if (!Number.isFinite(n) || n <= 0) return def
|
|
140
|
+
return Math.min(HUB_CAP, n)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export class Nebula extends EventEmitter {
|
|
144
|
+
constructor(options = {}) {
|
|
145
|
+
super()
|
|
146
|
+
// 两个调用方各用一套名字:宿主用 logger,独立引擎 CLI 用 log;roots 同理。
|
|
147
|
+
// 以前只认 logger/extraRoots,`node lib/standalone.mjs --root D:/x` 的根目录被静默忽略。
|
|
148
|
+
this.logger = options.logger || (typeof options.log === 'function' ? { info: options.log } : null)
|
|
149
|
+
const asList = (v) => (Array.isArray(v) ? v : typeof v === 'string' && v.trim() ? v.split(',').map((s) => s.trim()).filter(Boolean) : [])
|
|
150
|
+
const extra = Array.isArray(options.extraRoots) || typeof options.extraRoots === 'string' ? asList(options.extraRoots) : asList(options.roots)
|
|
151
|
+
this.roots = extra.length > 0 ? extra : defaultRoots()
|
|
152
|
+
/**
|
|
153
|
+
* 演示模式:不读任何真实库,用 lib/host/demo.js 的内置数据建同一张图。
|
|
154
|
+
* 走的是完全相同的 buildGraph / detail / recall / path 代码路径,
|
|
155
|
+
* 这样「示例里能用的功能」和「真实库里的功能」不会分叉。
|
|
156
|
+
*/
|
|
157
|
+
this.demo = Boolean(options.demo)
|
|
158
|
+
this.stores = []
|
|
159
|
+
this.nodes = []
|
|
160
|
+
this.ledgers = []
|
|
161
|
+
this.inventory = { plugins: [], skills: [], mcp: [] }
|
|
162
|
+
this.graph = { nodes: [], edges: [], clusters: [], stats: { nodes: 0, edges: 0 }, builtAt: 0 }
|
|
163
|
+
this.signature = ''
|
|
164
|
+
this.building = false
|
|
165
|
+
/**
|
|
166
|
+
* 建图走到哪了:{ stage, label, step, total, nodes, ms, at },没在建就是 null。
|
|
167
|
+
* 界面靠它把「转圈」换成「读来源 / 整理节点 / 第 3 步 · 共 11 步」。
|
|
168
|
+
*/
|
|
169
|
+
this.buildProgress = null
|
|
170
|
+
/** 后台重建的那次请求(refreshInBackground):并发时复用同一个 promise,不另起一轮 */
|
|
171
|
+
this._bgPromise = null
|
|
172
|
+
/** 正在等这一轮建图的调用方:冷启动时并发请求不该拿到一张空图。 */
|
|
173
|
+
this._waiters = []
|
|
174
|
+
/**
|
|
175
|
+
* 建完图之后隔多久在后台预热检索缓存(毫秒)。
|
|
176
|
+
* 单测会调小到几十毫秒;生产里留一拍,别让「刚刷新完」的那几个请求跟预抢 CPU。
|
|
177
|
+
*/
|
|
178
|
+
// 建好的图存哪儿:跟 sidecar 库同一个 home,主人要清就一起清。
|
|
179
|
+
this.cacheDir = cacheDir(nebulaHome())
|
|
180
|
+
this.lastCache = null
|
|
181
|
+
/** 现在这张图是从过期缓存恢复的(签名对不上),后台正在按新签名重建 */
|
|
182
|
+
this.staleGraph = false
|
|
183
|
+
this._bgRefreshPending = false
|
|
184
|
+
this._bgForce = false
|
|
185
|
+
// 体检也是「算一次就能复用」的东西,而且五万条上要 2.3 秒——
|
|
186
|
+
// 与其等用户点开看板时才在请求里算,不如后台先算好。NEBULA_HYGIENE_WARM=0 可关。
|
|
187
|
+
// 门槛可以用选项或环境变量调:探针要能在一个小库上演出「库里很大」这场戏,
|
|
188
|
+
// 真实用户也可能有自己的判断(比如机器内存小,十万条就该提醒)。
|
|
189
|
+
this.largeLibraryNodes = Number.isFinite(options.largeLibraryNodes)
|
|
190
|
+
? options.largeLibraryNodes
|
|
191
|
+
: Number.isFinite(Number(process.env.NEBULA_LARGE_LIBRARY))
|
|
192
|
+
? Number(process.env.NEBULA_LARGE_LIBRARY)
|
|
193
|
+
: LARGE_LIBRARY_NODES
|
|
194
|
+
this.scale = null
|
|
195
|
+
this.hygieneWarm = options.hygieneWarm !== false && process.env.NEBULA_HYGIENE_WARM !== '0'
|
|
196
|
+
this.lastHygieneWarm = null
|
|
197
|
+
this.prewarmDelayMs = Number.isFinite(options.prewarmDelayMs)
|
|
198
|
+
? options.prewarmDelayMs
|
|
199
|
+
: Number.isFinite(Number(process.env.NEBULA_PREWARM_DELAY))
|
|
200
|
+
? Number(process.env.NEBULA_PREWARM_DELAY)
|
|
201
|
+
: 1200
|
|
202
|
+
this._prewarmTimer = null
|
|
203
|
+
this.lastPrewarm = null
|
|
204
|
+
this.lastError = ''
|
|
205
|
+
this.storeErrors = []
|
|
206
|
+
this.storeWarnings = []
|
|
207
|
+
this.configError = ''
|
|
208
|
+
this.lastBuildMs = 0
|
|
209
|
+
this.cacheAgeMs = 0
|
|
210
|
+
this.timer = null
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** 写一条日志到 $DSH_HOME/memory-nebula/nebula.log(不污染宿主日志)。 */
|
|
214
|
+
log(line) {
|
|
215
|
+
const text = `[${new Date().toISOString()}] ${line}\n`
|
|
216
|
+
try {
|
|
217
|
+
const dir = nebulaHome()
|
|
218
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
219
|
+
writeFileSync(join(dir, 'nebula.log'), text, { flag: 'a' })
|
|
220
|
+
} catch {
|
|
221
|
+
/* ignore */
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
this.logger?.info?.(`[memory-nebula] ${line}`)
|
|
225
|
+
} catch {
|
|
226
|
+
/* ignore */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* 变化指纹:来源库的 size+mtime、会话账本目录的条目数、人工边数量。
|
|
232
|
+
* 只要这些没变,就不重建图(重建一次约几百毫秒)。
|
|
233
|
+
*/
|
|
234
|
+
computeSignature() {
|
|
235
|
+
if (this.demo) {
|
|
236
|
+
this.stores = DEMO_SOURCES
|
|
237
|
+
return DEMO_SIGNATURE
|
|
238
|
+
}
|
|
239
|
+
const found = discoverSources({ extraRoots: this.roots })
|
|
240
|
+
const { stores } = found
|
|
241
|
+
// sources.json 读不出来时,配置里声明的来源会整批消失。这里把它留下来,
|
|
242
|
+
// 由 #warnings() 报给界面——「你的配置坏了」不能只发生在日志里。
|
|
243
|
+
this.configError = found.config && found.config.error ? String(found.config.error) : ''
|
|
244
|
+
this.stores = stores
|
|
245
|
+
const parts = []
|
|
246
|
+
for (const store of stores) {
|
|
247
|
+
parts.push(`${store.id}:${store.size}:${Math.round(store.mtimeMs || 0)}`)
|
|
248
|
+
// 库是 WAL 模式时(meow-memory 就是),新写入先进 <db>-wal,主库文件的
|
|
249
|
+
// size/mtime 一动不动。只看主库会得出「没有变化」,于是新记忆永远进不了图,
|
|
250
|
+
// 要等对方进程关库触发 checkpoint 才看得到。所以 WAL 也要算进签名。
|
|
251
|
+
if (store.dbPath) {
|
|
252
|
+
try {
|
|
253
|
+
const wal = statSync(store.dbPath + '-wal')
|
|
254
|
+
// 空的 -wal 不算变化:我们自己每读一次库都会顺手建出一个 0 字节的
|
|
255
|
+
// -wal(WAL 模式是持久设置在库里),把它算进去就变成「读完必变」,
|
|
256
|
+
// 每一次刷新都会以为库变了,永远重建不完。
|
|
257
|
+
if (wal.size > 0) parts.push(`w${Math.round(wal.size)}:${Math.round(wal.mtimeMs)}`)
|
|
258
|
+
} catch {
|
|
259
|
+
/* 没有 -wal:数据已经在主库那份里了,上面那行就够 */
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (!store.sessionsDir) continue
|
|
263
|
+
try {
|
|
264
|
+
const names = readdirSync(store.sessionsDir)
|
|
265
|
+
let latest = 0
|
|
266
|
+
for (const name of names) {
|
|
267
|
+
if (!name.endsWith('.json')) continue
|
|
268
|
+
try {
|
|
269
|
+
latest = Math.max(latest, Math.round(statSync(join(store.sessionsDir, name)).mtimeMs))
|
|
270
|
+
} catch {
|
|
271
|
+
/* ignore */
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
parts.push(`s${names.length}:${latest}`)
|
|
275
|
+
} catch {
|
|
276
|
+
parts.push('s0:0')
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
let linkSig = ''
|
|
280
|
+
try {
|
|
281
|
+
const links = listLinks()
|
|
282
|
+
// 用「条数 + 排序后的 id 对」而不是 updatedAt:重新策展同一对只会刷新时间戳,
|
|
283
|
+
// 图本身一点没变,可签名一变就会让下一次 /graph?refresh=1 白重建一次(1.11.26 修)。
|
|
284
|
+
let h = 0
|
|
285
|
+
for (const l of links) {
|
|
286
|
+
const pair = l.a < l.b ? l.a + '>' + l.b : l.b + '>' + l.a
|
|
287
|
+
for (let i = 0; i < pair.length; i++) h = (h * 31 + pair.charCodeAt(i)) | 0
|
|
288
|
+
}
|
|
289
|
+
linkSig = `l${links.length}:${h}`
|
|
290
|
+
} catch {
|
|
291
|
+
linkSig = 'l0:0'
|
|
292
|
+
}
|
|
293
|
+
const invSig = `${this.inventory?.skills?.length || 0}:${this.inventory?.plugins?.length || 0}:${this.inventory?.mcp?.length || 0}`
|
|
294
|
+
return parts.join('|') + '|' + linkSig + '|' + invSig
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 建图后一次性建好的查找索引。
|
|
299
|
+
*
|
|
300
|
+
* 之前 `detail()` 里每次 `graph.nodes.find(...)`,一次点击在 1300 条记忆上是
|
|
301
|
+
* O(deg·n) 的线性扫;邻居多的节点能扫出几十万次比较。这里全部换成 Map 直取,
|
|
302
|
+
* 另外把邻接表建好,详情面板不用再遍历整张边表。
|
|
303
|
+
*/
|
|
304
|
+
#buildIndex() {
|
|
305
|
+
const g = this.graph
|
|
306
|
+
const byId = new Map()
|
|
307
|
+
const byI = new Map()
|
|
308
|
+
const byUid = new Map()
|
|
309
|
+
const adj = new Map()
|
|
310
|
+
for (const n of g.nodes) {
|
|
311
|
+
byId.set(n.id, n)
|
|
312
|
+
byI.set(n.i, n)
|
|
313
|
+
const uid = String(n.id).split(':').pop()
|
|
314
|
+
if (!byUid.has(uid)) byUid.set(uid, n)
|
|
315
|
+
}
|
|
316
|
+
for (const e of g.edges) {
|
|
317
|
+
let a = adj.get(e.s)
|
|
318
|
+
if (!a) adj.set(e.s, (a = []))
|
|
319
|
+
a.push({ n: e.t, w: e.w, t: e.type, why: e.why, curated: e.curated })
|
|
320
|
+
let b = adj.get(e.t)
|
|
321
|
+
if (!b) adj.set(e.t, (b = []))
|
|
322
|
+
b.push({ n: e.s, w: e.w, t: e.type, why: e.why, curated: e.curated })
|
|
323
|
+
}
|
|
324
|
+
for (const list of adj.values()) list.sort((x, y) => y.w - x.w)
|
|
325
|
+
const rawById = new Map()
|
|
326
|
+
for (const n of this.nodes || []) if (!rawById.has(n.id)) rawById.set(n.id, n)
|
|
327
|
+
this.index = { byId, byI, byUid, adj, rawById }
|
|
328
|
+
// 详情面板的两处「贵操作」加内存缓存:会话转写解码(zstd)与 sidecar 证据读库。
|
|
329
|
+
// 不缓存的话,连点 50 条记忆要 1.5 秒;缓存后只在首次访问时付一次代价。
|
|
330
|
+
this._originCache = new Map()
|
|
331
|
+
this._evCache = new Map()
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 动态加载「可选」引擎模块(会话转写、路径搜索)。
|
|
336
|
+
* 热载目录里可能还没有这些新文件,缺了就让对应功能优雅缺席。
|
|
337
|
+
*/
|
|
338
|
+
async #loadOptionalModules() {
|
|
339
|
+
if (!this._originOfMemory) {
|
|
340
|
+
try {
|
|
341
|
+
const m = await import('./transcripts.js')
|
|
342
|
+
this._originOfMemory = m.originOfMemory
|
|
343
|
+
this._transcriptStats = m.transcriptStats
|
|
344
|
+
this._usageOf = m.usageOf
|
|
345
|
+
} catch {
|
|
346
|
+
this._originOfMemory = null
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (!this._findPath) {
|
|
350
|
+
try {
|
|
351
|
+
const m = await import('./path.js')
|
|
352
|
+
this._findPath = m.findPath
|
|
353
|
+
} catch {
|
|
354
|
+
this._findPath = null
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* 重建星图。返回是否真的重建了。
|
|
361
|
+
* @param {{force?:boolean}} [opts]
|
|
362
|
+
*/
|
|
363
|
+
async refresh(opts = {}) {
|
|
364
|
+
if (this.building) {
|
|
365
|
+
// 等这一轮建完再返回:以前并发请求直接拿到 false + 一张空图,首屏偶尔一片黑。
|
|
366
|
+
await new Promise((resolve) => this._waiters.push(resolve))
|
|
367
|
+
// 1.11.24:把「这次没重建,是因为别人正在建」也如实记下来。
|
|
368
|
+
// 只说「没重建」会被界面读成「什么都没变」,那是两件事。
|
|
369
|
+
this.lastRefresh = { rebuilt: false, why: 'joined', ms: 0, at: Date.now() }
|
|
370
|
+
return false
|
|
371
|
+
}
|
|
372
|
+
this.building = true
|
|
373
|
+
const started = Date.now()
|
|
374
|
+
try {
|
|
375
|
+
// 引擎文件是逐个复制的(热载),新模块可能还没到位 —— 用动态 import 兜住,
|
|
376
|
+
// 缺了就退化成「没有出处 / 没有路径」,而不是整个引擎加载失败。
|
|
377
|
+
await this.#loadOptionalModules()
|
|
378
|
+
const rt0 = Date.now()
|
|
379
|
+
const rtick = (label) => {
|
|
380
|
+
if (process.env.NEBULA_REFRESH_PROFILE) console.error('[refresh] ' + label + ' +' + (Date.now() - rt0) + 'ms')
|
|
381
|
+
}
|
|
382
|
+
rtick('modules')
|
|
383
|
+
const signature = this.computeSignature()
|
|
384
|
+
// 来源集合指纹:宽松读盘(下面 loadNewestGraphCache)靠它分辨「这份图是不是这一批库长出来的」。
|
|
385
|
+
const srcKey = sourceSetKey((this.stores || []).map((st) => st.id))
|
|
386
|
+
rtick('signature')
|
|
387
|
+
// 1.11.28:上次建好的图还躺在盘上、签名一个字节都没变,就别再扫一遍——
|
|
388
|
+
// 五万条库上这一下省掉五秒多,重启之后第一眼就是上次那张图。
|
|
389
|
+
if (!opts.force && this.graph.nodes.length === 0 && cacheEnabled() && !this.demo) {
|
|
390
|
+
let hit = await loadGraphCache(this.cacheDir, signature)
|
|
391
|
+
let stale = false
|
|
392
|
+
let implStale = false
|
|
393
|
+
if (!hit) {
|
|
394
|
+
// 1.11.30:签名对不上不等于这份缓存没用——它就是「上一次的星图」。
|
|
395
|
+
// 以前这里整份作废,于是库里有几条新记忆,重启又要白等五秒多重建。
|
|
396
|
+
hit = await loadNewestGraphCache(this.cacheDir, srcKey)
|
|
397
|
+
stale = Boolean(hit)
|
|
398
|
+
// 1.11.31:这一份可能是**旧算法**建的。来源签名只看库,插件升级它看不出来,
|
|
399
|
+
// 所以严格读盘那边已经不认了;这里当「上一版」先给你看,紧接着按新算法重建。
|
|
400
|
+
if (stale && hit.impl && hit.impl !== 'unknown' && hit.impl !== implFingerprint()) implStale = true
|
|
401
|
+
}
|
|
402
|
+
if (hit && hit.graph.nodes.length > 0) {
|
|
403
|
+
this.nodes = hit.nodes
|
|
404
|
+
this.ledgers = hit.ledgers
|
|
405
|
+
this.graph = hit.graph
|
|
406
|
+
// 旧缓存(1.11.62 之前)里没有 clusters:补一个空数组,
|
|
407
|
+
// 让导出报告这类地方不至于在 .map 上撞 undefined。
|
|
408
|
+
if (!Array.isArray(this.graph.clusters)) this.graph.clusters = []
|
|
409
|
+
// 缓存里不带 sources / inventory:一个来自注册表、一个来自人写的清单,都很便宜,
|
|
410
|
+
// 而且它们要是变了,签名本来就会变(签名里含来源文件的 mtime 与清单内容)。
|
|
411
|
+
this.inventory = readInventory()
|
|
412
|
+
this.graph.inventory = this.inventory
|
|
413
|
+
// 「哪个库读不动」这句诊断要跟着缓存一起回来:只按当前来源反过来拼的话,
|
|
414
|
+
// error 全是空,重启之后坏来源就既不进图、也不告示(1.11.33 修)。
|
|
415
|
+
const cachedSources = Array.isArray(hit.graph.sources) ? hit.graph.sources : []
|
|
416
|
+
const errById = new Map()
|
|
417
|
+
for (const s of cachedSources) if (s && s.error) errById.set(s.id, s.error)
|
|
418
|
+
this.graph.sources = this.stores.map((st) => ({
|
|
419
|
+
key: st.key,
|
|
420
|
+
id: st.id,
|
|
421
|
+
adapter: st.adapter,
|
|
422
|
+
provider: st.provider,
|
|
423
|
+
title: st.title,
|
|
424
|
+
path: st.path,
|
|
425
|
+
size: st.size,
|
|
426
|
+
db: st.dbPath,
|
|
427
|
+
error: errById.get(st.id) || '',
|
|
428
|
+
}))
|
|
429
|
+
this.storeErrors = this.graph.sources.filter((s) => s.error).map((s) => ({ key: s.key, id: s.id, error: s.error }))
|
|
430
|
+
// 1.11.59:盘上那份图是「上一次建图那一刻」的样子。屏蔽(mute)只在内存里摘边,
|
|
431
|
+
// 又刻意不进签名(改一条边不该让整张图重算),于是重启读到的正是「屏蔽前」那一份:
|
|
432
|
+
// 屏蔽记录还在库里,边却回来了,muteCount 也变回旧数字。
|
|
433
|
+
// 这里按当前屏蔽记录再摘一次 —— 代价是几个哈希,比「好像没生效」便宜得多。
|
|
434
|
+
let droppedByMute = 0
|
|
435
|
+
try {
|
|
436
|
+
const muted = this.demo ? [] : listMutes()
|
|
437
|
+
if (muted.length) {
|
|
438
|
+
const idxOf = new Map(this.graph.nodes.map((n, i) => [n.id, i]))
|
|
439
|
+
const drop = new Set()
|
|
440
|
+
for (const m of muted) {
|
|
441
|
+
const x = idxOf.get(m.a)
|
|
442
|
+
const y = idxOf.get(m.b)
|
|
443
|
+
if (x === undefined || y === undefined) continue
|
|
444
|
+
drop.add(x < y ? x + ':' + y : y + ':' + x)
|
|
445
|
+
}
|
|
446
|
+
if (drop.size) {
|
|
447
|
+
const beforeMute = this.graph.edges.length
|
|
448
|
+
this.graph.edges = this.graph.edges.filter((e) => !drop.has(e.s < e.t ? e.s + ':' + e.t : e.t + ':' + e.s))
|
|
449
|
+
droppedByMute = beforeMute - this.graph.edges.length
|
|
450
|
+
this.#syncEdgeStats()
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
this.graph.muteCount = muted.length
|
|
454
|
+
} catch (err) {
|
|
455
|
+
// 屏蔽表读不出来不该挡住「读盘恢复」:图的其它部分照常可用,
|
|
456
|
+
// 这件事由 store 的自愈告示负责说,不在这一步重复。
|
|
457
|
+
this.graph.muteCount = Number(this.graph.muteCount) || 0
|
|
458
|
+
this.log('按屏蔽记录摘边失败:' + String((err && err.message) || err))
|
|
459
|
+
}
|
|
460
|
+
this.#buildIndex()
|
|
461
|
+
// 过期的缓存里记的是**旧签名**:写成当前签名的话,下一次 refresh 会认为
|
|
462
|
+
// 「什么都没变」,这张旧图就永远换不掉了。
|
|
463
|
+
this.signature = hit.sig || signature
|
|
464
|
+
this.staleGraph = stale
|
|
465
|
+
// 恢复不是重建:这一轮的建图耗时是 0,cacheAgeMs 才是「这份图多大年纪」。
|
|
466
|
+
// 以前这里把年纪当成本写进 buildMs,20 万条上会看到「buildMs 43780」,像是刚建了 43 秒。
|
|
467
|
+
this.lastBuildMs = 0
|
|
468
|
+
this.cacheAgeMs = hit.builtAt ? Date.now() - hit.builtAt : 0
|
|
469
|
+
this.lastCache = { hit: true, ms: hit.ms, builtAt: hit.builtAt, stale, implStale }
|
|
470
|
+
this.lastRefresh = { rebuilt: false, why: stale ? 'stale-cache' : 'cached', ms: Date.now() - started, at: started }
|
|
471
|
+
rtick('cache')
|
|
472
|
+
this.#schedulePrewarm(this.graph)
|
|
473
|
+
if (stale) this._bgRefreshPending = true
|
|
474
|
+
// 旧算法这一份要走 force:签名没变,不 force 的话后台那一轮会被
|
|
475
|
+
// 「什么都没变」直接跳过,旧图就永远换不掉了。
|
|
476
|
+
if (implStale) this._bgForce = true
|
|
477
|
+
this.log(
|
|
478
|
+
implStale
|
|
479
|
+
? `读盘恢复(旧算法):${this.graph.nodes.length} 条记忆 / ${hit.ms}ms —— 上一份是别的版本算的,后台按现在的算法重建`
|
|
480
|
+
: stale
|
|
481
|
+
? `读盘恢复(过期):${this.graph.nodes.length} 条记忆 / ${hit.ms}ms —— 先把上一份给你,后台按新签名重建`
|
|
482
|
+
: `读盘恢复:${this.graph.nodes.length} 条记忆 / ${this.graph.edges.length} 条关联 / ${hit.ms}ms(磁盘缓存,未重建)`,
|
|
483
|
+
)
|
|
484
|
+
// 摘掉的边要说一声:用户看到的图比上次少了几条,不该只有 muteCount 变了一下。
|
|
485
|
+
if (droppedByMute > 0) this.log(`按屏蔽记录摘掉 ${droppedByMute} 条关联(这条屏蔽是清空图之后记下的)`)
|
|
486
|
+
return false
|
|
487
|
+
}
|
|
488
|
+
this.lastCache = { hit: false, ms: 0 }
|
|
489
|
+
}
|
|
490
|
+
if (!opts.force && signature === this.signature && this.graph.nodes.length > 0) {
|
|
491
|
+
// 跳过也要有记录:界面上要能说清「没变」和「刚建过」是两件事。
|
|
492
|
+
this.lastRefresh = { rebuilt: false, why: 'unchanged', ms: Date.now() - started, at: started }
|
|
493
|
+
return false
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// 适配器层统一扫描:meow / 笔记 / 任意 SQLite / 外部推送,每种都可能多个库。
|
|
497
|
+
// 单个库读坏只记一条错误,不影响其它来源。
|
|
498
|
+
// 演示模式换一套内置节点,后面的建图、索引、详情、检索全部复用。
|
|
499
|
+
// 进度:从这一刻起界面就能问「走到哪了」,冷启动那几秒不再只剩一个转圈。
|
|
500
|
+
const progressT0 = Date.now()
|
|
501
|
+
let scannedCount = 0
|
|
502
|
+
const setStage = (stage) => {
|
|
503
|
+
const i = BUILD_STAGES.indexOf(stage)
|
|
504
|
+
this.buildProgress = {
|
|
505
|
+
stage,
|
|
506
|
+
label: STAGE_LABELS[stage] || stage,
|
|
507
|
+
step: i < 0 ? 0 : i,
|
|
508
|
+
total: BUILD_STAGES.length,
|
|
509
|
+
nodes: scannedCount,
|
|
510
|
+
ms: Date.now() - progressT0,
|
|
511
|
+
at: Date.now(),
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
setStage('scan')
|
|
515
|
+
const scanned = this.demo
|
|
516
|
+
? { nodes: DEMO_MEMORIES, ledgers: DEMO_LEDGERS, errors: [], warnings: [] }
|
|
517
|
+
: await scanAllAsync(this.stores)
|
|
518
|
+
rtick('scan')
|
|
519
|
+
const nodes = scanned.nodes
|
|
520
|
+
const ledgers = scanned.ledgers || []
|
|
521
|
+
scannedCount = nodes.length
|
|
522
|
+
// 坏来源要留到界面上,不能在「建图成功」时被清掉:
|
|
523
|
+
// 一个读不动的库会让这个工作区显示 0 条,用户只会以为「我的记忆没了」。
|
|
524
|
+
this.storeErrors = (scanned.errors || []).map((err) => ({
|
|
525
|
+
store: err.store || err.adapter || '来源',
|
|
526
|
+
id: err.id || '',
|
|
527
|
+
error: String(err.error || err),
|
|
528
|
+
}))
|
|
529
|
+
for (const err of this.storeErrors) {
|
|
530
|
+
this.lastError = `${err.store} 读取失败:${err.error}`
|
|
531
|
+
this.log(this.lastError)
|
|
532
|
+
}
|
|
533
|
+
if (this.storeErrors.length > 1) {
|
|
534
|
+
this.lastError = `${this.storeErrors.length} 个来源读取失败:` + this.storeErrors.map((e) => e.store).join(' / ')
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
this.inventory = this.demo ? DEMO_INVENTORY : readInventory()
|
|
538
|
+
this.nodes = nodes
|
|
539
|
+
this.ledgers = ledgers
|
|
540
|
+
|
|
541
|
+
const manual = this.demo ? DEMO_MANUAL : listLinks().map((x) => ({ a: x.a, b: x.b, note: x.note }))
|
|
542
|
+
const mutes = this.demo ? [] : listMutes().map((x) => ({ a: x.a, b: x.b }))
|
|
543
|
+
// 建图走异步版:2 万条库上要 3.7 秒,分片之后宿主界面不会跟着停住。
|
|
544
|
+
rtick('prep')
|
|
545
|
+
const graph = await buildGraphAsync({
|
|
546
|
+
nodes,
|
|
547
|
+
ledgers,
|
|
548
|
+
manual,
|
|
549
|
+
mutes,
|
|
550
|
+
inventory: this.inventory,
|
|
551
|
+
onStep: (stage) => setStage(stage),
|
|
552
|
+
})
|
|
553
|
+
rtick('buildGraph')
|
|
554
|
+
graph.muteCount = mutes.length
|
|
555
|
+
graph.inventory = this.inventory
|
|
556
|
+
this.storeWarnings = Array.isArray(scanned.warnings) ? scanned.warnings : []
|
|
557
|
+
graph.sources = this.stores.map((s) => ({
|
|
558
|
+
key: s.key,
|
|
559
|
+
id: s.id,
|
|
560
|
+
adapter: s.adapter,
|
|
561
|
+
provider: s.provider,
|
|
562
|
+
title: s.title,
|
|
563
|
+
path: s.path,
|
|
564
|
+
size: s.size,
|
|
565
|
+
db: s.dbPath,
|
|
566
|
+
// 这个来源自己读坏时的原文错误;其它来源正常就不带这个字段的空串
|
|
567
|
+
error: this.storeErrors.find((e) => e.store === s.key || e.store === s.id || e.id === s.id)?.error || '',
|
|
568
|
+
// 只读了前 N 个文件(maxFiles 上限)时为 true:界面要说明,别让人以为全在图里
|
|
569
|
+
truncated: Boolean(s.truncated),
|
|
570
|
+
}))
|
|
571
|
+
this.graph = graph
|
|
572
|
+
this.#buildIndex()
|
|
573
|
+
rtick('index')
|
|
574
|
+
this.signature = signature
|
|
575
|
+
this.staleGraph = false
|
|
576
|
+
this.lastBuildMs = Date.now() - started
|
|
577
|
+
this.cacheAgeMs = 0
|
|
578
|
+
this.scale = this.#scaleOf(graph)
|
|
579
|
+
this.lastRefresh = { rebuilt: true, why: 'rebuilt', ms: this.lastBuildMs, at: started }
|
|
580
|
+
this.#schedulePrewarm(graph)
|
|
581
|
+
if (this.storeErrors.length === 0) this.lastError = ''
|
|
582
|
+
if (!this.demo)
|
|
583
|
+
try {
|
|
584
|
+
cacheSet('graph', {
|
|
585
|
+
builtAt: graph.builtAt,
|
|
586
|
+
stats: graph.stats,
|
|
587
|
+
builtMs: this.lastBuildMs,
|
|
588
|
+
})
|
|
589
|
+
setMeta('lastBuiltAt', String(graph.builtAt))
|
|
590
|
+
} catch {
|
|
591
|
+
/* ignore */
|
|
592
|
+
}
|
|
593
|
+
// 写盘:下次重启就不用再算一遍。写失败只是没省到时间,不能影响这次建图。
|
|
594
|
+
// 不等它写完:5 万条库压缩要 1.6 秒(164MB → 4.3MB),等在这里等于让用户白等。
|
|
595
|
+
if (!this.demo && cacheEnabled()) {
|
|
596
|
+
this._cachePromise = saveGraphCache(this.cacheDir, signature, { nodes, ledgers, graph, srcs: srcKey })
|
|
597
|
+
.then((saved) => {
|
|
598
|
+
this.lastCache = { hit: false, writeMs: saved.ms, bytes: saved.bytes, raw: saved.raw, enc: saved.enc || 'json' }
|
|
599
|
+
rtick('cacheWrite')
|
|
600
|
+
return saved
|
|
601
|
+
})
|
|
602
|
+
.catch((err) => {
|
|
603
|
+
this.lastCache = { hit: false, error: String((err && err.message) || err) }
|
|
604
|
+
return null
|
|
605
|
+
})
|
|
606
|
+
}
|
|
607
|
+
this.log(
|
|
608
|
+
`重建完成:${graph.nodes.length} 条记忆 / ${graph.edges.length} 条关联 / ${graph.stats.workspaces} 个工作区 / ${this.lastBuildMs}ms${this.demo ? '(示例)' : ''}`,
|
|
609
|
+
)
|
|
610
|
+
if (!this.demo) logEvent('graph.rebuild', { nodes: graph.nodes.length, edges: graph.edges.length, ms: this.lastBuildMs })
|
|
611
|
+
// 写入时挂证据:新长出来的记忆,第一次建图就把「它凭什么连上别人」算好存进 sidecar,
|
|
612
|
+
// 以后开详情直接读缓存(也不必再现场算一遍)。
|
|
613
|
+
if (!this.demo)
|
|
614
|
+
try {
|
|
615
|
+
const seenAt = Number(getMeta('evidenceAt', '0')) || 0
|
|
616
|
+
const adj = new Map()
|
|
617
|
+
for (const e of graph.edges) {
|
|
618
|
+
const w = e.w || 0
|
|
619
|
+
for (const [self, other] of [
|
|
620
|
+
[e.s, e.t],
|
|
621
|
+
[e.t, e.s],
|
|
622
|
+
]) {
|
|
623
|
+
let arr = adj.get(self)
|
|
624
|
+
if (!arr) adj.set(self, (arr = []))
|
|
625
|
+
arr.push({ n: other, w, t: e.type, why: e.why })
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
let added = 0
|
|
629
|
+
const byIdx = new Map(graph.nodes.map((x) => [x.i, x]))
|
|
630
|
+
for (const n of graph.nodes) {
|
|
631
|
+
if (n.level === 'source') continue
|
|
632
|
+
if ((n.createdAt || 0) <= seenAt) continue
|
|
633
|
+
const list = (adj.get(n.i) || []).sort((a, b) => b.w - a.w).slice(0, 3)
|
|
634
|
+
cacheSet('ev:' + n.id, {
|
|
635
|
+
at: Date.now(),
|
|
636
|
+
edges: list.map((e) => ({
|
|
637
|
+
id: byIdx.get(e.n)?.id || '',
|
|
638
|
+
label: clip(byIdx.get(e.n)?.label || '', 48),
|
|
639
|
+
type: e.t,
|
|
640
|
+
w: Math.round(e.w * 100) / 100,
|
|
641
|
+
why: e.why,
|
|
642
|
+
})),
|
|
643
|
+
})
|
|
644
|
+
added++
|
|
645
|
+
if (added > 400) break
|
|
646
|
+
}
|
|
647
|
+
if (added) setMeta('evidenceAt', String(graph.builtAt))
|
|
648
|
+
} catch {
|
|
649
|
+
/* 缓存失败不影响建图 */
|
|
650
|
+
}
|
|
651
|
+
this.emit('updated', { builtAt: graph.builtAt, stats: graph.stats })
|
|
652
|
+
return true
|
|
653
|
+
} catch (err) {
|
|
654
|
+
this.lastError = err?.stack || String(err)
|
|
655
|
+
this.log('重建失败:' + this.lastError)
|
|
656
|
+
return false
|
|
657
|
+
} finally {
|
|
658
|
+
this.building = false
|
|
659
|
+
this.buildProgress = null
|
|
660
|
+
for (const wake of this._waiters.splice(0)) wake()
|
|
661
|
+
// 这一轮给出去的是过期缓存:等 building 落下来再排一轮后台重建。
|
|
662
|
+
// 不能在 return 之前直接调 refresh:同一 tick 里会把 building 又立起来,
|
|
663
|
+
// 拿到那张旧图的请求就被当成「正在重建」等在这里了。
|
|
664
|
+
if (this._bgRefreshPending) {
|
|
665
|
+
this._bgRefreshPending = false
|
|
666
|
+
const forceBg = this._bgForce
|
|
667
|
+
this._bgForce = false
|
|
668
|
+
const timer = setTimeout(() => this.refreshInBackground(forceBg ? { force: true } : {}), 0)
|
|
669
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* 后台重建:立刻返回,建完自己换图。
|
|
676
|
+
* 1.11.30:打开页面不该先等五秒——先把手上这张图给出去,新的一到再换上去。
|
|
677
|
+
* 已经有一轮在跑就不另起(并发重建只会互相覆盖),直接复用那一次。
|
|
678
|
+
* @param {{force?:boolean}} [opts]
|
|
679
|
+
*/
|
|
680
|
+
refreshInBackground(opts = {}) {
|
|
681
|
+
if (this.building) return this._bgPromise || null
|
|
682
|
+
const p = this.refresh(opts).finally(() => {
|
|
683
|
+
if (this._bgPromise === p) this._bgPromise = null
|
|
684
|
+
})
|
|
685
|
+
this._bgPromise = p
|
|
686
|
+
return p
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** 轻量轮询:只 stat,不重建;有变化才重建。 */
|
|
690
|
+
startWatching(intervalMs = 15000) {
|
|
691
|
+
if (this.timer) return
|
|
692
|
+
if (this.demo) return // 示例数据是常量,没有「文件变化」可看
|
|
693
|
+
const tick = async () => {
|
|
694
|
+
try {
|
|
695
|
+
if (this.building) return
|
|
696
|
+
const sig = this.computeSignature()
|
|
697
|
+
if (sig !== this.signature) await this.refresh({ force: true })
|
|
698
|
+
} catch (err) {
|
|
699
|
+
this.log('轮询异常:' + (err?.message || err))
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
this.timer = setInterval(tick, Math.max(4000, intervalMs))
|
|
703
|
+
if (typeof this.timer.unref === 'function') this.timer.unref()
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
stopWatching() {
|
|
707
|
+
if (this.timer) clearInterval(this.timer)
|
|
708
|
+
this.timer = null
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* 给前端的精简图。**只发「画得出来」的字段**:
|
|
713
|
+
* 正文/关键词/实体/每条边的 why 都不发(那些走 /node 按需取),
|
|
714
|
+
* 这样 1300 条记忆的包从 2.6MB 降到 0.5MB 量级,首帧早得多。
|
|
715
|
+
*/
|
|
716
|
+
/**
|
|
717
|
+
* 分页顺序按签名缓存:同一张图重复请求不再重排。
|
|
718
|
+
* @param {{nodes: unknown[]}} g
|
|
719
|
+
*/
|
|
720
|
+
pageOrderFor(g) {
|
|
721
|
+
const sig = this.signature || g.builtAt || 0
|
|
722
|
+
if (this._pageCache && this._pageCache.sig === sig) return this._pageCache.order
|
|
723
|
+
const order = pageOrder(g)
|
|
724
|
+
const rankByI = new Map()
|
|
725
|
+
for (let k = 0; k < order.length; k++) rankByI.set(g.nodes[order[k]].i, k)
|
|
726
|
+
this._pageCache = { sig, order, rankByI }
|
|
727
|
+
return order
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* 给前端的精简图。**只发「画得出来」的字段**:
|
|
732
|
+
* 正文/关键词/实体/每条边的 why 都不发(那些走 /node 按需取),
|
|
733
|
+
* 这样 1300 条记忆的包从 2.6MB 降到 0.5MB 量级,首帧早得多。
|
|
734
|
+
*
|
|
735
|
+
* 1.9.0 起支持分页:传 {limit, offset} 只发一页;不传时超过一万条自动截第一页
|
|
736
|
+
* (FIRST_PAGE_MAX,见 lib/host/page.js:两万条一页仍有 8.7MB,砍到一万约 4.4MB)。
|
|
737
|
+
* 页内边用本地下标(s/d),跨页边用真 id(a/b),前端合并时不会错位。
|
|
738
|
+
*/
|
|
739
|
+
publicGraph(opts = {}) {
|
|
740
|
+
const g = this.graph
|
|
741
|
+
const total = g.nodes.length
|
|
742
|
+
const order = this.pageOrderFor(g)
|
|
743
|
+
// all:不分页,整张图一次给出。只有 /share 用——它要么整份导出,要么按上限裁,
|
|
744
|
+
// 绝不能悄悄只拿到第一页(1.11.5 修的就是这件事:5 万条的库导出的快照里只有 1 万条)。
|
|
745
|
+
const { indices, page } = opts.all
|
|
746
|
+
? { indices: Array.from(order), page: { total, offset: 0, limit: total, next: null, order: 'importance' } }
|
|
747
|
+
: selectPage(g, { limit: opts.limit, offset: opts.offset, order })
|
|
748
|
+
const full = page.offset === 0 && page.limit >= total
|
|
749
|
+
|
|
750
|
+
// 簇=工作区:星云里每个工作区一团光,跨工作区的连线就是桥。
|
|
751
|
+
const wsMap = new Map()
|
|
752
|
+
for (const n of g.nodes) {
|
|
753
|
+
let c = wsMap.get(n.ws)
|
|
754
|
+
if (!c) {
|
|
755
|
+
c = { id: n.ws, title: n.wsTitle, label: n.wsTitle, size: 0, hue: hueOf(n.ws), color: hslHex(hueOf(n.ws)), workspaces: [n.ws] }
|
|
756
|
+
wsMap.set(n.ws, c)
|
|
757
|
+
}
|
|
758
|
+
c.size++
|
|
759
|
+
}
|
|
760
|
+
const clusters = [...wsMap.values()].sort((x, y) => y.size - x.size)
|
|
761
|
+
|
|
762
|
+
const shape = (n) => ({
|
|
763
|
+
id: n.id,
|
|
764
|
+
ws: n.wsTitle,
|
|
765
|
+
cluster: n.ws,
|
|
766
|
+
level: n.level,
|
|
767
|
+
label: clip(n.title || n.label, 46),
|
|
768
|
+
importance: n.importance,
|
|
769
|
+
status: n.status,
|
|
770
|
+
project: n.project,
|
|
771
|
+
hits: n.hits,
|
|
772
|
+
heat: n.heat,
|
|
773
|
+
degree: n.degree,
|
|
774
|
+
createdAt: n.createdAt,
|
|
775
|
+
provider: n.provider || 'meow-memory',
|
|
776
|
+
adapter: n.adapter || null,
|
|
777
|
+
seed: n.seed,
|
|
778
|
+
})
|
|
779
|
+
|
|
780
|
+
const edges = []
|
|
781
|
+
let nodes
|
|
782
|
+
if (full) {
|
|
783
|
+
nodes = g.nodes.map(shape)
|
|
784
|
+
// 边用「下标」而不是 id:id 长 60+ 字符,5000 条边光 id 就是 600KB
|
|
785
|
+
const idxOf = new Map(g.nodes.map((n, i) => [n.i, i]))
|
|
786
|
+
for (const e of g.edges) {
|
|
787
|
+
const s = idxOf.get(e.s)
|
|
788
|
+
const t = idxOf.get(e.t)
|
|
789
|
+
if (s == null || t == null) continue
|
|
790
|
+
edges.push({ s, d: t, w: Math.round(e.w * 1000) / 1000, t: e.type, curated: !!e.curated })
|
|
791
|
+
}
|
|
792
|
+
} else {
|
|
793
|
+
const localOf = new Map()
|
|
794
|
+
nodes = indices.map((orig, pos) => {
|
|
795
|
+
localOf.set(orig, pos)
|
|
796
|
+
return shape(g.nodes[orig])
|
|
797
|
+
})
|
|
798
|
+
const rankByI = this._pageCache.rankByI
|
|
799
|
+
const start = page.offset
|
|
800
|
+
const end = page.offset + page.limit
|
|
801
|
+
for (const e of g.edges) {
|
|
802
|
+
const rs = rankByI.get(e.s)
|
|
803
|
+
const rt = rankByI.get(e.t)
|
|
804
|
+
if (rs == null || rt == null) continue
|
|
805
|
+
// 另一端还在后面的页里:先不发,等那页到了再用 a/b 补上
|
|
806
|
+
if (rs >= end || rt >= end) continue
|
|
807
|
+
const A = rs >= start
|
|
808
|
+
const B = rt >= start
|
|
809
|
+
if (!A && !B) continue
|
|
810
|
+
const w = Math.round(e.w * 1000) / 1000
|
|
811
|
+
if (A && B) {
|
|
812
|
+
edges.push({ s: localOf.get(e.s), d: localOf.get(e.t), w, t: e.type, curated: !!e.curated })
|
|
813
|
+
} else {
|
|
814
|
+
edges.push({
|
|
815
|
+
a: g.nodes[e.s].id,
|
|
816
|
+
b: g.nodes[e.t].id,
|
|
817
|
+
w,
|
|
818
|
+
t: e.type,
|
|
819
|
+
curated: !!e.curated,
|
|
820
|
+
})
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
return {
|
|
826
|
+
v: 2,
|
|
827
|
+
nodes,
|
|
828
|
+
edges,
|
|
829
|
+
clusters,
|
|
830
|
+
page,
|
|
831
|
+
stats: g.stats,
|
|
832
|
+
sources: g.sources || [],
|
|
833
|
+
inventory: g.inventory || { plugins: [], skills: [], mcp: [] },
|
|
834
|
+
builtAt: g.builtAt,
|
|
835
|
+
buildMs: this.lastBuildMs,
|
|
836
|
+
cacheAgeMs: this.cacheAgeMs || 0,
|
|
837
|
+
lastError: this.lastError,
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* 单条记忆的完整详情:正文 + 邻居 + 每一条关联的证据。
|
|
843
|
+
* @param {string} id
|
|
844
|
+
*/
|
|
845
|
+
detail(id) {
|
|
846
|
+
const idx = this.index || {}
|
|
847
|
+
const node =
|
|
848
|
+
idx.byId?.get(id) || idx.byUid?.get(String(id)) || findNode(this.graph.nodes, id)
|
|
849
|
+
if (!node) return null
|
|
850
|
+
const raw = idx.rawById?.get(node.id) || this.nodes.find((x) => x.id === node.id) || null
|
|
851
|
+
const edges = []
|
|
852
|
+
if (idx.adj?.has(node.i)) {
|
|
853
|
+
for (const link of idx.adj.get(node.i)) {
|
|
854
|
+
const other = idx.byI?.get(link.n)
|
|
855
|
+
if (!other) continue
|
|
856
|
+
edges.push({
|
|
857
|
+
id: other.id,
|
|
858
|
+
label: other.label,
|
|
859
|
+
ws: other.wsTitle,
|
|
860
|
+
level: other.level,
|
|
861
|
+
importance: other.importance,
|
|
862
|
+
type: link.t,
|
|
863
|
+
weight: link.w,
|
|
864
|
+
why: link.why,
|
|
865
|
+
})
|
|
866
|
+
}
|
|
867
|
+
} else {
|
|
868
|
+
for (const edge of this.graph.edges) {
|
|
869
|
+
if (edge.s !== node.i && edge.t !== node.i) continue
|
|
870
|
+
const otherIdx = edge.s === node.i ? edge.t : edge.s
|
|
871
|
+
const other = idx.byI?.get(otherIdx) || this.graph.nodes.find((x) => x.i === otherIdx)
|
|
872
|
+
if (!other) continue
|
|
873
|
+
edges.push({
|
|
874
|
+
id: other.id,
|
|
875
|
+
label: other.label,
|
|
876
|
+
ws: other.wsTitle,
|
|
877
|
+
level: other.level,
|
|
878
|
+
importance: other.importance,
|
|
879
|
+
type: edge.type,
|
|
880
|
+
weight: edge.w,
|
|
881
|
+
why: edge.why,
|
|
882
|
+
})
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
edges.sort((a, b) => b.weight - a.weight)
|
|
886
|
+
const wsSize =
|
|
887
|
+
this.graph.stats?.byWorkspace?.[node.wsTitle] ??
|
|
888
|
+
this.graph.nodes.reduce((acc, x) => acc + (x.ws === node.ws ? 1 : 0), 0)
|
|
889
|
+
// 来源节点(技能 / MCP / 插件):反过来看「谁提到过它」,按项目分组统计
|
|
890
|
+
let mentionedBy = null
|
|
891
|
+
if (node.level === 'source') {
|
|
892
|
+
const tally = new Map()
|
|
893
|
+
for (const e of edges) {
|
|
894
|
+
if (e.type !== 'mentions' || e.level === 'source') continue
|
|
895
|
+
tally.set(e.ws, (tally.get(e.ws) || 0) + 1)
|
|
896
|
+
}
|
|
897
|
+
mentionedBy = {
|
|
898
|
+
total: edges.filter((e) => e.type === 'mentions' && e.level !== 'source').length,
|
|
899
|
+
byWorkspace: [...tally.entries()].map(([ws, n]) => ({ ws, n })).sort((a, b) => b.n - a.n),
|
|
900
|
+
top: edges
|
|
901
|
+
.filter((e) => e.type === 'mentions' && e.level !== 'source')
|
|
902
|
+
.sort((a, b) => (b.importance || 0) - (a.importance || 0) || b.weight - a.weight)
|
|
903
|
+
.slice(0, 12)
|
|
904
|
+
.map((e) => ({ id: e.id, label: e.label, ws: e.ws, level: e.level, importance: e.importance })),
|
|
905
|
+
}
|
|
906
|
+
// 实际调用次数(从会话转写的 tool/call 里数出来,和「被提到」是两条独立证据)
|
|
907
|
+
if (this._usageOf) {
|
|
908
|
+
const kindKey = node.sourceKind === 'MCP' ? 'mcp' : node.sourceKind === '技能' ? 'skill' : 'plugin'
|
|
909
|
+
try {
|
|
910
|
+
mentionedBy.usage = this._usageOf(kindKey, node.title || node.label)
|
|
911
|
+
} catch {}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
// 归属:这条记忆是在「主人在会话里说的哪句话」之后写下的。
|
|
915
|
+
// 读的是 DSH 的会话转写(多帧 zstd),只在真正打开详情时懒加载。
|
|
916
|
+
let origin = null
|
|
917
|
+
try {
|
|
918
|
+
if (this._originOfMemory) {
|
|
919
|
+
const sid = raw?.sessionId || ''
|
|
920
|
+
const at = raw?.createdAt || node.createdAt || 0
|
|
921
|
+
const key = sid + ':' + at
|
|
922
|
+
if (this._originCache?.has(key)) {
|
|
923
|
+
origin = this._originCache.get(key)
|
|
924
|
+
} else {
|
|
925
|
+
origin = this._originOfMemory({ sessionId: sid, createdAt: at })
|
|
926
|
+
this._originCache?.set(key, origin)
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
} catch {}
|
|
930
|
+
// 同一次会话里还写下了哪些记忆:一条上下文脉络,比单条记忆更好定位
|
|
931
|
+
let peers = null
|
|
932
|
+
const sid = raw?.sessionId || ''
|
|
933
|
+
if (sid && node.level !== 'source') {
|
|
934
|
+
const anchor = raw?.createdAt || node.createdAt || 0
|
|
935
|
+
const same = this.graph.nodes.filter((x) => x.level !== 'source' && x.sessionId === sid && x.id !== node.id)
|
|
936
|
+
const rawById = idx.rawById || new Map(this.nodes.map((x) => [x.id, x]))
|
|
937
|
+
peers = {
|
|
938
|
+
total: same.length,
|
|
939
|
+
items: same
|
|
940
|
+
// 按「时间上离它最近」排:前后几分钟写下的,才是同一条思路里的东西
|
|
941
|
+
.sort(
|
|
942
|
+
(a, b) =>
|
|
943
|
+
Math.abs((rawById.get(a.id)?.createdAt || 0) - anchor) - Math.abs((rawById.get(b.id)?.createdAt || 0) - anchor),
|
|
944
|
+
)
|
|
945
|
+
.slice(0, 12)
|
|
946
|
+
.map((x) => ({
|
|
947
|
+
id: x.id,
|
|
948
|
+
label: x.label,
|
|
949
|
+
level: x.level,
|
|
950
|
+
importance: x.importance,
|
|
951
|
+
ws: x.wsTitle,
|
|
952
|
+
createdAt: rawById.get(x.id)?.createdAt || 0,
|
|
953
|
+
})),
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
return {
|
|
957
|
+
...node,
|
|
958
|
+
content: raw?.content || node.preview,
|
|
959
|
+
goal: raw?.goal || '',
|
|
960
|
+
subcategory: raw?.subcategory || '',
|
|
961
|
+
corrected: raw?.corrected || false,
|
|
962
|
+
sessionId: raw?.sessionId || '',
|
|
963
|
+
keywords: raw?.keywords || node.keywords,
|
|
964
|
+
mentions: this.mentionsOf(raw?.content || node.preview || ''),
|
|
965
|
+
mentionedBy,
|
|
966
|
+
peers,
|
|
967
|
+
origin,
|
|
968
|
+
// 重要度建议:只提示,不改别人的库
|
|
969
|
+
suggest: (() => {
|
|
970
|
+
try {
|
|
971
|
+
const m = this._sugg && this._sugg.sig === this.signature ? this._sugg.value : null
|
|
972
|
+
const mm = m || this.suggestImportance()
|
|
973
|
+
this._sugg = { sig: this.signature, value: mm }
|
|
974
|
+
return mm.get(node.id) || null
|
|
975
|
+
} catch {
|
|
976
|
+
return null
|
|
977
|
+
}
|
|
978
|
+
})(),
|
|
979
|
+
// 写入时就算过的那几条证据(sidecar 缓存),只在第一次建图时算
|
|
980
|
+
evidence: (() => {
|
|
981
|
+
try {
|
|
982
|
+
if (this._evCache?.has(node.id)) return this._evCache.get(node.id)
|
|
983
|
+
const c = cacheGet('ev:' + node.id)
|
|
984
|
+
const val = c && c.edges ? c : null
|
|
985
|
+
this._evCache?.set(node.id, val)
|
|
986
|
+
return val
|
|
987
|
+
} catch {
|
|
988
|
+
return null
|
|
989
|
+
}
|
|
990
|
+
})(),
|
|
991
|
+
degree: edges.length,
|
|
992
|
+
cluster: { id: node.ws, label: node.wsTitle, size: wsSize },
|
|
993
|
+
neighbors: edges,
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
/**
|
|
998
|
+
* 这条记忆提到了哪些技能 / MCP / 记忆插件。
|
|
999
|
+
* 只认「名字原样出现」——不做模糊匹配,避免把无关记忆挂到技能上。
|
|
1000
|
+
*/
|
|
1001
|
+
mentionsOf(text) {
|
|
1002
|
+
const out = []
|
|
1003
|
+
const body = String(text || '')
|
|
1004
|
+
if (!body) return out
|
|
1005
|
+
const lower = body.toLowerCase()
|
|
1006
|
+
for (const skill of this.inventory.skills || []) {
|
|
1007
|
+
const name = String(skill.name || '')
|
|
1008
|
+
if (name.length >= 4 && lower.includes(name.toLowerCase())) {
|
|
1009
|
+
out.push({ kind: 'skill', name, description: String(skill.description || '').slice(0, 90) })
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
for (const m of this.inventory.mcp || []) {
|
|
1013
|
+
const name = String(m.name || '')
|
|
1014
|
+
if (name.length >= 4 && lower.includes(name.toLowerCase())) {
|
|
1015
|
+
out.push({ kind: 'mcp', name, description: '' })
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
for (const p of this.inventory.plugins || []) {
|
|
1019
|
+
const name = String(p.name || '')
|
|
1020
|
+
const short = name.replace(/^@[^/]+\//, '')
|
|
1021
|
+
if (short.length >= 6 && lower.includes(short.toLowerCase())) {
|
|
1022
|
+
out.push({ kind: 'plugin', name: short, description: '' })
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
// 去重(同名只留一条,技能 > MCP > 插件)+ 上限
|
|
1026
|
+
const order = { skill: 0, mcp: 1, plugin: 2 }
|
|
1027
|
+
const seen = new Set()
|
|
1028
|
+
return out
|
|
1029
|
+
.sort((a, b) => (order[a.kind] ?? 9) - (order[b.kind] ?? 9))
|
|
1030
|
+
.filter((x) => {
|
|
1031
|
+
const k = x.name.toLowerCase()
|
|
1032
|
+
if (seen.has(k)) return false
|
|
1033
|
+
seen.add(k)
|
|
1034
|
+
return true
|
|
1035
|
+
})
|
|
1036
|
+
.slice(0, 8)
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* 扩散检索。
|
|
1041
|
+
* @param {string} query
|
|
1042
|
+
* @param {object} [opts]
|
|
1043
|
+
*/
|
|
1044
|
+
recall(query, opts = {}) {
|
|
1045
|
+
return recall(this.graph, query, opts)
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
/**
|
|
1049
|
+
* 异步检索:词频表分片灌满再查,5 万条的库第一次查也不会把宿主按住。
|
|
1050
|
+
* @param {string} query
|
|
1051
|
+
* @param {object} [opts]
|
|
1052
|
+
*/
|
|
1053
|
+
async recallAsync(query, opts = {}) {
|
|
1054
|
+
return recallAsync(this.graph, query, opts)
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* 注入桥:从「别的记忆插件刚喂过的东西」出发,挑出该补充的邻居。
|
|
1059
|
+
*
|
|
1060
|
+
* 这是星图和其他记忆插件协同的正式接口。任何插件/agent 都能调:
|
|
1061
|
+
* nebula_bridge({ ids: [...刚注入的记忆], sessionId })
|
|
1062
|
+
* 返回的 items 是「没被讲过、但和这件事强相关」的记忆,可直接拼进上下文。
|
|
1063
|
+
*
|
|
1064
|
+
* @param {object} opts
|
|
1065
|
+
* @param {string[]} [opts.ids] 种子记忆(完整 id 或裸 uid)
|
|
1066
|
+
* @param {string} [opts.query] 没有 ids 时用查询词找种子
|
|
1067
|
+
* @param {string} [opts.sessionId]
|
|
1068
|
+
* @param {Set<string>|string[]} [opts.seen]
|
|
1069
|
+
* @param {object} [opts.budget]
|
|
1070
|
+
* @param {boolean} [opts.mark] 是否记账(默认 true,有 sessionId 时)
|
|
1071
|
+
*/
|
|
1072
|
+
bridge(opts = {}) {
|
|
1073
|
+
const seen = opts.seen instanceof Set ? new Set(opts.seen) : new Set(opts.seen || [])
|
|
1074
|
+
if (opts.sessionId) {
|
|
1075
|
+
const mine = readLedger(opts.sessionId)
|
|
1076
|
+
for (const uid of Object.keys(mine.seen)) seen.add(uid)
|
|
1077
|
+
for (const uid of Object.keys(mine.external)) seen.add(uid)
|
|
1078
|
+
}
|
|
1079
|
+
const res = bridgeFn(this.graph, {
|
|
1080
|
+
ids: opts.ids,
|
|
1081
|
+
query: opts.query,
|
|
1082
|
+
seen,
|
|
1083
|
+
cooldown: opts.cooldown || readCooldown(),
|
|
1084
|
+
budget: opts.budget,
|
|
1085
|
+
ws: opts.ws,
|
|
1086
|
+
adj: this.index?.adj,
|
|
1087
|
+
allowStale: opts.allowStale,
|
|
1088
|
+
})
|
|
1089
|
+
if (opts.mark !== false && opts.sessionId && res.items.length > 0) {
|
|
1090
|
+
const uids = res.items.map((x) => x.uid)
|
|
1091
|
+
try {
|
|
1092
|
+
markSeen(opts.sessionId, uids, opts.by || 'nebula:inject')
|
|
1093
|
+
markCooldown(uids)
|
|
1094
|
+
} catch {
|
|
1095
|
+
/* 记账失败不影响返回 */
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
return res
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/**
|
|
1102
|
+
* 接收外部推送的记忆(给没有本地落盘的记忆服务用)。
|
|
1103
|
+
* 写的是星图自己的目录,重建后立刻进图。
|
|
1104
|
+
* @param {string} provider
|
|
1105
|
+
* @param {object[]} items
|
|
1106
|
+
*/
|
|
1107
|
+
async ingest(provider, items) {
|
|
1108
|
+
const res = appendIngest(provider, items)
|
|
1109
|
+
if (res.written > 0) {
|
|
1110
|
+
this.signature = ''
|
|
1111
|
+
await this.refresh({ force: true })
|
|
1112
|
+
}
|
|
1113
|
+
// 1.11.68:写入端要把「丢了几条、为什么丢、批内重复几条」说清楚;全丢时给一句可读的错。
|
|
1114
|
+
const why = describeSkips(res.reasons || {})
|
|
1115
|
+
const note = []
|
|
1116
|
+
if (res.skipped > 0) note.push(`跳过 ${res.skipped} 条:${why || '都缺 title 与 content'}`)
|
|
1117
|
+
if (res.duplicates > 0) note.push(`${res.duplicates} 条 uid 重复,按后写的覆盖`)
|
|
1118
|
+
const extra = res.written === 0
|
|
1119
|
+
? { error: why ? `这些条目里没有可写入的内容:${why}` : '这些条目里没有可写入的内容(都缺 title 与 content)' }
|
|
1120
|
+
: (note.length > 0 ? { note: note.join(';') } : {})
|
|
1121
|
+
return { ...res, ...extra, graph: this.graph?.stats || null }
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/**
|
|
1125
|
+
* 来源体检:现在接了谁、读到了什么、配置在哪、怎么加新的。
|
|
1126
|
+
*
|
|
1127
|
+
* 注意:这里必须走 scanAllAsync —— 适配器层在 1.11.40 之后只剩「异步扫」这一条路,
|
|
1128
|
+
* 同步的 scanAll 早就不存在了;调用它会让整个 live 一栏变成一条假警报。
|
|
1129
|
+
* 给人看,也给 AI 看(AI 照着填 sources.json 就能接入新插件)。
|
|
1130
|
+
*/
|
|
1131
|
+
async sourcesReport() {
|
|
1132
|
+
// 面板不能依赖「上一次建图」:刚装好、还没建过图时,this.stores 还是空的,
|
|
1133
|
+
// 这时也要答得出「你接了谁」。算一次指纹(只 stat + readdir,很便宜)就够。
|
|
1134
|
+
if (!this.demo && (!this.stores || this.stores.length === 0)) {
|
|
1135
|
+
try { this.computeSignature() } catch { /* 指纹算不出来不该挡住体检 */ }
|
|
1136
|
+
}
|
|
1137
|
+
const probe = probeAll()
|
|
1138
|
+
let scanned = { nodes: [], ledgers: [], errors: [] }
|
|
1139
|
+
try {
|
|
1140
|
+
// 示例库没有「适配器」可扫:直接拿内置数据,别让来源面板挂一条假警报。
|
|
1141
|
+
scanned = this.demo
|
|
1142
|
+
? { nodes: DEMO_MEMORIES, ledgers: DEMO_LEDGERS, errors: [] }
|
|
1143
|
+
: await scanAllAsync(this.stores || [])
|
|
1144
|
+
} catch (err) {
|
|
1145
|
+
scanned.errors = [{ store: 'all', error: String(err?.message || err) }]
|
|
1146
|
+
}
|
|
1147
|
+
const byProvider = {}
|
|
1148
|
+
const byAdapter = {}
|
|
1149
|
+
for (const n of scanned.nodes) {
|
|
1150
|
+
byProvider[n.provider || '?'] = (byProvider[n.provider || '?'] || 0) + 1
|
|
1151
|
+
byAdapter[n.adapter || '?'] = (byAdapter[n.adapter || '?'] || 0) + 1
|
|
1152
|
+
}
|
|
1153
|
+
return {
|
|
1154
|
+
config: probe.config,
|
|
1155
|
+
adapters: adapterCatalog(),
|
|
1156
|
+
probes: probe.probes,
|
|
1157
|
+
live: {
|
|
1158
|
+
stores: (this.stores || []).map((s) => ({
|
|
1159
|
+
id: s.id,
|
|
1160
|
+
adapter: s.adapter,
|
|
1161
|
+
provider: s.provider,
|
|
1162
|
+
title: s.title,
|
|
1163
|
+
path: s.path,
|
|
1164
|
+
size: s.size,
|
|
1165
|
+
hasSessions: Boolean(s.sessionsDir),
|
|
1166
|
+
})),
|
|
1167
|
+
nodes: scanned.nodes.length,
|
|
1168
|
+
byProvider,
|
|
1169
|
+
byAdapter,
|
|
1170
|
+
errors: scanned.errors.slice(0, 8),
|
|
1171
|
+
},
|
|
1172
|
+
graph: this.graph?.stats || null,
|
|
1173
|
+
ledger: (() => {
|
|
1174
|
+
try {
|
|
1175
|
+
return ledgerStats()
|
|
1176
|
+
} catch {
|
|
1177
|
+
return null
|
|
1178
|
+
}
|
|
1179
|
+
})(),
|
|
1180
|
+
hint:
|
|
1181
|
+
'要接一个新记忆插件:读 docs/adapters.md,在 sources.json 里加一条(简单情况零代码),' +
|
|
1182
|
+
'远端服务用 nebula_ingest 推。改完调 nebula_sources 体检。',
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/**
|
|
1187
|
+
* 注入账本快照:谁被注入过、什么时候、冷却表还有多少。
|
|
1188
|
+
* @param {string} [sessionId]
|
|
1189
|
+
*/
|
|
1190
|
+
ledger(sessionId = '') {
|
|
1191
|
+
const stats = ledgerStats()
|
|
1192
|
+
if (!sessionId) return { stats }
|
|
1193
|
+
const book = readLedger(sessionId)
|
|
1194
|
+
return {
|
|
1195
|
+
stats,
|
|
1196
|
+
sessionId,
|
|
1197
|
+
seen: Object.keys(book.seen || {}).length,
|
|
1198
|
+
injected: (book.injected || []).length,
|
|
1199
|
+
recent: (book.injected || []).slice(-24),
|
|
1200
|
+
updatedAt: book.updatedAt || null,
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
/**
|
|
1205
|
+
* 导出图谱:给人看 Markdown,给别的 AI 看 JSON。
|
|
1206
|
+
* 不导出正文(正文在节点详情里,避免一次吐几十万字)。
|
|
1207
|
+
* @param {{format?:'md'|'json', scope?:'all'|'ws', ws?:string, limit?:number}} [opts]
|
|
1208
|
+
*/
|
|
1209
|
+
exportReport(opts = {}) {
|
|
1210
|
+
const format = String(opts.format || 'md').toLowerCase()
|
|
1211
|
+
const limit = Math.max(10, Math.min(2000, Number(opts.limit) || 200))
|
|
1212
|
+
const g = this.graph
|
|
1213
|
+
if (!g) return { error: '星图还没建好' }
|
|
1214
|
+
|
|
1215
|
+
// 范围导出:`all`,或 ws:<工作区> / project:<项目> / focus:<节点 id>。
|
|
1216
|
+
// 只影响这次导出,不改图、不写库。旧调用不传 scope 时行为与 all 完全一致。
|
|
1217
|
+
//
|
|
1218
|
+
// 1.8.0:拼错不再静默按 all 导出。之前 `scope=zzz:nope` 会得到整库报告,
|
|
1219
|
+
// 用户以为导的是某个工作区,实际把全部记忆写了出去——隐私上和契约上都不该这样。
|
|
1220
|
+
const rawScope = String(opts.scope || 'all').trim()
|
|
1221
|
+
const cut = rawScope.indexOf(':')
|
|
1222
|
+
const scopeKind = cut > 0 ? rawScope.slice(0, cut).toLowerCase() : 'all'
|
|
1223
|
+
const scopeValue = cut > 0 ? rawScope.slice(cut + 1) : ''
|
|
1224
|
+
if (!['md', 'json'].includes(format)) {
|
|
1225
|
+
return { error: `format 只支持 md 或 json,收到的是「${format}」` }
|
|
1226
|
+
}
|
|
1227
|
+
if (rawScope.toLowerCase() !== 'all') {
|
|
1228
|
+
if (cut <= 0) {
|
|
1229
|
+
return { error: `范围要写成 all、ws:<工作区>、project:<项目> 或 focus:<节点 id>,收到的是「${rawScope}」` }
|
|
1230
|
+
}
|
|
1231
|
+
if (!['ws', 'project', 'focus'].includes(scopeKind)) {
|
|
1232
|
+
return { error: `未知的范围类型「${scopeKind}」:只能是 ws / project / focus` }
|
|
1233
|
+
}
|
|
1234
|
+
if (!scopeValue.trim()) {
|
|
1235
|
+
return { error: `范围「${rawScope}」缺少取值,例如 ws:memory-universe` }
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
let allowed = null
|
|
1239
|
+
if (scopeKind === 'ws' || scopeKind === 'project') {
|
|
1240
|
+
const want = scopeValue.toLowerCase()
|
|
1241
|
+
allowed = new Set()
|
|
1242
|
+
for (const n of g.nodes) {
|
|
1243
|
+
const hit = scopeKind === 'ws'
|
|
1244
|
+
? (String(n.ws || '').toLowerCase() === want || String(n.wsTitle || '').toLowerCase() === want || String(n.cluster || '').toLowerCase() === want)
|
|
1245
|
+
: String(n.project || '').toLowerCase() === want
|
|
1246
|
+
if (hit) allowed.add(n.i)
|
|
1247
|
+
}
|
|
1248
|
+
if (!allowed.size) return { error: `这个范围里没有记忆:${rawScope}` }
|
|
1249
|
+
} else if (scopeKind === 'focus') {
|
|
1250
|
+
const start = g.nodes.find((n) => n.id === scopeValue || n.uid === scopeValue || n.label === scopeValue)
|
|
1251
|
+
if (!start) return { error: `找不到这条记忆:${scopeValue}` }
|
|
1252
|
+
const hops = Math.max(1, Math.min(5, Number(opts.hops) || 2))
|
|
1253
|
+
const adj = new Map()
|
|
1254
|
+
for (const e of g.edges) {
|
|
1255
|
+
if (!adj.has(e.s)) adj.set(e.s, [])
|
|
1256
|
+
if (!adj.has(e.t)) adj.set(e.t, [])
|
|
1257
|
+
adj.get(e.s).push(e.t)
|
|
1258
|
+
adj.get(e.t).push(e.s)
|
|
1259
|
+
}
|
|
1260
|
+
allowed = new Set([start.i])
|
|
1261
|
+
let frontier = [start.i]
|
|
1262
|
+
for (let h = 0; h < hops; h++) {
|
|
1263
|
+
const next = []
|
|
1264
|
+
for (const i of frontier) {
|
|
1265
|
+
for (const j of adj.get(i) || []) {
|
|
1266
|
+
if (allowed.has(j)) continue
|
|
1267
|
+
allowed.add(j)
|
|
1268
|
+
next.push(j)
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
frontier = next
|
|
1272
|
+
if (!frontier.length) break
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
const idx = allowed ? g.nodes.filter((n) => allowed.has(n.i)) : g.nodes
|
|
1277
|
+
const byIndex = new Map(idx.map((n) => [n.i, n]))
|
|
1278
|
+
const scopedEdges = allowed ? g.edges.filter((e) => allowed.has(e.s) && allowed.has(e.t)) : g.edges
|
|
1279
|
+
const top = [...idx].sort((a, b) => (b.degree || 0) - (a.degree || 0)).slice(0, limit)
|
|
1280
|
+
const strong = [...scopedEdges].sort((a, b) => b.w - a.w).slice(0, Math.min(limit, 120))
|
|
1281
|
+
|
|
1282
|
+
// 切片后按切片内的边重算度数,避免沿用全图的 degree 把「孤岛」写错。
|
|
1283
|
+
const degree = new Map()
|
|
1284
|
+
for (const e of scopedEdges) {
|
|
1285
|
+
degree.set(e.s, (degree.get(e.s) || 0) + 1)
|
|
1286
|
+
degree.set(e.t, (degree.get(e.t) || 0) + 1)
|
|
1287
|
+
}
|
|
1288
|
+
const orphans = idx.filter((n) => (allowed ? (degree.get(n.i) || 0) : n.degree) === 0)
|
|
1289
|
+
const rawById = new Map((this.nodes || []).map((n) => [n.id, n]))
|
|
1290
|
+
const keptIds = new Set(idx.map((n) => n.id))
|
|
1291
|
+
const keptUids = new Set(idx.map((n) => n.uid).filter(Boolean))
|
|
1292
|
+
const scopedSessions = allowed
|
|
1293
|
+
? new Set((this.ledgers || []).filter((l) => (l.ids || []).some((id) => keptIds.has(id) || keptUids.has(id))).map((l) => l.sessionId)).size
|
|
1294
|
+
: g.stats.sessions
|
|
1295
|
+
const stats = allowed ? {
|
|
1296
|
+
...g.stats,
|
|
1297
|
+
nodes: idx.length,
|
|
1298
|
+
edges: scopedEdges.length,
|
|
1299
|
+
workspaces: new Set(idx.map((n) => n.wsTitle)).size,
|
|
1300
|
+
sessions: scopedSessions,
|
|
1301
|
+
orphans: orphans.length,
|
|
1302
|
+
avgDegree: idx.length ? Math.round((2 * scopedEdges.length / idx.length) * 10) / 10 : 0,
|
|
1303
|
+
} : g.stats
|
|
1304
|
+
// 图可能是从盘上恢复的:老缓存不带 clusters,这里统一兜一层,
|
|
1305
|
+
// 免得导出报告在 .map 上崩掉(1.11.62 修)。
|
|
1306
|
+
const allClusters = Array.isArray(g.clusters) ? g.clusters : []
|
|
1307
|
+
const clusters = allowed
|
|
1308
|
+
? allClusters.map((c) => {
|
|
1309
|
+
const members = (c.members || []).filter((i) => allowed.has(i))
|
|
1310
|
+
const workspaces = [...new Set(members.map((i) => g.nodes[i]?.ws).filter(Boolean))]
|
|
1311
|
+
return { ...c, members, size: members.length, workspaces }
|
|
1312
|
+
}).filter((c) => c.size > 0)
|
|
1313
|
+
: allClusters
|
|
1314
|
+
const scopeInfo = allowed ? { kind: scopeKind, value: scopeValue, nodes: idx.length, edges: scopedEdges.length } : { kind: 'all' }
|
|
1315
|
+
|
|
1316
|
+
if (format === 'json') {
|
|
1317
|
+
return {
|
|
1318
|
+
generatedAt: Date.now(),
|
|
1319
|
+
scope: scopeInfo,
|
|
1320
|
+
stats,
|
|
1321
|
+
clusters: clusters.map((c) => ({ id: c.id, title: c.title || c.label, size: c.size, color: c.color })),
|
|
1322
|
+
nodes: top.map((n) => ({
|
|
1323
|
+
id: n.id,
|
|
1324
|
+
label: n.label,
|
|
1325
|
+
ws: n.wsTitle,
|
|
1326
|
+
level: n.level,
|
|
1327
|
+
provider: n.provider,
|
|
1328
|
+
importance: n.importance,
|
|
1329
|
+
degree: n.degree,
|
|
1330
|
+
})),
|
|
1331
|
+
edges: strong.map((e) => [byIndex.get(e.s)?.id, byIndex.get(e.t)?.id, Math.round(e.w * 1000) / 1000, e.type]),
|
|
1332
|
+
orphans: orphans.slice(0, 200).map((n) => ({ id: n.id, label: n.label, ws: n.wsTitle })),
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
const stamp = new Date().toLocaleString('zh-CN', { hour12: false })
|
|
1337
|
+
const L = []
|
|
1338
|
+
L.push(`# 宏记忆 · 星图导出${allowed ? ' · ' + rawScope : ''} · ${stamp}`)
|
|
1339
|
+
L.push('')
|
|
1340
|
+
L.push(`节点 ${stats.nodes} · 连接 ${stats.edges} · 工作区 ${stats.workspaces} · 会话 ${stats.sessions} · 平均连接 ${stats.avgDegree}`)
|
|
1341
|
+
L.push('')
|
|
1342
|
+
L.push('## 工作区')
|
|
1343
|
+
L.push('')
|
|
1344
|
+
L.push('| 工作区 | 记忆 |')
|
|
1345
|
+
L.push('| --- | ---: |')
|
|
1346
|
+
for (const [ws, n] of Object.entries(stats.byWorkspace || {}).sort((a, b) => b[1] - a[1])) {
|
|
1347
|
+
L.push(`| ${ws} | ${n} |`)
|
|
1348
|
+
}
|
|
1349
|
+
L.push('')
|
|
1350
|
+
L.push('## 层级')
|
|
1351
|
+
L.push('')
|
|
1352
|
+
L.push('| 层级 | 记忆 |')
|
|
1353
|
+
L.push('| --- | ---: |')
|
|
1354
|
+
for (const [lv, n] of Object.entries(stats.byLevel || {}).sort((a, b) => b[1] - a[1])) {
|
|
1355
|
+
L.push(`| ${lv} | ${n} |`)
|
|
1356
|
+
}
|
|
1357
|
+
L.push('')
|
|
1358
|
+
L.push(`## 枢纽(连接最多的 ${top.length} 条)`)
|
|
1359
|
+
L.push('')
|
|
1360
|
+
top.forEach((n, i) => {
|
|
1361
|
+
L.push(`${i + 1}. 【${n.level}·${n.wsTitle}】${clip(n.title || n.label, 80)} —— 连接 ${n.degree}`)
|
|
1362
|
+
})
|
|
1363
|
+
L.push('')
|
|
1364
|
+
L.push('## 最强关联')
|
|
1365
|
+
L.push('')
|
|
1366
|
+
for (const e of strong) {
|
|
1367
|
+
const a = byIndex.get(e.s)
|
|
1368
|
+
const b = byIndex.get(e.t)
|
|
1369
|
+
if (!a || !b) continue
|
|
1370
|
+
const why = (e.why || []).map((x) => x.label || x.k).filter(Boolean).slice(0, 2).join(';')
|
|
1371
|
+
L.push(`- ${clip(a.title || a.label, 40)} ⇄ ${clip(b.title || b.label, 40)} · w=${e.w.toFixed(2)} · ${e.type}${why ? ' · ' + why : ''}`)
|
|
1372
|
+
}
|
|
1373
|
+
L.push('')
|
|
1374
|
+
L.push(`## 孤岛(${orphans.length} 条)`)
|
|
1375
|
+
L.push('')
|
|
1376
|
+
for (const n of orphans.slice(0, 60)) L.push(`- 【${n.level}·${n.wsTitle}】${clip(n.title || n.label, 70)}`)
|
|
1377
|
+
if (orphans.length > 60) L.push(`- …还有 ${orphans.length - 60} 条`)
|
|
1378
|
+
return { format: 'md', text: L.join('\n'), stats }
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/**
|
|
1382
|
+
* 两个节点之间的最短证据链:回答「A 和 B 到底怎么连上的」。
|
|
1383
|
+
* 只走星图里已经算出来的边,不猜、不补;找不到就是找不到。
|
|
1384
|
+
* @param {string} a
|
|
1385
|
+
* @param {string} b
|
|
1386
|
+
* @param {{maxHops?:number}} [opts]
|
|
1387
|
+
*/
|
|
1388
|
+
async path(a, b, opts = {}) {
|
|
1389
|
+
if (!this._findPath) await this.#loadOptionalModules()
|
|
1390
|
+
if (!this._findPath) return { found: false, error: '这个引擎版本还没带上路径搜索(等宿主重启后生效)' }
|
|
1391
|
+
const n = resolveIds(this.graph.nodes, [a, b])
|
|
1392
|
+
if (n.length < 2) return { found: false, error: '找不到这两个节点:' + a + ' / ' + b }
|
|
1393
|
+
const i = this.graph.nodes.indexOf(n[0])
|
|
1394
|
+
const j = this.graph.nodes.indexOf(n[1])
|
|
1395
|
+
if (i < 0 || j < 0) return { found: false, error: '节点不在当前星图里' }
|
|
1396
|
+
const res = this._findPath(this.graph, i, j, opts)
|
|
1397
|
+
if (!res || !res.found) {
|
|
1398
|
+
const e0 = this.graph.edges[0]
|
|
1399
|
+
return { found: false, debug: { i, j, nodes: this.graph.nodes.length, edges: this.graph.edges.length } }
|
|
1400
|
+
}
|
|
1401
|
+
const nodes = this.graph.nodes
|
|
1402
|
+
const field = (x) => ({
|
|
1403
|
+
id: x.id,
|
|
1404
|
+
label: x.label,
|
|
1405
|
+
level: x.level,
|
|
1406
|
+
ws: x.wsTitle,
|
|
1407
|
+
importance: x.importance,
|
|
1408
|
+
kind: x.kind,
|
|
1409
|
+
})
|
|
1410
|
+
return {
|
|
1411
|
+
found: res.found,
|
|
1412
|
+
hops: res.hops,
|
|
1413
|
+
score: Math.round(res.score * 1000) / 1000,
|
|
1414
|
+
nodes: res.ids.map((k) => field(nodes[k])),
|
|
1415
|
+
edges: res.edges.map((e) => ({
|
|
1416
|
+
a: nodes[e.s].id,
|
|
1417
|
+
b: nodes[e.t].id,
|
|
1418
|
+
w: e.w,
|
|
1419
|
+
t: e.type,
|
|
1420
|
+
why: Array.isArray(e.why) ? e.why.join(' · ') : e.why,
|
|
1421
|
+
})),
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
/**
|
|
1426
|
+
* 人工连线。
|
|
1427
|
+
* @param {string} a
|
|
1428
|
+
* @param {string} b
|
|
1429
|
+
* @param {string} [note]
|
|
1430
|
+
*/
|
|
1431
|
+
/**
|
|
1432
|
+
* 策展改动就地落到现在这张图上,不重建。
|
|
1433
|
+
*
|
|
1434
|
+
* 依据(dev/probe-curate-diff.mjs,冻结 now、同一份节点):
|
|
1435
|
+
* - 策展一条:全量重建**只多一条边**(w=1 / type=explicit / why 一条),是精确的;
|
|
1436
|
+
* - 否掉一条:全量重建会消失 2 条、补上 3 条 —— 因为剪枝上限腾出空位,下一名候选顶上来了。
|
|
1437
|
+
* 这里只删那一条、**不补位**:用户要的是「这条别再连着」,不是「换一条给它」。
|
|
1438
|
+
* 下次 /refresh 重建时自然会补位,那时两者一致。
|
|
1439
|
+
*
|
|
1440
|
+
* 体检/卡片/真相这几个缓存的键都是来源签名,策展改不动来源签名,所以必须手动作废。
|
|
1441
|
+
*/
|
|
1442
|
+
#nodeIndex(id) {
|
|
1443
|
+
const g = this.graph
|
|
1444
|
+
if (!g || !Array.isArray(g.nodes)) return -1
|
|
1445
|
+
const hit = g.nodes.find((n) => n.id === id)
|
|
1446
|
+
return hit ? hit.i : -1
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
/**
|
|
1450
|
+
* 建完图就把检索要用的词频表先在后台算好。
|
|
1451
|
+
*
|
|
1452
|
+
* 5 万条的记忆,第一次搜索要 1.3 秒,几乎全花在分词与数词频上——这件事跟用户什么时候
|
|
1453
|
+
* 想起要搜索没有关系,属于「反正都要算,不如趁没人等」。隔一拍再开工:刚建完图的那几个
|
|
1454
|
+
* 请求(首屏 /graph)不该跟它抢 CPU;期间要是又发起重建,graph 对象已经换了,这次预热
|
|
1455
|
+
* 自然作废(缓存以 graph 为键,WeakMap 不用手动清)。
|
|
1456
|
+
*/
|
|
1457
|
+
// 写盘是「这次响应之外」的事:测试与探针要等它落定,就叫这个方法。
|
|
1458
|
+
cacheWriteDone() {
|
|
1459
|
+
return this._cachePromise || Promise.resolve(this.lastCache)
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
#schedulePrewarm(graph) {
|
|
1463
|
+
if (!graph || !Array.isArray(graph.nodes) || graph.nodes.length === 0) return
|
|
1464
|
+
if (this._prewarmTimer) clearTimeout(this._prewarmTimer)
|
|
1465
|
+
this.lastPrewarm = { scheduled: true, done: false, ms: 0 }
|
|
1466
|
+
this._prewarmTimer = setTimeout(() => {
|
|
1467
|
+
this._prewarmTimer = null
|
|
1468
|
+
if (this.graph !== graph || this.building) {
|
|
1469
|
+
this.lastPrewarm = { scheduled: false, done: false, ms: 0, why: 'skipped' }
|
|
1470
|
+
return
|
|
1471
|
+
}
|
|
1472
|
+
const t0 = Date.now()
|
|
1473
|
+
ensureTokenCacheAsync(graph)
|
|
1474
|
+
.then(async () => {
|
|
1475
|
+
if (this.graph === graph) this.lastPrewarm = { scheduled: false, done: true, ms: Date.now() - t0 }
|
|
1476
|
+
// 接着把体检算好:这一步五万条要 2.3 秒,若等用户点开看板再算,
|
|
1477
|
+
// 那 2.3 秒正好落在他的等待里。失败不影响正确性——真要看得时候会自己再算。
|
|
1478
|
+
if (!this.hygieneWarm || this.graph !== graph) return
|
|
1479
|
+
if (this._hygiene && this._hygiene.sig === this.signature) return
|
|
1480
|
+
const h0 = Date.now()
|
|
1481
|
+
try {
|
|
1482
|
+
await this.hygieneAsync()
|
|
1483
|
+
if (this.graph === graph) this.lastHygieneWarm = { done: true, ms: Date.now() - h0 }
|
|
1484
|
+
} catch {
|
|
1485
|
+
if (this.graph === graph) this.lastHygieneWarm = { done: false, ms: Date.now() - h0, why: 'failed' }
|
|
1486
|
+
}
|
|
1487
|
+
})
|
|
1488
|
+
.catch(() => {
|
|
1489
|
+
// 预热失败不影响检索:真要查的时候 recallAsync 会自己再算一遍
|
|
1490
|
+
if (this.graph === graph) this.lastPrewarm = { scheduled: false, done: false, ms: Date.now() - t0, why: 'failed' }
|
|
1491
|
+
})
|
|
1492
|
+
}, this.prewarmDelayMs)
|
|
1493
|
+
if (typeof this._prewarmTimer.unref === 'function') this._prewarmTimer.unref()
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
/** 库的规模与它该带的提醒。看得懂的人不会被吓到,看不懂的人至少知道为什么慢。 */
|
|
1497
|
+
#scaleOf(graph) {
|
|
1498
|
+
const nodes = (graph.nodes || []).length
|
|
1499
|
+
const edges = (graph.edges || []).length
|
|
1500
|
+
return {
|
|
1501
|
+
nodes,
|
|
1502
|
+
edges,
|
|
1503
|
+
level: nodes >= this.largeLibraryNodes ? 'large' : 'ok',
|
|
1504
|
+
buildMs: this.lastBuildMs || 0,
|
|
1505
|
+
at: Date.now(),
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/** 给界面与探针看的告示清单(现在只有一条,但格式留好了)。 */
|
|
1510
|
+
#warnings() {
|
|
1511
|
+
const out = []
|
|
1512
|
+
const rec = storeRecovery()
|
|
1513
|
+
if (rec) {
|
|
1514
|
+
out.push({
|
|
1515
|
+
code: 'store-recovered',
|
|
1516
|
+
path: rec.path,
|
|
1517
|
+
movedTo: rec.movedTo,
|
|
1518
|
+
message: rec.movedTo
|
|
1519
|
+
? '星图自己的小库(' + rec.path + ')上次打不开(' + rec.error + '),已经把坏文件挪到 ' + rec.movedTo + ',改用新建的空库:人工策展的连边与屏蔽记录需要重新做一遍。'
|
|
1520
|
+
: '星图自己的小库(' + rec.path + ')打不开(' + rec.error + '),而且挪不动旧文件,这次只能用内存里的空库:策展的连边与屏蔽记录都不会保存。',
|
|
1521
|
+
})
|
|
1522
|
+
}
|
|
1523
|
+
if (this.configError) {
|
|
1524
|
+
out.push({
|
|
1525
|
+
code: 'config-unreadable',
|
|
1526
|
+
message: 'sources.json 读不出来(' + this.configError + '):配置里声明的来源这次没有接入,只剩内置来源与自动发现。',
|
|
1527
|
+
})
|
|
1528
|
+
}
|
|
1529
|
+
for (const w of this.storeWarnings || []) {
|
|
1530
|
+
if (w.code !== "truncated") continue
|
|
1531
|
+
out.push({
|
|
1532
|
+
code: "source-truncated",
|
|
1533
|
+
store: w.store,
|
|
1534
|
+
id: w.id,
|
|
1535
|
+
maxFiles: w.maxFiles,
|
|
1536
|
+
message: w.message,
|
|
1537
|
+
})
|
|
1538
|
+
}
|
|
1539
|
+
const sc = this.scale
|
|
1540
|
+
if (sc && sc.level === "large") {
|
|
1541
|
+
out.push({
|
|
1542
|
+
code: 'large-library',
|
|
1543
|
+
nodes: sc.nodes,
|
|
1544
|
+
buildMs: sc.buildMs,
|
|
1545
|
+
message: '这个库有 ' + sc.nodes + ' 条记忆,建图会很慢(最近一次 ' + Math.round(sc.buildMs / 1000) + ' 秒),建议按工作区拆库。',
|
|
1546
|
+
})
|
|
1547
|
+
}
|
|
1548
|
+
return out
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
/**
|
|
1552
|
+
* 边集合变了之后,把 stats 里的数字重算一遍(读盘摘边、策展连线、屏蔽都走这里)。
|
|
1553
|
+
*
|
|
1554
|
+
* 为什么需要它:`byType` 是嵌套对象,`restamp()` 里 `{ ...g.stats }` 只是浅拷贝,
|
|
1555
|
+
* 于是「按类型」那份计数一直停在建图那一刻 —— 屏蔽一条边之后,图例里各类型加起来
|
|
1556
|
+
* 比总边数多一条(1.11.65 修)。数字不能出现两个来源,所以统一在这里算。
|
|
1557
|
+
*/
|
|
1558
|
+
#syncEdgeStats() {
|
|
1559
|
+
const g = this.graph
|
|
1560
|
+
if (!g || !Array.isArray(g.edges)) return
|
|
1561
|
+
const byType = {}
|
|
1562
|
+
for (const e of g.edges) {
|
|
1563
|
+
const key = e.type || 'other'
|
|
1564
|
+
byType[key] = (byType[key] || 0) + 1
|
|
1565
|
+
}
|
|
1566
|
+
if (g.stats) {
|
|
1567
|
+
if (this.graph.stats) this.graph.stats.edges = this.graph.edges.length
|
|
1568
|
+
g.stats.byType = byType
|
|
1569
|
+
g.stats.avgDegree = Math.round((g.edges.length * 2 * 100) / Math.max(1, g.nodes ? g.nodes.length : 1)) / 100
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
#applyCurated(kind, aId, bId, note, opts = {}) {
|
|
1574
|
+
const g = this.graph
|
|
1575
|
+
if (!g || !Array.isArray(g.nodes) || !Array.isArray(g.edges)) return
|
|
1576
|
+
const ia = this.#nodeIndex(aId)
|
|
1577
|
+
const ib = this.#nodeIndex(bId)
|
|
1578
|
+
if (ia < 0 || ib < 0 || ia === ib) return
|
|
1579
|
+
const s = Math.min(ia, ib)
|
|
1580
|
+
const t = Math.max(ia, ib)
|
|
1581
|
+
const at = g.edges.findIndex((e) => e.s === s && e.t === t)
|
|
1582
|
+
const restamp = () => {
|
|
1583
|
+
const na = g.nodes[s]
|
|
1584
|
+
const nb = g.nodes[t]
|
|
1585
|
+
this.#syncEdgeStats()
|
|
1586
|
+
void na
|
|
1587
|
+
void nb
|
|
1588
|
+
this._hygiene = null
|
|
1589
|
+
this._cards = null
|
|
1590
|
+
this._truth = null
|
|
1591
|
+
this._pageCache = null
|
|
1592
|
+
// 来源签名里带了「人工连线」这一项(l<条数>:<最新 updatedAt>)。策展改的就是它,
|
|
1593
|
+
// 所以要顺手把签名重算一遍:否则下一次 /graph?refresh=1 会认为「来源变了」,
|
|
1594
|
+
// 把刚做好的就地改动再用一次全量重建覆盖掉——那就白改了。
|
|
1595
|
+
try {
|
|
1596
|
+
this.signature = this.computeSignature()
|
|
1597
|
+
} catch {
|
|
1598
|
+
/* 算不出来就保持原样,下一次 refresh 会自己重算 */
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
const bump = (delta) => {
|
|
1602
|
+
for (const i of [s, t]) {
|
|
1603
|
+
const n = g.nodes[i]
|
|
1604
|
+
if (n) n.degree = Math.max(0, (n.degree || 0) + delta)
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
if (kind === 'add') {
|
|
1608
|
+
// 这条边已经在图里(多半是系统自己按关键词/语义连上的):不能就这么算了。
|
|
1609
|
+
// 以前这里只重算签名就返回 —— 主人点了「确认这两条是一件事」,界面上一点变化都没有;
|
|
1610
|
+
// 更糟的是接下来取消连线会把这条系统边一起摘掉(1.11.60)。
|
|
1611
|
+
// 现在的做法:把这条边就地升级成人工策展,原有证据留在 why 里,被顶掉的那份记进
|
|
1612
|
+
// _curatedAuto,取消连线时原样放回去。
|
|
1613
|
+
if (at >= 0) {
|
|
1614
|
+
const prev = g.edges[at]
|
|
1615
|
+
this._curatedAuto = this._curatedAuto || new Map()
|
|
1616
|
+
this._curatedAuto.set(s + '|' + t, prev)
|
|
1617
|
+
const keepWhy = Array.isArray(prev.why) ? prev.why : prev.why ? [String(prev.why)] : []
|
|
1618
|
+
g.edges[at] = {
|
|
1619
|
+
s,
|
|
1620
|
+
t,
|
|
1621
|
+
w: 1,
|
|
1622
|
+
type: 'explicit',
|
|
1623
|
+
why: [note ? '策展:' + note : '人工策展关联', ...keepWhy],
|
|
1624
|
+
}
|
|
1625
|
+
restamp()
|
|
1626
|
+
return
|
|
1627
|
+
}
|
|
1628
|
+
g.edges.push({
|
|
1629
|
+
s,
|
|
1630
|
+
t,
|
|
1631
|
+
w: 1,
|
|
1632
|
+
type: 'explicit',
|
|
1633
|
+
why: [note ? '策展:' + note : '人工策展关联'],
|
|
1634
|
+
})
|
|
1635
|
+
bump(1)
|
|
1636
|
+
restamp()
|
|
1637
|
+
return
|
|
1638
|
+
}
|
|
1639
|
+
if (at < 0) {
|
|
1640
|
+
// 图上本来就没有这条边:顺手把「系统原本那份」的记忆清掉,免得它日后复活
|
|
1641
|
+
if (opts.keepAuto) {
|
|
1642
|
+
this._curatedAuto = this._curatedAuto || new Map()
|
|
1643
|
+
this._curatedAuto.delete(s + '|' + t)
|
|
1644
|
+
}
|
|
1645
|
+
return
|
|
1646
|
+
}
|
|
1647
|
+
// 取消连线(不是屏蔽):如果这条边原本是系统连的,只是被人工升级过,就把原来那份放回去。
|
|
1648
|
+
// 主人取消的是自己那根线,系统找到的关系不该跟着消失(1.11.60)。
|
|
1649
|
+
if (opts.keepAuto) {
|
|
1650
|
+
this._curatedAuto = this._curatedAuto || new Map()
|
|
1651
|
+
const key = s + '|' + t
|
|
1652
|
+
const auto = this._curatedAuto.get(key)
|
|
1653
|
+
this._curatedAuto.delete(key)
|
|
1654
|
+
if (auto) {
|
|
1655
|
+
g.edges[at] = auto
|
|
1656
|
+
restamp()
|
|
1657
|
+
return
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
// 记住被删掉的这条:撤销屏蔽时能原样放回去,不用重算
|
|
1661
|
+
this._curatedGone = this._curatedGone || new Map()
|
|
1662
|
+
this._curatedGone.set(s + '|' + t, g.edges[at])
|
|
1663
|
+
g.edges.splice(at, 1)
|
|
1664
|
+
bump(-1)
|
|
1665
|
+
restamp()
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
/** 撤销屏蔽时把当初删掉的那条放回去(放不回去说明本来就没有这条边,交给重建)。 */
|
|
1669
|
+
#restoreCurated(aId, bId) {
|
|
1670
|
+
const g = this.graph
|
|
1671
|
+
if (!g || !Array.isArray(g.nodes) || !Array.isArray(g.edges)) return false
|
|
1672
|
+
const ia = this.#nodeIndex(aId)
|
|
1673
|
+
const ib = this.#nodeIndex(bId)
|
|
1674
|
+
if (ia < 0 || ib < 0) return false
|
|
1675
|
+
const s = Math.min(ia, ib)
|
|
1676
|
+
const t = Math.max(ia, ib)
|
|
1677
|
+
this._curatedGone = this._curatedGone || new Map()
|
|
1678
|
+
const edge = this._curatedGone.get(s + '|' + t)
|
|
1679
|
+
if (!edge) return false
|
|
1680
|
+
if (g.edges.some((e) => e.s === s && e.t === t)) return false
|
|
1681
|
+
g.edges.push(edge)
|
|
1682
|
+
this._curatedGone.delete(s + '|' + t)
|
|
1683
|
+
for (const i of [s, t]) {
|
|
1684
|
+
const n = g.nodes[i]
|
|
1685
|
+
if (n) n.degree = (n.degree || 0) + 1
|
|
1686
|
+
}
|
|
1687
|
+
const d = g.edges.length
|
|
1688
|
+
void d
|
|
1689
|
+
this.#syncEdgeStats()
|
|
1690
|
+
this._hygiene = null
|
|
1691
|
+
this._cards = null
|
|
1692
|
+
this._truth = null
|
|
1693
|
+
this._pageCache = null
|
|
1694
|
+
try {
|
|
1695
|
+
this.signature = this.computeSignature()
|
|
1696
|
+
} catch {
|
|
1697
|
+
/* 算不出来就保持原样 */
|
|
1698
|
+
}
|
|
1699
|
+
return true
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
link(a, b, note = '') {
|
|
1703
|
+
const n = resolveIds(this.graph.nodes, [a, b])
|
|
1704
|
+
if (n.length < 2) throw missingNodes(a, b)
|
|
1705
|
+
if (n[0].id === n[1].id) throw selfPair(n[0].id)
|
|
1706
|
+
addLink(n[0].id, n[1].id, note)
|
|
1707
|
+
this.#applyCurated('add', n[0].id, n[1].id, note)
|
|
1708
|
+
return { a: n[0].id, b: n[1].id, note }
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
/**
|
|
1712
|
+
* 解除人工连线。
|
|
1713
|
+
* @param {string} a
|
|
1714
|
+
* @param {string} b
|
|
1715
|
+
*/
|
|
1716
|
+
unlink(a, b) {
|
|
1717
|
+
const n = resolveIds(this.graph.nodes, [a, b])
|
|
1718
|
+
if (n.length < 2) return false
|
|
1719
|
+
const ok = removeLink(n[0].id, n[1].id)
|
|
1720
|
+
if (ok) {
|
|
1721
|
+
// 屏蔽优先:被屏蔽的一对本来就不该挂在图上,这里不把系统原本那份放回去
|
|
1722
|
+
const muted = this.demo
|
|
1723
|
+
? false
|
|
1724
|
+
: listMutes().some(
|
|
1725
|
+
(m) => (m.a === n[0].id && m.b === n[1].id) || (m.a === n[1].id && m.b === n[0].id),
|
|
1726
|
+
)
|
|
1727
|
+
this.#applyCurated('drop', n[0].id, n[1].id, '', muted ? {} : { keepAuto: true })
|
|
1728
|
+
}
|
|
1729
|
+
return ok
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
/**
|
|
1733
|
+
* 屏蔽一对节点之间的自动关联:重建星图时这条边不会再出现。
|
|
1734
|
+
* 这是「关联算错了」的正规出口 —— 不是一删了之,而是把这条推断记进黑名单。
|
|
1735
|
+
* @param {string} a
|
|
1736
|
+
* @param {string} b
|
|
1737
|
+
* @param {string} [note]
|
|
1738
|
+
*/
|
|
1739
|
+
mute(a, b, note = '') {
|
|
1740
|
+
const n = resolveIds(this.graph.nodes, [a, b])
|
|
1741
|
+
if (n.length < 2) throw missingNodes(a, b)
|
|
1742
|
+
if (n[0].id === n[1].id) throw selfPair(n[0].id)
|
|
1743
|
+
addMute(n[0].id, n[1].id, note)
|
|
1744
|
+
this.#applyCurated('drop', n[0].id, n[1].id)
|
|
1745
|
+
// 计数要跟着变:muteCount 是图载荷里的诊断数字(界面另有一份来自 /mutes 的列表),
|
|
1746
|
+
// 以前它只在建图与读盘时写一次,屏蔽完还是旧数字,两边对不上(1.11.59)。
|
|
1747
|
+
this.graph.muteCount = this.mutes().length
|
|
1748
|
+
return { a: n[0].id, b: n[1].id, note }
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
/**
|
|
1752
|
+
* 取消屏蔽。
|
|
1753
|
+
* @param {string} a
|
|
1754
|
+
* @param {string} b
|
|
1755
|
+
*/
|
|
1756
|
+
unmute(a, b) {
|
|
1757
|
+
const n = resolveIds(this.graph.nodes, [a, b])
|
|
1758
|
+
if (n.length < 2) return false
|
|
1759
|
+
const ok = removeMute(n[0].id, n[1].id)
|
|
1760
|
+
if (!ok) return false
|
|
1761
|
+
// 撤销屏蔽要「把这条关联还给我」:当初删掉的那条能原样放回就放回(毫秒级),
|
|
1762
|
+
// 放不回去(当时本来就没有这条边,或者屏蔽是在重建时生效的)才需要重算。
|
|
1763
|
+
if (!this.#restoreCurated(n[0].id, n[1].id)) this._needsRebuild = true
|
|
1764
|
+
this.graph.muteCount = this.mutes().length
|
|
1765
|
+
return true
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
/** 取走「这轮改动放不回去、必须重算」的标记(HTTP 层用完即清)。 */
|
|
1769
|
+
takeRebuildFlag() {
|
|
1770
|
+
const v = this._needsRebuild === true
|
|
1771
|
+
this._needsRebuild = false
|
|
1772
|
+
return v
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
/** 当前被屏蔽的关联对(UI 里要能看见、能撤销)。 */
|
|
1776
|
+
mutes() {
|
|
1777
|
+
return listMutes()
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
/** 记忆体检:把「越写越肥、两份打架、没人读、关系是凑的」查成一张清单。 */
|
|
1781
|
+
hygiene() {
|
|
1782
|
+
if (this._hygiene && this._hygiene.sig === this.signature) return this._hygiene.value
|
|
1783
|
+
let value
|
|
1784
|
+
try {
|
|
1785
|
+
// 体检要看正文,用原始节点(图节点只带 200 字预览)
|
|
1786
|
+
// 边是下标形状,必须把「下标 → id」一起交给体检,否则孤立/弱关系两格会被算成假数据
|
|
1787
|
+
// 建图时每条记忆已经分过一次词(graph.nodes[i].tokens);体检再分一遍
|
|
1788
|
+
// 在 1 万条库上要多花一秒多。这里把 token 直接传过去复用。
|
|
1789
|
+
const tokensById = new Map(this.graph.nodes.map((n) => [n.id, n.tokens]))
|
|
1790
|
+
value = auditHygiene({ nodes: this.nodes, edges: this.graph.edges, nodeIds: this.graph.nodes.map((n) => n.id), tokensById })
|
|
1791
|
+
} catch (err) {
|
|
1792
|
+
value = { total: 0, counts: {}, items: {}, error: String(err && err.message) }
|
|
1793
|
+
}
|
|
1794
|
+
this._hygiene = { sig: this.signature, value }
|
|
1795
|
+
return value
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
/**
|
|
1799
|
+
* 记忆体检(异步版):2 万条的库上要 2.9 秒(分词签名 1.1s + 重复检测 1.5s)。
|
|
1800
|
+
* 同步算等于把 HTTP 事件循环按住——在 DSH 里就是宿主自己的主界面卡住。
|
|
1801
|
+
* 这里分片算,每片之间让出事件循环;同一份图的并发调用共用一次计算。
|
|
1802
|
+
*/
|
|
1803
|
+
async hygieneAsync() {
|
|
1804
|
+
if (this._hygiene && this._hygiene.sig === this.signature) return this._hygiene.value
|
|
1805
|
+
const sig = this.signature
|
|
1806
|
+
if (this._hygienePending && this._hygienePending.sig === sig) return this._hygienePending.promise
|
|
1807
|
+
const tokensById = new Map(this.graph.nodes.map((n) => [n.id, n.tokens]))
|
|
1808
|
+
const promise = auditHygieneAsync({
|
|
1809
|
+
nodes: this.nodes,
|
|
1810
|
+
edges: this.graph.edges,
|
|
1811
|
+
nodeIds: this.graph.nodes.map((n) => n.id),
|
|
1812
|
+
tokensById,
|
|
1813
|
+
})
|
|
1814
|
+
.then((value) => {
|
|
1815
|
+
if (this.signature === sig) this._hygiene = { sig, value }
|
|
1816
|
+
return value
|
|
1817
|
+
})
|
|
1818
|
+
.catch((err) => ({ total: 0, counts: {}, shown: {}, items: {}, error: String((err && err.message) || err) }))
|
|
1819
|
+
.finally(() => {
|
|
1820
|
+
if (this._hygienePending && this._hygienePending.promise === promise) this._hygienePending = null
|
|
1821
|
+
})
|
|
1822
|
+
this._hygienePending = { sig, promise }
|
|
1823
|
+
return promise
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
/** 概览的异步版:先分片把体检算好(算完进缓存),再组装同步部分。 */
|
|
1827
|
+
async overviewAsync(opts = {}) {
|
|
1828
|
+
await this.hygieneAsync()
|
|
1829
|
+
return this.overview(opts)
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
/**
|
|
1833
|
+
* 等那一笔缓存真的落盘。
|
|
1834
|
+
*
|
|
1835
|
+
* 建完图后缓存是「立刻开始写、但不挡返回」——服务跑着时没问题,可一次性命令
|
|
1836
|
+
* (--export / --share / --diagnose)建完就 process.exit,写盘那一半被掐掉,
|
|
1837
|
+
* 于是下一次启动又得把整张图重算一遍(20 万条要三十多秒)。退出前等它一下。
|
|
1838
|
+
* @param {number} [timeoutMs] 最多等多久,超时就先走(不让命令行卡住)
|
|
1839
|
+
*/
|
|
1840
|
+
async flushCache(timeoutMs = 20000) {
|
|
1841
|
+
const pending = this._cachePromise
|
|
1842
|
+
if (!pending || typeof pending.then !== 'function') return this.lastCache || null
|
|
1843
|
+
let timer = null
|
|
1844
|
+
const guard = new Promise((resolve) => {
|
|
1845
|
+
timer = setTimeout(() => resolve(null), timeoutMs)
|
|
1846
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
1847
|
+
})
|
|
1848
|
+
try {
|
|
1849
|
+
return await Promise.race([pending.catch(() => null), guard])
|
|
1850
|
+
} finally {
|
|
1851
|
+
if (timer) clearTimeout(timer)
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
/**
|
|
1856
|
+
* 项目卡片:每个工作区一张「交接卡」——现状 / 最近变更 / 下一步与卡点 / 代表记忆。
|
|
1857
|
+
*
|
|
1858
|
+
* 只做聚合,不判断谁对谁错:数字全部来自只读抽取,卡片是给「换会话接活」的人看的。
|
|
1859
|
+
*/
|
|
1860
|
+
cards() {
|
|
1861
|
+
if (this._cards && this._cards.sig === this.signature) return this._cards.value
|
|
1862
|
+
const memories = this.nodes.filter((n) => n.level !== 'source')
|
|
1863
|
+
const degOf = new Map(this.graph.nodes.map((n) => [n.id, n.degree]))
|
|
1864
|
+
const hy = this.hygiene()
|
|
1865
|
+
const healthByWs = new Map()
|
|
1866
|
+
for (const [kind, list] of Object.entries((hy && hy.items) || {})) {
|
|
1867
|
+
for (const it of list || []) {
|
|
1868
|
+
const ws = it.ws
|
|
1869
|
+
if (!ws) continue
|
|
1870
|
+
const cur = healthByWs.get(ws) || {}
|
|
1871
|
+
cur[kind] = (cur[kind] || 0) + 1
|
|
1872
|
+
healthByWs.set(ws, cur)
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
const byWs = new Map()
|
|
1876
|
+
for (const n of memories) {
|
|
1877
|
+
const ws = n.ws || 'unknown'
|
|
1878
|
+
let arr = byWs.get(ws)
|
|
1879
|
+
if (!arr) byWs.set(ws, (arr = []))
|
|
1880
|
+
arr.push(n)
|
|
1881
|
+
}
|
|
1882
|
+
const cards = []
|
|
1883
|
+
for (const [ws, list] of byWs) {
|
|
1884
|
+
const levels = {}
|
|
1885
|
+
for (const n of list) levels[n.level] = (levels[n.level] || 0) + 1
|
|
1886
|
+
const sessions = new Set(list.map((n) => n.sessionId).filter(Boolean)).size
|
|
1887
|
+
const projects = [...new Set(list.map((n) => n.project).filter((p) => p && p !== '全局'))].slice(0, 4)
|
|
1888
|
+
const recent = list
|
|
1889
|
+
.slice()
|
|
1890
|
+
.sort((a, b) => (b.updatedAt || b.createdAt || 0) - (a.updatedAt || a.createdAt || 0))
|
|
1891
|
+
.slice(0, 3)
|
|
1892
|
+
.map((n) => ({
|
|
1893
|
+
id: n.id,
|
|
1894
|
+
label: clip(n.title || n.label, 42),
|
|
1895
|
+
level: n.level,
|
|
1896
|
+
status: n.status,
|
|
1897
|
+
at: n.updatedAt || n.createdAt || 0,
|
|
1898
|
+
}))
|
|
1899
|
+
// 下一步与卡点:project/todo 子类里还 active 的那几条
|
|
1900
|
+
const todos = list
|
|
1901
|
+
.filter((n) => n.level === 'project' && n.subcategory === 'todo' && n.status === 'active')
|
|
1902
|
+
.sort((a, b) => (b.importance || 0) - (a.importance || 0) || (b.updatedAt || 0) - (a.updatedAt || 0))
|
|
1903
|
+
.slice(0, 3)
|
|
1904
|
+
.map((n) => ({ id: n.id, label: clip(n.title || n.label, 72), importance: n.importance, goal: n.goal || '' }))
|
|
1905
|
+
const hubs = list
|
|
1906
|
+
.slice()
|
|
1907
|
+
.sort((a, b) => b.importance * 3 + (degOf.get(b.id) || 0) - (a.importance * 3 + (degOf.get(a.id) || 0)))
|
|
1908
|
+
.slice(0, 3)
|
|
1909
|
+
.map((n) => ({
|
|
1910
|
+
id: n.id,
|
|
1911
|
+
label: clip(n.title || n.label, 42),
|
|
1912
|
+
level: n.level,
|
|
1913
|
+
importance: n.importance,
|
|
1914
|
+
degree: degOf.get(n.id) || 0,
|
|
1915
|
+
}))
|
|
1916
|
+
const updatedAt = list.reduce((m, n) => Math.max(m, n.updatedAt || n.createdAt || 0), 0)
|
|
1917
|
+
cards.push({
|
|
1918
|
+
ws,
|
|
1919
|
+
title: list[0].wsTitle || ws,
|
|
1920
|
+
total: list.length,
|
|
1921
|
+
levels,
|
|
1922
|
+
sessions,
|
|
1923
|
+
projects,
|
|
1924
|
+
recent,
|
|
1925
|
+
todos,
|
|
1926
|
+
hubs,
|
|
1927
|
+
health: healthByWs.get(ws) || {},
|
|
1928
|
+
updatedAt,
|
|
1929
|
+
})
|
|
1930
|
+
}
|
|
1931
|
+
cards.sort((a, b) => b.total - a.total)
|
|
1932
|
+
const value = { generatedAt: Date.now(), cards }
|
|
1933
|
+
this._cards = { sig: this.signature, value }
|
|
1934
|
+
return value
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
/**
|
|
1938
|
+
* 单一真源清单:把「声明过自己是权威」的记忆挑出来。
|
|
1939
|
+
*
|
|
1940
|
+
* 只看正文里明确写了「以…为准 / 单一真源 / 唯一权威 / 以此为准 / 权威版本」的,
|
|
1941
|
+
* 不做语义猜测——宁可少列,也不给一堆要你判断的假冲突。
|
|
1942
|
+
*/
|
|
1943
|
+
truthSources() {
|
|
1944
|
+
if (this._truth && this._truth.sig === this.signature) return this._truth.value
|
|
1945
|
+
const RE = /(以.{0,12}为准|单一真源|唯一权威|以此为准|权威版本|以这条为准|source of truth)/i
|
|
1946
|
+
const byProject = new Map()
|
|
1947
|
+
for (const n of this.nodes) {
|
|
1948
|
+
if (n.level === 'source') continue
|
|
1949
|
+
if (!RE.test(n.content || '')) continue
|
|
1950
|
+
const key = n.project && n.project !== '全局' ? n.project : n.wsTitle || n.ws
|
|
1951
|
+
let arr = byProject.get(key)
|
|
1952
|
+
if (!arr) byProject.set(key, (arr = []))
|
|
1953
|
+
arr.push({ id: n.id, label: clip(n.title || n.label, 56), ws: n.wsTitle, level: n.level, importance: n.importance })
|
|
1954
|
+
}
|
|
1955
|
+
const groups = [...byProject.entries()]
|
|
1956
|
+
.map(([project, items]) => ({ project, items }))
|
|
1957
|
+
.sort((a, b) => b.items.length - a.items.length)
|
|
1958
|
+
const value = { total: groups.reduce((s, g) => s + g.items.length, 0), groups }
|
|
1959
|
+
this._truth = { sig: this.signature, value }
|
|
1960
|
+
return value
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
/**
|
|
1964
|
+
* 重要度建议:只给「建议」,不改别人的库。
|
|
1965
|
+
*
|
|
1966
|
+
* 依据三条可解释信号:被读过(hits)、连了几条(degree)、写了多久没人碰(age)。
|
|
1967
|
+
*/
|
|
1968
|
+
suggestImportance() {
|
|
1969
|
+
const now = Date.now()
|
|
1970
|
+
const out = new Map()
|
|
1971
|
+
for (const n of this.graph.nodes) {
|
|
1972
|
+
if (n.level === 'source') continue
|
|
1973
|
+
const cur = n.importance || 1
|
|
1974
|
+
const reasons = []
|
|
1975
|
+
let d = 0
|
|
1976
|
+
if (n.hits > 0) {
|
|
1977
|
+
d += 1
|
|
1978
|
+
reasons.push('被读过 ' + n.hits + ' 次')
|
|
1979
|
+
}
|
|
1980
|
+
if (n.degree >= 14) {
|
|
1981
|
+
d += 1
|
|
1982
|
+
reasons.push('连了 ' + n.degree + ' 条')
|
|
1983
|
+
} else if (n.degree <= 1) {
|
|
1984
|
+
d -= 1
|
|
1985
|
+
reasons.push('只连了 ' + n.degree + ' 条')
|
|
1986
|
+
}
|
|
1987
|
+
const days = (now - (n.createdAt || now)) / 86400000
|
|
1988
|
+
if (n.hits === 0 && days > 45) {
|
|
1989
|
+
d -= 1
|
|
1990
|
+
reasons.push('写了 ' + Math.round(days) + ' 天没人读')
|
|
1991
|
+
}
|
|
1992
|
+
const next = Math.max(1, Math.min(4, cur + Math.sign(d) * Math.min(2, Math.abs(d))))
|
|
1993
|
+
if (next !== cur) out.set(n.id, { from: cur, to: next, why: reasons.join(',') })
|
|
1994
|
+
}
|
|
1995
|
+
return out
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
/** 外部记忆源探测:能读就读,读不到就说读不到(不假装有数据)。 */
|
|
1999
|
+
externals() {
|
|
2000
|
+
const home = dshHome()
|
|
2001
|
+
const user = process.env.USERPROFILE || ''
|
|
2002
|
+
const items = []
|
|
2003
|
+
const cfg = join(user, '.hindsight', 'coding-agent.json')
|
|
2004
|
+
items.push({
|
|
2005
|
+
id: 'hindsight',
|
|
2006
|
+
name: 'Hindsight',
|
|
2007
|
+
ok: existsSync(cfg),
|
|
2008
|
+
note: existsSync(cfg) ? '检测到本地配置,知识页可作为来源节点' : '没有本地 token / 知识页,暂时读不到',
|
|
2009
|
+
})
|
|
2010
|
+
const ovDir = join(user, '.openviking')
|
|
2011
|
+
let pending = 0
|
|
2012
|
+
try {
|
|
2013
|
+
pending = existsSync(join(ovDir, 'pending')) ? readdirSync(join(ovDir, 'pending')).length : 0
|
|
2014
|
+
} catch {}
|
|
2015
|
+
items.push({
|
|
2016
|
+
id: 'openviking',
|
|
2017
|
+
name: 'OpenViking',
|
|
2018
|
+
ok: false,
|
|
2019
|
+
note: pending ? '只有待上传队列(' + pending + ' 条),没有可查记忆库' : '没有可查记忆库',
|
|
2020
|
+
})
|
|
2021
|
+
items.push({
|
|
2022
|
+
id: 'meow',
|
|
2023
|
+
name: 'meow-memory',
|
|
2024
|
+
ok: (this.stores || []).length > 0,
|
|
2025
|
+
note: (this.stores || []).length + ' 个工作区记忆库,只读',
|
|
2026
|
+
})
|
|
2027
|
+
return { items, home }
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
/** 星图概览(给 AI 用的极简摘要)。 */
|
|
2031
|
+
overview(opts = {}) {
|
|
2032
|
+
// opts.hygiene === false:不算体检(调用方自己算,或已经有切片专用的那份)。
|
|
2033
|
+
// 2 万条的体检要 3 秒,任何「只要个底稿」的地方都不该顺手把它算出来。
|
|
2034
|
+
// 1.11.46:opts.hygiene === 'cached' —— 有缓存就用,没有就先给别的并标 pending。
|
|
2035
|
+
// 20 万条的体检要 12.9 秒,让「打开面板」等它,等于一开就假死。
|
|
2036
|
+
const cachedOnly = opts.hygiene === 'cached'
|
|
2037
|
+
const cachedHygiene = cachedOnly && this._hygiene && this._hygiene.sig === this.signature ? this._hygiene.value : null
|
|
2038
|
+
const s = this.graph.stats
|
|
2039
|
+
const top = this.graph.nodes
|
|
2040
|
+
.slice()
|
|
2041
|
+
.sort((a, b) => b.degree * (1 + b.importance * 0.25) - a.degree * (1 + a.importance * 0.25))
|
|
2042
|
+
.slice(0, hubSlots(opts.hubs))
|
|
2043
|
+
.map((n) => ({ id: n.id, label: n.label, ws: n.wsTitle, level: n.level, degree: n.degree, importance: n.importance }))
|
|
2044
|
+
return {
|
|
2045
|
+
stats: s,
|
|
2046
|
+
workspaces: Object.entries(s.byWorkspace || {}).map(([name, count]) => ({ name, count })),
|
|
2047
|
+
levels: s.byLevel || {},
|
|
2048
|
+
edgeTypes: s.byType || {},
|
|
2049
|
+
clusters: (this.graph.clusters || []).slice(0, 8).map((c) => ({ label: c.label, size: c.size, workspaces: c.workspaces })),
|
|
2050
|
+
hubs: top,
|
|
2051
|
+
sources: this.graph.sources || [],
|
|
2052
|
+
// 规模与提醒:库大到影响体验时,机器可读的一句话说清「慢是正常的、为什么」
|
|
2053
|
+
scale: this.scale || null,
|
|
2054
|
+
warnings: this.#warnings(),
|
|
2055
|
+
// 读不动的库要有一个机器可读的清单:界面那条常驻横幅、导出的快照横幅
|
|
2056
|
+
// 都从这里来。以前只有每个 source 上的 error 字段,于是「图上少了一个库」
|
|
2057
|
+
// 只有翻到「记忆来源」面板里才看得见。
|
|
2058
|
+
readErrors: (this.graph.sources || [])
|
|
2059
|
+
.filter((s) => s.error)
|
|
2060
|
+
.map((s) => ({
|
|
2061
|
+
key: s.key,
|
|
2062
|
+
title: s.title || s.key,
|
|
2063
|
+
path: s.path || s.db || '',
|
|
2064
|
+
error: s.error,
|
|
2065
|
+
})),
|
|
2066
|
+
inventory: {
|
|
2067
|
+
plugins: (this.inventory.plugins || []).length,
|
|
2068
|
+
skills: (this.inventory.skills || []).length,
|
|
2069
|
+
mcp: (this.inventory.mcp || []).length,
|
|
2070
|
+
// 谁在记记忆:名字里带这些词的插件,多半就是记忆/上下文类
|
|
2071
|
+
// (排除 @deepseek-ai/* 框架包——"deepseek" 里也含 "seek",会误伤)
|
|
2072
|
+
memoryPlugins: (this.inventory.plugins || [])
|
|
2073
|
+
.filter((p) => !/^@deepseek-ai\//i.test(p.name))
|
|
2074
|
+
.filter((p) => /memory|memewiki|hindsight|openviking|seekmemory|context|recall|billion|mind/i.test(p.name))
|
|
2075
|
+
.map((p) => p.name),
|
|
2076
|
+
mcpNames: (this.inventory.mcp || []).map((m) => m.name).slice(0, 8),
|
|
2077
|
+
},
|
|
2078
|
+
builtAt: this.graph.builtAt,
|
|
2079
|
+
buildMs: this.lastBuildMs,
|
|
2080
|
+
cacheAgeMs: this.cacheAgeMs || 0,
|
|
2081
|
+
lastError: this.lastError,
|
|
2082
|
+
lastSignature: this.signature.slice(0, 120),
|
|
2083
|
+
dbPath: this.demo ? '' : join(nebulaHome(), 'nebula.db'),
|
|
2084
|
+
lastBuiltAt: this.demo ? '' : getMeta('lastBuiltAt', ''),
|
|
2085
|
+
hygiene: cachedOnly ? cachedHygiene : opts.hygiene === false ? null : this.hygiene(),
|
|
2086
|
+
// cards 里的 health 也是从体检推出来的:opts.hygiene === false 时不能顺手再算一遍,
|
|
2087
|
+
// 否则「不算体检」就成了一句空话(5 万条的库上这里要 7 秒)。
|
|
2088
|
+
cards: cachedOnly ? (cachedHygiene ? this.cards() : null) : opts.hygiene === false ? null : this.cards(),
|
|
2089
|
+
// 体检还没算出来:先把其余部分给出去,界面自己去 /hygiene 取这一份。
|
|
2090
|
+
// 说清楚「在算」而不是「没有问题」——空清单会被读成「库很干净」。
|
|
2091
|
+
hygienePending: cachedOnly && !cachedHygiene,
|
|
2092
|
+
truth: this.truthSources(),
|
|
2093
|
+
externals: this.externals(),
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
/** 读一个文件的前 N 字节(给调试用)。 */
|
|
2099
|
+
export function head(file, n = 400) {
|
|
2100
|
+
try {
|
|
2101
|
+
return readFileSync(file, 'utf8').slice(0, n)
|
|
2102
|
+
} catch {
|
|
2103
|
+
return ''
|
|
2104
|
+
}
|
|
2105
|
+
}
|