nebula-memory-mcp 1.2.3 → 1.2.5

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.1**(薄索引 + 画像反哺闸门) | **1.2.3** | 1.0.6(待同步) | 引擎与上游 2.1.1 对齐 |
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.3',
46
+ version: '1.2.5',
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:' };
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,
@@ -579,6 +581,14 @@ function isPidAlive(pid) {
579
581
  }
580
582
 
581
583
  /** 追加一行(append 只写一行,崩溃最多丢最后一行,读入时会当坏行跳过) */
584
+ function fileBytes(file) {
585
+ try {
586
+ return fs.statSync(file).size;
587
+ } catch {
588
+ return 0;
589
+ }
590
+ }
591
+
582
592
  function appendLine(file, obj) {
583
593
  // 返回这一行在文件里的字节区间,供薄索引记录原文位置(懒加载用)。
584
594
  // 先取文件长度当偏移:单进程追加写,长度即下一次写入的起点。
@@ -596,8 +606,8 @@ function appendLine(file, obj) {
596
606
  } finally {
597
607
  fs.closeSync(fd);
598
608
  }
599
- // len 去掉行尾换行,只覆盖 JSON 本体
600
- return { off, len: len - 1 };
609
+ // len 去掉行尾换行,只覆盖 JSON 本体;end 是下一行的起点字节位置
610
+ return { off, len: len - 1, end: off + len };
601
611
  }
602
612
 
603
613
  /** 人类可读的时间差(renderContext 用) */
