@modusensus/dsh-mneme 0.2.3 → 0.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.
Files changed (48) hide show
  1. package/README.md +27 -9
  2. package/lib/api.js +54 -4
  3. package/lib/client.js +58 -14
  4. package/lib/config.js +14 -2
  5. package/lib/dream/decisions.js +174 -62
  6. package/lib/dream.js +30 -5
  7. package/lib/index.js +4 -2
  8. package/lib/mirror.js +7 -1
  9. package/lib/service.js +117 -3
  10. package/lib/store.js +40 -0
  11. package/lib/tools.js +47 -4
  12. package/package.json +3 -1
  13. package/scripts/benchmark-embed.js +201 -0
  14. package/scripts/benchmark-rerank.js +166 -0
  15. package/scripts/e2e-dsh.js +216 -0
  16. package/scripts/stress-dsh.js +255 -0
  17. package/scripts/sync-lib.js +47 -0
  18. package/src/api.js +54 -4
  19. package/src/config.js +14 -2
  20. package/src/dream/decisions.js +174 -62
  21. package/src/dream.js +30 -5
  22. package/src/index.js +4 -2
  23. package/src/mirror.js +7 -1
  24. package/src/service.js +117 -3
  25. package/src/store.js +40 -0
  26. package/src/tools.js +47 -4
  27. package/test/api.test.js +385 -0
  28. package/test/audit.test.js +290 -0
  29. package/test/client.test.js +26 -0
  30. package/test/clustering.test.js +100 -0
  31. package/test/commands.test.js +69 -0
  32. package/test/config.test.js +31 -0
  33. package/test/dream.test.js +526 -0
  34. package/test/helpers/dream-mock.js +82 -0
  35. package/test/inject.test.js +82 -0
  36. package/test/local-embedder.test.js +227 -0
  37. package/test/mirror.test.js +249 -0
  38. package/test/reflection.test.js +226 -0
  39. package/test/reranker.test.js +197 -0
  40. package/test/semantic.test.js +123 -0
  41. package/test/service-search.test.js +169 -0
  42. package/test/service.test.js +198 -0
  43. package/test/settings.test.js +101 -0
  44. package/test/store.test.js +293 -0
  45. package/test/stress.test.js +209 -0
  46. package/test/summarize.test.js +156 -0
  47. package/test/tools.test.js +265 -0
  48. package/test/vector-index.test.js +205 -0
