@modusensus/dsh-mneme 0.14.0-beta.1 → 0.14.0-beta.2

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 (543) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +830 -830
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +964 -964
  5. package/bin/dsh-mneme-choro.mjs +262 -262
  6. package/bin/dsh-mneme-mcp.mjs +510 -510
  7. package/bin/dsh-mneme-serve.mjs +151 -151
  8. package/cordis.patch.yml +21 -21
  9. package/docs/CONFIGURATION.md +407 -404
  10. package/docs/CONTINUITY.md +139 -139
  11. package/docs/DAEMON.md +57 -57
  12. package/docs/DIRECTORIES.md +114 -114
  13. package/docs/DISTILL.md +397 -371
  14. package/docs/DSH-GO.md +97 -97
  15. package/docs/ENTITIES.md +247 -247
  16. package/docs/FORGET.md +77 -77
  17. package/docs/KB.md +110 -110
  18. package/docs/LOCAL_MODEL.md +222 -222
  19. package/docs/SEMANTIC.md +256 -256
  20. package/docs/SHARE.md +552 -552
  21. package/docs/SLEEP.md +202 -202
  22. package/docs/STORAGE.md +122 -122
  23. package/docs/WORKFLOWS.md +366 -366
  24. package/lib/api-standalone.js +1007 -1007
  25. package/lib/api.js +3600 -3600
  26. package/lib/attachment-text.js +122 -122
  27. package/lib/bootstrap-http.js +105 -105
  28. package/lib/bootstrap.js +215 -215
  29. package/lib/candidates.js +454 -454
  30. package/lib/capabilities.js +819 -819
  31. package/lib/choro-command.js +111 -111
  32. package/lib/client.js +14420 -14322
  33. package/lib/commands.js +95 -95
  34. package/lib/config-keys.js +144 -144
  35. package/lib/config.js +1361 -1344
  36. package/lib/content-hash.js +54 -54
  37. package/lib/continuity.js +258 -258
  38. package/lib/date-hint.js +32 -0
  39. package/lib/diary/auto.js +190 -190
  40. package/lib/diary/compose.js +440 -440
  41. package/lib/diary/dir.js +59 -59
  42. package/lib/diary/export.js +97 -97
  43. package/lib/diary/index.js +26 -26
  44. package/lib/diary/library.js +189 -189
  45. package/lib/diary/qq-inbox.js +142 -142
  46. package/lib/diary/rollover.js +61 -61
  47. package/lib/diary/session-provider.js +122 -122
  48. package/lib/document-index.js +94 -94
  49. package/lib/document.js +322 -322
  50. package/lib/dream/clustering.js +123 -123
  51. package/lib/dream/decisions.js +945 -945
  52. package/lib/dream/narratives.js +44 -44
  53. package/lib/dream/sleep.js +2027 -2027
  54. package/lib/dream/triage.js +139 -139
  55. package/lib/dream.js +1879 -1879
  56. package/lib/dsh-go/host.js +162 -162
  57. package/lib/dsh-go/panel.js +2091 -2091
  58. package/lib/dsh-go/text.js +342 -342
  59. package/lib/dsh-go/views/common.js +68 -68
  60. package/lib/dsh-go/views/entity.js +48 -48
  61. package/lib/dsh-go/views/memory.js +198 -198
  62. package/lib/dsh-go/views/root.js +30 -30
  63. package/lib/dsh-go/views/settings.js +398 -398
  64. package/lib/dsh-go/views/status.js +51 -51
  65. package/lib/embedding.js +342 -342
  66. package/lib/entities/extractor.js +285 -285
  67. package/lib/fence.js +24 -24
  68. package/lib/graph/anchoring.js +184 -184
  69. package/lib/guide.js +74 -74
  70. package/lib/heat.js +144 -144
  71. package/lib/hot-memory.js +119 -119
  72. package/lib/image-describe.js +158 -0
  73. package/lib/index.js +852 -852
  74. package/lib/inject.js +656 -651
  75. package/lib/kb/index.js +309 -309
  76. package/lib/kb/routes.js +219 -219
  77. package/lib/kb/tools.js +148 -148
  78. package/lib/lang.js +607 -595
  79. package/lib/local-embedder.js +358 -358
  80. package/lib/maintenance.js +162 -162
  81. package/lib/memory-source.js +9 -9
  82. package/lib/mirror.js +330 -330
  83. package/lib/organize.js +456 -456
  84. package/lib/peak-hours.js +172 -172
  85. package/lib/pipeline-activities.js +178 -178
  86. package/lib/pipeline-attribution.js +165 -165
  87. package/lib/pipeline-command.js +279 -279
  88. package/lib/pipeline-confirm.js +142 -142
  89. package/lib/pipeline-exec.js +174 -174
  90. package/lib/pipeline-nudge-auto.js +129 -129
  91. package/lib/pipeline-nudge.js +1623 -1623
  92. package/lib/pipeline-observations.js +181 -181
  93. package/lib/pipeline-observe.js +133 -133
  94. package/lib/pipeline-runner.js +361 -361
  95. package/lib/pipeline-runs.js +442 -442
  96. package/lib/pipeline.js +716 -716
  97. package/lib/placement.js +13 -13
  98. package/lib/pre-inject-gate.js +354 -354
  99. package/lib/profile-extract.js +164 -164
  100. package/lib/profile-facts.js +356 -356
  101. package/lib/provenance-http.js +251 -251
  102. package/lib/quality-filter.js +162 -162
  103. package/lib/recall-stats.js +190 -190
  104. package/lib/reclaim-http.js +150 -150
  105. package/lib/reranker.js +269 -269
  106. package/lib/runtime/adopt.js +176 -176
  107. package/lib/runtime/closure.js +172 -172
  108. package/lib/runtime/download.js +247 -247
  109. package/lib/runtime/layout.js +265 -265
  110. package/lib/runtime/loader.js +252 -252
  111. package/lib/runtime/model-fetch.js +361 -361
  112. package/lib/runtime/provision.js +237 -237
  113. package/lib/runtime/tarball.js +130 -130
  114. package/lib/runtime/verify.js +223 -223
  115. package/lib/safe-slice.js +18 -18
  116. package/lib/scope-state.js +277 -277
  117. package/lib/scope.js +187 -187
  118. package/lib/search/adaptive.js +60 -60
  119. package/lib/search/bm25.js +96 -96
  120. package/lib/semantic.js +572 -572
  121. package/lib/sensitive-scan.js +209 -209
  122. package/lib/serve.js +228 -228
  123. package/lib/service.js +3268 -3268
  124. package/lib/session-gate.js +91 -91
  125. package/lib/session-usage.js +350 -350
  126. package/lib/settings.js +827 -817
  127. package/lib/share-http.js +281 -281
  128. package/lib/share-import.js +234 -234
  129. package/lib/share.js +335 -335
  130. package/lib/store.js +5895 -5895
  131. package/lib/summarize.js +1388 -1343
  132. package/lib/tools.js +1370 -1356
  133. package/lib/user-settings.js +230 -230
  134. package/lib/vector-index.js +180 -180
  135. package/lib/version-check.js +122 -122
  136. package/lib/wiki/claims.js +267 -267
  137. package/lib/wiki/cli-hint.js +90 -90
  138. package/lib/wiki/inject.js +164 -164
  139. package/lib/wiki/partition.js +200 -200
  140. package/lib/wiki/plan.js +214 -214
  141. package/lib/wiki/queries.js +640 -640
  142. package/lib/wiki/render.js +261 -261
  143. package/lib/wiki/scan.js +371 -371
  144. package/lib/wiki/t0.js +500 -500
  145. package/lib/wiki/t1-jobs.js +232 -232
  146. package/lib/wiki/t1.js +609 -609
  147. package/lib/write-admission.js +404 -404
  148. package/locale/en.json +6 -6
  149. package/locale/zh.json +6 -6
  150. package/package.json +1 -1
  151. package/runtime-manifest.json +526 -526
  152. package/scripts/benchmark-embed.js +201 -201
  153. package/scripts/benchmark-recall.js +249 -249
  154. package/scripts/benchmark-rerank.js +166 -166
  155. package/scripts/build-runtime-manifest.mjs +224 -224
  156. package/scripts/changelog-prep.mjs +91 -91
  157. package/scripts/check-sync.js +44 -44
  158. package/scripts/e2e-dsh.js +220 -220
  159. package/scripts/mneme-runtime.mjs +277 -277
  160. package/scripts/publish-gate.mjs +197 -197
  161. package/scripts/release-docs.mjs +210 -210
  162. package/scripts/release-notes.mjs +164 -164
  163. package/scripts/stress-dsh.js +255 -255
  164. package/scripts/sync-lib.js +47 -47
  165. package/scripts/sync-test-badge.mjs +69 -69
  166. package/scripts/test-count-sync.mjs +48 -48
  167. package/src/api-standalone.js +1007 -1007
  168. package/src/api.js +3600 -3600
  169. package/src/attachment-text.js +122 -122
  170. package/src/bootstrap-http.js +105 -105
  171. package/src/bootstrap.js +215 -215
  172. package/src/candidates.js +454 -454
  173. package/src/capabilities.js +819 -819
  174. package/src/choro-command.js +111 -111
  175. package/src/commands.js +95 -95
  176. package/src/config-keys.js +144 -144
  177. package/src/config.js +1361 -1344
  178. package/src/content-hash.js +54 -54
  179. package/src/continuity.js +258 -258
  180. package/src/date-hint.js +32 -0
  181. package/src/diary/auto.js +190 -190
  182. package/src/diary/compose.js +440 -440
  183. package/src/diary/dir.js +59 -59
  184. package/src/diary/export.js +97 -97
  185. package/src/diary/index.js +26 -26
  186. package/src/diary/library.js +189 -189
  187. package/src/diary/qq-inbox.js +142 -142
  188. package/src/diary/rollover.js +61 -61
  189. package/src/diary/session-provider.js +122 -122
  190. package/src/document-index.js +94 -94
  191. package/src/document.js +322 -322
  192. package/src/dream/clustering.js +123 -123
  193. package/src/dream/decisions.js +945 -945
  194. package/src/dream/narratives.js +44 -44
  195. package/src/dream/sleep.js +2027 -2027
  196. package/src/dream/triage.js +139 -139
  197. package/src/dream.js +1879 -1879
  198. package/src/dsh-go/host.js +162 -162
  199. package/src/dsh-go/panel.js +2091 -2091
  200. package/src/dsh-go/text.js +342 -342
  201. package/src/dsh-go/views/common.js +68 -68
  202. package/src/dsh-go/views/entity.js +48 -48
  203. package/src/dsh-go/views/memory.js +198 -198
  204. package/src/dsh-go/views/root.js +30 -30
  205. package/src/dsh-go/views/settings.js +398 -398
  206. package/src/dsh-go/views/status.js +51 -51
  207. package/src/embedding.js +342 -342
  208. package/src/entities/extractor.js +285 -285
  209. package/src/fence.js +24 -24
  210. package/src/graph/anchoring.js +184 -184
  211. package/src/guide.js +74 -74
  212. package/src/heat.js +144 -144
  213. package/src/hot-memory.js +119 -119
  214. package/src/image-describe.js +158 -0
  215. package/src/index.js +852 -852
  216. package/src/inject.js +656 -651
  217. package/src/kb/index.js +309 -309
  218. package/src/kb/routes.js +219 -219
  219. package/src/kb/tools.js +148 -148
  220. package/src/lang.js +607 -595
  221. package/src/local-embedder.js +358 -358
  222. package/src/maintenance.js +162 -162
  223. package/src/memory-source.js +9 -9
  224. package/src/mirror.js +330 -330
  225. package/src/organize.js +456 -456
  226. package/src/peak-hours.js +172 -172
  227. package/src/pipeline-activities.js +178 -178
  228. package/src/pipeline-attribution.js +165 -165
  229. package/src/pipeline-command.js +279 -279
  230. package/src/pipeline-confirm.js +142 -142
  231. package/src/pipeline-exec.js +174 -174
  232. package/src/pipeline-nudge-auto.js +129 -129
  233. package/src/pipeline-nudge.js +1623 -1623
  234. package/src/pipeline-observations.js +181 -181
  235. package/src/pipeline-observe.js +133 -133
  236. package/src/pipeline-runner.js +361 -361
  237. package/src/pipeline-runs.js +442 -442
  238. package/src/pipeline.js +716 -716
  239. package/src/placement.js +13 -13
  240. package/src/pre-inject-gate.js +354 -354
  241. package/src/profile-extract.js +164 -164
  242. package/src/profile-facts.js +356 -356
  243. package/src/provenance-http.js +251 -251
  244. package/src/quality-filter.js +162 -162
  245. package/src/recall-stats.js +190 -190
  246. package/src/reclaim-http.js +150 -150
  247. package/src/reranker.js +269 -269
  248. package/src/runtime/adopt.js +176 -176
  249. package/src/runtime/closure.js +172 -172
  250. package/src/runtime/download.js +247 -247
  251. package/src/runtime/layout.js +265 -265
  252. package/src/runtime/loader.js +252 -252
  253. package/src/runtime/model-fetch.js +361 -361
  254. package/src/runtime/provision.js +237 -237
  255. package/src/runtime/tarball.js +130 -130
  256. package/src/runtime/verify.js +223 -223
  257. package/src/safe-slice.js +18 -18
  258. package/src/scope-state.js +277 -277
  259. package/src/scope.js +187 -187
  260. package/src/search/adaptive.js +60 -60
  261. package/src/search/bm25.js +96 -96
  262. package/src/semantic.js +572 -572
  263. package/src/sensitive-scan.js +209 -209
  264. package/src/serve.js +228 -228
  265. package/src/service.js +3268 -3268
  266. package/src/session-gate.js +91 -91
  267. package/src/session-usage.js +350 -350
  268. package/src/settings.js +827 -817
  269. package/src/share-http.js +281 -281
  270. package/src/share-import.js +234 -234
  271. package/src/share.js +335 -335
  272. package/src/store.js +5895 -5895
  273. package/src/summarize.js +1388 -1343
  274. package/src/tools.js +1370 -1356
  275. package/src/user-settings.js +230 -230
  276. package/src/vector-index.js +180 -180
  277. package/src/version-check.js +122 -122
  278. package/src/wiki/claims.js +267 -267
  279. package/src/wiki/cli-hint.js +90 -90
  280. package/src/wiki/inject.js +164 -164
  281. package/src/wiki/partition.js +200 -200
  282. package/src/wiki/plan.js +214 -214
  283. package/src/wiki/queries.js +640 -640
  284. package/src/wiki/render.js +261 -261
  285. package/src/wiki/scan.js +371 -371
  286. package/src/wiki/t0.js +500 -500
  287. package/src/wiki/t1-jobs.js +232 -232
  288. package/src/wiki/t1.js +609 -609
  289. package/src/write-admission.js +404 -404
  290. package/test/adaptive-inject-budget.test.js +85 -85
  291. package/test/api-hardening.test.js +173 -173
  292. package/test/api-nudge-route.test.js +259 -259
  293. package/test/api-routes-gaps.test.js +1092 -1092
  294. package/test/api.test.js +3007 -2998
  295. package/test/attachment-text.test.js +139 -139
  296. package/test/audit.test.js +448 -448
  297. package/test/baseline-persist.test.js +248 -248
  298. package/test/benchmark.test.js +94 -94
  299. package/test/bm25-corpus-cache.test.js +145 -145
  300. package/test/bootstrap.test.js +228 -228
  301. package/test/candidates.test.js +345 -345
  302. package/test/capabilities.test.js +577 -577
  303. package/test/capacity-warning.test.js +262 -262
  304. package/test/changelog-prep.test.js +125 -125
  305. package/test/choro-command.test.js +218 -218
  306. package/test/cli-enums.test.js +37 -37
  307. package/test/cli-flag-value.test.js +86 -86
  308. package/test/cli-receive.test.js +390 -390
  309. package/test/cli-share.test.js +437 -437
  310. package/test/client-share.test.js +225 -225
  311. package/test/client.test.js +4595 -4425
  312. package/test/clustering.test.js +100 -100
  313. package/test/commands.test.js +106 -106
  314. package/test/config-keys-routes.test.js +233 -233
  315. package/test/config.test.js +153 -153
  316. package/test/conflict-freeze.test.js +344 -344
  317. package/test/conflict-ledger-enforce.test.js +452 -452
  318. package/test/conflict-ledger.test.js +242 -242
  319. package/test/conflict-reviewed.test.js +79 -79
  320. package/test/content-hash.test.js +204 -204
  321. package/test/continuity.test.js +452 -452
  322. package/test/contrast.test.js +432 -432
  323. package/test/date-hint.test.js +156 -0
  324. package/test/dedupe-candidate-window.test.js +180 -180
  325. package/test/dependency-overrides.test.js +78 -78
  326. package/test/diary-library.test.js +187 -187
  327. package/test/diary.test.js +576 -576
  328. package/test/differentiate-feedback.test.js +248 -248
  329. package/test/distill-tx-embed-gap.test.js +110 -110
  330. package/test/docs-config-keys.test.js +65 -65
  331. package/test/document-dir.test.js +233 -233
  332. package/test/document.test.js +703 -703
  333. package/test/dream-archive-guardrail.test.js +116 -116
  334. package/test/dream-baseline-clamp.test.js +174 -174
  335. package/test/dream-candidate-hybrid.test.js +281 -281
  336. package/test/dream-coverage-degrade.test.js +86 -86
  337. package/test/dream-decision-evidence.test.js +314 -314
  338. package/test/dream-failure-backoff.test.js +173 -173
  339. package/test/dream-fence.test.js +207 -207
  340. package/test/dream-maxtokens-fallback.test.js +132 -132
  341. package/test/dream-merge-guardrail.test.js +219 -219
  342. package/test/dream-peak-hours.test.js +194 -194
  343. package/test/dream.test.js +1528 -1528
  344. package/test/dsh-go-host.test.js +134 -134
  345. package/test/dsh-go-panel-actions.test.js +854 -854
  346. package/test/dsh-go-panel.test.js +251 -251
  347. package/test/embed-ready-poll.test.js +94 -94
  348. package/test/embed-text-reasons.test.js +112 -112
  349. package/test/embedding-cache-f32.test.js +276 -276
  350. package/test/embedding-ready.test.js +226 -226
  351. package/test/entities.test.js +711 -711
  352. package/test/entity-recall.test.js +179 -179
  353. package/test/epistemic.test.js +325 -325
  354. package/test/failure-query.test.js +147 -147
  355. package/test/failure-retention.test.js +105 -105
  356. package/test/fnew-0112.test.js +311 -311
  357. package/test/fnew-03.test.js +422 -422
  358. package/test/forget-corrections.test.js +70 -70
  359. package/test/graph-anchoring.test.js +184 -184
  360. package/test/graph-api.test.js +333 -333
  361. package/test/graph-boosted-relations.test.js +189 -189
  362. package/test/graph-inject-budget.test.js +103 -103
  363. package/test/graph-multipath.test.js +269 -269
  364. package/test/graph-passive-confirm.test.js +91 -91
  365. package/test/graph-weight-evolution.test.js +104 -104
  366. package/test/heat.test.js +175 -175
  367. package/test/helpers/dream-mock.js +86 -86
  368. package/test/helpers/peer-worker.mjs +25 -25
  369. package/test/helpers/runtime-source.js +60 -60
  370. package/test/helpers/tar-builder.js +80 -80
  371. package/test/helpers/write-admission-samples.js +312 -312
  372. package/test/hot-memory.test.js +259 -259
  373. package/test/image-description.test.js +271 -0
  374. package/test/image-memory.test.js +170 -170
  375. package/test/inject-content-cap.test.js +91 -91
  376. package/test/inject-first-round-bm25.test.js +89 -89
  377. package/test/inject-heat.test.js +77 -77
  378. package/test/inject-parent-gate.test.js +134 -109
  379. package/test/inject-pin-explicit.test.js +300 -300
  380. package/test/inject-pin-vector-crowd.test.js +225 -225
  381. package/test/inject-pools.test.js +195 -195
  382. package/test/inject-recall.test.js +172 -172
  383. package/test/inject-rotation.test.js +161 -161
  384. package/test/inject.test.js +553 -553
  385. package/test/issue-617-step1-query-and-fusion.test.js +361 -361
  386. package/test/kb-api-wiring.test.js +128 -128
  387. package/test/kb-collections.test.js +272 -272
  388. package/test/kb-routes.test.js +379 -379
  389. package/test/lang.test.js +98 -98
  390. package/test/lastrunat-persist.test.js +101 -101
  391. package/test/lib-smoke.test.js +116 -116
  392. package/test/llm-audit.test.js +815 -815
  393. package/test/llm-message-source.test.js +207 -207
  394. package/test/local-embedder.test.js +292 -292
  395. package/test/maintenance.test.js +501 -501
  396. package/test/mcp-stdio.test.js +385 -385
  397. package/test/mint-source.test.js +311 -311
  398. package/test/mirror-dirty.test.js +424 -424
  399. package/test/mirror-edit-digest.test.js +187 -187
  400. package/test/mirror-generation.test.js +499 -499
  401. package/test/mirror-types.test.js +208 -208
  402. package/test/mirror.test.js +249 -249
  403. package/test/narrative-bars.test.js +162 -162
  404. package/test/organize-tool.test.js +232 -232
  405. package/test/organize.test.js +418 -418
  406. package/test/panel-chart-scale.test.js +90 -90
  407. package/test/panel-tokens.test.js +245 -245
  408. package/test/peak-hours-observability.test.js +70 -70
  409. package/test/peer-blockers.test.js +193 -193
  410. package/test/persona-addressing.test.js +83 -83
  411. package/test/persona-api.test.js +172 -172
  412. package/test/persona-by-session.test.js +568 -568
  413. package/test/persona-flag.test.js +36 -36
  414. package/test/persona-inject.test.js +145 -145
  415. package/test/persona-settings.test.js +198 -198
  416. package/test/pipeline-activities.test.js +155 -155
  417. package/test/pipeline-attribution.test.js +175 -175
  418. package/test/pipeline-command.test.js +243 -243
  419. package/test/pipeline-confirm.test.js +148 -148
  420. package/test/pipeline-exec.test.js +172 -172
  421. package/test/pipeline-nudge-auto.test.js +248 -248
  422. package/test/pipeline-nudge.test.js +1278 -1278
  423. package/test/pipeline-observations.test.js +157 -157
  424. package/test/pipeline-observe.test.js +127 -127
  425. package/test/pipeline-r1r2.test.js +278 -278
  426. package/test/pipeline-runner.test.js +468 -468
  427. package/test/pipeline-runs.test.js +767 -767
  428. package/test/pipeline.test.js +636 -636
  429. package/test/placement.test.js +36 -36
  430. package/test/policy-epoch.test.js +259 -259
  431. package/test/pre-inject-gate.test.js +444 -444
  432. package/test/profile-extract.test.js +269 -269
  433. package/test/profile-facts.test.js +492 -492
  434. package/test/prompt-stance.test.js +128 -128
  435. package/test/provenance-http.test.js +367 -367
  436. package/test/publish-gate.test.js +272 -272
  437. package/test/quality-backfill.test.js +290 -290
  438. package/test/quality-filter.test.js +295 -295
  439. package/test/readme-claims.test.js +113 -113
  440. package/test/reasoning-effort.test.js +752 -752
  441. package/test/recall-anti-update.test.js +82 -82
  442. package/test/recall-evals.test.js +253 -253
  443. package/test/recall-layer.test.js +326 -326
  444. package/test/recall-retention.test.js +128 -128
  445. package/test/recall-stats.test.js +274 -274
  446. package/test/receipt-chain.test.js +451 -451
  447. package/test/reclaim-http.test.js +209 -209
  448. package/test/reflection-update-gate.test.js +129 -129
  449. package/test/reflection.test.js +226 -226
  450. package/test/reindex-backfill.test.js +475 -475
  451. package/test/reindex-scheduler.test.js +369 -369
  452. package/test/release-docs.test.js +156 -156
  453. package/test/release-notes.test.js +265 -265
  454. package/test/release-workflow.test.js +93 -93
  455. package/test/reranker-single-logit.test.js +73 -73
  456. package/test/reranker.test.js +197 -197
  457. package/test/resident-status.test.js +83 -83
  458. package/test/route-policy.test.js +113 -113
  459. package/test/runtime-adopt.test.js +206 -206
  460. package/test/runtime-cli.test.js +89 -89
  461. package/test/runtime-closure.test.js +193 -193
  462. package/test/runtime-download.test.js +302 -302
  463. package/test/runtime-layout.test.js +163 -163
  464. package/test/runtime-loader.test.js +255 -255
  465. package/test/runtime-manifest.test.js +159 -159
  466. package/test/runtime-model-fetch.test.js +348 -348
  467. package/test/runtime-provision.test.js +101 -101
  468. package/test/runtime-tarball.test.js +81 -81
  469. package/test/runtime-verify.test.js +319 -319
  470. package/test/scope-candidates.test.js +491 -491
  471. package/test/scope-distill-stamp.test.js +134 -134
  472. package/test/scope-explicit.test.js +452 -452
  473. package/test/scope-inject-soft.test.js +106 -106
  474. package/test/scope-optional-service.test.js +110 -110
  475. package/test/scope-retrieval.test.js +197 -197
  476. package/test/scope-state.test.js +610 -610
  477. package/test/scope-storage.test.js +255 -255
  478. package/test/scope-strict.test.js +367 -367
  479. package/test/search-fusion.test.js +90 -90
  480. package/test/security-doc.test.js +188 -188
  481. package/test/semantic.test.js +124 -124
  482. package/test/sensitive-scan.test.js +251 -251
  483. package/test/serve-bin.test.js +121 -121
  484. package/test/serve.test.js +258 -258
  485. package/test/service-search.test.js +174 -174
  486. package/test/service.test.js +410 -410
  487. package/test/session-gate.test.js +264 -264
  488. package/test/session-usage.test.js +317 -317
  489. package/test/settings.test.js +273 -273
  490. package/test/share-foreign-rows.test.js +144 -144
  491. package/test/share-http.test.js +144 -144
  492. package/test/share-import.test.js +577 -577
  493. package/test/share-imported-guard.test.js +311 -311
  494. package/test/share-imported-identity.test.js +111 -111
  495. package/test/share-pack.test.js +511 -511
  496. package/test/share-receive-http.test.js +756 -756
  497. package/test/share-routes.test.js +337 -337
  498. package/test/share-store.test.js +133 -133
  499. package/test/share-validate.test.js +101 -101
  500. package/test/skip-invalid-restore.test.js +262 -262
  501. package/test/sleep-action-set.test.js +441 -441
  502. package/test/sleep-catchup.test.js +315 -315
  503. package/test/sleep-failure-backoff.test.js +156 -156
  504. package/test/sleep-heat.test.js +174 -174
  505. package/test/sleep-scheduler-rearm.test.js +89 -89
  506. package/test/sleep.test.js +1455 -1455
  507. package/test/standalone-api.test.js +1344 -1344
  508. package/test/store-vector-cache.test.js +98 -98
  509. package/test/store-write-path-columns.test.js +191 -191
  510. package/test/store.test.js +744 -744
  511. package/test/stress.test.js +209 -209
  512. package/test/summarize-occurred-at.test.js +127 -127
  513. package/test/summarize-parse-diagnostics.test.js +75 -75
  514. package/test/summarize-reasoning-effort.test.js +189 -189
  515. package/test/summarize.test.js +2251 -2251
  516. package/test/supersede-state-tracking.test.js +394 -394
  517. package/test/test-count-sync.test.js +71 -71
  518. package/test/tool-state-ignore.test.js +65 -65
  519. package/test/tools-dto-schema-matrix.test.js +398 -398
  520. package/test/tools-memory-get-schema.test.js +65 -65
  521. package/test/tools.test.js +585 -585
  522. package/test/updated-at-semantics.test.js +113 -113
  523. package/test/user-settings-preview.test.js +127 -127
  524. package/test/user-settings-segments.test.js +527 -527
  525. package/test/vector-index.test.js +334 -334
  526. package/test/version-check.test.js +152 -152
  527. package/test/webServer-optional.test.js +82 -82
  528. package/test/wiki-api.test.js +734 -734
  529. package/test/wiki-claims.test.js +194 -194
  530. package/test/wiki-cli-hint.test.js +118 -118
  531. package/test/wiki-inject.test.js +265 -265
  532. package/test/wiki-partition.test.js +112 -112
  533. package/test/wiki-plan.test.js +80 -80
  534. package/test/wiki-provenance.test.js +202 -202
  535. package/test/wiki-queries.test.js +398 -398
  536. package/test/wiki-scan.test.js +208 -208
  537. package/test/wiki-store.test.js +190 -190
  538. package/test/wiki-t0.test.js +456 -456
  539. package/test/wiki-t1-jobs.test.js +125 -125
  540. package/test/wiki-t1.test.js +460 -460
  541. package/test/wiki-tools.test.js +176 -176
  542. package/test/workflow-guards.test.js +155 -155
  543. package/test/write-admission.test.js +668 -668
