@modusensus/dsh-mneme 0.8.1 → 0.8.3

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 (58) hide show
  1. package/README.md +14 -3
  2. package/lib/api-standalone.js +12 -0
  3. package/lib/api.js +12 -2
  4. package/lib/client.js +5 -1
  5. package/lib/config.js +18 -0
  6. package/lib/dream/decisions.js +55 -8
  7. package/lib/dream/sleep.js +36 -5
  8. package/lib/dream.js +18 -7
  9. package/lib/entities/extractor.js +2 -2
  10. package/lib/index.js +8 -0
  11. package/lib/inject.js +43 -1
  12. package/lib/lang.js +2 -2
  13. package/lib/local-embedder.js +21 -1
  14. package/lib/reranker.js +47 -8
  15. package/lib/runtime/model-fetch.js +361 -0
  16. package/lib/service.js +37 -5
  17. package/lib/settings.js +1 -0
  18. package/lib/store.js +85 -25
  19. package/lib/summarize.js +2 -2
  20. package/lib/tools.js +6 -19
  21. package/lib/vector-index.js +2 -8
  22. package/package.json +2 -1
  23. package/scripts/sync-test-badge.mjs +61 -0
  24. package/src/api-standalone.js +12 -0
  25. package/src/api.js +12 -2
  26. package/src/config.js +18 -0
  27. package/src/dream/decisions.js +55 -8
  28. package/src/dream/sleep.js +36 -5
  29. package/src/dream.js +18 -7
  30. package/src/entities/extractor.js +2 -2
  31. package/src/index.js +8 -0
  32. package/src/inject.js +43 -1
  33. package/src/lang.js +2 -2
  34. package/src/local-embedder.js +21 -1
  35. package/src/reranker.js +47 -8
  36. package/src/runtime/model-fetch.js +361 -0
  37. package/src/service.js +37 -5
  38. package/src/settings.js +1 -0
  39. package/src/store.js +85 -25
  40. package/src/summarize.js +2 -2
  41. package/src/tools.js +6 -19
  42. package/src/vector-index.js +2 -8
  43. package/test/api.test.js +10 -4
  44. package/test/dream-archive-guardrail.test.js +116 -0
  45. package/test/dream-coverage-degrade.test.js +86 -0
  46. package/test/dream.test.js +15 -11
  47. package/test/inject-first-round-bm25.test.js +89 -0
  48. package/test/inject-rotation.test.js +161 -0
  49. package/test/llm-message-source.test.js +177 -0
  50. package/test/local-embedder.test.js +20 -0
  51. package/test/reranker-single-logit.test.js +73 -0
  52. package/test/runtime-model-fetch.test.js +348 -0
  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
package/src/tools.js CHANGED
@@ -39,6 +39,8 @@ const MEMORY_ITEM_SCHEMA = {
39
39
  updated_at: { type: "string", required: true }
40
40
  }
41
41
  };
42
+ // 导出供回归测试断言 memory_get 与共享 schema 同源(#184 防漂移护栏)。
43
+ export { MEMORY_ITEM_SCHEMA };
42
44
 
43
45
  // v0.8.0 A2:occurred 时间窗参数 → store 过滤选项(list/count 同口径);
44
46
  // 未传参返回空对象,既有调用方不受影响。(A3 复核:此处入参仅含 occurred 边界。)
@@ -277,25 +279,10 @@ export function createTools(ctx, service, config, embedder) {
277
279
  type: "object",
278
280
  additionalProperties: false,
279
281
  properties: {
280
- memory: {
281
- type: "object",
282
- additionalProperties: false,
283
- properties: {
284
- id: { type: "string", required: true },
285
- title: { type: "string", required: true },
286
- type: { type: "string", required: true },
287
- importance: { type: "integer", required: true },
288
- tags: { type: "array", items: { type: "string" } },
289
- content: { type: "string", required: true },
290
- source: { type: "string" },
291
- agent_scope: { type: "string" },
292
- workspace_scope: { type: "string" },
293
- sensitivity: { type: "string" },
294
- occurred_at: { type: "string" },
295
- created_at: { type: "string" },
296
- updated_at: { type: "string" }
297
- }
298
- }
282
+ // 与 memory_search / memory_list 共用同一份 item schema——DTO 由
283
+ // toApiList 统一产出,内联副本曾漏掉 v0.8.1 的 scope 来源三键,
284
+ // 任何被标注过的行都过不了 in-process 校验(#184)。
285
+ memory: MEMORY_ITEM_SCHEMA
299
286
  }
300
287
  },