@@ -0,0 +1,255 @@
1
+ // scripts/stress-dsh.js
2
+ // 压测:沿着三条轴线检验 dsh-mneme 的 autoDream 与存储在长会话、冲突、
3
+ // 并发压力下的表现。LLM 全部用确定性的 mock 决策,离线可跑、无需 API Key。
4
+ //
5
+ // 轴线 1 · 长会话检索:Recall@k(规范记忆能否被召回)与陈旧残留率
6
+ // 轴线 2 · 冲突裁决:可重放仲裁集 —— 仲裁正确率、确定性、审计/回放
7
+ // 轴线 3 · 多 Agent 并发:丢更新、重复合并、事务/崩溃恢复
8
+ //
9
+ // 运行:node scripts/stress-dsh.js
10
+ import { mkdtempSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { createStore } from "../src/store.js";
14
+ import { createService } from "../src/service.js";
15
+ import {
16
+ createDreamScheduler,
17
+ hashSnapshot,
18
+ parseReceipt
19
+ } from "../src/dream.js";
20
+ import { applyDecisions } from "../src/dream/decisions.js";
21
+ import {
22
+ sessionDecisions,
23
+ arbitrationDecisions,
24
+ mockCtx
25
+ } from "../test/helpers/dream-mock.js";
26
+
27
+ const pass = (ok) => (ok ? "✅" : "❌");
28
+
29
+ // ---------------------------------------------------------------- 轴线 1
30
+
31
+ async function axis1LongSessionRetrieval() {
32
+ console.log("【轴线 1】长会话检索:Recall@k 与陈旧残留率");
33
+ const topics = 20;
34
+ const rounds = 8;
35
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a1-"));
36
+ const store = createStore(join(dir, "memory.db"));
37
+ const service = createService({ store, mirror: null, config: {} });
38
+ const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
39
+ const ctx = mockCtx({ onConsolidation: sessionDecisions });
40
+
41
+ // 每个主题一条规范记忆(ground truth,importance 5)
42
+ const gt = [];
43
+ for (let t = 1; t <= topics; t++) {
44
+ const title = `主题${String(t).padStart(2, "0")}`;
45
+ const { memory } = service.saveWithDedupe({ type: "project", title, content: `${title} 的规范内容`, importance: 5 });
46
+ gt.push({ title, id: memory.id });
47
+ }
48
+ // 长会话:每轮追加同主题旧变体(importance 3)并触发一次 autoDream
49
+ for (let round = 1; round <= rounds; round++) {
50
+ for (let t = 1; t <= topics; t++) {
51
+ service.saveWithDedupe({
52
+ type: "project",
53
+ title: `主题${String(t).padStart(2, "0")}·变体${round}`,
54
+ content: `主题${t} 第${round}轮旧变体`,
55
+ importance: 3
56
+ });
57
+ }
58
+ await dream.runDream(ctx, service, {});
59
+ }
60
+
61
+ let hits5 = 0;
62
+ let hits10 = 0;
63
+ for (const { title, id } of gt) {
64
+ const k5 = service.search(title, { limit: 5 });
65
+ const k10 = service.search(title, { limit: 10 });
66
+ if (k5.some((m) => m.id === id)) hits5++;
67
+ if (k10.some((m) => m.id === id)) hits10++;
68
+ }
69
+ const recall5 = hits5 / topics;
70
+ const recall10 = hits10 / topics;
71
+
72
+ // 陈旧残留率 = 仍活跃的旧变体 / 全部旧变体(dream 应全部清掉 → 0)
73
+ const all = store.all();
74
+ const variants = all.filter((m) => m.type === "project" && m.title.includes("变体"));
75
+ const staleResidual = variants.filter((m) => !m.archived).length / variants.length;
76
+ const runs = store.listDreamRuns().length;
77
+
78
+ console.log(` 主题 ${topics} 个 × 变体 ${rounds} 轮 = ${topics * rounds} 条旧记忆,autoDream 触发 ${runs} 次`);
79
+ console.log(` ${pass(recall5 >= 0.95)} Recall@5 = ${(recall5 * 100).toFixed(1)}%(规范记忆 top5 召回)`);
80
+ console.log(` ${pass(recall10 >= 0.95)} Recall@10 = ${(recall10 * 100).toFixed(1)}%`);
81
+ console.log(` ${pass(staleResidual === 0)} 陈旧残留率 = ${(staleResidual * 100).toFixed(1)}%(理想 0%)`);
82
+ store.close();
83
+ return { recall5, recall10, staleResidual, runs };
84
+ }
85
+
86
+ // ---------------------------------------------------------------- 轴线 2
87
+
88
+ async function axis2ConflictArbitration() {
89
+ console.log("【轴线 2】冲突裁决:可重放仲裁集");
90
+ const sets = [
91
+ { key: "项目截止日期", winner: { type: "decision", title: "项目截止日期", content: "8月20日交付", importance: 5 }, loser: { type: "decision", title: "项目截止日期(旧)", content: "8月15日交付", importance: 3 } },
92
+ { key: "语言偏好", winner: { type: "preference", title: "语言偏好", content: "使用简体中文", importance: 5 }, loser: { type: "preference", title: "语言偏好(旧)", content: "使用繁体中文", importance: 2 } },
93
+ { key: "存储选型", winner: { type: "decision", title: "存储选型", content: "node:sqlite(零依赖)", importance: 5 }, loser: { type: "decision", title: "存储选型(旧)", content: "better-sqlite3(需编译)", importance: 3 } },
94
+ { key: "部署环境", winner: { type: "project", title: "部署环境", content: "生产环境 Node 24 + Windows Server", importance: 4 }, loser: { type: "project", title: "部署环境(旧)", content: "生产环境 Node 20 + Linux", importance: 2 } }
95
+ ];
96
+
97
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a2-"));
98
+ const store = createStore(join(dir, "memory.db"));
99
+ const service = createService({ store, mirror: null, config: {} });
100
+ const dream = createDreamScheduler({ onRun: () => Promise.resolve({ ok: true, skipped: true }) });
101
+ const ctx = mockCtx({ onConsolidation: arbitrationDecisions });
102
+
103
+ // 仲裁集入库(先败者后胜者,模拟旧信息先存、新信息后到)
104
+ for (const set of sets) {
105
+ service.saveWithDedupe({ ...set.loser });
106
+ service.saveWithDedupe({ ...set.winner });
107
+ }
108
+ const before = hashSnapshot(service.all().filter((m) => !m.archived && m.type !== "summary"));
109
+
110
+ // 跑一次裁决 → 审计 + receipt
111
+ const run1 = await dream.runDream(ctx, service, {});
112
+ console.log(` 裁决运行:${pass(run1.ok)}(applied=${run1.applied},receipt=${run1.receipt.slice(0, 40)}…)`);
113
+
114
+ // 正确性:胜者保留 + 败者归档 + 来源链注释
115
+ let arbOk = 0;
116
+ for (const set of sets) {
117
+ const winner = service.list({ type: set.winner.type }).find((m) => m.title === set.winner.title);
118
+ const loser = store.all().find((m) => m.title === set.loser.title);
119
+ if (winner && loser && loser.archived && winner.content.includes("已否决旧信息")) arbOk++;
120
+ }
121
+ const arbRate = arbOk / sets.length;
122
+ console.log(` ${pass(arbRate === 1)} 仲裁正确率 = ${(arbRate * 100).toFixed(0)}%(胜者保留 + 败者归档 + 来源链注释)`);
123
+
124
+ // 确定性:同一输入快照 → 同一决策。重跑前先把败者"复活"为原始状态。
125
+ const audit = store.getDreamRun(run1.runId);
126
+ const receipt = parseReceipt(audit.receipt);
127
+ console.log(` ${pass(!!receipt && receipt.status === "ok")} receipt 可解析,snapshot=${receipt.snapshotHash},输入 ${receipt.inputCount} 条`);
128
+ console.log(` ${pass(audit.outcome && Object.keys(audit.outcome.byId).length === sets.length * 2)} 审计 outcome 覆盖全部 ${sets.length * 2} 个仲裁对象`);
129
+
130
+ // 可重放:审计中的决策清单在同一 store 上重放 → 幂等(无副作用)
131
+ const winnerBefore = store.list({ type: sets[0].winner.type }).find((m) => m.title === sets[0].winner.title).content;
132
+ const replayed = applyDecisions(audit.decisions, service);
133
+ const winnerAfter = store.list({ type: sets[0].winner.type }).find((m) => m.title === sets[0].winner.title).content;
134
+ const idempotent = replayed.applied === 0 && winnerBefore === winnerAfter;
135
+ console.log(` ${pass(idempotent)} 决策清单重放幂等(repeat 无副作用,来源链不重复追加)`);
136
+ console.log(` ${pass(before.length === 64)} 快照哈希稳定(${before.length} hex 位)`);
137
+
138
+ const runs = store.listDreamRuns().length;
139
+ store.close();
140
+ return { arbRate, runs, idempotent };
141
+ }
142
+
143
+ // ---------------------------------------------------------------- 轴线 3
144
+
145
+ function bump(content) {
146
+ const m = content.match(/count=(\d+)/);
147
+ return `count=${m ? Number(m[1]) + 1 : 1}`;
148
+ }
149
+
150
+ async function axis3Concurrency() {
151
+ console.log("【轴线 3】多 Agent 并发:丢更新 / 重复合并 / 事务恢复");
152
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-stress-a3-"));
153
+ const path = join(dir, "memory.db");
154
+
155
+ // --- 重复合并:20 个 agent 并发保存同标题 → 最终只 1 条活跃
156
+ const sA = createStore(path);
157
+ const svA = createService({ store: sA, mirror: null, config: {} });
158
+ const agents = 20;
159
+ const writes = [];
160
+ for (let i = 0; i < agents; i++) {
161
+ writes.push(Promise.resolve().then(() => svA.saveWithDedupe({ type: "preference", title: "并发任务", content: `agent-${i}` })));
162
+ }
163
+ await Promise.all(writes);
164
+ const dupes = svA.list({ type: "preference", limit: 100 }).filter((m) => m.title === "并发任务");
165
+ const noDupes = dupes.length === 1;
166
+ console.log(` ${pass(noDupes)} 重复合并:${agents} 个 agent 同标题并发保存 → 活跃 ${dupes.length} 条(期望 1)`);
167
+
168
+ // --- 丢更新:CAS 原子递增(硬断言:陈旧版本必须被拒,增量不得丢失)
169
+ const sB = createStore(path);
170
+ const svB = createService({ store: sB, mirror: null, config: {} });
171
+ svA.saveWithDedupe({ type: "history", title: "计数器", content: "count=0", importance: 3 });
172
+ const counterId = svA.list({ type: "history" })[0].id;
173
+ svA.update(counterId, { content: "count=0" });
174
+ const baseline = svA.getById(counterId); // updated_at=T, count=0
175
+ // Agent A 持最新版本 → CAS 成功(count=1)
176
+ const aOk = svA.compareAndUpdate(counterId, baseline.updated_at, { content: bump(baseline.content) });
177
+ // Agent B 仍持过期版本 T → CAS 必须被拒;若被接受即丢更新
178
+ const bStale = svB.compareAndUpdate(counterId, baseline.updated_at, { content: bump("count=0") });
179
+ const casRejected = aOk !== undefined && bStale === undefined;
180
+ // B 重读最新值重试 → 两个 +1 都落地
181
+ if (bStale === undefined) {
182
+ const cur = svB.getById(counterId);
183
+ svB.compareAndUpdate(counterId, cur.updated_at, { content: bump(cur.content) });
184
+ }
185
+ const casResult = svB.getById(counterId).content;
186
+ const noLostUpdate = casRejected && casResult === "count=2";
187
+ console.log(` ${pass(noLostUpdate)} CAS 并发递增:陈旧版本被拒=${casRejected},重读重试后 → ${casResult}(期望 count=2,硬断言)`);
188
+ // 串行化修复(无 CAS 时的人工约定):写前重读最新值
189
+ svA.update(counterId, { content: "count=0" });
190
+ svA.update(counterId, { content: bump(svA.getById(counterId).content) });
191
+ svB.update(counterId, { content: bump(svB.getById(counterId).content) });
192
+ const fixedResult = svB.getById(counterId).content;
193
+ const fixed = fixedResult === "count=2";
194
+ console.log(` ${pass(fixed)} 串行重读修复:写前重读最新 → ${fixedResult}(期望 count=2)`);
195
+
196
+ // --- 多步原子性:事务中途抛错 → 全部回滚(硬断言,无半成品)
197
+ let txThrew = false;
198
+ try {
199
+ svB.transaction(() => {
200
+ svB.saveWithDedupe({ type: "project", title: "原子A", content: "x" });
201
+ svB.saveWithDedupe({ type: "project", title: "原子B", content: "y" });
202
+ throw new Error("boom");
203
+ });
204
+ } catch { txThrew = true; }
205
+ const allNow = svB.all();
206
+ const atomic = txThrew
207
+ && !allNow.some((m) => m.title === "原子A")
208
+ && !allNow.some((m) => m.title === "原子B");
209
+ console.log(` ${pass(atomic)} 多步原子性:事务中途抛错 → 原子A/原子B 全部回滚(期望均不存在,硬断言)`);
210
+
211
+ // --- 事务/崩溃恢复:已提交写入在异常后 + reopen 后完整保留
212
+ const svC = createService({ store: sB, mirror: null, config: {} }); // 复用同一文件连接
213
+ svC.saveWithDedupe({ type: "project", title: "已提交A", content: "x" });
214
+ svC.saveWithDedupe({ type: "project", title: "已提交B", content: "y" });
215
+ let threw = false;
216
+ try {
217
+ svC.update("nonexistent-id", { content: "boom" }); // store.update 对未知 id 抛错
218
+ } catch {
219
+ threw = true;
220
+ }
221
+ sA.close();
222
+ sB.close();
223
+ const sR = createStore(path); // 重新打开(模拟进程重启)
224
+ const recovered = sR.all();
225
+ const recoveryOk = threw
226
+ && recovered.some((m) => m.title === "已提交A")
227
+ && recovered.some((m) => m.title === "已提交B")
228
+ && recovered.some((m) => m.title === "计数器");
229
+ console.log(` ${pass(recoveryOk)} 事务恢复:中途异常后已提交写入不丢,reopen 后完整可读`);
230
+ console.log(` ${pass(recovered.filter((m) => m.title === "已提交A").length === 1)} 无半成品残留(已提交A 仅 1 条)`);
231
+
232
+ sR.close();
233
+ return { noDupes, noLostUpdate, atomic, fixed, recoveryOk };
234
+ }
235
+
236
+ // ---------------------------------------------------------------- 汇总
237
+
238
+ console.log("══════ dsh-mneme 压测:三条轴线 ══════");
239
+ console.log("");
240
+ const a1 = await axis1LongSessionRetrieval();
241
+ console.log("");
242
+ const a2 = await axis2ConflictArbitration();
243
+ console.log("");
244
+ const a3 = await axis3Concurrency();
245
+ console.log("");
246
+ console.log("══════ 压测汇总 ══════");
247
+ console.log(` 轴线1 长会话检索:Recall@5=${(a1.recall5 * 100).toFixed(1)}% Recall@10=${(a1.recall10 * 100).toFixed(1)}% 陈旧残留=${(a1.staleResidual * 100).toFixed(1)}% (${a1.runs} 次 autoDream 全部入审计)`);
248
+ console.log(` 轴线2 冲突裁决:仲裁正确率=${(a2.arbRate * 100).toFixed(0)}% 重放幂等=${a2.idempotent ? "是" : "否"}`);
249
+ console.log(` 轴线3 多 Agent 并发:去重=${a3.noDupes ? "✅" : "❌"} CAS无丢更新=${a3.noLostUpdate ? "✅" : "❌"} 多步原子=${a3.atomic ? "✅" : "❌"} 串行修复=${a3.fixed ? "✅" : "❌"} 崩溃恢复=${a3.recoveryOk ? "✅" : "❌"}`);
250
+ // 丢更新与多步原子性都是硬断言:任一失败 → 非零退出,绝不把风险标成通过
251
+ const allOk = a1.recall5 >= 0.95 && a1.staleResidual === 0 && a2.arbRate === 1 && a2.idempotent
252
+ && a3.noDupes && a3.noLostUpdate && a3.atomic && a3.fixed && a3.recoveryOk;
253
+ console.log(` 结论:${allOk ? "全部通过 ✅" : "存在失败项 ❌"}`);
254
+ console.log("══════ 压测结束 ══════");
255
+ process.exit(allOk ? 0 : 1);
@@ -0,0 +1,47 @@
1
+ // Sync the src/ tree into lib/ — the distributable consumed by DSH (package
2
+ // main is lib/index.js). lib/client.js (the Web panel bundle) is authored
3
+ // independently under lib/ and is left untouched: the sync only copies
4
+ // src -> lib, it never prunes lib-only files.
5
+ //
6
+ // Usage: npm run sync (also run automatically by `npm pack`/`npm publish`
7
+ // via the prepack hook, so a published tarball always ships a fresh lib/).
8
+ import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";
9
+ import { join, relative } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const root = join(fileURLToPath(new URL("..", import.meta.url)));
13
+ const srcDir = join(root, "src");
14
+ const libDir = join(root, "lib");
15
+
16
+ /** Recursively collect all files under a directory (sorted for stable output). */
17
+ function walk(dir) {
18
+ const out = [];
19
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
20
+ const full = join(dir, entry.name);
21
+ if (entry.isDirectory()) out.push(...walk(full));
22
+ else if (entry.isFile()) out.push(full);
23
+ }
24
+ return out;
25
+ }
26
+
27
+ let copied = 0;
28
+ mkdirSync(libDir, { recursive: true });
29
+
30
+ for (const file of walk(srcDir)) {
31
+ const rel = relative(srcDir, file);
32
+ const dest = join(libDir, rel);
33
+ mkdirSync(join(dest, ".."), { recursive: true });
34
+ cpSync(file, dest);
35
+ copied++;
36
+ console.log(`synced ${rel}`);
37
+ }
38
+
39
+ // Report lib-only files (authored separately, e.g. client.js) so drift is
40
+ // visible but never clobbered.
41
+ for (const file of walk(libDir)) {
42
+ const rel = relative(libDir, file);
43
+ if (!existsSync(join(srcDir, rel))) console.log(`kept ${rel} (lib-only, not pruned)`);
44
+ }
45
+
46
+ console.log(`\nSynced ${copied} file(s) from src/ to lib/.`);
47
+ if (!copied) process.exitCode = 1;
package/src/api.js CHANGED
@@ -1,10 +1,43 @@
1
1
  import { URL } from "node:url";
