@modusensus/dsh-mneme 0.6.7 → 0.6.9

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