@modusensus/dsh-mneme 0.6.7 → 0.6.8

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 (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +463 -463
  3. package/cordis.patch.yml +15 -15
  4. package/lib/api.js +783 -783
  5. package/lib/client.js +1757 -1757
  6. package/lib/commands.js +64 -64
  7. package/lib/config.js +288 -288
  8. package/lib/dream/clustering.js +118 -118
  9. package/lib/dream/decisions.js +439 -439
  10. package/lib/dream/sleep.js +561 -554
  11. package/lib/dream/tag-extractor.js +156 -156
  12. package/lib/dream.js +935 -929
  13. package/lib/embedding.js +154 -154
  14. package/lib/entities/extractor.js +242 -242
  15. package/lib/hot-memory.js +53 -53
  16. package/lib/index.js +361 -361
  17. package/lib/inject.js +208 -208
  18. package/lib/local-embedder.js +282 -282
  19. package/lib/mirror.js +170 -170
  20. package/lib/parser/tag.js +59 -59
  21. package/lib/parser/wiki-link.js +38 -38
  22. package/lib/quality-filter.js +123 -123
  23. package/lib/reranker.js +218 -218
  24. package/lib/search/adaptive.js +22 -22
  25. package/lib/search/bm25.js +96 -96
  26. package/lib/search/tag-boost.js +61 -61
  27. package/lib/service.js +1726 -1726
  28. package/lib/settings.js +172 -172
  29. package/lib/store.js +2238 -2238
  30. package/lib/summarize.js +236 -236
  31. package/lib/tools.js +290 -290
  32. package/lib/vector-index.js +116 -116
  33. package/package.json +80 -80
  34. package/scripts/benchmark-embed.js +201 -201
  35. package/scripts/benchmark-recall.js +133 -133
  36. package/scripts/benchmark-rerank.js +166 -166
  37. package/scripts/e2e-dsh.js +218 -218
  38. package/scripts/stress-dsh.js +255 -255
  39. package/scripts/sync-lib.js +52 -52
  40. package/src/api.js +783 -783
  41. package/src/commands.js +64 -64
  42. package/src/config.js +288 -288
  43. package/src/dream/clustering.js +118 -118
  44. package/src/dream/decisions.js +439 -439
  45. package/src/dream/sleep.js +561 -554
  46. package/src/dream/tag-extractor.js +156 -156
  47. package/src/dream.js +935 -929
  48. package/src/embedding.js +154 -154
  49. package/src/entities/extractor.js +242 -242
  50. package/src/hot-memory.js +53 -53
  51. package/src/index.js +361 -361
  52. package/src/inject.js +208 -208
  53. package/src/local-embedder.js +282 -282
  54. package/src/mirror.js +170 -170
  55. package/src/parser/tag.js +59 -59
  56. package/src/parser/wiki-link.js +38 -38
  57. package/src/quality-filter.js +123 -123
  58. package/src/reranker.js +218 -218
  59. package/src/search/adaptive.js +22 -22
  60. package/src/search/bm25.js +96 -96
  61. package/src/search/tag-boost.js +61 -61
  62. package/src/service.js +1726 -1726
  63. package/src/settings.js +172 -172
  64. package/src/store.js +2238 -2238
  65. package/src/summarize.js +236 -236
  66. package/src/tools.js +290 -290
  67. package/src/vector-index.js +116 -116
  68. package/test/api.test.js +594 -594
  69. package/test/audit.test.js +448 -448
  70. package/test/benchmark.test.js +35 -35
  71. package/test/boundary-v0625.test.js +82 -82
  72. package/test/client.test.js +368 -368
  73. package/test/clustering.test.js +100 -100
  74. package/test/commands.test.js +69 -69
  75. package/test/config.test.js +50 -50
  76. package/test/conflict-freeze.test.js +290 -290
  77. package/test/directory.test.js +134 -134
  78. package/test/dream.test.js +903 -901
  79. package/test/entities.test.js +522 -522
  80. package/test/epistemic.test.js +298 -298
  81. package/test/fnew-0112.test.js +311 -311
  82. package/test/fnew-03.test.js +422 -422
  83. package/test/graph-api.test.js +175 -175
  84. package/test/helpers/dream-mock.js +82 -82
  85. package/test/hot-memory.test.js +174 -174
  86. package/test/inject.test.js +103 -103
  87. package/test/llm-audit.test.js +279 -279
  88. package/test/local-embedder.test.js +227 -227
  89. package/test/mirror-dirty.test.js +424 -424
  90. package/test/mirror-edit-digest.test.js +187 -187
  91. package/test/mirror-generation.test.js +499 -499
  92. package/test/mirror.test.js +249 -249
  93. package/test/normalize-decisions.test.js +120 -120
  94. package/test/peer-blockers.test.js +190 -190
  95. package/test/policy-epoch.test.js +259 -259
  96. package/test/provenance.test.js +103 -103
  97. package/test/quality-filter.test.js +118 -118
  98. package/test/reasoning-effort.test.js +199 -199
  99. package/test/recall-evals.test.js +235 -235
  100. package/test/recall-layer.test.js +315 -315
  101. package/test/receipt-chain.test.js +451 -451
  102. package/test/reflection.test.js +226 -226
  103. package/test/reranker.test.js +240 -240
  104. package/test/search-fusion.test.js +90 -90
  105. package/test/semantic.test.js +124 -124
  106. package/test/service-search.test.js +199 -199
  107. package/test/service.test.js +435 -435
  108. package/test/settings.test.js +118 -118
  109. package/test/sleep.test.js +365 -365
  110. package/test/store.test.js +436 -436
  111. package/test/stress.test.js +209 -209
  112. package/test/summarize.test.js +191 -191
  113. package/test/tag-boost.test.js +125 -125
  114. package/test/tag.test.js +312 -312
  115. package/test/tools.test.js +285 -285
  116. package/test/vector-index.test.js +221 -221
  117. package/test/wiki-link.test.js +332 -332
package/lib/config.js CHANGED
@@ -1,288 +1,288 @@
1
- import z from "@deepseek-ai/schemastery";
2
-
3
- export const Config = z.object({
4
- memoryDir: z.string().default("~/.dsh/memory"),
5
- autoInject: z.boolean().default(true),
6
- autoSummarize: z.boolean().default(true),
7
- // Session lifecycle (v0.6.0): when enabled, deleting/disposing a session also
8
- // archives every memory that was born in it (treating the session as a save
9
- // point — entries stay recoverable via memory_archive/restoreBySession).
10
- // Default OFF: legacy behavior, a disposed session leaves its memories active.
11
- sessionLifecycleEnabled: z.boolean().default(false),
12
- // Optional model override for summarization. When both are non-empty, they
13
- // take priority over the session's current model. Empty = use the session's
14
- // active provider/model (same as before).
15
- summarizeProvider: z.string().default(""),
16
- summarizeModel: z.string().default(""),
17
- maxInjectedItems: z.natural().min(1).max(20).default(5),
18
- importanceThreshold: z.natural().min(1).max(5).default(3),
19
- autoDream: z.boolean().default(true),
20
- dreamThresholdCount: z.natural().min(1).max(1000).default(10),
21
- dreamThresholdChars: z.natural().min(100).max(100000).default(5000),
22
- dreamDelayMs: z.natural().min(0).max(60000).default(2000),
23
- dreamProvider: z.string(),
24
- dreamModel: z.string(),
25
- dreamMaxTokens: z.natural().min(256).max(131072).default(8192),
26
- // Pass-through reasoning effort for dream's LLM calls. 'none' (default)
27
- // omits the field so the provider's own default applies; 'off' explicitly
28
- // disables thinking — REQUIRED for thinking-type models (deepseek-v4-flash
29
- // etc.) that would otherwise drain the whole token budget into reasoning and
30
- // return an empty body ("no json array in llm output"); low/medium/high are
31
- // forwarded verbatim to cap reasoning spend.
32
- dreamReasoningEffort: z.union([
33
- z.const("off"),
34
- z.const("low"),
35
- z.const("medium"),
36
- z.const("high"),
37
- z.const("none")
38
- ]).default("none"),
39
- // 滑动窗口上限(v0.4.4):autoDream 每次只对最近 dreamMaxSnapshotSize 条
40
- // 记忆做 consolidation。大记忆量下全量快照会把 LLM 输入撑爆(636 记忆 →
41
- // 677 "missing" errors、applied=0),窗口外的旧记忆不进 snapshot。
42
- dreamMaxSnapshotSize: z.natural().min(1).max(1000).default(200),
43
- // 隐式 keep(v0.4.4):LLM 未提及的 snapshot 记忆自动补 {action:"keep"},
44
- // 避免"未覆盖即全拒"白白浪费整轮 run。设为 false 时保留旧的严格校验
45
- // (未覆盖即拒绝整单)。
46
- dreamImplicitKeep: z.boolean().default(true),
47
- // 显式决策覆盖率下限(v0.4.4 fix):dreamImplicitKeep 开启时,LLM 输出被
48
- // 截断只显式 claim 少量 snapshot 记忆(claimed.size / snapshot.size < 该阈值)
49
- // → 整单拒绝,防止残缺输出被隐式 keep 洗白成 ok 后再被真实 apply。0-1,
50
- // 默认 0.5(至少显式覆盖一半 snapshot)。
51
- dreamMinExplicitCoverage: z.number().min(0).max(1).default(0.5),
52
- // Rule version for dream adjudication: when this bumps, older dream_runs
53
- // degrade to historical evidence (their receipts no longer drive live
54
- // decisions). Default 0 = no versioning in use yet.
55
- policyEpoch: z.natural().min(0).max(1000000).default(0),
56
-
57
- // --- API protection ------------------------------------------------------
58
- // Optional shared token for the plugin's HTTP API. Empty (default) keeps
59
- // the API open (DSH binds to 127.0.0.1 and has no built-in auth); when set,
60
- // sensitive endpoints (vector-config, vector-reindex, and all write ops on
61
- // profile/rules/commands) require `Authorization: Bearer <apiToken>` (or
62
- // `X-DSH-Mneme-Token`). Read-only list/search/semantic stay open so the
63
- // Web panel keeps working without the token.
64
- apiToken: z.string(),
65
-
66
- // --- semantic: local embedding provider (v0.2) --------------------------
67
- // "openai" keeps the legacy external-API path (settings vector config);
68
- // "local" runs an ONNX model in-process; "ollama" calls a local Ollama.
69
- embedProvider: z.union([z.const("openai"), z.const("local"), z.const("ollama")]).default("openai"),
70
-
71
- // Local ONNX embedder (transformers.js / onnxruntime).
72
- localEmbedModel: z.string().default("Xenova/bge-small-zh-v1.5"),
73
- localEmbedDimension: z.natural().default(512),
74
- localEmbedDevice: z.union([z.const("cpu"), z.const("gpu")]).default("cpu"),
75
- localEmbedBatchSize: z.natural().min(1).max(64).default(8),
76
-
77
- // Ollama embedder.
78
- ollamaBaseUrl: z.string().default("http://localhost:11434"),
79
- ollamaModel: z.string().default("nomic-embed-text"),
80
-
81
- // Model download/cache. When empty (default), models are cached under the
82
- // user-level path ~/.dsh/mneme/models (resolved in local-embedder/reranker);
83
- // a non-empty value is used verbatim.
84
- embedModelCacheDir: z.string().default(""),
85
- embedModelMirror: z.string().default("https://hf-mirror.com"),
86
-
87
- // Vector search tuning.
88
- vectorSearchTopK: z.natural().min(1).max(100).default(20),
89
- vectorSearchThreshold: z.number().min(0).max(1).default(0.65),
90
- hybridSearchVectorWeight: z.number().min(0).max(1).default(0.6),
91
- hybridSearchKeywordWeight: z.number().min(0).max(1).default(0.4),
92
- // Lazy auto-backfill of missing embeddings on boot (Bug2): when the vector
93
- // API is configured and rows still lack an embedding, the index is rebuilt
94
- // in the background after a short delay, rate-limited in batches. On by
95
- // default; set false to keep the backfill manual only.
96
- autoReindexOnBoot: z.boolean().default(true),
97
- // Semantic-first injection (Bug4): when enabled, injectCandidates with a
98
- // non-empty query recalls via the vector index first and falls back to the
99
- // rule-based pick to fill/dedupe. Empty query / no vector → legacy behavior.
100
- hybridInject: z.boolean().default(true),
101
-
102
- // --- recall optimization (v0.5.0) ----------------------------------------
103
- // BM25 third recall path beside vector + LIKE keyword (1.1): per-token IDF
104
- // scoring recalls rows whose query terms are scattered — identifiers, code
105
- // fragments, mixed CJK/ASCII — where substring LIKE cannot match.
106
- bm25SearchEnabled: z.boolean().default(true),
107
- // Query-aware vector cutoff (1.2) replacing the fixed 0.65: entity:/attr:
108
- // prefixes loosen to 0.5, short queries tighten to 0.7, long queries loosen
109
- // to 0.6, and a decisive top-1/top-5 score gap loosens to 0.5 so the tail
110
- // still reaches the reranker. Off = legacy fixed threshold behavior.
111
- adaptiveThresholdEnabled: z.boolean().default(true),
112
- // Session-scoped hot memory (1.3): the latest N dialogue rounds rendered
113
- // ahead of the long-term recall block — short-term context that never
114
- // enters the memory store.
115
- hotMemoryEnabled: z.boolean().default(true),
116
- hotMemoryRounds: z.natural().min(1).max(50).default(5),
117
- hotMemoryMaxTokens: z.natural().min(200).max(32000).default(2000),
118
- // Topic-ranked injection (2.2): when a query vector is available the whole
119
- // injection candidate list is re-ordered by similarity to the current
120
- // query instead of keeping the rule-based order.
121
- selectiveInjectEnabled: z.boolean().default(true),
122
- // Search-time semantic dedup (2.3): greedy pass over the merged candidate
123
- // list dropping rows whose embedding cosine-similarity to an already-kept
124
- // row exceeds the threshold — duplicates are filtered at recall time
125
- // instead of waiting for a dream consolidation. Opt-in aggressive mode:
126
- // small embedding models can collapse legitimately distinct rows, so the
127
- // default keeps every recalled row.
128
- searchSemanticDedup: z.boolean().default(false),
129
- searchSemanticDedupThreshold: z.number().min(0.5).max(1).default(0.95),
130
-
131
- // --- semantic: rerank layer (v0.2) --------------------------------------
132
- // Opt-in by default (item ⑥): the local cross-encoder pulls in onnxruntime
133
- // (transformers.js) at init, so a bare install must not load it. Only an
134
- // explicit rerankEnabled=true + rerankProvider="local" constructs LocalReranker.
135
- rerankEnabled: z.boolean().default(false),
136
- rerankProvider: z.union([z.const("local"), z.const("none")]).default("none"),
137
- rerankModel: z.string().default("Xenova/bge-reranker-base"),
138
- rerankBatchSize: z.natural().min(1).max(64).default(8),
139
- rerankMaxCandidates: z.natural().min(5).max(100).default(30),
140
- rerankScoreThreshold: z.number().min(0).max(1).default(0.1),
141
-
142
- // --- reflection: update decision + failure tracking (v0.2.1) ------------
143
- reflectionUpdateEnabled: z.boolean().default(true),
144
- reflectionFailureTracking: z.boolean().default(true),
145
- reflectionUpdateMaxPerRun: z.natural().min(0).max(5).default(2),
146
- reflectionUpdateMinAgeHours: z.natural().min(0).max(168).default(24),
147
-
148
- // --- conflict freeze: manual review for conflicting memories (v0.2.1) ---
149
- // Opt-in by default: when true, conflicting memories are not auto-merged
150
- // and are marked as pending manual review instead.
151
- conflictFreezeEnabled: z.boolean().default(false),
152
- // Maximum number of frozen conflicts to keep pending for manual review.
153
- conflictFreezeMaxPending: z.natural().min(1).max(1000).default(100),
154
-
155
- // --- entity gene (v0.3.0) -----------------------------------------------
156
- // Opt-in: when false (default) nothing in the pipeline extracts entities.
157
- // The storage layer (entities/entity_attrs/entity_relations tables + CRUD)
158
- // is always available regardless of this flag.
159
- entityExtractionEnabled: z.boolean().default(false),
160
- // Optional model override for entity extraction; empty = use the caller's
161
- // default provider/model.
162
- entityExtractionModel: z.string().default(""),
163
- // Cap on entities per extraction pass and attributes per entity.
164
- entityExtractionMaxEntities: z.natural().min(1).max(20).default(10),
165
- entityExtractionMaxAttrs: z.natural().min(1).max(50).default(20),
166
- // Prefix/semantic search over entity names (used by recall).
167
- entitySearchEnabled: z.boolean().default(true),
168
-
169
- // --- wiki-link: explicit cross-memory [[links]] (v0.6.1) ----------------
170
- // Opt-in, off by default. When enabled, saveWithDedupe/update fire-and-forget
171
- // a wiki-link resolution pass: [[target]] / [[显示|target]] markers in a
172
- // memory's content become links_to relations in entity_relations (idempotent,
173
- // deduped by the unique relation index). The storage layer + read APIs
174
- // (getBacklinks/getForwardLinks/resolveWikiLink) are always available
175
- // regardless of this flag.
176
- wikiLinkEnabled: z.boolean().default(false),
177
-
178
- // --- tag system (v0.6.2) ---------------------------------------------------
179
- // Opt-in: when autoTagEnabled is true, a light LLM pass runs after each
180
- // autoDream consolidation and extracts 1-3 tags per retained memory
181
- // (autoTagMaxPerRun bounds how many memories are tagged per run). The tag
182
- // storage layer (store.setMemoryTags/getMemoryTags + tag: search + mirror
183
- // `#tag` line) is always available regardless of this flag.
184
- autoTagEnabled: z.boolean().default(false),
185
- autoTagMaxPerRun: z.natural().min(1).max(100).default(10),
186
- // Manual tagging (service.setMemoryTags / memory tools) is on by default;
187
- // set false to disable the manual write path too.
188
- manualTagEnabled: z.boolean().default(true),
189
-
190
- // --- tag-weighted re-rank (v0.6.4) -------------------------------------
191
- // Opt-in: boost candidates whose tags overlap the query/session tags.
192
- tagBoostEnabled: z.boolean().default(false),
193
- tagBoostFactor: z.number().min(1).max(2).default(1.15),
194
- sessionTagBoostFactor: z.number().min(1).max(2).default(1.08),
195
-
196
- // --- sleep mode: idle-triggered deep maintenance (v0.4.0) ---------------
197
- // Opt-in, off by default. Unlike autoDream (threshold-triggered, lightweight)
198
- // sleep fires when the store has been quiet for sleepIdleMinutes and deep-
199
- // maintains the whole library: conflict resolution, archival demotion,
200
- // pattern discovery and entity relation completion. Abortable on user
201
- // activity, audited into dream_runs (run_type='sleep'), and serialized with
202
- // autoDream so the two never overlap.
203
- sleepModeEnabled: z.boolean().default(false),
204
- // Quiet window before a cycle fires (minutes).
205
- sleepIdleMinutes: z.natural().min(1).max(60).default(5),
206
- // Minimum gap between two sleep runs (hours) — a second idle window within
207
- // this interval does not retrigger.
208
- sleepMinIntervalHours: z.natural().min(1).max(168).default(8),
209
- // Conflict adjudication strictness:
210
- // gentle only high-confidence conflicts (threshold 0.92) are resolved
211
- // normal standard dream-level (threshold 0.85)
212
- // aggressive low-confidence pairs are also adjudicated (threshold 0.75)
213
- sleepConflictStrictness: z.union([
214
- z.const("gentle"),
215
- z.const("normal"),
216
- z.const("aggressive")
217
- ]).default("normal"),
218
- // Archival demotion tiering (days since last access):
219
- // >= sleepArchiveDays → shrink to summary, full body kept in _full_content
220
- // >= sleepCompressDays → archived outright (entity relations preserved)
221
- sleepArchiveDays: z.natural().min(7).max(365).default(30),
222
- sleepCompressDays: z.natural().min(7).max(365).default(90),
223
- // Pattern discovery scan window (most recent memories to scan).
224
- sleepPatternMinMemories: z.natural().min(10).max(1000).default(100),
225
- // How far back pattern discovery considers entity attr changes (days).
226
- sleepPatternLookbackDays: z.natural().min(1).max(90).default(30),
227
- // Max pattern memories minted per run (0 = disabled).
228
- sleepMaxPatternPerRun: z.natural().min(0).max(10).default(3),
229
- // Optional LLM route override for sleep's bulk passes (empty = use dream
230
- // route / agent default model).
231
- sleepProvider: z.string().default(""),
232
- sleepModel: z.string().default(""),
233
- // Pass-through reasoning effort for sleep's LLM passes, same semantics as
234
- // dreamReasoningEffort: 'none' (default) omits the field; 'off' explicitly
235
- // disables thinking (thinking-type models would burn the whole budget on
236
- // reasoning); low/medium/high are forwarded verbatim.
237
- sleepReasoningEffort: z.union([
238
- z.const("off"),
239
- z.const("low"),
240
- z.const("medium"),
241
- z.const("high"),
242
- z.const("none")
243
- ]).default("none"),
244
-
245
- // --- epistemic trust: memory source credibility (v0.4.5) -----------------
246
- // Distinguish memories by source: observation (measured / witnessed),
247
- // subjective (opinion / guess) and inferred (derived from other evidence).
248
- // Opt-in by default: when false (default) retrieval ranking, injection
249
- // marking and dream merge/conflict keepSource are untouched and
250
- // epistemic_status stays inert data (still written + inferred on save, just
251
- // never used to influence behavior).
252
- trustEpistemicWeighting: z.boolean().default(false),
253
-
254
- // --- memory quality filter (Bug7) ------------------------------------------
255
- // Heuristic gate on what deserves the injection/recall surface. When enabled,
256
- // saveWithDedupe scores each new memory after dedupe and before write:
257
- // score >= degradeThreshold (60) → stored normally
258
- // archiveThreshold (30) <= score < 60 → quality_score persisted and the
259
- // injection sort re-ranks by importance * quality_score/100 (degraded)
260
- // score < 30 → archived + tagged low_quality (still explicitly searchable)
261
- // Meta-memory markers, near-duplicates and repetitive filler lose points.
262
- memoryQualityFilter: z.object({
263
- enabled: z.boolean().default(true),
264
- archiveThreshold: z.natural().min(1).max(100).default(30),
265
- degradeThreshold: z.natural().min(1).max(100).default(60),
266
- minContentLength: z.natural().min(1).max(1000).default(10)
267
- }).default({}),
268
-
269
- // --- LLM audit trail (Bug8) ------------------------------------------------
270
- // Records every background LLM call (autoDream consolidation + summary,
271
- // autoSummarize compression) into llm_audit_logs: tokens, duration, status
272
- // and which trigger produced it. Failures are recorded as status=error and
273
- // never block the feature. retentionDays bounds the table: older rows are
274
- // purged on boot.
275
- llmAudit: z.object({
276
- enabled: z.boolean().default(true),
277
- retentionDays: z.natural().min(1).max(3650).default(90)
278
- }).default({}),
279
-
280
- // --- recall evaluation: test-result storage (v0.4.6, 方案 B) --------------
281
- // Separate retrieval evaluation snapshots from the production recall audit.
282
- // When false (default) evaluateRetrieval still computes precision/recall/mrr
283
- // and returns them to the caller, but writes nothing to recall_evals — the
284
- // eval table only grows when the operator opts in. Production searchMemories
285
- // audits to recall_runs and NEVER touches recall_evals, regardless of this
286
- // flag (production isolation is unconditional).
287
- evalPersistTestResults: z.boolean().default(false),
288
- });
1
+ import z from "@deepseek-ai/schemastery";
2
+
3
+ export const Config = z.object({
4
+ memoryDir: z.string().default("~/.dsh/memory"),
5
+ autoInject: z.boolean().default(true),
6
+ autoSummarize: z.boolean().default(true),
7
+ // Session lifecycle (v0.6.0): when enabled, deleting/disposing a session also
8
+ // archives every memory that was born in it (treating the session as a save
9
+ // point — entries stay recoverable via memory_archive/restoreBySession).
10
+ // Default OFF: legacy behavior, a disposed session leaves its memories active.
11
+ sessionLifecycleEnabled: z.boolean().default(false),
12
+ // Optional model override for summarization. When both are non-empty, they
13
+ // take priority over the session's current model. Empty = use the session's
14
+ // active provider/model (same as before).
15
+ summarizeProvider: z.string().default(""),
16
+ summarizeModel: z.string().default(""),
17
+ maxInjectedItems: z.natural().min(1).max(20).default(5),
18
+ importanceThreshold: z.natural().min(1).max(5).default(3),
19
+ autoDream: z.boolean().default(true),
20
+ dreamThresholdCount: z.natural().min(1).max(1000).default(10),
21
+ dreamThresholdChars: z.natural().min(100).max(100000).default(5000),
22
+ dreamDelayMs: z.natural().min(0).max(60000).default(2000),
23
+ dreamProvider: z.string(),
24
+ dreamModel: z.string(),
25
+ dreamMaxTokens: z.natural().min(256).max(131072).default(8192),
26
+ // Pass-through reasoning effort for dream's LLM calls. 'none' (default)
27
+ // omits the field so the provider's own default applies; 'off' explicitly
28
+ // disables thinking — REQUIRED for thinking-type models (deepseek-v4-flash
29
+ // etc.) that would otherwise drain the whole token budget into reasoning and
30
+ // return an empty body ("no json array in llm output"); low/medium/high are
31
+ // forwarded verbatim to cap reasoning spend.
32
+ dreamReasoningEffort: z.union([
33
+ z.const("off"),
34
+ z.const("low"),
35
+ z.const("medium"),
36
+ z.const("high"),
37
+ z.const("none")
38
+ ]).default("none"),
39
+ // 滑动窗口上限(v0.4.4):autoDream 每次只对最近 dreamMaxSnapshotSize 条
40
+ // 记忆做 consolidation。大记忆量下全量快照会把 LLM 输入撑爆(636 记忆 →
41
+ // 677 "missing" errors、applied=0),窗口外的旧记忆不进 snapshot。
42
+ dreamMaxSnapshotSize: z.natural().min(1).max(1000).default(200),
43
+ // 隐式 keep(v0.4.4):LLM 未提及的 snapshot 记忆自动补 {action:"keep"},
44
+ // 避免"未覆盖即全拒"白白浪费整轮 run。设为 false 时保留旧的严格校验
45
+ // (未覆盖即拒绝整单)。
46
+ dreamImplicitKeep: z.boolean().default(true),
47
+ // 显式决策覆盖率下限(v0.4.4 fix):dreamImplicitKeep 开启时,LLM 输出被
48
+ // 截断只显式 claim 少量 snapshot 记忆(claimed.size / snapshot.size < 该阈值)
49
+ // → 整单拒绝,防止残缺输出被隐式 keep 洗白成 ok 后再被真实 apply。0-1,
50
+ // 默认 0.5(至少显式覆盖一半 snapshot)。
51
+ dreamMinExplicitCoverage: z.number().min(0).max(1).default(0.5),
52
+ // Rule version for dream adjudication: when this bumps, older dream_runs
53
+ // degrade to historical evidence (their receipts no longer drive live
54
+ // decisions). Default 0 = no versioning in use yet.
55
+ policyEpoch: z.natural().min(0).max(1000000).default(0),
56
+
57
+ // --- API protection ------------------------------------------------------
58
+ // Optional shared token for the plugin's HTTP API. Empty (default) keeps
59
+ // the API open (DSH binds to 127.0.0.1 and has no built-in auth); when set,
60
+ // sensitive endpoints (vector-config, vector-reindex, and all write ops on
61
+ // profile/rules/commands) require `Authorization: Bearer <apiToken>` (or
62
+ // `X-DSH-Mneme-Token`). Read-only list/search/semantic stay open so the
63
+ // Web panel keeps working without the token.
64
+ apiToken: z.string(),
65
+
66
+ // --- semantic: local embedding provider (v0.2) --------------------------
67
+ // "openai" keeps the legacy external-API path (settings vector config);
68
+ // "local" runs an ONNX model in-process; "ollama" calls a local Ollama.
69
+ embedProvider: z.union([z.const("openai"), z.const("local"), z.const("ollama")]).default("openai"),
70
+
71
+ // Local ONNX embedder (transformers.js / onnxruntime).
72
+ localEmbedModel: z.string().default("Xenova/bge-small-zh-v1.5"),
73
+ localEmbedDimension: z.natural().default(512),
74
+ localEmbedDevice: z.union([z.const("cpu"), z.const("gpu")]).default("cpu"),
75
+ localEmbedBatchSize: z.natural().min(1).max(64).default(8),
76
+
77
+ // Ollama embedder.
78
+ ollamaBaseUrl: z.string().default("http://localhost:11434"),
79
+ ollamaModel: z.string().default("nomic-embed-text"),
80
+
81
+ // Model download/cache. When empty (default), models are cached under the
82
+ // user-level path ~/.dsh/mneme/models (resolved in local-embedder/reranker);
83
+ // a non-empty value is used verbatim.
84
+ embedModelCacheDir: z.string().default(""),
85
+ embedModelMirror: z.string().default("https://hf-mirror.com"),
86
+
87
+ // Vector search tuning.
88
+ vectorSearchTopK: z.natural().min(1).max(100).default(20),
89
+ vectorSearchThreshold: z.number().min(0).max(1).default(0.65),
90
+ hybridSearchVectorWeight: z.number().min(0).max(1).default(0.6),
91
+ hybridSearchKeywordWeight: z.number().min(0).max(1).default(0.4),
92
+ // Lazy auto-backfill of missing embeddings on boot (Bug2): when the vector
93
+ // API is configured and rows still lack an embedding, the index is rebuilt
94
+ // in the background after a short delay, rate-limited in batches. On by
95
+ // default; set false to keep the backfill manual only.
96
+ autoReindexOnBoot: z.boolean().default(true),
97
+ // Semantic-first injection (Bug4): when enabled, injectCandidates with a
98
+ // non-empty query recalls via the vector index first and falls back to the
99
+ // rule-based pick to fill/dedupe. Empty query / no vector → legacy behavior.
100
+ hybridInject: z.boolean().default(true),
101
+
102
+ // --- recall optimization (v0.5.0) ----------------------------------------
103
+ // BM25 third recall path beside vector + LIKE keyword (1.1): per-token IDF
104
+ // scoring recalls rows whose query terms are scattered — identifiers, code
105
+ // fragments, mixed CJK/ASCII — where substring LIKE cannot match.
106
+ bm25SearchEnabled: z.boolean().default(true),
107
+ // Query-aware vector cutoff (1.2) replacing the fixed 0.65: entity:/attr:
108
+ // prefixes loosen to 0.5, short queries tighten to 0.7, long queries loosen
109
+ // to 0.6, and a decisive top-1/top-5 score gap loosens to 0.5 so the tail
110
+ // still reaches the reranker. Off = legacy fixed threshold behavior.
111
+ adaptiveThresholdEnabled: z.boolean().default(true),
112
+ // Session-scoped hot memory (1.3): the latest N dialogue rounds rendered
113
+ // ahead of the long-term recall block — short-term context that never
114
+ // enters the memory store.
115
+ hotMemoryEnabled: z.boolean().default(true),
116
+ hotMemoryRounds: z.natural().min(1).max(50).default(5),
117
+ hotMemoryMaxTokens: z.natural().min(200).max(32000).default(2000),
118
+ // Topic-ranked injection (2.2): when a query vector is available the whole
119
+ // injection candidate list is re-ordered by similarity to the current
120
+ // query instead of keeping the rule-based order.
121
+ selectiveInjectEnabled: z.boolean().default(true),
122
+ // Search-time semantic dedup (2.3): greedy pass over the merged candidate
123
+ // list dropping rows whose embedding cosine-similarity to an already-kept
124
+ // row exceeds the threshold — duplicates are filtered at recall time
125
+ // instead of waiting for a dream consolidation. Opt-in aggressive mode:
126
+ // small embedding models can collapse legitimately distinct rows, so the
127
+ // default keeps every recalled row.
128
+ searchSemanticDedup: z.boolean().default(false),
129
+ searchSemanticDedupThreshold: z.number().min(0.5).max(1).default(0.95),
130
+
131
+ // --- semantic: rerank layer (v0.2) --------------------------------------
132
+ // Opt-in by default (item ⑥): the local cross-encoder pulls in onnxruntime
133
+ // (transformers.js) at init, so a bare install must not load it. Only an
134
+ // explicit rerankEnabled=true + rerankProvider="local" constructs LocalReranker.
135
+ rerankEnabled: z.boolean().default(false),
136
+ rerankProvider: z.union([z.const("local"), z.const("none")]).default("none"),
137
+ rerankModel: z.string().default("Xenova/bge-reranker-base"),
138
+ rerankBatchSize: z.natural().min(1).max(64).default(8),
139
+ rerankMaxCandidates: z.natural().min(5).max(100).default(30),
140
+ rerankScoreThreshold: z.number().min(0).max(1).default(0.1),
141
+
142
+ // --- reflection: update decision + failure tracking (v0.2.1) ------------
143
+ reflectionUpdateEnabled: z.boolean().default(true),
144
+ reflectionFailureTracking: z.boolean().default(true),
145
+ reflectionUpdateMaxPerRun: z.natural().min(0).max(5).default(2),
146
+ reflectionUpdateMinAgeHours: z.natural().min(0).max(168).default(24),
147
+
148
+ // --- conflict freeze: manual review for conflicting memories (v0.2.1) ---
149
+ // Opt-in by default: when true, conflicting memories are not auto-merged
150
+ // and are marked as pending manual review instead.
151
+ conflictFreezeEnabled: z.boolean().default(false),
152
+ // Maximum number of frozen conflicts to keep pending for manual review.
153
+ conflictFreezeMaxPending: z.natural().min(1).max(1000).default(100),
154
+
155
+ // --- entity gene (v0.3.0) -----------------------------------------------
156
+ // Opt-in: when false (default) nothing in the pipeline extracts entities.
157
+ // The storage layer (entities/entity_attrs/entity_relations tables + CRUD)
158
+ // is always available regardless of this flag.
159
+ entityExtractionEnabled: z.boolean().default(false),
160
+ // Optional model override for entity extraction; empty = use the caller's
161
+ // default provider/model.
162
+ entityExtractionModel: z.string().default(""),
163
+ // Cap on entities per extraction pass and attributes per entity.
164
+ entityExtractionMaxEntities: z.natural().min(1).max(20).default(10),
165
+ entityExtractionMaxAttrs: z.natural().min(1).max(50).default(20),
166
+ // Prefix/semantic search over entity names (used by recall).
167
+ entitySearchEnabled: z.boolean().default(true),
168
+
169
+ // --- wiki-link: explicit cross-memory [[links]] (v0.6.1) ----------------
170
+ // Opt-in, off by default. When enabled, saveWithDedupe/update fire-and-forget
171
+ // a wiki-link resolution pass: [[target]] / [[显示|target]] markers in a
172
+ // memory's content become links_to relations in entity_relations (idempotent,
173
+ // deduped by the unique relation index). The storage layer + read APIs
174
+ // (getBacklinks/getForwardLinks/resolveWikiLink) are always available
175
+ // regardless of this flag.
176
+ wikiLinkEnabled: z.boolean().default(false),
177
+
178
+ // --- tag system (v0.6.2) ---------------------------------------------------
179
+ // Opt-in: when autoTagEnabled is true, a light LLM pass runs after each
180
+ // autoDream consolidation and extracts 1-3 tags per retained memory
181
+ // (autoTagMaxPerRun bounds how many memories are tagged per run). The tag
182
+ // storage layer (store.setMemoryTags/getMemoryTags + tag: search + mirror
183
+ // `#tag` line) is always available regardless of this flag.
184
+ autoTagEnabled: z.boolean().default(false),
185
+ autoTagMaxPerRun: z.natural().min(1).max(100).default(10),
186
+ // Manual tagging (service.setMemoryTags / memory tools) is on by default;
187
+ // set false to disable the manual write path too.
188
+ manualTagEnabled: z.boolean().default(true),
189
+
190
+ // --- tag-weighted re-rank (v0.6.4) -------------------------------------
191
+ // Opt-in: boost candidates whose tags overlap the query/session tags.
192
+ tagBoostEnabled: z.boolean().default(false),
193
+ tagBoostFactor: z.number().min(1).max(2).default(1.15),
194
+ sessionTagBoostFactor: z.number().min(1).max(2).default(1.08),
195
+
196
+ // --- sleep mode: idle-triggered deep maintenance (v0.4.0) ---------------
197
+ // Opt-in, off by default. Unlike autoDream (threshold-triggered, lightweight)
198
+ // sleep fires when the store has been quiet for sleepIdleMinutes and deep-
199
+ // maintains the whole library: conflict resolution, archival demotion,
200
+ // pattern discovery and entity relation completion. Abortable on user
201
+ // activity, audited into dream_runs (run_type='sleep'), and serialized with
202
+ // autoDream so the two never overlap.
203
+ sleepModeEnabled: z.boolean().default(false),
204
+ // Quiet window before a cycle fires (minutes).
205
+ sleepIdleMinutes: z.natural().min(1).max(60).default(5),
206
+ // Minimum gap between two sleep runs (hours) — a second idle window within
207
+ // this interval does not retrigger.
208
+ sleepMinIntervalHours: z.natural().min(1).max(168).default(8),
209
+ // Conflict adjudication strictness:
210
+ // gentle only high-confidence conflicts (threshold 0.92) are resolved
211
+ // normal standard dream-level (threshold 0.85)
212
+ // aggressive low-confidence pairs are also adjudicated (threshold 0.75)
213
+ sleepConflictStrictness: z.union([
214
+ z.const("gentle"),
215
+ z.const("normal"),
216
+ z.const("aggressive")
217
+ ]).default("normal"),
218
+ // Archival demotion tiering (days since last access):
219
+ // >= sleepArchiveDays → shrink to summary, full body kept in _full_content
220
+ // >= sleepCompressDays → archived outright (entity relations preserved)
221
+ sleepArchiveDays: z.natural().min(7).max(365).default(30),
222
+ sleepCompressDays: z.natural().min(7).max(365).default(90),
223
+ // Pattern discovery scan window (most recent memories to scan).
224
+ sleepPatternMinMemories: z.natural().min(10).max(1000).default(100),
225
+ // How far back pattern discovery considers entity attr changes (days).
226
+ sleepPatternLookbackDays: z.natural().min(1).max(90).default(30),
227
+ // Max pattern memories minted per run (0 = disabled).
228
+ sleepMaxPatternPerRun: z.natural().min(0).max(10).default(3),
229
+ // Optional LLM route override for sleep's bulk passes (empty = use dream
230
+ // route / agent default model).
231
+ sleepProvider: z.string().default(""),
232
+ sleepModel: z.string().default(""),
233
+ // Pass-through reasoning effort for sleep's LLM passes, same semantics as
234
+ // dreamReasoningEffort: 'none' (default) omits the field; 'off' explicitly
235
+ // disables thinking (thinking-type models would burn the whole budget on
236
+ // reasoning); low/medium/high are forwarded verbatim.
237
+ sleepReasoningEffort: z.union([
238
+ z.const("off"),
239
+ z.const("low"),
240
+ z.const("medium"),
241
+ z.const("high"),
242
+ z.const("none")
243
+ ]).default("none"),
244
+
245
+ // --- epistemic trust: memory source credibility (v0.4.5) -----------------
246
+ // Distinguish memories by source: observation (measured / witnessed),
247
+ // subjective (opinion / guess) and inferred (derived from other evidence).
248
+ // Opt-in by default: when false (default) retrieval ranking, injection
249
+ // marking and dream merge/conflict keepSource are untouched and
250
+ // epistemic_status stays inert data (still written + inferred on save, just
251
+ // never used to influence behavior).
252
+ trustEpistemicWeighting: z.boolean().default(false),
253
+
254
+ // --- memory quality filter (Bug7) ------------------------------------------
255
+ // Heuristic gate on what deserves the injection/recall surface. When enabled,
256
+ // saveWithDedupe scores each new memory after dedupe and before write:
257
+ // score >= degradeThreshold (60) → stored normally
258
+ // archiveThreshold (30) <= score < 60 → quality_score persisted and the
259
+ // injection sort re-ranks by importance * quality_score/100 (degraded)
260
+ // score < 30 → archived + tagged low_quality (still explicitly searchable)
261
+ // Meta-memory markers, near-duplicates and repetitive filler lose points.
262
+ memoryQualityFilter: z.object({
263
+ enabled: z.boolean().default(true),
264
+ archiveThreshold: z.natural().min(1).max(100).default(30),
265
+ degradeThreshold: z.natural().min(1).max(100).default(60),
266
+ minContentLength: z.natural().min(1).max(1000).default(10)
267
+ }).default({}),
268
+
269
+ // --- LLM audit trail (Bug8) ------------------------------------------------
270
+ // Records every background LLM call (autoDream consolidation + summary,
271
+ // autoSummarize compression) into llm_audit_logs: tokens, duration, status
272
+ // and which trigger produced it. Failures are recorded as status=error and
273
+ // never block the feature. retentionDays bounds the table: older rows are
274
+ // purged on boot.
275
+ llmAudit: z.object({
276
+ enabled: z.boolean().default(true),
277
+ retentionDays: z.natural().min(1).max(3650).default(90)
278
+ }).default({}),
279
+
280
+ // --- recall evaluation: test-result storage (v0.4.6, 方案 B) --------------
281
+ // Separate retrieval evaluation snapshots from the production recall audit.
282
+ // When false (default) evaluateRetrieval still computes precision/recall/mrr
283
+ // and returns them to the caller, but writes nothing to recall_evals — the
284
+ // eval table only grows when the operator opts in. Production searchMemories
285
+ // audits to recall_runs and NEVER touches recall_evals, regardless of this
286
+ // flag (production isolation is unconditional).
287
+ evalPersistTestResults: z.boolean().default(false),
288
+ });