@modusensus/dsh-mneme 0.8.13 → 0.8.15

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 (271) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +655 -626
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +689 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -0
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +263 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/ENTITIES.md +245 -0
  12. package/docs/LOCAL_MODEL.md +222 -0
  13. package/docs/SEMANTIC.md +256 -0
  14. package/docs/SLEEP.md +164 -0
  15. package/docs/STORAGE.md +89 -0
  16. package/lib/api-standalone.js +673 -572
  17. package/lib/api.js +1437 -1433
  18. package/lib/bootstrap.js +211 -211
  19. package/lib/client.js +5444 -5295
  20. package/lib/commands.js +95 -95
  21. package/lib/config.js +880 -836
  22. package/lib/content-hash.js +54 -54
  23. package/lib/continuity.js +220 -220
  24. package/lib/document-index.js +94 -94
  25. package/lib/document.js +303 -303
  26. package/lib/dream/clustering.js +118 -118
  27. package/lib/dream/decisions.js +674 -674
  28. package/lib/dream/narratives.js +44 -44
  29. package/lib/dream/sleep.js +819 -819
  30. package/lib/dream.js +1501 -1501
  31. package/lib/embedding.js +177 -177
  32. package/lib/entities/extractor.js +252 -252
  33. package/lib/graph/anchoring.js +179 -179
  34. package/lib/guide.js +74 -74
  35. package/lib/heat.js +144 -144
  36. package/lib/hot-memory.js +46 -46
  37. package/lib/index.js +535 -671
  38. package/lib/inject.js +464 -450
  39. package/lib/lang.js +248 -229
  40. package/lib/local-embedder.js +358 -358
  41. package/lib/maintenance.js +142 -142
  42. package/lib/mirror.js +330 -330
  43. package/lib/organize.js +450 -450
  44. package/lib/peak-hours.js +117 -117
  45. package/lib/placement.js +13 -0
  46. package/lib/pre-inject-gate.js +340 -0
  47. package/lib/quality-filter.js +126 -126
  48. package/lib/recall-stats.js +175 -175
  49. package/lib/reranker.js +269 -269
  50. package/lib/runtime/adopt.js +176 -176
  51. package/lib/runtime/closure.js +172 -172
  52. package/lib/runtime/download.js +247 -247
  53. package/lib/runtime/layout.js +265 -265
  54. package/lib/runtime/loader.js +252 -252
  55. package/lib/runtime/model-fetch.js +361 -361
  56. package/lib/runtime/provision.js +237 -237
  57. package/lib/runtime/tarball.js +130 -130
  58. package/lib/runtime/verify.js +223 -204
  59. package/lib/scope.js +146 -146
  60. package/lib/search/adaptive.js +60 -60
  61. package/lib/search/bm25.js +96 -96
  62. package/lib/semantic.js +229 -0
  63. package/lib/sensitive-scan.js +209 -209
  64. package/lib/serve.js +215 -0
  65. package/lib/service.js +2663 -2596
  66. package/lib/settings.js +517 -509
  67. package/lib/store.js +3007 -3007
  68. package/lib/summarize.js +891 -856
  69. package/lib/tools.js +743 -737
  70. package/lib/vector-index.js +110 -110
  71. package/lib/version-check.js +122 -122
  72. package/lib/write-admission.js +402 -402
  73. package/locale/en.json +6 -6
  74. package/locale/zh.json +6 -6
  75. package/package.json +8 -4
  76. package/runtime-manifest.json +526 -526
  77. package/scripts/benchmark-embed.js +201 -201
  78. package/scripts/benchmark-recall.js +249 -249
  79. package/scripts/benchmark-rerank.js +166 -166
  80. package/scripts/build-runtime-manifest.mjs +224 -224
  81. package/scripts/changelog-prep.mjs +36 -0
  82. package/scripts/check-sync.js +42 -42
  83. package/scripts/e2e-dsh.js +220 -220
  84. package/scripts/mneme-runtime.mjs +277 -277
  85. package/scripts/stress-dsh.js +255 -255
  86. package/scripts/sync-lib.js +47 -47
  87. package/scripts/sync-test-badge.mjs +69 -69
  88. package/scripts/test-count-sync.mjs +44 -44
  89. package/src/api-standalone.js +673 -572
  90. package/src/api.js +1437 -1433
  91. package/src/bootstrap.js +211 -211
  92. package/src/commands.js +95 -95
  93. package/src/config.js +880 -836
  94. package/src/content-hash.js +54 -54
  95. package/src/continuity.js +220 -220
  96. package/src/document-index.js +94 -94
  97. package/src/document.js +303 -303
  98. package/src/dream/clustering.js +118 -118
  99. package/src/dream/decisions.js +674 -674
  100. package/src/dream/narratives.js +44 -44
  101. package/src/dream/sleep.js +819 -819
  102. package/src/dream.js +1501 -1501
  103. package/src/embedding.js +177 -177
  104. package/src/entities/extractor.js +252 -252
  105. package/src/graph/anchoring.js +179 -179
  106. package/src/guide.js +74 -74
  107. package/src/heat.js +144 -144
  108. package/src/hot-memory.js +46 -46
  109. package/src/index.js +535 -671
  110. package/src/inject.js +464 -450
  111. package/src/lang.js +248 -229
  112. package/src/local-embedder.js +358 -358
  113. package/src/maintenance.js +142 -142
  114. package/src/mirror.js +330 -330
  115. package/src/organize.js +450 -450
  116. package/src/peak-hours.js +117 -117
  117. package/src/placement.js +13 -0
  118. package/src/pre-inject-gate.js +340 -0
  119. package/src/quality-filter.js +126 -126
  120. package/src/recall-stats.js +175 -175
  121. package/src/reranker.js +269 -269
  122. package/src/runtime/adopt.js +176 -176
  123. package/src/runtime/closure.js +172 -172
  124. package/src/runtime/download.js +247 -247
  125. package/src/runtime/layout.js +265 -265
  126. package/src/runtime/loader.js +252 -252
  127. package/src/runtime/model-fetch.js +361 -361
  128. package/src/runtime/provision.js +237 -237
  129. package/src/runtime/tarball.js +130 -130
  130. package/src/runtime/verify.js +223 -204
  131. package/src/scope.js +146 -146
  132. package/src/search/adaptive.js +60 -60
  133. package/src/search/bm25.js +96 -96
  134. package/src/semantic.js +229 -0
  135. package/src/sensitive-scan.js +209 -209
  136. package/src/serve.js +215 -0
  137. package/src/service.js +2663 -2596
  138. package/src/settings.js +517 -509
  139. package/src/store.js +3007 -3007
  140. package/src/summarize.js +891 -856
  141. package/src/tools.js +743 -737
  142. package/src/vector-index.js +110 -110
  143. package/src/version-check.js +122 -122
  144. package/src/write-admission.js +402 -402
  145. package/test/adaptive-inject-budget.test.js +85 -85
  146. package/test/api-routes-gaps.test.js +218 -218
  147. package/test/api.test.js +1702 -1688
  148. package/test/audit.test.js +448 -448
  149. package/test/baseline-persist.test.js +248 -248
  150. package/test/benchmark.test.js +94 -94
  151. package/test/bootstrap.test.js +220 -220
  152. package/test/changelog-prep.test.js +60 -0
  153. package/test/client.test.js +1230 -1169
  154. package/test/clustering.test.js +100 -100
  155. package/test/commands.test.js +106 -106
  156. package/test/config.test.js +66 -66
  157. package/test/conflict-freeze.test.js +300 -300
  158. package/test/content-hash.test.js +204 -204
  159. package/test/continuity.test.js +333 -333
  160. package/test/document-dir.test.js +233 -233
  161. package/test/document.test.js +671 -671
  162. package/test/dream-archive-guardrail.test.js +116 -116
  163. package/test/dream-candidate-hybrid.test.js +281 -281
  164. package/test/dream-coverage-degrade.test.js +86 -86
  165. package/test/dream-failure-backoff.test.js +173 -173
  166. package/test/dream-peak-hours.test.js +194 -194
  167. package/test/dream.test.js +1385 -1383
  168. package/test/embedding-ready.test.js +196 -196
  169. package/test/entities.test.js +627 -547
  170. package/test/entity-recall.test.js +179 -179
  171. package/test/epistemic.test.js +325 -325
  172. package/test/fnew-0112.test.js +311 -311
  173. package/test/fnew-03.test.js +422 -422
  174. package/test/graph-anchoring.test.js +184 -184
  175. package/test/graph-api.test.js +175 -175
  176. package/test/graph-inject-budget.test.js +103 -103
  177. package/test/graph-passive-confirm.test.js +91 -91
  178. package/test/graph-weight-evolution.test.js +104 -104
  179. package/test/heat.test.js +175 -175
  180. package/test/helpers/dream-mock.js +82 -82
  181. package/test/helpers/peer-worker.mjs +25 -25
  182. package/test/helpers/runtime-source.js +60 -60
  183. package/test/helpers/tar-builder.js +80 -80
  184. package/test/helpers/write-admission-samples.js +308 -308
  185. package/test/hot-memory.test.js +145 -145
  186. package/test/inject-content-cap.test.js +91 -91
  187. package/test/inject-first-round-bm25.test.js +89 -89
  188. package/test/inject-heat.test.js +77 -61
  189. package/test/inject-parent-gate.test.js +106 -106
  190. package/test/inject-pools.test.js +194 -194
  191. package/test/inject-recall.test.js +105 -105
  192. package/test/inject-rotation.test.js +161 -161
  193. package/test/inject.test.js +420 -420
  194. package/test/lang.test.js +87 -87
  195. package/test/lastrunat-persist.test.js +101 -101
  196. package/test/lib-smoke.test.js +96 -96
  197. package/test/llm-audit.test.js +598 -598
  198. package/test/llm-message-source.test.js +207 -207
  199. package/test/local-embedder.test.js +292 -292
  200. package/test/maintenance.test.js +391 -391
  201. package/test/mcp-stdio.test.js +385 -385
  202. package/test/mirror-dirty.test.js +424 -424
  203. package/test/mirror-edit-digest.test.js +187 -187
  204. package/test/mirror-generation.test.js +499 -499
  205. package/test/mirror-types.test.js +208 -208
  206. package/test/mirror.test.js +249 -249
  207. package/test/narrative-bars.test.js +162 -162
  208. package/test/organize.test.js +418 -418
  209. package/test/peer-blockers.test.js +193 -193
  210. package/test/placement.test.js +36 -0
  211. package/test/policy-epoch.test.js +259 -259
  212. package/test/pre-inject-gate.test.js +434 -0
  213. package/test/quality-filter.test.js +186 -186
  214. package/test/reasoning-effort.test.js +752 -752
  215. package/test/recall-anti-update.test.js +82 -82
  216. package/test/recall-evals.test.js +253 -253
  217. package/test/recall-layer.test.js +326 -326
  218. package/test/recall-stats.test.js +189 -189
  219. package/test/receipt-chain.test.js +451 -451
  220. package/test/reflection.test.js +226 -226
  221. package/test/reindex-backfill.test.js +62 -62
  222. package/test/reranker-single-logit.test.js +73 -73
  223. package/test/reranker.test.js +197 -197
  224. package/test/resident-status.test.js +83 -83
  225. package/test/runtime-adopt.test.js +206 -206
  226. package/test/runtime-cli.test.js +89 -89
  227. package/test/runtime-closure.test.js +193 -193
  228. package/test/runtime-download.test.js +302 -302
  229. package/test/runtime-layout.test.js +163 -163
  230. package/test/runtime-loader.test.js +255 -255
  231. package/test/runtime-manifest.test.js +159 -159
  232. package/test/runtime-model-fetch.test.js +348 -348
  233. package/test/runtime-provision.test.js +101 -101
  234. package/test/runtime-tarball.test.js +81 -81
  235. package/test/runtime-verify.test.js +319 -279
  236. package/test/scope-candidates.test.js +239 -239
  237. package/test/scope-explicit.test.js +452 -452
  238. package/test/scope-inject-soft.test.js +106 -106
  239. package/test/scope-retrieval.test.js +197 -197
  240. package/test/scope-storage.test.js +255 -255
  241. package/test/scope-strict.test.js +367 -343
  242. package/test/search-fusion.test.js +90 -90
  243. package/test/semantic.test.js +124 -124
  244. package/test/sensitive-scan.test.js +207 -207
  245. package/test/serve-bin.test.js +121 -0
  246. package/test/serve.test.js +196 -0
  247. package/test/service-search.test.js +174 -174
  248. package/test/service.test.js +405 -405
  249. package/test/settings.test.js +261 -261
  250. package/test/skip-invalid-restore.test.js +262 -262
  251. package/test/sleep-action-set.test.js +422 -422
  252. package/test/sleep-heat.test.js +126 -126
  253. package/test/sleep-scheduler-rearm.test.js +89 -89
  254. package/test/sleep.test.js +527 -527
  255. package/test/standalone-api.test.js +751 -544
  256. package/test/store-vector-cache.test.js +98 -98
  257. package/test/store.test.js +396 -396
  258. package/test/stress.test.js +209 -209
  259. package/test/summarize-occurred-at.test.js +127 -0
  260. package/test/summarize-reasoning-effort.test.js +189 -189
  261. package/test/summarize.test.js +1465 -1465
  262. package/test/supersede-state-tracking.test.js +394 -0
  263. package/test/test-count-sync.test.js +60 -60
  264. package/test/tools-dto-schema-matrix.test.js +325 -325
  265. package/test/tools-memory-get-schema.test.js +65 -65
  266. package/test/tools.test.js +428 -374
  267. package/test/updated-at-semantics.test.js +113 -113
  268. package/test/vector-index.test.js +221 -221
  269. package/test/version-check.test.js +152 -152
  270. package/test/webServer-optional.test.js +82 -82
  271. package/test/write-admission.test.js +668 -668
