@modusensus/dsh-mneme 0.8.11 → 0.8.13

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 (54) hide show
  1. package/README.md +5 -5
  2. package/assets/icon.svg +3 -3
  3. package/lib/api.js +2 -0
  4. package/lib/client.js +12 -1
  5. package/lib/config.js +66 -1
  6. package/lib/dream/decisions.js +16 -0
  7. package/lib/dream/sleep.js +3 -0
  8. package/lib/dream.js +57 -9
  9. package/lib/entities/extractor.js +4 -1
  10. package/lib/graph/anchoring.js +180 -0
  11. package/lib/guide.js +13 -1
  12. package/lib/index.js +18 -5
  13. package/lib/inject.js +15 -3
  14. package/lib/lang.js +10 -0
  15. package/lib/sensitive-scan.js +209 -0
  16. package/lib/service.js +203 -35
  17. package/lib/settings.js +29 -3
  18. package/lib/store.js +155 -11
  19. package/lib/summarize.js +104 -7
  20. package/locale/en.json +6 -6
  21. package/locale/zh.json +6 -6
  22. package/package.json +114 -113
  23. package/scripts/sync-test-badge.mjs +9 -7
  24. package/scripts/test-count-sync.mjs +44 -0
  25. package/src/api.js +2 -0
  26. package/src/config.js +66 -1
  27. package/src/dream/decisions.js +16 -0
  28. package/src/dream/sleep.js +3 -0
  29. package/src/dream.js +57 -9
  30. package/src/entities/extractor.js +4 -1
  31. package/src/graph/anchoring.js +180 -0
  32. package/src/guide.js +13 -1
  33. package/src/index.js +18 -5
  34. package/src/inject.js +15 -3
  35. package/src/lang.js +10 -0
  36. package/src/sensitive-scan.js +209 -0
  37. package/src/service.js +203 -35
  38. package/src/settings.js +29 -3
  39. package/src/store.js +155 -11
  40. package/src/summarize.js +104 -7
  41. package/test/api.test.js +15 -2
  42. package/test/baseline-persist.test.js +248 -0
  43. package/test/dream.test.js +75 -0
  44. package/test/graph-anchoring.test.js +185 -0
  45. package/test/graph-inject-budget.test.js +104 -0
  46. package/test/graph-passive-confirm.test.js +92 -0
  47. package/test/graph-weight-evolution.test.js +105 -0
  48. package/test/inject-pools.test.js +19 -0
  49. package/test/scope-inject-soft.test.js +106 -0
  50. package/test/scope-strict.test.js +112 -0
  51. package/test/sensitive-scan.test.js +207 -0
  52. package/test/summarize.test.js +177 -0
  53. package/test/test-count-sync.test.js +60 -0
  54. package/test/write-admission.test.js +115 -0
