@modusensus/dsh-mneme 0.6.9 → 0.6.10

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/LICENSE +21 -21
  2. package/README.md +468 -219
  3. package/{dsh-mneme/cordis.patch.yml → cordis.patch.yml} +15 -15
  4. package/{dsh-mneme/src → lib}/api.js +783 -783
  5. package/{dsh-mneme/lib → lib}/client.js +1754 -1757
  6. package/{dsh-mneme/src → lib}/commands.js +64 -64
  7. package/{dsh-mneme/lib → lib}/config.js +298 -298
  8. package/{dsh-mneme/lib → lib}/dream/clustering.js +118 -118
  9. package/{dsh-mneme/lib → lib}/dream/decisions.js +488 -488
  10. package/{dsh-mneme/lib → lib}/dream/sleep.js +561 -561
  11. package/{dsh-mneme/src → lib}/dream/tag-extractor.js +156 -156
  12. package/{dsh-mneme/lib → lib}/dream.js +958 -958
  13. package/{dsh-mneme/src → lib}/embedding.js +154 -154
  14. package/{dsh-mneme/src → lib}/entities/extractor.js +242 -242
  15. package/{dsh-mneme/lib → lib}/hot-memory.js +53 -53
  16. package/{dsh-mneme/lib → lib}/index.js +361 -361
  17. package/{dsh-mneme/src → lib}/inject.js +208 -208
  18. package/{dsh-mneme/lib → lib}/local-embedder.js +282 -282
  19. package/{dsh-mneme/lib → lib}/mirror.js +170 -170
  20. package/{dsh-mneme/lib → lib}/parser/tag.js +59 -59
  21. package/{dsh-mneme/lib → lib}/parser/wiki-link.js +38 -38
  22. package/{dsh-mneme/src → lib}/quality-filter.js +123 -123
  23. package/{dsh-mneme/lib → lib}/reranker.js +218 -218
  24. package/{dsh-mneme/src → lib}/search/adaptive.js +22 -22
  25. package/{dsh-mneme/src → lib}/search/bm25.js +96 -96
  26. package/{dsh-mneme/src → lib}/search/tag-boost.js +61 -61
  27. package/{dsh-mneme/src → lib}/service.js +1726 -1726
  28. package/{dsh-mneme/lib → lib}/settings.js +172 -172
  29. package/{dsh-mneme/src → lib}/store.js +2238 -2238
  30. package/{dsh-mneme/src → lib}/summarize.js +236 -236
  31. package/{dsh-mneme/lib → lib}/tools.js +290 -290
  32. package/{dsh-mneme/lib → lib}/vector-index.js +116 -116
  33. package/package.json +40 -18
  34. package/{dsh-mneme/scripts → scripts}/benchmark-embed.js +201 -201
  35. package/{dsh-mneme/scripts → scripts}/benchmark-recall.js +133 -133
  36. package/{dsh-mneme/scripts → scripts}/benchmark-rerank.js +166 -166
  37. package/{dsh-mneme/scripts → scripts}/e2e-dsh.js +218 -218
  38. package/{dsh-mneme/scripts → scripts}/stress-dsh.js +255 -255
  39. package/{dsh-mneme/scripts → scripts}/sync-lib.js +52 -52
  40. package/{dsh-mneme/lib → src}/api.js +783 -783
  41. package/{dsh-mneme/lib → src}/commands.js +64 -64
  42. package/{dsh-mneme/src → src}/config.js +298 -298
  43. package/{dsh-mneme/src → src}/dream/clustering.js +118 -118
  44. package/{dsh-mneme/src → src}/dream/decisions.js +488 -488
  45. package/{dsh-mneme/src → src}/dream/sleep.js +561 -561
  46. package/{dsh-mneme/lib → src}/dream/tag-extractor.js +156 -156
  47. package/{dsh-mneme/src → src}/dream.js +958 -958
  48. package/{dsh-mneme/lib → src}/embedding.js +154 -154
  49. package/{dsh-mneme/lib → src}/entities/extractor.js +242 -242
  50. package/{dsh-mneme/src → src}/hot-memory.js +53 -53
  51. package/{dsh-mneme/src → src}/index.js +361 -361
  52. package/{dsh-mneme/lib → src}/inject.js +208 -208
  53. package/{dsh-mneme/src → src}/local-embedder.js +282 -282
  54. package/{dsh-mneme/src → src}/mirror.js +170 -170
  55. package/{dsh-mneme/src → src}/parser/tag.js +59 -59
  56. package/{dsh-mneme/src → src}/parser/wiki-link.js +38 -38
  57. package/{dsh-mneme/lib → src}/quality-filter.js +123 -123
  58. package/{dsh-mneme/src → src}/reranker.js +218 -218
  59. package/{dsh-mneme/lib → src}/search/adaptive.js +22 -22
  60. package/{dsh-mneme/lib → src}/search/bm25.js +96 -96
  61. package/{dsh-mneme/lib → src}/search/tag-boost.js +61 -61
  62. package/{dsh-mneme/lib → src}/service.js +1726 -1726
  63. package/{dsh-mneme/src → src}/settings.js +172 -172
  64. package/{dsh-mneme/lib → src}/store.js +2238 -2238
  65. package/{dsh-mneme/lib → src}/summarize.js +236 -236
  66. package/{dsh-mneme/src → src}/tools.js +290 -290
  67. package/{dsh-mneme/src → src}/vector-index.js +116 -116
  68. package/{dsh-mneme/test → test}/api.test.js +594 -594
  69. package/{dsh-mneme/test → test}/audit.test.js +448 -448
  70. package/{dsh-mneme/test → test}/benchmark.test.js +35 -35
  71. package/{dsh-mneme/test → test}/boundary-v0625.test.js +82 -82
  72. package/{dsh-mneme/test → test}/client.test.js +368 -368
  73. package/{dsh-mneme/test → test}/clustering.test.js +100 -100
  74. package/{dsh-mneme/test → test}/commands.test.js +69 -69
  75. package/{dsh-mneme/test → test}/config.test.js +50 -50
  76. package/{dsh-mneme/test → test}/conflict-freeze.test.js +290 -290
  77. package/{dsh-mneme/test → test}/directory.test.js +134 -134
  78. package/{dsh-mneme/test → test}/dream.test.js +1060 -1060
  79. package/{dsh-mneme/test → test}/entities.test.js +522 -522
  80. package/{dsh-mneme/test → test}/epistemic.test.js +298 -298
  81. package/{dsh-mneme/test → test}/fnew-0112.test.js +311 -311
  82. package/{dsh-mneme/test → test}/fnew-03.test.js +422 -422
  83. package/{dsh-mneme/test → test}/graph-api.test.js +175 -175
  84. package/{dsh-mneme/test → test}/helpers/dream-mock.js +82 -82
  85. package/{dsh-mneme/test → test}/hot-memory.test.js +174 -174
  86. package/{dsh-mneme/test → test}/inject.test.js +103 -103
  87. package/{dsh-mneme/test → test}/llm-audit.test.js +279 -279
  88. package/{dsh-mneme/test → test}/local-embedder.test.js +227 -227
  89. package/{dsh-mneme/test → test}/mirror-dirty.test.js +424 -424
  90. package/{dsh-mneme/test → test}/mirror-edit-digest.test.js +187 -187
  91. package/{dsh-mneme/test → test}/mirror-generation.test.js +499 -499
  92. package/{dsh-mneme/test → test}/mirror.test.js +249 -249
  93. package/{dsh-mneme/test → test}/normalize-decisions.test.js +120 -120
  94. package/{dsh-mneme/test → test}/peer-blockers.test.js +190 -190
  95. package/{dsh-mneme/test → test}/policy-epoch.test.js +259 -259
  96. package/{dsh-mneme/test → test}/provenance.test.js +103 -103
  97. package/{dsh-mneme/test → test}/quality-filter.test.js +118 -118
  98. package/{dsh-mneme/test → test}/reasoning-effort.test.js +199 -199
  99. package/{dsh-mneme/test → test}/recall-evals.test.js +235 -235
  100. package/{dsh-mneme/test → test}/recall-layer.test.js +315 -315
  101. package/{dsh-mneme/test → test}/receipt-chain.test.js +451 -451
  102. package/{dsh-mneme/test → test}/reflection.test.js +226 -226
  103. package/{dsh-mneme/test → test}/reranker.test.js +240 -240
  104. package/{dsh-mneme/test → test}/search-fusion.test.js +90 -90
  105. package/{dsh-mneme/test → test}/semantic.test.js +124 -124
  106. package/{dsh-mneme/test → test}/service-search.test.js +199 -199
  107. package/{dsh-mneme/test → test}/service.test.js +435 -435
  108. package/{dsh-mneme/test → test}/settings.test.js +118 -118
  109. package/{dsh-mneme/test → test}/sleep.test.js +365 -365
  110. package/{dsh-mneme/test → test}/store.test.js +436 -436
  111. package/{dsh-mneme/test → test}/stress.test.js +209 -209
  112. package/{dsh-mneme/test → test}/summarize.test.js +191 -191
  113. package/{dsh-mneme/test → test}/tag-boost.test.js +125 -125
  114. package/{dsh-mneme/test → test}/tag.test.js +312 -312
  115. package/{dsh-mneme/test → test}/tools.test.js +285 -285
  116. package/{dsh-mneme/test → test}/vector-index.test.js +221 -221
  117. package/{dsh-mneme/test → test}/wiki-link.test.js +332 -332
  118. package/.github/workflows/test.yml +0 -32
  119. package/.release-notes-v0.6.9.md +0 -13
  120. package/CHANGELOG.md +0 -89
  121. package/SECURITY.md +0 -544
  122. package/docs/devlog/2026-08-14-dsh-mneme-dev-log.md +0 -247
  123. package/docs/devlog/2026-08-15-dsh-mneme-audit-stress-dev-log.md +0 -145
  124. package/docs/devlog/2026-08-15-dsh-mneme-pipeline-dev-log.md +0 -56
  125. package/docs/devlog/2026-08-15-dsh-mneme-reflection-dev-log.md +0 -77
  126. package/docs/devlog/2026-08-15-dsh-mneme-review-fixes-dev-log.md +0 -64
  127. package/docs/devlog/2026-08-15-dsh-mneme-semantic-dev-log.md +0 -90
  128. package/dsh-mneme/CHANGELOG.md +0 -248
  129. package/dsh-mneme/LICENSE +0 -21
  130. package/dsh-mneme/README.md +0 -465
  131. package/dsh-mneme/docs/AGENT_MEMORY_RESEARCH.md +0 -183
  132. package/dsh-mneme/docs/ENTITIES.md +0 -245
  133. package/dsh-mneme/docs/LOCAL_MODEL.md +0 -141
  134. package/dsh-mneme/docs/MIGRATION.md +0 -127
  135. package/dsh-mneme/docs/SEMANTIC.md +0 -256
  136. package/dsh-mneme/docs/SLEEP.md +0 -163
  137. package/dsh-mneme/package-lock.json +0 -1936
  138. package/dsh-mneme/package.json +0 -80
  139. package//346/250/252/345/271/205.png +0 -0
@@ -1,298 +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
- // 跳过非法决策(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
- });
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
+ });