dsh-macro-memory 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,197 @@
1
+ // [macro-fusion 0.4.0] P3:自动 supersedes(默认只给建议,apply 才动库)。
2
+ //
3
+ // 病:`conflictCandidates`(vendor/meow-memory/lib/index.js:3692)已经在写侧认出「同一件事的另一种说法」,
4
+ // 但只印一句 ⚠️ 提醒,要不要标 stale 全靠人。长期库里最伤的不是重复措辞,是**旧结论冒充现状**:
5
+ // 四条 fact 并排写着「当前版本是 X」,检索时读到哪条算数没有答案。
6
+ //
7
+ // 为什么在 macro 侧判、而不是把 meow 的那个函数搬过来用:融合层只能通过 `flow.call` 走工具面,
8
+ // 拿不到 vendor 的内部函数。所以这里按同一套硬事实(版本号 / 日期 / 状态词 / 数值 / 路径)重写一份判据,
9
+ // 用两条判据把「漂移」钉住:①两处正则字面量必须逐字相同(verify 的 as: 块);
10
+ // ②同一批 fixture 在两处跑出同一结论(tools/probe-supersede.mjs 的一致性对照)。
11
+ //
12
+ // 判据刻意窄(宁可漏,不可误杀):只报「它写 A,你这次写 B」这种硬事实;相似度门槛 0.3;
13
+ // 数值与路径两类还要求逐字重复度 ≥ 0.5——同一句话的改写才比数字,否则「3 条」跟「5 条」到处撞。
14
+
15
+ export const SUPERSEDE_ROWS = 20
16
+ export const SUPERSEDE_MAX = 3
17
+ export const SUPERSEDE_SIM = 0.3
18
+ export const SUPERSEDE_REPEAT = 0.5
19
+
20
+ // 与 vendor/meow-memory/lib/index.js:3669-3670 逐字相同(verify 的 as: 块钉着这两行)。
21
+ const VERSION_TOKEN = /(?:^|[^\w.])(\d+\.\d+(?:\.\d+){0,2})(?![\w.])/g
22
+ const DATE_TOKEN = /(?:^|\D)(\d{4}-\d{2}-\d{2})(?!\d)/g
23
+ // 路径:`D:\a\b`、`./x/y`、`tools/foo.mjs` 都收;判据是「同一个文件名、不同目录」。
24
+ const PATH_TOKEN = /(?:[A-Za-z]:[\\/]|\.{1,2}[\\/]|[\w.-]+[\\/])[\w.\\/-]+/g
25
+ // 数值 + 单位:只说「同一个单位下两个不同的数」,跨单位不比(27 支 vs 26 条不是同一件事)。
26
+ const NUM_UNIT = /(\d[\d,]*)\s*(支|条|个|次|毫秒|ms|秒|%|B|KB|MB)/g
27
+ const DONE_WORDS = ['已落地', '已完成', '已合并', '已修复', '已上线', '开着', '启用着']
28
+ const TODO_WORDS = ['未开始', '未做', '未落地', '还没做', '关着', '禁用']
29
+
30
+ function numOf(text) {
31
+ const n = Number(String(text).replace(/,/g, ''))
32
+ return Number.isFinite(n) ? n : null
33
+ }
34
+
35
+ function basenameOf(path) {
36
+ const parts = String(path).split(/[\\/]/).filter((one) => one !== '' && one !== '.' && one !== '..')
37
+ return parts.length === 0 ? '' : parts[parts.length - 1]
38
+ }
39
+
40
+ export function tokensOf(text) {
41
+ const s = String(text ?? '')
42
+ const versions = new Set()
43
+ const dates = new Set()
44
+ const nums = new Map()
45
+ const bases = new Map()
46
+ let m
47
+ VERSION_TOKEN.lastIndex = 0
48
+ while ((m = VERSION_TOKEN.exec(s))) versions.add(m[1])
49
+ DATE_TOKEN.lastIndex = 0
50
+ while ((m = DATE_TOKEN.exec(s))) dates.add(m[1])
51
+ NUM_UNIT.lastIndex = 0
52
+ while ((m = NUM_UNIT.exec(s))) {
53
+ const unit = m[2]
54
+ const value = numOf(m[1])
55
+ if (value === null) continue
56
+ if (!nums.has(unit)) nums.set(unit, new Set())
57
+ nums.get(unit).add(value)
58
+ }
59
+ PATH_TOKEN.lastIndex = 0
60
+ while ((m = PATH_TOKEN.exec(s))) {
61
+ const path = m[0].replace(/[.。,,;;::]+$/, '')
62
+ const base = basenameOf(path)
63
+ if (base === '') continue
64
+ if (!bases.has(base)) bases.set(base, new Set())
65
+ bases.get(base).add(path)
66
+ }
67
+ return { versions, dates, nums, bases }
68
+ }
69
+
70
+ const only = (x, y) => [...x].filter((v) => !y.has(v))
71
+
72
+ function stateOf(text) {
73
+ const s = String(text ?? '')
74
+ const done = DONE_WORDS.find((w) => s.includes(w))
75
+ const todo = todoHit(s)
76
+ if (done && !todo) return { side: 'done', word: done }
77
+ if (todo && !done) return { side: 'todo', word: todo }
78
+ return null
79
+ }
80
+
81
+ function todoHit(s) {
82
+ return TODO_WORDS.find((w) => s.includes(w))
83
+ }
84
+
85
+ // 返回 null 或 { kind, mine, theirs }:mine 是「这次写的」,theirs 是「库里那条写的」。
86
+ export function conflictOf(content, oldText) {
87
+ const A = tokensOf(content)
88
+ const B = tokensOf(oldText)
89
+ // 版本号:两侧都有、且各不相同。
90
+ const mineV = only(A.versions, B.versions)
91
+ const theirV = only(B.versions, A.versions)
92
+ if (mineV.length > 0 && theirV.length > 0) return { kind: '版本', mine: mineV, theirs: theirV }
93
+ // 日期:同上。
94
+ const mineD = only(A.dates, B.dates)
95
+ const theirD = only(B.dates, A.dates)
96
+ if (mineD.length > 0 && theirD.length > 0) return { kind: '日期', mine: mineD, theirs: theirD }
97
+ // 状态词反转:一边说做完了、另一边说没做——这是结论互斥,比数字更要紧。
98
+ const a = stateOf(content)
99
+ const b = stateOf(oldText)
100
+ if (a && b && a.side !== b.side) return { kind: '状态', mine: [a.word], theirs: [b.word] }
101
+ // 数值:同一个单位、两侧都有、集合不相交。
102
+ for (const [unit, setA] of A.nums) {
103
+ const setB = B.nums.get(unit)
104
+ if (!setB || setB.size === 0) continue
105
+ const mineN = only(setA, setB)
106
+ const theirN = only(setB, setA)
107
+ if (mineN.length > 0 && theirN.length > 0) {
108
+ return { kind: '数值', unit, mine: mineN.map(String), theirs: theirN.map(String) }
109
+ }
110
+ }
111
+ // 路径:同一个文件名、不同目录(「同一主语换了地方」)。
112
+ for (const [base, setA] of A.bases) {
113
+ const setB = B.bases.get(base)
114
+ if (!setB || setB.size === 0) continue
115
+ const mineP = only(setA, setB)
116
+ const theirP = only(setB, setA)
117
+ if (mineP.length > 0 && theirP.length > 0) return { kind: '路径', mine: [...mineP], theirs: [...theirP] }
118
+ }
119
+ return null
120
+ }
121
+
122
+ export function supersedeMode(config = {}) {
123
+ const raw = config?.autoSupersede
124
+ // 与 consolidateMode 同一条纪律:没配就是默认那一档(suggest);显式写错退到 off(不动库最安全)。
125
+ if (raw === undefined || raw === null) return 'suggest'
126
+ const mode = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
127
+ return mode === 'off' || mode === 'suggest' || mode === 'apply' ? mode : 'off'
128
+ }
129
+
130
+ export function conflictCandidatesOf({ hits = [], content = '', newId = '', skipIds = [], max = SUPERSEDE_MAX } = {}) {
131
+ const skip = new Set([newId, ...skipIds].filter((one) => typeof one === 'string' && one !== ''))
132
+ const out = []
133
+ for (const h of hits) {
134
+ if (!h || typeof h.id !== 'string' || h.id === '') continue
135
+ // 人已经点名要取代的那几条不重复建议——短 id 与完整 id 两种写法都认。
136
+ if (skip.has(h.id) || skip.has(h.id.slice(0, 8))) continue
137
+ const sim = Number(h.similarity ?? h.sim ?? NaN)
138
+ if (!Number.isFinite(sim) || sim < SUPERSEDE_SIM) continue
139
+ const rep = Number(h.repeat ?? NaN)
140
+ const c = conflictOf(content, String(h.content ?? ''))
141
+ if (!c) continue
142
+ // 数值与路径两类天生容易撞(「3 条」「tools/x.mjs」满库都是),要求两条本来就是同一句话的改写。
143
+ if ((c.kind === '数值' || c.kind === '路径') && !(Number.isFinite(rep) && rep >= SUPERSEDE_REPEAT)) continue
144
+ out.push({
145
+ id: h.id,
146
+ id8: h.id.slice(0, 8),
147
+ level: String(h.level ?? ''),
148
+ sim: Math.round(sim * 1e3) / 1e3,
149
+ repeat: Number.isFinite(rep) ? Math.round(rep * 1e3) / 1e3 : null,
150
+ kind: c.kind,
151
+ mine: c.mine,
152
+ theirs: c.theirs,
153
+ })
154
+ }
155
+ out.sort((a, b) => b.sim - a.sim)
156
+ return out.slice(0, max)
157
+ }
158
+
159
+ function oneLine(c) {
160
+ const mine = c.mine.join('/')
161
+ const theirs = c.theirs.join('/')
162
+ const unit = c.unit ? `${c.unit} ` : ''
163
+ const where = c.level ? `${c.level} ` : ''
164
+ return `- ${where}${c.id8}(${c.kind}):它写 ${unit}${theirs},你这次写 ${unit}${mine}`
165
+ }
166
+
167
+ export function supersedeSuggestNote(cands = []) {
168
+ if (cands.length === 0) return ''
169
+ const lines = [
170
+ `⚠️ 这几条像是同一件事的旧说法(autoSupersede: suggest——只建议,一个字没动库):`,
171
+ ...cands.map(oneLine),
172
+ `确认要被取代就重写一次带 supersedes: [${cands.map((c) => `'${c.id8}'`).join(', ')}](旧条会标 stale 并留一句「已被取代」,不删除);若说的是不同对象,忽略这段。`,
173
+ ]
174
+ return lines.join('\n')
175
+ }
176
+
177
+ // apply 态:真正动库前先说清「要动谁、为什么」,动完由调用方把 markSuperseded 的结果接在后面。
178
+ export function supersedeApplyLead(cands = []) {
179
+ if (cands.length === 0) return ''
180
+ return [
181
+ `自动取代(autoSupersede: apply):${cands.length} 条旧说法要被降格(不删除,可 memory_update(status:'active') 反悔)`,
182
+ ...cands.map(oneLine),
183
+ ].join('\n')
184
+ }
185
+
186
+ // 打一枪同层近邻检索(internal: true:这是我自己判「要不要取代」用的,不替用户记账、不抬召回次数)。
187
+ export async function supersedeAdvice({ flow, exec, content = '', project = '', level = '', keywords = [], newId = '', skipIds = [] } = {}) {
188
+ const words = [...new Set((Array.isArray(keywords) ? keywords : []).map((k) => String(k).trim()).filter(Boolean))]
189
+ const query = words.length > 0 ? words.join(' ') : String(content).slice(0, 60).trim()
190
+ if (query === '') return []
191
+ const base = { query, level: level || 'fact', k: SUPERSEDE_ROWS, status: 'active', content_max: 0, internal: true }
192
+ const proj = typeof project === 'string' ? project.trim() : ''
193
+ if (proj !== '') base.project = proj
194
+ const got = await flow.tryCall('memory_search', base, exec, '取代检查:同层近邻')
195
+ const hits = Array.isArray(got?.value?.hits) ? got.value.hits : []
196
+ return conflictCandidatesOf({ hits, content, newId, skipIds })
197
+ }
@@ -25,9 +25,9 @@ export function createUnifiedTools({ bridge, config = {}, meowDir }) {
25
25
  const flow = createLinkFlow({ bridge, config })
26
26
 
27
27
  return [
28
- createRemember({ flow }),
28
+ createRemember({ flow, config }),
29
29
  createUpdate({ flow, meowDir }),
30
- createSearch({ flow }),
30
+ createSearch({ flow, config }),
31
31
  createRead({ flow, meowDir }),
32
32
  createProject({ flow }),
33
33
  createLink({ flow }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-macro-memory",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "private": false,
5
5
  "description": "宏观记忆调控插件:以 meow-memory 的记忆库为主库、dsh-memory-nebula 的星图为索引,融合成一套 8 个 memory_* 统一工具 + 一段最小注入;两个原插件退化为引擎,工具面与注入面由本插件统一接管并互相联动。",
6
6
  "type": "module",
@@ -8,16 +8,16 @@
8
8
  "name": "meow-memory",
9
9
  "version": "0.32.8",
10
10
  "files": 44,
11
- "bytes": 1985163,
12
- "sha256": "c822a00e87ac34acf69b0b16828632ed1716eb3156fd496180aee1608001f88c"
11
+ "bytes": 1997459,
12
+ "sha256": "e4770b3c73ca9e81cc82e774edfeee503fac782fdfe66ea74e9d60eca7a35d37"
13
13
  },
14
14
  {
15
15
  "dir": "vendor/dsh-memory-nebula",
16
16
  "name": "dsh-memory-nebula",
17
17
  "version": "1.11.74",
18
- "files": 51,
19
- "bytes": 1020104,
20
- "sha256": "f7f00d07e295e0c272c694206d26ca9cfa0cb7d2c758c895b80c455812fa6642"
18
+ "files": 52,
19
+ "bytes": 1043811,
20
+ "sha256": "f44782b18b7a742c453f20d560a81dbebe8b8055fee06ef30cffd7592b5144c0"
21
21
  }
22
22
  ]
23
23
  }
