nebula-memory-mcp 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -112,7 +112,7 @@ agent-memory(引擎真源,9 个模块) ──人工对齐──▶ 本
112
112
 
113
113
  | 上游 `agent-memory` | **本仓库** | `nebula-workbuddy-mcp` | 备注 |
114
114
  |---|---|---|---|
115
- | 2.1.0(薄索引,冷启动 2.4s→0.8s) | **1.2.2** | 1.0.3 → 待同步 | 1.2.2 起引擎与上游 2.1.0 对齐 |
115
+ | **2.2.0**(+ PII 脱敏) | **1.2.4** | 1.0.7(待同步) | 引擎与上游 2.2.0 对齐 |
116
116
 
117
117
  ## License
118
118
 
package/mcp-server.mjs CHANGED
@@ -43,7 +43,7 @@ const DATA_DIR = path.resolve(
43
43
  const SERVER_INFO = {
44
44
  name: 'agent-memory',
45
45
  // 与 package.json 的 version 保持一致(发版时必须一起改,见 README「引擎来历与同步」)
46
- version: '1.2.2',
46
+ version: '1.2.4',
47
47
  }
48
48
 
49
49
  // MCP 协议版本(当前规范)
package/memory/pii.cjs ADDED
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * pii.cjs — 敏感信息脱敏(零依赖,纯正则)
5
+ *
6
+ * 为什么需要:用户很容易把 API Key、Token、手机号、身份证贴进对话,本地引擎会原样落盘。
7
+ * 本地存储 ≠ 安全存储(共享电脑、备份、以后接 Hindsight 上云都会成为泄漏面)。
8
+ *
9
+ * 设计原则(2026-11-29):
10
+ * 1. **只做高置信模式** —— 宁可漏判,不可误改。误改会让记忆失真,比漏判更糟。
11
+ * (所以不做「password=xxx」这类宽泛匹配,那会把正常文本改坏)
12
+ * 2. **替换而非删除** —— 换成长度无关的占位符 `[REDACTED:type]`,
13
+ * 保留句子结构,周边语义仍能被检索到。
14
+ * 3. **类型可审计** —— 返回命中的类型列表,调用方写进 meta.redacted(只存类型不存原值)。
15
+ * 4. **幂等** —— 占位符本身不会匹配任何规则,重复调用安全。
16
+ *
17
+ * 调用时机(重要):必须在**算词频之前**、且在**长文分块之前**。
18
+ * - 之前算词频 → 否则原文 token 进倒排索引,index.thin.json 就成了泄漏面
19
+ * - 分块之前 → 私钥块这类跨行结构先切块就匹配不到了
20
+ */
21
+
22
+ /** 占位符:保留类型名,便于人读与审计 */
23
+ const placeholder = (type) => `[REDACTED:${type}]`;
24
+
25
+ /**
26
+ * 规则表。顺序敏感:越具体的越靠前(私钥整块 > 各家 key > 通用 token > 号码)。
27
+ * 每条:type(进 meta.redacted)、re(global)、why(说明)
28
+ */
29
+ const RULES = [
30
+ {
31
+ type: 'private_key',
32
+ // 整块 PEM:跨行匹配,必须先于其他规则
33
+ re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
34
+ why: 'PEM 私钥块',
35
+ },
36
+ {
37
+ type: 'api_key',
38
+ // OpenAI / Anthropic / 类似 sk- 前缀
39
+ re: /\bsk-(?:ant-)?[A-Za-z0-9_-]{20,}\b/g,
40
+ why: 'sk- 前缀的模型 API Key',
41
+ },
42
+ {
43
+ type: 'api_key',
44
+ re: /\bAIza[0-9A-Za-z_-]{35}\b/g,
45
+ why: 'Google API Key',
46
+ },
47
+ {
48
+ type: 'credential',
49
+ re: /\bAKIA[0-9A-Z]{16}\b/g,
50
+ why: 'AWS Access Key ID',
51
+ },
52
+ {
53
+ type: 'credential',
54
+ re: /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,
55
+ why: 'GitHub token',
56
+ },
57
+ {
58
+ type: 'credential',
59
+ re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
60
+ why: 'Slack token',
61
+ },
62
+ {
63
+ type: 'token',
64
+ re: /\bBearer\s+[A-Za-z0-9._~+/-]{20,}=*\b/g,
65
+ why: 'HTTP Bearer token',
66
+ },
67
+ {
68
+ type: 'id_card',
69
+ // 18 位:17 位数字 + 校验位(数字或 X),前后不能紧邻数字
70
+ re: /(?<!\d)\d{17}[\dXx](?!\d)/g,
71
+ why: '中国大陆 18 位身份证',
72
+ },
73
+ {
74
+ type: 'phone',
75
+ // 中国大陆手机号:1[3-9] 开头 11 位,前后不能紧邻数字
76
+ re: /(?<!\d)1[3-9]\d{9}(?!\d)/g,
77
+ why: '中国大陆手机号',
78
+ },
79
+ {
80
+ type: 'password',
81
+ // 「密码 ybzhai102058」「口令:abc12345」「password: hunter2」这类。
82
+ // 判定条件(为了保证精度,缺一不可):
83
+ // 1. 关键词后允许 空格 / 是 / 为 / : / :/ = 作为分隔
84
+ // 2. 值 6 位以上、**不含中文**(密码不会写成中文句子)
85
+ // 3. 值里**必须含数字或符号** —— 这样 "password resetting" 这种英文短语不会被误伤
86
+ // 2026-11-29 补:真实库里发现「帐号yb0758@139.com 密码 ybzhai102058」明文落盘,
87
+ // 且真实写法没有「是/冒号」分隔,所以分隔符必须可选。
88
+ re: /((?:密码|口令|(?<![A-Za-z])(?:password|passwd|pwd)(?![A-Za-z]))\s*(?:是|为|[::=])?\s*)((?![\[\(]REDACTED:)(?=[A-Za-z0-9`'"*\[(_-])(?=[^\s\u4e00-\u9fa5]{6,})(?=[^\s]*[\d!@#$%^&*_+=.,-])[^\s\u4e00-\u9fa5]{6,})/gi,
89
+ why: '关键词 + 值形式的密码',
90
+ keepPrefix: true,
91
+ // 尾部标点不参与替换(否则「新密码:`Zhai@2026`(已改)」会把「(」一起吞掉)
92
+ stripTrailing: /[、,。;:!?()【】「」『』<>《》,.;:!?()\[\]{}||]+$/,
93
+ },
94
+ {
95
+ type: 'email',
96
+ // 域名必须以字母结尾(2~24 位)。加这个尾巴是为了排除 npm 风格 `包名@1.3.8`
97
+ // —— 2026-11-29 在真实库里踩到:81 条 email 命中全是 `dsh-local-xxx@1.3.8`,
98
+ // 纯误报(包名@版本),差点把整库编码方式改坏。
99
+ // 末尾 (?!:) 排除 `git@github.com:owner/repo.git` 这类 SSH remote(是仓库引用不是 PII)。
100
+ re: /\b[\w.+-]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,24}\b(?!:)/g,
101
+ why: '邮箱地址(域名须以字母 TLD 结尾;排除 git@host:path)',
102
+ },
103
+ ];
104
+
105
+ /** 允许单独关闭某类(默认全开) */
106
+ const DEFAULT_ENABLED = new Set(RULES.map((r) => r.type));
107
+
108
+ /**
109
+ * 脱敏文本。
110
+ * @param {string} text
111
+ * @param {{mode?:'on'|'off'|'report', enabledTypes?:string[]|Set<string>, disabledTypes?:string[]|Set<string>}} [opts]
112
+ * @returns {{text:string, types:string[], hits:number}}
113
+ * - mode='on'(默认):替换
114
+ * - mode='report':只统计不修改(text 原样返回)
115
+ * - mode='off':直接返回原文,零开销
116
+ */
117
+ function redact(text, opts = {}) {
118
+ const src = typeof text === 'string' ? text : String(text == null ? '' : text);
119
+ const mode = opts.mode === 'off' ? 'off' : opts.mode === 'report' ? 'report' : 'on';
120
+ if (mode === 'off' || !src) return { text: src, types: [], hits: 0 };
121
+
122
+ const enabled = (() => {
123
+ if (opts.enabledTypes) return new Set(opts.enabledTypes);
124
+ const s = new Set(DEFAULT_ENABLED);
125
+ if (opts.disabledTypes) for (const t of opts.disabledTypes) s.delete(t);
126
+ return s;
127
+ })();
128
+
129
+ let out = src;
130
+ const types = [];
131
+ let hits = 0;
132
+
133
+ for (const rule of RULES) {
134
+ if (!enabled.has(rule.type)) continue;
135
+ // 每次都重置 lastIndex,避免 /g 的状态在多次调用间残留
136
+ rule.re.lastIndex = 0;
137
+ const found = out.match(rule.re);
138
+ if (!found || !found.length) continue;
139
+ hits += found.length;
140
+ if (!types.includes(rule.type)) types.push(rule.type);
141
+ if (mode === 'on') {
142
+ // keepPrefix:只替换「值」那部分,保留「密码是 / password:」这类前缀,句子仍可读
143
+ out = rule.keepPrefix
144
+ ? out.replace(rule.re, (_m, p1, p2) => {
145
+ const tail = rule.stripTrailing ? (p2.match(rule.stripTrailing) || [''])[0] : '';
146
+ const val = tail ? p2.slice(0, p2.length - tail.length) : p2;
147
+ if (!val) return _m; // 全是标点,不动
148
+ return `${p1}${placeholder(rule.type)}${tail}`;
149
+ })
150
+ : out.replace(rule.re, placeholder(rule.type));
151
+ }
152
+ }
153
+
154
+ return { text: mode === 'on' ? out : src, types, hits };
155
+ }
156
+
157
+ /**
158
+ * 只检测,不修改。用于「想先看看库里有没有敏感信息」。
159
+ * @param {string} text
160
+ * @returns {{types:string[], hits:number}}
161
+ */
162
+ function scan(text) {
163
+ const r = redact(text, { mode: 'report' });
164
+ return { types: r.types, hits: r.hits };
165
+ }
166
+
167
+ module.exports = { redact, scan, RULES, PLACEHOLDER_PREFIX: '[REDACTED:' };
@@ -40,6 +40,45 @@ function isPersonalQuery(query) {
40
40
  return PERSONAL_PATTERNS.some((re) => re.test(q));
41
41
  }
42
42
 
43
+ /**
44
+ * 功能虚词 bigram:这些词在任何中文句子里都高频出现,
45
+ * 不能用来判断「query 与画像节点是否同一个话题」。
46
+ * (2026-11-29 加:没有这层过滤时,「我平时喝什么咖啡」会因为「我平/平时/什么」
47
+ * 跟画像节点「孩子上二年级」之外的高重要度 fact 撞上而被污染)
48
+ */
49
+ const FUNCTION_STEMS = [
50
+ '什么', '怎么', '为什', '多少', '哪个', '哪家', '是不', '有什',
51
+ '我平', '平时', '我的', '我叫', '我是', '我喜', '喜欢', '习惯', '偏好', '爱好',
52
+ '一些', '这个', '那个', '现在', '今天', '时候',
53
+ ];
54
+
55
+ /** 取文本的 2~3 字 n-gram 集合(纯字符切分,不做分词,零依赖) */
56
+ function gramsOf(text, maxLen = 3) {
57
+ const out = new Set();
58
+ for (const seg of String(text || '').split(/[^\u4e00-\u9fa5A-Za-z0-9]+/)) {
59
+ for (let len = 2; len <= maxLen; len++) {
60
+ for (let i = 0; i + len <= seg.length; i++) out.add(seg.slice(i, i + len));
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /**
67
+ * 画像节点是否与 query 属于同一话题。
68
+ *
69
+ * 规则:两者至少有一个**非功能虚词**的 n-gram 交集。
70
+ * 只有同话题时才反哺——否则「用户的名字是李雷」这种高重要度身份节点
71
+ * 会在任何个人化提问里被注入,把无关的画像词塞进查询。
72
+ */
73
+ function sharesTopic(queryGrams, nodeText) {
74
+ for (const g of gramsOf(nodeText)) {
75
+ // 含功能词干的 n-gram 一律不算实义(否则 3-gram「我平时」会被当成话题交集)
76
+ if (FUNCTION_STEMS.some((s) => g.includes(s))) continue;
77
+ if (queryGrams.has(g)) return true;
78
+ }
79
+ return false;
80
+ }
81
+
43
82
  /**
44
83
  * 收集库里的画像/摘要节点文本(最多 N 条,按 importance 降序)。
45
84
  * @param {any} mem NebulaMemory 实例
@@ -78,11 +117,16 @@ function boostPersonalQuery(mem, query, opts = {}) {
78
117
  const nodes = collectProfileNodes(mem, maxNodes);
79
118
  if (!nodes.length) return { boosted: false, reason: 'no-profile', tokens: [] };
80
119
 
120
+ // 相关性闸门:只有与 query 同话题的画像节点才参与反哺
121
+ const queryGrams = gramsOf(query);
122
+ const relevant = nodes.filter((n) => sharesTopic(queryGrams, n.text));
123
+ if (!relevant.length) return { boosted: false, reason: 'off-topic', tokens: [] };
124
+
81
125
  // 从画像节点文本里抽关键词(用简单的二元切分 + 过滤停用词)
82
126
  const STOP = new Set(['的', '了', '是', '在', '有', '和', '与', '我', '你', '他', '她', '这', '那', '就', '也', '都', '很', '个', '上', '下', '中', '为', '对', '从', '到', '把', '被', '让', '给', '但', '而', '或', '如果', '因为', '所以', '一个', '我们', '你们', '他们']);
83
127
  const tokens = [];
84
128
  const seen = new Set();
85
- for (const node of nodes) {
129
+ for (const node of relevant) {
86
130
  const text = String(node.text || '');
87
131
  // 中文按 2-4 字滑窗取词组(比单字有区分度,比整句更可匹配)
88
132
  for (const seg of text.split(/[,。;:、\s\n|()()\[\]【】"'"'']+/)) {
@@ -106,4 +150,4 @@ function boostPersonalQuery(mem, query, opts = {}) {
106
150
  return { boosted: tokens.length > 0, reason: 'personal', tokens };
107
151
  }
108
152
 
109
- module.exports = { isPersonalQuery, collectProfileNodes, boostPersonalQuery, PERSONAL_PATTERNS };
153
+ module.exports = { isPersonalQuery, collectProfileNodes, boostPersonalQuery, PERSONAL_PATTERNS, gramsOf, sharesTopic, FUNCTION_STEMS };
package/memory/store.cjs CHANGED
@@ -42,6 +42,7 @@ const fragmentsView = require('./fragments.cjs');
42
42
  const recallSynonyms = require('./synonyms.cjs');
43
43
  const profileRecall = require('./profile-recall.cjs');
44
44
  const typoCorrect = require('./typo-fix.cjs');
45
+ const pii = require('./pii.cjs');
45
46
 
46
47
  const { LAYER, EDGE_KIND, SUMMARY_KIND } = dynamics;
47
48
 
@@ -80,6 +81,7 @@ const DEFAULTS = {
80
81
  dormantDays: 60, // 超过这么多天没访问的 episode 标记 dormant(不删除)
81
82
  dormantPenalty: 0.55, // dormant 节点在检索里的乘子
82
83
  dedupeThreshold: 0.92, // remember 去重阈值(同 kind、tf-idf 余弦)
84
+ redact: 'on', // 写入前敏感信息脱敏:'on'(默认替换)| 'off'(完全关闭)| 'report'(只统计)
83
85
  consolidateThreshold: 0.85, // episode 聚合阈值
84
86
  consolidateMinCluster: 2,
85
87
  consolidateMaxCluster: 12,
@@ -902,7 +904,11 @@ class NebulaMemory {
902
904
  async remember(input = {}) {
903
905
  this._assertReady();
904
906
  // 超长文本自动切块(2026-11-23 修复静默截断:原实现直接 slice(0, 2000))
905
- const raw = cleanText(input.text);
907
+ const cleaned = cleanText(input.text);
908
+ // 敏感信息脱敏:必须在**算词频之前**(否则原文 token 进倒排索引)且
909
+ // 在**长文分块之前**(否则跨行私钥块会被从中间切断,正则就匹配不到了)
910
+ const redacted = this._redactForWrite(cleaned);
911
+ const raw = redacted.text;
906
912
  const chunks = splitText(raw, MAX_TEXT);
907
913
  if (chunks.length > 1) {
908
914
  const docId = `doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
@@ -913,6 +919,7 @@ class NebulaMemory {
913
919
  ...input,
914
920
  text: chunks[i],
915
921
  _noDedupe: true,
922
+ _redactTypes: redacted.types,
916
923
  meta: { ...(input.meta || {}), docId, chunkIndex: i, chunkTotal: chunks.length },
917
924
  });
918
925
  ids.push(r.id);
@@ -927,7 +934,7 @@ class NebulaMemory {
927
934
  }
928
935
  return { id: ids[0], ids, deduped: false, chunks: chunks.length, docId, node: this._publicNode(this.nodes.get(ids[0])) };
929
936
  }
930
- return this._rememberOne(input);
937
+ return this._rememberOne({ ...input, text: raw, _redactTypes: redacted.types });
931
938
  }
932
939
 
933
940
  /** 单条写入(被 remember 调用;超长已在调用方切块)。 */
@@ -2802,6 +2809,25 @@ class NebulaMemory {
2802
2809
  // 内部:构造 / 巩固 / 统计
2803
2810
  // -------------------------------------------------------------------------
2804
2811
 
2812
+ /**
2813
+ * 写入前脱敏。opts.redact 三态:
2814
+ * 'on'(默认)替换为占位符;'report' 只记日志不改;'off' 完全跳过。
2815
+ * @param {string} text
2816
+ * @returns {{text:string, types:string[]}}
2817
+ */
2818
+ _redactForWrite(text) {
2819
+ const mode = this.opts.redact === 'off' ? 'off' : this.opts.redact === 'report' ? 'report' : 'on';
2820
+ if (mode === 'off') return { text, types: [] };
2821
+ const r = pii.redact(text, { mode });
2822
+ if (r.hits > 0) {
2823
+ this._log(
2824
+ 'info',
2825
+ `redact: 命中 ${r.types.join(',')}(${mode === 'report' ? '仅报告未修改' : '已替换为占位符'})`
2826
+ );
2827
+ }
2828
+ return { text: r.text, types: r.types };
2829
+ }
2830
+
2805
2831
  _buildRecord(input) {
2806
2832
  // cleanText 处理空白/不可见字符(始终执行)。
2807
2833
  // 清洗思考标签/工具原始输出是可选的:由 opts.sanitizeContent 控制,
@@ -2847,6 +2873,10 @@ class NebulaMemory {
2847
2873
  deleted: false,
2848
2874
  _tf: null,
2849
2875
  };
2876
+ // 脱敏审计痕迹:只记录类型,不记录原值(便于「这条被改过什么」可追溯)
2877
+ if (Array.isArray(input._redactTypes) && input._redactTypes.length) {
2878
+ node.meta = { ...(node.meta || {}), redacted: input._redactTypes.slice() };
2879
+ }
2850
2880
  return node;
2851
2881
  }
2852
2882
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nebula-memory-mcp",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
4
4
  "mcpName": "io.github.yb-zhai/nebula-memory",
5
5
  "description": "Zero-dependency local Agent memory MCP Server (stdio JSON-RPC). Works offline, no API keys, no database. Exposes remember/recall/stats/forget to Claude Desktop, Cursor, ChatGPT and any MCP client.",
6
6
  "type": "module",