@modusensus/dsh-mneme 0.8.0 → 0.8.2

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 (59) hide show
  1. package/README.md +15 -5
  2. package/lib/api-standalone.js +12 -0
  3. package/lib/api.js +52 -14
  4. package/lib/client.js +130 -8
  5. package/lib/config.js +8 -0
  6. package/lib/dream/decisions.js +55 -8
  7. package/lib/dream/sleep.js +79 -17
  8. package/lib/dream.js +61 -9
  9. package/lib/entities/extractor.js +2 -2
  10. package/lib/index.js +6 -0
  11. package/lib/lang.js +13 -2
  12. package/lib/local-embedder.js +9 -1
  13. package/lib/reranker.js +38 -8
  14. package/lib/scope.js +39 -4
  15. package/lib/service.js +121 -18
  16. package/lib/store.js +243 -40
  17. package/lib/summarize.js +2 -2
  18. package/lib/tools.js +64 -30
  19. package/lib/vector-index.js +2 -8
  20. package/lib/version-check.js +122 -0
  21. package/package.json +2 -1
  22. package/scripts/sync-test-badge.mjs +61 -0
  23. package/src/api-standalone.js +12 -0
  24. package/src/api.js +52 -14
  25. package/src/config.js +8 -0
  26. package/src/dream/decisions.js +55 -8
  27. package/src/dream/sleep.js +79 -17
  28. package/src/dream.js +61 -9
  29. package/src/entities/extractor.js +2 -2
  30. package/src/index.js +6 -0
  31. package/src/lang.js +13 -2
  32. package/src/local-embedder.js +9 -1
  33. package/src/reranker.js +38 -8
  34. package/src/scope.js +39 -4
  35. package/src/service.js +121 -18
  36. package/src/store.js +243 -40
  37. package/src/summarize.js +2 -2
  38. package/src/tools.js +64 -30
  39. package/src/vector-index.js +2 -8
  40. package/src/version-check.js +122 -0
  41. package/test/api.test.js +5 -0
  42. package/test/conflict-freeze.test.js +15 -5
  43. package/test/dream-archive-guardrail.test.js +116 -0
  44. package/test/dream-coverage-degrade.test.js +86 -0
  45. package/test/dream.test.js +15 -11
  46. package/test/inject-first-round-bm25.test.js +89 -0
  47. package/test/llm-message-source.test.js +177 -0
  48. package/test/reranker-single-logit.test.js +73 -0
  49. package/test/scope-candidates.test.js +239 -0
  50. package/test/scope-explicit.test.js +452 -0
  51. package/test/scope-storage.test.js +13 -5
  52. package/test/scope-strict.test.js +107 -41
  53. package/test/skip-invalid-restore.test.js +7 -5
  54. package/test/sleep-scheduler-rearm.test.js +89 -0
  55. package/test/sleep.test.js +2 -2
  56. package/test/standalone-api.test.js +34 -1
  57. package/test/store-vector-cache.test.js +98 -0
  58. package/test/tools-memory-get-schema.test.js +65 -0
  59. package/test/version-check.test.js +152 -0