301
288
  render: (_args, value) => {
@@ -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. */
package/test/api.test.js CHANGED
@@ -644,17 +644,18 @@ test("GET /api/dsh-mneme/features returns empty overrides and effective config d
644
644
  assert.equal(res.statusCode, 200);
645
645
  const data = JSON.parse(res.body);
646
646
  assert.deepEqual(data.overrides, {});
647
- // effective 覆盖全部 51 个白名单键(含 v0.7.20 heatEnabled、Issue #89 新增
647
+ // effective 覆盖全部 52 个白名单键(含 v0.7.20 heatEnabled、Issue #89 新增
648
648
  // dreamSkipInvalid/allowCrossTypeMerge/dreamMinIntervalMinutes、面板可调的
649
649
  // dreamMaxTokens、睡眠路由 sleepProvider/sleepModel、PR1 新增的
650
650
  // recallFusion/signalTransparency、issue #109 新增的实体抽取路由
651
651
  // entityExtractionProvider/entityExtractionModel/entityExtractionReasoning、
652
652
  // issue #127 新增的 summarize 五键、issue #126 新增的 sleepActionSet,
653
653
  // 以及 issue #125 新增的候选集三键、issue #17(v0.8.0 A1/A3)新增的
654
- // scopeEnabled/strictScope),未覆盖时取 bundle 配置的解析默认值;
654
+ // scopeEnabled/strictScope、issue #194 新增的 resilientModelDownload),
655
+ // 未覆盖时取 bundle 配置的解析默认值;
655
656
  // dreamProvider/dreamModel 无 schema 默认值(Config({}) 解析为 undefined),
656
- // 不编造给前端 → 53 - 2 = 51
657
- assert.equal(Object.keys(data.effective).length, 51);
657
+ // 不编造给前端 → 54 - 2 = 52
658
+ assert.equal(Object.keys(data.effective).length, 52);
658
659
  assert.equal(data.effective.dreamSkipInvalid, true);
659
660
  assert.equal(data.effective.allowCrossTypeMerge, false);
660
661
  assert.equal(data.effective.dreamMinIntervalMinutes, 0);
@@ -1394,6 +1395,11 @@ test("POST /api/dsh-mneme/test-model succeeds and reports reply + latency", asyn
1394
1395
  assert.equal(data.modelId, "deepseek:deepseek-chat", "modelId reports the probed route");
1395
1396
  assert.equal(MOCK_LLM.lastOptions.provider, "deepseek");
1396
1397
  assert.equal(MOCK_LLM.lastOptions.purpose, "dsh-mneme-connectivity-test");
1398
+ // 回归:探测必须是一条 user 消息(带 source)。system-only 对话自
1399
+ // 0.1.6-alpha.1 起被官方 API 整单拒绝(「messages: at least one message
1400
+ // is required」),探测按钮会 502。
1401
+ assert.equal(MOCK_LLM.lastOptions.messages[0].role, "user");
1402
+ assert.equal(MOCK_LLM.lastOptions.messages[0].source?.kind, "plugin");
1397
1403
  assert.equal("reasoningEffort" in MOCK_LLM.lastOptions, false, "no effort configured -> field omitted");
1398
1404
  });
1399
1405
 
@@ -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
+ });
@@ -0,0 +1,161 @@
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
+ import { createInjector } from "../src/inject.js";
7
+ import { createSettings } from "../src/settings.js";
8
+
9
+ // 回归(issue #205):注入位跨轮轮换。长会话(几十上百轮、注入位有限)中
10
+ // 同一批条目在相邻轮次反复出现——报告者 15.5 小时实测 86 次注入 93% 重复,
11
+ // 库总览一条 43/43 块全勤。新配置 injectRotationTurns(默认 0 = 关闭):
12
+ // 同一条记忆在最近 N 个「不同用户查询」轮次注入过后,本轮不再优先——
13
+ // 新鲜者前置、不足按原序回填(槽位数不变);同一查询的重复渲染(工具轮)
14
+ // 不推进窗口;会话边界自动重置。
15
+
16
+ function setup(configOver = {}) {
17
+ const store = createStore(":memory:");
18
+ const service = createService({ store, mirror: null, config: {} });
19
+ const settings = createSettings(store.db);
20
+ const contexts = [];
21
+ const ctx = {
22
+ systemPrompt: {
23
+ context(def) {
24
+ contexts.push(def);
25
+ return () => {};
26
+ }
27
+ }
28
+ };
29
+ const config = { maxInjectedItems: 2, importanceThreshold: 3, ...configOver };
30
+ createInjector(ctx, service, settings, config);
31
+ // 注入块是 contexts[0](memory),user-settings 是 contexts[1]
32
+ const render = (sessionId, query) => contexts[0].text({
33
+ agent: { session: { id: sessionId, snapshotEvents: () => query ? [
34
+ { type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: query }] } }
35
+ ] : [] } }
36
+ });
37
+ const titles = (text) => [...text.matchAll(/- \[([^\]]+)\] ([^((]*)/g)].map((m) => m[2].trim());
38
+ return { store, service, render, titles };
39
+ }
40
+
41
+ function seedMemories(service, n = 4) {
42
+ const saved = [];
43
+ for (let i = 0; i < n; i++) {
44
+ saved.push(service.saveWithDedupe({
45
+ type: "preference",
46
+ title: `偏好条目${i}`,
47
+ content: `第 ${i} 条独立的用户偏好内容,主题互不相同`,
48
+ importance: 5
49
+ }).memory);
50
+ }
51
+ return saved;
52
+ }
53
+
54
+ test("#205: default (rotation off) repeats the same entries across turns", () => {
55
+ const { store, service, render, titles } = setup({});
56
+ seedMemories(service, 4);
57
+ const turn1 = titles(render("s1", "第一个问题"));
58
+ const turn2 = titles(render("s1", "第二个问题"));
59
+ assert.equal(turn1.length, 2);
60
+ assert.deepEqual(turn1, turn2, "rotation off → same entries repeat (current behavior)");
61
+ store.close();
62
+ });
63
+
64
+ test("#205: rotation=1 swaps out previously injected entries, slots stay full", () => {
65
+ const { store, service, render, titles } = setup({ injectRotationTurns: 1 });
66
+ seedMemories(service, 4);
67
+ const turn1 = titles(render("s1", "第一个问题"));
68
+ const turn2 = titles(render("s1", "第二个问题"));
69
+ assert.equal(turn2.length, 2, "slots stay full");
70
+ for (const t of turn1) {
71
+ assert.ok(!turn2.includes(t), `previously injected "${t}" must rotate out`);
72
+ }
73
+ store.close();
74
+ });
75
+
76
+ test("#205: entry becomes eligible again after leaving the window", () => {
77
+ const { store, service, render, titles } = setup({ injectRotationTurns: 1 });
78
+ seedMemories(service, 4);
79
+ const turn1 = titles(render("s1", "q1"));
80
+ const turn2 = titles(render("s1", "q2")); // window = [q1] → turn1 条目被换下
81
+ const turn3 = titles(render("s1", "q3")); // window = [q2] → turn1 条目重新有资格
82
+ for (const t of turn2) assert.ok(!turn3.includes(t), `"${t}" (injected at turn2) rotates out at turn3`);
83
+ for (const t of turn1) assert.ok(turn3.includes(t), `"${t}" (turn1) is fresh again at turn3`);
84
+ store.close();
85
+ });
86
+
87
+ test("#205: repeated renders within the same query do not advance the window", () => {
88
+ const { store, service, render, titles } = setup({ injectRotationTurns: 1 });
89
+ seedMemories(service, 4);
90
+ const turn1a = titles(render("s1", "q1"));
91
+ const turn1b = titles(render("s1", "q1")); // 同一查询:工具调用轮,不推进
92
+ assert.deepEqual(turn1a, turn1b, "same query renders identically (window not advanced)");
93
+ const turn2 = titles(render("s1", "q2"));
94
+ for (const t of turn1a) assert.ok(!turn2.includes(t), "rotation happens on the next query only");
95
+ store.close();
96
+ });
97
+
98
+ test("#205: a new session starts fresh", () => {
99
+ const { store, service, render, titles } = setup({ injectRotationTurns: 1 });
100
+ seedMemories(service, 4);
101
+ const turn1 = titles(render("s1", "q1"));
102
+ const other = titles(render("s2", "q1")); // 新会话:历史为空
103
+ assert.deepEqual(other, turn1, "session boundary resets rotation history");
104
+ store.close();
105
+ });
106
+
107
+ test("#205: backfill keeps slots full when fresh candidates run out", () => {
108
+ const { store, service, render, titles } = setup({ injectRotationTurns: 1 });
109
+ seedMemories(service, 2); // 候选恰等于槽位
110
+ const turn1 = titles(render("s1", "q1"));
111
+ const turn2 = titles(render("s1", "q2"));
112
+ assert.equal(turn2.length, 2, "stale entries backfill when nothing fresh remains");
113
+ assert.deepEqual(turn1, turn2, "no fresh candidates → original selection returned");
114
+ store.close();
115
+ });
116
+
117
+ // 回归(issue #205 补测,报告者读码发现):轮换窗口需要 maxItems×(N+1) 张
118
+ // 不同的牌,但候选池各有硬上限——语义路径截在 maxItems×2、合并层也是
119
+ // maxItems×2。池子只有十来张时,窗口一开就把池子吃光、只剩回填:重复率的
120
+ // 结构性下限由池子大小决定,轮换本身越不出箱子。修复:rotateWindow > 0 时
121
+ // 池子按 maxItems×(N+1) 扩容(语义检索、bm25、合并层三处同步),无轮换时
122
+ // 保持既有上限不变。旧测试样本(4 条记忆 + 注入位 2 = 恰好 maxItems×2)
123
+ // 正好测不到这个边界——本用例刻意用 8 条 + 窗口 2 压过旧上限。
124
+ test("#205 补测: semantic pool grows with the rotation window (no forced repeats)", () => {
125
+ const store = createStore(":memory:");
126
+ const service = createService({ store, mirror: null, config: {} });
127
+ const vectorIndex = createVectorIndex({ store });
128
+ service.setVectorIndex(vectorIndex);
129
+ const ids = [];
130
+ for (let i = 0; i < 8; i++) {
131
+ const theta = i * 0.1; // 角度递增 → 与 query [1,0,0] 的余弦严格递减
132
+ const m = service.saveWithDedupe({
133
+ type: "preference",
134
+ title: `条目${i}`,
135
+ content: `第 ${i} 条,主题互不相同`,
136
+ importance: 5
137
+ }).memory;
138
+ vectorIndex.saveEmbedding(m.id, [Math.cos(theta), Math.sin(theta), 0]);
139
+ ids.push(m.id);
140
+ }
141
+
142
+ const call = (rotate, rotateWindow) => service.injectCandidates({
143
+ query: "q",
144
+ queryVector: [1, 0, 0],
145
+ maxItems: 2,
146
+ threshold: 3,
147
+ rotate,
148
+ rotateWindow
149
+ }).map((m) => m.id);
150
+
151
+ const turn1 = call(null, 2);
152
+ assert.deepEqual(turn1, [ids[0], ids[1]], "baseline: top-2 by cosine");
153
+ const turn2 = call(new Set(turn1), 2);
154
+ assert.deepEqual(turn2, [ids[2], ids[3]], "window 1: next two fresh");
155
+ // 窗口 2 = 前两轮的并集(真实流程里注入层会把最近 N 轮的 id 合成一个集合)
156
+ const turn3 = call(new Set([...turn1, ...turn2]), 2);
157
+ // 旧上限(maxItems×2 = 4)下池子只有 m0..m3,第三轮 fresh 为空 → 只能回填
158
+ // m0/m1(强制重复)。池子扩到 6 后,m4/m5 仍在箱内可被轮换换上来。
159
+ assert.deepEqual(turn3, [ids[4], ids[5]], "window 2: pool grew with the window, no forced repeat");
160
+ store.close();
161
+ });