@modusensus/dsh-mneme 0.8.14 → 0.8.16

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