macro-memory 0.0.0-stage → 0.9.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.
Files changed (200) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +386 -2
  3. package/bin/macro-memory.mjs +735 -0
  4. package/docs/CHANGELOG.md +268 -0
  5. package/docs/MAC.md +156 -0
  6. package/docs/images/_architecture.svg +70 -0
  7. package/docs/images/_memory-flow.svg +75 -0
  8. package/docs/images/_token-budget.svg +40 -0
  9. package/docs/images/architecture.png +0 -0
  10. package/docs/images/hero.png +0 -0
  11. package/docs/images/memory-flow.png +0 -0
  12. package/docs/images/src/graph.html +78 -0
  13. package/docs/images/src/hero.html +88 -0
  14. package/docs/images/src/panel.html +63 -0
  15. package/docs/images/src/pipeline.html +97 -0
  16. package/docs/images/token-budget.png +0 -0
  17. package/lib/client.js +3811 -0
  18. package/lib/core/agents-file.js +95 -0
  19. package/lib/core/client.js +313 -0
  20. package/lib/core/compat/dsh-llm.js +78 -0
  21. package/lib/core/config.js +117 -0
  22. package/lib/core/engine.js +456 -0
  23. package/lib/core/fence.js +109 -0
  24. package/lib/core/index.js +102 -0
  25. package/lib/core/migrate.js +70 -0
  26. package/lib/core/mini-host.js +324 -0
  27. package/lib/core/owner.js +347 -0
  28. package/lib/core/paths.js +95 -0
  29. package/lib/core/serve.js +378 -0
  30. package/lib/core/trust.js +173 -0
  31. package/lib/index.js +567 -0
  32. package/lib/macro/brand.js +82 -0
  33. package/lib/macro/bridge.js +158 -0
  34. package/lib/macro/chain.js +206 -0
  35. package/lib/macro/contract.js +471 -0
  36. package/lib/macro/cost.js +164 -0
  37. package/lib/macro/defs/admin.js +528 -0
  38. package/lib/macro/defs/dream.js +24 -0
  39. package/lib/macro/defs/link.js +408 -0
  40. package/lib/macro/defs/project.js +237 -0
  41. package/lib/macro/defs/read.js +160 -0
  42. package/lib/macro/defs/remember.js +411 -0
  43. package/lib/macro/defs/search.js +899 -0
  44. package/lib/macro/defs/update.js +161 -0
  45. package/lib/macro/dreamledger.js +1398 -0
  46. package/lib/macro/facade.js +135 -0
  47. package/lib/macro/fusion.js +188 -0
  48. package/lib/macro/injectledger.js +843 -0
  49. package/lib/macro/linkflow.js +391 -0
  50. package/lib/macro/links.js +448 -0
  51. package/lib/macro/neighbor.js +1083 -0
  52. package/lib/macro/panel.js +96 -0
  53. package/lib/macro/platform.js +134 -0
  54. package/lib/macro/prompt.js +139 -0
  55. package/lib/macro/provenance.js +148 -0
  56. package/lib/macro/render.js +35 -0
  57. package/lib/macro/revisions.js +253 -0
  58. package/lib/macro/shared.js +113 -0
  59. package/lib/macro/shortid.js +114 -0
  60. package/lib/macro/snapshot.js +700 -0
  61. package/lib/macro/spend.js +312 -0
  62. package/lib/macro/store.js +238 -0
  63. package/lib/macro/supersede.js +197 -0
  64. package/lib/macro/tokencost.js +90 -0
  65. package/lib/macro/tools.js +67 -0
  66. package/lib/mcp/server.js +201 -0
  67. package/lib/mcp/stdio.js +151 -0
  68. package/lib/ui/page.js +300 -0
  69. package/lib/ui/server.js +226 -0
  70. package/package.json +56 -4
  71. package/vendor/VENDOR.json +39 -0
  72. package/vendor/cosmokit/LICENSE +21 -0
  73. package/vendor/cosmokit/README.md +30 -0
  74. package/vendor/cosmokit/lib/index.js +418 -0
  75. package/vendor/cosmokit/lib/types/array.d.ts +15 -0
  76. package/vendor/cosmokit/lib/types/array.d.ts.map +1 -0
  77. package/vendor/cosmokit/lib/types/index.d.ts +13 -0
  78. package/vendor/cosmokit/lib/types/index.d.ts.map +1 -0
  79. package/vendor/cosmokit/lib/types/misc.d.ts +41 -0
  80. package/vendor/cosmokit/lib/types/misc.d.ts.map +1 -0
  81. package/vendor/cosmokit/lib/types/string.d.ts +89 -0
  82. package/vendor/cosmokit/lib/types/string.d.ts.map +1 -0
  83. package/vendor/cosmokit/lib/types/time.d.ts +19 -0
  84. package/vendor/cosmokit/lib/types/time.d.ts.map +1 -0
  85. package/vendor/cosmokit/lib/types/types.d.ts +42 -0
  86. package/vendor/cosmokit/lib/types/types.d.ts.map +1 -0
  87. package/vendor/cosmokit/lib/types/volatile.d.ts +40 -0
  88. package/vendor/cosmokit/lib/types/volatile.d.ts.map +1 -0
  89. package/vendor/cosmokit/package.json +32 -0
  90. package/vendor/cosmokit/src/array.ts +42 -0
  91. package/vendor/cosmokit/src/index.ts +12 -0
  92. package/vendor/cosmokit/src/misc.ts +78 -0
  93. package/vendor/cosmokit/src/string.ts +113 -0
  94. package/vendor/cosmokit/src/time.ts +92 -0
  95. package/vendor/cosmokit/src/types.ts +168 -0
  96. package/vendor/cosmokit/src/volatile.ts +86 -0
  97. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  98. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  99. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  100. package/vendor/dsh-memory-nebula/README.md +253 -0
  101. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  102. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  103. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  104. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  105. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  106. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  107. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  108. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  109. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  110. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  111. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  112. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  113. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  114. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  115. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  116. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  117. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  118. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  119. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  120. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  121. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  122. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  123. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  124. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  125. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  126. package/vendor/dsh-memory-nebula/lib/host/recall.js +526 -0
  127. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  128. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  129. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  130. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  131. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  132. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  133. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  134. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  135. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  136. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  137. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  138. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  139. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  140. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  141. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  142. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  143. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  144. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  145. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  146. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  147. package/vendor/dsh-memory-nebula/package.json +87 -0
  148. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  149. package/vendor/meow-memory/LICENSE +21 -0
  150. package/vendor/meow-memory/README.en.md +192 -0
  151. package/vendor/meow-memory/README.md +174 -0
  152. package/vendor/meow-memory/README.pt-br.md +180 -0
  153. package/vendor/meow-memory/cordis.patch.yml +7 -0
  154. package/vendor/meow-memory/lib/client.js +3354 -0
  155. package/vendor/meow-memory/lib/client.js.map +7 -0
  156. package/vendor/meow-memory/lib/index.js +13500 -0
  157. package/vendor/meow-memory/lib/index.js.map +7 -0
  158. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  159. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  160. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  161. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  162. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  163. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  164. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  165. package/vendor/meow-memory/lib/prompts/en/labels.md +104 -0
  166. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  167. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  168. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  169. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  170. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  171. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  172. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  173. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  174. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  175. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  176. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +104 -0
  177. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  178. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  179. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  180. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  181. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  182. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  183. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  184. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  185. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  186. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  187. package/vendor/meow-memory/lib/prompts/zh/labels.md +104 -0
  188. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  189. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  190. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  191. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  192. package/vendor/meow-memory/package.json +64 -0
  193. package/vendor/schemastery/LICENSE +21 -0
  194. package/vendor/schemastery/README.md +393 -0
  195. package/vendor/schemastery/lib/index.cjs +635 -0
  196. package/vendor/schemastery/lib/index.mjs +637 -0
  197. package/vendor/schemastery/lib/types/index.d.ts +211 -0
  198. package/vendor/schemastery/lib/types/index.d.ts.map +1 -0
  199. package/vendor/schemastery/package.json +39 -0
  200. package/vendor/schemastery/src/index.ts +962 -0