@@ -679,6 +689,11 @@ class NebulaMemory {
679
689
 
680
690
  this._nodeLines = 0;
681
691
  this._edgeLines = 0;
692
+ // 本实例「已经读到/写到」的 jsonl 字节边界。
693
+ // 写薄索引时用它而不是 fs.statSync:否则持有旧视图的进程会写出
694
+ // 「内容少、大小新」的假自洽索引,把别人新写的记录静默吞掉(2026-11-30 踩到)。
695
+ this._nodeBytes = 0;
696
+ this._edgeBytes = 0;
682
697
  this._badLines = 0;
683
698
  this._indexDirty = true;
684
699
  this._indexMeta = null;
@@ -902,7 +917,11 @@ class NebulaMemory {
902
917
  async remember(input = {}) {
903
918
  this._assertReady();
904
919
  // 超长文本自动切块(2026-11-23 修复静默截断:原实现直接 slice(0, 2000))
905
- const raw = cleanText(input.text);
920
+ const cleaned = cleanText(input.text);
921
+ // 敏感信息脱敏:必须在**算词频之前**(否则原文 token 进倒排索引)且
922
+ // 在**长文分块之前**(否则跨行私钥块会被从中间切断,正则就匹配不到了)
923
+ const redacted = this._redactForWrite(cleaned);
924
+ const raw = redacted.text;
906
925
  const chunks = splitText(raw, MAX_TEXT);
907
926
  if (chunks.length > 1) {
908
927
  const docId = `doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
@@ -913,6 +932,7 @@ class NebulaMemory {
913
932
  ...input,
914
933
  text: chunks[i],
915
934
  _noDedupe: true,
935
+ _redactTypes: redacted.types,
916
936
  meta: { ...(input.meta || {}), docId, chunkIndex: i, chunkTotal: chunks.length },
917
937
  });
918
938
  ids.push(r.id);
@@ -927,7 +947,7 @@ class NebulaMemory {
927
947
  }
928
948
  return { id: ids[0], ids, deduped: false, chunks: chunks.length, docId, node: this._publicNode(this.nodes.get(ids[0])) };
929
949
  }
930
- return this._rememberOne(input);
950
+ return this._rememberOne({ ...input, text: raw, _redactTypes: redacted.types });
931
951
  }
932
952
 
933
953
  /** 单条写入(被 remember 调用;超长已在调用方切块)。 */
@@ -1812,6 +1832,7 @@ class NebulaMemory {
1812
1832
  offsets.set(id, { off, len });
1813
1833
  });
1814
1834
  this._nodeLines = res.lines;
1835
+ this._nodeBytes = fileBytes(this.fileNodes);
1815
1836
  this._badLines += res.bad + invalid;
1816
1837
  for (const [id, raw] of this._raw) {
1817
1838
  if (raw.deleted) continue; // 软删记录留在 _raw 里,不进索引
@@ -1864,6 +1885,7 @@ class NebulaMemory {
1864
1885
  this.edgeMap.set(key, { a: lo, b: hi, w, kind, lastFired, fireCount });
1865
1886
  });
1866
1887
  this._edgeLines = res.lines;
1888
+ this._edgeBytes = fileBytes(this.fileEdges);
1867
1889
  this._badLines += res.bad + invalid;
1868
1890
  // 端点不存在的边(对端被 forget / 或压缩前残留)不参与内存图
1869
1891
  for (const [key, e] of this.edgeMap) {
@@ -2015,6 +2037,8 @@ class NebulaMemory {
2015
2037
  this._tombstones = num(payload.tombstones, 0);
2016
2038
  this._nodeLines = num(payload.nodeLines, 0);
2017
2039
  this._edgeLines = num(payload.edgeLines, 0);
2040
+ this._nodeBytes = num(payload.nodeBytes, 0);
2041
+ this._edgeBytes = num(payload.edgeBytes, 0);
2018
2042
  this._badLines = 0;
2019
2043
 
2020
2044
  this.postings.clear();
@@ -2304,8 +2328,10 @@ class NebulaMemory {
2304
2328
  thinVersion: THIN_VERSION,
2305
2329
  builtAt: new Date().toISOString(),
2306
2330
  dir: this.dir,
2307
- nodeBytes: sizeOf(this.fileNodes),
2308
- edgeBytes: sizeOf(this.fileEdges),
2331
+ // 用本实例已知边界,而不是 fs.statSync:文件可能被别的进程追加过,
2332
+ // 现取大小会让薄索引「内容旧、大小新」,校验永远通过、数据永远丢(2026-11-30)。
2333
+ nodeBytes: this._nodeBytes || sizeOf(this.fileNodes),
2334
+ edgeBytes: this._edgeBytes || sizeOf(this.fileEdges),
2309
2335
  nodeLines: this._nodeLines,
2310
2336
  edgeLines: this._edgeLines,
2311
2337
  tombstones: this._countTombstones(),
@@ -2405,6 +2431,7 @@ class NebulaMemory {
2405
2431
  _appendNode(n) {
2406
2432
  const rec = this._publicNode(n);
2407
2433
  const pos = appendLine(this.fileNodes, rec);
2434
+ if (pos) this._nodeBytes = pos.end;
2408
2435
  // 记下这一行的位置:薄索引写盘时要用它做原文懒加载
2409
2436
  if (pos) {
2410
2437
  Object.defineProperty(n, '_off', { value: pos.off, writable: true, enumerable: false, configurable: true });
@@ -2440,7 +2467,8 @@ class NebulaMemory {
2440
2467
 
2441
2468
  /** 追加一行边记录(同一对端点后写覆盖先写) */
2442
2469
  _saveEdge(edge) {
2443
- appendLine(this.fileEdges, { ...edge, ts: Date.now() });
2470
+ const pos = appendLine(this.fileEdges, { ...edge, ts: Date.now() });
2471
+ if (pos) this._edgeBytes = pos.end;
2444
2472
  this._edgeLines++;
2445
2473
  this._writesSinceIndex++;
2446
2474
  }
@@ -2461,7 +2489,8 @@ class NebulaMemory {
2461
2489
  if (ma) ma.delete(edge.b);
2462
2490
  const mb = this.adj.get(edge.b);
2463
2491
  if (mb) mb.delete(edge.a);
2464
- appendLine(this.fileEdges, { a: edge.a, b: edge.b, deleted: true, ts: Date.now() });
2492
+ const pos = appendLine(this.fileEdges, { a: edge.a, b: edge.b, deleted: true, ts: Date.now() });
2493
+ if (pos) this._edgeBytes = pos.end;
2465
2494
  this._edgeLines++;
2466
2495
  this._writesSinceIndex++;
2467
2496
  }
@@ -2664,6 +2693,7 @@ class NebulaMemory {
2664
2693
  }
2665
2694
  atomicWrite(this.fileNodes, lines.length ? lines.join('\n') + '\n' : '');
2666
2695
  this._nodeLines = lines.length;
2696
+ this._nodeBytes = off; // off 已经累加到「全部重写后的总字节数」
2667
2697
  this._thinDirty = true;
2668
2698
  this._log('info', `compacted nodes.jsonl -> ${lines.length} lines`);
2669
2699
  }
@@ -2673,6 +2703,7 @@ class NebulaMemory {
2673
2703
  for (const e of this.edgeMap.values()) lines.push(JSON.stringify(e));
2674
2704
  atomicWrite(this.fileEdges, lines.length ? lines.join('\n') + '\n' : '');
2675
2705
  this._edgeLines = lines.length;
2706
+ this._edgeBytes = sizeOf(this.fileEdges);
2676
2707
  this._log('info', `compacted edges.jsonl -> ${lines.length} lines`);
2677
2708
  }
2678
2709
  }
@@ -2802,6 +2833,25 @@ class NebulaMemory {
2802
2833
  // 内部:构造 / 巩固 / 统计
2803
2834
  // -------------------------------------------------------------------------
2804
2835
 
2836
+ /**
2837
+ * 写入前脱敏。opts.redact 三态:
2838
+ * 'on'(默认)替换为占位符;'report' 只记日志不改;'off' 完全跳过。
2839
+ * @param {string} text
2840
+ * @returns {{text:string, types:string[]}}
2841
+ */
2842
+ _redactForWrite(text) {
2843
+ const mode = this.opts.redact === 'off' ? 'off' : this.opts.redact === 'report' ? 'report' : 'on';
2844
+ if (mode === 'off') return { text, types: [] };
2845
+ const r = pii.redact(text, { mode });
2846
+ if (r.hits > 0) {
2847
+ this._log(
2848
+ 'info',
2849
+ `redact: 命中 ${r.types.join(',')}(${mode === 'report' ? '仅报告未修改' : '已替换为占位符'})`
2850
+ );
2851
+ }
2852
+ return { text: r.text, types: r.types };
2853
+ }
2854
+
2805
2855
  _buildRecord(input) {
2806
2856
  // cleanText 处理空白/不可见字符(始终执行)。
2807
2857
  // 清洗思考标签/工具原始输出是可选的:由 opts.sanitizeContent 控制,
@@ -2847,6 +2897,10 @@ class NebulaMemory {
2847
2897
  deleted: false,
2848
2898
  _tf: null,
2849
2899
  };
2900
+ // 脱敏审计痕迹:只记录类型,不记录原值(便于「这条被改过什么」可追溯)
2901
+ if (Array.isArray(input._redactTypes) && input._redactTypes.length) {
2902
+ node.meta = { ...(node.meta || {}), redacted: input._redactTypes.slice() };
2903
+ }
2850
2904
  return node;
2851
2905
  }
2852
2906
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nebula-memory-mcp",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
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",