package/src/inject.js CHANGED
@@ -1,450 +1,464 @@
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
- import { injectChildEnabled } from "./config.js";
7
-
8
- // Issue #179:注入预览的数据底座。systemPrompt 渲染是同步回调,面板只能事后
9
- // 拉取,所以在这里旁路缓存「最近一帧组装」——快照就是本次渲染用过的同一份
10
- // candidates/hotText/body,不重新检索、不二次组装,零额外开销。模块级单例:
11
- // 注入器全局唯一(index.js 仅在 autoInject 开启时注册一个),面板经 api.js 的
12
- // 只读 getter 读取;autoInject 关闭时注入器不存在,快照保持 null——「预览
13
- // 不可用」本身就是「注入关闭」的诚实呈现。
14
- let injectionSnapshot = null;
15
- export function getInjectionSnapshot() {
16
- return injectionSnapshot;
17
- }
18
-
19
- // Issue #334:UTF-16 截断切开 emoji 代理对会留下孤立代理项(如 🔴 = D83D DD34
20
- // 在 800 处切,D83D 留下、DD34 被切走)。DSH 把它序列化成非法 UTF-8,DeepSeek
21
- // API 对每个请求回 400 INVALID_REQUEST——而且畸形文本随注入消息被永久写进会话
22
- // 历史,此后**每一轮**都带着它,表现为会话从某一轮起连续 400、换话题/重启都不
23
- // 恢复(会话级不可逆损坏)。防法是「少一个字符都行,绝不留半个」:尾字符是
24
- // 高位代理(0xD800–0xDBFF)说明它的低位搭档被切走了,把这个高位代理整个丢掉。
25
- // (反过来尾字符是低位代理不可能孤立——它的搭档必然紧邻在前、同在切点之内。)
26
- // ASCII-only 的文本零开销(length 相等直接短路)。
27
- function safeSlice(text, limit) {
28
- const s = String(text);
29
- if (s.length <= limit) return s;
30
- let cut = s.slice(0, limit);
31
- const tail = cut.charCodeAt(cut.length - 1);
32
- if (tail >= 0xd800 && tail <= 0xdbff) cut = cut.slice(0, -1);
33
- return cut;
34
- }
35
-
36
- // Best-effort extraction of the current user's latest message text from the
37
- // live session, for semantic-first injection (Bug4). The system-prompt
38
- // interpolator renders synchronously, so this walks the already-materialized
39
- // session event log (same event shape summarize.js consumes) and returns the
40
- // most recent human message. Any failure degrades to "" — the injector then
41
- // falls back to the legacy rule-based pick, never breaking the render.
42
- function lastUserQuery(ctx) {
43
- try {
44
- const session = ctx?.agent?.session;
45
- // DSH ≥0.1.2-rc only exposes events via snapshotEvents(); older builds
46
- // still have the .events property, so fall back to it.
47
- const events = session?.snapshotEvents?.() ?? session?.events;
48
- if (!Array.isArray(events) || events.length === 0) return "";
49
- for (let i = events.length - 1; i >= 0; i--) {
50
- const event = events[i];
51
- if (event?.type !== "user/message") continue;
52
- const kind = event.data?.source?.kind;
53
- if (kind !== undefined && kind !== "user") continue;
54
- const parts = event.data?.content;
55
- if (!Array.isArray(parts) || parts.length === 0) continue;
56
- return safeSlice(
57
- parts
58
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
59
- .filter(Boolean)
60
- .join("\n"),
61
- 500
62
- );
63
- }
64
- } catch { /* session internals unavailable: degrade to no query */ }
65
- return "";
66
- }
67
-
68
- // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
69
- // next assistant reply from the materialized session log. Tolerates shapes
70
- // where assistant events carry a different type tag — anything whose payload
71
- // has content parts and is not a user message counts as a reply. Best-effort:
72
- // returns [] on any failure, and the hot block simply does not render.
73
- function extractRounds(ctx, maxRounds) {
74
- try {
75
- const session = ctx?.agent?.session;
76
- const events = session?.snapshotEvents?.() ?? session?.events;
77
- if (!Array.isArray(events) || events.length === 0) return [];
78
- const rounds = [];
79
- let pendingQuery = null;
80
- const textOf = (event) => {
81
- // user/message 的正文就在 data 上,而 assistant/message(以及 tool/result)的消息体
82
- // 嵌在 data.message 下 —— DSH 侧由 @deepseek-ai/dsh-session 的
83
- // assertMessageEventShape 一行写死:const message = type === "user/message" ? record : record?.["message"]。
84
- // 只读 data.content 会让每一轮的 response 恒为空(Issue #129)。
85
- // 这里用 ?? 兜底而不是直接改成 data.message.content:user 消息与旧的扁平形状都照旧可用。
86
- const parts = event?.data?.content ?? event?.data?.message?.content;
87
- if (!Array.isArray(parts)) return "";
88
- // 只取正文 part(type === "text" 或字符串),跳过 reasoning(issue #162):
89
- // reasoning 里出现 Go template / Vue / Handlebars / 正则 / 日志原文的概率远高于
90
- // 正文,把它带进 hot memory 会让 `{{...}}` 模板片段注入 prompt。旧的扁平形状
91
- // (字符串 part)照旧取用,无 type 字段的兜底视为正文。
92
- return parts
93
- .map((p) => {
94
- if (typeof p === "string") return p;
95
- if (p?.type && p.type !== "text") return "";
96
- return p?.text ?? "";
97
- })
98
- .filter(Boolean)
99
- .join("\n")
100
- .trim();
101
- };
102
- for (const event of events) {
103
- const kind = event?.data?.source?.kind;
104
- const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
105
- if (isUser) {
106
- if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
107
- pendingQuery = safeSlice(textOf(event), 500);
108
- continue;
109
- }
110
- // Only assistant-originated events close a round; tool/system events
111
- // carrying text must not be mistaken for the model's reply.
112
- const isAssistant = typeof event?.type === "string" && event.type.includes("assistant")
113
- || kind === "assistant";
114
- const body = isAssistant ? textOf(event) : "";
115
- if (!body || !pendingQuery) continue;
116
- rounds.push({ query: pendingQuery, response: safeSlice(body, 800) });
117
- pendingQuery = null;
118
- }
119
- if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
120
- return rounds.slice(-maxRounds);
121
- } catch {
122
- return [];
123
- }
124
- }
125
-
126
- export function createInjector(ctx, service, settings, config) {
127
- const language = langOf(config);
128
- const baseMaxItems = config.maxInjectedItems ?? 5;
129
- const threshold = config.importanceThreshold ?? 3;
130
- // Issue #205:注入位跨轮轮换。rotationTurns = 最近 N 个「不同用户查询」轮次
131
- // 注入过的记忆本轮不再优先(0 = 关闭,保持既有行为)。历史按会话维护——
132
- // 新会话从零开始;同一查询的多次渲染(工具调用轮)视为同一轮,不推进窗口。
133
- const rotationTurns = Math.max(0, Math.floor(config.injectRotationTurns ?? 0));
134
- const rotationHistory = new Map(); // sessionId -> [{ query, ids: Set }]
135
- const ROTATION_HISTORY_MAX = 32; // 覆盖 max(20) 配置档仍有余量
136
-
137
- function recentInjectedIds(sessionId, query) {
138
- if (rotationTurns <= 0) return null;
139
- const deque = rotationHistory.get(sessionId);
140
- if (!deque || deque.length === 0) return null;
141
- // 只看「之前的轮次」:排除与当前查询相同的条目——同一查询的重复渲染
142
- // (工具调用轮)不该拿本轮自己的集合来转自己。
143
- const prior = query ? deque.filter((e) => e.query !== query) : deque;
144
- if (prior.length === 0) return null;
145
- const recent = new Set();
146
- for (const entry of prior.slice(-rotationTurns)) {
147
- for (const id of entry.ids) recent.add(id);
148
- }
149
- return recent.size > 0 ? recent : null;
150
- }
151
-
152
- function recordInjection(sessionId, query, candidates) {
153
- if (rotationTurns <= 0 || !query) return;
154
- const deque = rotationHistory.get(sessionId) ?? [];
155
- const ids = new Set(candidates.map((c) => c.id));
156
- const last = deque[deque.length - 1];
157
- if (last && last.query === query) {
158
- last.ids = ids; // 同一查询的重复渲染:覆盖本轮内容,不推进窗口
159
- } else {
160
- deque.push({ query, ids });
161
- if (deque.length > ROTATION_HISTORY_MAX) deque.shift();
162
- rotationHistory.set(sessionId, deque);
163
- }
164
- }
165
- // v0.8.0 A3(issue #17):注入路径的会话 scope 解析——strictScope 硬过滤
166
- // 需要。渲染 ctx 与工具 exec 同形(agent.session),解析器直接复用。
167
- // logger 透传:registry 反查失败时 warnOnce 才有出口。
168
- const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
169
-
170
- // Bug6: bound the injected memory block. Each entry's content is truncated to
171
- // injectContentMaxChars chars (issue #164①: configurable, was a hardcoded
172
- // 300); a truncated entry carries a tail hint (limit / original length /
173
- // memory_get id) so the cut is never silent — BUDGET_EXCEEDED principle, the
174
- // agent can always fetch the full text. The whole block gets a block budget
175
- // (scales up with the per-entry cap so raising the cap is not defeated by a
176
- // stale 1500) and an entry that would exceed it collapses to its title only.
177
- const maxContent = config.injectContentMaxChars ?? 300;
178
- const MAX_BLOCK = Math.max(1500, maxContent + 600);
179
- // #249 第一批:pin 条目的正文硬顶。逐字保真不等于无界——单条上限取
180
- // injectContentMaxChars 与 2000 的较大者,默认档下约束/偏好不会因常规截断
181
- // 失真,同时给「一条超长约束每轮吃满常驻段」留一道闸(超顶仍带截断提示)。
182
- const PINNED_CONTENT_MAX = Math.max(maxContent, 2000);
183
-
184
- // Compressed injection (v0.5.0 2.1): a sleep-demoted row carries its summary in
185
- // `content` with the original parked in `_full_content` — inject the summary
186
- // verbatim instead of re-truncating the (already short) text. 但「降级过」不等于
187
- // 「天然够短」:原先那条 `_full_content` 早返回的唯一效果就是**跳过 maxLength**
188
- // (两条分支取的都是 m.content),于是 pin 的硬顶在这一路上形同不存在(#266 评审)。
189
- // 现在只有一条截断路径:超限照旧带提示,原文永远可通过 memory_get 取回。
190
- function injectMemory(m, maxLength = maxContent) {
191
- const text = String(m?.content ?? "");
192
- if (text.length <= maxLength) return text;
193
- return `${safeSlice(text, maxLength)}…${STR.truncatedHint[language](maxLength, text.length, m.id)}`;
194
- }
195
-
196
- // Prompt-variable brace escaping (issue #162, restored from v0.7.4 #40):
197
- // DSH's interpolate() scans every injected section for `{{...}}` and throws
198
- // unless the variable name matches /^[a-z][a-z0-9_]*$/ — memory/profile
199
- // content carrying legal template syntax (docker `--format "{{.Server.Version}}"`,
200
- // Obsidian-style `{{hl|}}`, `{{挖空}}`, `{{关键词}}`) would hit an illegal
201
- // variable name and throw, crashing the whole turn. At the injection boundary
202
- // we escape every run of 2+ consecutive braces, inserting a `\` between each
203
- // pair, so no `{{`/`}}` substring survives into the prompt: `{{a}}` → `{\{a\}\}`,
204
- // and odd runs like `{{{a}}}` (which pair-wise escaping would leave with a
205
- // literal `{{`) are handled too. The text keeps its readable template form,
206
- // the transform is idempotent (escaped braces are single + `\`, never two
207
- // adjacent), and single braces pass through untouched — interpolate only
208
- // scans `{{`. Off via config.escapePromptVariables=false (default true).
209
- function escapePromptVars(text) {
210
- if (config.escapePromptVariables === false) return String(text);
211
- return String(text).replace(/[{}]{2,}/g, (run) => run.split("").join("\\"));
212
- }
213
-
214
- // Time-prefix injection (issue #34,恢复于 #333): opt-in, off by default.
215
- // When enabled the current date/time is injected once per conversation — at
216
- // the first prompt assembly of a new session — so the model can sense what
217
- // time/day it is. A per-session latch means later assemblies in the same
218
- // session never re-inject; a bare render ctx (no session id) falls back to
219
- // once per injector lifetime.
220
- // v0.7.11 面板大改版(ce4658e)时这段随一次批量删除被静默移除,CHANGELOG 无
221
- // 登记(#162 的 escapePromptVars 同刀误删、后来恢复,本函数漏了)——用户按
222
- // CHANGELOG 开着开关,实际什么都不会发生。本次按 v0.7.2 语义原样恢复:键名、
223
- // 默认值(false)、格式 `[当前时间: YYYY-MM-DD 周X HH:MM]` 全部不变,存量
224
- // feature_flags 里的配置恢复即生效。
225
- // 已注入过时间前缀的会话集合(#335 review:单值闩锁在 A→B→A 交替渲染下会
226
- // 重复注入)。上限 500 防长驻进程无界增长,超限逐出最早记录。
227
- const timePrefixDone = new Set();
228
- let timePrefixBare = false;
229
-
230
- function renderTimePrefix(ctx) {
231
- if (config.injectTimePrefix !== true) return "";
232
- const sessionId = ctx?.agent?.session?.id;
233
- if (sessionId === undefined) {
234
- if (timePrefixBare) return "";
235
- timePrefixBare = true;
236
- } else {
237
- if (timePrefixDone.has(sessionId)) return "";
238
- if (timePrefixDone.size >= 500) timePrefixDone.delete(timePrefixDone.keys().next().value);
239
- timePrefixDone.add(sessionId);
240
- }
241
- const WEEKDAYS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
242
- const now = new Date();
243
- const pad = (n) => String(n).padStart(2, "0");
244
- const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
245
- const time = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
246
- return escapePromptVars(`[当前时间: ${date} ${WEEKDAYS[now.getDay()]} ${time}]`);
247
- }
248
-
249
- // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
250
- // the materialized event log on every render — stateless, so it survives
251
- // session switches and never persists anywhere.
252
- const hot = createHotMemory({
253
- maxRounds: config.hotMemoryRounds ?? 5,
254
- maxTokens: config.hotMemoryMaxTokens ?? 2000
255
- });
256
-
257
- function renderHotContext(ctx) {
258
- if (config.hotMemoryEnabled === false) return "";
259
- const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
260
- if (!rounds.length) return "";
261
- hot.clear();
262
- for (const r of rounds) hot.add(r);
263
- const body = hot.getContext();
264
- if (!body) return "";
265
- return escapePromptVars(STR.hotHeader[language](rounds.length, body));
266
- }
267
-
268
- function render(candidates, pinnedStats = null) {
269
- if (!candidates.length) return "";
270
- const header = STR.memoryHeader[language];
271
- const lines = [header];
272
- let budget = MAX_BLOCK - header.length;
273
- // #249 第一批:pin 池(约束/偏好)排在块头且不参与块的塌缩预算——「与情景
274
- // 日志抢同一份预算后被降级」正是本议题要修的结构缺陷。单条仍有硬顶
275
- // (PINNED_CONTENT_MAX),超出照旧带截断提示,不静默。
276
- const pinnedCount = Math.max(0, Math.min(candidates.length, pinnedStats?.shown ?? 0));
277
- // #24 块3:图召回线索行(graphHint)——引导语插在第一个线索行之前(保持块头
278
- // 语义:先声明「这些不是事实」)。线索行自身按 graphHintLine 渲染(线索/ 前缀
279
- // 区别于普通记忆行)。
280
- let graphSeen = 0;
281
- for (let i = 0; i < candidates.length; i++) {
282
- const m = candidates[i];
283
- const pinned = i < pinnedCount;
284
- if (m.graphHint === true) graphSeen++;
285
- // Epistemic trust (v0.4.5): when enabled, measured observations are
286
- // flagged so the agent can weigh them above guesses/opinions.
287
- const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
288
- ? STR.verified[language]
289
- : "";
290
- const title = STR.entryTitle[language](m.title, m.importance);
291
- const content = injectMemory(m, pinned ? PINNED_CONTENT_MAX : maxContent);
292
- const full = m.graphHint === true
293
- ? STR.graphHintLine[language](m.type, title, content)
294
- : STR.entryLine[language](m.type, verified, title, content);
295
- // 线索行引导语插在第一个线索行之前(保持块头语义:先声明「这些不是事实」)。
296
- if (m.graphHint === true && graphSeen === 1) {
297
- lines.push(STR.graphHintHeader[language]);
298
- }
299
- if (pinned) {
300
- // pin 不扣块预算(上面那条设计注释的落地):pin 一条就够击穿 MAX_BLOCK
301
- // (PINNED_CONTENT_MAX 2000 > MAX_BLOCK 1500),照扣会把 budget 压成负数,
302
- // 同一轮随后的普通候选全部退化成标题行——正是本议题要修的结构缺陷。
303
- lines.push(full);
304
- } else if (budget - full.length >= 0) {
305
- lines.push(full);
306
- budget -= full.length;
307
- } else {
308
- lines.push(`- [${m.type}] ${verified}${title}`);
309
- }
310
- if (pinned && i === pinnedCount - 1) {
311
- const hidden = Math.max(0, pinnedStats?.suppressed ?? 0);
312
- if (hidden > 0) lines.push(STR.pinnedOverflow[language](hidden));
313
- }
314
- }
315
- return escapePromptVars(lines.join("\n"));
316
- }
317
-
318
- // Bug4: the system-prompt render is synchronous, so the semantic query vector
319
- // must be prefetched asynchronously and cached for the next assembly. The
320
- // first render after a new user message may still fall back to the rule-based
321
- // pick; later assemblies in the same session reuse the cached vector. Bounded
322
- // cache (cap 8, drop oldest) so a long session never grows it unbounded.
323
- const QUERY_VECTOR_CACHE_MAX = 8;
324
- const queryVectorCache = new Map();
325
- let lastPrefetched = "";
326
-
327
- function prefetchQueryVector(query) {
328
- if (!query || query === lastPrefetched || queryVectorCache.has(query)) return;
329
- lastPrefetched = query;
330
- service.embedQuery(query).then((vec) => {
331
- if (Array.isArray(vec) && vec.length) {
332
- queryVectorCache.set(query, vec);
333
- if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
334
- queryVectorCache.delete(queryVectorCache.keys().next().value);
335
- }
336
- }
337
- }).catch(() => { /* prefetch is best-effort */ });
338
- }
339
-
340
- // User profile + rules: injected ahead of the memory block because they are
341
- // always-relevant instructions the agent should follow every turn.
342
- function renderUserSettings() {
343
- const profile = settings.getProfile().trim();
344
- const rules = settings.getRules();
345
- if (!profile && !rules.length) return "";
346
- const lines = [STR.userSettingsHeader[language]];
347
- if (profile) lines.push(STR.profileLine[language](profile));
348
- for (const rule of rules) lines.push(STR.ruleLine[language](rule));
349
- return escapePromptVars(lines.join("\n"));
350
- }
351
-
352
- // #249 能力说明的系统提示段。order 150 = 插件指引段的既有惯例
353
- // (ACP 的 ACP_SYSTEM_PROMPT 与 mnemon 的 routing 段都在 150)。文本是常量、
354
- // 同会话内不随轮次变化,故不影响其后的前缀缓存,也不逐轮复读。宿主若不提供
355
- // section seam 就静默跳过——#249 §3 的口径是「只用现成 seam,拿不到位的语义
356
- // 降级处理」:能力说明仍落在工具描述上,不算失败。
357
- // 走父/子闸门(#249 第二批):注入器本身只在 `autoInject` 开时挂载,这里是
358
- // 第二道、也是同一个判据的显式落点——两处消费点共用 injectChildEnabled,
359
- // 不在各自的地方重写「父关则子不生效」。
360
- const guideSection = injectChildEnabled(config, "injectGuidanceEnabled") && typeof ctx.systemPrompt?.section === "function"
361
- ? ctx.systemPrompt.section({ name: "memory-guide", order: 150, text: MEMORY_GUIDE_SECTION })
362
- : null;
363
-
364
- const disposers = [
365
- ...(guideSection ? [guideSection] : []),
366
- ctx.systemPrompt.context({
367
- name: "memory",
368
- order: 90,
369
- text: (ctx) => {
370
- // Bug4: pass the latest user query so injection prefers semantically
371
- // relevant memories; lastUserQuery is best-effort (empty → legacy).
372
- // The query vector is prefetched asynchronously (cached) because the
373
- // render itself must stay synchronous.
374
- const query = lastUserQuery(ctx);
375
- if (query) prefetchQueryVector(query);
376
- const queryVector = queryVectorCache.get(query);
377
- // v0.8.0 A3:scope 随请求解析(解析器恒返回对象,身份取不到时两维为
378
- // null);硬过滤与软加权的门控都在 injectCandidates 内——strict 看
379
- // strictScope,软加权看 scopeEnabled 且至少一维可解析(issue #339)。
380
- const scope = resolveSessionScope(ctx);
381
- // Issue #205:跨轮轮换——最近 N 个查询轮次注入过的 id 本轮不再优先。
382
- const sessionId = ctx?.agent?.session?.id ?? "_";
383
- const rotate = recentInjectedIds(sessionId, query);
384
- // rotateWindow 随集合一起传入:候选池按 maxItems×(N+1) 扩容——窗口要的
385
- // 牌比既有 maxItems×2 池多时,轮换才有新鲜牌可换(#205 补测)。
386
- // Issue #239(第 5 项):注入条数的查询自适应(默认关)。确定性强的话题收缩
387
- // 条数、模糊话题维持上限——单向收缩,绝不越过 maxInjectedItems;判据只看查询
388
- // 本身,不做额外检索(先探针检索等于白付一次 fuseRecall)。
389
- const maxItems = config.injectUncertaintyAdaptive === true
390
- ? adaptiveInjectBudget(query, baseMaxItems)
391
- : baseMaxItems;
392
- // #249 第一批:pin 池统计走可选出参,不动 injectCandidates 的数组契约。
393
- const pinnedStats = {};
394
- const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold, scope, rotate, rotateWindow: rotationTurns, pinnedStats });
395
- // #249:pin 条目不进轮换历史——它们每轮固定前置,记进去只会占满轮换
396
- // 窗口、挤掉情景候选的新鲜度(验收:pin 不参与跨轮轮换)。
397
- recordInjection(sessionId, query, pinnedStats.shown > 0 ? candidates.slice(pinnedStats.shown) : candidates);
398
- // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
399
- // sees the short-term rounds first, then the cross-session recall —
400
- // the documented injection order 1→2. Folding it here (instead of a
401
- // separate context) keeps the prompt assembly stable at two blocks.
402
- const hotText = renderHotContext(ctx);
403
- const body = render(candidates, pinnedStats);
404
- // #333(issue #34 恢复):时间前缀只在会话首轮出现(per-session 闩锁),
405
- // 排在整个记忆块的最前——模型先知道「今天几号」,再看热上下文与长期记忆。
406
- const timePrefix = renderTimePrefix(ctx);
407
- // 拼接次序:时间 → 热上下文 → 长期记忆(三者都可能为空,逐级判空拼接)。
408
- const withHot = !hotText ? body : body ? `${hotText}\n\n${body}` : hotText;
409
- const finalBody = !timePrefix ? withHot : withHot ? `${timePrefix}\n\n${withHot}` : timePrefix;
410
- // Issue #179:旁路缓存一帧——面板「注入预览」卡据此展示构成与体积。
411
- // chars 为条目内容的截断后近似值(与 render 同一函数计长),totalChars
412
- // 是本次实际返回块的精确长度。maxItems 反映自适应收缩后的生效值。
413
- injectionSnapshot = {
414
- at: Date.now(),
415
- sessionId,
416
- query: query || "",
417
- maxItems,
418
- threshold,
419
- adaptive: config.injectUncertaintyAdaptive === true,
420
- scoped: scope && (scope.agent_scope || scope.workspace_scope) ? scope : null,
421
- rotated: rotate ? rotate.size : 0,
422
- hotChars: hotText.length,
423
- entries: candidates.map((m) => ({
424
- id: m.id,
425
- type: m.type,
426
- title: m.title,
427
- importance: m.importance,
428
- chars: injectMemory(m).length
429
- })),
430
- totalChars: finalBody.length
431
- };
432
- return finalBody;
433
- }
434
- }),
435
- ctx.systemPrompt.context({
436
- name: "user-settings",
437
- order: 85,
438
- text: renderUserSettings
439
- })
440
- ];
441
-
442
- return () => {
443
- queryVectorCache.clear();
444
- rotationHistory.clear();
445
- injectionSnapshot = null; // 注入器卸载即失效:快照不得跨生命周期存留
446
- for (const dispose of disposers) {
447
- if (typeof dispose === "function") dispose();
448
- }
449
- };
450
- }
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
+ import { injectChildEnabled } from "./config.js";
7
+
8
+ // Issue #179:注入预览的数据底座。systemPrompt 渲染是同步回调,面板只能事后
9
+ // 拉取,所以在这里旁路缓存「最近一帧组装」——快照就是本次渲染用过的同一份
10
+ // candidates/hotText/body,不重新检索、不二次组装,零额外开销。模块级单例:
11
+ // 注入器全局唯一(index.js 仅在 autoInject 开启时注册一个),面板经 api.js 的
12
+ // 只读 getter 读取;autoInject 关闭时注入器不存在,快照保持 null——「预览
13
+ // 不可用」本身就是「注入关闭」的诚实呈现。
14
+ let injectionSnapshot = null;
15
+ export function getInjectionSnapshot() {
16
+ return injectionSnapshot;
17
+ }
18
+
19
+ // Issue #334:UTF-16 截断切开 emoji 代理对会留下孤立代理项(如 🔴 = D83D DD34
20
+ // 在 800 处切,D83D 留下、DD34 被切走)。DSH 把它序列化成非法 UTF-8,DeepSeek
21
+ // API 对每个请求回 400 INVALID_REQUEST——而且畸形文本随注入消息被永久写进会话
22
+ // 历史,此后**每一轮**都带着它,表现为会话从某一轮起连续 400、换话题/重启都不
23
+ // 恢复(会话级不可逆损坏)。防法是「少一个字符都行,绝不留半个」:尾字符是
24
+ // 高位代理(0xD800–0xDBFF)说明它的低位搭档被切走了,把这个高位代理整个丢掉。
25
+ // (反过来尾字符是低位代理不可能孤立——它的搭档必然紧邻在前、同在切点之内。)
26
+ // ASCII-only 的文本零开销(length 相等直接短路)。
27
+ function safeSlice(text, limit) {
28
+ const s = String(text);
29
+ if (s.length <= limit) return s;
30
+ let cut = s.slice(0, limit);
31
+ const tail = cut.charCodeAt(cut.length - 1);
32
+ if (tail >= 0xd800 && tail <= 0xdbff) cut = cut.slice(0, -1);
33
+ return cut;
34
+ }
35
+
36
+ // Best-effort extraction of the current user's latest message text from the
37
+ // live session, for semantic-first injection (Bug4). The system-prompt
38
+ // interpolator renders synchronously, so this walks the already-materialized
39
+ // session event log (same event shape summarize.js consumes) and returns the
40
+ // most recent human message. Any failure degrades to "" — the injector then
41
+ // falls back to the legacy rule-based pick, never breaking the render.
42
+ function lastUserQuery(ctx) {
43
+ try {
44
+ const session = ctx?.agent?.session;
45
+ // DSH ≥0.1.2-rc only exposes events via snapshotEvents(); older builds
46
+ // still have the .events property, so fall back to it.
47
+ const events = session?.snapshotEvents?.() ?? session?.events;
48
+ if (!Array.isArray(events) || events.length === 0) return "";
49
+ for (let i = events.length - 1; i >= 0; i--) {
50
+ const event = events[i];
51
+ if (event?.type !== "user/message") continue;
52
+ const kind = event.data?.source?.kind;
53
+ if (kind !== undefined && kind !== "user") continue;
54
+ const parts = event.data?.content;
55
+ if (!Array.isArray(parts) || parts.length === 0) continue;
56
+ return safeSlice(
57
+ parts
58
+ .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
59
+ .filter(Boolean)
60
+ .join("\n"),
61
+ 500
62
+ );
63
+ }
64
+ } catch { /* session internals unavailable: degrade to no query */ }
65
+ return "";
66
+ }
67
+
68
+ // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
69
+ // next assistant reply from the materialized session log. Tolerates shapes
70
+ // where assistant events carry a different type tag — anything whose payload
71
+ // has content parts and is not a user message counts as a reply. Best-effort:
72
+ // returns [] on any failure, and the hot block simply does not render.
73
+ function extractRounds(ctx, maxRounds) {
74
+ try {
75
+ const session = ctx?.agent?.session;
76
+ const events = session?.snapshotEvents?.() ?? session?.events;
77
+ if (!Array.isArray(events) || events.length === 0) return [];
78
+ const rounds = [];
79
+ let pendingQuery = null;
80
+ const textOf = (event) => {
81
+ // user/message 的正文就在 data 上,而 assistant/message(以及 tool/result)的消息体
82
+ // 嵌在 data.message 下 —— DSH 侧由 @deepseek-ai/dsh-session 的
83
+ // assertMessageEventShape 一行写死:const message = type === "user/message" ? record : record?.["message"]。
84
+ // 只读 data.content 会让每一轮的 response 恒为空(Issue #129)。
85
+ // 这里用 ?? 兜底而不是直接改成 data.message.content:user 消息与旧的扁平形状都照旧可用。
86
+ const parts = event?.data?.content ?? event?.data?.message?.content;
87
+ if (!Array.isArray(parts)) return "";
88
+ // 只取正文 part(type === "text" 或字符串),跳过 reasoning(issue #162):
89
+ // reasoning 里出现 Go template / Vue / Handlebars / 正则 / 日志原文的概率远高于
90
+ // 正文,把它带进 hot memory 会让 `{{...}}` 模板片段注入 prompt。旧的扁平形状
91
+ // (字符串 part)照旧取用,无 type 字段的兜底视为正文。
92
+ return parts
93
+ .map((p) => {
94
+ if (typeof p === "string") return p;
95
+ if (p?.type && p.type !== "text") return "";
96
+ return p?.text ?? "";
97
+ })
98
+ .filter(Boolean)
99
+ .join("\n")
100
+ .trim();
101
+ };
102
+ for (const event of events) {
103
+ const kind = event?.data?.source?.kind;
104
+ const isUser = event?.type === "user/message" && (kind === undefined || kind === "user");
105
+ if (isUser) {
106
+ if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
107
+ pendingQuery = safeSlice(textOf(event), 500);
108
+ continue;
109
+ }
110
+ // Only assistant-originated events close a round; tool/system events
111
+ // carrying text must not be mistaken for the model's reply.
112
+ const isAssistant = typeof event?.type === "string" && event.type.includes("assistant")
113
+ || kind === "assistant";
114
+ const body = isAssistant ? textOf(event) : "";
115
+ if (!body || !pendingQuery) continue;
116
+ rounds.push({ query: pendingQuery, response: safeSlice(body, 800) });
117
+ pendingQuery = null;
118
+ }
119
+ if (pendingQuery) rounds.push({ query: pendingQuery, response: "" });
120
+ return rounds.slice(-maxRounds);
121
+ } catch {
122
+ return [];
123
+ }
124
+ }
125
+
126
+ export function createInjector(ctx, service, settings, config, gate = null) {
127
+ const language = langOf(config);
128
+ const baseMaxItems = config.maxInjectedItems ?? 5;
129
+ const threshold = config.importanceThreshold ?? 3;
130
+ // Issue #205:注入位跨轮轮换。rotationTurns = 最近 N 个「不同用户查询」轮次
131
+ // 注入过的记忆本轮不再优先(0 = 关闭,保持既有行为)。历史按会话维护——
132
+ // 新会话从零开始;同一查询的多次渲染(工具调用轮)视为同一轮,不推进窗口。
133
+ const rotationTurns = Math.max(0, Math.floor(config.injectRotationTurns ?? 0));
134
+ const rotationHistory = new Map(); // sessionId -> [{ query, ids: Set }]
135
+ const ROTATION_HISTORY_MAX = 32; // 覆盖 max(20) 配置档仍有余量
136
+
137
+ function recentInjectedIds(sessionId, query) {
138
+ if (rotationTurns <= 0) return null;
139
+ const deque = rotationHistory.get(sessionId);
140
+ if (!deque || deque.length === 0) return null;
141
+ // 只看「之前的轮次」:排除与当前查询相同的条目——同一查询的重复渲染
142
+ // (工具调用轮)不该拿本轮自己的集合来转自己。
143
+ const prior = query ? deque.filter((e) => e.query !== query) : deque;
144
+ if (prior.length === 0) return null;
145
+ const recent = new Set();
146
+ for (const entry of prior.slice(-rotationTurns)) {
147
+ for (const id of entry.ids) recent.add(id);
148
+ }
149
+ return recent.size > 0 ? recent : null;
150
+ }
151
+
152
+ function recordInjection(sessionId, query, candidates) {
153
+ if (rotationTurns <= 0 || !query) return;
154
+ const deque = rotationHistory.get(sessionId) ?? [];
155
+ const ids = new Set(candidates.map((c) => c.id));
156
+ const last = deque[deque.length - 1];
157
+ if (last && last.query === query) {
158
+ last.ids = ids; // 同一查询的重复渲染:覆盖本轮内容,不推进窗口
159
+ } else {
160
+ deque.push({ query, ids });
161
+ if (deque.length > ROTATION_HISTORY_MAX) deque.shift();
162
+ rotationHistory.set(sessionId, deque);
163
+ }
164
+ }
165
+ // v0.8.0 A3(issue #17):注入路径的会话 scope 解析——strictScope 硬过滤
166
+ // 需要。渲染 ctx 与工具 exec 同形(agent.session),解析器直接复用。
167
+ // logger 透传:registry 反查失败时 warnOnce 才有出口。
168
+ const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
169
+
170
+ // Bug6: bound the injected memory block. Each entry's content is truncated to
171
+ // injectContentMaxChars chars (issue #164①: configurable, was a hardcoded
172
+ // 300); a truncated entry carries a tail hint (limit / original length /
173
+ // memory_get id) so the cut is never silent — BUDGET_EXCEEDED principle, the
174
+ // agent can always fetch the full text. The whole block gets a block budget
175
+ // (scales up with the per-entry cap so raising the cap is not defeated by a
176
+ // stale 1500) and an entry that would exceed it collapses to its title only.
177
+ const maxContent = config.injectContentMaxChars ?? 300;
178
+ const MAX_BLOCK = Math.max(1500, maxContent + 600);
179
+ // #249 第一批:pin 条目的正文硬顶。逐字保真不等于无界——单条上限取
180
+ // injectContentMaxChars 与 2000 的较大者,默认档下约束/偏好不会因常规截断
181
+ // 失真,同时给「一条超长约束每轮吃满常驻段」留一道闸(超顶仍带截断提示)。
182
+ const PINNED_CONTENT_MAX = Math.max(maxContent, 2000);
183
+
184
+ // Compressed injection (v0.5.0 2.1): a sleep-demoted row carries its summary in
185
+ // `content` with the original parked in `_full_content` — inject the summary
186
+ // verbatim instead of re-truncating the (already short) text. 但「降级过」不等于
187
+ // 「天然够短」:原先那条 `_full_content` 早返回的唯一效果就是**跳过 maxLength**
188
+ // (两条分支取的都是 m.content),于是 pin 的硬顶在这一路上形同不存在(#266 评审)。
189
+ // 现在只有一条截断路径:超限照旧带提示,原文永远可通过 memory_get 取回。
190
+ function injectMemory(m, maxLength = maxContent) {
191
+ const text = String(m?.content ?? "");
192
+ if (text.length <= maxLength) return text;
193
+ return `${safeSlice(text, maxLength)}…${STR.truncatedHint[language](maxLength, text.length, m.id)}`;
194
+ }
195
+
196
+ // Prompt-variable brace escaping (issue #162, restored from v0.7.4 #40):
197
+ // DSH's interpolate() scans every injected section for `{{...}}` and throws
198
+ // unless the variable name matches /^[a-z][a-z0-9_]*$/ — memory/profile
199
+ // content carrying legal template syntax (docker `--format "{{.Server.Version}}"`,
200
+ // Obsidian-style `{{hl|}}`, `{{挖空}}`, `{{关键词}}`) would hit an illegal
201
+ // variable name and throw, crashing the whole turn. At the injection boundary
202
+ // we escape every run of 2+ consecutive braces, inserting a `\` between each
203
+ // pair, so no `{{`/`}}` substring survives into the prompt: `{{a}}` → `{\{a\}\}`,
204
+ // and odd runs like `{{{a}}}` (which pair-wise escaping would leave with a
205
+ // literal `{{`) are handled too. The text keeps its readable template form,
206
+ // the transform is idempotent (escaped braces are single + `\`, never two
207
+ // adjacent), and single braces pass through untouched — interpolate only
208
+ // scans `{{`. Off via config.escapePromptVariables=false (default true).
209
+ function escapePromptVars(text) {
210
+ if (config.escapePromptVariables === false) return String(text);
211
+ return String(text).replace(/[{}]{2,}/g, (run) => run.split("").join("\\"));
212
+ }
213
+
214
+ // Time-prefix injection (issue #34,恢复于 #333): opt-in, off by default.
215
+ // When enabled the current date/time is injected once per conversation — at
216
+ // the first prompt assembly of a new session — so the model can sense what
217
+ // time/day it is. A per-session latch means later assemblies in the same
218
+ // session never re-inject; a bare render ctx (no session id) falls back to
219
+ // once per injector lifetime.
220
+ // v0.7.11 面板大改版(ce4658e)时这段随一次批量删除被静默移除,CHANGELOG 无
221
+ // 登记(#162 的 escapePromptVars 同刀误删、后来恢复,本函数漏了)——用户按
222
+ // CHANGELOG 开着开关,实际什么都不会发生。本次按 v0.7.2 语义原样恢复:键名、
223
+ // 默认值(false)、格式 `[当前时间: YYYY-MM-DD 周X HH:MM]` 全部不变,存量
224
+ // feature_flags 里的配置恢复即生效。
225
+ // 已注入过时间前缀的会话集合(#335 review:单值闩锁在 A→B→A 交替渲染下会
226
+ // 重复注入)。上限 500 防长驻进程无界增长,超限逐出最早记录。
227
+ const timePrefixDone = new Set();
228
+ let timePrefixBare = false;
229
+
230
+ function renderTimePrefix(ctx) {
231
+ if (config.injectTimePrefix !== true) return "";
232
+ const sessionId = ctx?.agent?.session?.id;
233
+ if (sessionId === undefined) {
234
+ if (timePrefixBare) return "";
235
+ timePrefixBare = true;
236
+ } else {
237
+ if (timePrefixDone.has(sessionId)) return "";
238
+ if (timePrefixDone.size >= 500) timePrefixDone.delete(timePrefixDone.keys().next().value);
239
+ timePrefixDone.add(sessionId);
240
+ }
241
+ const WEEKDAYS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
242
+ const now = new Date();
243
+ const pad = (n) => String(n).padStart(2, "0");
244
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
245
+ const time = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
246
+ return escapePromptVars(`[当前时间: ${date} ${WEEKDAYS[now.getDay()]} ${time}]`);
247
+ }
248
+
249
+ // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
250
+ // the materialized event log on every render — stateless, so it survives
251
+ // session switches and never persists anywhere.
252
+ const hot = createHotMemory({
253
+ maxRounds: config.hotMemoryRounds ?? 5,
254
+ maxTokens: config.hotMemoryMaxTokens ?? 2000
255
+ });
256
+
257
+ function renderHotContext(ctx) {
258
+ if (config.hotMemoryEnabled === false) return "";
259
+ const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
260
+ if (!rounds.length) return "";
261
+ hot.clear();
262
+ for (const r of rounds) hot.add(r);
263
+ const body = hot.getContext();
264
+ if (!body) return "";
265
+ return escapePromptVars(STR.hotHeader[language](rounds.length, body));
266
+ }
267
+
268
+ function render(candidates, pinnedStats = null) {
269
+ if (!candidates.length) return "";
270
+ const header = STR.memoryHeader[language];
271
+ const lines = [header];
272
+ let budget = MAX_BLOCK - header.length;
273
+ // #249 第一批:pin 池(约束/偏好)排在块头且不参与块的塌缩预算——「与情景
274
+ // 日志抢同一份预算后被降级」正是本议题要修的结构缺陷。单条仍有硬顶
275
+ // (PINNED_CONTENT_MAX),超出照旧带截断提示,不静默。
276
+ const pinnedCount = Math.max(0, Math.min(candidates.length, pinnedStats?.shown ?? 0));
277
+ // #24 块3:图召回线索行(graphHint)——引导语插在第一个线索行之前(保持块头
278
+ // 语义:先声明「这些不是事实」)。线索行自身按 graphHintLine 渲染(线索/ 前缀
279
+ // 区别于普通记忆行)。
280
+ let graphSeen = 0;
281
+ for (let i = 0; i < candidates.length; i++) {
282
+ const m = candidates[i];
283
+ const pinned = i < pinnedCount;
284
+ if (m.graphHint === true) graphSeen++;
285
+ // Epistemic trust (v0.4.5): when enabled, measured observations are
286
+ // flagged so the agent can weigh them above guesses/opinions.
287
+ const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
288
+ ? STR.verified[language]
289
+ : "";
290
+ const title = STR.entryTitle[language](m.title, m.importance);
291
+ const content = injectMemory(m, pinned ? PINNED_CONTENT_MAX : maxContent);
292
+ const full = m.graphHint === true
293
+ ? STR.graphHintLine[language](m.type, title, content)
294
+ : STR.entryLine[language](m.type, verified, title, content);
295
+ // 线索行引导语插在第一个线索行之前(保持块头语义:先声明「这些不是事实」)。
296
+ if (m.graphHint === true && graphSeen === 1) {
297
+ lines.push(STR.graphHintHeader[language]);
298
+ }
299
+ if (pinned) {
300
+ // pin 不扣块预算(上面那条设计注释的落地):pin 一条就够击穿 MAX_BLOCK
301
+ // (PINNED_CONTENT_MAX 2000 > MAX_BLOCK 1500),照扣会把 budget 压成负数,
302
+ // 同一轮随后的普通候选全部退化成标题行——正是本议题要修的结构缺陷。
303
+ lines.push(full);
304
+ } else if (budget - full.length >= 0) {
305
+ lines.push(full);
306
+ budget -= full.length;
307
+ } else {
308
+ lines.push(`- [${m.type}] ${verified}${title}`);
309
+ }
310
+ if (pinned && i === pinnedCount - 1) {
311
+ const hidden = Math.max(0, pinnedStats?.suppressed ?? 0);
312
+ if (hidden > 0) lines.push(STR.pinnedOverflow[language](hidden));
313
+ }
314
+ }
315
+ return escapePromptVars(lines.join("\n"));
316
+ }
317
+
318
+ // Bug4: the system-prompt render is synchronous, so the semantic query vector
319
+ // must be prefetched asynchronously and cached for the next assembly. The
320
+ // first render after a new user message may still fall back to the rule-based
321
+ // pick; later assemblies in the same session reuse the cached vector. Bounded
322
+ // cache (cap 8, drop oldest) so a long session never grows it unbounded.
323
+ const QUERY_VECTOR_CACHE_MAX = 8;
324
+ const queryVectorCache = new Map();
325
+ let lastPrefetched = "";
326
+
327
+ function prefetchQueryVector(query) {
328
+ if (!query || query === lastPrefetched || queryVectorCache.has(query)) return;
329
+ lastPrefetched = query;
330
+ service.embedQuery(query).then((vec) => {
331
+ if (Array.isArray(vec) && vec.length) {
332
+ queryVectorCache.set(query, vec);
333
+ if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
334
+ queryVectorCache.delete(queryVectorCache.keys().next().value);
335
+ }
336
+ }
337
+ }).catch(() => { /* prefetch is best-effort */ });
338
+ }
339
+
340
+ // User profile + rules: injected ahead of the memory block because they are
341
+ // always-relevant instructions the agent should follow every turn.
342
+ function renderUserSettings() {
343
+ const profile = settings.getProfile().trim();
344
+ const rules = settings.getRules();
345
+ if (!profile && !rules.length) return "";
346
+ const lines = [STR.userSettingsHeader[language]];
347
+ if (profile) lines.push(STR.profileLine[language](profile));
348
+ for (const rule of rules) lines.push(STR.ruleLine[language](rule));
349
+ return escapePromptVars(lines.join("\n"));
350
+ }
351
+
352
+ // #249 能力说明的系统提示段。order 150 = 插件指引段的既有惯例
353
+ // (ACP 的 ACP_SYSTEM_PROMPT 与 mnemon 的 routing 段都在 150)。文本是常量、
354
+ // 同会话内不随轮次变化,故不影响其后的前缀缓存,也不逐轮复读。宿主若不提供
355
+ // section seam 就静默跳过——#249 §3 的口径是「只用现成 seam,拿不到位的语义
356
+ // 降级处理」:能力说明仍落在工具描述上,不算失败。
357
+ // 走父/子闸门(#249 第二批):注入器本身只在 `autoInject` 开时挂载,这里是
358
+ // 第二道、也是同一个判据的显式落点——两处消费点共用 injectChildEnabled,
359
+ // 不在各自的地方重写「父关则子不生效」。
360
+ const guideSection = injectChildEnabled(config, "injectGuidanceEnabled") && typeof ctx.systemPrompt?.section === "function"
361
+ ? ctx.systemPrompt.section({ name: "memory-guide", order: 150, text: MEMORY_GUIDE_SECTION })
362
+ : null;
363
+
364
+ const disposers = [
365
+ ...(guideSection ? [guideSection] : []),
366
+ ctx.systemPrompt.context({
367
+ name: "memory",
368
+ order: 90,
369
+ text: (ctx) => {
370
+ // Bug4: pass the latest user query so injection prefers semantically
371
+ // relevant memories; lastUserQuery is best-effort (empty → legacy).
372
+ // The query vector is prefetched asynchronously (cached) because the
373
+ // render itself must stay synchronous.
374
+ const query = lastUserQuery(ctx);
375
+ if (query) prefetchQueryVector(query);
376
+ const queryVector = queryVectorCache.get(query);
377
+ // v0.8.0 A3:scope 随请求解析(解析器恒返回对象,身份取不到时两维为
378
+ // null);硬过滤与软加权的门控都在 injectCandidates 内——strict 看
379
+ // strictScope,软加权看 scopeEnabled 且至少一维可解析(issue #339)。
380
+ const scope = resolveSessionScope(ctx);
381
+ // Issue #205:跨轮轮换——最近 N 个查询轮次注入过的 id 本轮不再优先。
382
+ const sessionId = ctx?.agent?.session?.id ?? "_";
383
+ const rotate = recentInjectedIds(sessionId, query);
384
+ // rotateWindow 随集合一起传入:候选池按 maxItems×(N+1) 扩容——窗口要的
385
+ // 牌比既有 maxItems×2 池多时,轮换才有新鲜牌可换(#205 补测)。
386
+ // Issue #239(第 5 项):注入条数的查询自适应(默认关)。确定性强的话题收缩
387
+ // 条数、模糊话题维持上限——单向收缩,绝不越过 maxInjectedItems;判据只看查询
388
+ // 本身,不做额外检索(先探针检索等于白付一次 fuseRecall)。
389
+ const maxItems = config.injectUncertaintyAdaptive === true
390
+ ? adaptiveInjectBudget(query, baseMaxItems)
391
+ : baseMaxItems;
392
+ // #249 第一批:pin 池统计走可选出参,不动 injectCandidates 的数组契约。
393
+ const pinnedStats = {};
394
+ // Issue #380:注入前判定(preInjectGate)由 injectCandidates **内部**消费——
395
+ // 判定与滤除必须发生在它的 touchRecalled / recall 记账之前(#380 评审:与
396
+ // strictScope 同纪律,见 service.js 的「闸门还必须在 touchRecalled 之前」)。
397
+ // pin 池(#249 逐字保真)与 graphHint 线索行豁免由 service 侧按同口径切出。
398
+ // 渲染同步约束 → 闸门是 async prefetch + cache、同步消费:缓存命中当帧生效
399
+ // (enforce 滤除 / observe 记账),冷缓存首帧降级为原样注入、下一轮同 key
400
+ // 渲染生效——防线故障永不阻塞注入。帧状态经 gateStats 出参带回(同 pinnedStats
401
+ // 的出参口径),这里只读它做面板快照。
402
+ const gateStats = {};
403
+ const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold, scope, rotate, rotateWindow: rotationTurns, pinnedStats, gate, gateStats });
404
+ const pinnedShown = Math.max(0, pinnedStats.shown ?? 0);
405
+ const gateFrame = gateStats.frame ?? null;
406
+ // #249:pin 条目不进轮换历史——它们每轮固定前置,记进去只会占满轮换
407
+ // 窗口、挤掉情景候选的新鲜度(验收:pin 不参与跨轮轮换)。
408
+ recordInjection(sessionId, query, pinnedShown > 0 ? candidates.slice(pinnedShown) : candidates);
409
+ // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
410
+ // sees the short-term rounds first, then the cross-session recall —
411
+ // the documented injection order 1→2. Folding it here (instead of a
412
+ // separate context) keeps the prompt assembly stable at two blocks.
413
+ const hotText = renderHotContext(ctx);
414
+ const body = render(candidates, pinnedStats);
415
+ // #333(issue #34 恢复):时间前缀只在会话首轮出现(per-session 闩锁),
416
+ // 排在整个记忆块的最前——模型先知道「今天几号」,再看热上下文与长期记忆。
417
+ const timePrefix = renderTimePrefix(ctx);
418
+ // 拼接次序:时间 → 热上下文 → 长期记忆(三者都可能为空,逐级判空拼接)。
419
+ const withHot = !hotText ? body : body ? `${hotText}\n\n${body}` : hotText;
420
+ const finalBody = !timePrefix ? withHot : withHot ? `${timePrefix}\n\n${withHot}` : timePrefix;
421
+ // Issue #179:旁路缓存一帧——面板「注入预览」卡据此展示构成与体积。
422
+ // chars 为条目内容的截断后近似值(与 render 同一函数计长),totalChars
423
+ // 是本次实际返回块的精确长度。maxItems 反映自适应收缩后的生效值。
424
+ injectionSnapshot = {
425
+ at: Date.now(),
426
+ sessionId,
427
+ query: query || "",
428
+ maxItems,
429
+ threshold,
430
+ adaptive: config.injectUncertaintyAdaptive === true,
431
+ scoped: scope && (scope.agent_scope || scope.workspace_scope) ? scope : null,
432
+ rotated: rotate ? rotate.size : 0,
433
+ // Issue #380:闸门状态进快照(off/pending/observed/filtered),面板
434
+ // 「注入预览」卡据此展示判定是否生效与标记数。
435
+ gate: gateFrame ? { state: gateFrame.state, nFlagged: gateFrame.flaggedIds ? gateFrame.flaggedIds.size : null, judged: gateFrame.judged ?? null } : null,
436
+ hotChars: hotText.length,
437
+ entries: candidates.map((m) => ({
438
+ id: m.id,
439
+ type: m.type,
440
+ title: m.title,
441
+ importance: m.importance,
442
+ chars: injectMemory(m).length
443
+ })),
444
+ totalChars: finalBody.length
445
+ };
446
+ return finalBody;
447
+ }
448
+ }),
449
+ ctx.systemPrompt.context({
450
+ name: "user-settings",
451
+ order: 85,
452
+ text: renderUserSettings
453
+ })
454
+ ];
455
+
456
+ return () => {
457
+ queryVectorCache.clear();
458
+ rotationHistory.clear();
459
+ injectionSnapshot = null; // 注入器卸载即失效:快照不得跨生命周期存留
460
+ for (const dispose of disposers) {
461
+ if (typeof dispose === "function") dispose();
462
+ }
463
+ };
464
+ }