@@ -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
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * [macro-fusion 0.2.109] 回执成本:省 token 的前提是知道自己花了多少。
3
+ *
4
+ * 为什么单独一格:记忆系统的六个衡量维度里,「效率(检索快、不拖累当前任务)」是唯一没有数的——
5
+ * probe 里有条数、有耗时,没有「这次检索占了多少上下文」。没有这个数,
6
+ * 「多查几次也无所谓」就永远是一句空话,调用方也没法判断「值不值」。
7
+ *
8
+ * 口径三件事:
9
+ * 1. 这是**估算**,不是计量。CJK 一个字按 1 token 算(偏保守:真实分词常见 1 字 0.6~1),
10
+ * 其余按 4 字符 1 token。报出来的用量级够用来决定「要不要收紧、收紧多少」,
11
+ * 不够用来跟账单对账——这句要写在尾注里,不然读者会拿它当账单。
12
+ * 2. 只在回执已经够大时才报(`COST_SHOW_MIN`)。一条 40 token 的成本说明加在 80 token 的回执上,
13
+ * 就是拿 token 换噪音——省 token 的工具自己先要省。
14
+ * 3. 预算(budget)是**约束**,不是愿望:给了就让工具自己收缩并如实交代缩了什么;
15
+ * 装不下就说最小能给多少,绝不假装装下了。
16
+ */
17
+
18
+ /** CJK 统一表意文字 + 日文假名 + 谚文 + 全角标点:这些按「一字一 token」估。 */
19
+ const CJK = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uff00-\uffef]/g
20
+
21
+ /** 回执大到这个量级才值得报成本(token)。低于它的成本说明本身比省下的还贵。 */
22
+ export const COST_SHOW_MIN = 500
23
+
24
+ /** 小到这个量级才建议「只看骨架」。再小就没有可省的了。 */
25
+ export const COST_HINT_MIN = 1200
26
+
27
+ /** 预算下限:比它还小的预算连一条标题都装不下,按不限额处理并说明原因。 */
28
+ export const BUDGET_MIN = 80
29
+
30
+ /** 估算 token 数:CJK 一字算 1,其余 4 字符算 1(向上取整)。空串算 0。 */
31
+ export function estTokens(text) {
32
+ const s = typeof text === 'string' ? text : String(text ?? '')
33
+ if (s.length === 0) return 0
34
+ const cjk = (s.match(CJK) ?? []).length
35
+ return cjk + Math.ceil((s.length - cjk) / 4)
36
+ }
37
+
38
+ /** 报数格式:一千以内给整数,过千给一位小数的 k(`1.2k`),不写成 `1.0k`。 */
39
+ export function fmtTokens(n) {
40
+ const v = Number(n)
41
+ if (!Number.isFinite(v) || v < 0) return '0'
42
+ if (v < 1000) return String(Math.round(v))
43
+ const k = (v / 1000).toFixed(1)
44
+ return `${k.endsWith('.0') ? k.slice(0, -2) : k}k`
45
+ }
46
+
47
+ /**
48
+ * 解析 budget。四种结果要分开,别压成「没给」:
49
+ * - 没给 → `{ value: null, note: '' }`(不限额,也不解释)
50
+ * - 给了但不像数 → 不限额 + 说清「你给的那个没被用上」
51
+ * - 给了但太小 → 不限额 + 说清最小可用值(假装缩到 80 只会给出一条标题,问不出东西)
52
+ * - 给了但太大 → 夹到上界 + 说清「结果是被改过的条件算出来的」
53
+ */
54
+ export function budgetOf(raw, { max = 20000 } = {}) {
55
+ if (raw === undefined || raw === null) return { value: null, note: '' }
56
+ if (typeof raw === 'string' && raw.trim() === '') return { value: null, note: '' }
57
+ const n = Number(raw)
58
+ if (!Number.isFinite(n)) {
59
+ return { value: null, note: `budget 给的是「${String(raw)}」,不是数字——这次按不限额给(回执仍会报成本)。` }
60
+ }
61
+ if (n < BUDGET_MIN) {
62
+ return {
63
+ value: null,
64
+ note: `budget 给的是「${n}」,比最小可用预算 ${BUDGET_MIN} token 还小——这么点连一条标题都装不下,这次按不限额给。`,
65
+ }
66
+ }
67
+ const whole = Math.floor(n)
68
+ if (whole > max) {
69
+ return { value: max, note: `budget 给的是「${whole}」,超出上界 ${max}——这次按 ${max} token 算,不是你给的那个。` }
70
+ }
71
+ return { value: whole, note: '' }
72
+ }
73
+
74
+ /** 成本那句话(不含预算部分):`成本 ≈1.2k token(…)`。 */
75
+ export function costSentence(text) {
76
+ const est = estTokens(text)
77
+ return `成本 ≈${fmtTokens(est)} token(CJK 一字算 1、其余 4 字符算 1,是量级不是账单)`
78
+ }
79
+
80
+ /**
81
+ * 给「读」这类固定形态的回执补成本:够大才说,不够大一个字不加。
82
+ * 阈值放在这里而不是调用处——两处各写一个数,迟早一个来改、一个忘改。
83
+ */
84
+ export function readCostTail(text, { min = COST_SHOW_MIN, hint = COST_HINT_MIN } = {}) {
85
+ const s = String(text ?? '')
86
+ const est = estTokens(s)
87
+ if (est < min) return s
88
+ const hintText = est >= hint ? ';只要骨架就少给几条邻居(neighbors=0 或 3)' : ''
89
+ return `${s}\n\n${costSentence(s)}${hintText}`
90
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * macro-memory 的统一工具面装配器:把 8 个 `defs/*.js` 拼成工具数组。
3
+ *
4
+ * 规矩(DESIGN §7 R2):写路径一律复用子插件自己的工具定义,
5
+ * 这里只做「选哪个子插件工具 + 参数路由 + 结果拼接」,绝不重写记忆逻辑。
6
+ *
7
+ * 0.2.5 起工具定义按「一个工具一个文件」放在 `lib/macro/defs/`,
8
+ * 本文件只剩装配 + 兼容别名;加点工具时改一个文件、在下面 push 一行即可(DESIGN §16)。
9
+ */
10
+ import { TEXT_OUT } from './shared.js'
11
+ import { createLinkFlow } from './linkflow.js'
12
+ import { createRemember } from './defs/remember.js'
13
+ import { createUpdate } from './defs/update.js'
14
+ import { createSearch } from './defs/search.js'
15
+ import { createRead } from './defs/read.js'
16
+ import { createProject } from './defs/project.js'
17
+ import { createLink } from './defs/link.js'
18
+ import { createDream } from './defs/dream.js'
19
+ import { createAdmin } from './defs/admin.js'
20
+
21
+ export { LEVELS, PROJECT_SUBCATEGORIES, neighborSection } from './shared.js'
22
+ export { LINKS_SCHEMA, normalizeLinks } from './linkflow.js'
23
+
24
+ export function createUnifiedTools({ bridge, config = {}, meowDir }) {
25
+ const flow = createLinkFlow({ bridge, config })
26
+
27
+ return [
28
+ createRemember({ flow, config }),
29
+ createUpdate({ flow, meowDir }),
30
+ createSearch({ flow, config, meowDir }),
31
+ createRead({ flow, meowDir }),
32
+ createProject({ flow, config, meowDir }),
33
+ createLink({ flow, meowDir }),
34
+ createDream({ flow }),
35
+ createAdmin({ flow, bridge, config, meowDir }),
36
+ ]
37
+ }
38
+
39
+ /**
40
+ * 兼容别名:把子插件原来的工具原样暴露(默认关)。
41
+ * 只在主人明确要做 A/B 对比或第三方提示词还写着 nebula_* 时才打开。
42
+ */
43
+ export function createAliasTools({ bridge }) {
44
+ const wanted = [
45
+ 'memory_find_similar',
46
+ 'memory_home',
47
+ 'nebula_recall',
48
+ 'nebula_inspect',
49
+ 'nebula_link',
50
+ 'nebula_path',
51
+ 'nebula_stats',
52
+ 'nebula_hygiene',
53
+ 'nebula_bridge',
54
+ 'nebula_sources',
55
+ 'nebula_ingest',
56
+ ]
57
+ return wanted.map((name) => ({
58
+ name,
59
+ description: `兼容别名 → 建议改用 memory_* 统一工具(原 ${name})。`,
60
+ parameters: { type: 'object', additionalProperties: true, properties: {} },
61
+ output: TEXT_OUT,
62
+ async execute(args, exec) {
63
+ const r = await bridge.call(name, args, exec)
64
+ return r.text
65
+ },
66
+ }))
67
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * mcp/server —— 把 8 个 memory_* 工具按 Model Context Protocol 暴露出去。
3
+ *
4
+ * 为什么手写而不引 @modelcontextprotocol/sdk:这个包的安装判据是「不装编译链、不加依赖」。
5
+ * MCP 的 stdio 传输就是「一行一个 JSON-RPC 2.0 报文」,实现它不到两百行;换一个
6
+ * 会跟着升级、会带依赖的 SDK 进来,不划算。协议细节按 2024-11-05 与 2025-06-18 两版
7
+ * 对齐(两者在 initialize / tools 上兼容)。
8
+ *
9
+ * 三条纪律:
10
+ * 1. **stdout 只准出协议报文**。任何日志、警告、进度都走 stderr——MCP 客户端会
11
+ * 因为一行杂音把整条连接判成坏掉。
12
+ * 2. **单个请求失败不许拖垮连接**。工具抛错 → 包成 isError:true 的结果返回;
13
+ * 只有「报文本身不是 JSON-RPC」才回 error 对象。
14
+ * 3. **不主动发通知**。没有「有新记忆」这类推送(那需要订阅语义,宿主支持程度也参差)。
15
+ */
16
+
17
+ import readline from 'node:readline'
18
+
19
+ /** 我们实现的协议版本;客户端给的版本在我们列表里就照它回,否则回最新的。 */
20
+ const SUPPORTED_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05']
21
+ const LATEST_PROTOCOL = SUPPORTED_PROTOCOLS[0]
22
+
23
+ const ERR_PARSE = -32700
24
+ const ERR_INVALID_REQUEST = -32600
25
+ const ERR_METHOD_NOT_FOUND = -32601
26
+ const ERR_INVALID_PARAMS = -32602
27
+ const ERR_INTERNAL = -32603
28
+
29
+ /**
30
+ * 起一个 stdio 服务器。
31
+ *
32
+ * @param {object} opts
33
+ * @param {object} opts.engine createMacroEngine() 的返回值
34
+ * @param {string} [opts.version] 自报版本号
35
+ * @param {string} [opts.name] 自报名字
36
+ * @param {NodeJS.ReadableStream} [opts.input]
37
+ * @param {NodeJS.WritableStream} [opts.output]
38
+ * @param {(line:string)=>void} [opts.log] 调试日志(写 stderr)
39
+ * @param {string} [opts.cwd] 默认工作区:宿主不在 tools/call 里带 cwd 时用它。
40
+ * MCP 子进程的 process.cwd() 是宿主自己的目录(Codex 每个对话一个新目录),
41
+ * 不传这个,库就会落在宿主临时目录下的空库里——`mcp --cwd DIR` 就是给它兜底的。
42
+ */
43
+ export async function serveStdio(opts) {
44
+ const engine = opts.engine
45
+ const version = opts.version ?? '0.0.0'
46
+ const name = opts.name ?? 'macro-memory'
47
+ const input = opts.input ?? process.stdin
48
+ const output = opts.output ?? process.stdout
49
+ const log = typeof opts.log === 'function' ? opts.log : () => {}
50
+ // 默认工作区:宿主没带 cwd 时用它(见 opts.cwd 的说明)
51
+ const defaultCwd = typeof opts.cwd === 'string' && opts.cwd.length > 0 ? opts.cwd : undefined
52
+
53
+ const send = (obj) => {
54
+ try {
55
+ output.write(`${JSON.stringify(obj)}\n`)
56
+ } catch (err) {
57
+ log(`写 stdout 失败:${err?.message ?? err}`)
58
+ }
59
+ }
60
+ const reply = (id, result) => send({ jsonrpc: '2.0', id, result })
61
+ const fail = (id, code, message, data) => {
62
+ const error = { code, message }
63
+ if (data !== undefined) error.data = data
64
+ send({ jsonrpc: '2.0', id, error })
65
+ }
66
+
67
+ const rl = readline.createInterface({ input, crlfDelay: Infinity })
68
+ let closed = false
69
+ // 客户端名字(initialize 的 clientInfo.name):多 agent 共用一个库时,这就是「谁写的」。
70
+ // 记不到就退回 'mcp'——归属宁可是粗的,也不要编一个具体名字。
71
+ let clientName = ''
72
+
73
+ const shutdown = async () => {
74
+ if (closed) return
75
+ closed = true
76
+ try {
77
+ rl.close()
78
+ } catch {
79
+ /* 已经关了 */
80
+ }
81
+ try {
82
+ await engine.close?.()
83
+ } catch (err) {
84
+ log(`关闭引擎失败:${err?.message ?? err}`)
85
+ }
86
+ }
87
+ for (const sig of ['SIGINT', 'SIGTERM']) {
88
+ process.once(sig, () => {
89
+ void shutdown().then(() => process.exit(0))
90
+ })
91
+ }
92
+
93
+ /** 处理一条报文。返回 false 表示「该退了」。 */
94
+ async function handle(msg) {
95
+ if (msg === null || typeof msg !== 'object' || Array.isArray(msg)) {
96
+ fail(null, ERR_INVALID_REQUEST, '报文必须是 JSON-RPC 对象')
97
+ return
98
+ }
99
+ const { id, method, params } = msg
100
+ const isNotification = id === undefined || id === null
101
+ if (typeof method !== 'string') {
102
+ if (!isNotification) fail(id, ERR_INVALID_REQUEST, '缺少 method')
103
+ return
104
+ }
105
+
106
+ // 通知一律不回包(MCP 的 notifications/* 都是单向的)
107
+ if (isNotification) {
108
+ log(`通知:${method}`)
109
+ return
110
+ }
111
+
112
+ switch (method) {
113
+ case 'initialize': {
114
+ const asked = typeof params?.protocolVersion === 'string' ? params.protocolVersion : ''
115
+ const protocolVersion = SUPPORTED_PROTOCOLS.includes(asked) ? asked : LATEST_PROTOCOL
116
+ const info = params?.clientInfo
117
+ clientName = typeof info?.name === 'string' ? info.name.trim().slice(0, 64) : ''
118
+ if (clientName !== '') log(`客户端:${clientName}${typeof info?.version === 'string' ? ` ${info.version}` : ''}`)
119
+ reply(id, {
120
+ protocolVersion,
121
+ capabilities: { tools: { listChanged: false } },
122
+ serverInfo: { name, version },
123
+ instructions: engine.injection({ maxChars: 1200 }),
124
+ })
125
+ return
126
+ }
127
+ case 'ping':
128
+ reply(id, {})
129
+ return
130
+ case 'tools/list':
131
+ reply(id, {
132
+ tools: engine.tools.map((t) => ({
133
+ name: t.name,
134
+ description: t.description,
135
+ inputSchema: t.parameters ?? { type: 'object', properties: {} },
136
+ })),
137
+ })
138
+ return
139
+ case 'tools/call': {
140
+ const toolName = params?.name
141
+ if (typeof toolName !== 'string' || toolName.length === 0) {
142
+ fail(id, ERR_INVALID_PARAMS, 'tools/call 缺少 name')
143
+ return
144
+ }
145
+ if (!engine.def(toolName)) {
146
+ fail(id, ERR_INVALID_PARAMS, `没有这个工具:${toolName}`, { available: engine.tools.map((t) => t.name) })
147
+ return
148
+ }
149
+ const args = params?.arguments ?? {}
150
+ const cwd = typeof params?.cwd === 'string' ? params.cwd : defaultCwd
151
+ try {
152
+ const out = await engine.call(toolName, args, { cwd, agentId: clientName !== '' ? clientName : 'mcp' })
153
+ const result = { content: [{ type: 'text', text: out.text }] }
154
+ if (out.refused === true) result.isError = true
155
+ reply(id, result)
156
+ } catch (err) {
157
+ // 工具自身的错误也走 result(isError),而不是 JSON-RPC error:
158
+ // 前者模型看得见正文,后者会被客户端当成协议故障。
159
+ reply(id, { content: [{ type: 'text', text: String(err?.message ?? err) }], isError: true })
160
+ }
161
+ return
162
+ }
163
+ // MCP 里这些是可选能力:明确回「没实现方法」,别装死
164
+ case 'resources/list':
165
+ reply(id, { resources: [] })
166
+ return
167
+ case 'prompts/list':
168
+ reply(id, { prompts: [] })
169
+ return
170
+ case 'logging/setLevel':
171
+ reply(id, {})
172
+ return
173
+ default:
174
+ fail(id, ERR_METHOD_NOT_FOUND, `没实现这个方法:${method}`)
175
+ }
176
+ }
177
+
178
+ let queue = Promise.resolve()
179
+ rl.on('line', (line) => {
180
+ const text = line.trim()
181
+ if (text.length === 0) return
182
+ let msg
183
+ try {
184
+ msg = JSON.parse(text)
185
+ } catch {
186
+ fail(null, ERR_PARSE, '不是合法 JSON')
187
+ return
188
+ }
189
+ // 串行处理:MCP 客户端可能并发发请求,但写库必须一条一条来
190
+ queue = queue.then(() => handle(msg)).catch((err) => {
191
+ log(`处理失败:${err?.stack ?? err}`)
192
+ fail(msg?.id ?? null, ERR_INTERNAL, String(err?.message ?? err))
193
+ })
194
+ })
195
+
196
+ await new Promise((resolve) => {
197
+ rl.on('close', resolve)
198
+ })
199
+ await queue
200
+ await shutdown()
201
+ }