@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,208 +1,208 @@
1
- import { createHotMemory } from "./hot-memory.js";
2
-
3
- // Best-effort extraction of the current user's latest message text from the
4
- // live session, for semantic-first injection (Bug4). The system-prompt
5
- // interpolator renders synchronously, so this walks the already-materialized
6
- // session event log (same event shape summarize.js consumes) and returns the
7
- // most recent human message. Any failure degrades to "" — the injector then
8
- // falls back to the legacy rule-based pick, never breaking the render.
9
- function lastUserQuery(ctx) {
10
- try {
11
- const events = ctx?.agent?.session?.events;
12
- if (!Array.isArray(events) || events.length === 0) return "";
13
- for (let i = events.length - 1; i >= 0; i--) {
14
- const event = events[i];
15
- if (event?.type !== "user/message") continue;
16
- const kind = event.data?.source?.kind;
17
- if (kind !== undefined && kind !== "user") continue;
18
- const parts = event.data?.content;
19
- if (!Array.isArray(parts) || parts.length === 0) continue;
20
- return parts
21
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
22
- .filter(Boolean)
23
- .join("\n")
24
- .slice(0, 500);
25
- }
26
- } catch { /* session internals unavailable: degrade to no query */ }
27
- return "";
28
- }
29
-
30
- // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
31
- // next assistant reply from the materialized session log. Tolerates shapes
32
- // where assistant events carry a different type tag — anything whose payload
33
- // has content parts and is not a user message counts as a reply. Best-effort:
34
- // returns [] on any failure, and the hot block simply does not render.
35
- function extractRounds(ctx, maxRounds) {
36
- try {
37
- const events = ctx?.agent?.session?.events;
38
- if (!Array.isArray(events) || events.length === 0) return [];
39
- const rounds = [];
40
- let pendingQuery = null;
41
- const textOf = (event) => {
42
- const parts = event?.data?.content;
43
- if (!Array.isArray(parts)) return "";
44
- return parts
45
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
46
- .filter(Boolean)
47
- .join("\n")
48
- .trim();
49
- };
50
- for (const event of events) {
51
- const kind = event?.data?.source?.kind;
52
- const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
53
- if (isUser) {
54
- if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
55
- pendingQuery = textOf(event).slice(0, 500);
56
- continue;
57
- }
58
- // Only assistant-originated events close a round; tool/system events
59
- // carrying text must not be mistaken for the model's reply.
60
- const isAssistant = typeof event?.type === "string" && event.type.includes("assistant")
61
- || kind === "assistant";
62
- const body = isAssistant ? textOf(event) : "";
63
- if (!body || !pendingQuery) continue;
64
- rounds.push({ query: pendingQuery, response: body.slice(0, 800) });
65
- pendingQuery = null;
66
- }
67
- if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
68
- return rounds.slice(-maxRounds);
69
- } catch {
70
- return [];
71
- }
72
- }
73
-
74
- export function createInjector(ctx, service, settings, config) {
75
- const maxItems = config.maxInjectedItems ?? 5;
76
- const threshold = config.importanceThreshold ?? 3;
77
-
78
- // Bug6: bound the injected memory block. Each entry's content is truncated to
79
- // MAX_CONTENT chars (trailing `…`); the whole block gets a MAX_BLOCK budget
80
- // and an entry that would exceed it collapses to its title only, so a long
81
- // memory can never push the injected context past a few thousand chars.
82
- const MAX_CONTENT = 300;
83
- const MAX_BLOCK = 1500;
84
-
85
- // Compressed injection (v0.5.0 2.1): a sleep-demoted row already carries its
86
- // summary in `content` with the original parked in `_full_content` — inject
87
- // the summary verbatim instead of re-truncating the (already short) text.
88
- // Regular long rows keep the hard truncate.
89
- function injectMemory(m, maxLength = MAX_CONTENT) {
90
- if (m?._full_content) return String(m.content ?? "");
91
- const text = String(m?.content ?? "");
92
- return text.length <= maxLength ? text : `${text.slice(0, maxLength)}…`;
93
- }
94
-
95
- // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
96
- // the materialized event log on every render — stateless, so it survives
97
- // session switches and never persists anywhere.
98
- const hot = createHotMemory({
99
- maxRounds: config.hotMemoryRounds ?? 5,
100
- maxTokens: config.hotMemoryMaxTokens ?? 2000
101
- });
102
-
103
- function renderHotContext(ctx) {
104
- if (config.hotMemoryEnabled === false) return "";
105
- const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
106
- if (!rounds.length) return "";
107
- hot.clear();
108
- for (const r of rounds) hot.add(r);
109
- const body = hot.getContext();
110
- if (!body) return "";
111
- return `[短期上下文] 最近对话(共 ${rounds.length} 轮):\n${body}`;
112
- }
113
-
114
- function render(candidates) {
115
- if (!candidates.length) return "";
116
- const header = "[记忆库] 来自 dsh-mneme 的跨会话记忆(用户偏好与高优先级项目/决策):";
117
- const lines = [header];
118
- let budget = MAX_BLOCK - header.length;
119
- for (const m of candidates) {
120
- // Epistemic trust (v0.4.5): when enabled, measured observations are
121
- // flagged so the agent can weigh them above guesses/opinions.
122
- const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
123
- ? "[verified] "
124
- : "";
125
- const title = `${m.title}(重要性 ${m.importance})`;
126
- const content = injectMemory(m);
127
- const full = `- [${m.type}] ${verified}${title}:${content}`;
128
- if (budget - full.length >= 0) {
129
- lines.push(full);
130
- budget -= full.length;
131
- } else {
132
- lines.push(`- [${m.type}] ${verified}${title}`);
133
- }
134
- }
135
- return lines.join("\n");
136
- }
137
-
138
- // Bug4: the system-prompt render is synchronous, so the semantic query vector
139
- // must be prefetched asynchronously and cached for the next assembly. The
140
- // first render after a new user message may still fall back to the rule-based
141
- // pick; later assemblies in the same session reuse the cached vector. Bounded
142
- // cache (cap 8, drop oldest) so a long session never grows it unbounded.
143
- const QUERY_VECTOR_CACHE_MAX = 8;
144
- const queryVectorCache = new Map();
145
- let lastPrefetched = "";
146
-
147
- function prefetchQueryVector(query) {
148
- if (!query || query === lastPrefetched || queryVectorCache.has(query)) return;
149
- lastPrefetched = query;
150
- service.embedQuery(query).then((vec) => {
151
- if (Array.isArray(vec) && vec.length) {
152
- queryVectorCache.set(query, vec);
153
- if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
154
- queryVectorCache.delete(queryVectorCache.keys().next().value);
155
- }
156
- }
157
- }).catch(() => { /* prefetch is best-effort */ });
158
- }
159
-
160
- // User profile + rules: injected ahead of the memory block because they are
161
- // always-relevant instructions the agent should follow every turn.
162
- function renderUserSettings() {
163
- const profile = settings.getProfile().trim();
164
- const rules = settings.getRules();
165
- if (!profile && !rules.length) return "";
166
- const lines = ["[用户设置] 来自 dsh-mneme 的用户画像与规则:"];
167
- if (profile) lines.push(`- 用户画像:${profile}`);
168
- for (const rule of rules) lines.push(`- 规则:${rule}`);
169
- return lines.join("\n");
170
- }
171
-
172
- const disposers = [
173
- ctx.systemPrompt.context({
174
- name: "memory",
175
- order: 90,
176
- text: (ctx) => {
177
- // Bug4: pass the latest user query so injection prefers semantically
178
- // relevant memories; lastUserQuery is best-effort (empty → legacy).
179
- // The query vector is prefetched asynchronously (cached) because the
180
- // render itself must stay synchronous.
181
- const query = lastUserQuery(ctx);
182
- if (query) prefetchQueryVector(query);
183
- const queryVector = queryVectorCache.get(query);
184
- const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold });
185
- // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
186
- // sees the short-term rounds first, then the cross-session recall —
187
- // the documented injection order 1→2. Folding it here (instead of a
188
- // separate context) keeps the prompt assembly stable at two blocks.
189
- const hotText = renderHotContext(ctx);
190
- const body = render(candidates);
191
- if (!hotText) return body;
192
- return body ? `${hotText}\n\n${body}` : hotText;
193
- }
194
- }),
195
- ctx.systemPrompt.context({
196
- name: "user-settings",
197
- order: 85,
198
- text: renderUserSettings
199
- })
200
- ];
201
-
202
- return () => {
203
- queryVectorCache.clear();
204
- for (const dispose of disposers) {
205
- if (typeof dispose === "function") dispose();
206
- }
207
- };
208
- }
1
+ import { createHotMemory } from "./hot-memory.js";
2
+
3
+ // Best-effort extraction of the current user's latest message text from the
4
+ // live session, for semantic-first injection (Bug4). The system-prompt
5
+ // interpolator renders synchronously, so this walks the already-materialized
6
+ // session event log (same event shape summarize.js consumes) and returns the
7
+ // most recent human message. Any failure degrades to "" — the injector then
8
+ // falls back to the legacy rule-based pick, never breaking the render.
9
+ function lastUserQuery(ctx) {
10
+ try {
11
+ const events = ctx?.agent?.session?.events;
12
+ if (!Array.isArray(events) || events.length === 0) return "";
13
+ for (let i = events.length - 1; i >= 0; i--) {
14
+ const event = events[i];
15
+ if (event?.type !== "user/message") continue;
16
+ const kind = event.data?.source?.kind;
17
+ if (kind !== undefined && kind !== "user") continue;
18
+ const parts = event.data?.content;
19
+ if (!Array.isArray(parts) || parts.length === 0) continue;
20
+ return parts
21
+ .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
22
+ .filter(Boolean)
23
+ .join("\n")
24
+ .slice(0, 500);
25
+ }
26
+ } catch { /* session internals unavailable: degrade to no query */ }
27
+ return "";
28
+ }
29
+
30
+ // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
31
+ // next assistant reply from the materialized session log. Tolerates shapes
32
+ // where assistant events carry a different type tag — anything whose payload
33
+ // has content parts and is not a user message counts as a reply. Best-effort:
34
+ // returns [] on any failure, and the hot block simply does not render.
35
+ function extractRounds(ctx, maxRounds) {
36
+ try {
37
+ const events = ctx?.agent?.session?.events;
38
+ if (!Array.isArray(events) || events.length === 0) return [];
39
+ const rounds = [];
40
+ let pendingQuery = null;
41
+ const textOf = (event) => {
42
+ const parts = event?.data?.content;
43
+ if (!Array.isArray(parts)) return "";
44
+ return parts
45
+ .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
46
+ .filter(Boolean)
47
+ .join("\n")
48
+ .trim();
49
+ };
50
+ for (const event of events) {
51
+ const kind = event?.data?.source?.kind;
52
+ const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
53
+ if (isUser) {
54
+ if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
55
+ pendingQuery = textOf(event).slice(0, 500);
56
+ continue;
57
+ }
58
+ // Only assistant-originated events close a round; tool/system events
59
+ // carrying text must not be mistaken for the model's reply.
60
+ const isAssistant = typeof event?.type === "string" && event.type.includes("assistant")
61
+ || kind === "assistant";
62
+ const body = isAssistant ? textOf(event) : "";
63
+ if (!body || !pendingQuery) continue;
64
+ rounds.push({ query: pendingQuery, response: body.slice(0, 800) });
65
+ pendingQuery = null;
66
+ }
67
+ if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
68
+ return rounds.slice(-maxRounds);
69
+ } catch {
70
+ return [];
71
+ }
72
+ }
73
+
74
+ export function createInjector(ctx, service, settings, config) {
75
+ const maxItems = config.maxInjectedItems ?? 5;
76
+ const threshold = config.importanceThreshold ?? 3;
77
+
78
+ // Bug6: bound the injected memory block. Each entry's content is truncated to
79
+ // MAX_CONTENT chars (trailing `…`); the whole block gets a MAX_BLOCK budget
80
+ // and an entry that would exceed it collapses to its title only, so a long
81
+ // memory can never push the injected context past a few thousand chars.
82
+ const MAX_CONTENT = 300;
83
+ const MAX_BLOCK = 1500;
84
+
85
+ // Compressed injection (v0.5.0 2.1): a sleep-demoted row already carries its
86
+ // summary in `content` with the original parked in `_full_content` — inject
87
+ // the summary verbatim instead of re-truncating the (already short) text.
88
+ // Regular long rows keep the hard truncate.
89
+ function injectMemory(m, maxLength = MAX_CONTENT) {
90
+ if (m?._full_content) return String(m.content ?? "");
91
+ const text = String(m?.content ?? "");
92
+ return text.length <= maxLength ? text : `${text.slice(0, maxLength)}…`;
93
+ }
94
+
95
+ // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
96
+ // the materialized event log on every render — stateless, so it survives
97
+ // session switches and never persists anywhere.
98
+ const hot = createHotMemory({
99
+ maxRounds: config.hotMemoryRounds ?? 5,
100
+ maxTokens: config.hotMemoryMaxTokens ?? 2000
101
+ });
102
+
103
+ function renderHotContext(ctx) {
104
+ if (config.hotMemoryEnabled === false) return "";
105
+ const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
106
+ if (!rounds.length) return "";
107
+ hot.clear();
108
+ for (const r of rounds) hot.add(r);
109
+ const body = hot.getContext();
110
+ if (!body) return "";
111
+ return `[短期上下文] 最近对话(共 ${rounds.length} 轮):\n${body}`;
112
+ }
113
+
114
+ function render(candidates) {
115
+ if (!candidates.length) return "";
116
+ const header = "[记忆库] 来自 dsh-mneme 的跨会话记忆(用户偏好与高优先级项目/决策):";
117
+ const lines = [header];
118
+ let budget = MAX_BLOCK - header.length;
119
+ for (const m of candidates) {
120
+ // Epistemic trust (v0.4.5): when enabled, measured observations are
121
+ // flagged so the agent can weigh them above guesses/opinions.
122
+ const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
123
+ ? "[verified] "
124
+ : "";
125
+ const title = `${m.title}(重要性 ${m.importance})`;
126
+ const content = injectMemory(m);
127
+ const full = `- [${m.type}] ${verified}${title}:${content}`;
128
+ if (budget - full.length >= 0) {
129
+ lines.push(full);
130
+ budget -= full.length;
131
+ } else {
132
+ lines.push(`- [${m.type}] ${verified}${title}`);
133
+ }
134
+ }
135
+ return lines.join("\n");
136
+ }
137
+
138
+ // Bug4: the system-prompt render is synchronous, so the semantic query vector
139
+ // must be prefetched asynchronously and cached for the next assembly. The
140
+ // first render after a new user message may still fall back to the rule-based
141
+ // pick; later assemblies in the same session reuse the cached vector. Bounded
142
+ // cache (cap 8, drop oldest) so a long session never grows it unbounded.
143
+ const QUERY_VECTOR_CACHE_MAX = 8;
144
+ const queryVectorCache = new Map();
145
+ let lastPrefetched = "";
146
+
147
+ function prefetchQueryVector(query) {
148
+ if (!query || query === lastPrefetched || queryVectorCache.has(query)) return;
149
+ lastPrefetched = query;
150
+ service.embedQuery(query).then((vec) => {
151
+ if (Array.isArray(vec) && vec.length) {
152
+ queryVectorCache.set(query, vec);
153
+ if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
154
+ queryVectorCache.delete(queryVectorCache.keys().next().value);
155
+ }
156
+ }
157
+ }).catch(() => { /* prefetch is best-effort */ });
158
+ }
159
+
160
+ // User profile + rules: injected ahead of the memory block because they are
161
+ // always-relevant instructions the agent should follow every turn.
162
+ function renderUserSettings() {
163
+ const profile = settings.getProfile().trim();
164
+ const rules = settings.getRules();
165
+ if (!profile && !rules.length) return "";
166
+ const lines = ["[用户设置] 来自 dsh-mneme 的用户画像与规则:"];
167
+ if (profile) lines.push(`- 用户画像:${profile}`);
168
+ for (const rule of rules) lines.push(`- 规则:${rule}`);
169
+ return lines.join("\n");
170
+ }
171
+
172
+ const disposers = [
173
+ ctx.systemPrompt.context({
174
+ name: "memory",
175
+ order: 90,
176
+ text: (ctx) => {
177
+ // Bug4: pass the latest user query so injection prefers semantically
178
+ // relevant memories; lastUserQuery is best-effort (empty → legacy).
179
+ // The query vector is prefetched asynchronously (cached) because the
180
+ // render itself must stay synchronous.
181
+ const query = lastUserQuery(ctx);
182
+ if (query) prefetchQueryVector(query);
183
+ const queryVector = queryVectorCache.get(query);
184
+ const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold });
185
+ // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
186
+ // sees the short-term rounds first, then the cross-session recall —
187
+ // the documented injection order 1→2. Folding it here (instead of a
188
+ // separate context) keeps the prompt assembly stable at two blocks.
189
+ const hotText = renderHotContext(ctx);
190
+ const body = render(candidates);
191
+ if (!hotText) return body;
192
+ return body ? `${hotText}\n\n${body}` : hotText;
193
+ }
194
+ }),
195
+ ctx.systemPrompt.context({
196
+ name: "user-settings",
197
+ order: 85,
198
+ text: renderUserSettings
199
+ })
200
+ ];
201
+
202
+ return () => {
203
+ queryVectorCache.clear();
204
+ for (const dispose of disposers) {
205
+ if (typeof dispose === "function") dispose();
206
+ }
207
+ };
208
+ }