2
+ import { timingSafeEqual } from "node:crypto";
2
3
 
3
4
  function sendJson(res, status, payload) {
4
5
  res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
5
6
  res.end(JSON.stringify(payload));
6
7
  }
7
8
 
9
+ /**
10
+ * Mask an API key for client display: keep a recognizable prefix and suffix,
11
+ * hide the middle. Empty keys stay empty; short keys are fully hidden.
12
+ * The mask only exists in the API layer — storage keeps the real key.
13
+ */
14
+ function maskApiKey(key) {
15
+ if (!key) return "";
16
+ if (key.length <= 8) return "***";
17
+ return `${key.slice(0, 3)}***${key.slice(-4)}`;
18
+ }
19
+
20
+ /** True when the request carries the configured apiToken (or no token is set). */
21
+ function isAuthorized(req, apiToken) {
22
+ if (!apiToken) return true;
23
+ const raw = req.headers?.authorization ?? req.headers?.["x-dsh-mneme-token"] ?? "";
24
+ const token = raw.startsWith("Bearer ") ? raw.slice(7).trim() : raw.trim();
25
+ if (token === "" || token.length !== apiToken.length) return false;
26
+ // Constant-time comparison: avoid leaking the token via timing when the API
27
+ // is exposed beyond loopback.
28
+ return timingSafeEqual(Buffer.from(token), Buffer.from(apiToken));
29
+ }
30
+
31
+ /**
32
+ * Reject a request with 401 when auth is enabled and the token is missing or
33
+ * wrong. Returns true when the request may proceed.
34
+ */
35
+ function requireAuth(req, res, apiToken) {
36
+ if (isAuthorized(req, apiToken)) return true;
37
+ sendJson(res, 401, { error: "unauthorized" });
38
+ return false;
39
+ }
40
+
8
41
  /** Collect the request body as text (tolerant of empty/invalid bodies). */