@@ -0,0 +1,180 @@
1
+ // dsh-mneme/src/graph/anchoring.js
2
+ // 图谱锚定层(issue #24 · 块1 Activation Anchoring)。
3
+ import assert from "node:assert/strict";
4
+ // 纯函数模块:把「查询命中实体的多路激活信号」归一化、合并成种子集、再沿
5
+ // entity_relations 级联扩散。零数据库依赖——store 侧查询由调用方注入,
6
+ // 本模块只做信号处理,便于单测与与其他召回通路(BM25/向量)同等对待。
7
+ //
8
+ // 设计输入来自 #24 合议 + heptaspirit serendipity-engine 实战(#24 评论):
9
+ // - 归一化二分法:连续分(cos/PPR)走 min-max;匹配通路(精确/tag/别名)
10
+ // 走离散级别,不用 min-max——布尔通路用 min-max 会把「中 1 个」和「中
11
+ // 20 个」都拉平到 1.0,级别信息被压平。
12
+ // - 级联扩散加「跳数配额」:λ/θ 只管可及性,可见性由配额决定——直接按 hop
13
+ // 深度打 0.5/0.3/0.2 权重,配桶内 round-robin,防深跳被 1-hop 完全压住。
14
+ // - graphSeedCap:防「多锚点命中 + 模糊通路」把种子集撑爆成整库。
15
+ // - 排序稳定:并列按实体 ID 破序(同输入两次结果不同会让 A/B 调参白做)。
16
+
17
+ /** 匹配通路的离散级别(heptaspirit 建议:布尔/计数通路不用 min-max)。 */
18
+ export const DISCRETE_LEVELS = Object.freeze({
19
+ exact: 1.0, // 名称精确含于查询(布尔 1.0)
20
+ title: 0.8, // 实体名匹配记忆标题(tag/别名层)
21
+ alias: 0.6,
22
+ tag: 0.4, // tag 共现
23
+ substring: 0.2, // 子串命中(最弱,纯计数不级联)
24
+ });
25
+
26
+ /** 级联每跳的权重(跳数配额:1:2:3-hop = 0.5/0.3/0.2)。 */
27
+ export const HOP_QUOTA = Object.freeze({ 1: 0.5, 2: 0.3, 3: 0.2 });
28
+
29
+ /**
30
+ * 连续分 min-max 归一化(向量 cos 相似度、PPR 激活分等)。
31
+ * 输入 [] 或全同值时返回原样(无尺度可压平,防除零)。
32
+ */
33
+ export function minMax(scores) {
34
+ const arr = Array.isArray(scores) ? scores : [];
35
+ if (arr.length === 0) return [];
36
+ let min = Infinity;
37
+ let max = -Infinity;
38
+ for (const v of arr) {
39
+ if (v < min) min = v;
40
+ if (v > max) max = v;
41
+ }
42
+ if (max - min < 1e-12) return arr.map(() => 1); // 平局视为满权
43
+ return arr.map((v) => (v - min) / (max - min));
44
+ }
45
+
46
+ /**
47
+ * 把一条检测通路的结果归一化成 0..1 的打分表。
48
+ * path 是离散通路名(exact/tag/...)→ 查 DISCRETE_LEVELS;是连续通路
49
+ * (continuous=true)→ min-max。返回 { byId: Map<id, score>, order: [id...] }。
50
+ */
51
+ export function normalizePath(hits, { path = "exact", continuous = false } = {}) {
52
+ const ids = Array.isArray(hits) ? hits : [];
53
+ const byId = new Map();
54
+ if (continuous) {
55
+ const raw = ids.map((h) => (typeof h === "number" ? h : h?.score ?? 0));
56
+ const norm = minMax(raw);
57
+ ids.forEach((h, i) => {
58
+ const id = typeof h === "object" ? h.id : h;
59
+ byId.set(id, norm[i]);
60
+ });
61
+ } else {
62
+ const level = DISCRETE_LEVELS[path] ?? DISCRETE_LEVELS.substring;
63
+ for (const id of ids) byId.set(id, level);
64
+ }
65
+ return { byId, order: [...byId.keys()] };
66
+ }
67
+
68
+ /**
69
+ * 合并多路激活成种子集:每路先归一化(调用方负责通路分类),再累加。
70
+ * seedsCap 上限(graphSeedCap,默认 12);封顶前按总分排序取前 N——保证
71
+ * 扩散的是活跃子图而非冷启动点爆整库。
72
+ * 返回 { id, name, score, paths: Set } 列表,按 score 降序、name 升序(稳定)。
73
+ */
74
+ export function anchorSeeds({ paths = [], cap = 12 } = {}) {
75
+ const score = new Map();
76
+ const nameOf = new Map();
77
+ const pathSet = new Map();
78
+ for (const p of paths) {
79
+ for (const [id, s] of p.byId ?? []) {
80
+ score.set(id, (score.get(id) ?? 0) + s);
81
+ if (!pathSet.has(id)) pathSet.set(id, new Set());
82
+ pathSet.get(id).add(p.path ?? "?");
83
+ if (p.nameOf?.has?.(id)) nameOf.set(id, p.nameOf.get(id));
84
+ }
85
+ }
86
+ let seeds = [...score.entries()].map(([id, s]) => ({
87
+ id,
88
+ name: nameOf.get(id) ?? id,
89
+ score: s,
90
+ paths: pathSet.get(id) ?? new Set()
91
+ }));
92
+ seeds.sort((a, b) => b.score - a.score || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
93
+ if (cap > 0 && seeds.length > cap) seeds = seeds.slice(0, cap);
94
+ return seeds;
95
+ }
96
+
97
+ /**
98
+ * 级联扩散:从种子实体出发沿 adjacency 走 BFS,为每个可达实体贴最短深度。
99
+ * depth 上界默认 2([1,3] 配置范围)。返回 Map<entityId, minDepth>——
100
+ * 调用方据此取 HOP_QUOTA[minDepth] 权重 + 桶内 round-robin(见 pickByHopQuota)。
101
+ * adjacency 由调用方提供(store.getEntityNeighbors(id) 或全量邻接矩阵),
102
+ * 本模块不感知存储。
103
+ */
104
+ export function cascadeDepths({ seeds, adjacencyOf, maxDepth = 2 } = {}) {
105
+ const depths = new Map();
106
+ const idOfSeeds = (seeds ?? []).map((s) => (typeof s === "object" ? s.id : s));
107
+ const queue = [];
108
+ for (const id of idOfSeeds) {
109
+ if (!depths.has(id)) {
110
+ depths.set(id, 0);
111
+ queue.push([id, 0]);
112
+ }
113
+ }
114
+ for (let i = 0; i < queue.length; i++) {
115
+ const [id, d] = queue[i];
116
+ if (d >= maxDepth) continue;
117
+ let neighbors = [];
118
+ try {
119
+ neighbors = typeof adjacencyOf === "function" ? adjacencyOf(id) : (adjacencyOf?.get?.(id) ?? []);
120
+ } catch { /* single neighbor fetch failure: keep spreading from the rest */ }
121
+ for (const nb of neighbors) {
122
+ const nid = typeof nb === "object" ? nb.id : nb;
123
+ if (!nid || depths.has(nid)) continue;
124
+ depths.set(nid, d + 1);
125
+ queue.push([nid, d + 1]);
126
+ }
127
+ }
128
+ return depths;
129
+ }
130
+
131
+ /**
132
+ * 跳数配额选取:候选实体按深度分层,层内按(分,ID)稳定排序后取额度。
133
+ * quota 形如 { 1: 0.5, 2: 0.3, 3: 0.2 }——每层最多取 ceil(depthCap * quota[d]) 个,
134
+ * 桶内按 score 降序(并列按 ID)。返回 { ids, scoreOf, depthOf }。
135
+ * 这一步把「级联可及性」与「最终可见性」解耦(heptaspirit:λ/θ 只管前者)。
136
+ */
137
+ export function pickByHopQuota({
138
+ depths = new Map(),
139
+ scoreOf = () => 0,
140
+ maxDepth = 2,
141
+ depthCap = 12
142
+ } = {}) {
143
+ const buckets = new Map(); // depth -> [{id, score}]
144
+ for (const [id, d] of depths) {
145
+ if (d === 0 || d > maxDepth) continue;
146
+ const key = Math.min(d, 3);
147
+ if (!buckets.has(key)) buckets.set(key, []);
148
+ buckets.get(key).push({ id, score: scoreOf(id) ?? 0 });
149
+ }
150
+ const picked = [];
151
+ for (const [d, items] of buckets) {
152
+ items.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
153
+ const quota = HOP_QUOTA[d] ?? 0.2;
154
+ const n = Math.max(1, Math.floor(depthCap * quota));
155
+ picked.push(...items.slice(0, n).map((x) => x.id));
156
+ }
157
+ // 队内稳定序:按深度升序(1-hop 优先),保证可感知的扩散次序。
158
+ picked.sort((a, b) => (depths.get(a) - depths.get(b)) || (a < b ? -1 : a > b ? 1 : 0));
159
+ return { ids: picked, scoreOf, depthOf: depths };
160
+ }
161
+
162
+ // Lightweight self-check (ponytail: 非平凡逻辑留一个可运行断言)。
163
+ export function _selfCheck() {
164
+ const exact = normalizePath(["e1", "e2"], { path: "exact" });
165
+ const tag = normalizePath(["e2", "e3"], { path: "tag" });
166
+ assert(exact.byId.get("e1") === 1.0 && exact.byId.get("e2") === 1.0, "exact level");
167
+ assert(tag.byId.get("e2") === 0.4 && tag.byId.get("e3") === 0.4, "tag level");
168
+ const seeds = anchorSeeds({ paths: [exact, tag], cap: 10 });
169
+ assert(seeds[0].id === "e2", "merged highest first"); // e2: 精确+tag = 1.4
170
+ assert(seeds[0].score >= 1.4 - 1e-9, "score accumulates");
171
+ const adj = new Map([
172
+ ["e2", ["n1", "n2"]],
173
+ ["n1", ["n2", "deep3"]],
174
+ ]);
175
+ const depths = cascadeDepths({ seeds, adjacencyOf: (id) => adj.get(id) ?? [], maxDepth: 2 });
176
+ assert(depths.get("n1") === 1 && depths.get("n2") === 1 && depths.get("deep3") === 2, "bfs depth");
177
+ const { ids } = pickByHopQuota({ depths, maxDepth: 2, depthCap: 12 });
178
+ assert(ids.includes("n1") && ids.includes("n2") && ids.includes("deep3"), "quota picks all");
179
+ return "anchoring self-check ok";
180
+ }
package/src/guide.js CHANGED
@@ -38,9 +38,21 @@ export const TOOL_GUIDE = {
38
38
  " Use this when the task depends on earlier decisions, preferences, or project history that is not already in context, " +
39
39
  "or to look for a newer memory behind one that seems stale. " +
40
40
  "Skip it for facts you can read directly from the repository.",
41
+ // 第二句(#249 第二批:「能力说明里没提 scope」):TOOL_GUIDE.memory_save 此前只
42
+ // 讲「该不该写」,没讲「写给谁看」——而 memory_save 的 scope 参数是**必填面**,
43
+ // 漏填的后果是单向的。所以这里给的是一条判断规则而不是一句免责声明:不确定就别填
44
+ // (未标注 = 处处可见,NULL 恒可见,是安全的默认);标了 scope 才在多 scope 检索里
45
+ // 付出代价。那句代价必须按实写:A2 软隔离是「他 scope 降权 ×0.5 但保留可见」
46
+ // (service.js),只有 A3 `strictScope`(默认关)才真的硬过滤。写「静默消失」既不
47
+ // 符合默认配置下的行为,也撞上「拒绝可解释、不静默丢弃」的口径(#254 验收第 2 条),
48
+ // 会让模型以为标注有它实际没有的隐私效果。
49
+ // 写进工具描述而不是总则:它是 memory_save 单工具的判据,总则那五条讲的是
50
+ // 「何时查 / 何时写 / 何时 no-op」,加第六条会把单工具语义抬成全局纪律。
41
51
  memory_save:
42
52
  " Save only durable, cross-session value (a preference, a decision with its rationale, an engineering constraint, " +
43
- "a pitfall with its root cause). Trivial single-turn work does not belong here, and when unsure, do not save."
53
+ "a pitfall with its root cause). Trivial single-turn work does not belong here, and when unsure, do not save. " +
54
+ "If a memory only holds for one workspace or one agent, declare workspace_scope / agent_scope; otherwise leave both out. " +
55
+ "An unscoped memory is visible everywhere; a scoped one is filtered or downranked outside its scope."
44
56
  };
45
57
 
46
58
  /**
package/src/index.js CHANGED
@@ -5,6 +5,8 @@ import { resolveDocumentDir } from "./document.js";
5
5
  import { createService } from "./service.js";
6
6
  // #254 写入准入(第一阶段只计量,不拦截):见 src/write-admission.js 的文件头。
7
7
  import { createWriteAdmission } from "./write-admission.js";
8
+ // #164 A2:写入边界的密钥 / PII 判据,注入给上面的写入准入。
9
+ import { createSensitiveScan } from "./sensitive-scan.js";
8
10
  import { createTools } from "./tools.js";
9
11
  import { createInjector } from "./inject.js";
10
12
  import { createContinuityRescue } from "./continuity.js";
@@ -278,11 +280,17 @@ export const apply = (ctx, config) => {
278
280
  // 关掉,在无保留期的表里按写入频次增长是不能接受的)。
279
281
  //
280
282
  // sensitiveScan 是密钥 / PII 那一类判据的注入点。按 #254 验收第 4 条它是 #164 A2
281
- // 的判据来源(A2 记在维护者排期里),所以本批不实现它,只把接口形状定在这里——
282
- // 接上时只改这一行:
283
- // createWriteAdmission({ ..., sensitiveScan: createSensitiveScan({ config: cfg }) })
284
- // 缺省 null 时第 1 级只跑空白 / 噪声两类判据,其余一切照旧。
285
- const writeAdmission = createWriteAdmission({ store, config: cfg, logger: ctx.logger });
283
+ // 的判据来源,现在由 src/sensitive-scan.js 实现(维护者 09-28 把 A2 的认领转给
284
+ // 本侧)。这里只做接线:判据开不开由它自己的键 sensitiveScanEnabled 决定,工厂在
285
+ // 关时返回 null,闸门的行为就与 #332 合并时逐字段一致(那一版根本没有这个函数);
286
+ // 命中之后是仅告警还是真拦,仍是 writeAdmission.enforce 的事(#164 口径:
287
+ // 默认仅告警、拦截 opt-in),判据不碰决策。
288
+ const writeAdmission = createWriteAdmission({
289
+ store,
290
+ config: cfg,
291
+ logger: ctx.logger,
292
+ sensitiveScan: createSensitiveScan({ config: cfg })
293
+ });
286
294
  const service = createService({ store, mirror, config: cfg, logger: ctx.logger, documentIndex, writeAdmission });
287
295
 
288
296
  // F-NEW-03: if the mirror sync failed last run (persisted dirty state), retry
@@ -502,6 +510,11 @@ export const apply = (ctx, config) => {
502
510
  logger: ctx.logger,
503
511
  semantic: { embedder, vectorIndex },
504
512
  lastRunAtSeed: store.lastDreamRunAt("auto"),
513
+ // Issue #89(基线半边):阈值基线同样跨重启恢复——只恢复 lastRunAt 的话,
514
+ // 重启后的第一条写入仍会绕过阈值(库里记忆多于阈值时 overBase 恒成立)开跑
515
+ // 整轮。种子取上次成功轮的库规模,口径与运行期刷新一致;读不到时调度器退回
516
+ // 零基线(= 升级前行为)。
517
+ baselineSeed: store.lastDreamBaseline("auto"),
505
518
  // Issue #239(第 4 项)镜像到巩固:高峰期不做梦,顺延到最近的高峰结束时刻。
506
519
  peakHours: cfg.dreamPeakHours ?? "",
507
520
  peakMaxDeferMinutes: cfg.dreamPeakMaxDeferMinutes ?? 120,
package/src/inject.js CHANGED
@@ -274,9 +274,14 @@ export function createInjector(ctx, service, settings, config) {
274
274
  // 日志抢同一份预算后被降级」正是本议题要修的结构缺陷。单条仍有硬顶
275
275
  // (PINNED_CONTENT_MAX),超出照旧带截断提示,不静默。
276
276
  const pinnedCount = Math.max(0, Math.min(candidates.length, pinnedStats?.shown ?? 0));
277
+ // #24 块3:图召回线索行(graphHint)——引导语插在第一个线索行之前(保持块头
278
+ // 语义:先声明「这些不是事实」)。线索行自身按 graphHintLine 渲染(线索/ 前缀
279
+ // 区别于普通记忆行)。
280
+ let graphSeen = 0;
277
281
  for (let i = 0; i < candidates.length; i++) {
278
282
  const m = candidates[i];
279
283
  const pinned = i < pinnedCount;
284
+ if (m.graphHint === true) graphSeen++;
280
285
  // Epistemic trust (v0.4.5): when enabled, measured observations are
281
286
  // flagged so the agent can weigh them above guesses/opinions.
282
287
  const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
@@ -284,7 +289,13 @@ export function createInjector(ctx, service, settings, config) {
284
289
  : "";
285
290
  const title = STR.entryTitle[language](m.title, m.importance);
286
291
  const content = injectMemory(m, pinned ? PINNED_CONTENT_MAX : maxContent);
287
- const full = STR.entryLine[language](m.type, verified, title, content);
292
+ const full = m.graphHint === true
293
+ ? STR.graphHintLine[language](m.type, title, content)
294
+ : STR.entryLine[language](m.type, verified, title, content);
295
+ // 线索行引导语插在第一个线索行之前(保持块头语义:先声明「这些不是事实」)。
296
+ if (m.graphHint === true && graphSeen === 1) {
297
+ lines.push(STR.graphHintHeader[language]);
298
+ }
288
299
  if (pinned) {
289
300
  // pin 不扣块预算(上面那条设计注释的落地):pin 一条就够击穿 MAX_BLOCK
290
301
  // (PINNED_CONTENT_MAX 2000 > MAX_BLOCK 1500),照扣会把 budget 压成负数,
@@ -363,8 +374,9 @@ export function createInjector(ctx, service, settings, config) {
363
374
  const query = lastUserQuery(ctx);
364
375
  if (query) prefetchQueryVector(query);
365
376
  const queryVector = queryVectorCache.get(query);
366
- // v0.8.0 A3:scope 随请求解析(strict 开启时 injectCandidates 内硬过滤;
367
- // flag 关闭时解析器返回 null,注入行为不变)。
377
+ // v0.8.0 A3:scope 随请求解析(解析器恒返回对象,身份取不到时两维为
378
+ // null);硬过滤与软加权的门控都在 injectCandidates 内——strict 看
379
+ // strictScope,软加权看 scopeEnabled 且至少一维可解析(issue #339)。
368
380
  const scope = resolveSessionScope(ctx);
369
381
  // Issue #205:跨轮轮换——最近 N 个查询轮次注入过的 id 本轮不再优先。
370
382
  const sessionId = ctx?.agent?.session?.id ?? "_";
package/src/lang.js CHANGED
@@ -81,6 +81,16 @@ export const STR = {
81
81
  zh: (n) => `〔约束/偏好类另有 ${n} 条未展示〕`,
82
82
  en: (n) => `[${n} more constraint/preference entries not shown]`
83
83
  },
84
+ // Issue #24 块3:图召回线索行的引导语——正向声明「链路信息非事实断言」,
85
+ // 防 LLM 单次消费把桥接召回当有依据的事实回头扩散(幻觉诱导)。
86
+ graphHintHeader: {
87
+ zh: "[检索线索] 以下为实体图搜索的链路信息,仅供定位参考,非事实断言:",
88
+ en: "[Retrieval hints] Entity-graph link trails below are navigation aids, not factual assertions:"
89
+ },
90
+ graphHintLine: {
91
+ zh: (type, title, content) => `- [线索/${type}] ${title}:${content}`,
92
+ en: (type, title, content) => `- [hint/${type}] ${title}: ${content}`
93
+ },
84
94
  userSettingsHeader: {
85
95
  zh: "[用户设置] 来自 dsh-mneme 的用户画像与规则:",
86
96
  en: "[User settings] Profile and rules from dsh-mneme:"
@@ -0,0 +1,209 @@
1
+ // #164 A2:写入边界的密钥 / PII 判据。判据来源是 #164 A2(维护者 09-28 把认领转给
2
+ // 本侧),消费方是 #254 的写入准入——`write-admission.js` 从 #332 起就留了
3
+ // `sensitiveScan` 注入点,本模块是那个占位的实现。
4
+ //
5
+ // 为什么判据独立成文件、不写进 write-admission.js:判据的归属是 #164 A2,闸门的归属
6
+ // 是 #254。闸门只消费 `{kind, label}`(deny 面已在 #332 定死),判据自己既不认识
7
+ // 「会话预算」也不认识 `llm_audit_logs`——换一个判据(比如将来接更重的 PII 分类器)
8
+ // 只换注入的那一行。写入边界的另外两个出口(autoSummarize / dream 输出)要复用同一份
9
+ // 判据时也直接 import 本模块的 `scanSensitive`,不必各写一套形状。
10
+ //
11
+ // 三条判据口径(前两条是 #254 已定的硬约束,第三条是本模块自己的):
12
+ //
13
+ // 1. 零 LLM、纯确定性。写入路径在最上游,这里多花的时间会乘上每一次写入;EdgeMem
14
+ // (2609.05553)那句「能不用模型判定就不用」说的就是这一层。
15
+ //
16
+ // 2. 假阳率由负样本定。`test/helpers/write-admission-samples.js` 的 12 条负样本是
17
+ // #332 就配好的验收面,维护者把话说死了:「同一套负样本原样跑,抓错任何一条就不
18
+ // 算落地」。所以本模块的形状是**先认形状再认关键词**——纯关键词匹配在那组负样本
19
+ // 上全军覆没(「把 API key 放进环境变量」这类讨论句里一个凭据值都没有)。
20
+ //
21
+ // 3. 报最严重的那一类(`kind` 落审计)。同一个字符串可能同时像两类(`sk_live_` 前缀
22
+ // 既是 Stripe 的形状、也能被通用的 `sk-` 规则吃下),所以规则表按「越具体越靠前」
23
+ // 排,命中即返回。密钥在前、PII 在后:两者误杀面差一个量级(密钥串出现在正常项目
24
+ // 记忆里就是事故,邮箱 / 手机号完全可能是正当内容),同时命中时报更严重的那一类。
25
+ // `kind` 是稳定判据键(不是展示文案),enforce 打开前先按它看分布,将来要按类放行
26
+ // 也只改策略、不动判据。
27
+ //
28
+ // 已知边界(都是「宁漏不误杀」的取舍,不是遗漏):
29
+ // - 只扫文本(title / content / tags)。不扫路径、id、时间戳这类元数据字段——它们
30
+ // 由系统生成,不是用户写进来的内容,扫它们只会引入假阳。
31
+ // - 中文关键词(密码 / 令牌)不认。补进去会让「密码必须脱敏后再入库」这类讨论句
32
+ // 命中,而那正是负样本 group 的形状。要覆盖中文赋值得先设计「关键词语种 × 值形状」
33
+ // 的两维判据,不在本批。
34
+ // - 手机号只认大陆移动号段(1[3-9] + 9 位),固定电话与带国家码的写法不认。宽一位
35
+ // 就会把长度相近的订单号 / 内部编号吃进来,而 PII 这一档的误杀面已经比密钥大一档。
36
+ // - 银行卡号加 Luhn 校验:`0000000000000000`、`4111111111111112` 这类形状对但校验
37
+ // 不过的串不报。少了这道校验,任何 16 位数字串(订单号、时间戳拼接)都会命中。
38
+ // - 身份证同样加校验位(GB 11643 / ISO 7064 MOD 11-2):位数对但校验不过的 18 位
39
+ // 数字串不报。原先只有银行卡有校验、身份证没有,结果是 18 位纯数字先被身份证规则
40
+ // 命中,反倒绕过银行卡那条的 Luhn。
41
+ //
42
+ // 归一化:这里**不**用 content-hash.js 的 normalizeForHash。那套口径(NFKC → 小写 →
43
+ // 去标点)是为「只差格式的两条写入是否同一件事」定的,判据要的是原串的形状——大小写
44
+ // 是密钥 alphabet 的一部分(`AKIA` 与 `akia` 不是同一个值),去掉 `-` / `_` 会把 JWT
45
+ // 与 Slack token 的分段结构一起折没。两个口径别互换。
46
+
47
+ /** 判据命中的返回形状(与 `createWriteAdmission` 的 sensitiveScan 契约一致)。 */
48
+ // kind 是稳定键、label 是给人看的一行说明;两者都落 llm_audit_logs 的
49
+ // metadata.deny,所以别在其中塞运行时的值(命中的凭据本身绝不落盘 / 不回显)。
50
+ const SECRET_RULES = [
51
+ { kind: "aws_access_key", label: "AWS access key id", re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
52
+ // AWS 的 secret access key 没有前缀,只能靠赋值键认:`AWS_SECRET_ACCESS_KEY` /
53
+ // `aws_secret_access_key` 这个键名是它的形状。最早的一批 `secret` 关键词规则被
54
+ // 「必须在赋值号前」的位置要求挡在外面(多词键里 `secret` 后面跟的是 `_`,不是
55
+ // `:`/`=`),所以它得单独一条。40 位下限取 AWS 官方密钥的固定长度。
56
+ {
57
+ kind: "aws_secret_key",
58
+ label: "AWS secret access key",
59
+ // 键名不分大小写,所以挂 `/i` 而不是行内修饰符组 `(?i:...)`:后者是 ES2025 语法,
60
+ // CI 矩阵里的 Node 22 直接抛 SyntaxError(本文件其余规则也没有用它的)。
61
+ // 值那一半本来就是 `[A-Za-z0-9/+=]`,带上 `/i` 不改变大小写敏感度。
62
+ re: /(?:aws[_-]?secret[_-]?access[_-]?key)\s*[:=]\s*["']?([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])/i
63
+ },
64
+ { kind: "github_token", label: "GitHub token", re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b/ },
65
+ { kind: "slack_token", label: "Slack token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/ },
66
+ // PEM 头是明文私钥的确定标志,带不带正文都一样判——`BEGIN` 与 `PRIVATE KEY` 之间
67
+ // 可能有 `RSA` / `EC` / `OPENSSH`,所以中间那段是 [A-Z ]*。
68
+ { kind: "private_key", label: "PEM private key", re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
69
+ { kind: "jwt", label: "JSON Web Token", re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/ },
70
+ // scheme 与 userinfo 两段都加上界。scheme 那段的 `*` 作用在含 `.` 的字符类上,
71
+ // 一条长点分串(包名 / 路径 / 版本链)里每个起点都要一路回溯到结尾才发现没有
72
+ // `://` → 与 email 同源的 O(n²)(实测 120KB 对抗串里这条占 4.1 秒)。
73
+ // URL scheme 名本就短、`user:password` 也不会长到 64,上界只钉住回溯面,
74
+ // 真实连接串一条不少。
75
+ { kind: "connection_string", label: "credentials in URL", re: /\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s/:@]{1,64}:[^\s/:@]{6,}@/ },
76
+ // Stripe 排在通用 `sk-` 之前:`sk_live_…` 两条规则都吃,先到的那条决定 kind。
77
+ // 只认 sk_live_(生产密钥):sk_test_ 是公开测试密钥,报它是纯误杀。
78
+ { kind: "stripe_key", label: "Stripe secret key", re: /\bsk_live_[A-Za-z0-9]{16,}\b/ },
79
+ { kind: "npm_token", label: "npm auth token", re: /_authToken\s*=\s*[A-Za-z0-9_-]{20,}/ },
80
+ // 下限 24 而不是 20:这是一条纯收紧、不动语料读数的加固——OpenAI 的 key 没有校验
81
+ // 位,前缀 + 长度是唯一形状,20 位会把更长的假阳性面留在表里。`sk-` 后面跟短串的
82
+ // 赋值句仍会被赋值型那条认下(那是**对的**:值长了 8 位以上就该报)。
83
+ { kind: "openai_key", label: "OpenAI API key", re: /\bsk-(?:proj-)?[A-Za-z0-9_-]{24,}\b/ },
84
+ {
85
+ // 赋值型:最常见的一类,也是负样本组(占位符 / 环境变量 / 模板变量 / 只提关键词)
86
+ // 的主要靶子。判据是「关键词 + 赋值号 + 右边真的是个值的形状」,值本身不校验
87
+ // alphabet——凭据值没有通用形状,能通用的只有「它不像占位符」。
88
+ kind: "assigned_secret",
89
+ label: "assigned credential literal",
90
+ // 左边界不能把 `_` 排除在外:环境变量名正是拿 `_` 当分隔符,排除它会让
91
+ // `DB_PASSWORD=` / `MY_API_KEY=` / `MYSQL_PASSWORD=` 整类漏放(只有恰好落在
92
+ // 行首的 `API_KEY=` 能中)。放宽后 #332 那套 26 条语料(含 12 条负样本)全绿,
93
+ // 说明原写法不是语料换来的取舍。挡误杀的是下面那道占位符守卫,不是这个边界。
94
+ re: /(?:^|[^A-Za-z0-9])(?:password|passwd|pwd|secret|api[_-]?key|token)\b\s*[:=]\s*["']?([^\s"']{8,})/i,
95
+ // 占位符守卫:右边是尖括号占位、shell / 模板变量、环境变量读取、或一串 x / * / …
96
+ // 时不算命中。少这道守卫,`password: <redacted>` 与 `token: ${TOKEN}` 都会被报,
97
+ // 而它们正是「配置里该怎么写」的示例文本。
98
+ guard: (value) => !/^(?:<[^>]*>|\$\{|\$[A-Z_]+$|process\.env|redacted|xx+|\*+|\u2026)/i.test(value)
99
+ }
100
+ ];
101
+
102
+ const PII_RULES = [
103
+ {
104
+ kind: "email",
105
+ label: "email address",
106
+ // 先看 TLD 再看 `@`:反过来的 `(?:[A-Za-z]{2,}\.)+[A-Za-z]{2,}` 对
107
+ // `a@b.c.d.e` 这类可以回溯出指数条路径。
108
+ // local part 的 `+` 必须加上界。该字符类含 `.`,所以一条长点分串(包名 / 路径 /
109
+ // 版本链)后跟一个 `@` 时,每个起点都要重扫到那个 `@` 才失败 → 整体 O(n²)。
110
+ // 实测 120KB 对抗串 23.5 秒里这条占 18.6 秒,34KB 点分链要 0.6 秒;本判据在写入
111
+ // 路径上同步跑,等于把写入阻塞住。64 是 RFC 5321 给 local part 的上限,加上界
112
+ // 不缩检测面——放弃的只是长于 64 的非法形状。
113
+ re: /\b[A-Za-z0-9._%+-]{1,64}@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}\b/
114
+ },
115
+ { kind: "cn_mobile", label: "mainland mobile number", re: /(?<!\d)1[3-9]\d{9}(?!\d)/ },
116
+ { kind: "cn_id_card", label: "mainland ID number", re: /(?<![0-9A-Za-z])\d{17}[\dXx](?![0-9A-Za-z])/, cnId: true },
117
+ { kind: "bank_card", label: "payment card number", re: /(?<!\d)(?:\d{13,19})(?!\d)/, luhn: true }
118
+ ];
119
+
120
+ /**
121
+ * Luhn(模 10)校验。银行卡号这一档只靠位数与首字符形状会把所有 13–19 位数字串
122
+ * 都吃进来,而项目记忆里长度差不多的数字串(订单号、拼接的时间戳)很常见;校验位
123
+ * 是卡号自带的、零成本的第二道形状。负样本里没有卡号形状的串,这道校验是防未列举
124
+ * 的那一类(同时它也不影响正样本:4111111111111111 是 Luhn 通过的公开测试卡号)。
125
+ * @param {string} value 归一后的数字串(可能含分隔符)
126
+ */
127
+ function passesLuhn(value) {
128
+ const digits = value.replace(/\D/g, "");
129
+ if (digits.length < 13 || digits.length > 19) return false;
130
+ let sum = 0;
131
+ let double = false;
132
+ for (let i = digits.length - 1; i >= 0; i--) {
133
+ let d = digits.charCodeAt(i) - 48;
134
+ if (double) {
135
+ d *= 2;
136
+ if (d > 9) d -= 9;
137
+ }
138
+ sum += d;
139
+ double = !double;
140
+ }
141
+ return sum % 10 === 0;
142
+ }
143
+
144
+ // 大陆身份证校验位(GB 11643 / ISO 7064 MOD 11-2)。与银行卡的 Luhn 同理:18 位
145
+ // 数字串在项目记忆里很常见(订单号、内部编号、拼接时间戳),位数这个形状拦不住它们,
146
+ // 而校验位是身份证自带的、零成本的第二道形状。权重序列与余数映射都是标准值,别改。
147
+ const CN_ID_WEIGHTS = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
148
+ const CN_ID_CODES = "10X98765432";
149
+ /** @param {string} value 命中串(17 位数字 + 校验位,校验位可为 X) */
150
+ function passesCnId(value) {
151
+ if (!/^\d{17}[\dXx]$/.test(value)) return false;
152
+ let sum = 0;
153
+ for (let i = 0; i < 17; i++) sum += Number(value[i]) * CN_ID_WEIGHTS[i];
154
+ return CN_ID_CODES[sum % 11] === value[17].toUpperCase();
155
+ }
156
+
157
+ /**
158
+ * 扫一段文本里的密钥 / PII。命中返回 `{kind, label}`、未命中返回 null,不抛。
159
+ *
160
+ * 只认第一处命中(按规则表顺序 = 严重度顺序)。一次写入里出现第二条凭据时不再报——
161
+ * deny 面只记判据类别,报多条只是把同一件事写几遍。
162
+ * @param {unknown} value
163
+ * @returns {{kind: string, label: string}|null}
164
+ */
165
+ export function scanSensitive(value) {
166
+ const text = typeof value === "string" ? value : String(value ?? "");
167
+ if (!text) return null;
168
+ for (const rule of [...SECRET_RULES, ...PII_RULES]) {
169
+ const match = text.match(rule.re);
170
+ if (!match) continue;
171
+ // 守卫只看捕获组:没有捕获组的规则天然没有守卫。
172
+ if (rule.guard && !rule.guard(match[1] ?? "")) continue;
173
+ if (rule.luhn && !passesLuhn(match[0])) continue;
174
+ if (rule.cnId && !passesCnId(match[0])) continue;
175
+ return { kind: rule.kind, label: rule.label };
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /**
181
+ * 判据的两种调用面,共用同一份规则表:
182
+ * `scanSensitive(text)` — 任意文本,给写入边界之外的消费方(autoSummarize /
183
+ * dream 输出)直接调;它们手里是文本,不是记忆行。
184
+ * `createSensitiveScan({config})` — `write-admission.js` 的 `sensitiveScan` 契约,
185
+ * 入参是记忆对象、返回 `{kind, label}` 或 null。
186
+ *
187
+ * 开关在工厂里判一次:`sensitiveScanEnabled` 关时返回 null,闸门侧连函数都拿不到,
188
+ * 于是「第 1 级只跑空白 / 噪声」这条路与 #332 合并时**逐字段一致**(那一版根本没有
189
+ * 这个函数)。反过来,本键开着也不会自己去扫:唯一的调用点是闸门的 firstLevelHit,
190
+ * 而闸门要 `writeAdmission.enabled` 打开才走第 1 级判据。所以两个键是「闸门」与
191
+ * 「闸门内这一批判据」的关系,不是互为子开关——任一个关着,A2 都不产生任何判定。
192
+ * 分成两个键是为了能单独观察 A2 的命中分布(空白 / 噪声与密钥 / PII 的误杀面差一个
193
+ * 量级),不是为了让它能脱离闸门独立生效。
194
+ *
195
+ * @param {{config?: object}} [deps]
196
+ * @returns {((memory: object) => ({kind: string, label: string}|null))|null}
197
+ */
198
+ export function createSensitiveScan({ config } = {}) {
199
+ if (config?.sensitiveScanEnabled !== true) return null;
200
+ const scan = (memory) => {
201
+ const text = [memory?.title, memory?.content, ...(Array.isArray(memory?.tags) ? memory.tags : [])]
202
+ .filter((s) => typeof s === "string")
203
+ .join("\n");
204
+ return scanSensitive(text);
205
+ };
206
+ // 工厂只认「开 / 关」;enforce 由 write-admission 决定(命中即 deny 还是仅告警),
207
+ // 判据自己不碰决策——那一步在闸门里。两层分开就能先开检测看分布、再开拦截。
208
+ return scan;
209
+ }