@@ -56,14 +56,8 @@ export function createVectorIndex({ store, logger }) {
56
56
 
57
57
  /** Read one memory's cached vector; undefined when none/parse failure. */
58
58
  getEmbedding(id) {
59
- const row = db.prepare("SELECT embedding FROM memories WHERE id = ?").get(id);
60
- if (!row?.embedding) return undefined;
61
- try {
62
- const v = JSON.parse(row.embedding);
63
- return Array.isArray(v) && v.length ? v : undefined;
64
- } catch {
65
- return undefined;
66
- }
59
+ // Issue #202:走 store 的解析缓存(与 searchVector/getEmbeddings 同源)。
60
+ return store.getParsedEmbedding(id);
67
61
  },
68
62
 
69
63
  /** Cosine search over embedded rows; results carry a 0..1 score. */
@@ -0,0 +1,122 @@
1
+ // 版本自检(issue #174 后续,2026-09-15 拍板):独立插件不把「用户在用哪个
2
+ // 版本」托付给插件市场——市场收录有 ~26h 年龄闸门 + 30min 缓存,且安装时
3
+ // 精确指定过版本的 profile 会被 pnpm 钉子挡住(update 尊重既有 semver 范围,
4
+ // 永不跨 minor/major,#174 的报障者正是这样用着 0.7.32 的行为模型来报 bug)。
5
+ //
6
+ // 本模块只做三件事:
7
+ // 1. 向 npm registry 查 @modusensus/dsh-mneme 的 latest dist-tag(带 TTL
8
+ // 缓存 + 超时 + 全失败静默——离线/被墙/registry 异常都返回 null,调用方
9
+ // 据 null 渲染「未知」,前端不打扰);
10
+ // 2. 与运行版本做纯函数比对(classify);
11
+ // 3. 对外暴露 registry URL 白名单校验(validateRegistryUrl)——发请求前
12
+ // 强制 https + 精确 host,构造上排除本机与内网地址。
13
+ import { readFileSync } from "node:fs";
14
+
15
+ // 运行版本:src/ 与 lib/ 都在插件根下一层,相对 import.meta.url 解析一致;
16
+ // 读取失败(打包/受限环境)降级 "unknown",横幅随之静默。
17
+ const PACKAGE_VERSION = (() => {
18
+ try {
19
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version ?? "unknown";
20
+ } catch {
21
+ return "unknown";
22
+ }
23
+ })();
24
+
25
+ // registry 查询地址是模块常量而非用户输入;validateRegistryUrl 仍作为发请求
26
+ // 前的强制闸(构造上即排除非 https 与非白名单 host,双保险且可单测)。
27
+ const REGISTRY_URL = "https://registry.npmjs.org/@modusensus%2Fdsh-mneme/latest";
28
+ const REGISTRY_HOST = "registry.npmjs.org";
29
+ // 市场收录本身有 ~1 天年龄闸门,1h 的 registry 缓存远低于该粒度,足够新鲜。
30
+ const CACHE_TTL_MS = 60 * 60 * 1000;
31
+ const FETCH_TIMEOUT_MS = 5000;
32
+
33
+ // 精确 host 白名单:协议必须 https,且 host 逐字等于 registry.npmjs.org。
34
+ // 这一条即构造性排除本机回环、私有网段与保留地址——不做任何
35
+ // 「看起来像公网」的宽松判断,将来换源必须显式改这里的常量。
36
+ export function validateRegistryUrl(candidate) {
37
+ let url;
38
+ try {
39
+ url = new URL(candidate);
40
+ } catch {
41
+ return false;
42
+ }
43
+ return url.protocol === "https:" && url.hostname === REGISTRY_HOST;
44
+ }
45
+
46
+ /** 解析 `x.y.z` / `x.y.z-后缀` 为可比较结构;解析失败返回 null。 */
47
+ function parseVersion(text) {
48
+ if (typeof text !== "string") return null;
49
+ const match = text.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
50
+ if (!match) return null;
51
+ return {
52
+ major: Number(match[1]),
53
+ minor: Number(match[2]),
54
+ patch: Number(match[3]),
55
+ // 有 prerelease 后缀的同号版本视为更旧(0.9.0-rc.1 < 0.9.0)。
56
+ prerelease: match[4] !== undefined
57
+ };
58
+ }
59
+
60
+ /**
61
+ * 三元组语义化比较:a<b → -1,a>b → 1,无法比较 → null(调用方归入 unknown)。
62
+ * 仅比较数字部分;数字相等时,带 prerelease 的一方更旧(0.9.0-rc.1 < 0.9.0),
63
+ * 两侧都带则视为同版——横幅只关心「是否落后于 latest」,不追求完整 semver 序。
64
+ */
65
+ export function compareVersions(a, b) {
66
+ const va = parseVersion(a);
67
+ const vb = parseVersion(b);
68
+ if (!va || !vb) return null;
69
+ for (const key of ["major", "minor", "patch"]) {
70
+ if (va[key] !== vb[key]) return va[key] < vb[key] ? -1 : 1;
71
+ }
72
+ if (va.prerelease !== vb.prerelease) return va.prerelease ? -1 : 1;
73
+ return 0;
74
+ }
75
+
76
+ /**
77
+ * 运行版本 vs registry latest 的展示归类。latest 为 null(查询失败/离线)
78
+ * 或任一侧解析失败时归 unknown——前端对 unknown 完全静默。
79
+ */
80
+ export function classify(version, latest) {
81
+ const cmp = compareVersions(version, latest);
82
+ if (cmp === null) return "unknown";
83
+ if (cmp < 0) return "outdated";
84
+ if (cmp > 0) return "ahead";
85
+ return "up-to-date";
86
+ }
87
+
88
+ // 模块级缓存:面板可能多处/多次拉取,TTL 内一律复用,不重复打 registry。
89
+ // at 用 -Infinity 作「从未拉取」哨兵:任何时钟下 now-at 都是正无穷,首轮
90
+ // 必然真实请求(测试的假时钟从 0 起也不会被误判成新鲜缓存)。
91
+ let cache = { at: -Infinity, latest: null };
92
+
93
+ /**
94
+ * 查询 registry latest。TTL 内直接命中缓存;任何失败(网络/超时/非 2xx/
95
+ * 响应形状不对/URL 校验不过)都静默返回 null——版本提示是锦上添花,绝不
96
+ * 让它成为新的故障面。失败不写缓存:TTL 起点保持旧值,下次调用立刻重试。
97
+ */
98
+ export async function fetchLatestVersion({ fetchImpl = typeof fetch === "function" ? fetch : () => Promise.reject(new Error("no fetch")), now = Date.now } = {}) {
99
+ if (now() - cache.at < CACHE_TTL_MS) return cache.latest;
100
+ if (!validateRegistryUrl(REGISTRY_URL)) return null;
101
+ let manifest;
102
+ try {
103
+ const response = await fetchImpl(REGISTRY_URL, {
104
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
105
+ headers: { accept: "application/json" }
106
+ });
107
+ if (!response.ok) return null;
108
+ manifest = await response.json();
109
+ } catch {
110
+ return null;
111
+ }
112
+ const latest = typeof manifest?.version === "string" && manifest.version ? manifest.version : null;
113
+ cache = { at: now(), latest };
114
+ return latest;
115
+ }
116
+
117
+ /** 仅供测试:清空模块级缓存与时间戳。 */
118
+ export function resetCacheForTest() {
119
+ cache = { at: -Infinity, latest: null };
120
+ }
121
+
122
+ export { PACKAGE_VERSION, REGISTRY_URL, CACHE_TTL_MS };
package/test/api.test.js CHANGED
@@ -1394,6 +1394,11 @@ test("POST /api/dsh-mneme/test-model succeeds and reports reply + latency", asyn
1394
1394
  assert.equal(data.modelId, "deepseek:deepseek-chat", "modelId reports the probed route");
1395
1395
  assert.equal(MOCK_LLM.lastOptions.provider, "deepseek");
1396
1396
  assert.equal(MOCK_LLM.lastOptions.purpose, "dsh-mneme-connectivity-test");
1397
+ // 回归:探测必须是一条 user 消息(带 source)。system-only 对话自
1398
+ // 0.1.6-alpha.1 起被官方 API 整单拒绝(「messages: at least one message
1399
+ // is required」),探测按钮会 502。
1400
+ assert.equal(MOCK_LLM.lastOptions.messages[0].role, "user");
1401
+ assert.equal(MOCK_LLM.lastOptions.messages[0].source?.kind, "plugin");
1397
1402
  assert.equal("reasoningEffort" in MOCK_LLM.lastOptions, false, "no effort configured -> field omitted");
1398
1403
  });