9
42
  function readBody(req) {
10
43
  return new Promise((resolve) => {
@@ -23,7 +56,7 @@ function parseBody(text) {
23
56
  }
24
57
  }
25
58
 
26
- export function createApi(ctx, service, settings, commands, embedder, semantic = null) {
59
+ export function createApi(ctx, service, settings, commands, embedder, semantic = null, apiToken = "") {
27
60
  const disposers = [];
28
61
 
29
62
  // Ensure the service has an embedder when the API layer was handed one
@@ -113,6 +146,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
113
146
  handler(req, res) {
114
147
  try {
115
148
  if (req.method === "PUT" || req.method === "POST") {
149
+ if (!requireAuth(req, res, apiToken)) return;
116
150
  return readBody(req).then((text) => {
117
151
  const body = parseBody(text);
118
152
  settings.setProfile(typeof body.profile === "string" ? body.profile : "");
@@ -133,6 +167,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
133
167
  handler(req, res) {
134
168
  try {
135
169
  if (req.method === "PUT" || req.method === "POST") {
170
+ if (!requireAuth(req, res, apiToken)) return;
136
171
  return readBody(req).then((text) => {
137
172
  const body = parseBody(text);
138
173
  settings.setRules(Array.isArray(body.rules) ? body.rules : []);
@@ -152,19 +187,31 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
152
187
  path: "/api/dsh-mneme/vector-config",
153
188
  handler(req, res) {
154
189
  try {
190
+ // Secret-bearing endpoint: fully protected when apiToken is set.
191
+ if (!requireAuth(req, res, apiToken)) return;
155
192
  if (req.method === "PUT" || req.method === "POST") {
156
193
  return readBody(req).then((text) => {
157
194
  const body = parseBody(text);
195
+ // An empty apiKey, or one that already looks masked (round-trips
196
+ // through maskApiKey unchanged), means "keep the existing key".
197
+ // Only a fresh, unmasked key is treated as a real replacement.
198
+ const prev = settings.getVectorConfig();
199
+ const incoming = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
200
+ const isMaskedOrEmpty = incoming === "" || maskApiKey(incoming) === incoming;
201
+ const key = isMaskedOrEmpty
202
+ ? (prev?.apiKey ?? "")
203
+ : incoming;
158
204
  const cfg = settings.setVectorConfig({
159
205
  enabled: body.enabled,
160
206
  baseUrl: body.baseUrl,
161
- apiKey: body.apiKey,
207
+ apiKey: key,
162
208
  model: body.model
163
209
  });
164
- sendJson(res, 200, { config: cfg });
210
+ sendJson(res, 200, { config: { ...cfg, apiKey: maskApiKey(cfg.apiKey) } });
165
211
  });
166
212
  }
167
- sendJson(res, 200, { config: settings.getVectorConfig() ?? { enabled: false, baseUrl: "", apiKey: "", model: "" } });
213
+ const cfg = settings.getVectorConfig() ?? { enabled: false, baseUrl: "", apiKey: "", model: "" };
214
+ sendJson(res, 200, { config: { ...cfg, apiKey: maskApiKey(cfg.apiKey) } });
168
215
  } catch {
169
216
  sendJson(res, 500, { error: "internal" });
170
217
  }
@@ -177,6 +224,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
177
224
  path: "/api/dsh-mneme/vector-reindex",
178
225
  handler(req, res) {
179
226
  try {
227
+ if (!requireAuth(req, res, apiToken)) return;
180
228
  if (!embedder) {
181
229
  sendJson(res, 200, { indexed: 0, skipped: 0, error: "vector-unavailable" });
182
230
  return;
@@ -227,6 +275,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
227
275
  handler(req, res) {
228
276
  try {
229
277
  if (req.method === "POST") {
278
+ if (!requireAuth(req, res, apiToken)) return;
230
279
  return readBody(req).then((text) => {
231
280
  const body = parseBody(text);
232
281
  try {
@@ -242,6 +291,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
242
291
  });
243
292
  }
244
293
  if (req.method === "DELETE") {
294
+ if (!requireAuth(req, res, apiToken)) return;
245
295
  const url = new URL(req.url, "http://localhost");
246
296
  const id = url.searchParams.get("id");
247
297
  const removed = id ? commands.remove(id) : false;
package/src/config.js CHANGED
@@ -14,6 +14,15 @@ export const Config = z.object({
14
14
  dreamModel: z.string(),
15
15
  dreamMaxTokens: z.natural().min(256).max(32768).default(4096),
16
16
 
17
+ // --- API protection ------------------------------------------------------
18
+ // Optional shared token for the plugin's HTTP API. Empty (default) keeps
19
+ // the API open (DSH binds to 127.0.0.1 and has no built-in auth); when set,
20
+ // sensitive endpoints (vector-config, vector-reindex, and all write ops on
21
+ // profile/rules/commands) require `Authorization: Bearer <apiToken>` (or
22
+ // `X-DSH-Mneme-Token`). Read-only list/search/semantic stay open so the
23
+ // Web panel keeps working without the token.
24
+ apiToken: z.string(),
25
+
17
26
  // --- semantic: local embedding provider (v0.2) --------------------------
18
27
  // "openai" keeps the legacy external-API path (settings vector config);
19
28
  // "local" runs an ONNX model in-process; "ollama" calls a local Ollama.
@@ -40,8 +49,11 @@ export const Config = z.object({
40
49
  hybridSearchKeywordWeight: z.number().min(0).max(1).default(0.4),
41
50
 
42
51
  // --- semantic: rerank layer (v0.2) --------------------------------------
43
- rerankEnabled: z.boolean().default(true),
44
- rerankProvider: z.union([z.const("local"), z.const("none")]).default("local"),
52
+ // Opt-in by default (item ⑥): the local cross-encoder pulls in onnxruntime
53
+ // (transformers.js) at init, so a bare install must not load it. Only an
54
+ // explicit rerankEnabled=true + rerankProvider="local" constructs LocalReranker.
55
+ rerankEnabled: z.boolean().default(false),
56
+ rerankProvider: z.union([z.const("local"), z.const("none")]).default("none"),
45
57
  rerankModel: z.string().default("Xenova/bge-reranker-base"),
46
58
  rerankBatchSize: z.natural().min(1).max(64).default(8),
47
59
  rerankMaxCandidates: z.natural().min(5).max(100).default(30),