@@ -1,4 +1,4 @@
1
- /**
1
+ /**
2
2
  * 适配器:meow-memory
3
3
  *
4
4
  * 数据面:每个工作区目录下的 `.dsh-meow/memory.db`(SQLite,7 张层表)
@@ -245,6 +245,9 @@ export function* scanSteps(store) {
245
245
  keywords,
246
246
  sessionId: String(row.source_session ?? ''),
247
247
  hits: Number(row.hit_count) || 0,
248
+ // [macro-fusion 0.4.0] 真被 memory_read 打开过几次(老库没这列 → 0)。
249
+ // 体检的 unused 判的是「召回过但没人读」,所以这两个数必须分开传上来。
250
+ reads: cols.has('read_count') ? Number(row.read_count) || 0 : 0,
248
251
  createdAt: toMs(row.created_at),
249
252
  updatedAt: toMs(row.updated_at),
250
253
  accessedAt: toMs(row.last_accessed_at),
@@ -0,0 +1,230 @@
1
+ /**
2
+ * 实体层(P4):把「同一件事的锚点」从记忆里单独抽出来,供星图按实体找。
3
+ *
4
+ * [macro-fusion 0.4.0] 这一段是我们加的,不在上游 dsh-memory-nebula 里;
5
+ * 上游升级会整文件覆盖,冲掉之后召回不会报错、只会静默退回「只按词面找邻居」。
6
+ *
7
+ * 为什么单独成层,而不是把实体做成节点:
8
+ * - `nodes` 是「记忆」的口径:度数、聚类、orphans、面板条数、召回结果位全按它算。
9
+ * 混进实体节点,`1804 条记忆` 会变成 `2200 条`,召回还得处处过滤——等于给每次读数
10
+ * 加一个「这算不算记忆」的判断题。
11
+ * - 回滚只要一条配置:读层关掉,图里就当它不存在,一条记忆都不用重写、不用重建。
12
+ *
13
+ * 只收四类(都是硬事实,不是语义猜测):
14
+ * - `project`:记忆自带的 `project` 字段(人写的,最可信)
15
+ * - `path`:`D:\x\y.js` / `lib/macro/defs/search.js:67` 这种带行号的文件路径
16
+ * - `tool`:`memory_search` / `nebula_recall` 这类工具名
17
+ * - `version`:`0.4.0` 这种三段版本号
18
+ *
19
+ * 刻意不收:人名、机构名、普通名词。那些要靠分词与统计,抽错一次就把两条无关记忆连上,
20
+ * 而星图的错边比缺边贵得多——缺边只是少一条路,错边会让「关于 X 的一切」混进别的东西。
21
+ */
22
+
23
+ /** 只有被 ≥2 条记忆共享的实体才进层:只出现一次的「实体」是索引噪声,只涨体积。 */
24
+ export const ENTITY_MIN_MEMBERS = 2
25
+ /** 层的上限:再多就不叫「锚点」了。按成员数排前 400 个。 */
26
+ export const ENTITY_MAX = 400
27
+ /** 实体当种子时的能量:低于文本种子(1.0),高于「弱关联」(0.2 以下会被当噪声)。 */
28
+ export const ENTITY_SEED = 0.6
29
+ /** 一条记忆最多贡献几个实体当种子(防「一条水词很多的记忆」把半个图点亮)。 */
30
+ export const ENTITY_PER_NODE = 6
31
+ /** 实体名短于这个长度不参与「查询里含实体名」的包含匹配(`0.4` 这种太短)。 */
32
+ export const ENTITY_MIN_LABEL = 4
33
+
34
+ /** 实体层收的类型(与 text.js 的 `type|value` 键前缀对齐)。 */
35
+ export const ENTITY_KINDS = new Set(['project', 'path', 'tool', 'version'])
36
+
37
+ /**
38
+ * 带盘符或 ≥2 段斜杠的文件路径,末尾可带 `:行号`。
39
+ * 例:`d:\a\b\c.js`、`lib/macro/defs/search.js:67`、`./docs/PLAN-0.4.md`
40
+ */
41
+ const PATH_RE = /(?:[a-z]:[\\/]|\.{1,2}[\\/]|(?:^|[\s((`'"[{])[\w@.-]+[\\/])[\w@.\\/-]{2,}\.(?:js|mjs|cjs|ts|tsx|jsx|json|jsonc|md|mdx|py|rs|go|java|kt|cs|cpp|cc|h|hpp|sql|yml|yaml|toml|ini|cfg|sh|ps1|bat|cmd|html|css|db|sqlite|log)(?::\d{1,5})?/g
42
+
43
+ /** 工具名:`memory_*` / `nebula_*` 这类下划线命名的专名。 */
44
+ const TOOL_RE = /\b(?:memory|nebula|macro|dsh)_[a-z][a-z0-9_]{2,28}\b/g
45
+
46
+ /** 版本号:三段或四段,`v` 前缀可有。 */
47
+ const VERSION_RE = /\bv?\d+\.\d+\.\d+(?:-[0-9a-z.]{1,12})?\b/g
48
+
49
+ /** 尾巴上的标点剪掉(路径后面常跟着逗号、右括号)。 */
50
+ function trimTail(s) {
51
+ let end = s.length
52
+ while (end > 0) {
53
+ const c = s.charCodeAt(end - 1)
54
+ if (c === 44 || c === 46 || c === 59 || c === 58 || c === 41 || c === 93 || c === 125 || c === 34 || c === 39 || c === 96 || c === 92) end--
55
+ else break
56
+ }
57
+ return end === s.length ? s : s.slice(0, end)
58
+ }
59
+
60
+ /**
61
+ * 从一条记忆里抽四类实体。
62
+ * @param {object} node buildGraph 产出的节点(有 `blob` 小写全文与 `project` 字段)
63
+ * @returns {Map<string,string>} `type|value` -> type
64
+ */
65
+ export function entitiesOfNode(node) {
66
+ const out = new Map()
67
+ const put = (type, raw) => {
68
+ const v = trimTail(String(raw || '').trim().toLowerCase())
69
+ if (v.length < ENTITY_MIN_LABEL) return
70
+ if (type === 'version' && !/^\d+\.\d+\.\d+/.test(v.replace(/^v/, ''))) return
71
+ out.set(type + '|' + v, type)
72
+ }
73
+ const project = typeof node?.project === 'string' ? node.project.trim() : ''
74
+ if (project) put('project', project)
75
+ const blob = typeof node?.blob === 'string' ? node.blob : ''
76
+ if (blob) {
77
+ for (const m of blob.matchAll(PATH_RE)) put('path', m[0])
78
+ for (const m of blob.matchAll(TOOL_RE)) put('tool', m[0])
79
+ for (const m of blob.matchAll(VERSION_RE)) put('version', m[0])
80
+ }
81
+ return out
82
+ }
83
+
84
+ /**
85
+ * 建整层:哪些实体被哪几条记忆提到。
86
+ *
87
+ * @param {object[]} nodes buildGraph 的节点(已带 `i` 下标与 `blob`)
88
+ * @param {{minMembers?:number,max?:number}} [opts]
89
+ * @returns {{list:object[],byKey:Map<string,object>,byNode:Map<number,string[]>,stats:object}}
90
+ */
91
+ export function collectEntities(nodes, opts = {}) {
92
+ const minMembers = opts.minMembers ?? ENTITY_MIN_MEMBERS
93
+ const max = opts.max ?? ENTITY_MAX
94
+ /** @type {Map<string,{key:string,type:string,label:string,members:number[]}>} */
95
+ const byKey = new Map()
96
+ /** @type {Map<number,string[]>} */
97
+ const byNode = new Map()
98
+
99
+ for (const node of nodes || []) {
100
+ if (!node || typeof node.i !== 'number') continue
101
+ const ents = entitiesOfNode(node)
102
+ const mine = []
103
+ for (const [key, type] of ents) {
104
+ const cut = key.indexOf('|')
105
+ const label = cut < 0 ? key : key.slice(cut + 1)
106
+ let rec = byKey.get(key)
107
+ if (!rec) {
108
+ rec = { key, type, label, members: [] }
109
+ byKey.set(key, rec)
110
+ }
111
+ rec.members.push(node.i)
112
+ mine.push(key)
113
+ }
114
+ if (mine.length) byNode.set(node.i, mine)
115
+ }
116
+
117
+ // 成员数不够的整条丢掉(只在一条记忆里出现 = 索引噪声)
118
+ const list = [...byKey.values()].filter((e) => e.members.length >= minMembers)
119
+ list.sort((a, b) => b.members.length - a.members.length || a.label.localeCompare(b.label))
120
+ const kept = list.slice(0, max)
121
+ const keepKeys = new Set(kept.map((e) => e.key))
122
+ const byKeyKept = new Map(kept.map((e) => [e.key, e]))
123
+
124
+ // byNode 也收紧到留下的实体;并且每条记忆最多 ENTITY_PER_NODE 个(按实体成员数降序)
125
+ /** @type {Map<number,string[]>} */
126
+ const byNodeKept = new Map()
127
+ for (const [i, keys] of byNode) {
128
+ const alive = keys.filter((k) => keepKeys.has(k))
129
+ if (!alive.length) continue
130
+ alive.sort((a, b) => (byKeyKept.get(b)?.members.length || 0) - (byKeyKept.get(a)?.members.length || 0))
131
+ byNodeKept.set(i, alive.slice(0, ENTITY_PER_NODE))
132
+ }
133
+
134
+ const byType = {}
135
+ for (const e of kept) byType[e.type] = (byType[e.type] || 0) + 1
136
+
137
+ return {
138
+ list: kept,
139
+ byKey: byKeyKept,
140
+ byNode: byNodeKept,
141
+ stats: {
142
+ entities: kept.length,
143
+ dropped: byKey.size - kept.length,
144
+ byType,
145
+ mentioned: byNodeKept.size,
146
+ },
147
+ }
148
+ }
149
+
150
+ /**
151
+ * 从 `list` 重建索引(`byKey` / `byNode`)。
152
+ *
153
+ * 为什么要这一步:图的缓存是 JSON——Map 存不住,落盘再读回来只剩 `list`。
154
+ * 400 个实体的索引重建是微秒级,比给缓存加一套 Map 序列化协议便宜得多,
155
+ * 也让「盘上读回来的图」与「刚建好的图」走同一条代码。
156
+ */
157
+ export function indexOf(layer) {
158
+ const byKey = new Map()
159
+ const byNode = new Map()
160
+ for (const e of layer?.list || []) {
161
+ byKey.set(e.key, e)
162
+ for (const i of e.members || []) {
163
+ const arr = byNode.get(i)
164
+ if (arr) arr.push(e.key)
165
+ else byNode.set(i, [e.key])
166
+ }
167
+ }
168
+ return { byKey, byNode }
169
+ }
170
+
171
+ /** 拿到可用的索引:已在就用,缺了现建。 */
172
+ export function ensureLayer(layer) {
173
+ if (!layer || !Array.isArray(layer.list)) return null
174
+ if (layer.byKey instanceof Map) return layer
175
+ return { ...layer, ...indexOf(layer) }
176
+ }
177
+
178
+ /**
179
+ * 查询里出现了哪些实体名?命中的实体把成员节点全带上。
180
+ *
181
+ * 匹配规则故意保守:要求「查询里包含完整的实体名」(label 在 query 里,且 label ≥ 4 字)。
182
+ * 反向包含(query 在 label 里)只在 query ≥ 3 字时允许——否则问「星图」会把
183
+ * `nebula_recall` 之类的长实体全拉进来,把一次精确提问变成一次泛泛扩散。
184
+ *
185
+ * @param {string} query
186
+ * @param {object} layer collectEntities 的产物
187
+ * @param {{limit?:number}} [opts]
188
+ * @returns {{i:number,key:string,label:string,type:string,members:number,weight:number}[]}
189
+ */
190
+ export function entitySeedsOf(query, layer, opts = {}) {
191
+ const q = String(query || '').trim().toLowerCase()
192
+ const ready = ensureLayer(layer)
193
+ if (!q || !ready || ready.list.length === 0) return []
194
+ const limit = Math.max(1, Math.min(20, opts.limit ?? 8))
195
+ const out = []
196
+ for (const e of ready.list) {
197
+ const label = e.label
198
+ if (label.length < ENTITY_MIN_LABEL) continue
199
+ const forward = q.includes(label)
200
+ const backward = !forward && q.length >= 3 && label.includes(q)
201
+ if (!forward && !backward) continue
202
+ // 正向命中(查询里点名了这个实体)比反向(只沾到一段)可信
203
+ const weight = forward ? 1 : 0.6
204
+ out.push({ i: -1, key: e.key, label, type: e.type, members: e.members.length, weight })
205
+ }
206
+ out.sort((a, b) => b.weight - a.weight || b.members - a.members)
207
+ return out.slice(0, limit)
208
+ }
209
+
210
+ /**
211
+ * 让实体种子落到具体节点上(查询命中的实体 → 它的成员)。
212
+ * @param {object[]} hits entitySeedsOf 的结果
213
+ * @param {object} layer
214
+ * @returns {{i:number,key:string,label:string,energy:number}[]}
215
+ */
216
+ export function entitySeedNodes(hits, layer) {
217
+ const ready = ensureLayer(layer)
218
+ const out = []
219
+ const seen = new Set()
220
+ for (const hit of hits || []) {
221
+ const rec = ready?.byKey?.get(hit.key)
222
+ if (!rec) continue
223
+ for (const i of rec.members) {
224
+ if (seen.has(i)) continue
225
+ seen.add(i)
226
+ out.push({ i, key: hit.key, label: rec.label, energy: ENTITY_SEED * (hit.weight || 1) })
227
+ }
228
+ }
229
+ return out
230
+ }
@@ -22,6 +22,9 @@ import {
22
22
  cut,
23
23
  hash32,
24
24
  } from './text.js'
25
+ // [macro-fusion 0.4.0 · P4] 实体层单独一个文件:它只读节点、只产一份可序列化的 list,
26
+ // 与建边逻辑没有任何耦合。关掉它只需 `entityLayer: false`,图里就当没这回事。
27
+ import { collectEntities } from './entities.js'
25
28
 
26
29
  /**
27
30
  * 通用文件名:跨工作区时不作为「同一实体」的证据。
@@ -242,7 +245,8 @@ export function* buildGraphSteps(input) {
242
245
  nodes: [],
243
246
  edges: [],
244
247
  clusters: [],
245
- stats: { nodes: 0, edges: 0, workspaces: 0, byType: {}, byWorkspace: {}, byLevel: {}, orphans: 0 },
248
+ stats: { nodes: 0, edges: 0, workspaces: 0, byType: {}, byWorkspace: {}, byLevel: {}, orphans: 0, entities: 0 },
249
+ entityLayer: null,
246
250
  builtAt: now,
247
251
  }
248
252
  }
@@ -1162,10 +1166,22 @@ export function* buildGraphSteps(input) {
1162
1166
  yield 'output'
1163
1167
  }
1164
1168
 
1169
+ // [macro-fusion 0.4.0 · P4] 实体层:从「同一项目/路径/工具/版本」这四类硬事实里
1170
+ // 抽出锚点,供召回按实体找「关于 X 的一切」。它不进 nodes、不进 edges:
1171
+ // 度数、聚类、孤岛、面板条数全按「记忆」算,混进实体节点会把这些读数一起改写。
1172
+ // 只留可序列化的 `list`:图的缓存是 JSON,Map 存不住,读回来用 indexOf() 现建索引。
1173
+ const entityLayer = input.entityLayer === false
1174
+ ? null
1175
+ : (() => {
1176
+ const layer = collectEntities(nodes, { minMembers: input.entityMinMembers })
1177
+ return layer.list.length ? { list: layer.list, stats: layer.stats } : null
1178
+ })()
1179
+
1165
1180
  return {
1166
1181
  nodes: outNodes,
1167
1182
  edges: outEdges,
1168
1183
  clusters: clusters.slice(0, 60),
1184
+ entityLayer,
1169
1185
  stats: {
1170
1186
  nodes: nodes.length,
1171
1187
  edges: finalEdges.length,
@@ -1176,6 +1192,8 @@ export function* buildGraphSteps(input) {
1176
1192
  byLevel,
1177
1193
  orphans,
1178
1194
  avgDegree: Math.round((finalEdges.length * 2 * 100) / Math.max(1, nodes.length)) / 100,
1195
+ // 实体数单独报:想知道「这一层到底抽出了多少东西」,不用再翻列表
1196
+ entities: entityLayer ? entityLayer.list.length : 0,
1179
1197
  },
1180
1198
  builtAt: now,
1181
1199
  }
@@ -1211,6 +1229,20 @@ export const HYGIENE_META = {
1211
1229
  unread: { label: '没人读过', hint: '写下一周以上、一次都没被检索命中过' },
1212
1230
  thin: { label: '关系是凑的', hint: '边很多,但没有一条强关系(实体/项目级),全是关键词撞出来的' },
1213
1231
  orphan: { label: '孤立', hint: '一条边都没有:要么是独特知识,要么是没人会再想起的碎片' },
1232
+ // [macro-fusion 0.4.0] 写入端通胀三连:这三条看的不是「记忆写错了」,而是
1233
+ // 「检索与写入被同一批词反复喂」——写入方(包括我自己)会针对召回机制优化自己。
1234
+ selfecho: {
1235
+ label: '关键词自证',
1236
+ hint: 'keywords 里超过七成逐字出现在正文里:这些词靠 BM25 本来就能命中,堆上去等于没扩召回面(自证,不是扩展)',
1237
+ },
1238
+ unused: {
1239
+ label: '召回过没人读',
1240
+ hint: '被检索命中过、却一次都没被 memory_read 打开过:排进了候选,但没人真去读。注意记账从 0.4.0 起,更早的读没有被记(老库这一格会偏大)',
1241
+ },
1242
+ inflate: {
1243
+ label: '写得多收得少',
1244
+ hint: '近 30 天 fact 层条数增速是结论层(rules / lesson)的 3 倍以上:原子事实在堆,没人把它收成结论',
1245
+ },
1214
1246
  }
1215
1247
 
1216
1248
  const HY_MAX = 40
@@ -1637,7 +1669,71 @@ export function* auditHygieneSteps({ nodes, edges, nodeIds = null, tokensById =
1637
1669
  sim: Number(p.j.toFixed(3)),
1638
1670
  }))
1639
1671
 
1640
- const items = { dup, oversize, stale, unread, thin, orphan }
1672
+ // [macro-fusion 0.4.0] 写入端通胀三连(P2.5)。这三条不是「记忆写错了」,
1673
+ // 而是「检索与写入被同一批词反复喂」——写入方(包括 AI 自己)会针对召回机制优化自己:
1674
+ // 关键词挑能命中自己的词、正文写成关键词的复读、事实一条条堆而结论不增。
1675
+ mark('inflate')
1676
+ const SELF_ECHO_MIN_KW = 3
1677
+ const SELF_ECHO_RATE = 0.7
1678
+ const selfechoAll = []
1679
+ for (const n of memories) {
1680
+ const kws = kwOf(n)
1681
+ // 只有 1–2 个关键词的条目,1/2 = 50% 也能算「高」——样本太小的比例不是信号。
1682
+ if (kws.length < SELF_ECHO_MIN_KW) continue
1683
+ const body = String(n.content || '').toLowerCase()
1684
+ if (!body) continue
1685
+ let echo = 0
1686
+ for (const k of kws) if (k && body.includes(k)) echo++
1687
+ const rate = echo / kws.length
1688
+ if (rate <= SELF_ECHO_RATE) continue
1689
+ selfechoAll.push({ id: n.id, label: n.label, ws: n.wsTitle, level: n.level, rate: Number(rate.toFixed(2)), echo, kws: kws.length })
1690
+ }
1691
+ // 自证率高的先吵:1.00 才是「关键词全是正文的复读机」,0.75 只是偏。
1692
+ selfechoAll.sort((a, b) => b.rate - a.rate || b.kws - a.kws)
1693
+ const selfechoTotal = selfechoAll.length
1694
+ const selfecho = selfechoAll.slice(0, HY_MAX)
1695
+
1696
+ // 「召回过没人读」:命中过(排进过候选)却一次都没被 memory_read 打开。
1697
+ // 只对真记了 read_count 的源成立(meow 从 0.4.0 起);别的适配器没这个数就不参与,
1698
+ // 否则 hits 一有就全部假阳。老库这一格偏大是必然的——以前的读没被记过。
1699
+ const unusedAll = memories
1700
+ .filter((n) => typeof n.reads === 'number' && n.status === 'active' && (n.hits || 0) > 0 && !n.reads)
1701
+ .sort((a, b) => (b.hits || 0) - (a.hits || 0))
1702
+ const unusedTotal = unusedAll.length
1703
+ const unused = unusedAll
1704
+ .slice(0, HY_MAX)
1705
+ .map((n) => ({ id: n.id, label: n.label, ws: n.wsTitle, level: n.level, hits: n.hits || 0 }))
1706
+
1707
+ // 层通胀:近 30 天 fact 条数 vs 结论层(rules / lesson)。看增速比值、不看绝对量,
1708
+ // 所以要有最小样本——新库里 fact 3 条、结论层 0 条也是「无限倍」,那不是病。
1709
+ const INFLATE_DAYS = 30
1710
+ const INFLATE_RATIO = 3
1711
+ const INFLATE_MIN = 6
1712
+ const inflateSince = now - INFLATE_DAYS * DAY
1713
+ let factNew = 0
1714
+ let semNew = 0
1715
+ for (const n of memories) {
1716
+ if ((n.createdAt || 0) < inflateSince) continue
1717
+ if (n.level === 'fact') factNew++
1718
+ else if (n.level === 'rules' || n.level === 'lesson') semNew++
1719
+ }
1720
+ const inflateX = semNew > 0 ? factNew / semNew : factNew
1721
+ const inflateTotal = factNew >= INFLATE_MIN && factNew > semNew * INFLATE_RATIO ? 1 : 0
1722
+ // 这一类是「整库一个判断」,不是逐条清单:命中就给一行汇总,id 留空(面板别当记忆跳)。
1723
+ const inflate = inflateTotal
1724
+ ? [
1725
+ {
1726
+ id: '',
1727
+ label: `近 ${INFLATE_DAYS} 天:fact ${factNew} 条 / 结论层 ${semNew} 条(${Number(inflateX.toFixed(1))}×)`,
1728
+ ws: '',
1729
+ level: 'fact',
1730
+ fact: factNew,
1731
+ semantic: semNew,
1732
+ },
1733
+ ]
1734
+ : []
1735
+
1736
+ const items = { dup, oversize, stale, unread, thin, orphan, selfecho, unused, inflate }
1641
1737
  // 计数用「全部命中」,列表只留前 HY_MAX 条:payload 有上限,数字不失真。
1642
1738
  const full = {
1643
1739
  dup: dupPairs.length,
@@ -1646,6 +1742,9 @@ export function* auditHygieneSteps({ nodes, edges, nodeIds = null, tokensById =
1646
1742
  unread: unreadAll.length,
1647
1743
  thin: thinTotal,
1648
1744
  orphan: orphanAll.length,
1745
+ selfecho: selfechoTotal,
1746
+ unused: unusedTotal,
1747
+ inflate: inflateTotal,
1649
1748
  }
1650
1749
  const counts = {}
1651
1750
  const shown = {}
@@ -30,7 +30,10 @@ const KEEP = 3 // 盘上最多留几份;旧的多半只是「万一要回滚
30
30
  // 为什么要有它:缓存只看来源签名(库的大小与时间戳)。来源没变、插件升了级、
31
31
  // 边算法改了 —— 签名一模一样,盘上那份旧图会被一直当成正确答案,
32
32
  // 用户永远看不到新算法算出来的关联。代价是一行 sha1,一次进程只算一次。
33
- const IMPL_FILES = ['graph.js', 'text.js']
33
+ // [macro-fusion 0.4.0 · P4] `entities.js` 也是「输出会变的源码」:实体层的抽取规则改了,
34
+ // 图里的 entityLayer 就该跟着变。只认 graph.js 的话,改抽取规则不会让缓存失效,
35
+ // 盘上那份旧实体层会被一直当成新答案读出来。
36
+ const IMPL_FILES = ['graph.js', 'text.js', 'entities.js']
34
37
  let implMemo = ''
35
38
 
36
39
  export function implFingerprint() {
@@ -217,6 +220,11 @@ export async function saveGraphCache(dir, signature, { nodes, ledgers, graph, im
217
220
  nodes: graph.nodes,
218
221
  edges: graph.edges,
219
222
  stats: graph.stats,
223
+ // [macro-fusion 0.4.0 · P4] 实体层也要落盘:它在 buildGraph 里只是一份
224
+ // `{list:[{key,type,label,members}]}`(没有 Map),天生可序列化。
225
+ // 不存的话,重启读盘之后图还在、实体却悄悄消失——召回会静默退回 0.4.0 之前的行为,
226
+ // 而且这种退化没有任何报错,最难发现。
227
+ entityLayer: graph.entityLayer || null,
220
228
  builtAt: graph.builtAt,
221
229
  muteCount: graph.muteCount || 0,
222
230
  // 簇(工作区围成的团)也要一起存:读盘恢复端出的是「上次建图那一刻」的图,