1399
1404
 
@@ -111,13 +111,23 @@ test("store: countConflictPending 只统计未决行", () => {
111
111
  store.close();
112
112
  });
113
113
 
114
- test("store: 已解决的同一对后续可再次 pending", () => {
114
+ test("store: 已解决的同一对在内容变化后才可再次 pending(issue #170 复核项 4)", async () => {
115
115
  const store = openStore();
116
- const p1 = store.saveConflictPending({ memory_a: "a", memory_b: "b", reason: "r" });
116
+ const a = store.save({ type: "project", title: "对A", content: "内容A" });
117
+ const b = store.save({ type: "project", title: "对B", content: "内容B" });
118
+ const p1 = store.saveConflictPending({ memory_a: a.id, memory_b: b.id, reason: "r" });
117
119
  store.resolveConflictPending(p1.id, { winner: "a" });
118
- // 去重只看未决行 —— 已解决后再现同一对应产生新 pending
119
- const p2 = store.saveConflictPending({ memory_a: "b", memory_b: "a", reason: "again" });
120
- assert.notEqual(p2.id, p1.id, "已解决行不参与去重");
120
+ // 内容未变 → 已裁决对不重新入队:「保留双方」是有效决定,不是待办。
121
+ const suppressed = store.saveConflictPending({ memory_a: b.id, memory_b: a.id, reason: "again" });
122
+ assert.equal(suppressed, undefined, "未变化的已裁决对被抑制");
123
+ assert.equal(store.countConflictPending(), 0);
124
+ // 任一侧被改过(updated_at 晚于 resolved_at)→ 重新入队产生新 pending。
125
+ // 留真实时间间隔:updated_at/resolved_at 毫秒精度,同毫秒算未变。
126
+ await new Promise((resolve) => setTimeout(resolve, 5));
127
+ store.update(a.id, { content: "内容A(改)" });
128
+ const p2 = store.saveConflictPending({ memory_a: b.id, memory_b: a.id, reason: "changed" });
129
+ assert.ok(p2, "内容变化后的对重新入队");
130
+ assert.notEqual(p2.id, p1.id, "新 pending 是新行");
121
131
  assert.equal(p2.resolved_at, undefined);
122
132
  assert.equal(store.countConflictPending(), 1);
123
133
  store.close();
@@ -0,0 +1,116 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createStore } from "../src/store.js";
4
+ import { createService } from "../src/service.js";
5
+ import { createDreamScheduler, validateDecisions } from "../src/dream.js";
6
+ import { mockCtx } from "./helpers/dream-mock.js";
7
+
8
+ // 回归(issue #104 方向 2):archive 决策语义越界 + 批量大扫除。
9
+ // 实测事故:一轮 12 条互不相关主题被批量 archive,LLM 自述理由是「价值判断」
10
+ // (对核心知识库长期参考价值较低、保持整洁和高信噪比),而提示词对 archive 的
11
+ // 定义是「重复或过时」;12 条中 8 条疑似误伤,含 rejected_solution ×2、
12
+ // constraint ×3、pitfall ×1 等长保留类型——这些类型的存在意义即长期保存,
13
+ // 误归档损失最大。修复:
14
+ // 1. 类型护栏——长保留类型(preference / pattern / rejected_solution /
15
+ // constraint / pitfall)的 archive 必须命中「重复/过时」类理由,否则单条
16
+ // 跳过记 skipped(run 记 degraded),绝不整单拒绝;
17
+ // 2. 批量上限——单轮 archive 条数封顶(dreamMaxArchivePerRun,默认 8),
18
+ // 与 update 上限同类的全局闸门:skipInvalid 也不豁免,超限整单拒绝;
19
+ // 3. 提示词同步强化(辅助防线)。
20
+ // conflict 裁决的败者归档不经过 archive action,不受护栏影响。
21
+
22
+ function snap(entries) {
23
+ return new Map(entries.map(([id, type]) => [id, { id, type, title: `t-${id}`, content: `c-${id}`, importance: 3, archived: false, forgotten: false }]));
24
+ }
25
+
26
+ // ---------------------------------------------------------- 类型护栏(纯函数)
27
+
28
+ test("#104-2: long-retention archive with a duplicate/outdated rationale passes", () => {
29
+ const s = snap([["p1", "preference"], ["rs1", "rejected_solution"]]);
30
+ const decisions = [
31
+ { action: "archive", ids: ["p1"], reason: "与后续偏好重复,已被新条目取代" },
32
+ { action: "archive", ids: ["rs1"], reason: "duplicate of an earlier rejected approach (stale)" }
33
+ ];
34
+ const { ok, skipped } = validateDecisions(decisions, s, { skipInvalid: true });
35
+ assert.equal(ok, true);
36
+ assert.deepEqual(skipped, [], "duplicate/outdated rationales are accepted");
37
+ });
38
+
39
+ test("#104-2: long-retention archive with a value-judgment rationale is skipped (run degrades)", () => {
40
+ const s = snap([["c1", "constraint"], ["k1", "project"]]);
41
+ const decisions = [
42
+ { action: "archive", ids: ["c1"], reason: "多为一次性调试细节,对核心知识库长期参考价值较低,保持整洁和高信噪比" },
43
+ { action: "archive", ids: ["k1"], reason: "价值较低" }
44
+ ];
45
+ const { ok, skipped } = validateDecisions(decisions, s, { skipInvalid: true });
46
+ assert.equal(ok, true, "guard skips the single decision instead of rejecting the run");
47
+ assert.equal(skipped.length, 1, "only the guarded long-retention archive is skipped");
48
+ assert.match(skipped[0].error, /long-retention type\(s\) constraint/);
49
+ assert.match(skipped[0].error, /duplicate\/outdated rationale/);
50
+ // 幸存列表:普通类型照常归档,c1 被跳过后由隐式 keep 补位
51
+ assert.deepEqual(decisions.map((d) => d.action), ["archive", "keep"]);
52
+ });
53
+
54
+ test("#104-2: plain-type archive needs no rationale keywords (guard boundary)", () => {
55
+ const s = snap([["d1", "decision"], ["f1", "factor"]]);
56
+ const decisions = [
57
+ { action: "archive", ids: ["d1"], reason: "阶段性结论,已沉淀进项目记忆" },
58
+ { action: "archive", ids: ["f1"], reason: "清理" }
59
+ ];
60
+ const { ok, skipped } = validateDecisions(decisions, s, { skipInvalid: true });
61
+ assert.equal(ok, true);
62
+ assert.deepEqual(skipped, [], "guard applies to long-retention types only");
63
+ });
64
+
65
+ test("#104-2: conflict-loser archive is exempt (adjudication, not archive action)", () => {
66
+ const s = snap([["w", "preference"], ["l", "preference"]]);
67
+ const decisions = [{ action: "conflict", winner: "w", loser: "l", reason: "内容矛盾,保留更新的信息" }];
68
+ const { ok, skipped } = validateDecisions(decisions, s, { skipInvalid: true });
69
+ assert.equal(ok, true);
70
+ assert.deepEqual(skipped, [], "conflict adjudication does not go through the archive guard");
71
+ });
72
+
73
+ // ---------------------------------------------------------- 批量上限(纯函数)
74
+
75
+ test("#104-2: archive count above the cap rejects the whole batch (global gate)", () => {
76
+ const entries = Array.from({ length: 10 }, (_, i) => [`d${i}`, "decision"]);
77
+ const s = snap(entries);
78
+ const decisions = entries.map(([id]) => ({ action: "archive", ids: [id], reason: "stale" }));
79
+ const { ok, errors } = validateDecisions(decisions, s, { skipInvalid: true });
80
+ assert.equal(ok, false, "9 archives > default cap 8 → reject even under skipInvalid");
81
+ assert.ok(errors.some((e) => e.includes("too many archive decisions")), `cap error present, got: ${errors.join("; ")}`);
82
+ });
83
+
84
+ test("#104-2: archive cap is configurable", () => {
85
+ const entries = Array.from({ length: 10 }, (_, i) => [`d${i}`, "decision"]);
86
+ const s = snap(entries);
87
+ const decisions = entries.map(([id]) => ({ action: "archive", ids: [id], reason: "stale" }));
88
+ const { ok, errors } = validateDecisions(decisions, s, { skipInvalid: true, maxArchivePerRun: 20 });
89
+ assert.equal(ok, true, `raised cap lets the sweep through, got: ${errors.join("; ")}`);
90
+ });
91
+
92
+ // ---------------------------------------------------------- 端到端(runDream)
93
+
94
+ test("#104-2: runDream skips a value-judgment archive of a long-retention type and lands the rest", async () => {
95
+ const store = createStore(":memory:");
96
+ const service = createService({ store, mirror: null, config: {} });
97
+ service.saveWithDedupe({ type: "project", title: "旧项目", content: "已完结并被取代", importance: 3 });
98
+ service.saveWithDedupe({ type: "constraint", title: "接口约束", content: "v1 接口只能串行调用", importance: 3 });
99
+ const ctx = mockCtx({
100
+ onConsolidation: (listText) => {
101
+ const entries = [...listText.matchAll(/id=([^\s|]+)\s*\|\s*type=(\w+)/g)].map((m) => ({ id: m[1], type: m[2] }));
102
+ const projectId = entries.find((e) => e.type === "project").id;
103
+ const constraintId = entries.find((e) => e.type === "constraint").id;
104
+ return JSON.stringify([
105
+ { action: "archive", ids: [projectId], reason: "重复或过时" },
106
+ { action: "archive", ids: [constraintId], reason: "保持知识库整洁,参考价值较低" }
107
+ ]);
108
+ }
109
+ });
110
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
111
+ const result = await dream.runDream(ctx, service, { dreamProvider: "deepseek", dreamModel: "deepseek-chat" });
112
+ assert.notEqual(result.status, "failed", "guard skips instead of failing the run");
113
+ const constraint = service.all().find((m) => m.type === "constraint");
114
+ assert.equal(constraint.archived, false, "value-judgment archive of a long-retention type must not land");
115
+ store.close();
116
+ });
@@ -0,0 +1,86 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createStore } from "../src/store.js";
4
+ import { createService } from "../src/service.js";
5
+ import { createDreamScheduler, validateDecisions } from "../src/dream.js";
6
+ import { mockCtx } from "./helpers/dream-mock.js";
7
+
8
+ // 回归(issue #104 方向 1):dreamMinExplicitCoverage 覆盖率护栏误伤「挑重点」
9
+ // 型输出。提示词明文要求「无问题的条目无需输出」(lang.js 硬性规则),模型
10
+ // 只显式决策少数条目是提示词要求的行为;但护栏把显式覆盖率 < 下限判成
11
+ // 「截断 → 隐式 keep 洗白」整单拒绝——heptaspirit 实测官方路由 + 强模型也
12
+ // 天天命中(81 轮 failed 全是 coverage,applied=0,LLM 调用本身已成功)。
13
+ // 修复:coverage 不足降级为 degraded(合法子集照常应用 + 未提及条目隐式
14
+ // keep),降级理由落库 outcome.degradations;护栏以状态暴露而非一票否决。
15
+ // 明确异常信号(create 上限等)保持整单拒绝不变;dreamImplicitKeep=false 的
16
+ // 严格模式不受影响。
17
+
18
+ function snapshot(ids, type = "project") {
19
+ return new Map(ids.map((id, i) => [id, { id, type, title: `t${i}`, content: `c${i}`, importance: 3, archived: false, forgotten: false }]));
20
+ }
21
+
22
+ // ---------------------------------------------------------- validateDecisions
23
+
24
+ test("#104-1: coverage shortfall degrades — ok:true + reason surfaced, implicit keeps fill", () => {
25
+ const snap = snapshot(["a", "b", "c", "d"]);
26
+ const decisions = [{ action: "update", ids: ["a"], title: "t-new", content: "c-new" }];
27
+ const { ok, errors, coverageShortfall } = validateDecisions(decisions, snap, {
28
+ dreamImplicitKeep: true,
29
+ dreamMinExplicitCoverage: 0.5,
30
+ skipInvalid: true
31
+ });
32
+ assert.equal(ok, true, "valid subset is applied instead of whole-order rejection");
33
+ assert.deepEqual(errors, [], "coverage shortfall is not a per-decision error");
34
+ assert.match(String(coverageShortfall), /coverage/, "degradation reason surfaced for audit");
35
+ assert.equal(decisions.length, 4, "unclaimed ids filled with implicit keeps");
36
+ });
37
+
38
+ test("#104-1: sufficient coverage carries no shortfall marker", () => {
39
+ const snap = snapshot(["a", "b"]);
40
+ const decisions = [{ action: "archive", ids: ["a"], reason: "stale" }, { action: "keep", ids: ["b"] }];
41
+ const { ok, coverageShortfall } = validateDecisions(decisions, snap, {
42
+ dreamImplicitKeep: true,
43
+ dreamMinExplicitCoverage: 0.5
44
+ });
45
+ assert.equal(ok, true);
46
+ assert.equal(coverageShortfall ?? null, null);
47
+ });
48
+
49
+ test("#104-1: strict mode (implicitKeep=false) unchanged — missing ids still reject", () => {
50
+ const snap = snapshot(["a", "b"]);
51
+ const decisions = [{ action: "keep", ids: ["a"] }];
52
+ const { ok } = validateDecisions(decisions, snap, { dreamImplicitKeep: false });
53
+ assert.equal(ok, false, "strict mode keeps whole-order rejection");
54
+ });
55
+
56
+ // ---------------------------------------------------------- runDream 端到端
57
+
58
+ test("#104-1: runDream records degraded (not failed) with the coverage reason in the run row", async () => {
59
+ const store = createStore(":memory:");
60
+ const service = createService({ store, mirror: null, config: {} });
61
+ for (let i = 0; i < 20; i++) {
62
+ service.saveWithDedupe({ type: "project", title: `主题${i}`, content: `内容${i}`, importance: 3 });
63
+ }
64
+ // 只显式决策 1/20 = 5%(< 默认下限 50%)——提示词要求的「挑重点」形态
65
+ const ctx = mockCtx({
66
+ onConsolidation: (listText) => {
67
+ const ids = [...listText.matchAll(/id=([^\s|]+)\s*\|\s*type=(\w+)/g)].map((m) => m[1]);
68
+ return JSON.stringify([{ action: "archive", ids: [ids[0]], reason: "stale variant" }]);
69
+ }
70
+ });
71
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
72
+ const result = await dream.runDream(ctx, service, {
73
+ dreamProvider: "deepseek",
74
+ dreamModel: "deepseek-chat",
75
+ dreamMinExplicitCoverage: 0.5
76
+ });
77
+ assert.equal(result.status, "degraded", "coverage shortfall degrades the run, not rejects it");
78
+ assert.equal(result.ok, true, "valid subset absorbed — scheduler baseline advances");
79
+ assert.ok(result.applied >= 1, "the explicit decision was applied");
80
+
81
+ const run = store.listDreamRuns()[0];
82
+ assert.equal(run.status, "degraded");
83
+ const degradations = run.outcome?.degradations ?? [];
84
+ assert.ok(degradations.some((s) => String(s).includes("coverage")), "coverage reason persisted in outcome.degradations");
85
+ store.close();
86
+ });
@@ -789,8 +789,10 @@ test("autoDream with 650 memories: sliding window truncates snapshot + implicit
789
789
  dreamProvider: "deepseek", dreamModel: "deepseek-chat", dreamMaxSnapshotSize: 200,
790
790
  // mock only claims 20/200 = 10%; the implicit-keep coverage floor must be
791
791
  // lowered so this deliberate "tiny explicit claim" scenario still passes
792
- // (it exercises the window + keep-fill, not the coverage guard)
793
- dreamMinExplicitCoverage: 0.1
792
+ // (it exercises the window + keep-fill, not the coverage guard). Same for
793
+ // the archive cap: 20 mock archives exceed the default 8 — #104 方向 2.
794
+ dreamMinExplicitCoverage: 0.1,
795
+ dreamMaxArchivePerRun: 20
794
796
  });
795
797
  assert.equal(result.ok, true, "run succeeds instead of 677-error rejection");
796
798
  assert.ok(result.applied > 0, "archive decisions applied");
@@ -807,16 +809,18 @@ test("autoDream with 650 memories: sliding window truncates snapshot + implicit
807
809
 
808
810
  // --- v0.4.4 fix: 残缺输出防洗白(显式覆盖率下限) + 严格模式透传 --------------
809
811
 
810
- test("validateDecisions rejects a truncated output whose explicit coverage is below the floor", () => {
812
+ test("validateDecisions degrades a low-coverage valid output (Issue #104 方向 1)", () => {
811
813
  const snap = snapshot(["a", "b", "c", "d"]);
812
814
  const decisions = [{ action: "keep", ids: ["a"] }]; // claims 1/4 = 25%
813
- const { ok, errors } = validateDecisions(decisions, snap, { dreamMinExplicitCoverage: 0.5 });
814
- assert.equal(ok, false, "low explicit coverage rejects the whole list");
815
- assert.ok(
816
- errors.some((e) => e.includes("explicit decision coverage 25% < minimum 50%")),
817
- `coverage error present, got: ${errors.join("; ")}`
815
+ const { ok, errors, coverageShortfall } = validateDecisions(decisions, snap, { dreamMinExplicitCoverage: 0.5 });
816
+ assert.equal(ok, true, "valid subset applies — coverage shortfall degrades instead of rejecting");
817
+ assert.deepEqual(errors, [], "shortfall is not a per-decision error");
818
+ assert.match(
819
+ String(coverageShortfall),
820
+ /explicit decision coverage 25% < minimum 50%/,
821
+ `coverage reason surfaced, got: ${coverageShortfall}`
818
822
  );
819
- assert.equal(decisions.length, 1, "no keep-fill pushed on rejection (nothing washed white)");
823
+ assert.equal(decisions.length, 4, "implicit keeps fill the unclaimed ids");
820
824
  });
821
825
 
822
826
  test("validateDecisions covers the whole snapshot when explicit coverage meets the floor", () => {
@@ -1014,7 +1018,7 @@ test("validateDecisions skipInvalid: a single invalid decision is skipped, valid
1014
1018
  assert.ok(decisions.some((d) => d.action === "keep" && d.ids.includes("j")), "j auto-kept");
1015
1019
  });
1016
1020
 
1017
- test("validateDecisions skipInvalid: an all-invalid batch still rejects (coverage floor guards truncation)", () => {
1021
+ test("validateDecisions skipInvalid: an all-invalid batch still rejects (zero-survivor guard, #104 方向 1 重审后保留)", () => {
1018
1022
  const snap = new Map([
1019
1023
  ["p", { id: "p", type: "preference", title: "语言", content: "中文", importance: 3, archived: false, forgotten: false }],
1020
1024
  ["j", { id: "j", type: "project", title: "插件", content: "内容", importance: 3, archived: false, forgotten: false }],
@@ -1029,7 +1033,7 @@ test("validateDecisions skipInvalid: an all-invalid batch still rejects (coverag
1029
1033
  const { ok, errors, skipped } = validateDecisions(decisions, snap, { skipInvalid: true });
1030
1034
  assert.equal(ok, false, "no valid decisions left → whole batch rejected");
1031
1035
  assert.equal(skipped.length, 2);
1032
- assert.ok(errors.some((e) => e.includes("coverage")), "coverage error present");
1036
+ assert.ok(errors.some((e) => e.includes("nothing valid survived")), "zero-survivor guard error present");
1033
1037
  assert.equal(decisions.length, 2, "rejected batch left untouched (splice only on the success path)");
1034
1038
  });
1035
1039
 
@@ -0,0 +1,89 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createStore } from "../src/store.js";
4
+ import { createService } from "../src/service.js";
5
+ import { createVectorIndex } from "../src/vector-index.js";
6
+
7
+ // 回归(issue #198):注入渲染是同步的(宿主 systemPrompt 不支持异步 text),
8
+ // 查询向量只能异步 prefetch 给下一轮用——首轮 queryVectorCache 必 miss。
9
+ // 此时 injectCandidates 落到静态 priority 排序(summary > preference >
10
+ // importance×quality):老的高重要性 preference 会占满全部槽位,当前话题的
11
+ // decision/project 进不来(报告者库:427 活跃、29 条 imp=5 preference)。
12
+ // 修复:首轮同步兜底用 BM25 词法召回领位(纯进程内、无需向量);语义向量
13
+ // 命中时行为不变(向量 > 缓存召回 > BM25 > 静态排序)。
14
+
15
+ function setup(config = {}) {
16
+ const store = createStore(":memory:");
17
+ const service = createService({ store, mirror: null, config });
18
+ return { store, service };
19
+ }
20
+
21
+ // 与查询词法完全不相交的旧高价值 preference(双字组不重叠)
22
+ function seedStalePreferences(service, n = 8) {
23
+ const ids = [];
24
+ for (let i = 0; i < n; i++) {
25
+ ids.push(service.saveWithDedupe({
26
+ type: "preference",
27
+ title: `旧偏好条目${i}`,
28
+ content: `用户喜欢深色界面与紧凑排版,这是第${i}条历史偏好存档`
29
+ , importance: 5 }).memory.id);
30
+ }
31
+ return ids;
32
+ }
33
+
34
+ test("#198: first round (no vector) leads with BM25 topical hits, not stale preferences", () => {
35
+ const { service, store } = setup();
36
+ seedStalePreferences(service, 8);
37
+ const onTopic = service.saveWithDedupe({
38
+ type: "decision",
39
+ title: "夜航限流选型",
40
+ content: "决定采用令牌桶做夜航App的限流方案,阈值按用户等级分层",
41
+ importance: 3
42
+ }).memory;
43
+
44
+ const picked = service.injectCandidates({ query: "夜航App令牌桶限流方案怎么设计的", maxItems: 5, threshold: 3 });
45
+ assert.ok(picked.some((m) => m.id === onTopic.id), "on-topic decision must enter the first-round block");
46
+ assert.equal(picked[0].id, onTopic.id, "BM25 topical hit leads the block");
47
+ store.close();
48
+ });
49
+
50
+ test("#198: legacy static order is kept when bm25 is disabled", () => {
51
+ const { service, store } = setup({ bm25SearchEnabled: false });
52
+ seedStalePreferences(service, 8);
53
+ const onTopic = service.saveWithDedupe({
54
+ type: "decision",
55
+ title: "夜航限流选型",
56
+ content: "决定采用令牌桶做夜航App的限流方案,阈值按用户等级分层",
57
+ importance: 3
58
+ }).memory;
59
+
60
+ const picked = service.injectCandidates({ query: "夜航App令牌桶限流方案怎么设计的", maxItems: 5, threshold: 3 });
61
+ assert.ok(!picked.some((m) => m.id === onTopic.id), "bm25 off -> legacy static order (preferences fill the slots)");
62
+ store.close();
63
+ });
64
+
65
+ test("#198: vector hits still outrank BM25 when a queryVector is available", async () => {
66
+ const { service, store } = setup();
67
+ seedStalePreferences(service, 3);
68
+ // 词法与查询不相交、但向量命中的记忆:语义路径必须压过 BM25 词法路径。
69
+ const vectorHit = service.saveWithDedupe({
70
+ type: "project",
71
+ title: "星图渲染重构",
72
+ content: "星图渲染重构记录:绘制管线迁移与图层合并",
73
+ importance: 3
74
+ }).memory;
75
+ const bm25Hit = service.saveWithDedupe({
76
+ type: "decision",
77
+ title: "夜航限流选型",
78
+ content: "决定采用令牌桶做夜航App的限流方案,阈值按用户等级分层",
79
+ importance: 3
80
+ }).memory;
81
+ const vectorIndex = createVectorIndex({ store });
82
+ service.setVectorIndex(vectorIndex);
83
+ vectorIndex.saveEmbedding(vectorHit.id, [1, 0, 0]);
84
+
85
+ const picked = service.injectCandidates({ query: "夜航App令牌桶限流方案怎么设计的", maxItems: 5, threshold: 3, queryVector: [1, 0, 0] });
86
+ assert.equal(picked[0].id, vectorHit.id, "vector hit leads; BM25 only fills the gap when no vector");
87
+ assert.ok(picked.some((m) => m.id === bm25Hit.id), "BM25 hit still present among candidates");
88
+ store.close();
89
+ });