package/lib/inject.js CHANGED
@@ -1,651 +1,656 @@
1
- import { createScopeResolver, sessionOf } from "./scope.js";
2
- import { createHotMemory, roundsFromEvents } from "./hot-memory.js";
3
- import { STR, langOf } from "./lang.js";
4
- import { escapePromptVars as escapePromptVarsWithConfig, renderUserSettingsBlock } from "./user-settings.js";
5
- import { MEMORY_GUIDE_SECTION } from "./guide.js";
6
- import { adaptiveInjectBudget } from "./search/adaptive.js";
7
- import { injectChildEnabled } from "./config.js";
8
- import { safeSlice } from "./safe-slice.js";
9
-
10
- // Issue #179:注入预览的数据底座。systemPrompt 渲染是同步回调,面板只能事后
11
- // 拉取,所以在这里旁路缓存「最近一帧组装」——快照就是本次渲染用过的同一份
12
- // candidates/hotText/body,不重新检索、不二次组装,零额外开销。模块级单例:
13
- // 注入器全局唯一(index.js 仅在 autoInject 开启时注册一个),面板经 api.js 的
14
- // 只读 getter 读取;autoInject 关闭时注入器不存在,快照保持 null——「预览
15
- // 不可用」本身就是「注入关闭」的诚实呈现。
16
- let injectionSnapshot = null;
17
- export function getInjectionSnapshot() {
18
- return injectionSnapshot;
19
- }
20
-
21
- // 「模型可见事件 seq」集合:宿主在 session.surface.nodes 维护可见面——rewind 的
22
- // surfaceOp replace 与 compact 的隐藏替换都作用在这层(dsh-rewind 插件即据此计算
23
- // 替换区间)。拿不到(老版本宿主)返回 null,调用方退回「全量事件」的旧行为。
24
- // 读取必须在 try 内:`surface.nodes` 是宿主 getter,其 _assertProjections 在消息投影
25
- // 所属插件被移除时会 throw(dsh-session lib/types/surface.js)。抛出等同于「没有
26
- // 可见面」,绝不能让整块热记忆消失——那是比旧偏差更糟的退化。
27
- function visibleSeqsOf(session) {
28
- try {
29
- const nodes = session?.surface?.nodes;
30
- return Array.isArray(nodes) ? new Set(nodes) : null;
31
- } catch {
32
- return null;
33
- }
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
- //
43
- // v0.9.0:导出给 tools.js 的 memory_update 用。失败记录表的 query 与注入
44
- // 候选问的是同一件事——「当时到底想干什么」;这条取原话的路只该有一份实现。
45
- // 复制一份的代价本仓库付过几次(src/lib 平价、snapshotEvents 兼容层),所以
46
- // 这里只加 export,不改行为。
47
- //
48
- // #617:多带一个 seq——注入器要拿它判断「待认领票据是否比事件流更新」(见
49
- // createInjector 的 pendingQueries)。seq 是宿主事件序号,取不到时为 null
50
- // (老版本宿主 / 测试夹具),调用方按 null 参与相等比较,不做真假推断。
51
- export function lastUserMessageInfo(ctx) {
52
- try {
53
- const session = ctx?.agent?.session;
54
- // DSH ≥0.1.2-rc only exposes events via snapshotEvents(); older builds
55
- // still have the .events property, so fall back to it.
56
- const events = session?.snapshotEvents?.() ?? session?.events;
57
- if (!Array.isArray(events) || events.length === 0) return { text: "", seq: null };
58
- const visibleSeqs = visibleSeqsOf(session);
59
- for (let i = events.length - 1; i >= 0; i--) {
60
- const event = events[i];
61
- // 被撤回/被压缩遮蔽的事件不算「最近一条用户消息」(与 extractRounds 同口径)。
62
- if (visibleSeqs && !visibleSeqs.has(event?.seq)) continue;
63
- if (event?.type !== "user/message") continue;
64
- const kind = event.data?.source?.kind;
65
- if (kind !== undefined && kind !== "user") continue;
66
- const parts = event.data?.content;
67
- if (!Array.isArray(parts) || parts.length === 0) continue;
68
- return {
69
- text: safeSlice(
70
- parts
71
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
72
- .filter(Boolean)
73
- .join("\n"),
74
- 500
75
- ),
76
- seq: event?.seq ?? null
77
- };
78
- }
79
- } catch { /* session internals unavailable: degrade to no query */ }
80
- return { text: "", seq: null };
81
- }
82
-
83
- export function lastUserQuery(ctx) {
84
- return lastUserMessageInfo(ctx).text;
85
- }
86
-
87
- // 认领消息 → 查询文本。#617 的补位票据就是这里算出来的字符串:判定口径与
88
- // user/message 事件同源(content parts + source.kind),于是「插件注入的上下文」
89
- // 这类非人类消息照样被跳过,票据不会拿插件自己的话当用户问题。
90
- function inboxMessageQuery(message) {
91
- try {
92
- const parts = message?.content ?? message?.data?.content;
93
- if (!Array.isArray(parts) || parts.length === 0) return "";
94
- const kind = message?.source?.kind ?? message?.data?.source?.kind;
95
- if (kind !== undefined && kind !== "user") return "";
96
- return safeSlice(
97
- parts
98
- .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
99
- .filter(Boolean)
100
- .join("\n"),
101
- 500
102
- );
103
- } catch {
104
- return "";
105
- }
106
- }
107
-
108
- // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
109
- // next assistant reply. The pairing lives in hot-memory.js (roundsFromEvents)
110
- // so it can be unit-tested directly; this adapter only resolves the session's
111
- // raw event log and the model-visible seq set (session.surface.nodes — see
112
- // visibleSeqsOf). Rewind-shadowed / compacted events are thereby excluded:
113
- // hot memory and the model see the same conversation. Best-effort: returns []
114
- // on any failure, and the hot block simply does not render.
115
- //
116
- // omitPendingRound: true(Issue #637):prompt 组装发生的时刻,尾部 pending 轮
117
- // 就是「正在组装的这一轮」——它的提问已经作为真实 user message 在本条 prompt
118
- // 里,热记忆里再渲染一份空 `A:` 行是纯重复,且回答落地后该行会从空 `A:` 抖成
119
- // 正文:宿主「文本变了就追加快照」的契机会让同一轮的注入块被追加多份 runtime-
120
- // context,旧份永久留在会话历史(#637 报告:4 轮 → 10 份、75% 重复)。省略之后
121
- // 一轮内热块文本恒定、回答落地时恰好变一次——快照数降到每轮一份。直调方
122
- // (tests / 其他消费者)不传这个参数,保持完整配对。
123
- function extractRounds(ctx, maxRounds) {
124
- try {
125
- const session = ctx?.agent?.session;
126
- // DSH ≥0.1.2-rc only exposes events via snapshotEvents(); older builds
127
- // still have the .events property, so fall back to it.
128
- const events = session?.snapshotEvents?.() ?? session?.events;
129
- if (!Array.isArray(events) || events.length === 0) return [];
130
- return roundsFromEvents(events, maxRounds, visibleSeqsOf(session), { omitPendingRound: true });
131
- } catch {
132
- return [];
133
- }
134
- }
135
-
136
- export function createInjector(ctx, service, settings, config, gate = null, sessionGate = null, choroInject = null, factsInject = null) {
137
- const language = langOf(config);
138
- const baseMaxItems = config.maxInjectedItems ?? 5;
139
- const threshold = config.importanceThreshold ?? 3;
140
- // Issue #205:注入位跨轮轮换。rotationTurns = 最近 N 个「不同用户查询」轮次
141
- // 注入过的记忆本轮不再优先(0 = 关闭,保持既有行为)。历史按会话维护——
142
- // 新会话从零开始;同一查询的多次渲染(工具调用轮)视为同一轮,不推进窗口。
143
- const rotationTurns = Math.max(0, Math.floor(config.injectRotationTurns ?? 0));
144
- const rotationHistory = new Map(); // sessionId -> [{ query, ids: Set }]
145
- const ROTATION_HISTORY_MAX = 32; // 覆盖 max(20) 配置档仍有余量
146
-
147
- function recentInjectedIds(sessionId, query) {
148
- if (rotationTurns <= 0) return null;
149
- const deque = rotationHistory.get(sessionId);
150
- if (!deque || deque.length === 0) return null;
151
- // 只看「之前的轮次」:排除与当前查询相同的条目——同一查询的重复渲染
152
- // (工具调用轮)不该拿本轮自己的集合来转自己。
153
- const prior = query ? deque.filter((e) => e.query !== query) : deque;
154
- if (prior.length === 0) return null;
155
- const recent = new Set();
156
- for (const entry of prior.slice(-rotationTurns)) {
157
- for (const id of entry.ids) recent.add(id);
158
- }
159
- return recent.size > 0 ? recent : null;
160
- }
161
-
162
- function recordInjection(sessionId, query, candidates) {
163
- if (rotationTurns <= 0 || !query) return;
164
- const deque = rotationHistory.get(sessionId) ?? [];
165
- const ids = new Set(candidates.map((c) => c.id));
166
- const last = deque[deque.length - 1];
167
- if (last && last.query === query) {
168
- last.ids = ids; // 同一查询的重复渲染:覆盖本轮内容,不推进窗口
169
- } else {
170
- deque.push({ query, ids });
171
- if (deque.length > ROTATION_HISTORY_MAX) deque.shift();
172
- rotationHistory.set(sessionId, deque);
173
- }
174
- }
175
- // v0.8.0 A3(issue #17):注入路径的会话 scope 解析——strictScope 硬过滤
176
- // 需要。渲染 ctx 与工具 exec 同形(agent.session),解析器直接复用。
177
- // logger 透传:registry 反查失败时 warnOnce 才有出口。
178
- const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
179
-
180
- // Bug6: bound the injected memory block. Each entry's content is truncated to
181
- // injectContentMaxChars chars (issue #164①: configurable, was a hardcoded
182
- // 300); a truncated entry carries a tail hint (limit / original length /
183
- // memory_get id) so the cut is never silent — BUDGET_EXCEEDED principle, the
184
- // agent can always fetch the full text. The whole block gets a block budget
185
- // (scales up with the per-entry cap so raising the cap is not defeated by a
186
- // stale 1500) and an entry that would exceed it collapses to its title only.
187
- const maxContent = config.injectContentMaxChars ?? 300;
188
- const MAX_BLOCK = Math.max(1500, maxContent + 600);
189
- // #249 第一批:pin 条目的正文硬顶。逐字保真不等于无界——单条上限取
190
- // injectContentMaxChars 与 2000 的较大者,默认档下约束/偏好不会因常规截断
191
- // 失真,同时给「一条超长约束每轮吃满常驻段」留一道闸(超顶仍带截断提示)。
192
- const PINNED_CONTENT_MAX = Math.max(maxContent, 2000);
193
-
194
- // Compressed injection (v0.5.0 2.1): a sleep-demoted row carries its summary in
195
- // `content` with the original parked in `_full_content` — inject the summary
196
- // verbatim instead of re-truncating the (already short) text. 但「降级过」不等于
197
- // 「天然够短」:原先那条 `_full_content` 早返回的唯一效果就是**跳过 maxLength**
198
- // (两条分支取的都是 m.content),于是 pin 的硬顶在这一路上形同不存在(#266 评审)。
199
- // 现在只有一条截断路径:超限照旧带提示,原文永远可通过 memory_get 取回。
200
- function injectMemory(m, maxLength = maxContent) {
201
- const text = String(m?.content ?? "");
202
- if (text.length <= maxLength) return text;
203
- return `${safeSlice(text, maxLength)}…${STR.truncatedHint[language](maxLength, text.length, m.id)}`;
204
- }
205
-
206
- // Prompt-variable brace escaping (issue #162, restored from v0.7.4 #40):
207
- // DSH's interpolate() scans every injected section for `{{...}}` and throws
208
- // unless the variable name matches /^[a-z][a-z0-9_]*$/ — memory/profile
209
- // content carrying legal template syntax (docker `--format "{{.Server.Version}}"`,
210
- // Obsidian-style `{{hl|}}`, `{{挖空}}`, `{{关键词}}`) would hit an illegal
211
- // variable name and throw, crashing the whole turn. At the injection boundary
212
- // we escape every run of 2+ consecutive braces, inserting a `\` between each
213
- // pair, so no `{{`/`}}` substring survives into the prompt: `{{a}}` → `{\{a\}\}`,
214
- // and odd runs like `{{{a}}}` (which pair-wise escaping would leave with a
215
- // literal `{{`) are handled too. The text keeps its readable template form,
216
- // the transform is idempotent (escaped braces are single + `\`, never two
217
- // adjacent), and single braces pass through untouched — interpolate only
218
- // scans `{{`. Off via config.escapePromptVariables=false (default true).
219
- function escapePromptVars(text) {
220
- // 实现搬到 src/user-settings.js:预览路由要用同一份转义,否则「注入生效文本」的
221
- // 预览又是第二份实现、又会漂。这里保留同名闭包,其余调用点一字不动。
222
- return escapePromptVarsWithConfig(config, text);
223
- }
224
-
225
- // Time-prefix injection (issue #34,恢复于 #333): opt-in, off by default.
226
- // When enabled the current date/time is injected once per conversation — at
227
- // the first prompt assembly of a new session — so the model can sense what
228
- // time/day it is. A per-session latch means later assemblies in the same
229
- // session never re-inject; a bare render ctx (no session id) falls back to
230
- // once per injector lifetime.
231
- // v0.7.11 面板大改版(ce4658e)时这段随一次批量删除被静默移除,CHANGELOG 无
232
- // 登记(#162 的 escapePromptVars 同刀误删、后来恢复,本函数漏了)——用户按
233
- // CHANGELOG 开着开关,实际什么都不会发生。本次按 v0.7.2 语义原样恢复:键名、
234
- // 默认值(false)、格式 `[当前时间: YYYY-MM-DD 周X HH:MM]` 全部不变,存量
235
- // feature_flags 里的配置恢复即生效。
236
- // 已注入过时间前缀的会话集合(#335 review:单值闩锁在 A→B→A 交替渲染下会
237
- // 重复注入)。上限 500 防长驻进程无界增长,超限逐出最早记录。
238
- const timePrefixDone = new Set();
239
- let timePrefixBare = false;
240
-
241
- function renderTimePrefix(ctx) {
242
- if (config.injectTimePrefix !== true) return "";
243
- const sessionId = ctx?.agent?.session?.id;
244
- if (sessionId === undefined) {
245
- if (timePrefixBare) return "";
246
- timePrefixBare = true;
247
- } else {
248
- if (timePrefixDone.has(sessionId)) return "";
249
- if (timePrefixDone.size >= 500) timePrefixDone.delete(timePrefixDone.keys().next().value);
250
- timePrefixDone.add(sessionId);
251
- }
252
- const WEEKDAYS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
253
- const now = new Date();
254
- const pad = (n) => String(n).padStart(2, "0");
255
- const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
256
- const time = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
257
- return escapePromptVars(`[当前时间: ${date} ${WEEKDAYS[now.getDay()]} ${time}]`);
258
- }
259
-
260
- // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
261
- // the materialized event log on every render — stateless, so it survives
262
- // session switches and never persists anywhere.
263
- const hot = createHotMemory({
264
- maxRounds: config.hotMemoryRounds ?? 5,
265
- maxTokens: config.hotMemoryMaxTokens ?? 2000
266
- });
267
-
268
- function renderHotContext(ctx) {
269
- if (config.hotMemoryEnabled === false) return "";
270
- const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
271
- if (!rounds.length) return "";
272
- hot.clear();
273
- for (const r of rounds) hot.add(r);
274
- const body = hot.getContext();
275
- if (!body) return "";
276
- return escapePromptVars(STR.hotHeader[language](rounds.length, body));
277
- }
278
-
279
- function render(candidates, pinnedStats = null) {
280
- if (!candidates.length) return "";
281
- const header = STR.memoryHeader[language];
282
- const lines = [header];
283
- let budget = MAX_BLOCK - header.length;
284
- // #249 第一批:pin 池(约束/偏好)排在块头且不参与块的塌缩预算——「与情景
285
- // 日志抢同一份预算后被降级」正是本议题要修的结构缺陷。单条仍有硬顶
286
- // (PINNED_CONTENT_MAX),超出照旧带截断提示,不静默。
287
- const pinnedCount = Math.max(0, Math.min(candidates.length, pinnedStats?.shown ?? 0));
288
- // #24 块3:图召回线索行(graphHint)——引导语插在第一个线索行之前(保持块头
289
- // 语义:先声明「这些不是事实」)。线索行自身按 graphHintLine 渲染(线索/ 前缀
290
- // 区别于普通记忆行)。
291
- let graphSeen = 0;
292
- for (let i = 0; i < candidates.length; i++) {
293
- const m = candidates[i];
294
- const pinned = i < pinnedCount;
295
- if (m.graphHint === true) graphSeen++;
296
- // Epistemic trust (v0.4.5): when enabled, measured observations are
297
- // flagged so the agent can weigh them above guesses/opinions.
298
- const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
299
- ? STR.verified[language]
300
- : "";
301
- const title = STR.entryTitle[language](m.title, m.importance);
302
- // Issue #641(T4 注入标注):conflictNote 由 injectCandidates 在 enforce
303
- // 档下挂上(矛盾对同批时的机械排位说明)。#537 的教训:标注必须进注入
304
- // 文本本体,不能只留在账本里——消费方看不见的标注等于没标。
305
- const content = injectMemory(m, pinned ? PINNED_CONTENT_MAX : maxContent)
306
- + (m.conflictNote ? "\n" + m.conflictNote : "");
307
- const full = m.graphHint === true
308
- ? STR.graphHintLine[language](m.type, title, content)
309
- : STR.entryLine[language](m.type, verified, title, content);
310
- // 线索行引导语插在第一个线索行之前(保持块头语义:先声明「这些不是事实」)。
311
- if (m.graphHint === true && graphSeen === 1) {
312
- lines.push(STR.graphHintHeader[language]);
313
- }
314
- if (pinned) {
315
- // pin 不扣块预算(上面那条设计注释的落地):pin 一条就够击穿 MAX_BLOCK
316
- // (PINNED_CONTENT_MAX 2000 > MAX_BLOCK 1500),照扣会把 budget 压成负数,
317
- // 同一轮随后的普通候选全部退化成标题行——正是本议题要修的结构缺陷。
318
- lines.push(full);
319
- } else if (budget - full.length >= 0) {
320
- lines.push(full);
321
- budget -= full.length;
322
- } else {
323
- lines.push(`- [${m.type}] ${verified}${title}`);
324
- }
325
- if (pinned && i === pinnedCount - 1) {
326
- const hidden = Math.max(0, pinnedStats?.suppressed ?? 0);
327
- if (hidden > 0) lines.push(STR.pinnedOverflow[language](hidden));
328
- }
329
- }
330
- return escapePromptVars(lines.join("\n"));
331
- }
332
-
333
- // Bug4: the system-prompt render is synchronous, so the semantic query vector
334
- // must be prefetched asynchronously and cached for the next assembly. The
335
- // first render after a new user message may still fall back to the rule-based
336
- // pick; later assemblies in the same session reuse the cached vector. Bounded
337
- // cache (cap 8, drop oldest) so a long session never grows it unbounded.
338
- //
339
- // #617 根因 B:旧实现用一个 lastPrefetched 字符串做去重,且它在 await 之前
340
- // 就置位——同一条查询第一次失败(模型没下好、超时)之后**永不重试**,而那
341
- // 恰好是最需要重试的一次。这里换成三件套:inflight Map 去重(渲染同一步会
342
- // 被求值两次:assemble 一次、refreshContext 一次,同一条查询只该嵌一次)、
343
- // 失败冷却 15s(失败可重试,但不许每次渲染都拿一次失败去撞模型)、返回
344
- // Promise(调用方/测试能等到它,而不是靠魔法延时)。
345
- const QUERY_VECTOR_CACHE_MAX = 8;
346
- const PREFETCH_FAIL_COOLDOWN_MS = 15000;
347
- const queryVectorCache = new Map();
348
- const inflightPrefetches = new Map(); // query -> Promise<vector|null>
349
- const prefetchFailedAt = new Map(); // query -> ms
350
-
351
- function prefetchQueryVector(query) {
352
- if (!query) return null;
353
- const cached = queryVectorCache.get(query);
354
- if (cached) return Promise.resolve(cached);
355
- const inflight = inflightPrefetches.get(query);
356
- if (inflight) return inflight;
357
- const failedAt = prefetchFailedAt.get(query);
358
- if (failedAt !== undefined && Date.now() - failedAt < PREFETCH_FAIL_COOLDOWN_MS) return null;
359
- const pending = service.embedQuery(query).then((vec) => {
360
- if (Array.isArray(vec) && vec.length) {
361
- queryVectorCache.set(query, vec);
362
- if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
363
- queryVectorCache.delete(queryVectorCache.keys().next().value);
364
- }
365
- prefetchFailedAt.delete(query);
366
- return vec;
367
- }
368
- prefetchFailedAt.set(query, Date.now());
369
- return null;
370
- }).catch(() => {
371
- prefetchFailedAt.set(query, Date.now());
372
- return null; /* prefetch is best-effort */
373
- }).finally(() => {
374
- inflightPrefetches.delete(query);
375
- });
376
- inflightPrefetches.set(query, pending);
377
- return pending;
378
- }
379
-
380
- // #617 根因 A 的补位票据:宿主(agent-loop 0.2.x)在每个 step 的 pre-step 里
381
- // 先 inbox.claim()(同步 emit agent/inbox/claimed),再 assemble(),而
382
- // user/message 要到 step() 末尾(:865)才 append——注入的 text 回调在
383
- // assemble / refreshContext 里求值,**永远比当轮用户输入早一拍**:Step 1 拿到
384
- // "",第 N 轮的 Step 1 只能拿到第 N-1 轮的旧文本(实测 46 个渲染点错 3 次)。
385
- // 票据在 claim 那一刻记下原文;渲染时若事件流里最后一条用户消息还不是它,
386
- // 说明本轮 user/message 尚未落盘,用票据;一旦落盘,事件流才是权威(它对
387
- // rewind / compact 的可见面判定更准,票据不看 surface)。
388
- //
389
- // 为什么只在 claimed 上记、不从 agent/inbox/spliced 推:claim 自己的两次
390
- // mutate 都落 outcome:"canceled" 的 spliced(inserted 为空),拿 removedCount
391
- // 当撤回信号会把每次正常认领误判成取消;claimed 只在真有消息被认领时触发,
392
- // 是唯一无歧义的信号源。Cancel/Rewind 穿透因此也不存在——它们不产生 claimed。
393
- const PENDING_QUERY_MAX = 32;
394
- // 票据超过这个岁数就不再采信:一个 step 的 assemble 不可能跑这么久,更久说明
395
- // 那条消息压根没落盘(认领后整轮被取消),票据已是过期证据。
396
- const PENDING_QUERY_TTL_MS = 60000;
397
- const pendingQueries = new Map(); // sessionId -> { text, at }
398
- const offClaimed = typeof ctx?.on === "function"
399
- ? ctx.on("agent/inbox/claimed", (payload) => {
400
- try {
401
- const message = payload?.message;
402
- const text = inboxMessageQuery(message);
403
- if (!text) return;
404
- const session = payload?.agent?.session;
405
- const sessionId = session?.id;
406
- if (typeof sessionId !== "string" || !sessionId) return;
407
- // #539 无痕闸门必须挡在这里,不能只挡渲染侧:claim 在 pre-step 里同步触发,
408
- // 早于 assemble;这条路径既写票据(票据会变成注入查询文本)又预取向量
409
- // (embedQuery 直接 POST 外部 /embeddings),闸门命中时两者都是该会话数据的
410
- // 外流。嵌入层自身没有任何会话维度判断,这里是唯一的拦截点。
411
- if (sessionGate?.isOff(session)) return;
412
- pendingQueries.delete(sessionId); // 重新插入 = 移到队尾
413
- pendingQueries.set(sessionId, { text, at: Date.now() });
414
- if (pendingQueries.size > PENDING_QUERY_MAX) {
415
- pendingQueries.delete(pendingQueries.keys().next().value);
416
- }
417
- // 认领即预取:embed 在 assemble→step 之间就已经在跑,Step 1 的第二次
418
- // 求值(refreshContext)有机会拿到向量。拿不到也无妨——查询文本已经在
419
- // 手上,BM25 词法路(#198)能顶上。
420
- prefetchQueryVector(text);
421
- } catch { /* the ticket is best-effort; injection must never break */ }
422
- })
423
- : null;
424
-
425
- // 当轮查询:票据优先于事件流(见上)。判据是**文本比对**而不是事件条数——
426
- // 从 claim 到 assemble 之间还夹着 await tools.resolve(...),这期间任何插件
427
- // 追加一个事件都会让条数增长,按条数判会把「消息还没落盘」误判成「已落盘」,
428
- // 票据提前退休、Step 1 又退回空串(正是本 issue 要修的那一拍)。文本相等才是
429
- // 「这条消息真的进事件流了」的直接证据;连续两轮同一句话时两者相等,取哪个都对。
430
- function liveStepQuery(ctx) {
431
- const info = lastUserMessageInfo(ctx);
432
- let sessionId = null;
433
- try {
434
- const id = ctx?.agent?.session?.id;
435
- if (typeof id === "string" && id) sessionId = id;
436
- } catch { /* session internals unavailable */ }
437
- if (!sessionId) return info.text;
438
- const ticket = pendingQueries.get(sessionId);
439
- if (!ticket) return info.text;
440
- if (info.text === ticket.text) {
441
- pendingQueries.delete(sessionId); // 已落盘,票据退休(顺带保证 Map 不被历史会话撑大)
442
- return info.text;
443
- }
444
- if (Date.now() - ticket.at > PENDING_QUERY_TTL_MS) {
445
- pendingQueries.delete(sessionId); // 过期证据,不采信
446
- return info.text;
447
- }
448
- return ticket.text;
449
- }
450
-
451
- // 会话身份解析(v1.2 人格寻址用):读 session.header.agentPreset——冻结的
452
- // SessionHeader(issue #17 身份契约)。⚠️ 不能先读 requestHeader():那返回
453
- // EpochHeader(请求级头,首请求后为真),会把 session.header 遮蔽掉,身份取空
454
- // (scope.js 同坑,本地实测踩过)。任何失败静默 → null(落 default 卡)。
455
- function sessionAgentId(ctx) {
456
- try {
457
- const session = ctx?.agent?.session;
458
- const header = session?.header ?? null;
459
- const preset = header?.agentPreset;
460
- return typeof preset === "string" && preset.trim() ? preset.trim() : null;
461
- } catch {
462
- return null;
463
- }
464
- }
465
-
466
- // 会话 id 解析(#606 绑会话卡用):session.id 在宿主里稳定可用(scope.js:97-103
467
- // 就是靠它反查 workspace 的)。与 agentPreset 一样各自护住——两者来自同一个
468
- // session 对象,但 accessor 抛错时不该互相拖累(一个取不到不影响另一个)。
469
- // 为什么需要第二个键:DS Bot 里 agentPreset 恒为 "standard",按 bot 建卡分不开,
470
- // 只有会话 id 能分开(实测见 issue #606)。
471
- function sessionIdOf(ctx) {
472
- try {
473
- const id = ctx?.agent?.session?.id;
474
- return typeof id === "string" && id.trim() ? id.trim() : null;
475
- } catch {
476
- return null;
477
- }
478
- }
479
-
480
- // 父会话 id 解析(子 agent 继承人格卡用):子代理会话的 header 里有 `parentSession`
481
- // (实测 518 个子代理头恒带此字段,主会话没有)。⚠️ 与 `session-gate.js` 的口径不同:
482
- // 那里刻意不用它判「是不是子代理」(宿主 fork 出的主会话分支同样带 parentSession),
483
- // 这里只把它当「自己没建卡时该继承谁」的线索,fork 出的分支继承父卡同样是正确语义。
484
- function parentSessionIdOf(ctx) {
485
- try {
486
- const session = ctx?.agent?.session;
487
- const parent = session?.header?.parentSession;
488
- return typeof parent === "string" && parent.trim() ? parent.trim() : null;
489
- } catch {
490
- return null;
491
- }
492
- }
493
-
494
- // 一次取全三个寻址键。分开取值、各自兜错:一个失败不该让另一个也丢。
495
- function sessionIdentity(ctx) {
496
- return { agentId: sessionAgentId(ctx), sessionId: sessionIdOf(ctx), parentSessionId: parentSessionIdOf(ctx) };
497
- }
498
-
499
- // User profile + rules: injected ahead of the memory block because they are
500
- // always-relevant instructions the agent should follow every turn.
501
- // 渲染整体搬到 src/user-settings.js(与面板预览共用一份,见那里的模块头注释)。
502
- // 口径不变:双闸门(config.personaEnabled && 卡.enabled)都开时人格行在最前,
503
- // 画像与规则后出、后写覆盖占上风,rules 恒最硬;任一闸关着时输出与历史版本逐字节
504
- // 一致(老用户零变化)。personaStrictAddressing 打开时,「有身份但没建卡」与
505
- // 「卡被显式关掉」都不注入人格——default 只兜「这一帧解析不到身份」的会话。
506
- function renderUserSettings(ctx) {
507
- // factsInject 是 profile-facts 域的读口(index.js 接线,面板预览路由传同一份):
508
- // 开关与事实有无的判定都在 renderUserSettingsBlock 内部,「关」等于零读数。
509
- const { agentId, sessionId, parentSessionId } = sessionIdentity(ctx);
510
- return renderUserSettingsBlock({ settings, config, agentId, sessionId, parentSessionId, factsProvider: factsInject })
511
- .text;
512
- }
513
-
514
- // #249 能力说明的系统提示段。order 150 = 插件指引段的既有惯例
515
- // (ACP 的 ACP_SYSTEM_PROMPT 与 mnemon 的 routing 段都在 150)。文本是常量、
516
- // 同会话内不随轮次变化,故不影响其后的前缀缓存,也不逐轮复读。宿主若不提供
517
- // section seam 就静默跳过——#249 §3 的口径是「只用现成 seam,拿不到位的语义
518
- // 降级处理」:能力说明仍落在工具描述上,不算失败。
519
- // 走父/子闸门(#249 第二批):注入器本身只在 `autoInject` 开时挂载,这里是
520
- // 第二道、也是同一个判据的显式落点——两处消费点共用 injectChildEnabled,
521
- // 不在各自的地方重写「父关则子不生效」。
522
- const guideSection = injectChildEnabled(config, "injectGuidanceEnabled") && typeof ctx.systemPrompt?.section === "function"
523
- ? ctx.systemPrompt.section({
524
- name: "memory-guide",
525
- order: 150,
526
- text: (promptCtx) => (sessionGate?.isOff(sessionOf(promptCtx)) ? "" : MEMORY_GUIDE_SECTION)
527
- })
528
- : null;
529
-
530
- const disposers = [
531
- ...(guideSection ? [guideSection] : []),
532
- ctx.systemPrompt.context({
533
- name: "memory",
534
- order: 90,
535
- text: (ctx) => {
536
- if (sessionGate?.isOff(sessionOf(ctx))) return "";
537
- // Bug4: pass the latest user query so injection prefers semantically
538
- // relevant memories; liveStepQuery is best-effort (empty → legacy).
539
- // The query vector is prefetched asynchronously (cached) because the
540
- // render itself must stay synchronous.
541
- // #617:liveStepQuery 而不是 lastUserQuery——宿主在 step 末尾才 append
542
- // user/message,而注入在这之前求值,只看事件流会拿到上一轮的输入。
543
- const query = liveStepQuery(ctx);
544
- if (query) prefetchQueryVector(query);
545
- const queryVector = queryVectorCache.get(query);
546
- // v0.8.0 A3:scope 随请求解析(解析器恒返回对象,身份取不到时两维为
547
- // null);硬过滤与软加权的门控都在 injectCandidates 内——strict 看
548
- // strictScope,软加权看 scopeEnabled 且至少一维可解析(issue #339)。
549
- const scope = resolveSessionScope(ctx);
550
- // Issue #205:跨轮轮换——最近 N 个查询轮次注入过的 id 本轮不再优先。
551
- const sessionId = ctx?.agent?.session?.id ?? "_";
552
- const rotate = recentInjectedIds(sessionId, query);
553
- // rotateWindow 随集合一起传入:候选池按 maxItems×(N+1) 扩容——窗口要的
554
- // 牌比既有 maxItems×2 池多时,轮换才有新鲜牌可换(#205 补测)。
555
- // Issue #239(第 5 项):注入条数的查询自适应(默认关)。确定性强的话题收缩
556
- // 条数、模糊话题维持上限——单向收缩,绝不越过 maxInjectedItems;判据只看查询
557
- // 本身,不做额外检索(先探针检索等于白付一次 fuseRecall)。
558
- const maxItems = config.injectUncertaintyAdaptive === true
559
- ? adaptiveInjectBudget(query, baseMaxItems)
560
- : baseMaxItems;
561
- // #249 第一批:pin 池统计走可选出参,不动 injectCandidates 的数组契约。
562
- const pinnedStats = {};
563
- // Issue #380:注入前判定(preInjectGate)由 injectCandidates **内部**消费——
564
- // 判定与滤除必须发生在它的 touchRecalled / recall 记账之前(#380 评审:与
565
- // strictScope 同纪律,见 service.js 的「闸门还必须在 touchRecalled 之前」)。
566
- // pin 池(#249 逐字保真)与 graphHint 线索行豁免由 service 侧按同口径切出。
567
- // 渲染同步约束 → 闸门是 async prefetch + cache、同步消费:缓存命中当帧生效
568
- // (enforce 滤除 / observe 记账),冷缓存首帧降级为原样注入、下一轮同 key
569
- // 渲染生效——防线故障永不阻塞注入。帧状态经 gateStats 出参带回(同 pinnedStats
570
- // 的出参口径),这里只读它做面板快照。
571
- const gateStats = {};
572
- const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold, scope, rotate, rotateWindow: rotationTurns, pinnedStats, gate, gateStats });
573
- const pinnedShown = Math.max(0, pinnedStats.shown ?? 0);
574
- const gateFrame = gateStats.frame ?? null;
575
- // #249:pin 条目不进轮换历史——它们每轮固定前置,记进去只会占满轮换
576
- // 窗口、挤掉情景候选的新鲜度(验收:pin 不参与跨轮轮换)。
577
- recordInjection(sessionId, query, pinnedShown > 0 ? candidates.slice(pinnedShown) : candidates);
578
- // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
579
- // sees the short-term rounds first, then the cross-session recall —
580
- // the documented injection order 1→2. Folding it here (instead of a
581
- // separate context) keeps the prompt assembly stable at two blocks.
582
- const hotText = renderHotContext(ctx);
583
- const body = render(candidates, pinnedStats);
584
- // #333(issue #34 恢复):时间前缀只在会话首轮出现(per-session 闩锁),
585
- // 排在整个记忆块的最前——模型先知道「今天几号」,再看热上下文与长期记忆。
586
- const timePrefix = renderTimePrefix(ctx);
587
- // M3 仓库地志(chorography):只注标题级提纲,档位 off/light/full。
588
- // cwd 用 scope.workspace_scope——那是全仓唯一的 cwd 口径(registry 反查,
589
- // header.cwd 兜底),另读一份就是两张皮且重犯 #487 的 Proxy 陷阱(P27)。
590
- // 取不到 cwd / 仓库没登记 / 渲染失败一律空串:本块在热路径上,不能抛。
591
- const choroText = choroInject && typeof choroInject.text === "function"
592
- ? choroInject.text(scope?.workspace_scope ?? null)
593
- : "";
594
- // 拼接次序:时间 → 地志 → 热上下文 → 长期记忆(四者都可能为空,逐级判空)。
595
- // 地志排在热上下文之前:它是「这个仓库由哪些模块组成」的稳定背景,
596
- // 而热上下文是「刚才聊到哪」,越靠近正文越晚——稳定的在前,易变的在后。
597
- const withHot = !hotText ? body : body ? `${hotText}\n\n${body}` : hotText;
598
- const withChoro = !choroText ? withHot : withHot ? `${choroText}\n\n${withHot}` : choroText;
599
- const finalBody = !timePrefix ? withChoro : withChoro ? `${timePrefix}\n\n${withChoro}` : timePrefix;
600
- // Issue #179:旁路缓存一帧——面板「注入预览」卡据此展示构成与体积。
601
- // chars 为条目内容的截断后近似值(与 render 同一函数计长),totalChars
602
- // 是本次实际返回块的精确长度。maxItems 反映自适应收缩后的生效值。
603
- injectionSnapshot = {
604
- at: Date.now(),
605
- sessionId,
606
- query: query || "",
607
- maxItems,
608
- threshold,
609
- adaptive: config.injectUncertaintyAdaptive === true,
610
- scoped: scope && (scope.agent_scope || scope.workspace_scope) ? scope : null,
611
- rotated: rotate ? rotate.size : 0,
612
- // Issue #380:闸门状态进快照(off/pending/observed/filtered),面板
613
- // 「注入预览」卡据此展示判定是否生效与标记数。
614
- gate: gateFrame ? { state: gateFrame.state, nFlagged: gateFrame.flaggedIds ? gateFrame.flaggedIds.size : null, judged: gateFrame.judged ?? null } : null,
615
- hotChars: hotText.length,
616
- // M3:地志块实际占的字符数(0 = 本帧没注入),面板据此区分「关」与「没匹配到仓库」。
617
- choroChars: choroText.length,
618
- entries: candidates.map((m) => ({
619
- id: m.id,
620
- type: m.type,
621
- title: m.title,
622
- importance: m.importance,
623
- chars: injectMemory(m).length
624
- })),
625
- totalChars: finalBody.length
626
- };
627
- return finalBody;
628
- }
629
- }),
630
- ctx.systemPrompt.context({
631
- name: "user-settings",
632
- order: 85,
633
- text: (ctx) => (sessionGate?.isOff(sessionOf(ctx)) ? "" : renderUserSettings(ctx))
634
- })
635
- ];
636
-
637
- return () => {
638
- // #617:认领票据是监听宿主事件的活句柄,卸载时必须成对摘掉,否则注入器重装
639
- // (面板开关、宿主热重载)会留下一个继续写 Map 的孤儿监听。
640
- offClaimed?.();
641
- pendingQueries.clear();
642
- inflightPrefetches.clear();
643
- prefetchFailedAt.clear();
644
- queryVectorCache.clear();
645
- rotationHistory.clear();
646
- injectionSnapshot = null; // 注入器卸载即失效:快照不得跨生命周期存留
647
- for (const dispose of disposers) {
648
- if (typeof dispose === "function") dispose();
649
- }
650
- };
651
- }
1
+ import { createScopeResolver, sessionOf } from "./scope.js";
2
+ import { createHotMemory, roundsFromEvents } from "./hot-memory.js";
3
+ import { STR, langOf } from "./lang.js";
4
+ import { escapePromptVars as escapePromptVarsWithConfig, renderUserSettingsBlock } from "./user-settings.js";
5
+ import { MEMORY_GUIDE_SECTION } from "./guide.js";
6
+ import { adaptiveInjectBudget } from "./search/adaptive.js";
7
+ import { injectChildEnabled } from "./config.js";
8
+ import { safeSlice } from "./safe-slice.js";
9
+ import { memoryDate } from "./date-hint.js";
10
+
11
+ // Issue #179:注入预览的数据底座。systemPrompt 渲染是同步回调,面板只能事后
12
+ // 拉取,所以在这里旁路缓存「最近一帧组装」——快照就是本次渲染用过的同一份
13
+ // candidates/hotText/body,不重新检索、不二次组装,零额外开销。模块级单例:
14
+ // 注入器全局唯一(index.js 仅在 autoInject 开启时注册一个),面板经 api.js 的
15
+ // 只读 getter 读取;autoInject 关闭时注入器不存在,快照保持 null——「预览
16
+ // 不可用」本身就是「注入关闭」的诚实呈现。
17
+ let injectionSnapshot = null;
18
+ export function getInjectionSnapshot() {
19
+ return injectionSnapshot;
20
+ }
21
+
22
+ // 「模型可见事件 seq」集合:宿主在 session.surface.nodes 维护可见面——rewind 的
23
+ // surfaceOp replace 与 compact 的隐藏替换都作用在这层(dsh-rewind 插件即据此计算
24
+ // 替换区间)。拿不到(老版本宿主)返回 null,调用方退回「全量事件」的旧行为。
25
+ // 读取必须在 try 内:`surface.nodes` 是宿主 getter,其 _assertProjections 在消息投影
26
+ // 所属插件被移除时会 throw(dsh-session lib/types/surface.js)。抛出等同于「没有
27
+ // 可见面」,绝不能让整块热记忆消失——那是比旧偏差更糟的退化。
28
+ function visibleSeqsOf(session) {
29
+ try {
30
+ const nodes = session?.surface?.nodes;
31
+ return Array.isArray(nodes) ? new Set(nodes) : null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ // Best-effort extraction of the current user's latest message text from the
38
+ // live session, for semantic-first injection (Bug4). The system-prompt
39
+ // interpolator renders synchronously, so this walks the already-materialized
40
+ // session event log (same event shape summarize.js consumes) and returns the
41
+ // most recent human message. Any failure degrades to "" — the injector then
42
+ // falls back to the legacy rule-based pick, never breaking the render.
43
+ //
44
+ // v0.9.0:导出给 tools.js 的 memory_update 用。失败记录表的 query 与注入
45
+ // 候选问的是同一件事——「当时到底想干什么」;这条取原话的路只该有一份实现。
46
+ // 复制一份的代价本仓库付过几次(src/lib 平价、snapshotEvents 兼容层),所以
47
+ // 这里只加 export,不改行为。
48
+ //
49
+ // #617:多带一个 seq——注入器要拿它判断「待认领票据是否比事件流更新」(见
50
+ // createInjector 的 pendingQueries)。seq 是宿主事件序号,取不到时为 null
51
+ // (老版本宿主 / 测试夹具),调用方按 null 参与相等比较,不做真假推断。
52
+ export function lastUserMessageInfo(ctx) {
53
+ try {
54
+ const session = ctx?.agent?.session;
55
+ // DSH ≥0.1.2-rc only exposes events via snapshotEvents(); older builds
56
+ // still have the .events property, so fall back to it.
57
+ const events = session?.snapshotEvents?.() ?? session?.events;
58
+ if (!Array.isArray(events) || events.length === 0) return { text: "", seq: null };
59
+ const visibleSeqs = visibleSeqsOf(session);
60
+ for (let i = events.length - 1; i >= 0; i--) {
61
+ const event = events[i];
62
+ // 被撤回/被压缩遮蔽的事件不算「最近一条用户消息」(与 extractRounds 同口径)。
63
+ if (visibleSeqs && !visibleSeqs.has(event?.seq)) continue;
64
+ if (event?.type !== "user/message") continue;
65
+ const kind = event.data?.source?.kind;
66
+ if (kind !== undefined && kind !== "user") continue;
67
+ const parts = event.data?.content;
68
+ if (!Array.isArray(parts) || parts.length === 0) continue;
69
+ return {
70
+ text: safeSlice(
71
+ parts
72
+ .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
73
+ .filter(Boolean)
74
+ .join("\n"),
75
+ 500
76
+ ),
77
+ seq: event?.seq ?? null
78
+ };
79
+ }
80
+ } catch { /* session internals unavailable: degrade to no query */ }
81
+ return { text: "", seq: null };
82
+ }
83
+
84
+ export function lastUserQuery(ctx) {
85
+ return lastUserMessageInfo(ctx).text;
86
+ }
87
+
88
+ // 认领消息 → 查询文本。#617 的补位票据就是这里算出来的字符串:判定口径与
89
+ // user/message 事件同源(content parts + source.kind),于是「插件注入的上下文」
90
+ // 这类非人类消息照样被跳过,票据不会拿插件自己的话当用户问题。
91
+ function inboxMessageQuery(message) {
92
+ try {
93
+ const parts = message?.content ?? message?.data?.content;
94
+ if (!Array.isArray(parts) || parts.length === 0) return "";
95
+ const kind = message?.source?.kind ?? message?.data?.source?.kind;
96
+ if (kind !== undefined && kind !== "user") return "";
97
+ return safeSlice(
98
+ parts
99
+ .map((p) => (typeof p === "string" ? p : p?.text ?? ""))
100
+ .filter(Boolean)
101
+ .join("\n"),
102
+ 500
103
+ );
104
+ } catch {
105
+ return "";
106
+ }
107
+ }
108
+
109
+ // Hot-memory round extraction (v0.5.0 1.3): pairs each user/message with the
110
+ // next assistant reply. The pairing lives in hot-memory.js (roundsFromEvents)
111
+ // so it can be unit-tested directly; this adapter only resolves the session's
112
+ // raw event log and the model-visible seq set (session.surface.nodes — see
113
+ // visibleSeqsOf). Rewind-shadowed / compacted events are thereby excluded:
114
+ // hot memory and the model see the same conversation. Best-effort: returns []
115
+ // on any failure, and the hot block simply does not render.
116
+ //
117
+ // omitPendingRound: true(Issue #637):prompt 组装发生的时刻,尾部 pending 轮
118
+ // 就是「正在组装的这一轮」——它的提问已经作为真实 user message 在本条 prompt
119
+ // 里,热记忆里再渲染一份空 `A:` 行是纯重复,且回答落地后该行会从空 `A:` 抖成
120
+ // 正文:宿主「文本变了就追加快照」的契机会让同一轮的注入块被追加多份 runtime-
121
+ // context,旧份永久留在会话历史(#637 报告:4 轮 → 10 份、75% 重复)。省略之后
122
+ // 一轮内热块文本恒定、回答落地时恰好变一次——快照数降到每轮一份。直调方
123
+ // (tests / 其他消费者)不传这个参数,保持完整配对。
124
+ function extractRounds(ctx, maxRounds) {
125
+ try {
126
+ const session = ctx?.agent?.session;
127
+ // DSH ≥0.1.2-rc only exposes events via snapshotEvents(); older builds
128
+ // still have the .events property, so fall back to it.
129
+ const events = session?.snapshotEvents?.() ?? session?.events;
130
+ if (!Array.isArray(events) || events.length === 0) return [];
131
+ return roundsFromEvents(events, maxRounds, visibleSeqsOf(session), { omitPendingRound: true });
132
+ } catch {
133
+ return [];
134
+ }
135
+ }
136
+
137
+ export function createInjector(ctx, service, settings, config, gate = null, sessionGate = null, choroInject = null, factsInject = null) {
138
+ const language = langOf(config);
139
+ const baseMaxItems = config.maxInjectedItems ?? 5;
140
+ const threshold = config.importanceThreshold ?? 3;
141
+ // Issue #205:注入位跨轮轮换。rotationTurns = 最近 N 个「不同用户查询」轮次
142
+ // 注入过的记忆本轮不再优先(0 = 关闭,保持既有行为)。历史按会话维护——
143
+ // 新会话从零开始;同一查询的多次渲染(工具调用轮)视为同一轮,不推进窗口。
144
+ const rotationTurns = Math.max(0, Math.floor(config.injectRotationTurns ?? 0));
145
+ const rotationHistory = new Map(); // sessionId -> [{ query, ids: Set }]
146
+ const ROTATION_HISTORY_MAX = 32; // 覆盖 max(20) 配置档仍有余量
147
+
148
+ function recentInjectedIds(sessionId, query) {
149
+ if (rotationTurns <= 0) return null;
150
+ const deque = rotationHistory.get(sessionId);
151
+ if (!deque || deque.length === 0) return null;
152
+ // 只看「之前的轮次」:排除与当前查询相同的条目——同一查询的重复渲染
153
+ // (工具调用轮)不该拿本轮自己的集合来转自己。
154
+ const prior = query ? deque.filter((e) => e.query !== query) : deque;
155
+ if (prior.length === 0) return null;
156
+ const recent = new Set();
157
+ for (const entry of prior.slice(-rotationTurns)) {
158
+ for (const id of entry.ids) recent.add(id);
159
+ }
160
+ return recent.size > 0 ? recent : null;
161
+ }
162
+
163
+ function recordInjection(sessionId, query, candidates) {
164
+ if (rotationTurns <= 0 || !query) return;
165
+ const deque = rotationHistory.get(sessionId) ?? [];
166
+ const ids = new Set(candidates.map((c) => c.id));
167
+ const last = deque[deque.length - 1];
168
+ if (last && last.query === query) {
169
+ last.ids = ids; // 同一查询的重复渲染:覆盖本轮内容,不推进窗口
170
+ } else {
171
+ deque.push({ query, ids });
172
+ if (deque.length > ROTATION_HISTORY_MAX) deque.shift();
173
+ rotationHistory.set(sessionId, deque);
174
+ }
175
+ }
176
+ // v0.8.0 A3(issue #17):注入路径的会话 scope 解析——strictScope 硬过滤
177
+ // 需要。渲染 ctx 与工具 exec 同形(agent.session),解析器直接复用。
178
+ // logger 透传:registry 反查失败时 warnOnce 才有出口。
179
+ const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
180
+
181
+ // Bug6: bound the injected memory block. Each entry's content is truncated to
182
+ // injectContentMaxChars chars (issue #164①: configurable, was a hardcoded
183
+ // 300); a truncated entry carries a tail hint (limit / original length /
184
+ // memory_get id) so the cut is never silent — BUDGET_EXCEEDED principle, the
185
+ // agent can always fetch the full text. The whole block gets a block budget
186
+ // (scales up with the per-entry cap so raising the cap is not defeated by a
187
+ // stale 1500) and an entry that would exceed it collapses to its title only.
188
+ const maxContent = config.injectContentMaxChars ?? 300;
189
+ const MAX_BLOCK = Math.max(1500, maxContent + 600);
190
+ // #249 第一批:pin 条目的正文硬顶。逐字保真不等于无界——单条上限取
191
+ // injectContentMaxChars 与 2000 的较大者,默认档下约束/偏好不会因常规截断
192
+ // 失真,同时给「一条超长约束每轮吃满常驻段」留一道闸(超顶仍带截断提示)。
193
+ const PINNED_CONTENT_MAX = Math.max(maxContent, 2000);
194
+
195
+ // Compressed injection (v0.5.0 2.1): a sleep-demoted row carries its summary in
196
+ // `content` with the original parked in `_full_content` — inject the summary
197
+ // verbatim instead of re-truncating the (already short) text. 但「降级过」不等于
198
+ // 「天然够短」:原先那条 `_full_content` 早返回的唯一效果就是**跳过 maxLength**
199
+ // (两条分支取的都是 m.content),于是 pin 的硬顶在这一路上形同不存在(#266 评审)。
200
+ // 现在只有一条截断路径:超限照旧带提示,原文永远可通过 memory_get 取回。
201
+ function injectMemory(m, maxLength = maxContent) {
202
+ const text = String(m?.content ?? "");
203
+ if (text.length <= maxLength) return text;
204
+ return `${safeSlice(text, maxLength)}…${STR.truncatedHint[language](maxLength, text.length, m.id)}`;
205
+ }
206
+
207
+ // Prompt-variable brace escaping (issue #162, restored from v0.7.4 #40):
208
+ // DSH's interpolate() scans every injected section for `{{...}}` and throws
209
+ // unless the variable name matches /^[a-z][a-z0-9_]*$/ — memory/profile
210
+ // content carrying legal template syntax (docker `--format "{{.Server.Version}}"`,
211
+ // Obsidian-style `{{hl|}}`, `{{挖空}}`, `{{关键词}}`) would hit an illegal
212
+ // variable name and throw, crashing the whole turn. At the injection boundary
213
+ // we escape every run of 2+ consecutive braces, inserting a `\` between each
214
+ // pair, so no `{{`/`}}` substring survives into the prompt: `{{a}}` → `{\{a\}\}`,
215
+ // and odd runs like `{{{a}}}` (which pair-wise escaping would leave with a
216
+ // literal `{{`) are handled too. The text keeps its readable template form,
217
+ // the transform is idempotent (escaped braces are single + `\`, never two
218
+ // adjacent), and single braces pass through untouched — interpolate only
219
+ // scans `{{`. Off via config.escapePromptVariables=false (default true).
220
+ function escapePromptVars(text) {
221
+ // 实现搬到 src/user-settings.js:预览路由要用同一份转义,否则「注入生效文本」的
222
+ // 预览又是第二份实现、又会漂。这里保留同名闭包,其余调用点一字不动。
223
+ return escapePromptVarsWithConfig(config, text);
224
+ }
225
+
226
+ // Time-prefix injection (issue #34,恢复于 #333): opt-in, off by default.
227
+ // When enabled the current date/time is injected once per conversation — at
228
+ // the first prompt assembly of a new session — so the model can sense what
229
+ // time/day it is. A per-session latch means later assemblies in the same
230
+ // session never re-inject; a bare render ctx (no session id) falls back to
231
+ // once per injector lifetime.
232
+ // v0.7.11 面板大改版(ce4658e)时这段随一次批量删除被静默移除,CHANGELOG 无
233
+ // 登记(#162 的 escapePromptVars 同刀误删、后来恢复,本函数漏了)——用户按
234
+ // CHANGELOG 开着开关,实际什么都不会发生。本次按 v0.7.2 语义原样恢复:键名、
235
+ // 默认值(false)、格式 `[当前时间: YYYY-MM-DD 周X HH:MM]` 全部不变,存量
236
+ // feature_flags 里的配置恢复即生效。
237
+ // 已注入过时间前缀的会话集合(#335 review:单值闩锁在 A→B→A 交替渲染下会
238
+ // 重复注入)。上限 500 防长驻进程无界增长,超限逐出最早记录。
239
+ const timePrefixDone = new Set();
240
+ let timePrefixBare = false;
241
+
242
+ function renderTimePrefix(ctx) {
243
+ if (config.injectTimePrefix !== true) return "";
244
+ const sessionId = ctx?.agent?.session?.id;
245
+ if (sessionId === undefined) {
246
+ if (timePrefixBare) return "";
247
+ timePrefixBare = true;
248
+ } else {
249
+ if (timePrefixDone.has(sessionId)) return "";
250
+ if (timePrefixDone.size >= 500) timePrefixDone.delete(timePrefixDone.keys().next().value);
251
+ timePrefixDone.add(sessionId);
252
+ }
253
+ const WEEKDAYS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
254
+ const now = new Date();
255
+ const pad = (n) => String(n).padStart(2, "0");
256
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
257
+ const time = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
258
+ return escapePromptVars(`[当前时间: ${date} ${WEEKDAYS[now.getDay()]} ${time}]`);
259
+ }
260
+
261
+ // Hot memory (v0.5.0 1.3): the latest rounds of THIS session, rebuilt from
262
+ // the materialized event log on every render — stateless, so it survives
263
+ // session switches and never persists anywhere.
264
+ const hot = createHotMemory({
265
+ maxRounds: config.hotMemoryRounds ?? 5,
266
+ maxTokens: config.hotMemoryMaxTokens ?? 2000
267
+ });
268
+
269
+ function renderHotContext(ctx) {
270
+ if (config.hotMemoryEnabled === false) return "";
271
+ const rounds = extractRounds(ctx, config.hotMemoryRounds ?? 5);
272
+ if (!rounds.length) return "";
273
+ hot.clear();
274
+ for (const r of rounds) hot.add(r);
275
+ const body = hot.getContext();
276
+ if (!body) return "";
277
+ return escapePromptVars(STR.hotHeader[language](rounds.length, body));
278
+ }
279
+
280
+ function render(candidates, pinnedStats = null) {
281
+ if (!candidates.length) return "";
282
+ const header = STR.memoryHeader[language];
283
+ const lines = [header];
284
+ let budget = MAX_BLOCK - header.length;
285
+ // #249 第一批:pin 池(约束/偏好)排在块头且不参与块的塌缩预算——「与情景
286
+ // 日志抢同一份预算后被降级」正是本议题要修的结构缺陷。单条仍有硬顶
287
+ // (PINNED_CONTENT_MAX),超出照旧带截断提示,不静默。
288
+ const pinnedCount = Math.max(0, Math.min(candidates.length, pinnedStats?.shown ?? 0));
289
+ // #24 块3:图召回线索行(graphHint)——引导语插在第一个线索行之前(保持块头
290
+ // 语义:先声明「这些不是事实」)。线索行自身按 graphHintLine 渲染(线索/ 前缀
291
+ // 区别于普通记忆行)。
292
+ let graphSeen = 0;
293
+ for (let i = 0; i < candidates.length; i++) {
294
+ const m = candidates[i];
295
+ const pinned = i < pinnedCount;
296
+ if (m.graphHint === true) graphSeen++;
297
+ // Epistemic trust (v0.4.5): when enabled, measured observations are
298
+ // flagged so the agent can weigh them above guesses/opinions.
299
+ const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
300
+ ? STR.verified[language]
301
+ : "";
302
+ const title = STR.entryTitle[language](m.title, m.importance);
303
+ // 条目日期(模型可见时间线索):occurred_at 优先、缺省回落 created_at。不给
304
+ // 日期模型只能拿 updated_at 当年龄,而巩固合并会刷新 updated_at —— 见
305
+ // src/date-hint.js 顶部。
306
+ const date = memoryDate(m);
307
+ // Issue #641(T4 注入标注):conflictNote 由 injectCandidates 在 enforce
308
+ // 档下挂上(矛盾对同批时的机械排位说明)。#537 的教训:标注必须进注入
309
+ // 文本本体,不能只留在账本里——消费方看不见的标注等于没标。
310
+ const content = injectMemory(m, pinned ? PINNED_CONTENT_MAX : maxContent)
311
+ + (m.conflictNote ? "\n" + m.conflictNote : "");
312
+ const full = m.graphHint === true
313
+ ? STR.graphHintLine[language](m.type, title, content, date)
314
+ : STR.entryLine[language](m.type, verified, title, content, date);
315
+ // 线索行引导语插在第一个线索行之前(保持块头语义:先声明「这些不是事实」)。
316
+ if (m.graphHint === true && graphSeen === 1) {
317
+ lines.push(STR.graphHintHeader[language]);
318
+ }
319
+ if (pinned) {
320
+ // pin 不扣块预算(上面那条设计注释的落地):pin 一条就够击穿 MAX_BLOCK
321
+ // (PINNED_CONTENT_MAX 2000 > MAX_BLOCK 1500),照扣会把 budget 压成负数,
322
+ // 同一轮随后的普通候选全部退化成标题行——正是本议题要修的结构缺陷。
323
+ lines.push(full);
324
+ } else if (budget - full.length >= 0) {
325
+ lines.push(full);
326
+ budget -= full.length;
327
+ } else {
328
+ lines.push(`- [${m.type}] ${date ? `${date} ` : ""}${verified}${title}`);
329
+ }
330
+ if (pinned && i === pinnedCount - 1) {
331
+ const hidden = Math.max(0, pinnedStats?.suppressed ?? 0);
332
+ if (hidden > 0) lines.push(STR.pinnedOverflow[language](hidden));
333
+ }
334
+ }
335
+ return escapePromptVars(lines.join("\n"));
336
+ }
337
+
338
+ // Bug4: the system-prompt render is synchronous, so the semantic query vector
339
+ // must be prefetched asynchronously and cached for the next assembly. The
340
+ // first render after a new user message may still fall back to the rule-based
341
+ // pick; later assemblies in the same session reuse the cached vector. Bounded
342
+ // cache (cap 8, drop oldest) so a long session never grows it unbounded.
343
+ //
344
+ // #617 根因 B:旧实现用一个 lastPrefetched 字符串做去重,且它在 await 之前
345
+ // 就置位——同一条查询第一次失败(模型没下好、超时)之后**永不重试**,而那
346
+ // 恰好是最需要重试的一次。这里换成三件套:inflight Map 去重(渲染同一步会
347
+ // 被求值两次:assemble 一次、refreshContext 一次,同一条查询只该嵌一次)、
348
+ // 失败冷却 15s(失败可重试,但不许每次渲染都拿一次失败去撞模型)、返回
349
+ // Promise(调用方/测试能等到它,而不是靠魔法延时)。
350
+ const QUERY_VECTOR_CACHE_MAX = 8;
351
+ const PREFETCH_FAIL_COOLDOWN_MS = 15000;
352
+ const queryVectorCache = new Map();
353
+ const inflightPrefetches = new Map(); // query -> Promise<vector|null>
354
+ const prefetchFailedAt = new Map(); // query -> ms
355
+
356
+ function prefetchQueryVector(query) {
357
+ if (!query) return null;
358
+ const cached = queryVectorCache.get(query);
359
+ if (cached) return Promise.resolve(cached);
360
+ const inflight = inflightPrefetches.get(query);
361
+ if (inflight) return inflight;
362
+ const failedAt = prefetchFailedAt.get(query);
363
+ if (failedAt !== undefined && Date.now() - failedAt < PREFETCH_FAIL_COOLDOWN_MS) return null;
364
+ const pending = service.embedQuery(query).then((vec) => {
365
+ if (Array.isArray(vec) && vec.length) {
366
+ queryVectorCache.set(query, vec);
367
+ if (queryVectorCache.size > QUERY_VECTOR_CACHE_MAX) {
368
+ queryVectorCache.delete(queryVectorCache.keys().next().value);
369
+ }
370
+ prefetchFailedAt.delete(query);
371
+ return vec;
372
+ }
373
+ prefetchFailedAt.set(query, Date.now());
374
+ return null;
375
+ }).catch(() => {
376
+ prefetchFailedAt.set(query, Date.now());
377
+ return null; /* prefetch is best-effort */
378
+ }).finally(() => {
379
+ inflightPrefetches.delete(query);
380
+ });
381
+ inflightPrefetches.set(query, pending);
382
+ return pending;
383
+ }
384
+
385
+ // #617 根因 A 的补位票据:宿主(agent-loop 0.2.x)在每个 step 的 pre-step 里
386
+ // 先 inbox.claim()(同步 emit agent/inbox/claimed),再 assemble(),而
387
+ // user/message 要到 step() 末尾(:865)才 append——注入的 text 回调在
388
+ // assemble / refreshContext 里求值,**永远比当轮用户输入早一拍**:Step 1 拿到
389
+ // "",第 N 轮的 Step 1 只能拿到第 N-1 轮的旧文本(实测 46 个渲染点错 3 次)。
390
+ // 票据在 claim 那一刻记下原文;渲染时若事件流里最后一条用户消息还不是它,
391
+ // 说明本轮 user/message 尚未落盘,用票据;一旦落盘,事件流才是权威(它对
392
+ // rewind / compact 的可见面判定更准,票据不看 surface)。
393
+ //
394
+ // 为什么只在 claimed 上记、不从 agent/inbox/spliced 推:claim 自己的两次
395
+ // mutate 都落 outcome:"canceled" 的 spliced(inserted 为空),拿 removedCount
396
+ // 当撤回信号会把每次正常认领误判成取消;claimed 只在真有消息被认领时触发,
397
+ // 是唯一无歧义的信号源。Cancel/Rewind 穿透因此也不存在——它们不产生 claimed。
398
+ const PENDING_QUERY_MAX = 32;
399
+ // 票据超过这个岁数就不再采信:一个 step 的 assemble 不可能跑这么久,更久说明
400
+ // 那条消息压根没落盘(认领后整轮被取消),票据已是过期证据。
401
+ const PENDING_QUERY_TTL_MS = 60000;
402
+ const pendingQueries = new Map(); // sessionId -> { text, at }
403
+ const offClaimed = typeof ctx?.on === "function"
404
+ ? ctx.on("agent/inbox/claimed", (payload) => {
405
+ try {
406
+ const message = payload?.message;
407
+ const text = inboxMessageQuery(message);
408
+ if (!text) return;
409
+ const session = payload?.agent?.session;
410
+ const sessionId = session?.id;
411
+ if (typeof sessionId !== "string" || !sessionId) return;
412
+ // #539 无痕闸门必须挡在这里,不能只挡渲染侧:claim 在 pre-step 里同步触发,
413
+ // 早于 assemble;这条路径既写票据(票据会变成注入查询文本)又预取向量
414
+ // (embedQuery 直接 POST 外部 /embeddings),闸门命中时两者都是该会话数据的
415
+ // 外流。嵌入层自身没有任何会话维度判断,这里是唯一的拦截点。
416
+ if (sessionGate?.isOff(session)) return;
417
+ pendingQueries.delete(sessionId); // 重新插入 = 移到队尾
418
+ pendingQueries.set(sessionId, { text, at: Date.now() });
419
+ if (pendingQueries.size > PENDING_QUERY_MAX) {
420
+ pendingQueries.delete(pendingQueries.keys().next().value);
421
+ }
422
+ // 认领即预取:embed 在 assemble→step 之间就已经在跑,Step 1 的第二次
423
+ // 求值(refreshContext)有机会拿到向量。拿不到也无妨——查询文本已经在
424
+ // 手上,BM25 词法路(#198)能顶上。
425
+ prefetchQueryVector(text);
426
+ } catch { /* the ticket is best-effort; injection must never break */ }
427
+ })
428
+ : null;
429
+
430
+ // 当轮查询:票据优先于事件流(见上)。判据是**文本比对**而不是事件条数——
431
+ // 从 claim 到 assemble 之间还夹着 await tools.resolve(...),这期间任何插件
432
+ // 追加一个事件都会让条数增长,按条数判会把「消息还没落盘」误判成「已落盘」,
433
+ // 票据提前退休、Step 1 又退回空串(正是本 issue 要修的那一拍)。文本相等才是
434
+ // 「这条消息真的进事件流了」的直接证据;连续两轮同一句话时两者相等,取哪个都对。
435
+ function liveStepQuery(ctx) {
436
+ const info = lastUserMessageInfo(ctx);
437
+ let sessionId = null;
438
+ try {
439
+ const id = ctx?.agent?.session?.id;
440
+ if (typeof id === "string" && id) sessionId = id;
441
+ } catch { /* session internals unavailable */ }
442
+ if (!sessionId) return info.text;
443
+ const ticket = pendingQueries.get(sessionId);
444
+ if (!ticket) return info.text;
445
+ if (info.text === ticket.text) {
446
+ pendingQueries.delete(sessionId); // 已落盘,票据退休(顺带保证 Map 不被历史会话撑大)
447
+ return info.text;
448
+ }
449
+ if (Date.now() - ticket.at > PENDING_QUERY_TTL_MS) {
450
+ pendingQueries.delete(sessionId); // 过期证据,不采信
451
+ return info.text;
452
+ }
453
+ return ticket.text;
454
+ }
455
+
456
+ // 会话身份解析(v1.2 人格寻址用):读 session.header.agentPreset——冻结的
457
+ // SessionHeader(issue #17 身份契约)。⚠️ 不能先读 requestHeader():那返回
458
+ // EpochHeader(请求级头,首请求后为真),会把 session.header 遮蔽掉,身份取空
459
+ // (scope.js 同坑,本地实测踩过)。任何失败静默 → null(落 default 卡)。
460
+ function sessionAgentId(ctx) {
461
+ try {
462
+ const session = ctx?.agent?.session;
463
+ const header = session?.header ?? null;
464
+ const preset = header?.agentPreset;
465
+ return typeof preset === "string" && preset.trim() ? preset.trim() : null;
466
+ } catch {
467
+ return null;
468
+ }
469
+ }
470
+
471
+ // 会话 id 解析(#606 绑会话卡用):session.id 在宿主里稳定可用(scope.js:97-103
472
+ // 就是靠它反查 workspace 的)。与 agentPreset 一样各自护住——两者来自同一个
473
+ // session 对象,但 accessor 抛错时不该互相拖累(一个取不到不影响另一个)。
474
+ // 为什么需要第二个键:DS Bot 里 agentPreset 恒为 "standard",按 bot 建卡分不开,
475
+ // 只有会话 id 能分开(实测见 issue #606)。
476
+ function sessionIdOf(ctx) {
477
+ try {
478
+ const id = ctx?.agent?.session?.id;
479
+ return typeof id === "string" && id.trim() ? id.trim() : null;
480
+ } catch {
481
+ return null;
482
+ }
483
+ }
484
+
485
+ // 父会话 id 解析(子 agent 继承人格卡用):子代理会话的 header 里有 `parentSession`
486
+ // (实测 518 个子代理头恒带此字段,主会话没有)。⚠️ 与 `session-gate.js` 的口径不同:
487
+ // 那里刻意不用它判「是不是子代理」(宿主 fork 出的主会话分支同样带 parentSession),
488
+ // 这里只把它当「自己没建卡时该继承谁」的线索,fork 出的分支继承父卡同样是正确语义。
489
+ function parentSessionIdOf(ctx) {
490
+ try {
491
+ const session = ctx?.agent?.session;
492
+ const parent = session?.header?.parentSession;
493
+ return typeof parent === "string" && parent.trim() ? parent.trim() : null;
494
+ } catch {
495
+ return null;
496
+ }
497
+ }
498
+
499
+ // 一次取全三个寻址键。分开取值、各自兜错:一个失败不该让另一个也丢。
500
+ function sessionIdentity(ctx) {
501
+ return { agentId: sessionAgentId(ctx), sessionId: sessionIdOf(ctx), parentSessionId: parentSessionIdOf(ctx) };
502
+ }
503
+
504
+ // User profile + rules: injected ahead of the memory block because they are
505
+ // always-relevant instructions the agent should follow every turn.
506
+ // 渲染整体搬到 src/user-settings.js(与面板预览共用一份,见那里的模块头注释)。
507
+ // 口径不变:双闸门(config.personaEnabled && 卡.enabled)都开时人格行在最前,
508
+ // 画像与规则后出、后写覆盖占上风,rules 恒最硬;任一闸关着时输出与历史版本逐字节
509
+ // 一致(老用户零变化)。personaStrictAddressing 打开时,「有身份但没建卡」与
510
+ // 「卡被显式关掉」都不注入人格——default 只兜「这一帧解析不到身份」的会话。
511
+ function renderUserSettings(ctx) {
512
+ // factsInject 是 profile-facts 域的读口(index.js 接线,面板预览路由传同一份):
513
+ // 开关与事实有无的判定都在 renderUserSettingsBlock 内部,「关」等于零读数。
514
+ const { agentId, sessionId, parentSessionId } = sessionIdentity(ctx);
515
+ return renderUserSettingsBlock({ settings, config, agentId, sessionId, parentSessionId, factsProvider: factsInject })
516
+ .text;
517
+ }
518
+
519
+ // #249 能力说明的系统提示段。order 150 = 插件指引段的既有惯例
520
+ // (ACP 的 ACP_SYSTEM_PROMPT 与 mnemon 的 routing 段都在 150)。文本是常量、
521
+ // 同会话内不随轮次变化,故不影响其后的前缀缓存,也不逐轮复读。宿主若不提供
522
+ // section seam 就静默跳过——#249 §3 的口径是「只用现成 seam,拿不到位的语义
523
+ // 降级处理」:能力说明仍落在工具描述上,不算失败。
524
+ // 走父/子闸门(#249 第二批):注入器本身只在 `autoInject` 开时挂载,这里是
525
+ // 第二道、也是同一个判据的显式落点——两处消费点共用 injectChildEnabled,
526
+ // 不在各自的地方重写「父关则子不生效」。
527
+ const guideSection = injectChildEnabled(config, "injectGuidanceEnabled") && typeof ctx.systemPrompt?.section === "function"
528
+ ? ctx.systemPrompt.section({
529
+ name: "memory-guide",
530
+ order: 150,
531
+ text: (promptCtx) => (sessionGate?.isOff(sessionOf(promptCtx)) ? "" : MEMORY_GUIDE_SECTION)
532
+ })
533
+ : null;
534
+
535
+ const disposers = [
536
+ ...(guideSection ? [guideSection] : []),
537
+ ctx.systemPrompt.context({
538
+ name: "memory",
539
+ order: 90,
540
+ text: (ctx) => {
541
+ if (sessionGate?.isOff(sessionOf(ctx))) return "";
542
+ // Bug4: pass the latest user query so injection prefers semantically
543
+ // relevant memories; liveStepQuery is best-effort (empty → legacy).
544
+ // The query vector is prefetched asynchronously (cached) because the
545
+ // render itself must stay synchronous.
546
+ // #617:liveStepQuery 而不是 lastUserQuery——宿主在 step 末尾才 append
547
+ // user/message,而注入在这之前求值,只看事件流会拿到上一轮的输入。
548
+ const query = liveStepQuery(ctx);
549
+ if (query) prefetchQueryVector(query);
550
+ const queryVector = queryVectorCache.get(query);
551
+ // v0.8.0 A3:scope 随请求解析(解析器恒返回对象,身份取不到时两维为
552
+ // null);硬过滤与软加权的门控都在 injectCandidates 内——strict 看
553
+ // strictScope,软加权看 scopeEnabled 且至少一维可解析(issue #339)。
554
+ const scope = resolveSessionScope(ctx);
555
+ // Issue #205:跨轮轮换——最近 N 个查询轮次注入过的 id 本轮不再优先。
556
+ const sessionId = ctx?.agent?.session?.id ?? "_";
557
+ const rotate = recentInjectedIds(sessionId, query);
558
+ // rotateWindow 随集合一起传入:候选池按 maxItems×(N+1) 扩容——窗口要的
559
+ // 牌比既有 maxItems×2 池多时,轮换才有新鲜牌可换(#205 补测)。
560
+ // Issue #239(第 5 项):注入条数的查询自适应(默认关)。确定性强的话题收缩
561
+ // 条数、模糊话题维持上限——单向收缩,绝不越过 maxInjectedItems;判据只看查询
562
+ // 本身,不做额外检索(先探针检索等于白付一次 fuseRecall)。
563
+ const maxItems = config.injectUncertaintyAdaptive === true
564
+ ? adaptiveInjectBudget(query, baseMaxItems)
565
+ : baseMaxItems;
566
+ // #249 第一批:pin 池统计走可选出参,不动 injectCandidates 的数组契约。
567
+ const pinnedStats = {};
568
+ // Issue #380:注入前判定(preInjectGate)由 injectCandidates **内部**消费——
569
+ // 判定与滤除必须发生在它的 touchRecalled / recall 记账之前(#380 评审:与
570
+ // strictScope 同纪律,见 service.js 的「闸门还必须在 touchRecalled 之前」)。
571
+ // pin 池(#249 逐字保真)与 graphHint 线索行豁免由 service 侧按同口径切出。
572
+ // 渲染同步约束 → 闸门是 async prefetch + cache、同步消费:缓存命中当帧生效
573
+ // (enforce 滤除 / observe 记账),冷缓存首帧降级为原样注入、下一轮同 key
574
+ // 渲染生效——防线故障永不阻塞注入。帧状态经 gateStats 出参带回(同 pinnedStats
575
+ // 的出参口径),这里只读它做面板快照。
576
+ const gateStats = {};
577
+ const candidates = service.injectCandidates({ query, queryVector, maxItems, threshold, scope, rotate, rotateWindow: rotationTurns, pinnedStats, gate, gateStats });
578
+ const pinnedShown = Math.max(0, pinnedStats.shown ?? 0);
579
+ const gateFrame = gateStats.frame ?? null;
580
+ // #249:pin 条目不进轮换历史——它们每轮固定前置,记进去只会占满轮换
581
+ // 窗口、挤掉情景候选的新鲜度(验收:pin 不参与跨轮轮换)。
582
+ recordInjection(sessionId, query, pinnedShown > 0 ? candidates.slice(pinnedShown) : candidates);
583
+ // Hot memory (v0.5.0 1.3) leads the single memory block: the agent
584
+ // sees the short-term rounds first, then the cross-session recall —
585
+ // the documented injection order 1→2. Folding it here (instead of a
586
+ // separate context) keeps the prompt assembly stable at two blocks.
587
+ const hotText = renderHotContext(ctx);
588
+ const body = render(candidates, pinnedStats);
589
+ // #333(issue #34 恢复):时间前缀只在会话首轮出现(per-session 闩锁),
590
+ // 排在整个记忆块的最前——模型先知道「今天几号」,再看热上下文与长期记忆。
591
+ const timePrefix = renderTimePrefix(ctx);
592
+ // M3 仓库地志(chorography):只注标题级提纲,档位 off/light/full。
593
+ // cwd 用 scope.workspace_scope——那是全仓唯一的 cwd 口径(registry 反查,
594
+ // header.cwd 兜底),另读一份就是两张皮且重犯 #487 的 Proxy 陷阱(P27)。
595
+ // 取不到 cwd / 仓库没登记 / 渲染失败一律空串:本块在热路径上,不能抛。
596
+ const choroText = choroInject && typeof choroInject.text === "function"
597
+ ? choroInject.text(scope?.workspace_scope ?? null)
598
+ : "";
599
+ // 拼接次序:时间 → 地志 → 热上下文 → 长期记忆(四者都可能为空,逐级判空)。
600
+ // 地志排在热上下文之前:它是「这个仓库由哪些模块组成」的稳定背景,
601
+ // 而热上下文是「刚才聊到哪」,越靠近正文越晚——稳定的在前,易变的在后。
602
+ const withHot = !hotText ? body : body ? `${hotText}\n\n${body}` : hotText;
603
+ const withChoro = !choroText ? withHot : withHot ? `${choroText}\n\n${withHot}` : choroText;
604
+ const finalBody = !timePrefix ? withChoro : withChoro ? `${timePrefix}\n\n${withChoro}` : timePrefix;
605
+ // Issue #179:旁路缓存一帧——面板「注入预览」卡据此展示构成与体积。
606
+ // chars 为条目内容的截断后近似值(与 render 同一函数计长),totalChars
607
+ // 是本次实际返回块的精确长度。maxItems 反映自适应收缩后的生效值。
608
+ injectionSnapshot = {
609
+ at: Date.now(),
610
+ sessionId,
611
+ query: query || "",
612
+ maxItems,
613
+ threshold,
614
+ adaptive: config.injectUncertaintyAdaptive === true,
615
+ scoped: scope && (scope.agent_scope || scope.workspace_scope) ? scope : null,
616
+ rotated: rotate ? rotate.size : 0,
617
+ // Issue #380:闸门状态进快照(off/pending/observed/filtered),面板
618
+ // 「注入预览」卡据此展示判定是否生效与标记数。
619
+ gate: gateFrame ? { state: gateFrame.state, nFlagged: gateFrame.flaggedIds ? gateFrame.flaggedIds.size : null, judged: gateFrame.judged ?? null } : null,
620
+ hotChars: hotText.length,
621
+ // M3:地志块实际占的字符数(0 = 本帧没注入),面板据此区分「关」与「没匹配到仓库」。
622
+ choroChars: choroText.length,
623
+ entries: candidates.map((m) => ({
624
+ id: m.id,
625
+ type: m.type,
626
+ title: m.title,
627
+ importance: m.importance,
628
+ chars: injectMemory(m).length
629
+ })),
630
+ totalChars: finalBody.length
631
+ };
632
+ return finalBody;
633
+ }
634
+ }),
635
+ ctx.systemPrompt.context({
636
+ name: "user-settings",
637
+ order: 85,
638
+ text: (ctx) => (sessionGate?.isOff(sessionOf(ctx)) ? "" : renderUserSettings(ctx))
639
+ })
640
+ ];
641
+
642
+ return () => {
643
+ // #617:认领票据是监听宿主事件的活句柄,卸载时必须成对摘掉,否则注入器重装
644
+ // (面板开关、宿主热重载)会留下一个继续写 Map 的孤儿监听。
645
+ offClaimed?.();
646
+ pendingQueries.clear();
647
+ inflightPrefetches.clear();
648
+ prefetchFailedAt.clear();
649
+ queryVectorCache.clear();
650
+ rotationHistory.clear();
651
+ injectionSnapshot = null; // 注入器卸载即失效:快照不得跨生命周期存留
652
+ for (const dispose of disposers) {
653
+ if (typeof dispose === "function") dispose();
654
+ }
655
+ };
656
+ }