@modusensus/dsh-mneme 0.8.3 → 0.8.5
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.
- package/LICENSE +21 -21
- package/README.md +727 -636
- package/bin/cli.mjs +0 -0
- package/bin/dsh-mneme-mcp.mjs +510 -0
- package/cordis.patch.yml +21 -21
- package/lib/api-standalone.js +506 -316
- package/lib/api.js +1403 -1316
- package/lib/bootstrap.js +211 -0
- package/lib/client.js +4657 -4366
- package/lib/commands.js +95 -95
- package/lib/config.js +615 -510
- package/lib/document.js +221 -0
- package/lib/dream/clustering.js +118 -118
- package/lib/dream/decisions.js +658 -658
- package/lib/dream/narratives.js +44 -0
- package/lib/dream/sleep.js +702 -700
- package/lib/dream.js +147 -16
- package/lib/embedding.js +177 -177
- package/lib/entities/extractor.js +249 -249
- package/lib/guide.js +44 -0
- package/lib/heat.js +144 -136
- package/lib/hot-memory.js +46 -46
- package/lib/index.js +515 -515
- package/lib/inject.js +375 -295
- package/lib/lang.js +208 -179
- package/lib/local-embedder.js +320 -320
- package/lib/mirror.js +198 -198
- package/lib/organize.js +450 -0
- package/lib/quality-filter.js +126 -126
- package/lib/recall-stats.js +125 -0
- package/lib/reranker.js +269 -269
- package/lib/runtime/adopt.js +176 -176
- package/lib/runtime/closure.js +172 -172
- package/lib/runtime/download.js +247 -247
- package/lib/runtime/layout.js +265 -235
- package/lib/runtime/loader.js +252 -249
- package/lib/runtime/model-fetch.js +361 -361
- package/lib/runtime/provision.js +237 -237
- package/lib/runtime/tarball.js +130 -130
- package/lib/runtime/verify.js +204 -191
- package/lib/scope.js +118 -118
- package/lib/search/adaptive.js +60 -22
- package/lib/search/bm25.js +96 -96
- package/lib/service.js +2324 -2087
- package/lib/settings.js +459 -420
- package/lib/store.js +2549 -2367
- package/lib/summarize.js +820 -449
- package/lib/tools.js +702 -574
- package/lib/vector-index.js +110 -110
- package/lib/version-check.js +122 -122
- package/package.json +109 -108
- package/runtime-manifest.json +526 -596
- package/scripts/benchmark-embed.js +201 -201
- package/scripts/benchmark-recall.js +199 -199
- package/scripts/benchmark-rerank.js +166 -166
- package/scripts/build-runtime-manifest.mjs +224 -217
- package/scripts/check-sync.js +42 -42
- package/scripts/e2e-dsh.js +220 -220
- package/scripts/mneme-runtime.mjs +277 -277
- package/scripts/stress-dsh.js +255 -255
- package/scripts/sync-lib.js +47 -47
- package/scripts/sync-test-badge.mjs +67 -61
- package/src/api-standalone.js +506 -316
- package/src/api.js +1403 -1316
- package/src/bootstrap.js +211 -0
- package/src/commands.js +95 -95
- package/src/config.js +615 -510
- package/src/document.js +221 -0
- package/src/dream/clustering.js +118 -118
- package/src/dream/decisions.js +658 -658
- package/src/dream/narratives.js +44 -0
- package/src/dream/sleep.js +702 -700
- package/src/dream.js +147 -16
- package/src/embedding.js +177 -177
- package/src/entities/extractor.js +249 -249
- package/src/guide.js +44 -0
- package/src/heat.js +144 -136
- package/src/hot-memory.js +46 -46
- package/src/index.js +515 -515
- package/src/inject.js +375 -295
- package/src/lang.js +208 -179
- package/src/local-embedder.js +320 -320
- package/src/mirror.js +198 -198
- package/src/organize.js +450 -0
- package/src/quality-filter.js +126 -126
- package/src/recall-stats.js +125 -0
- package/src/reranker.js +269 -269
- package/src/runtime/adopt.js +176 -176
- package/src/runtime/closure.js +172 -172
- package/src/runtime/download.js +247 -247
- package/src/runtime/layout.js +265 -235
- package/src/runtime/loader.js +252 -249
- package/src/runtime/model-fetch.js +361 -361
- package/src/runtime/provision.js +237 -237
- package/src/runtime/tarball.js +130 -130
- package/src/runtime/verify.js +204 -191
- package/src/scope.js +118 -118
- package/src/search/adaptive.js +60 -22
- package/src/search/bm25.js +96 -96
- package/src/service.js +2324 -2087
- package/src/settings.js +459 -420
- package/src/store.js +2549 -2367
- package/src/summarize.js +820 -449
- package/src/tools.js +702 -574
- package/src/vector-index.js +110 -110
- package/src/version-check.js +122 -122
- package/test/adaptive-inject-budget.test.js +85 -0
- package/test/api-routes-gaps.test.js +218 -218
- package/test/api.test.js +1640 -1482
- package/test/audit.test.js +448 -448
- package/test/benchmark.test.js +94 -94
- package/test/bootstrap.test.js +220 -0
- package/test/client.test.js +860 -736
- package/test/clustering.test.js +100 -100
- package/test/commands.test.js +106 -106
- package/test/config.test.js +66 -66
- package/test/conflict-freeze.test.js +300 -300
- package/test/document.test.js +523 -0
- package/test/dream-archive-guardrail.test.js +116 -116
- package/test/dream-candidate-hybrid.test.js +281 -281
- package/test/dream-coverage-degrade.test.js +86 -86
- package/test/dream.test.js +1308 -1254
- package/test/embedding-ready.test.js +196 -196
- package/test/entities.test.js +547 -547
- package/test/entity-recall.test.js +179 -0
- package/test/epistemic.test.js +298 -298
- package/test/fnew-0112.test.js +311 -311
- package/test/fnew-03.test.js +422 -422
- package/test/graph-api.test.js +175 -175
- package/test/heat.test.js +175 -148
- package/test/helpers/dream-mock.js +82 -82
- package/test/helpers/peer-worker.mjs +25 -25
- package/test/helpers/runtime-source.js +60 -60
- package/test/helpers/tar-builder.js +80 -80
- package/test/hot-memory.test.js +145 -145
- package/test/inject-content-cap.test.js +91 -0
- package/test/inject-first-round-bm25.test.js +89 -89
- package/test/inject-heat.test.js +61 -0
- package/test/inject-pools.test.js +170 -0
- package/test/inject-recall.test.js +105 -0
- package/test/inject-rotation.test.js +161 -161
- package/test/inject.test.js +283 -249
- package/test/lang.test.js +87 -87
- package/test/lib-smoke.test.js +96 -96
- package/test/llm-audit.test.js +462 -309
- package/test/llm-message-source.test.js +177 -177
- package/test/local-embedder.test.js +249 -249
- package/test/mcp-stdio.test.js +385 -0
- package/test/mirror-dirty.test.js +424 -424
- package/test/mirror-edit-digest.test.js +187 -187
- package/test/mirror-generation.test.js +499 -499
- package/test/mirror.test.js +249 -249
- package/test/narrative-bars.test.js +162 -0
- package/test/organize.test.js +418 -0
- package/test/peer-blockers.test.js +193 -193
- package/test/policy-epoch.test.js +259 -259
- package/test/quality-filter.test.js +186 -186
- package/test/reasoning-effort.test.js +746 -746
- package/test/recall-evals.test.js +235 -235
- package/test/recall-layer.test.js +326 -326
- package/test/recall-stats.test.js +123 -0
- package/test/receipt-chain.test.js +451 -451
- package/test/reflection.test.js +226 -226
- package/test/reindex-backfill.test.js +62 -62
- package/test/reranker-single-logit.test.js +73 -73
- package/test/reranker.test.js +197 -197
- package/test/resident-status.test.js +83 -0
- package/test/runtime-adopt.test.js +206 -206
- package/test/runtime-cli.test.js +89 -89
- package/test/runtime-closure.test.js +193 -193
- package/test/runtime-download.test.js +302 -302
- package/test/runtime-layout.test.js +163 -163
- package/test/runtime-loader.test.js +255 -237
- package/test/runtime-manifest.test.js +159 -158
- package/test/runtime-model-fetch.test.js +348 -348
- package/test/runtime-provision.test.js +101 -101
- package/test/runtime-tarball.test.js +81 -81
- package/test/runtime-verify.test.js +279 -214
- package/test/scope-candidates.test.js +239 -239
- package/test/scope-explicit.test.js +452 -452
- package/test/scope-retrieval.test.js +197 -197
- package/test/scope-storage.test.js +255 -255
- package/test/scope-strict.test.js +231 -231
- package/test/search-fusion.test.js +90 -90
- package/test/semantic.test.js +124 -124
- package/test/service-search.test.js +174 -174
- package/test/service.test.js +405 -405
- package/test/settings.test.js +261 -261
- package/test/skip-invalid-restore.test.js +262 -262
- package/test/sleep-action-set.test.js +422 -422
- package/test/sleep-heat.test.js +126 -125
- package/test/sleep-scheduler-rearm.test.js +89 -89
- package/test/sleep.test.js +410 -373
- package/test/standalone-api.test.js +544 -359
- package/test/store-vector-cache.test.js +98 -98
- package/test/store.test.js +396 -383
- package/test/stress.test.js +209 -209
- package/test/summarize.test.js +1288 -575
- package/test/tools-dto-schema-matrix.test.js +325 -0
- package/test/tools-memory-get-schema.test.js +65 -65
- package/test/tools.test.js +374 -341
- package/test/updated-at-semantics.test.js +113 -113
- package/test/vector-index.test.js +221 -221
- package/test/version-check.test.js +152 -152
- package/test/webServer-optional.test.js +82 -82
package/src/inject.js
CHANGED
|
@@ -1,295 +1,375 @@
|
|
|
1
|
-
import { createScopeResolver } from "./scope.js";
|
|
2
|
-
import { createHotMemory } from "./hot-memory.js";
|
|
3
|
-
import { STR, langOf } from "./lang.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
if (
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
if (
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
//
|
|
155
|
-
//
|
|
156
|
-
//
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
//
|
|
160
|
-
//
|
|
161
|
-
//
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
//
|
|
165
|
-
//
|
|
166
|
-
//
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
1
|
+
import { createScopeResolver } from "./scope.js";
|
|
2
|
+
import { createHotMemory } from "./hot-memory.js";
|
|
3
|
+
import { STR, langOf } from "./lang.js";
|
|
4
|
+
import { MEMORY_GUIDE_SECTION } from "./guide.js";
|
|
5
|
+
import { adaptiveInjectBudget } from "./search/adaptive.js";
|
|
6
|
+
|
|
7
|
+
// Issue #179:注入预览的数据底座。systemPrompt 渲染是同步回调,面板只能事后
|
|
8
|
+
// 拉取,所以在这里旁路缓存「最近一帧组装」——快照就是本次渲染用过的同一份
|
|
9
|
+
// candidates/hotText/body,不重新检索、不二次组装,零额外开销。模块级单例:
|
|
10
|
+
// 注入器全局唯一(index.js 仅在 autoInject 开启时注册一个),面板经 api.js 的
|
|
11
|
+
// 只读 getter 读取;autoInject 关闭时注入器不存在,快照保持 null——「预览
|
|
12
|
+
// 不可用」本身就是「注入关闭」的诚实呈现。
|
|
13
|
+
let injectionSnapshot = null;
|
|
14
|
+
export function getInjectionSnapshot() {
|
|
15
|
+
return injectionSnapshot;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Best-effort extraction of the current user's latest message text from the
|
|
19
|
+
// live session, for semantic-first injection (Bug4). The system-prompt
|
|
20
|
+
// interpolator renders synchronously, so this walks the already-materialized
|
|
21
|
+
// session event log (same event shape summarize.js consumes) and returns the
|
|
22
|
+
// most recent human message. Any failure degrades to "" — the injector then
|
|
23
|
+
// falls back to the legacy rule-based pick, never breaking the render.
|
|
24
|
+
function lastUserQuery(ctx) {
|
|
25
|
+
try {
|
|
26
|
+
const session = ctx?.agent?.session;
|
|
27
|
+
// DSH ≥0.1.2-rc only exposes events via snapshotEvents(); older builds
|
|
28
|
+
// still have the .events property, so fall back to it.
|
|
29
|
+
const events = session?.snapshotEvents?.() ?? session?.events;
|
|
30
|
+
if (!Array.isArray(events) || events.length === 0) return "";
|
|
31
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
32
|
+
const event = events[i];
|
|
33
|
+
if (event?.type !== "user/message") continue;
|
|
34
|
+
const kind = event.data?.source?.kind;
|
|
35
|
+
if (kind !== undefined && kind !== "user") continue;
|
|
36
|
+
const parts = event.data?.content;
|
|
37
|
+
if (!Array.isArray(parts) || parts.length === 0) continue;
|
|
38
|
+
return parts
|
|
39
|
+
.map((p) => (typeof p === "string" ? p : p?.text ?? ""))
|
|
40
|
+
.filter(Boolean)
|
|
41
|
+
.join("\n")
|
|
42
|
+
.slice(0, 500);
|
|
43
|
+
}
|
|
44
|
+
} catch { /* session internals unavailable: degrade to no query */ }
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
|
|
49
|
+
// next assistant reply from the materialized session log. Tolerates shapes
|
|
50
|
+
// where assistant events carry a different type tag — anything whose payload
|
|
51
|
+
// has content parts and is not a user message counts as a reply. Best-effort:
|
|
52
|
+
// returns [] on any failure, and the hot block simply does not render.
|
|
53
|
+
function extractRounds(ctx, maxRounds) {
|
|
54
|
+
try {
|
|
55
|
+
const session = ctx?.agent?.session;
|
|
56
|
+
const events = session?.snapshotEvents?.() ?? session?.events;
|
|
57
|
+
if (!Array.isArray(events) || events.length === 0) return [];
|
|
58
|
+
const rounds = [];
|
|
59
|
+
let pendingQuery = null;
|
|
60
|
+
const textOf = (event) => {
|
|
61
|
+
// user/message 的正文就在 data 上,而 assistant/message(以及 tool/result)的消息体
|
|
62
|
+
// 嵌在 data.message 下 —— DSH 侧由 @deepseek-ai/dsh-session 的
|
|
63
|
+
// assertMessageEventShape 一行写死:const message = type === "user/message" ? record : record?.["message"]。
|
|
64
|
+
// 只读 data.content 会让每一轮的 response 恒为空(Issue #129)。
|
|
65
|
+
// 这里用 ?? 兜底而不是直接改成 data.message.content:user 消息与旧的扁平形状都照旧可用。
|
|
66
|
+
const parts = event?.data?.content ?? event?.data?.message?.content;
|
|
67
|
+
if (!Array.isArray(parts)) return "";
|
|
68
|
+
// 只取正文 part(type === "text" 或字符串),跳过 reasoning(issue #162):
|
|
69
|
+
// reasoning 里出现 Go template / Vue / Handlebars / 正则 / 日志原文的概率远高于
|
|
70
|
+
// 正文,把它带进 hot memory 会让 `{{...}}` 模板片段注入 prompt。旧的扁平形状
|
|
71
|
+
// (字符串 part)照旧取用,无 type 字段的兜底视为正文。
|
|
72
|
+
return parts
|
|
73
|
+
.map((p) => {
|
|
74
|
+
if (typeof p === "string") return p;
|
|
75
|
+
if (p?.type && p.type !== "text") return "";
|
|
76
|
+
return p?.text ?? "";
|
|
77
|
+
})
|
|
78
|
+
.filter(Boolean)
|
|
79
|
+
.join("\n")
|
|
80
|
+
.trim();
|
|
81
|
+
};
|
|
82
|
+
for (const event of events) {
|
|
83
|
+
const kind = event?.data?.source?.kind;
|
|
84
|
+
const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
|
|
85
|
+
if (isUser) {
|
|
86
|
+
if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
|
|
87
|
+
pendingQuery = textOf(event).slice(0, 500);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
// Only assistant-originated events close a round; tool/system events
|
|
91
|
+
// carrying text must not be mistaken for the model's reply.
|
|
92
|
+
const isAssistant = typeof event?.type === "string" && event.type.includes("assistant")
|
|
93
|
+
|| kind === "assistant";
|
|
94
|
+
const body = isAssistant ? textOf(event) : "";
|
|
95
|
+
if (!body || !pendingQuery) continue;
|
|
96
|
+
rounds.push({ query: pendingQuery, response: body.slice(0, 800) });
|
|
97
|
+
pendingQuery = null;
|
|
98
|
+
}
|
|
99
|
+
if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
|
|
100
|
+
return rounds.slice(-maxRounds);
|
|
101
|
+
} catch {
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function createInjector(ctx, service, settings, config) {
|
|
107
|
+
const language = langOf(config);
|
|
108
|
+
const baseMaxItems = config.maxInjectedItems ?? 5;
|
|
109
|
+
const threshold = config.importanceThreshold ?? 3;
|
|
110
|
+
// Issue #205:注入位跨轮轮换。rotationTurns = 最近 N 个「不同用户查询」轮次
|
|
111
|
+
// 注入过的记忆本轮不再优先(0 = 关闭,保持既有行为)。历史按会话维护——
|
|
112
|
+
// 新会话从零开始;同一查询的多次渲染(工具调用轮)视为同一轮,不推进窗口。
|
|
113
|
+
const rotationTurns = Math.max(0, Math.floor(config.injectRotationTurns ?? 0));
|
|
114
|
+
const rotationHistory = new Map(); // sessionId -> [{ query, ids: Set }]
|
|
115
|
+
const ROTATION_HISTORY_MAX = 32; // 覆盖 max(20) 配置档仍有余量
|
|
116
|
+
|
|
117
|
+
function recentInjectedIds(sessionId, query) {
|
|
118
|
+
if (rotationTurns <= 0) return null;
|
|
119
|
+
const deque = rotationHistory.get(sessionId);
|
|
120
|
+
if (!deque || deque.length === 0) return null;
|
|
121
|
+
// 只看「之前的轮次」:排除与当前查询相同的条目——同一查询的重复渲染
|
|
122
|
+
// (工具调用轮)不该拿本轮自己的集合来转自己。
|
|
123
|
+
const prior = query ? deque.filter((e) => e.query !== query) : deque;
|
|
124
|
+
if (prior.length === 0) return null;
|
|
125
|
+
const recent = new Set();
|
|
126
|
+
for (const entry of prior.slice(-rotationTurns)) {
|
|
127
|
+
for (const id of entry.ids) recent.add(id);
|
|
128
|
+
}
|
|
129
|
+
return recent.size > 0 ? recent : null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function recordInjection(sessionId, query, candidates) {
|
|
133
|
+
if (rotationTurns <= 0 || !query) return;
|
|
134
|
+
const deque = rotationHistory.get(sessionId) ?? [];
|
|
135
|
+
const ids = new Set(candidates.map((c) => c.id));
|
|
136
|
+
const last = deque[deque.length - 1];
|
|
137
|
+
if (last && last.query === query) {
|
|
138
|
+
last.ids = ids; // 同一查询的重复渲染:覆盖本轮内容,不推进窗口
|
|
139
|
+
} else {
|
|
140
|
+
deque.push({ query, ids });
|
|
141
|
+
if (deque.length > ROTATION_HISTORY_MAX) deque.shift();
|
|
142
|
+
rotationHistory.set(sessionId, deque);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// v0.8.0 A3(issue #17):注入路径的会话 scope 解析——strictScope 硬过滤
|
|
146
|
+
// 需要。渲染 ctx 与工具 exec 同形(agent.session),解析器直接复用。
|
|
147
|
+
// logger 透传:registry 反查失败时 warnOnce 才有出口。
|
|
148
|
+
const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
|
|
149
|
+
|
|
150
|
+
// Bug6: bound the injected memory block. Each entry's content is truncated to
|
|
151
|
+
// injectContentMaxChars chars (issue #164①: configurable, was a hardcoded
|
|
152
|
+
// 300); a truncated entry carries a tail hint (limit / original length /
|
|
153
|
+
// memory_get id) so the cut is never silent — BUDGET_EXCEEDED principle, the
|
|
154
|
+
// agent can always fetch the full text. The whole block gets a block budget
|
|
155
|
+
// (scales up with the per-entry cap so raising the cap is not defeated by a
|
|
156
|
+
// stale 1500) and an entry that would exceed it collapses to its title only.
|
|
157
|
+
const maxContent = config.injectContentMaxChars ?? 300;
|
|
158
|
+
const MAX_BLOCK = Math.max(1500, maxContent + 600);
|
|
159
|
+
// #249 第一批:pin 条目的正文硬顶。逐字保真不等于无界——单条上限取
|
|
160
|
+
// injectContentMaxChars 与 2000 的较大者,默认档下约束/偏好不会因常规截断
|
|
161
|
+
// 失真,同时给「一条超长约束每轮吃满常驻段」留一道闸(超顶仍带截断提示)。
|
|
162
|
+
const PINNED_CONTENT_MAX = Math.max(maxContent, 2000);
|
|
163
|
+
|
|
164
|
+
// Compressed injection (v0.5.0 2.1): a sleep-demoted row carries its summary in
|
|
165
|
+
// `content` with the original parked in `_full_content` — inject the summary
|
|
166
|
+
// verbatim instead of re-truncating the (already short) text. 但「降级过」不等于
|
|
167
|
+
// 「天然够短」:原先那条 `_full_content` 早返回的唯一效果就是**跳过 maxLength**
|
|
168
|
+
// (两条分支取的都是 m.content),于是 pin 的硬顶在这一路上形同不存在(#266 评审)。
|
|
169
|
+
// 现在只有一条截断路径:超限照旧带提示,原文永远可通过 memory_get 取回。
|
|
170
|
+
function injectMemory(m, maxLength = maxContent) {
|
|
171
|
+
const text = String(m?.content ?? "");
|
|
172
|
+
if (text.length <= maxLength) return text;
|
|
173
|
+
return `${text.slice(0, maxLength)}…${STR.truncatedHint[language](maxLength, text.length, m.id)}`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Prompt-variable brace escaping (issue #162, restored from v0.7.4 #40):
|
|
177
|
+
// DSH's interpolate() scans every injected section for `{{...}}` and throws
|
|
178
|
+
// unless the variable name matches /^[a-z][a-z0-9_]*$/ — memory/profile
|
|
179
|
+
// content carrying legal template syntax (docker `--format "{{.Server.Version}}"`,
|
|
180
|
+
// Obsidian-style `{{hl|}}`, `{{挖空}}`, `{{关键词}}`) would hit an illegal
|
|
181
|
+
// variable name and throw, crashing the whole turn. At the injection boundary
|
|
182
|
+
// we escape every run of 2+ consecutive braces, inserting a `\` between each
|
|
183
|
+
// pair, so no `{{`/`}}` substring survives into the prompt: `{{a}}` → `{\{a\}\}`,
|
|
184
|
+
// and odd runs like `{{{a}}}` (which pair-wise escaping would leave with a
|
|
185
|
+
// literal `{{`) are handled too. The text keeps its readable template form,
|
|
186
|
+
// the transform is idempotent (escaped braces are single + `\`, never two
|
|
187
|
+
// adjacent), and single braces pass through untouched — interpolate only
|
|
188
|
+
// scans `{{`. Off via config.escapePromptVariables=false (default true).
|
|
189
|
+
function escapePromptVars(text) {
|
|
190
|
+
if (config.escapePromptVariables === false) return String(text);
|
|
191
|
+
return String(text).replace(/[{}]{2,}/g, (run) => run.split("").join("\\"));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
|
|
195
|
+
// the materialized event log on every render — stateless, so it survives
|
|
196
|
+
// session switches and never persists anywhere.
|
|
197
|
+
const hot = createHotMemory({
|
|
198
|
+
maxRounds: config.hotMemoryRounds ?? 5,
|
|
199
|
+
maxTokens: config.hotMemoryMaxTokens ?? 2000
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
function renderHotContext(ctx) {
|
|
203
|
+
if (config.hotMemoryEnabled === false) return "";
|
|
204
|
+
const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
|
|
205
|
+
if (!rounds.length) return "";
|
|
206
|
+
hot.clear();
|
|
207
|
+
for (const r of rounds) hot.add(r);
|
|
208
|
+
const body = hot.getContext();
|
|
209
|
+
if (!body) return "";
|
|
210
|
+
return escapePromptVars(STR.hotHeader[language](rounds.length, body));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function render(candidates, pinnedStats = null) {
|
|
214
|
+
if (!candidates.length) return "";
|
|
215
|
+
const header = STR.memoryHeader[language];
|
|
216
|
+
const lines = [header];
|
|
217
|
+
let budget = MAX_BLOCK - header.length;
|
|
218
|
+
// #249 第一批:pin 池(约束/偏好)排在块头且不参与块的塌缩预算——「与情景
|
|
219
|
+
// 日志抢同一份预算后被降级」正是本议题要修的结构缺陷。单条仍有硬顶
|
|
220
|
+
// (PINNED_CONTENT_MAX),超出照旧带截断提示,不静默。
|
|
221
|
+
const pinnedCount = Math.max(0, Math.min(candidates.length, pinnedStats?.shown ?? 0));
|
|
222
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
223
|
+
const m = candidates[i];
|
|
224
|
+
const pinned = i < pinnedCount;
|
|
225
|
+
// Epistemic trust (v0.4.5): when enabled, measured observations are
|
|
226
|
+
// flagged so the agent can weigh them above guesses/opinions.
|
|
227
|
+
const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
|
|
228
|
+
? STR.verified[language]
|
|
229
|
+
: "";
|
|
230
|
+
const title = STR.entryTitle[language](m.title, m.importance);
|
|
231
|
+
const content = injectMemory(m, pinned ? PINNED_CONTENT_MAX : maxContent);
|
|
232
|
+
const full = STR.entryLine[language](m.type, verified, title, content);
|
|
233
|
+
if (pinned) {
|
|
234
|
+
// pin 不扣块预算(上面那条设计注释的落地):pin 一条就够击穿 MAX_BLOCK
|
|
235
|
+
// (PINNED_CONTENT_MAX 2000 > MAX_BLOCK 1500),照扣会把 budget 压成负数,
|
|
236
|
+
// 同一轮随后的普通候选全部退化成标题行——正是本议题要修的结构缺陷。
|
|
237
|
+
lines.push(full);
|
|
238
|
+
} else if (budget - full.length >= 0) {
|
|
239
|
+
lines.push(full);
|
|
240
|
+
budget -= full.length;
|
|
241
|
+
} else {
|
|
242
|
+
lines.push(`- [${m.type}] ${verified}${title}`);
|
|
243
|
+
}
|
|
244
|
+
if (pinned && i === pinnedCount - 1) {
|
|
245
|
+
const hidden = Math.max(0, pinnedStats?.suppressed ?? 0);
|
|
246
|
+
if (hidden > 0) lines.push(STR.pinnedOverflow[language](hidden));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return escapePromptVars(lines.join("\n"));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Bug4: the system-prompt render is synchronous, so the semantic query vector
|
|
253
|
+
// must be prefetched asynchronously and cached for the next assembly. The
|
|
254
|
+
// first render after a new user message may still fall back to the rule-based
|
|
255
|
+
// pick; later assemblies in the same session reuse the cached vector. Bounded
|
|
256
|
+
// cache (cap 8, drop oldest) so a long session never grows it unbounded.
|
|
257
|
+
const QUERY_VECTOR_CACHE_MAX = 8;
|
|
258
|
+
const queryVectorCache = new Map();
|
|
259
|
+
let lastPrefetched = "";
|
|
260
|
+
|
|
261
|
+
function prefetchQueryVector(query) {
|
|
262
|
+
if (!query || query === lastPrefetched || queryVectorCache.has(query)) return;
|
|
263
|
+
lastPrefetched = query;
|
|
264
|
+
service.embedQuery(query).then((vec) => {
|
|
265
|
+
if (Array.isArray(vec) && vec.length) {
|
|
266
|
+
queryVectorCache.set(query, vec);
|
|
267
|
+
if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
|
|
268
|
+
queryVectorCache.delete(queryVectorCache.keys().next().value);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}).catch(() => { /* prefetch is best-effort */ });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// User profile + rules: injected ahead of the memory block because they are
|
|
275
|
+
// always-relevant instructions the agent should follow every turn.
|
|
276
|
+
function renderUserSettings() {
|
|
277
|
+
const profile = settings.getProfile().trim();
|
|
278
|
+
const rules = settings.getRules();
|
|
279
|
+
if (!profile && !rules.length) return "";
|
|
280
|
+
const lines = [STR.userSettingsHeader[language]];
|
|
281
|
+
if (profile) lines.push(STR.profileLine[language](profile));
|
|
282
|
+
for (const rule of rules) lines.push(STR.ruleLine[language](rule));
|
|
283
|
+
return escapePromptVars(lines.join("\n"));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// #249 第一批:能力说明的系统提示段。order 150 = 插件指引段的既有惯例
|
|
287
|
+
// (ACP 的 ACP_SYSTEM_PROMPT 与 mnemon 的 routing 段都在 150)。文本是常量、
|
|
288
|
+
// 同会话内不随轮次变化,故不影响其后的前缀缓存,也不逐轮复读。宿主若不提供
|
|
289
|
+
// section seam 就静默跳过——#249 §3 的口径是「只用现成 seam,拿不到位的语义
|
|
290
|
+
// 降级处理」:能力说明仍落在工具描述上,不算失败。
|
|
291
|
+
const guideSection = config.injectGuidanceEnabled === true && typeof ctx.systemPrompt?.section === "function"
|
|
292
|
+
? ctx.systemPrompt.section({ name: "memory-guide", order: 150, text: MEMORY_GUIDE_SECTION })
|
|
293
|
+
: null;
|
|
294
|
+
|
|
295
|
+
const disposers = [
|
|
296
|
+
...(guideSection ? [guideSection] : []),
|
|
297
|
+
ctx.systemPrompt.context({
|
|
298
|
+
name: "memory",
|
|
299
|
+
order: 90,
|
|
300
|
+
text: (ctx) => {
|
|
301
|
+
// Bug4: pass the latest user query so injection prefers semantically
|
|
302
|
+
// relevant memories; lastUserQuery is best-effort (empty → legacy).
|
|
303
|
+
// The query vector is prefetched asynchronously (cached) because the
|
|
304
|
+
// render itself must stay synchronous.
|
|
305
|
+
const query = lastUserQuery(ctx);
|
|
306
|
+
if (query) prefetchQueryVector(query);
|
|
307
|
+
const queryVector = queryVectorCache.get(query);
|
|
308
|
+
// v0.8.0 A3:scope 随请求解析(strict 开启时 injectCandidates 内硬过滤;
|
|
309
|
+
// flag 关闭时解析器返回 null,注入行为不变)。
|
|
310
|
+
const scope = resolveSessionScope(ctx);
|
|
311
|
+
// Issue #205:跨轮轮换——最近 N 个查询轮次注入过的 id 本轮不再优先。
|
|
312
|
+
const sessionId = ctx?.agent?.session?.id ?? "_";
|
|
313
|
+
const rotate = recentInjectedIds(sessionId, query);
|
|
314
|
+
// rotateWindow 随集合一起传入:候选池按 maxItems×(N+1) 扩容——窗口要的
|
|
315
|
+
// 牌比既有 maxItems×2 池多时,轮换才有新鲜牌可换(#205 补测)。
|
|
316
|
+
// Issue #239(第 5 项):注入条数的查询自适应(默认关)。确定性强的话题收缩
|
|
317
|
+
// 条数、模糊话题维持上限——单向收缩,绝不越过 maxInjectedItems;判据只看查询
|
|
318
|
+
// 本身,不做额外检索(先探针检索等于白付一次 fuseRecall)。
|
|
319
|
+
const maxItems = config.injectUncertaintyAdaptive === true
|
|
320
|
+
? adaptiveInjectBudget(query, baseMaxItems)
|
|
321
|
+
: baseMaxItems;
|
|
322
|
+
// #249 第一批:pin 池统计走可选出参,不动 injectCandidates 的数组契约。
|
|
323
|
+
const pinnedStats = {};
|
|
324
|
+
const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold, scope, rotate, rotateWindow: rotationTurns, pinnedStats });
|
|
325
|
+
// #249:pin 条目不进轮换历史——它们每轮固定前置,记进去只会占满轮换
|
|
326
|
+
// 窗口、挤掉情景候选的新鲜度(验收:pin 不参与跨轮轮换)。
|
|
327
|
+
recordInjection(sessionId, query, pinnedStats.shown > 0 ? candidates.slice(pinnedStats.shown) : candidates);
|
|
328
|
+
// Hot memory (v0.5.0 1.3) leads the single memory block: the agent
|
|
329
|
+
// sees the short-term rounds first, then the cross-session recall —
|
|
330
|
+
// the documented injection order 1→2. Folding it here (instead of a
|
|
331
|
+
// separate context) keeps the prompt assembly stable at two blocks.
|
|
332
|
+
const hotText = renderHotContext(ctx);
|
|
333
|
+
const body = render(candidates, pinnedStats);
|
|
334
|
+
const finalBody = !hotText ? body : body ? `${hotText}\n\n${body}` : hotText;
|
|
335
|
+
// Issue #179:旁路缓存一帧——面板「注入预览」卡据此展示构成与体积。
|
|
336
|
+
// chars 为条目内容的截断后近似值(与 render 同一函数计长),totalChars
|
|
337
|
+
// 是本次实际返回块的精确长度。maxItems 反映自适应收缩后的生效值。
|
|
338
|
+
injectionSnapshot = {
|
|
339
|
+
at: Date.now(),
|
|
340
|
+
sessionId,
|
|
341
|
+
query: query || "",
|
|
342
|
+
maxItems,
|
|
343
|
+
threshold,
|
|
344
|
+
adaptive: config.injectUncertaintyAdaptive === true,
|
|
345
|
+
scoped: scope && (scope.agent_scope || scope.workspace_scope) ? scope : null,
|
|
346
|
+
rotated: rotate ? rotate.size : 0,
|
|
347
|
+
hotChars: hotText.length,
|
|
348
|
+
entries: candidates.map((m) => ({
|
|
349
|
+
id: m.id,
|
|
350
|
+
type: m.type,
|
|
351
|
+
title: m.title,
|
|
352
|
+
importance: m.importance,
|
|
353
|
+
chars: injectMemory(m).length
|
|
354
|
+
})),
|
|
355
|
+
totalChars: finalBody.length
|
|
356
|
+
};
|
|
357
|
+
return finalBody;
|
|
358
|
+
}
|
|
359
|
+
}),
|
|
360
|
+
ctx.systemPrompt.context({
|
|
361
|
+
name: "user-settings",
|
|
362
|
+
order: 85,
|
|
363
|
+
text: renderUserSettings
|
|
364
|
+
})
|
|
365
|
+
];
|
|
366
|
+
|
|
367
|
+
return () => {
|
|
368
|
+
queryVectorCache.clear();
|
|
369
|
+
rotationHistory.clear();
|
|
370
|
+
injectionSnapshot = null; // 注入器卸载即失效:快照不得跨生命周期存留
|
|
371
|
+
for (const dispose of disposers) {
|
|
372
|
+
if (typeof dispose === "function") dispose();
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
}
|