@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/src/tools.js CHANGED
@@ -1,1356 +1,1370 @@
1
- import { defineTool } from "@deepseek-ai/dsh-tools";
2
- import { createScopeResolver, normalizeExplicitScope, sessionKeyOf, sessionOf } from "./scope.js";
3
- import { describeLocalRuntime, resolveRuntimeEntry } from "./runtime/loader.js";
4
- import { defaultRuntimeDir } from "./runtime/layout.js";
5
- import { hostModulesDir, loadRuntimeManifest, provisionRuntime } from "./runtime/provision.js";
6
- import { matchesPlatform } from "./runtime/closure.js";
7
- import { verifyPayload } from "./runtime/verify.js";
8
- import { TOOL_GUIDE, CONTINUITY_TOOL_RULE } from "./guide.js";
9
- import { injectChildEnabled } from "./config.js";
10
- import { normalizeScopeStateDimension, normalizeScopeStateValue, normalizeScopeStateState } from "./scope-state.js";
11
- import { lastUserQuery } from "./inject.js";
12
- // issue #607:工具报错里的 CLI 命令同样要给绝对路径入口——profile 装的插件没有
13
- // 全局 shim,光写 `dsh-mneme-choro` 用户照抄只会 command not found。
14
- import { choroCliCommandFrom } from "./wiki/cli-hint.js";
15
- // 知识库三工具(契约 §3.4):定义住在 kb/tools.js,本文件只决定注册不注册。
16
- import { kbToolDefinitions } from "./kb/tools.js";
17
-
18
- const TEXT_OUTPUT = (text) => [{ type: "text", text }];
19
- // 工具报错里的命令串:本文件在 src/ 与 lib/ 同一层(bin/ 的父级),模块加载时推导一次。
20
- // 推导不出(源码树被裁剪)就返回 null,文案退回通用说法。
21
- const CHORO_CLI = choroCliCommandFrom(import.meta.url, "<repo>");
22
- const incompleteChoroSearch = (pages) =>
23
- `Search was incomplete because these pages could not be read (${pages.join(", ")}). Check the local checkout and page permissions.`;
24
- // Per-registry tool-name registry: guards against duplicate registration on
25
- // live patch reload (DSH Desktop `patchReload: "live"`) where a plugin may be
26
- // re-applied on the same tools registry without an intervening unregister.
27
- const REGISTERED_TOOLS = new WeakMap();
28
-
29
- // Wire shape emitted by service.toApiList: shared by memory_search and
30
- // memory_list so their output schemas always declare every key the runtime
31
- // value carries (additionalProperties: false would reject undeclared keys).
32
- const MEMORY_ITEM_SCHEMA = {
33
- type: "object",
34
- additionalProperties: false,
35
- properties: {
36
- id: { type: "string", required: true },
37
- type: { type: "string", required: true },
38
- title: { type: "string", required: true },
39
- content: { type: "string", required: true },
40
- tags: { type: "array", items: { type: "string" } },
41
- importance: { type: "integer", required: true },
42
- source: { type: "string" },
43
- // v0.8.0 A2:scope 标注与事件发生时间随行透出(未标注时缺省,可选属性)。
44
- // v0.8.1 底座:scope 来源(auto/explicit)与决策时间随行透出(同样可选)。
45
- agent_scope: { type: "string" },
46
- workspace_scope: { type: "string" },
47
- agent_scope_source: { type: "string" },
48
- workspace_scope_source: { type: "string" },
49
- scope_decided_at: { type: "string" },
50
- sensitivity: { type: "string" },
51
- occurred_at: { type: "string" },
52
- // #230:document 指针行的文件定位——「全文按需读」的入口;普通行缺省。
53
- doc_path: { type: "string" },
54
- created_at: { type: "string", required: true },
55
- updated_at: { type: "string", required: true }
56
- }
57
- };
58
- // 导出供回归测试断言 memory_get 与共享 schema 同源(#184 防漂移护栏)。
59
- export { MEMORY_ITEM_SCHEMA };
60
-
61
- // v0.8.0 A2:occurred 时间窗参数 → store 过滤选项(list/count 同口径);
62
- // 未传参返回空对象,既有调用方不受影响。(A3 复核:此处入参仅含 occurred 边界。)
63
- function occurredWindow(args) {
64
- const from = args?.occurred_from ?? null;
65
- const to = args?.occurred_to ?? null;
66
- return from !== null || to !== null ? { occurredFrom: from, occurredTo: to } : {};
67
- }
68
-
69
- // v0.8.0 A3:strictScope 硬过滤的 visibility 选项(store.list/count 同口径)。
70
- // flag 关或会话 scope 未解析出(flag 关时解析器返回 null)→ 空对象不过滤;
71
- // scope 为 {null,null}(匿名会话)时照传——store 侧 fail-closed 只放行未标注行。
72
- function strictVisibility(config, scope) {
73
- if (config?.strictScope !== true || !scope) return {};
74
- return { visibility: { agentScope: scope.agent_scope, workspaceScope: scope.workspace_scope } };
75
- }
76
-
77
- // v0.8.0 A2:检索结果的 provenance 附加段——只在有标注时出现,未标注行渲染
78
- // 与 A2 前逐字节一致。
79
- const MEMORY_PROVENANCE = (m) => {
80
- const parts = [];
81
- if (m.occurred_at) parts.push(`occurred: ${m.occurred_at}`);
82
- if (m.agent_scope || m.workspace_scope) {
83
- parts.push(`scope: ${m.agent_scope ?? "global"} / ${m.workspace_scope ?? "global"}`);
84
- }
85
- if (m.sensitivity) parts.push(`sensitivity: ${m.sensitivity}`);
86
- return parts.length ? ` | ${parts.join(" | ")}` : "";
87
- };
88
-
89
- // choro(M1):chorography 只读查询对象(createChoroQueries 产物)。缺省 null =
90
- // 装配层没接(headless/测试),三个 choro_* 工具走 hiddenTools 闸根本不注册。
91
- // 它与 service 刻意分开传——chorography 的所有权模型与记忆域相反(spec §3)。
92
- // kb:知识库装配对象(createKb 产物);缺省 null = 宿主没装它,三个 kb 工具不注册。
93
- export function createTools(ctx, service, config, embedder, sessionGate = null, choro = null, kb = null) {
94
- const toolsRegistry = ctx.tools;
95
- let registration = REGISTERED_TOOLS.get(toolsRegistry);
96
- if (!registration) {
97
- registration = { names: new Set(), sessionGate: null };
98
- REGISTERED_TOOLS.set(toolsRegistry, registration);
99
- }
100
- registration.sessionGate = sessionGate;
101
- const registeredTools = registration.names;
102
- // v0.8.0 A1/A2(issue #17):会话 scope 解析(agentPreset + workspace 反查)。
103
- // flag 关闭时恒返回 null——写入不标注,检索不加权,行为与 A1 前完全一致。
104
- // logger 透传:registry 反查失败时 warnOnce 才有出口(否则静默降级无观测)。
105
- const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
106
- // 宿主在 render 前按成功 schema 校验返回值,仓库解析失败要走工具错误通道。
107
- const resolveChoroRepo = (ref) => {
108
- const row = choro.resolveRepo(ref);
109
- if (!row) {
110
- const reason = ref ? `Repository ${JSON.stringify(ref)} is not registered.` : "No repository is registered for chorography.";
111
- throw new Error(`${reason} ${CHORO_CLI ? `Run \`${CHORO_CLI}\`` : "Run `dsh-mneme-choro <repo> --apply`"} to register a repository.`);
112
- }
113
- if (row.ambiguous) {
114
- const choices = row.ambiguous.map(({ id, name }) => `${id} (${name})`).join(", ");
115
- throw new Error(`More than one repository is registered. Pass one of these repository IDs (${choices}).`);
116
- }
117
- return row;
118
- };
119
- // #249 能力说明(injectGuidanceEnabled):开启时给「何时用」最有歧义的两个
120
- // 工具补一句判断指引。工具描述常驻、不进每轮上下文,这个位子零注入成本;
121
- // 关闭时描述逐字节不变,也不动其他工具的文案。
122
- // 它是注入父开关的子项(#249 第二批):`autoInject` 关掉时这里同样不生效——
123
- // 工具描述是这个子项唯一住在注入器之外的落点,不在闸门内就漏了。
124
- // #249 N3 降级路径(continuityRescueEnabled):宿主若不提供可挂钩的压缩前时机,
125
- // 双落点里的注入那一半就没有触发者,这时把规则交给 agent 自判(见 CONTINUITY_TOOL_RULE)。
126
- // 与能力说明各自独立:任一开关关闭时描述逐字节不变。
127
- // 本批不做宿主能力探测(没有可靠的探测口),所以子开关打开时这条规则常驻,与自动双落点并存。
128
- const withToolGuide = (name, description) => {
129
- let text = description;
130
- if (injectChildEnabled(config, "injectGuidanceEnabled") && TOOL_GUIDE[name]) text += TOOL_GUIDE[name];
131
- if (injectChildEnabled(config, "continuityRescueEnabled") && CONTINUITY_TOOL_RULE[name]) text += CONTINUITY_TOOL_RULE[name];
132
- return text;
133
- };
134
-
135
- // 复核项 4(issue #170):strictScope 下他 scope(explicit)的行对工具侧按
136
- // 「不存在」处理——update/delete 与 memory_get 同款无存在性泄漏。strictScope
137
- // 关、或会话身份取不到(scope 为 null)时恒可见(与 get 的短路语义一致)。
138
- const visibleUnderStrictScope = (memory, exec) => {
139
- if (config?.strictScope !== true) return true;
140
- const scope = resolveSessionScope(exec);
141
- return !scope || service.isVisibleInScope(memory, scope);
142
- };
143
- // 在调用点以「展开恒为 undefined」的形态前置校验(抛错即中止写入)。
144
- const assertVisibleForTool = (id, exec) => {
145
- const memory = id ? service.getById(id) : undefined;
146
- if (!visibleUnderStrictScope(memory, exec)) throw new Error("memory not found");
147
- return undefined;
148
- };
149
- // delete 侧需要目标行本身判断存在性(不可见 = 视作不存在,不抛错)。
150
- const visibleForTool = (id, exec) => {
151
- const memory = id ? service.getById(id) : undefined;
152
- return visibleUnderStrictScope(memory, exec) ? memory : undefined;
153
- };
154
- const tools = [
155
- defineTool({
156
- name: "memory_save",
157
- description: withToolGuide(
158
- "memory_save",
159
- "Persist one memory entry for future sessions (user preferences, project state, decisions). " +
160
- "Call this when the user states a durable preference, a project decision is made, or a lesson is learned. " +
161
- "Merges into an existing entry of the same type when the title matches."
162
- ),
163
- parameters: {
164
- // document 不在此列(#230):document 行只能经 memory_register_document
165
- // 铸造(注册校验 + doc_path + evidence),防止 memory_save 造出无指针
166
- // 无回链的伪行。
167
- type: { type: "string", required: true, enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint"], description: "preference=user profile; project=project knowledge/state; decision=key decision; history=conversation summary; rejected_solution=rejected/abandoned implementation approach; pitfall=debugging lesson (symptom+root cause+fix); constraint=engineering constraint" },
168
- title: { type: "string", required: true, description: "Short unique title" },
169
- content: { type: "string", required: true, description: "Memory body" },
170
- tags: { type: "array", items: { type: "string" }, description: "Optional tags" },
171
- importance: { type: "integer", description: "1-5; >= threshold auto-injects into future sessions" },
172
- source: { type: "string", description: "Optional provenance" },
173
- sensitivity: { type: "string", description: "Optional sensitivity label (free-form, e.g. personal). Same-title entries with different sensitivity stay separate instead of merging." },
174
- occurred_at: { type: "string", description: "Optional ISO-8601 instant the remembered event happened (differs from write time). Invalid values are ignored." },
175
- agent_scope: { type: "string", description: "Optional explicit agent-scope declaration (issue #170): 'global' or '*' makes this memory visible to every agent; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." },
176
- workspace_scope: { type: "string", description: "Optional explicit workspace-scope declaration: 'global' or '*' makes this memory visible in every workspace; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." }
177
- },
178
- output: {
179
- schema: {
180
- type: "object",
181
- additionalProperties: false,
182
- properties: {
183
- action: { type: "string", required: true, enum: ["created", "merged", "denied"] },
184
- // denied 时压根没有行可指,所以 id 缺省而不是空串:空串会让「写成功但
185
- // id 为空」与「根本没写」在读回执时长得一样,与 #254 验收第 2 条
186
- // (被拒写入可解释、不静默丢弃)相悖。
187
- id: { type: "string", description: "Row id; absent when action=denied." },
188
- reason: { type: "string", description: "Rejection reason when action=denied: blank | noise | sensitive." }
189
- }
190
- },
191
- render: (_args, value) => TEXT_OUTPUT(value.action === "denied"
192
- ? `memory save rejected (${value.reason ?? "denied"}): nothing was written`
193
- : `memory ${value.action}: ${value.id}`)
194
- },
195
- async execute(args, exec) {
196
- // scope 标注(v0.8.1 底座,issue #170):默认由会话身份解析(载体自动
197
- // 标注,盖 auto 章);显式 agent_scope/workspace_scope 参数逐维覆盖并盖
198
- // explicit 章。解析绝不抛错、取不到落 NULL。
199
- // 复核项 2(#170):scopeEnabled 只门控「自动标注」分支——显式声明与
200
- // 读取身份(search/list/get/注入经同一解析器)不受 flag 限制,否则
201
- // strictScope 硬墙会被 flag 静默拆掉(fail-open)。
202
- // (存储 NULL,由 source 列与「从未标注」区分)。非字符串参数在工具
203
- // 入参 schema 层即被拒(type: "string")——脏值到不了归一化,无静默放宽。
204
- const scope = resolveSessionScope(exec);
205
- const autoStamping = config?.scopeEnabled === true;
206
- const agentLabel = args.agent_scope !== undefined
207
- ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
208
- : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
209
- const workspaceLabel = args.workspace_scope !== undefined
210
- ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
211
- : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
212
- const result = service.saveWithDedupe({
213
- // #254 写入准入的计数单位:会话键作为瞬时字段随写入传递(与 _mergeInto /
214
- // _overwrite 同款约定,不落库)。缺会话身份的宿主返回 null = 这次写入不进
215
- // 预算;系统写入(dream / summarize / organize)从不带这个字段。
216
- _sessionKey: sessionKeyOf(exec),
217
- type: args.type,
218
- title: args.title,
219
- content: args.content,
220
- tags: args.tags ?? [],
221
- importance: args.importance ?? 3,
222
- source: args.source ?? "tool",
223
- ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
224
- ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {}),
225
- ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
226
- ...(args.occurred_at !== undefined ? { occurred_at: args.occurred_at } : {})
227
- });
228
- // #254 第 1 级硬拒:工具层是模型唯一能看到这次失败的地方,必须显式回一句
229
- // 可行动的拒绝理由。静默返回成功会让模型以为记住了,然后永远不再重写。
230
- if (result.action === "denied") return { action: "denied", reason: result.reason };
231
- return { action: result.action, id: result.memory.id };
232
- }
233
- }),
234
-
235
- defineTool({
236
- name: "memory_search",
237
- description: withToolGuide(
238
- "memory_search",
239
- "Search the cross-session memory store for past context (solved problems, user preferences, project decisions). IMPORTANT: relevant cross-session memories are already injected into your context every turn — only call this when the injected memory block does NOT contain what you need, or you need to look something specific up. Substring-matches title/content/tags, and augments results with semantic (vector) recall + optional rerank when an embeddings provider is configured. Returns matching entries with source and timestamps."
240
- ),
241
- // A2 检索接线:occurred 时间窗 + 会话 scope 加成(见 execute)。
242
- parameters: {
243
- query: { type: "string", required: true, description: "Search text; substring match over title/content/tags" },
244
- limit: { type: "integer", description: "Max results (default 20)" },
245
- mode: { type: "string", enum: ["auto", "keyword", "vector", "hybrid"], description: "auto (default) = keyword hits first + vector fill when enabled; keyword = text only; vector = semantic recall first (falls back to keyword); hybrid = vector leads, keyword fills remaining slots" },
246
- semantic: { type: "boolean", description: "Shorthand: enable semantic (vector) recall (same as mode=vector when true)" },
247
- rerank: { type: "boolean", description: "Run cross-encoder rerank over candidates when a local reranker is configured (default true)" },
248
- occurred_from: { type: "string", description: "Optional ISO date/timestamp lower bound on when the remembered event happened (occurred_at, falling back to created_at). Date-only values are inclusive from that day's 00:00Z." },
249
- occurred_to: { type: "string", description: "Optional ISO date/timestamp upper bound on occurred_at. Date-only values are inclusive through that day's 23:59:59.999Z." }
250
- },
251
- output: {
252
- schema: {
253
- type: "object",
254
- additionalProperties: false,
255
- properties: {
256
- items: {
257
- type: "array", required: true,
258
- items: MEMORY_ITEM_SCHEMA
259
- }
260
- }
261
- },
262
- render: (_args, value) => {
263
- const items = value.items ?? [];
264
- if (items.length === 0) return TEXT_OUTPUT("No memory entries found.");
265
- const body = items
266
- .map((m, i) => {
267
- const preview = (m.content ?? "").replace(/\s+/g, " ").trim();
268
- const cut = preview.length > 200 ? `${preview.slice(0, 200)}…` : preview;
269
- return `[${i + 1}] ${m.title}\n ID: ${m.id} | type: ${m.type} | importance: ${m.importance} | updated: ${m.updated_at}${MEMORY_PROVENANCE(m)}\n ${cut}`;
270
- })
271
- .join("\n\n");
272
- return TEXT_OUTPUT(`Found ${items.length} memory entr${items.length === 1 ? "y" : "ies"}:\n\n${body}`);
273
- }
274
- },
275
- async execute(args, exec) {
276
- const limit = args.limit ?? 20;
277
- const mode = args.semantic === true && !args.mode ? "vector" : args.mode ?? "auto";
278
- // v0.8.0 A2(issue #17):scope 检索加权 + occurred 时间窗的检索接线。
279
- // flag 关闭或解析不出 scope 时为 null,检索行为与 A2 前一致。
280
- const scope = resolveSessionScope(exec);
281
- const occurredFrom = args.occurred_from ?? null;
282
- const occurredTo = args.occurred_to ?? null;
283
- const rows = await service.searchMemories(args.query, {
284
- mode,
285
- topK: limit,
286
- useRerank: args.rerank !== false,
287
- ...(scope ? { scope } : {}),
288
- ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
289
- });
290
- return { items: service.toApiList(rows) };
291
- }
292
- }),
293
-
294
- defineTool({
295
- name: "memory_list",
296
- description: "List memory entries by type, high-importance first, then newest, paginated. Set include_archived=true to also list archived (hidden) entries so they can be located and restored.",
297
- parameters: {
298
- type: { type: "string", enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint", "document"], description: "Filter by type; omit for all. 'document' (#230) = agent-registered document pointer rows" },
299
- limit: { type: "integer", description: "Page size (default 50)" },
300
- offset: { type: "integer", description: "Page offset (default 0)" },
301
- include_archived: { type: "boolean", description: "Include archived (hidden) entries so they can be found and restored (default false)" },
302
- occurred_from: { type: "string", description: "Optional ISO date/timestamp lower bound on when the remembered event happened (occurred_at, falling back to created_at). Date-only values are inclusive from that day's 00:00Z." },
303
- occurred_to: { type: "string", description: "Optional ISO date/timestamp upper bound on occurred_at. Date-only values are inclusive through that day's 23:59:59.999Z." }
304
- },
305
- output: {
306
- schema: {
307
- type: "object",
308
- additionalProperties: false,
309
- properties: {
310
- items: {
311
- type: "array", required: true,
312
- items: MEMORY_ITEM_SCHEMA
313
- },
314
- total: { type: "integer", required: true }
315
- }
316
- },
317
- render: (_args, value) => {
318
- const items = value.items ?? [];
319
- if (items.length === 0) return TEXT_OUTPUT(`0 memory entries (of ${value.total}).`);
320
- const body = items
321
- .map((m, i) => `[${i + 1}] ${m.title} (type=${m.type}, importance=${m.importance})\n ID: ${m.id} | updated: ${m.updated_at}${MEMORY_PROVENANCE(m)}`)
322
- .join("\n\n");
323
- return TEXT_OUTPUT(`${items.length} memory entries (of ${value.total}):\n\n${body}`);
324
- }
325
- },
326
- async execute(args) {
327
- const includeArchived = args.include_archived === true;
328
- const rows = service.toApiList(service.list({
329
- type: args.type,
330
- limit: args.limit ?? 50,
331
- offset: args.offset ?? 0,
332
- includeArchived,
333
- ...occurredWindow(args),
334
- // A3:strict 开启时按会话 scope 硬过滤(宿主按 (args, runContext) 调用,
335
- // 从 arguments 取第二参)。
336
- ...strictVisibility(config, resolveSessionScope(arguments[1]))
337
- }));
338
- return { items: rows, total: service.count(args.type, { includeArchived, ...occurredWindow(args), ...strictVisibility(config, resolveSessionScope(arguments[1])) }) };
339
- }
340
- }),
341
-
342
- defineTool({
343
- name: "memory_get",
344
- description: "Fetch one memory entry by ID and return its full content as text. Use after memory_list to read a specific entry.",
345
- parameters: {
346
- id: { type: "string", required: true, description: "Memory id" }
347
- },
348
- output: {
349
- schema: {
350
- type: "object",
351
- additionalProperties: false,
352
- properties: {
353
- // 与 memory_search / memory_list 共用同一份 item schema——DTO 由
354
- // toApiList 统一产出,内联副本曾漏掉 v0.8.1 的 scope 来源三键,
355
- // 任何被标注过的行都过不了 in-process 校验(#184)。
356
- memory: MEMORY_ITEM_SCHEMA
357
- }
358
- },
359
- render: (_args, value) => {
360
- const m = value.memory;
361
- // #230:document 指针行把文件路径亮在首行——「全文按需读」从这里拿路径。
362
- const doc = m.doc_path ? ` | doc: ${m.doc_path}` : "";
363
- return TEXT_OUTPUT(`${m.title}\nID: ${m.id} | type: ${m.type} | importance: ${m.importance}${doc}${MEMORY_PROVENANCE(m)}\n\n${m.content}`);
364
- }
365
- },
366
- async execute(args) {
367
- const memory = service.getById(args.id);
368
- if (memory === undefined) throw new Error("memory not found");
369
- // v0.8.0 A3:strictScope 下他 scope 的行按不存在处理(无存在性泄漏)。
370
- // 宿主注册表按 (args, runContext) 两参调用处理器,从 arguments 取第二参。
371
- const runContext = arguments[1];
372
- const scope = resolveSessionScope(runContext);
373
- if (config.strictScope === true && scope && !service.isVisibleInScope(memory, scope)) {
374
- throw new Error("memory not found");
375
- }
376
- return { memory: service.toApiList([memory])[0] };
377
- }
378
- }),
379
-
380
- defineTool({
381
- name: "memory_update",
382
- description: "Modify an existing memory entry (title, content, type, tags, importance).",
383
- parameters: {
384
- id: { type: "string", required: true, description: "Memory id" },
385
- title: { type: "string" },
386
- content: { type: "string" },
387
- // document 不在此列(#230):type 不许改入 document——既有 document 行
388
- // 的摘要修复(只改 content/title)不受影响。
389
- type: { type: "string", enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint"] },
390
- tags: { type: "array", items: { type: "string" } },
391
- importance: { type: "integer", description: "1-5" },
392
- reason: { type: "string", description: "Optional context for the correction (what the user actually said/wanted), recorded for reflection" },
393
- agent_scope: { type: "string", description: "Optional explicit agent-scope correction (issue #170): 'global' or '*' widens visibility to every agent; any other value narrows it to that label. Omit to keep the current agent scope. Recorded as an explicit scope decision (audited)." },
394
- workspace_scope: { type: "string", description: "Optional explicit workspace-scope correction: 'global' or '*' widens visibility to every workspace; any other value narrows it to that label. Omit to keep the current workspace scope. Recorded as an explicit scope decision (audited)." }
395
- },
396
- output: {
397
- schema: {
398
- type: "object",
399
- additionalProperties: false,
400
- properties: {
401
- memory: {
402
- type: "object",
403
- additionalProperties: false,
404
- properties: {
405
- id: { type: "string", required: true },
406
- title: { type: "string", required: true },
407
- content: { type: "string", required: true }
408
- }
409
- }
410
- }
411
- },
412
- render: (_args, value) => TEXT_OUTPUT(`Updated memory ${value.memory.id}: ${value.memory.title}`)
413
- },
414
- async execute(args) {
415
- // v0.9.0:失败表的 query 是「当时到底想干什么」唯一的落点,而 service
416
- // 层看不到会话(它只认 ctx.query,见 src/service.js 的 saveFailure 注释)。
417
- // 工具层是唯一同时握着改写动作与本轮会话的入口:没给 reason 就退回当轮用户
418
- // 原话,取法与注入侧共用同一份实现(src/inject.js 的 lastUserQuery),不复制
419
- // 第二份。两边都取不到时仍然写 NULL——空串会假装「有意图」,NULL 才说实话。
420
- const exec = arguments[1];
421
- const reason = typeof args.reason === "string" ? args.reason.trim() : "";
422
- const query = reason || lastUserQuery(exec) || undefined;
423
- const memory = service.update(args.id, {
424
- title: args.title,
425
- content: args.content,
426
- type: args.type,
427
- tags: args.tags,
428
- importance: args.importance,
429
- // 复核项 4(#170):strictScope 下他 scope 的行按「不存在」处理(与 get 对齐),
430
- // 展开恒为 undefined,仅承担写入前校验。
431
- ...(assertVisibleForTool(args.id, exec)),
432
- ...(args.agent_scope !== undefined ? { agent_scope: args.agent_scope } : {}),
433
- ...(args.workspace_scope !== undefined ? { workspace_scope: args.workspace_scope } : {})
434
- }, { query });
435
- return { memory: { id: memory.id, title: memory.title, content: memory.content } };
436
- }
437
- }),
438
-
439
- defineTool({
440
- name: "memory_delete",
441
- description: "Permanently delete a memory entry.",
442
- parameters: {
443
- id: { type: "string", required: true }
444
- },
445
- output: {
446
- schema: {
447
- type: "object",
448
- additionalProperties: false,
449
- properties: { deleted: { type: "boolean", required: true } }
450
- },
451
- render: (_args, value) => TEXT_OUTPUT(value.deleted ? "Memory deleted." : "Memory not found.")
452
- },
453
- async execute(args) {
454
- // 复核项 4(#170):不可见(explicit 他 scope)= 视作不存在,无存在性泄漏。
455
- const target = visibleForTool(args.id, arguments[1]);
456
- if (target) service.remove(args.id);
457
- return { deleted: !!target };
458
- }
459
- }),
460
-
461
- defineTool({
462
- name: "memory_forget",
463
- description:
464
- "Stop a memory from being auto-injected and from appearing in searches and lists without deleting it. " +
465
- "The entry stays in storage; pass forgotten: false to restore it. " +
466
- "#532: suppression is per ROW - facts fused into the same entry leave visibility together. " +
467
- "When the request targets one fact among several held by a row, inspect the row first (memory_get), " +
468
- "split it with memory_update if needed, or say in your reply what else the suppression took down " +
469
- "(docs/FORGET.md records the supersession gap behind this).",
470
- parameters: {
471
- id: { type: "string", required: true },
472
- forgotten: { type: "boolean", description: "Suppress (true, default) or restore (false) the entry's visibility" }
473
- },
474
- output: {
475
- schema: {
476
- type: "object",
477
- additionalProperties: false,
478
- properties: {
479
- memory: {
480
- type: "object",
481
- additionalProperties: false,
482
- properties: {
483
- id: { type: "string", required: true },
484
- forgotten: { type: "boolean", required: true }
485
- }
486
- }
487
- }
488
- },
489
- render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} injection ${value.memory.forgotten ? "suppressed" : "restored"}.`)
490
- },
491
- async execute(args) {
492
- if (service.getById(args.id) === undefined) {
493
- throw new Error("memory not found");
494
- }
495
- const memory = service.setForget(args.id, args.forgotten ?? true);
496
- return { memory: { id: memory.id, forgotten: memory.forgotten } };
497
- }
498
- }),
499
-
500
- // #249 第二批:显式 pin。注入侧原来靠「type 是 constraint/preference 就算
501
- // 重要」推断谁该每轮置顶,那是隐含假设——库里 1100+ 条自动成了「每轮必进」
502
- // 的候选而预算只有 5,真正该进去的反而排到二十名外。这个工具是那条推断的
503
- // 唯一人工替代口:钉住 = 每轮注入块最前面那几条(受 pinnedInjectBudget 约束),
504
- // 与类型无关(写得最全的那版常常是 pattern)。
505
- //
506
- // 三个边界写在这里:
507
- // - 它不改记忆内容,也不改任何「记忆行」字段,只动 pinned_memories 这张关系
508
- // 表,所以与 memory_forget / memory_archive / set_scope_state 都是**不同的轴**:
509
- // 遗忘/归档/暂停作用域仍然优先——被它们处理掉的行就算钉着也不会注入,
510
- // 回执里的 injectable 就是如实告诉我们这件事。
511
- // - 存在性校验走 visibleForTool:strictScope 下 he scope 的行按「不存在」处理,
512
- // 与 memory_delete 同款无存在性泄漏。
513
- // - unpin 幂等:本来没钉也返回 pinned:false,不报错。
514
- defineTool({
515
- name: "memory_pin",
516
- description:
517
- "Pin a memory so it is injected at the top of the memory block every turn, regardless of its type or how it ranks against other memories. " +
518
- "Use this only when the user explicitly says an entry must always be present (a hard rule, a standing preference); it is not a way to mark something as important — importance already affects ranking. " +
519
- "Pinned entries still obey forgetting, archiving, the scope gate and the two injection switches: when autoInject is off the host registers no injector at all, and when pinnedInjectBudget is 0 the pin pool is off (its default). In either case a pinned entry is not injected through the pin channel, and the receipt reports injectable: false. The receipt answers \"is the pin channel open right now\", not \"is this memory kept out of every block\": a row reported false can still be picked up by the ordinary candidate path on its own merits. " +
520
- "Pass unpin: true to release it. Pin order is first-pinned-first, so the oldest pin holds its slot when the budget is tight.",
521
- parameters: {
522
- id: { type: "string", required: true, description: "Memory id to pin (or unpin with unpin: true)" },
523
- note: { type: "string", description: "Optional short reason to keep with the pin, so a later reader knows why it is pinned" },
524
- unpin: { type: "boolean", description: "true releases the pin instead of setting it" }
525
- },
526
- output: {
527
- schema: {
528
- type: "object",
529
- additionalProperties: false,
530
- properties: {
531
- memory_id: { type: "string", required: true },
532
- pinned: { type: "boolean", required: true },
533
- // 如实回显库现值,不是回显入参:重钉一条已有的 pin 不刷新 created_at,
534
- // 回显它才看得出「这次其实没改变顺序」。
535
- created_at: { type: "string" },
536
- note: { type: "string" },
537
- // 钉着 ≠ 会注入。遗忘/归档/暂停作用域/autoInject 关/pinnedInjectBudget=0
538
- // 都优先于 pin,把这件事放进回执,而不是让用户以为钉完就一定出现在上下文里。
539
- // 回执回答的是「pin 这条通道此刻开不开」:报 false 不等于这条记忆一定不在
540
- // 上下文里——它仍可能凭自身重要性走常规候选路进块。
541
- // autoInject 是这条通道的总闸:关着时宿主根本不注册注入器
542
- // (src/index.js:617 的 if (cfg.autoInject)),pin 段自然也不执行。
543
- injectable: { type: "boolean", required: true }
544
- }
545
- },
546
- render: (_args, value) => {
547
- if (!value.pinned) return TEXT_OUTPUT(`Memory ${value.memory_id} is no longer pinned.`);
548
- const when = value.created_at ? ` (pinned at ${value.created_at})` : "";
549
- const blocked = value.injectable
550
- ? ""
551
- : " The pin channel is closed right now (forgotten, archived, inside a paused scope, autoInject off, or pinnedInjectBudget is 0 — the pin pool is off by default), so it is not placed at the top of the block; the ordinary candidate path can still pick it up on its own merits.";
552
- return TEXT_OUTPUT(`Memory ${value.memory_id} is pinned${when}.${blocked}`);
553
- }
554
- },
555
- async execute(args) {
556
- // 不可见(explicit 他 scope)= 视作不存在,无存在性泄漏。
557
- const target = visibleForTool(args.id, arguments[1]);
558
- if (target === undefined) throw new Error("memory not found");
559
- // 钉着 ≠ 会注入。这里必须跟注入侧用同一个出口判定,否则回执照样会说谎:
560
- // 暂停作用域的行在 enforce 档会被 scopeStateGate 剔掉,但 forgotten/archived
561
- // 两个标志位对此一无所知——只算这两项,一条被暂停作用域挡住的行就会报
562
- // injectable: true 而实际一条都没注入。filterPaused 正是那个出口(开关关、
563
- // 或只开观察档时它原样返回,于是此时报 true 是对的:那种状态下本来就不拦)。
564
- // #593 遗留缺口:pin 池整体由 pinnedInjectBudget 开关(src/service.js:1885 的
565
- // pinnedBudget > 0 才读表选路),而它默认 0 = 关闭。只看遗忘/归档/暂停作用域时,
566
- // 预算为 0 的一条回执照样报 injectable: true——钉住的动作确实成功了,但它此刻
567
- // 一条都不会被注入,这正是「返回成功不等于生效」。预算 0 必须报 false。
568
- //
569
- // 同一类谎话的第二处(CodeRabbit 在 #596 指出):autoInject 才是 pin 通道的总闸
570
- // ——关着时 src/index.js:617 根本不注册注入器,pin 段无从执行,而回执仍会报
571
- // true。config schema 里它的默认值是 true(src/config.js:10),所以按「只有显式
572
- // false 才算关」判:拿不到已填 defaults 的 config(测试直连 createTools)时不会
573
- // 被误报成 false。
574
- //
575
- // 仍然没建模的:候选池侧的 type / importance / codingGate 闸(一条被钉的
576
- // document 行同样进不了注入块)。那几道闸随候选池变化,回执不做猜测;
577
- // 这里只回答「pin 这条通道此刻开不开」——报 false 也不等于这条记忆一定不在
578
- // 上下文里,它仍可能凭自身重要性走常规候选路进块。
579
- const pinnedBudget = Math.max(0, Math.min(5, Math.floor(config?.pinnedInjectBudget ?? 0)));
580
- const autoInjectOn = config?.autoInject !== false;
581
- const injectable =
582
- autoInjectOn &&
583
- pinnedBudget > 0 &&
584
- !target.forgotten &&
585
- !target.archived &&
586
- service.filterPaused([target]).length > 0;
587
- if (args.unpin === true) {
588
- service.unpinMemory(target.id);
589
- return { memory_id: target.id, pinned: false, injectable };
590
- }
591
- const row = service.pinMemory(target.id, { note: args.note });
592
- if (row === undefined) throw new Error("pin could not be recorded");
593
- return {
594
- memory_id: row.memory_id,
595
- pinned: true,
596
- created_at: row.created_at,
597
- // 没写过理由时键整个不出现(output schema 是闭合的,留 undefined 等于空壳)。
598
- ...(row.note === undefined ? {} : { note: row.note }),
599
- injectable
600
- };
601
- }
602
- }),
603
-
604
- defineTool({
605
- name: "memory_archive",
606
- description:
607
- "Archive a memory (hide it from active lists, search, injection and dream consolidation) or restore it. " +
608
- "Archived entries stay in storage and are recoverable: pass archived=false to restore, and use memory_list with " +
609
- "include_archived=true to find archived entries. " +
610
- "Only archive when the user asks, or an entry is clearly stale/no longer relevant — do not archive proactively mid-session to tidy up.",
611
- parameters: {
612
- id: { type: "string", required: true, description: "Memory id" },
613
- archived: { type: "boolean", description: "Archive (true, default) or restore (false) the entry" }
614
- },
615
- output: {
616
- schema: {
617
- type: "object",
618
- additionalProperties: false,
619
- properties: {
620
- memory: {
621
- type: "object",
622
- additionalProperties: false,
623
- properties: {
624
- id: { type: "string", required: true },
625
- archived: { type: "boolean", required: true }
626
- }
627
- }
628
- }
629
- },
630
- render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} ${value.memory.archived ? "archived" : "restored"}.`)
631
- },
632
- async execute(args) {
633
- if (service.getById(args.id) === undefined) {
634
- throw new Error("memory not found");
635
- }
636
- const memory = service.setArchived(args.id, args.archived ?? true);
637
- return { memory: { id: memory.id, archived: memory.archived } };
638
- }
639
- }),
640
-
641
- // #471:政策轴——作用域级可逆闸门。与 memory_forget/memory_archive 的分工:
642
- // 那两个是事实轴的单条操作(改的是「这条记忆属于谁 / 还算不算数」,一条条来);
643
- // 本工具是政策轴的按作用域操作(改的是「这一路现在通不通」,跨会话存续、
644
- // 松开即原样回来,一条记忆行都不动)。判断指引:整条工作线要临时静音用本工具;
645
- // 单条记忆不该再被想起才用 memory_forget/memory_archive。
646
- defineTool({
647
- name: "set_scope_state",
648
- description:
649
- "Press or release the reversible scope gate for one scope (issue #471): while paused, that scope's memories stay stored and unchanged but are held back from injection and dream consolidation. " +
650
- "This is not deletion and not forgetting — release with state=active and everything comes back exactly as it was, which is why it is the right tool for temporarily silencing a whole work stream rather than editing memories one by one. " +
651
- "dimension is agent or workspace; scope_value is the label itself, or * for that dimension's global gate. " +
652
- "Both switches (scopeState.enabled/enforce) are off by default, so setting a state has no effect on injection until the user turns them on in the panel.",
653
- parameters: {
654
- dimension: { type: "string", required: true, description: "Scope dimension to press: \"agent\" or \"workspace\"" },
655
- scope_value: { type: "string", required: true, description: "The scope label, or \"*\" for that dimension's global gate" },
656
- state: { type: "string", required: true, description: "\"paused\" presses the gate, \"active\" releases it" },
657
- note: { type: "string", description: "Optional short reason, stored with the decision so the next reader knows why it was pressed" }
658
- },
659
- output: {
660
- schema: {
661
- type: "object",
662
- additionalProperties: false,
663
- properties: {
664
- scope: {
665
- type: "object",
666
- additionalProperties: false,
667
- properties: {
668
- dimension: { type: "string", required: true },
669
- scope_value: { type: "string", required: true },
670
- state: { type: "string", required: true },
671
- // 理由要能读回来:不带它,下次读的人只知道「按下过」却不知道为什么。
672
- // 这与库层 setScopeState 的 note 取舍是同一条理由——不带理由的重按
673
- // 不抹掉旧理由,正是为了让这里读得回来。可选:从没写过就没有。
674
- note: { type: "string" },
675
- decided_at: { type: "string", required: true }
676
- }
677
- }
678
- }
679
- },
680
- // 回执如实回显当前值(不是回显入参):同一个状态重复按下时 decided_at 保持
681
- // 首次值,回显它才看得出「这次没有真的改变什么」。
682
- render: (_args, value) =>
683
- TEXT_OUTPUT(
684
- `Scope ${value.scope.dimension}:${value.scope.scope_value} is now ${value.scope.state} (decided at ${value.scope.decided_at}).`
685
- )
686
- },
687
- async execute(args) {
688
- const dimension = normalizeScopeStateDimension(args.dimension);
689
- const scopeValue = normalizeScopeStateValue(args.scope_value);
690
- const state = normalizeScopeStateState(args.state);
691
- if (dimension === null) throw new Error("dimension must be \"agent\" or \"workspace\"");
692
- if (scopeValue === null) throw new Error("scope_value must be a non-empty label or \"*\"");
693
- if (state === null) throw new Error("state must be \"active\" or \"paused\"");
694
- const row = service.setScopeState({ dimension, scope_value: scopeValue, state, note: args.note });
695
- if (row === undefined) throw new Error("scope state could not be recorded");
696
- return {
697
- scope: {
698
- dimension: row.dimension,
699
- scope_value: row.scope_value,
700
- state: row.state,
701
- // 没写过理由时键整个不出现(而不是 note: undefined):output schema 是
702
- // 闭合的,DTO 矩阵会拿真实返回值过 validateJsonSchemaValue,留一个
703
- // 值为 undefined 的键等于留个空壳。
704
- ...(row.note === undefined ? {} : { note: row.note }),
705
- decided_at: row.decided_at
706
- }
707
- };
708
- }
709
- }),
710
-
711
- // #230(#164 设计稿评审线):document 型记忆注册——agent 产长文档的指针
712
- // 行铸造口。写入权分离:全文归 agent(管线对文件零读零写零改),库里只
713
- // 存摘要 + doc_path + evidence 三样;C2 比对去重、supersede 记账在
714
- // service.registerDocument(src/document.js)内完成。判断指引:调研报告/
715
- // 设计稿/长整理产物「存外档」用本工具;原子事实(偏好/决策/教训)仍走
716
- // memory_save;tag 与章节名建议用英文(跨语言稳定键),摘要正文可多语言。
717
- defineTool({
718
- name: "memory_register_document",
719
- description:
720
- "Register an agent-authored document (research report, design doc, long digest) into memory as a pointer row. " +
721
- "Write-ownership split: the full text stays agent-owned on disk — the pipeline never reads or rewrites it; the DB " +
722
- "stores only the summary + doc_path + evidence. Validates the file exists (absolute path, non-empty regular file), " +
723
- "intersects evidence with real memory ids (all-fabricated evidence is rejected; unknown ids are dropped and the row " +
724
- "is tagged evidence_degraded), and dedupes: re-registering the same path or title supersedes the old row (the old " +
725
- "file is never touched; content_history stays traceable), while a merely near-duplicate summary of a different " +
726
- "document row is rejected — update that row instead. On success the absorbed atomic evidence rows leave the active " +
727
- "face in the same transaction (recoverable, nothing deleted); constraint/preference rows and other " +
728
- "document/summary rows are never auto-archived, and keep_evidence_active: true opts out. Ids this same document " +
729
- "absorbed on an earlier version still count as its evidence, so re-registering a new version is not read as " +
730
- "fabricated evidence. Use for 'where is the conclusion doc for this project?' " +
731
- "lookups; atomic facts still go to memory_save.",
732
- parameters: {
733
- path: { type: "string", required: true, description: "Absolute path of the document file (~ is expanded); must already exist as a non-empty regular file. The full text stays agent-owned — this pipeline never touches it." },
734
- title: { type: "string", required: true, description: "Short unique title (English recommended: it is the cross-language stable dedupe/supersede key)" },
735
- summary: { type: "string", required: true, description: "One-paragraph summary stored in the DB and used for injection (any language)" },
736
- tags: { type: "array", items: { type: "string" }, description: "Optional tags (English recommended)" },
737
- importance: { type: "integer", description: "1-5 (default 3); the summary row injects at the next-priority tier within documentInjectBudget when importance >= threshold" },
738
- evidence: { type: "array", items: { type: "string" }, description: "Memory ids this document is grounded in (atomic facts, not other pointer rows); each is verified against the store — fabricated evidence is rejected, unknown/archived ids are dropped and the row is tagged evidence_degraded, except ids this same document absorbed on an earlier version, which stay its evidence. On success the absorbed atomic rows leave the active face unless keep_evidence_active is true." },
739
- keep_evidence_active: { type: "boolean", description: "Opt out of archiving the evidence rows absorbed by this document. Default false: after a successful registration the absorbed atomic rows leave the active face (recoverable, nothing deleted; constraint/preference rows and other document/summary rows are never auto-archived)." },
740
- source: { type: "string", description: "Optional provenance" },
741
- sensitivity: { type: "string", description: "Optional sensitivity label (free-form, e.g. personal). Part of the supersede matching key — same path/title with a different sensitivity stays a separate document." },
742
- agent_scope: { type: "string", description: "Optional explicit agent-scope declaration (issue #170): 'global' or '*' makes this document visible to every agent; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." },
743
- workspace_scope: { type: "string", description: "Optional explicit workspace-scope declaration (issue #170): 'global' or '*' makes this document visible in every workspace; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." }
744
- },
745
- output: {
746
- schema: {
747
- type: "object",
748
- additionalProperties: false,
749
- properties: {
750
- action: { type: "string", required: true, enum: ["created", "superseded"] },
751
- id: { type: "string", required: true },
752
- superseded_id: { type: "string" },
753
- evidence_kept: { type: "integer", required: true },
754
- evidence_dropped: { type: "integer", required: true },
755
- evidence_archived: { type: "integer", required: true },
756
- degraded: { type: "boolean", required: true }
757
- }
758
- },
759
- render: (_args, value) => {
760
- const sup = value.superseded_id ? ` (supersedes ${value.superseded_id})` : "";
761
- const ev = ` | evidence: ${value.evidence_kept} kept, ${value.evidence_dropped} dropped, ${value.evidence_archived} archived${value.degraded ? " [degraded]" : ""}`;
762
- return TEXT_OUTPUT(`document ${value.action}: ${value.id}${sup}${ev}`);
763
- }
764
- },
765
- async execute(args, exec) {
766
- // scope 标注与 memory_save 同款(#170):默认会话身份自动标注,显式
767
- // 参数逐维覆盖。校验/去重/supersede 全在 service.registerDocument。
768
- const scope = resolveSessionScope(exec);
769
- const autoStamping = config?.scopeEnabled === true;
770
- const agentLabel = args.agent_scope !== undefined
771
- ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
772
- : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
773
- const workspaceLabel = args.workspace_scope !== undefined
774
- ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
775
- : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
776
- // strictScope(#170 复核项 4 同款无存在性泄漏):他 scope 的 evidence id
777
- // 按「不存在」处理——注册器用全局 getById 求交,看不见的行在这里先标出,
778
- // 与 unknown/archived 同落 dropped,不进持久化 evidence(不得为跨 scope
779
- // id 建立引用)。
780
- const hiddenEvidence = [];
781
- if (config?.strictScope === true && scope && Array.isArray(args.evidence)) {
782
- for (const raw of args.evidence) {
783
- const id = String(raw ?? "").trim();
784
- if (!id) continue;
785
- const row = service.getById(id);
786
- if (row && !service.isVisibleInScope(row, scope)) hiddenEvidence.push(id);
787
- }
788
- }
789
- const result = await service.registerDocument({
790
- path: args.path,
791
- title: args.title,
792
- summary: args.summary,
793
- tags: args.tags ?? [],
794
- ...(args.importance !== undefined ? { importance: args.importance } : {}),
795
- evidence: args.evidence ?? [],
796
- source: args.source ?? "tool",
797
- ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
798
- ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
799
- ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {})
800
- }, {
801
- hiddenEvidenceIds: hiddenEvidence,
802
- // 默认开着归档(#275 拍板 5);agent 显式要保留活跃面时走 keep_evidence_active。
803
- archiveEvidence: args.keep_evidence_active !== true
804
- });
805
- return {
806
- action: result.action,
807
- id: result.memory.id,
808
- ...(result.superseded ? { superseded_id: result.superseded.id } : {}),
809
- evidence_kept: result.evidence_kept,
810
- evidence_dropped: result.evidence_dropped,
811
- evidence_archived: result.evidence_archived,
812
- degraded: result.degraded
813
- };
814
- }
815
- }),
816
-
817
- // #231 第二批:agent 主动整理接口的调用入口。引擎在 src/organize.js(PR #267),
818
- // 当时刻意「不进工具列表、不加独立 opt-in 开关——#249 到位时只差注册工具一步」,
819
- // 本条就是那一步。工具描述是 agent 侧唯一的协议说明,所以两步规则(apply 必须带
820
- // 真实 run_id、筛除=discard 不删任何东西、archive 可恢复)都写在这里:本体已经
821
- // 强制了这些,描述的作用是让第一次调用就成功,而不是靠被拒后试错。
822
- defineTool({
823
- name: "memory_organize",
824
- description:
825
- "Close out a stretch of work: compare candidate memories against the store first, then land only what you decide to keep. " +
826
- "Two steps through one tool. mode=dryRun (default) takes `candidates` and answers one verdict per candidate — exact / near / new — with the " +
827
- "matched row when there is one; it writes NO memories, only an audit receipt. mode=apply takes that report's `run_id` plus one decision per " +
828
- "candidate (save | discard) and may archive a row the report flagged as superseded (action=archive with that matched id). " +
829
- "apply is rejected without a real run_id, and a report can be applied only once: candidates that were never compared cannot be written, and " +
830
- "a row the report never matched cannot be archived. Discard keeps a candidate out and deletes nothing; archive is recoverable and never " +
831
- "physically removes a row. This tool exists only when organizeEnabled is on (off by default, and off in lightweight mode) — if it is missing " +
832
- "from your tool list the user has not enabled it. For a single write use memory_save instead.",
833
- parameters: {
834
- mode: { type: "string", description: '"dryRun" (default: compare and report, writes nothing) or "apply" (land the decisions of a reported dryRun)' },
835
- candidates: {
836
- type: "array",
837
- // 宿主强制的 JSON Schema 子集要求 object 显式声明 additionalProperties,
838
- // 所以候选字段在这里逐键写死:scope **来源**两列(*_scope_source)故意不给
839
- // ——那是可信调用层盖的章,不是模型可自选的内容。
840
- items: {
841
- type: "object",
842
- additionalProperties: false,
843
- properties: {
844
- type: { type: "string", required: true, description: "Memory type (project / preference / constraint / ... ; 'document' is rejected here — it is minted by memory_register_document)" },
845
- title: { type: "string", required: true, description: "Short stable title — part of the dedupe key (type + title + scope)" },
846
- content: { type: "string", required: true, description: "The body that would be stored" },
847
- importance: { type: "integer", description: "1-5 (default 3)" },
848
- tags: { type: "array", items: { type: "string" }, description: "Optional tags" },
849
- sensitivity: { type: "string", description: "Optional per-candidate sensitivity, overriding the payload-level default" },
850
- agent_scope: { type: "string", description: "Optional per-candidate agent scope, overriding the payload-level default" },
851
- workspace_scope: { type: "string", description: "Optional per-candidate workspace scope, overriding the payload-level default" }
852
- }
853
- },
854
- description: "dryRun only: candidates to compare (hard cap 50 per call — this is for closing out a work stretch, not bulk import). Candidates missing type/title/content, or of type document, come back in `skipped`."
855
- },
856
- run_id: { type: "string", description: "apply only: the run_id returned by the dryRun report you are acting on" },
857
- decisions: {
858
- type: "array",
859
- items: {
860
- type: "object",
861
- additionalProperties: false,
862
- properties: {
863
- action: { type: "string", required: true, enum: ["save", "discard", "archive"], description: 'save writes the candidate at `index` through the normal dedupe path (an existing row with the same key is merged, not duplicated); discard keeps it out and deletes nothing; archive hides the row at `id` (recoverable, and only legal for a row this report matched)' },
864
- index: { type: "integer", description: "save | discard: the candidate index from the dryRun report" },
865
- id: { type: "string", description: "archive: id of the matched row to archive" }
866
- }
867
- },
868
- description: "apply only: one entry per candidate you judged. Entries whose index the dryRun never accepted are reported in `skipped`."
869
- },
870
- sensitivity: { type: "string", description: "dryRun only: payload-level default sensitivity label for candidates that do not set their own (also the scope dimension the comparison runs within)" },
871
- agent_scope: { type: "string", description: "dryRun only: payload-level default agent scope for candidates that do not set their own. 'global' or '*' widens visibility to every agent; any other value narrows it. Defaults to this session's auto-stamped agent label when scope labeling is on (same rule as memory_save)." },
872
- workspace_scope: { type: "string", description: "dryRun only: payload-level default workspace scope for candidates that do not set their own. 'global' or '*' widens visibility to every workspace; any other value narrows it. Defaults to this session's auto-stamped workspace label when scope labeling is on." }
873
- },
874
- output: {
875
- schema: {
876
- type: "object",
877
- additionalProperties: false,
878
- properties: {
879
- // mode 是判别键:两种分支的返回键集不同,渲染与调用方都要靠它分流。
880
- mode: { type: "string", required: true, enum: ["dryRun", "apply"] },
881
- run_id: { type: "string", required: true },
882
- status: { type: "string", required: true },
883
- skipped: {
884
- type: "array",
885
- required: true,
886
- items: {
887
- type: "object",
888
- additionalProperties: false,
889
- properties: {
890
- index: { type: "integer", required: true },
891
- action: { type: "string" },
892
- error: { type: "string", required: true },
893
- ids: { type: "array", items: { type: "string" } }
894
- }
895
- }
896
- },
897
- // --- dryRun 分支 ---
898
- created_at: { type: "string" },
899
- counts: {
900
- type: "object",
901
- additionalProperties: false,
902
- properties: {
903
- total: { type: "integer", required: true },
904
- exact: { type: "integer", required: true },
905
- near: { type: "integer", required: true },
906
- new: { type: "integer", required: true },
907
- skipped: { type: "integer", required: true },
908
- truncated: { type: "integer", required: true }
909
- }
910
- },
911
- items: {
912
- type: "array",
913
- items: {
914
- type: "object",
915
- additionalProperties: false,
916
- properties: {
917
- index: { type: "integer", required: true },
918
- type: { type: "string", required: true },
919
- title: { type: "string", required: true },
920
- verdict: { type: "string", required: true, enum: ["exact", "near", "new"] },
921
- // match.sim 只在向量档命中时出现(exact 档无相似度可报);
922
- // 归档目标必须是报告里出现过的 id,所以这条链接就是 archive 的凭据。
923
- match: {
924
- type: "object",
925
- additionalProperties: false,
926
- properties: {
927
- id: { type: "string", required: true },
928
- title: { type: "string", required: true },
929
- sim: { type: "number" }
930
- }
931
- }
932
- }
933
- }
934
- },
935
- // --- apply 分支 ---
936
- dry_run_id: { type: "string" },
937
- saved: { type: "integer" },
938
- merged: { type: "integer" },
939
- discarded: { type: "integer" },
940
- archived: { type: "integer" },
941
- memory_ids: { type: "array", items: { type: "string" } },
942
- degraded: { type: "boolean" }
943
- }
944
- },
945
- render: (_args, value) => {
946
- if (value.mode === "apply") {
947
- return TEXT_OUTPUT(
948
- `organize applied (${value.run_id}, report ${value.dry_run_id}): ${value.saved} saved, ${value.merged} merged, ` +
949
- `${value.archived} archived, ${value.discarded} discarded${value.skipped.length ? ` | ${value.skipped.length} skipped` : ""}.`
950
- );
951
- }
952
- const c = value.counts;
953
- return TEXT_OUTPUT(
954
- `organize dryRun ${value.run_id}: ${c.total} compared — ${c.new} new, ${c.exact} exact, ${c.near} near` +
955
- `${c.skipped ? `, ${c.skipped} rejected` : ""}${c.truncated ? `, ${c.truncated} over the cap not compared` : ""}. ` +
956
- `Nothing was written; pass this run_id with your decisions to memory_organize mode=apply.`
957
- );
958
- }
959
- },
960
- async execute(args, exec) {
961
- const mode = String(args?.mode ?? "dryRun").trim();
962
- const scope = resolveSessionScope(exec);
963
- const autoStamping = config?.scopeEnabled === true;
964
- // 载荷级缺省与 memory_save 同源:显式参数盖 explicit 章,否则吃会话自动标注
965
- // 盖 auto 章。少了这一步,整理接口就成了第二条「写进库却不带 scope」的通道
966
- // ——candidates 会全部落在未标注(全局可见)那一档。
967
- const agentLabel = args.agent_scope !== undefined
968
- ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
969
- : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
970
- const workspaceLabel = args.workspace_scope !== undefined
971
- ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
972
- : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
973
- const hiddenIds = [];
974
- if (mode === "apply" && config?.strictScope === true && scope && Array.isArray(args.decisions)) {
975
- // #170 复核项 4 的口径延伸(register_document 的 hiddenEvidenceIds 同形):
976
- // 他 scope 的 explicit 行按「不存在」处理,由**可信调用层**算好传入,绝不
977
- // 取 payload 里的字段——那是调用方可自选的内容,不是授权。少了这一段,
978
- // archive 就成了第二条绕过 scope 治理的改库通道。
979
- for (const decision of args.decisions) {
980
- if (String(decision?.action ?? "").trim() !== "archive") continue;
981
- const id = String(decision?.id ?? "").trim();
982
- if (!id) continue;
983
- const row = service.getById(id);
984
- if (row && !service.isVisibleInScope(row, scope)) hiddenIds.push(id);
985
- }
986
- }
987
- const result = await service.organize(
988
- {
989
- mode,
990
- ...(args.candidates !== undefined ? { candidates: args.candidates } : {}),
991
- ...(args.run_id !== undefined ? { run_id: args.run_id } : {}),
992
- ...(args.decisions !== undefined ? { decisions: args.decisions } : {}),
993
- ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
994
- ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
995
- ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {})
996
- },
997
- { hiddenIds }
998
- );
999
- if (mode === "apply") {
1000
- return {
1001
- mode: "apply",
1002
- run_id: result.run_id,
1003
- dry_run_id: result.dry_run_id,
1004
- status: result.status,
1005
- saved: result.saved,
1006
- merged: result.merged,
1007
- discarded: result.discarded,
1008
- archived: result.archived,
1009
- memory_ids: result.memory_ids,
1010
- skipped: result.skipped,
1011
- degraded: result.degraded
1012
- };
1013
- }
1014
- // dryRun 的落点必须过一遍调用方的可见性。`agent_scope` / `workspace_scope`
1015
- // 是模型自己给的参数,而 `organize.dryRun` 的比对只看三列**值**(不看
1016
- // `*_scope_source`、不调 `isVisibleInScope`)——不过这一关,dryRun 就成了
1017
- // 「那一档有没有这个标题」的探测口:#170 复核项 4 给 memory_get / memory_delete
1018
- // 的口径是「不存在」,这里也按不存在说,落点一个键都不带。
1019
- // counts 跟着重算:留着引擎那份计数,`exact: 1` 配一个不带 match 的条目本身就是
1020
- // 存在性oracle,等于把泄露从 id 挪到计数器。审计行仍存原始落点(那是给操作者看的
1021
- // 证据面),apply 侧另有 hiddenIds 挡归档。
1022
- const visibleItems = result.items.map((item) => {
1023
- const match = item.match && visibleUnderStrictScope(service.getById(item.match.id), exec) ? item.match : null;
1024
- return {
1025
- index: item.index,
1026
- type: item.type,
1027
- title: item.title,
1028
- verdict: match ? item.verdict : "new",
1029
- ...(match ? { match: { id: match.id, title: match.title, ...(match.sim != null ? { sim: match.sim } : {}) } } : {})
1030
- };
1031
- });
1032
- const verdictCount = (verdict) => visibleItems.filter((i) => i.verdict === verdict).length;
1033
- return {
1034
- mode: "dryRun",
1035
- run_id: result.run_id,
1036
- created_at: result.created_at,
1037
- status: result.status,
1038
- counts: {
1039
- total: visibleItems.length,
1040
- exact: verdictCount("exact"),
1041
- near: verdictCount("near"),
1042
- new: verdictCount("new"),
1043
- skipped: result.counts.skipped,
1044
- truncated: result.counts.truncated
1045
- },
1046
- items: visibleItems,
1047
- skipped: result.skipped
1048
- };
1049
- }
1050
- }),
1051
-
1052
- // 运行时口子(issue #131 / PR-C)。
1053
- //
1054
- // 为什么要有这个工具:mneme 的取向是「本体保持完善但轻量;重的功能存在、默认不开、不被依赖」。
1055
- // 本地向量化就是那个重功能 —— 它需要额外一份运行时(解包后数百 MB)。面板上有按钮,但用户
1056
- // 可能根本不看面板;这时 agent 需要一个入口,能先查状态、把代价告诉用户,再按需取回。
1057
- //
1058
- // 关于「要不要直接 provision」:它会联网、可能传几十到上百 MB、耗时数分钟。所以工具描述里
1059
- // 明确要求先告知用户;只有在用户已经表示要本地向量化时才直接动手。
1060
- defineTool({
1061
- name: "memory_runtime",
1062
- description:
1063
- "Inspect or provision the LOCAL inference runtime that dsh-mneme's local (offline) embedding and rerank need: " +
1064
- "the transformers + onnxruntime dependency closure, hundreds of MB unpacked. It is deliberately NOT a default " +
1065
- "dependency — mneme's core stays lightweight and local vectorization is opt-in — so this tool is the hook that " +
1066
- "makes the heavy capability available on demand. Use action=status first: it is read-only and reports whether " +
1067
- "the runtime is ready plus what provisioning would cost. action=provision tries, in order: (1) adopting an " +
1068
- "existing copy from this profile's node_modules (no network; hardlinked when on the same volume, so no extra " +
1069
- "disk), (2) a configured local .tgz directory, (3) downloading from the npm registry against a pinned manifest, " +
1070
- "verifying every tarball's sha512. Provisioning can transfer tens to hundreds of MB and take minutes: unless " +
1071
- "the user has already asked for local vectorization, tell them that cost before calling it. action=verify loads " +
1072
- "the runtime and runs one real inference (strictly offline, so the model must already be cached).",
1073
- parameters: {
1074
- action: { type: "string", enum: ["status", "provision", "verify"], required: true, description: "status = read-only; provision = fetch/adopt the runtime; verify = run one real inference" },
1075
- overwrite: { type: "boolean", description: "provision only: replace an existing payload (use when repairing a broken one)" }
1076
- },
1077
- output: {
1078
- schema: {
1079
- type: "object",
1080
- additionalProperties: false,
1081
- properties: {
1082
- summary: { type: "string", required: true },
1083
- status: { type: "string", required: true },
1084
- cost: { type: "string", required: true },
1085
- strategy: { type: "string" },
1086
- payloadId: { type: "string" },
1087
- packages: { type: "integer" },
1088
- files: { type: "integer" },
1089
- bytes: { type: "integer" },
1090
- dimension: { type: "integer" },
1091
- reason: { type: "string" }
1092
- }
1093
- },
1094
- render: (_args, value) => TEXT_OUTPUT(value.summary)
1095
- },
1096
- async execute(args) {
1097
- const runtimeDir = config?.runtimeDir ?? "";
1098
- const manifest = loadRuntimeManifest();
1099
- const forPlatform = Array.isArray(manifest?.packages) ? manifest.packages.filter((pkg) => matchesPlatform(pkg, process.platform, process.arch)) : null;
1100
- const cost =
1101
- `Local vectorization needs an extra local inference runtime (transformers + onnxruntime closure, ` +
1102
- `hundreds of MB unpacked${forPlatform ? `, ${forPlatform.length} packages for this platform` : ""}). ` +
1103
- `It is not a default dependency: provisioning adopts an existing copy when possible, otherwise downloads it.`;
1104
-
1105
- if (args.action === "provision") {
1106
- const result = await provisionRuntime({
1107
- hostModulesDir: hostModulesDir(import.meta.url),
1108
- runtimeDir,
1109
- localTarballDir: config?.runtimeTarballDir ?? "",
1110
- mirror: config?.runtimeMirror ?? "",
1111
- overwrite: args.overwrite === true,
1112
- manifest
1113
- });
1114
- return {
1115
- summary: result.ok
1116
- ? `Runtime ${result.strategy === "download" ? "downloaded from npm" : "adopted from this machine"}: ` +
1117
- `${result.packages} packages / ${result.files} files. Local embedding can be used after a DSH reload.`
1118
- : `Could not provision the runtime: ${result.reason}`,
1119
- status: result.ok ? "available" : "failed",
1120
- cost,
1121
- strategy: result.strategy,
1122
- ...(result.payloadId ? { payloadId: result.payloadId } : {}),
1123
- ...(result.packages === undefined ? {} : { packages: result.packages }),
1124
- ...(result.files === undefined ? {} : { files: result.files }),
1125
- ...(result.bytes === undefined ? {} : { bytes: result.bytes }),
1126
- ...(result.reason ? { reason: result.reason } : {})
1127
- };
1128
- }
1129
-
1130
- if (args.action === "verify") {
1131
- const candidate = resolveRuntimeEntry({ runtimeDir: runtimeDir || undefined });
1132
- if (candidate === null) {
1133
- return { summary: "No usable runtime payload to verify.", status: "missing", cost };
1134
- }
1135
- // 验的必须是用户真实在用的那一份:缓存目录与嵌入模型都跟配置走。空目录交给 verify
1136
- // 自己补默认值(「空 = ~/.dsh/mneme/models」是配置与文档的约定,嵌入侧同一份解析);
1137
- // 模型不给会让 verify 恒探默认小模型,用户换了模型时这份结论就不是他实际使用的那份(#387)。
1138
- const report = await verifyPayload(candidate.dir, {
1139
- cacheDir: config?.embedModelCacheDir,
1140
- model: config?.localEmbedModel || undefined
1141
- });
1142
- return {
1143
- summary: report.ok
1144
- ? `Runtime verified: real inference succeeded (dim ${report.functional.dim}, ${report.functional.rows} rows, ` +
1145
- `${report.functional.elapsedMs}ms, offline). Integrity: ${report.integrity.status}.`
1146
- : `Runtime verification failed — structural: ${report.structural.ok}, functional: ${report.functional.ok} (${report.functional.reason}).`,
1147
- status: report.ok ? "verified" : "failed",
1148
- cost,
1149
- payloadId: candidate.payloadId,
1150
- ...(report.functional.dim ? { dimension: report.functional.dim } : {}),
1151
- ...(report.ok ? {} : { reason: report.functional.reason })
1152
- };
1153
- }
1154
-
1155
- // status:只读,且刻意不加载模型(那要几百毫秒且碰缓存)。报告要给到 agent 足够的信息去
1156
- // 决定「要不要打扰用户」。
1157
- const report = describeLocalRuntime({ runtimeDir: runtimeDir || defaultRuntimeDir() });
1158
- return {
1159
- summary:
1160
- `Local inference runtime: ${report.status}` +
1161
- (report.payloadId ? ` (${report.payloadId}, ${report.procedure ?? "?"}, ${report.materialize ?? "?"})` : "") +
1162
- `. ${report.status === "available" ? "Local embedding/rerank can be used." : "Local embedding is unavailable — " + (report.hint ?? "")}`,
1163
- status: report.status,
1164
- cost,
1165
- ...(report.payloadId ? { payloadId: report.payloadId } : {}),
1166
- ...(forPlatform ? { packages: forPlatform.length } : {}),
1167
- ...(report.reason ? { reason: report.reason } : {})
1168
- };
1169
- }
1170
- }),
1171
-
1172
- // --- chorography(仓库地志)只读工具(M1,spec §7)------------------
1173
- // 三个全只读(红线 3:写操作一个不注册——生成只走 dsh-mneme-choro CLI,
1174
- // 那是人按的按钮,不是模型的权利)。默认不在场:chorographyEnabled 关着时
1175
- // 走下面的 hiddenTools 闸,模型连名字都看不到(与 memory_organize 同款反向
1176
- // 语义)。执行器包 sessionGate 由注册循环统一做——仓库地志是文档不是会话
1177
- // 派生内容,无痕会话里被一并关掉是保守取向,可接受。
1178
- defineTool({
1179
- name: "choro_module_map",
1180
- description: "Show the chorography module map of a registered repository: module list (slug, title, file count, status) and cross-module dependency edges. Read-only. Use it to orient yourself in a codebase before reading pages; requires the user to have enabled chorography and generated the wiki (T0 skeleton).",
1181
- parameters: {
1182
- repo: { type: "string", description: "Repository id or display name; omit when exactly one repository is registered" }
1183
- },
1184
- output: {
1185
- schema: {
1186
- type: "object",
1187
- additionalProperties: false,
1188
- properties: {
1189
- repo: { type: "string", required: true },
1190
- modules: { type: "array", required: true, items: { type: "object", additionalProperties: true } },
1191
- edges: { type: "array", required: true, items: { type: "object", additionalProperties: true } }
1192
- }
1193
- },
1194
- render: (_args, value) => {
1195
- const mods = value.modules ?? [];
1196
- const edges = value.edges ?? [];
1197
- const lines = mods.map((m) =>
1198
- `- ${m.slug} — ${m.title}(${m.file_count} 文件${m.page_status ? `,页 ${m.page_status}` : ",无页"})`
1199
- );
1200
- for (const e of edges) lines.push(` ↳ ${e.from_slug} → ${e.to_slug} ×${e.weight}`);
1201
- return TEXT_OUTPUT(`${mods.length} modules, ${edges.length} edges:\n${lines.join("\n")}`);
1202
- }
1203
- },
1204
- async execute(args) {
1205
- const repo = resolveChoroRepo(args?.repo);
1206
- const { modules, edges } = choro.moduleMap(repo.id);
1207
- return { repo: repo.name, modules, edges };
1208
- }
1209
- }),
1210
-
1211
- defineTool({
1212
- name: "choro_read_page",
1213
- description: "Read one chorography wiki page (module skeleton: file list, entries, internal/external dependencies) of a registered repository by slug. Use choro_module_map first to learn the slugs. Read-only.",
1214
- parameters: {
1215
- slug: { type: "string", description: "Page slug as listed by choro_module_map" },
1216
- repo: { type: "string", description: "Repository id or display name; omit when exactly one repository is registered" }
1217
- },
1218
- output: {
1219
- schema: {
1220
- type: "object",
1221
- additionalProperties: false,
1222
- properties: {
1223
- slug: { type: "string", required: true },
1224
- content: { type: "string", required: true }
1225
- }
1226
- },
1227
- render: (_args, value) => TEXT_OUTPUT(value.content)
1228
- },
1229
- async execute(args) {
1230
- const repo = resolveChoroRepo(args?.repo);
1231
- const page = choro.readPage(repo.id, args?.slug);
1232
- if (!page) {
1233
- throw new Error(`Page ${JSON.stringify(args?.slug ?? "")} was not found. Use choro_module_map to list page slugs.`);
1234
- }
1235
- if (page.error === "page-missing") {
1236
- throw new Error(`Page ${JSON.stringify(page.slug)} is missing from disk (${page.relPath}). Check the local checkout or run ${CHORO_CLI ? `\`${CHORO_CLI}\`` : "`dsh-mneme-choro <repo> --apply`"} to rebuild it.`);
1237
- }
1238
- if (page.error) {
1239
- throw new Error(`Page ${JSON.stringify(page.slug)} could not be read (${page.relPath}). Check the local file and its permissions.`);
1240
- }
1241
- return { slug: page.slug, content: page.content };
1242
- }
1243
- }),
1244
-
1245
- defineTool({
1246
- name: "choro_search",
1247
- description: "Keyword search over a repository's chorography wiki pages. Returns matching sections with page slug, section title, line number and excerpt (case-insensitive substring; matches frontmatter too — sections let you tell metadata hits from body hits). Read-only.",
1248
- parameters: {
1249
- query: { type: "string", description: "Keyword substring to search for" },
1250
- repo: { type: "string", description: "Repository id or display name; omit when exactly one repository is registered" },
1251
- module: { type: "string", description: "Restrict to one module slug" },
1252
- limit: { type: "integer", description: "Max hits (default 20, cap 100)" }
1253
- },
1254
- output: {
1255
- schema: {
1256
- type: "object",
1257
- additionalProperties: false,
1258
- properties: {
1259
- hits: { type: "array", required: true, items: { type: "object", additionalProperties: true } },
1260
- unreadablePages: { type: "array", items: { type: "string" }, description: "Page slugs that could not be read during the search" }
1261
- }
1262
- },
1263
- render: (_args, value) => {
1264
- const { hits, unreadablePages } = value;
1265
- if (hits.length === 0) return TEXT_OUTPUT("0 hits.");
1266
- const lines = hits.map((hit) => `${hit.slug} · ${hit.section} · L${hit.line}: ${hit.excerpt}`);
1267
- if (unreadablePages?.length) lines.push("", incompleteChoroSearch(unreadablePages));
1268
- return TEXT_OUTPUT(lines.join("\n"));
1269
- }
1270
- },
1271
- async execute(args) {
1272
- const repo = resolveChoroRepo(args?.repo);
1273
- const unreadablePages = [];
1274
- const hits = choro.search(repo.id, args?.query, {
1275
- moduleSlug: args?.module ?? null,
1276
- limit: args?.limit,
1277
- onUnreadablePage: (slug) => unreadablePages.push(slug)
1278
- });
1279
- if (unreadablePages.length === 0) return { hits };
1280
- if (hits.length === 0) throw new Error(incompleteChoroSearch(unreadablePages));
1281
- return { hits, unreadablePages };
1282
- }
1283
- })
1284
- ];
1285
-
1286
- // Tool-exposure gate (v0.8.5): 跨会话记忆已自动注入,memory_search /
1287
- // memory_archive 在慢/轻量模型上是多余往返,面板开关可直接隐藏工具——
1288
- // 模型看不到就不会调,比在描述里劝它少调用更可靠。注意:live patch reload
1289
- // 下已注册的工具不会被宿主反注册,排除只对全新会话生效。
1290
- const hiddenTools = new Set();
1291
- if (config?.disableMemorySearch === true) hiddenTools.add("memory_search");
1292
- if (config?.disableMemoryArchive === true) hiddenTools.add("memory_archive");
1293
- // #231 第二批是**反向**语义:memory_organize 默认不在场,organizeEnabled 打开才
1294
- // 注册。仍走同一个闸门而不是在数组里条件展开——模型看不到就不会调,这比在描述里
1295
- // 劝它别用可靠(上面那段 v0.8.5 的定性对两个方向都成立)。
1296
- if (config?.organizeEnabled !== true) hiddenTools.add("memory_organize");
1297
- // chorography 三个只读工具(M1):默认不在场,chorographyEnabled 打开才注册。
1298
- // 与 organizeEnabled 同款反向语义;queries 未装配(null)时同样藏——「开了开关
1299
- // 但装配缺件」与「没开」对模型都是不可见,可区分性由面板路由的 409/503 负责。
1300
- if (config?.chorographyEnabled !== true || !choro) {
1301
- hiddenTools.add("choro_module_map");
1302
- hiddenTools.add("choro_read_page");
1303
- hiddenTools.add("choro_search");
1304
- }
1305
- // 知识库三工具(契约 §3.4):与 choro 同款反向语义。装配缺件(kb 为 null)与没开
1306
- // 对模型同样不可见——可区分性归路由层(503 / 409),模型侧不需要看见半个知识库。
1307
- if (config?.kbEnabled !== true || !kb) {
1308
- hiddenTools.add("kb_list_collections");
1309
- hiddenTools.add("kb_search");
1310
- hiddenTools.add("kb_read_doc");
1311
- }
1312
-
1313
- // 知识库工具定义在 kb/tools.js。**必须过 defineTool**:那里返回的是「describe 形状」
1314
- // (属性上的 required:true、output.schema 用 spec 写法),直接 ctx.tools.register
1315
- // 会被宿主的 JSON Schema 校验拒("required is not supported on type string")——
1316
- // 这是接线时踩到的真故障,不是可选加工。判定按 parameters.type==="object" 分:
1317
- // 已经是 JSON Schema 的说明调用方自己包过,再包一次会把 schema 转坏。
1318
- if (typeof kbToolDefinitions === "function") {
1319
- for (const def of kbToolDefinitions({ kb, cfg: config })) {
1320
- tools.push(def?.parameters?.type === "object" ? def : defineTool(def));
1321
- }
1322
- }
1323
-
1324
- for (const tool of tools) {
1325
- if (hiddenTools.has(tool.name)) {
1326
- ctx.logger?.info?.(`[dsh-mneme] tool "${tool.name}" hidden by config (disableMemorySearch/disableMemoryArchive/organizeEnabled)`);
1327
- continue;
1328
- }
1329
- if (registeredTools.has(tool.name)) {
1330
- ctx.logger?.warn?.(`[dsh-mneme] tool "${tool.name}" already registered, skipping duplicate`);
1331
- continue;
1332
- }
1333
- // #539:闸门包在**注册期**,而不是在 execute 内部各写一遍。已注册的执行器
1334
- // 不会被宿主反注册(同上面 disableMemorySearch 那段 v0.8.5 的定性),所以
1335
- // 包一层的意义在于:热重载后 registration.sessionGate 换成新实例,旧的执行器
1336
- // 也跟着读新的闸门,不会拿着过期 config 继续放行。
1337
- //
1338
- // 取会话走 sessionOf(exec) = exec.agent.session。ToolExecutionInput.agent 在
1339
- // 宿主类型里是**可选**的,PTC 内层派发可能压根不带 agent;这种调用会拿到
1340
- // null → isOff(null) 为 false → 放行。这是有意的:不认识调用者的工具调用
1341
- // 不能一律拒绝(那会把正常会话也打死),闸门只对「能证明自己是谁」的调用生效。
1342
- if (typeof tool.execute === "function") {
1343
- const execute = tool.execute.bind(tool);
1344
- tool.execute = async (args, exec) => {
1345
- if (registration.sessionGate?.isOff(sessionOf(exec))) {
1346
- throw new Error("dsh-mneme: memory tools are disabled for this incognito session");
1347
- }
1348
- return execute(args, exec);
1349
- };
1350
- }
1351
- registeredTools.add(tool.name);
1352
- ctx.tools.register(tool);
1353
- }
1354
-
1355
- return tools;
1356
- }
1
+ import { defineTool } from "@deepseek-ai/dsh-tools";
2
+ import { createScopeResolver, normalizeExplicitScope, sessionKeyOf, sessionOf } from "./scope.js";
3
+ import { describeLocalRuntime, resolveRuntimeEntry } from "./runtime/loader.js";
4
+ import { defaultRuntimeDir } from "./runtime/layout.js";
5
+ import { hostModulesDir, loadRuntimeManifest, provisionRuntime } from "./runtime/provision.js";
6
+ import { matchesPlatform } from "./runtime/closure.js";
7
+ import { verifyPayload } from "./runtime/verify.js";
8
+ import { TOOL_GUIDE, CONTINUITY_TOOL_RULE } from "./guide.js";
9
+ import { injectChildEnabled } from "./config.js";
10
+ import { normalizeScopeStateDimension, normalizeScopeStateValue, normalizeScopeStateState } from "./scope-state.js";
11
+ import { lastUserQuery } from "./inject.js";
12
+ import { hintDate } from "./date-hint.js";
13
+ // issue #607:工具报错里的 CLI 命令同样要给绝对路径入口——profile 装的插件没有
14
+ // 全局 shim,光写 `dsh-mneme-choro` 用户照抄只会 command not found。
15
+ import { choroCliCommandFrom } from "./wiki/cli-hint.js";
16
+ // 知识库三工具(契约 §3.4):定义住在 kb/tools.js,本文件只决定注册不注册。
17
+ import { kbToolDefinitions } from "./kb/tools.js";
18
+
19
+ const TEXT_OUTPUT = (text) => [{ type: "text", text }];
20
+ // 工具报错里的命令串:本文件在 src/ 与 lib/ 同一层(bin/ 的父级),模块加载时推导一次。
21
+ // 推导不出(源码树被裁剪)就返回 null,文案退回通用说法。
22
+ const CHORO_CLI = choroCliCommandFrom(import.meta.url, "<repo>");
23
+ const incompleteChoroSearch = (pages) =>
24
+ `Search was incomplete because these pages could not be read (${pages.join(", ")}). Check the local checkout and page permissions.`;
25
+ // Per-registry tool-name registry: guards against duplicate registration on
26
+ // live patch reload (DSH Desktop `patchReload: "live"`) where a plugin may be
27
+ // re-applied on the same tools registry without an intervening unregister.
28
+ const REGISTERED_TOOLS = new WeakMap();
29
+
30
+ // Wire shape emitted by service.toApiList: shared by memory_search and
31
+ // memory_list so their output schemas always declare every key the runtime
32
+ // value carries (additionalProperties: false would reject undeclared keys).
33
+ const MEMORY_ITEM_SCHEMA = {
34
+ type: "object",
35
+ additionalProperties: false,
36
+ properties: {
37
+ id: { type: "string", required: true },
38
+ type: { type: "string", required: true },
39
+ title: { type: "string", required: true },
40
+ content: { type: "string", required: true },
41
+ tags: { type: "array", items: { type: "string" } },
42
+ importance: { type: "integer", required: true },
43
+ source: { type: "string" },
44
+ // v0.8.0 A2:scope 标注与事件发生时间随行透出(未标注时缺省,可选属性)。
45
+ // v0.8.1 底座:scope 来源(auto/explicit)与决策时间随行透出(同样可选)。
46
+ agent_scope: { type: "string" },
47
+ workspace_scope: { type: "string" },
48
+ agent_scope_source: { type: "string" },
49
+ workspace_scope_source: { type: "string" },
50
+ scope_decided_at: { type: "string" },
51
+ sensitivity: { type: "string" },
52
+ occurred_at: { type: "string" },
53
+ // #230:document 指针行的文件定位——「全文按需读」的入口;普通行缺省。
54
+ doc_path: { type: "string" },
55
+ created_at: { type: "string", required: true },
56
+ updated_at: { type: "string", required: true }
57
+ }
58
+ };
59
+ // 导出供回归测试断言 memory_get 与共享 schema 同源(#184 防漂移护栏)。
60
+ export { MEMORY_ITEM_SCHEMA };
61
+
62
+ // v0.8.0 A2:occurred 时间窗参数 → store 过滤选项(list/count 同口径);
63
+ // 未传参返回空对象,既有调用方不受影响。(A3 复核:此处入参仅含 occurred 边界。)
64
+ function occurredWindow(args) {
65
+ const from = args?.occurred_from ?? null;
66
+ const to = args?.occurred_to ?? null;
67
+ return from !== null || to !== null ? { occurredFrom: from, occurredTo: to } : {};
68
+ }
69
+
70
+ // v0.8.0 A3:strictScope 硬过滤的 visibility 选项(store.list/count 同口径)。
71
+ // flag 关或会话 scope 未解析出(flag 关时解析器返回 null)→ 空对象不过滤;
72
+ // scope 为 {null,null}(匿名会话)时照传——store 侧 fail-closed 只放行未标注行。
73
+ function strictVisibility(config, scope) {
74
+ if (config?.strictScope !== true || !scope) return {};
75
+ return { visibility: { agentScope: scope.agent_scope, workspaceScope: scope.workspace_scope } };
76
+ }
77
+
78
+ // v0.8.0 A2:检索结果的 provenance 附加段——只在有标注时出现,未标注行渲染
79
+ // 与 A2 前逐字节一致。
80
+ const MEMORY_PROVENANCE = (m) => {
81
+ const parts = [];
82
+ if (m.occurred_at) parts.push(`occurred: ${m.occurred_at}`);
83
+ if (m.agent_scope || m.workspace_scope) {
84
+ parts.push(`scope: ${m.agent_scope ?? "global"} / ${m.workspace_scope ?? "global"}`);
85
+ }
86
+ if (m.sensitivity) parts.push(`sensitivity: ${m.sensitivity}`);
87
+ return parts.length ? ` | ${parts.join(" | ")}` : "";
88
+ };
89
+
90
+ // 条目年龄段(模型可见时间线索):created 是落库时间,与 updated 一起给,因为
91
+ // updated 会被巩固合并刷新(见 src/date-hint.js 顶部),单看 updated 会把旧条目
92
+ // 当新条目。带前导分隔符返回,created_at 是 schema 必填列,形状不对才整段消失
93
+ // (不留悬空 ` | `)。
94
+ const MEMORY_AGE = (m) => {
95
+ const created = hintDate(m?.created_at);
96
+ const updated = hintDate(m?.updated_at);
97
+ const parts = [];
98
+ if (created) parts.push(`created: ${created}`);
99
+ if (updated) parts.push(`updated: ${updated}`);
100
+ return parts.length ? ` | ${parts.join(" | ")}` : "";
101
+ };
102
+
103
+ // choro(M1):chorography 只读查询对象(createChoroQueries 产物)。缺省 null =
104
+ // 装配层没接(headless/测试),三个 choro_* 工具走 hiddenTools 闸根本不注册。
105
+ // 它与 service 刻意分开传——chorography 的所有权模型与记忆域相反(spec §3)。
106
+ // kb:知识库装配对象(createKb 产物);缺省 null = 宿主没装它,三个 kb 工具不注册。
107
+ export function createTools(ctx, service, config, embedder, sessionGate = null, choro = null, kb = null) {
108
+ const toolsRegistry = ctx.tools;
109
+ let registration = REGISTERED_TOOLS.get(toolsRegistry);
110
+ if (!registration) {
111
+ registration = { names: new Set(), sessionGate: null };
112
+ REGISTERED_TOOLS.set(toolsRegistry, registration);
113
+ }
114
+ registration.sessionGate = sessionGate;
115
+ const registeredTools = registration.names;
116
+ // v0.8.0 A1/A2(issue #17):会话 scope 解析(agentPreset + workspace 反查)。
117
+ // flag 关闭时恒返回 null——写入不标注,检索不加权,行为与 A1 前完全一致。
118
+ // logger 透传:registry 反查失败时 warnOnce 才有出口(否则静默降级无观测)。
119
+ const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
120
+ // 宿主在 render 前按成功 schema 校验返回值,仓库解析失败要走工具错误通道。
121
+ const resolveChoroRepo = (ref) => {
122
+ const row = choro.resolveRepo(ref);
123
+ if (!row) {
124
+ const reason = ref ? `Repository ${JSON.stringify(ref)} is not registered.` : "No repository is registered for chorography.";
125
+ throw new Error(`${reason} ${CHORO_CLI ? `Run \`${CHORO_CLI}\`` : "Run `dsh-mneme-choro <repo> --apply`"} to register a repository.`);
126
+ }
127
+ if (row.ambiguous) {
128
+ const choices = row.ambiguous.map(({ id, name }) => `${id} (${name})`).join(", ");
129
+ throw new Error(`More than one repository is registered. Pass one of these repository IDs (${choices}).`);
130
+ }
131
+ return row;
132
+ };
133
+ // #249 能力说明(injectGuidanceEnabled):开启时给「何时用」最有歧义的两个
134
+ // 工具补一句判断指引。工具描述常驻、不进每轮上下文,这个位子零注入成本;
135
+ // 关闭时描述逐字节不变,也不动其他工具的文案。
136
+ // 它是注入父开关的子项(#249 第二批):`autoInject` 关掉时这里同样不生效——
137
+ // 工具描述是这个子项唯一住在注入器之外的落点,不在闸门内就漏了。
138
+ // #249 N3 降级路径(continuityRescueEnabled):宿主若不提供可挂钩的压缩前时机,
139
+ // 双落点里的注入那一半就没有触发者,这时把规则交给 agent 自判(见 CONTINUITY_TOOL_RULE)。
140
+ // 与能力说明各自独立:任一开关关闭时描述逐字节不变。
141
+ // 本批不做宿主能力探测(没有可靠的探测口),所以子开关打开时这条规则常驻,与自动双落点并存。
142
+ const withToolGuide = (name, description) => {
143
+ let text = description;
144
+ if (injectChildEnabled(config, "injectGuidanceEnabled") && TOOL_GUIDE[name]) text += TOOL_GUIDE[name];
145
+ if (injectChildEnabled(config, "continuityRescueEnabled") && CONTINUITY_TOOL_RULE[name]) text += CONTINUITY_TOOL_RULE[name];
146
+ return text;
147
+ };
148
+
149
+ // 复核项 4(issue #170):strictScope 下他 scope(explicit)的行对工具侧按
150
+ // 「不存在」处理——update/delete 与 memory_get 同款无存在性泄漏。strictScope
151
+ // 关、或会话身份取不到(scope 为 null)时恒可见(与 get 的短路语义一致)。
152
+ const visibleUnderStrictScope = (memory, exec) => {
153
+ if (config?.strictScope !== true) return true;
154
+ const scope = resolveSessionScope(exec);
155
+ return !scope || service.isVisibleInScope(memory, scope);
156
+ };
157
+ // 在调用点以「展开恒为 undefined」的形态前置校验(抛错即中止写入)。
158
+ const assertVisibleForTool = (id, exec) => {
159
+ const memory = id ? service.getById(id) : undefined;
160
+ if (!visibleUnderStrictScope(memory, exec)) throw new Error("memory not found");
161
+ return undefined;
162
+ };
163
+ // delete 侧需要目标行本身判断存在性(不可见 = 视作不存在,不抛错)。
164
+ const visibleForTool = (id, exec) => {
165
+ const memory = id ? service.getById(id) : undefined;
166
+ return visibleUnderStrictScope(memory, exec) ? memory : undefined;
167
+ };
168
+ const tools = [
169
+ defineTool({
170
+ name: "memory_save",
171
+ description: withToolGuide(
172
+ "memory_save",
173
+ "Persist one memory entry for future sessions (user preferences, project state, decisions). " +
174
+ "Call this when the user states a durable preference, a project decision is made, or a lesson is learned. " +
175
+ "Merges into an existing entry of the same type when the title matches."
176
+ ),
177
+ parameters: {
178
+ // document 不在此列(#230):document 行只能经 memory_register_document
179
+ // 铸造(注册校验 + doc_path + evidence),防止 memory_save 造出无指针
180
+ // 无回链的伪行。
181
+ type: { type: "string", required: true, enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint"], description: "preference=user profile; project=project knowledge/state; decision=key decision; history=conversation summary; rejected_solution=rejected/abandoned implementation approach; pitfall=debugging lesson (symptom+root cause+fix); constraint=engineering constraint" },
182
+ title: { type: "string", required: true, description: "Short unique title" },
183
+ content: { type: "string", required: true, description: "Memory body" },
184
+ tags: { type: "array", items: { type: "string" }, description: "Optional tags" },
185
+ importance: { type: "integer", description: "1-5; >= threshold auto-injects into future sessions" },
186
+ source: { type: "string", description: "Optional provenance" },
187
+ sensitivity: { type: "string", description: "Optional sensitivity label (free-form, e.g. personal). Same-title entries with different sensitivity stay separate instead of merging." },
188
+ occurred_at: { type: "string", description: "Optional ISO-8601 instant the remembered event happened (differs from write time). Invalid values are ignored." },
189
+ agent_scope: { type: "string", description: "Optional explicit agent-scope declaration (issue #170): 'global' or '*' makes this memory visible to every agent; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." },
190
+ workspace_scope: { type: "string", description: "Optional explicit workspace-scope declaration: 'global' or '*' makes this memory visible in every workspace; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." }
191
+ },
192
+ output: {
193
+ schema: {
194
+ type: "object",
195
+ additionalProperties: false,
196
+ properties: {
197
+ action: { type: "string", required: true, enum: ["created", "merged", "denied"] },
198
+ // denied 时压根没有行可指,所以 id 缺省而不是空串:空串会让「写成功但
199
+ // id 为空」与「根本没写」在读回执时长得一样,与 #254 验收第 2 条
200
+ // (被拒写入可解释、不静默丢弃)相悖。
201
+ id: { type: "string", description: "Row id; absent when action=denied." },
202
+ reason: { type: "string", description: "Rejection reason when action=denied: blank | noise | sensitive." }
203
+ }
204
+ },
205
+ render: (_args, value) => TEXT_OUTPUT(value.action === "denied"
206
+ ? `memory save rejected (${value.reason ?? "denied"}): nothing was written`
207
+ : `memory ${value.action}: ${value.id}`)
208
+ },
209
+ async execute(args, exec) {
210
+ // scope 标注(v0.8.1 底座,issue #170):默认由会话身份解析(载体自动
211
+ // 标注,盖 auto 章);显式 agent_scope/workspace_scope 参数逐维覆盖并盖
212
+ // explicit 章。解析绝不抛错、取不到落 NULL。
213
+ // 复核项 2(#170):scopeEnabled 只门控「自动标注」分支——显式声明与
214
+ // 读取身份(search/list/get/注入经同一解析器)不受 flag 限制,否则
215
+ // strictScope 硬墙会被 flag 静默拆掉(fail-open)。
216
+ // (存储 NULL,由 source 列与「从未标注」区分)。非字符串参数在工具
217
+ // 入参 schema 层即被拒(type: "string")——脏值到不了归一化,无静默放宽。
218
+ const scope = resolveSessionScope(exec);
219
+ const autoStamping = config?.scopeEnabled === true;
220
+ const agentLabel = args.agent_scope !== undefined
221
+ ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
222
+ : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
223
+ const workspaceLabel = args.workspace_scope !== undefined
224
+ ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
225
+ : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
226
+ const result = service.saveWithDedupe({
227
+ // #254 写入准入的计数单位:会话键作为瞬时字段随写入传递(与 _mergeInto /
228
+ // _overwrite 同款约定,不落库)。缺会话身份的宿主返回 null = 这次写入不进
229
+ // 预算;系统写入(dream / summarize / organize)从不带这个字段。
230
+ _sessionKey: sessionKeyOf(exec),
231
+ type: args.type,
232
+ title: args.title,
233
+ content: args.content,
234
+ tags: args.tags ?? [],
235
+ importance: args.importance ?? 3,
236
+ source: args.source ?? "tool",
237
+ ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
238
+ ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {}),
239
+ ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
240
+ ...(args.occurred_at !== undefined ? { occurred_at: args.occurred_at } : {})
241
+ });
242
+ // #254 第 1 级硬拒:工具层是模型唯一能看到这次失败的地方,必须显式回一句
243
+ // 可行动的拒绝理由。静默返回成功会让模型以为记住了,然后永远不再重写。
244
+ if (result.action === "denied") return { action: "denied", reason: result.reason };
245
+ return { action: result.action, id: result.memory.id };
246
+ }
247
+ }),
248
+
249
+ defineTool({
250
+ name: "memory_search",
251
+ description: withToolGuide(
252
+ "memory_search",
253
+ "Search the cross-session memory store for past context (solved problems, user preferences, project decisions). IMPORTANT: relevant cross-session memories are already injected into your context every turn — only call this when the injected memory block does NOT contain what you need, or you need to look something specific up. Substring-matches title/content/tags, and augments results with semantic (vector) recall + optional rerank when an embeddings provider is configured. Returns matching entries with source and timestamps."
254
+ ),
255
+ // A2 检索接线:occurred 时间窗 + 会话 scope 加成(见 execute)。
256
+ parameters: {
257
+ query: { type: "string", required: true, description: "Search text; substring match over title/content/tags" },
258
+ limit: { type: "integer", description: "Max results (default 20)" },
259
+ mode: { type: "string", enum: ["auto", "keyword", "vector", "hybrid"], description: "auto (default) = keyword hits first + vector fill when enabled; keyword = text only; vector = semantic recall first (falls back to keyword); hybrid = vector leads, keyword fills remaining slots" },
260
+ semantic: { type: "boolean", description: "Shorthand: enable semantic (vector) recall (same as mode=vector when true)" },
261
+ rerank: { type: "boolean", description: "Run cross-encoder rerank over candidates when a local reranker is configured (default true)" },
262
+ occurred_from: { type: "string", description: "Optional ISO date/timestamp lower bound on when the remembered event happened (occurred_at, falling back to created_at). Date-only values are inclusive from that day's 00:00Z." },
263
+ occurred_to: { type: "string", description: "Optional ISO date/timestamp upper bound on occurred_at. Date-only values are inclusive through that day's 23:59:59.999Z." }
264
+ },
265
+ output: {
266
+ schema: {
267
+ type: "object",
268
+ additionalProperties: false,
269
+ properties: {
270
+ items: {
271
+ type: "array", required: true,
272
+ items: MEMORY_ITEM_SCHEMA
273
+ }
274
+ }
275
+ },
276
+ render: (_args, value) => {
277
+ const items = value.items ?? [];
278
+ if (items.length === 0) return TEXT_OUTPUT("No memory entries found.");
279
+ const body = items
280
+ .map((m, i) => {
281
+ const preview = (m.content ?? "").replace(/\s+/g, " ").trim();
282
+ const cut = preview.length > 200 ? `${preview.slice(0, 200)}…` : preview;
283
+ return `[${i + 1}] ${m.title}\n ID: ${m.id} | type: ${m.type} | importance: ${m.importance}${MEMORY_AGE(m)}${MEMORY_PROVENANCE(m)}\n ${cut}`;
284
+ })
285
+ .join("\n\n");
286
+ return TEXT_OUTPUT(`Found ${items.length} memory entr${items.length === 1 ? "y" : "ies"}:\n\n${body}`);
287
+ }
288
+ },
289
+ async execute(args, exec) {
290
+ const limit = args.limit ?? 20;
291
+ const mode = args.semantic === true && !args.mode ? "vector" : args.mode ?? "auto";
292
+ // v0.8.0 A2(issue #17):scope 检索加权 + occurred 时间窗的检索接线。
293
+ // flag 关闭或解析不出 scope 时为 null,检索行为与 A2 前一致。
294
+ const scope = resolveSessionScope(exec);
295
+ const occurredFrom = args.occurred_from ?? null;
296
+ const occurredTo = args.occurred_to ?? null;
297
+ const rows = await service.searchMemories(args.query, {
298
+ mode,
299
+ topK: limit,
300
+ useRerank: args.rerank !== false,
301
+ ...(scope ? { scope } : {}),
302
+ ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
303
+ });
304
+ return { items: service.toApiList(rows) };
305
+ }
306
+ }),
307
+
308
+ defineTool({
309
+ name: "memory_list",
310
+ description: "List memory entries by type, high-importance first, then newest, paginated. Set include_archived=true to also list archived (hidden) entries so they can be located and restored.",
311
+ parameters: {
312
+ type: { type: "string", enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint", "document"], description: "Filter by type; omit for all. 'document' (#230) = agent-registered document pointer rows" },
313
+ limit: { type: "integer", description: "Page size (default 50)" },
314
+ offset: { type: "integer", description: "Page offset (default 0)" },
315
+ include_archived: { type: "boolean", description: "Include archived (hidden) entries so they can be found and restored (default false)" },
316
+ occurred_from: { type: "string", description: "Optional ISO date/timestamp lower bound on when the remembered event happened (occurred_at, falling back to created_at). Date-only values are inclusive from that day's 00:00Z." },
317
+ occurred_to: { type: "string", description: "Optional ISO date/timestamp upper bound on occurred_at. Date-only values are inclusive through that day's 23:59:59.999Z." }
318
+ },
319
+ output: {
320
+ schema: {
321
+ type: "object",
322
+ additionalProperties: false,
323
+ properties: {
324
+ items: {
325
+ type: "array", required: true,
326
+ items: MEMORY_ITEM_SCHEMA
327
+ },
328
+ total: { type: "integer", required: true }
329
+ }
330
+ },
331
+ render: (_args, value) => {
332
+ const items = value.items ?? [];
333
+ if (items.length === 0) return TEXT_OUTPUT(`0 memory entries (of ${value.total}).`);
334
+ const body = items
335
+ .map((m, i) => `[${i + 1}] ${m.title} (type=${m.type}, importance=${m.importance})\n ID: ${m.id}${MEMORY_AGE(m)}${MEMORY_PROVENANCE(m)}`)
336
+ .join("\n\n");
337
+ return TEXT_OUTPUT(`${items.length} memory entries (of ${value.total}):\n\n${body}`);
338
+ }
339
+ },
340
+ async execute(args) {
341
+ const includeArchived = args.include_archived === true;
342
+ const rows = service.toApiList(service.list({
343
+ type: args.type,
344
+ limit: args.limit ?? 50,
345
+ offset: args.offset ?? 0,
346
+ includeArchived,
347
+ ...occurredWindow(args),
348
+ // A3:strict 开启时按会话 scope 硬过滤(宿主按 (args, runContext) 调用,
349
+ // 从 arguments 取第二参)。
350
+ ...strictVisibility(config, resolveSessionScope(arguments[1]))
351
+ }));
352
+ return { items: rows, total: service.count(args.type, { includeArchived, ...occurredWindow(args), ...strictVisibility(config, resolveSessionScope(arguments[1])) }) };
353
+ }
354
+ }),
355
+
356
+ defineTool({
357
+ name: "memory_get",
358
+ description: "Fetch one memory entry by ID and return its full content as text. Use after memory_list to read a specific entry.",
359
+ parameters: {
360
+ id: { type: "string", required: true, description: "Memory id" }
361
+ },
362
+ output: {
363
+ schema: {
364
+ type: "object",
365
+ additionalProperties: false,
366
+ properties: {
367
+ // 与 memory_search / memory_list 共用同一份 item schema——DTO 由
368
+ // toApiList 统一产出,内联副本曾漏掉 v0.8.1 的 scope 来源三键,
369
+ // 任何被标注过的行都过不了 in-process 校验(#184)。
370
+ memory: MEMORY_ITEM_SCHEMA
371
+ }
372
+ },
373
+ render: (_args, value) => {
374
+ const m = value.memory;
375
+ // #230:document 指针行把文件路径亮在首行——「全文按需读」从这里拿路径。
376
+ const doc = m.doc_path ? ` | doc: ${m.doc_path}` : "";
377
+ return TEXT_OUTPUT(`${m.title}\nID: ${m.id} | type: ${m.type} | importance: ${m.importance}${doc}${MEMORY_AGE(m)}${MEMORY_PROVENANCE(m)}\n\n${m.content}`);
378
+ }
379
+ },
380
+ async execute(args) {
381
+ const memory = service.getById(args.id);
382
+ if (memory === undefined) throw new Error("memory not found");
383
+ // v0.8.0 A3:strictScope 下他 scope 的行按不存在处理(无存在性泄漏)。
384
+ // 宿主注册表按 (args, runContext) 两参调用处理器,从 arguments 取第二参。
385
+ const runContext = arguments[1];
386
+ const scope = resolveSessionScope(runContext);
387
+ if (config.strictScope === true && scope && !service.isVisibleInScope(memory, scope)) {
388
+ throw new Error("memory not found");
389
+ }
390
+ return { memory: service.toApiList([memory])[0] };
391
+ }
392
+ }),
393
+
394
+ defineTool({
395
+ name: "memory_update",
396
+ description: "Modify an existing memory entry (title, content, type, tags, importance).",
397
+ parameters: {
398
+ id: { type: "string", required: true, description: "Memory id" },
399
+ title: { type: "string" },
400
+ content: { type: "string" },
401
+ // document 不在此列(#230):type 不许改入 document——既有 document 行
402
+ // 的摘要修复(只改 content/title)不受影响。
403
+ type: { type: "string", enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint"] },
404
+ tags: { type: "array", items: { type: "string" } },
405
+ importance: { type: "integer", description: "1-5" },
406
+ reason: { type: "string", description: "Optional context for the correction (what the user actually said/wanted), recorded for reflection" },
407
+ agent_scope: { type: "string", description: "Optional explicit agent-scope correction (issue #170): 'global' or '*' widens visibility to every agent; any other value narrows it to that label. Omit to keep the current agent scope. Recorded as an explicit scope decision (audited)." },
408
+ workspace_scope: { type: "string", description: "Optional explicit workspace-scope correction: 'global' or '*' widens visibility to every workspace; any other value narrows it to that label. Omit to keep the current workspace scope. Recorded as an explicit scope decision (audited)." }
409
+ },
410
+ output: {
411
+ schema: {
412
+ type: "object",
413
+ additionalProperties: false,
414
+ properties: {
415
+ memory: {
416
+ type: "object",
417
+ additionalProperties: false,
418
+ properties: {
419
+ id: { type: "string", required: true },
420
+ title: { type: "string", required: true },
421
+ content: { type: "string", required: true }
422
+ }
423
+ }
424
+ }
425
+ },
426
+ render: (_args, value) => TEXT_OUTPUT(`Updated memory ${value.memory.id}: ${value.memory.title}`)
427
+ },
428
+ async execute(args) {
429
+ // v0.9.0:失败表的 query 是「当时到底想干什么」唯一的落点,而 service
430
+ // 层看不到会话(它只认 ctx.query,见 src/service.js 的 saveFailure 注释)。
431
+ // 工具层是唯一同时握着改写动作与本轮会话的入口:没给 reason 就退回当轮用户
432
+ // 原话,取法与注入侧共用同一份实现(src/inject.js 的 lastUserQuery),不复制
433
+ // 第二份。两边都取不到时仍然写 NULL——空串会假装「有意图」,NULL 才说实话。
434
+ const exec = arguments[1];
435
+ const reason = typeof args.reason === "string" ? args.reason.trim() : "";
436
+ const query = reason || lastUserQuery(exec) || undefined;
437
+ const memory = service.update(args.id, {
438
+ title: args.title,
439
+ content: args.content,
440
+ type: args.type,
441
+ tags: args.tags,
442
+ importance: args.importance,
443
+ // 复核项 4(#170):strictScope 下他 scope 的行按「不存在」处理(与 get 对齐),
444
+ // 展开恒为 undefined,仅承担写入前校验。
445
+ ...(assertVisibleForTool(args.id, exec)),
446
+ ...(args.agent_scope !== undefined ? { agent_scope: args.agent_scope } : {}),
447
+ ...(args.workspace_scope !== undefined ? { workspace_scope: args.workspace_scope } : {})
448
+ }, { query });
449
+ return { memory: { id: memory.id, title: memory.title, content: memory.content } };
450
+ }
451
+ }),
452
+
453
+ defineTool({
454
+ name: "memory_delete",
455
+ description: "Permanently delete a memory entry.",
456
+ parameters: {
457
+ id: { type: "string", required: true }
458
+ },
459
+ output: {
460
+ schema: {
461
+ type: "object",
462
+ additionalProperties: false,
463
+ properties: { deleted: { type: "boolean", required: true } }
464
+ },
465
+ render: (_args, value) => TEXT_OUTPUT(value.deleted ? "Memory deleted." : "Memory not found.")
466
+ },
467
+ async execute(args) {
468
+ // 复核项 4(#170):不可见(explicit 他 scope)= 视作不存在,无存在性泄漏。
469
+ const target = visibleForTool(args.id, arguments[1]);
470
+ if (target) service.remove(args.id);
471
+ return { deleted: !!target };
472
+ }
473
+ }),
474
+
475
+ defineTool({
476
+ name: "memory_forget",
477
+ description:
478
+ "Stop a memory from being auto-injected and from appearing in searches and lists without deleting it. " +
479
+ "The entry stays in storage; pass forgotten: false to restore it. " +
480
+ "#532: suppression is per ROW - facts fused into the same entry leave visibility together. " +
481
+ "When the request targets one fact among several held by a row, inspect the row first (memory_get), " +
482
+ "split it with memory_update if needed, or say in your reply what else the suppression took down " +
483
+ "(docs/FORGET.md records the supersession gap behind this).",
484
+ parameters: {
485
+ id: { type: "string", required: true },
486
+ forgotten: { type: "boolean", description: "Suppress (true, default) or restore (false) the entry's visibility" }
487
+ },
488
+ output: {
489
+ schema: {
490
+ type: "object",
491
+ additionalProperties: false,
492
+ properties: {
493
+ memory: {
494
+ type: "object",
495
+ additionalProperties: false,
496
+ properties: {
497
+ id: { type: "string", required: true },
498
+ forgotten: { type: "boolean", required: true }
499
+ }
500
+ }
501
+ }
502
+ },
503
+ render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} injection ${value.memory.forgotten ? "suppressed" : "restored"}.`)
504
+ },
505
+ async execute(args) {
506
+ if (service.getById(args.id) === undefined) {
507
+ throw new Error("memory not found");
508
+ }
509
+ const memory = service.setForget(args.id, args.forgotten ?? true);
510
+ return { memory: { id: memory.id, forgotten: memory.forgotten } };
511
+ }
512
+ }),
513
+
514
+ // #249 第二批:显式 pin。注入侧原来靠「type 是 constraint/preference 就算
515
+ // 重要」推断谁该每轮置顶,那是隐含假设——库里 1100+ 条自动成了「每轮必进」
516
+ // 的候选而预算只有 5,真正该进去的反而排到二十名外。这个工具是那条推断的
517
+ // 唯一人工替代口:钉住 = 每轮注入块最前面那几条(受 pinnedInjectBudget 约束),
518
+ // 与类型无关(写得最全的那版常常是 pattern)。
519
+ //
520
+ // 三个边界写在这里:
521
+ // - 它不改记忆内容,也不改任何「记忆行」字段,只动 pinned_memories 这张关系
522
+ // 表,所以与 memory_forget / memory_archive / set_scope_state 都是**不同的轴**:
523
+ // 遗忘/归档/暂停作用域仍然优先——被它们处理掉的行就算钉着也不会注入,
524
+ // 回执里的 injectable 就是如实告诉我们这件事。
525
+ // - 存在性校验走 visibleForTool:strictScope 下 he scope 的行按「不存在」处理,
526
+ // 与 memory_delete 同款无存在性泄漏。
527
+ // - unpin 幂等:本来没钉也返回 pinned:false,不报错。
528
+ defineTool({
529
+ name: "memory_pin",
530
+ description:
531
+ "Pin a memory so it is injected at the top of the memory block every turn, regardless of its type or how it ranks against other memories. " +
532
+ "Use this only when the user explicitly says an entry must always be present (a hard rule, a standing preference); it is not a way to mark something as important — importance already affects ranking. " +
533
+ "Pinned entries still obey forgetting, archiving, the scope gate and the two injection switches: when autoInject is off the host registers no injector at all, and when pinnedInjectBudget is 0 the pin pool is off (its default). In either case a pinned entry is not injected through the pin channel, and the receipt reports injectable: false. The receipt answers \"is the pin channel open right now\", not \"is this memory kept out of every block\": a row reported false can still be picked up by the ordinary candidate path on its own merits. " +
534
+ "Pass unpin: true to release it. Pin order is first-pinned-first, so the oldest pin holds its slot when the budget is tight.",
535
+ parameters: {
536
+ id: { type: "string", required: true, description: "Memory id to pin (or unpin with unpin: true)" },
537
+ note: { type: "string", description: "Optional short reason to keep with the pin, so a later reader knows why it is pinned" },
538
+ unpin: { type: "boolean", description: "true releases the pin instead of setting it" }
539
+ },
540
+ output: {
541
+ schema: {
542
+ type: "object",
543
+ additionalProperties: false,
544
+ properties: {
545
+ memory_id: { type: "string", required: true },
546
+ pinned: { type: "boolean", required: true },
547
+ // 如实回显库现值,不是回显入参:重钉一条已有的 pin 不刷新 created_at,
548
+ // 回显它才看得出「这次其实没改变顺序」。
549
+ created_at: { type: "string" },
550
+ note: { type: "string" },
551
+ // 钉着 ≠ 会注入。遗忘/归档/暂停作用域/autoInject 关/pinnedInjectBudget=0
552
+ // 都优先于 pin,把这件事放进回执,而不是让用户以为钉完就一定出现在上下文里。
553
+ // 回执回答的是「pin 这条通道此刻开不开」:报 false 不等于这条记忆一定不在
554
+ // 上下文里——它仍可能凭自身重要性走常规候选路进块。
555
+ // autoInject 是这条通道的总闸:关着时宿主根本不注册注入器
556
+ // (src/index.js:617 的 if (cfg.autoInject)),pin 段自然也不执行。
557
+ injectable: { type: "boolean", required: true }
558
+ }
559
+ },
560
+ render: (_args, value) => {
561
+ if (!value.pinned) return TEXT_OUTPUT(`Memory ${value.memory_id} is no longer pinned.`);
562
+ const when = value.created_at ? ` (pinned at ${value.created_at})` : "";
563
+ const blocked = value.injectable
564
+ ? ""
565
+ : " The pin channel is closed right now (forgotten, archived, inside a paused scope, autoInject off, or pinnedInjectBudget is 0 — the pin pool is off by default), so it is not placed at the top of the block; the ordinary candidate path can still pick it up on its own merits.";
566
+ return TEXT_OUTPUT(`Memory ${value.memory_id} is pinned${when}.${blocked}`);
567
+ }
568
+ },
569
+ async execute(args) {
570
+ // 不可见(explicit 他 scope)= 视作不存在,无存在性泄漏。
571
+ const target = visibleForTool(args.id, arguments[1]);
572
+ if (target === undefined) throw new Error("memory not found");
573
+ // 钉着 ≠ 会注入。这里必须跟注入侧用同一个出口判定,否则回执照样会说谎:
574
+ // 暂停作用域的行在 enforce 档会被 scopeStateGate 剔掉,但 forgotten/archived
575
+ // 两个标志位对此一无所知——只算这两项,一条被暂停作用域挡住的行就会报
576
+ // injectable: true 而实际一条都没注入。filterPaused 正是那个出口(开关关、
577
+ // 或只开观察档时它原样返回,于是此时报 true 是对的:那种状态下本来就不拦)。
578
+ // #593 遗留缺口:pin 池整体由 pinnedInjectBudget 开关(src/service.js:1885 的
579
+ // pinnedBudget > 0 才读表选路),而它默认 0 = 关闭。只看遗忘/归档/暂停作用域时,
580
+ // 预算为 0 的一条回执照样报 injectable: true——钉住的动作确实成功了,但它此刻
581
+ // 一条都不会被注入,这正是「返回成功不等于生效」。预算 0 必须报 false。
582
+ //
583
+ // 同一类谎话的第二处(CodeRabbit 在 #596 指出):autoInject 才是 pin 通道的总闸
584
+ // ——关着时 src/index.js:617 根本不注册注入器,pin 段无从执行,而回执仍会报
585
+ // true。config schema 里它的默认值是 true(src/config.js:10),所以按「只有显式
586
+ // false 才算关」判:拿不到已填 defaults 的 config(测试直连 createTools)时不会
587
+ // 被误报成 false。
588
+ //
589
+ // 仍然没建模的:候选池侧的 type / importance / codingGate 闸(一条被钉的
590
+ // document 行同样进不了注入块)。那几道闸随候选池变化,回执不做猜测;
591
+ // 这里只回答「pin 这条通道此刻开不开」——报 false 也不等于这条记忆一定不在
592
+ // 上下文里,它仍可能凭自身重要性走常规候选路进块。
593
+ const pinnedBudget = Math.max(0, Math.min(5, Math.floor(config?.pinnedInjectBudget ?? 0)));
594
+ const autoInjectOn = config?.autoInject !== false;
595
+ const injectable =
596
+ autoInjectOn &&
597
+ pinnedBudget > 0 &&
598
+ !target.forgotten &&
599
+ !target.archived &&
600
+ service.filterPaused([target]).length > 0;
601
+ if (args.unpin === true) {
602
+ service.unpinMemory(target.id);
603
+ return { memory_id: target.id, pinned: false, injectable };
604
+ }
605
+ const row = service.pinMemory(target.id, { note: args.note });
606
+ if (row === undefined) throw new Error("pin could not be recorded");
607
+ return {
608
+ memory_id: row.memory_id,
609
+ pinned: true,
610
+ created_at: row.created_at,
611
+ // 没写过理由时键整个不出现(output schema 是闭合的,留 undefined 等于空壳)。
612
+ ...(row.note === undefined ? {} : { note: row.note }),
613
+ injectable
614
+ };
615
+ }
616
+ }),
617
+
618
+ defineTool({
619
+ name: "memory_archive",
620
+ description:
621
+ "Archive a memory (hide it from active lists, search, injection and dream consolidation) or restore it. " +
622
+ "Archived entries stay in storage and are recoverable: pass archived=false to restore, and use memory_list with " +
623
+ "include_archived=true to find archived entries. " +
624
+ "Only archive when the user asks, or an entry is clearly stale/no longer relevant — do not archive proactively mid-session to tidy up.",
625
+ parameters: {
626
+ id: { type: "string", required: true, description: "Memory id" },
627
+ archived: { type: "boolean", description: "Archive (true, default) or restore (false) the entry" }
628
+ },
629
+ output: {
630
+ schema: {
631
+ type: "object",
632
+ additionalProperties: false,
633
+ properties: {
634
+ memory: {
635
+ type: "object",
636
+ additionalProperties: false,
637
+ properties: {
638
+ id: { type: "string", required: true },
639
+ archived: { type: "boolean", required: true }
640
+ }
641
+ }
642
+ }
643
+ },
644
+ render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} ${value.memory.archived ? "archived" : "restored"}.`)
645
+ },
646
+ async execute(args) {
647
+ if (service.getById(args.id) === undefined) {
648
+ throw new Error("memory not found");
649
+ }
650
+ const memory = service.setArchived(args.id, args.archived ?? true);
651
+ return { memory: { id: memory.id, archived: memory.archived } };
652
+ }
653
+ }),
654
+
655
+ // #471:政策轴——作用域级可逆闸门。与 memory_forget/memory_archive 的分工:
656
+ // 那两个是事实轴的单条操作(改的是「这条记忆属于谁 / 还算不算数」,一条条来);
657
+ // 本工具是政策轴的按作用域操作(改的是「这一路现在通不通」,跨会话存续、
658
+ // 松开即原样回来,一条记忆行都不动)。判断指引:整条工作线要临时静音用本工具;
659
+ // 单条记忆不该再被想起才用 memory_forget/memory_archive。
660
+ defineTool({
661
+ name: "set_scope_state",
662
+ description:
663
+ "Press or release the reversible scope gate for one scope (issue #471): while paused, that scope's memories stay stored and unchanged but are held back from injection and dream consolidation. " +
664
+ "This is not deletion and not forgetting — release with state=active and everything comes back exactly as it was, which is why it is the right tool for temporarily silencing a whole work stream rather than editing memories one by one. " +
665
+ "dimension is agent or workspace; scope_value is the label itself, or * for that dimension's global gate. " +
666
+ "Both switches (scopeState.enabled/enforce) are off by default, so setting a state has no effect on injection until the user turns them on in the panel.",
667
+ parameters: {
668
+ dimension: { type: "string", required: true, description: "Scope dimension to press: \"agent\" or \"workspace\"" },
669
+ scope_value: { type: "string", required: true, description: "The scope label, or \"*\" for that dimension's global gate" },
670
+ state: { type: "string", required: true, description: "\"paused\" presses the gate, \"active\" releases it" },
671
+ note: { type: "string", description: "Optional short reason, stored with the decision so the next reader knows why it was pressed" }
672
+ },
673
+ output: {
674
+ schema: {
675
+ type: "object",
676
+ additionalProperties: false,
677
+ properties: {
678
+ scope: {
679
+ type: "object",
680
+ additionalProperties: false,
681
+ properties: {
682
+ dimension: { type: "string", required: true },
683
+ scope_value: { type: "string", required: true },
684
+ state: { type: "string", required: true },
685
+ // 理由要能读回来:不带它,下次读的人只知道「按下过」却不知道为什么。
686
+ // 这与库层 setScopeState 的 note 取舍是同一条理由——不带理由的重按
687
+ // 不抹掉旧理由,正是为了让这里读得回来。可选:从没写过就没有。
688
+ note: { type: "string" },
689
+ decided_at: { type: "string", required: true }
690
+ }
691
+ }
692
+ }
693
+ },
694
+ // 回执如实回显当前值(不是回显入参):同一个状态重复按下时 decided_at 保持
695
+ // 首次值,回显它才看得出「这次没有真的改变什么」。
696
+ render: (_args, value) =>
697
+ TEXT_OUTPUT(
698
+ `Scope ${value.scope.dimension}:${value.scope.scope_value} is now ${value.scope.state} (decided at ${value.scope.decided_at}).`
699
+ )
700
+ },
701
+ async execute(args) {
702
+ const dimension = normalizeScopeStateDimension(args.dimension);
703
+ const scopeValue = normalizeScopeStateValue(args.scope_value);
704
+ const state = normalizeScopeStateState(args.state);
705
+ if (dimension === null) throw new Error("dimension must be \"agent\" or \"workspace\"");
706
+ if (scopeValue === null) throw new Error("scope_value must be a non-empty label or \"*\"");
707
+ if (state === null) throw new Error("state must be \"active\" or \"paused\"");
708
+ const row = service.setScopeState({ dimension, scope_value: scopeValue, state, note: args.note });
709
+ if (row === undefined) throw new Error("scope state could not be recorded");
710
+ return {
711
+ scope: {
712
+ dimension: row.dimension,
713
+ scope_value: row.scope_value,
714
+ state: row.state,
715
+ // 没写过理由时键整个不出现(而不是 note: undefined):output schema 是
716
+ // 闭合的,DTO 矩阵会拿真实返回值过 validateJsonSchemaValue,留一个
717
+ // 值为 undefined 的键等于留个空壳。
718
+ ...(row.note === undefined ? {} : { note: row.note }),
719
+ decided_at: row.decided_at
720
+ }
721
+ };
722
+ }
723
+ }),
724
+
725
+ // #230(#164 设计稿评审线):document 型记忆注册——agent 产长文档的指针
726
+ // 行铸造口。写入权分离:全文归 agent(管线对文件零读零写零改),库里只
727
+ // 存摘要 + doc_path + evidence 三样;C2 比对去重、supersede 记账在
728
+ // service.registerDocument(src/document.js)内完成。判断指引:调研报告/
729
+ // 设计稿/长整理产物「存外档」用本工具;原子事实(偏好/决策/教训)仍走
730
+ // memory_save;tag 与章节名建议用英文(跨语言稳定键),摘要正文可多语言。
731
+ defineTool({
732
+ name: "memory_register_document",
733
+ description:
734
+ "Register an agent-authored document (research report, design doc, long digest) into memory as a pointer row. " +
735
+ "Write-ownership split: the full text stays agent-owned on disk — the pipeline never reads or rewrites it; the DB " +
736
+ "stores only the summary + doc_path + evidence. Validates the file exists (absolute path, non-empty regular file), " +
737
+ "intersects evidence with real memory ids (all-fabricated evidence is rejected; unknown ids are dropped and the row " +
738
+ "is tagged evidence_degraded), and dedupes: re-registering the same path or title supersedes the old row (the old " +
739
+ "file is never touched; content_history stays traceable), while a merely near-duplicate summary of a different " +
740
+ "document row is rejected — update that row instead. On success the absorbed atomic evidence rows leave the active " +
741
+ "face in the same transaction (recoverable, nothing deleted); constraint/preference rows and other " +
742
+ "document/summary rows are never auto-archived, and keep_evidence_active: true opts out. Ids this same document " +
743
+ "absorbed on an earlier version still count as its evidence, so re-registering a new version is not read as " +
744
+ "fabricated evidence. Use for 'where is the conclusion doc for this project?' " +
745
+ "lookups; atomic facts still go to memory_save.",
746
+ parameters: {
747
+ path: { type: "string", required: true, description: "Absolute path of the document file (~ is expanded); must already exist as a non-empty regular file. The full text stays agent-owned — this pipeline never touches it." },
748
+ title: { type: "string", required: true, description: "Short unique title (English recommended: it is the cross-language stable dedupe/supersede key)" },
749
+ summary: { type: "string", required: true, description: "One-paragraph summary stored in the DB and used for injection (any language)" },
750
+ tags: { type: "array", items: { type: "string" }, description: "Optional tags (English recommended)" },
751
+ importance: { type: "integer", description: "1-5 (default 3); the summary row injects at the next-priority tier within documentInjectBudget when importance >= threshold" },
752
+ evidence: { type: "array", items: { type: "string" }, description: "Memory ids this document is grounded in (atomic facts, not other pointer rows); each is verified against the store — fabricated evidence is rejected, unknown/archived ids are dropped and the row is tagged evidence_degraded, except ids this same document absorbed on an earlier version, which stay its evidence. On success the absorbed atomic rows leave the active face unless keep_evidence_active is true." },
753
+ keep_evidence_active: { type: "boolean", description: "Opt out of archiving the evidence rows absorbed by this document. Default false: after a successful registration the absorbed atomic rows leave the active face (recoverable, nothing deleted; constraint/preference rows and other document/summary rows are never auto-archived)." },
754
+ source: { type: "string", description: "Optional provenance" },
755
+ sensitivity: { type: "string", description: "Optional sensitivity label (free-form, e.g. personal). Part of the supersede matching key — same path/title with a different sensitivity stays a separate document." },
756
+ agent_scope: { type: "string", description: "Optional explicit agent-scope declaration (issue #170): 'global' or '*' makes this document visible to every agent; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." },
757
+ workspace_scope: { type: "string", description: "Optional explicit workspace-scope declaration (issue #170): 'global' or '*' makes this document visible in every workspace; any other value narrows it to that label. Overrides the automatic carrier label for this write; honored even when automatic scope labeling is disabled." }
758
+ },
759
+ output: {
760
+ schema: {
761
+ type: "object",
762
+ additionalProperties: false,
763
+ properties: {
764
+ action: { type: "string", required: true, enum: ["created", "superseded"] },
765
+ id: { type: "string", required: true },
766
+ superseded_id: { type: "string" },
767
+ evidence_kept: { type: "integer", required: true },
768
+ evidence_dropped: { type: "integer", required: true },
769
+ evidence_archived: { type: "integer", required: true },
770
+ degraded: { type: "boolean", required: true }
771
+ }
772
+ },
773
+ render: (_args, value) => {
774
+ const sup = value.superseded_id ? ` (supersedes ${value.superseded_id})` : "";
775
+ const ev = ` | evidence: ${value.evidence_kept} kept, ${value.evidence_dropped} dropped, ${value.evidence_archived} archived${value.degraded ? " [degraded]" : ""}`;
776
+ return TEXT_OUTPUT(`document ${value.action}: ${value.id}${sup}${ev}`);
777
+ }
778
+ },
779
+ async execute(args, exec) {
780
+ // scope 标注与 memory_save 同款(#170):默认会话身份自动标注,显式
781
+ // 参数逐维覆盖。校验/去重/supersede 全在 service.registerDocument。
782
+ const scope = resolveSessionScope(exec);
783
+ const autoStamping = config?.scopeEnabled === true;
784
+ const agentLabel = args.agent_scope !== undefined
785
+ ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
786
+ : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
787
+ const workspaceLabel = args.workspace_scope !== undefined
788
+ ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
789
+ : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
790
+ // strictScope(#170 复核项 4 同款无存在性泄漏):他 scope 的 evidence id
791
+ // 按「不存在」处理——注册器用全局 getById 求交,看不见的行在这里先标出,
792
+ // 与 unknown/archived 同落 dropped,不进持久化 evidence(不得为跨 scope
793
+ // id 建立引用)。
794
+ const hiddenEvidence = [];
795
+ if (config?.strictScope === true && scope && Array.isArray(args.evidence)) {
796
+ for (const raw of args.evidence) {
797
+ const id = String(raw ?? "").trim();
798
+ if (!id) continue;
799
+ const row = service.getById(id);
800
+ if (row && !service.isVisibleInScope(row, scope)) hiddenEvidence.push(id);
801
+ }
802
+ }
803
+ const result = await service.registerDocument({
804
+ path: args.path,
805
+ title: args.title,
806
+ summary: args.summary,
807
+ tags: args.tags ?? [],
808
+ ...(args.importance !== undefined ? { importance: args.importance } : {}),
809
+ evidence: args.evidence ?? [],
810
+ source: args.source ?? "tool",
811
+ ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
812
+ ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
813
+ ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {})
814
+ }, {
815
+ hiddenEvidenceIds: hiddenEvidence,
816
+ // 默认开着归档(#275 拍板 5);agent 显式要保留活跃面时走 keep_evidence_active。
817
+ archiveEvidence: args.keep_evidence_active !== true
818
+ });
819
+ return {
820
+ action: result.action,
821
+ id: result.memory.id,
822
+ ...(result.superseded ? { superseded_id: result.superseded.id } : {}),
823
+ evidence_kept: result.evidence_kept,
824
+ evidence_dropped: result.evidence_dropped,
825
+ evidence_archived: result.evidence_archived,
826
+ degraded: result.degraded
827
+ };
828
+ }
829
+ }),
830
+
831
+ // #231 第二批:agent 主动整理接口的调用入口。引擎在 src/organize.js(PR #267),
832
+ // 当时刻意「不进工具列表、不加独立 opt-in 开关——#249 到位时只差注册工具一步」,
833
+ // 本条就是那一步。工具描述是 agent 侧唯一的协议说明,所以两步规则(apply 必须带
834
+ // 真实 run_id、筛除=discard 不删任何东西、archive 可恢复)都写在这里:本体已经
835
+ // 强制了这些,描述的作用是让第一次调用就成功,而不是靠被拒后试错。
836
+ defineTool({
837
+ name: "memory_organize",
838
+ description:
839
+ "Close out a stretch of work: compare candidate memories against the store first, then land only what you decide to keep. " +
840
+ "Two steps through one tool. mode=dryRun (default) takes `candidates` and answers one verdict per candidate — exact / near / new — with the " +
841
+ "matched row when there is one; it writes NO memories, only an audit receipt. mode=apply takes that report's `run_id` plus one decision per " +
842
+ "candidate (save | discard) and may archive a row the report flagged as superseded (action=archive with that matched id). " +
843
+ "apply is rejected without a real run_id, and a report can be applied only once: candidates that were never compared cannot be written, and " +
844
+ "a row the report never matched cannot be archived. Discard keeps a candidate out and deletes nothing; archive is recoverable and never " +
845
+ "physically removes a row. This tool exists only when organizeEnabled is on (off by default, and off in lightweight mode) — if it is missing " +
846
+ "from your tool list the user has not enabled it. For a single write use memory_save instead.",
847
+ parameters: {
848
+ mode: { type: "string", description: '"dryRun" (default: compare and report, writes nothing) or "apply" (land the decisions of a reported dryRun)' },
849
+ candidates: {
850
+ type: "array",
851
+ // 宿主强制的 JSON Schema 子集要求 object 显式声明 additionalProperties,
852
+ // 所以候选字段在这里逐键写死:scope **来源**两列(*_scope_source)故意不给
853
+ // ——那是可信调用层盖的章,不是模型可自选的内容。
854
+ items: {
855
+ type: "object",
856
+ additionalProperties: false,
857
+ properties: {
858
+ type: { type: "string", required: true, description: "Memory type (project / preference / constraint / ... ; 'document' is rejected here — it is minted by memory_register_document)" },
859
+ title: { type: "string", required: true, description: "Short stable title — part of the dedupe key (type + title + scope)" },
860
+ content: { type: "string", required: true, description: "The body that would be stored" },
861
+ importance: { type: "integer", description: "1-5 (default 3)" },
862
+ tags: { type: "array", items: { type: "string" }, description: "Optional tags" },
863
+ sensitivity: { type: "string", description: "Optional per-candidate sensitivity, overriding the payload-level default" },
864
+ agent_scope: { type: "string", description: "Optional per-candidate agent scope, overriding the payload-level default" },
865
+ workspace_scope: { type: "string", description: "Optional per-candidate workspace scope, overriding the payload-level default" }
866
+ }
867
+ },
868
+ description: "dryRun only: candidates to compare (hard cap 50 per call — this is for closing out a work stretch, not bulk import). Candidates missing type/title/content, or of type document, come back in `skipped`."
869
+ },
870
+ run_id: { type: "string", description: "apply only: the run_id returned by the dryRun report you are acting on" },
871
+ decisions: {
872
+ type: "array",
873
+ items: {
874
+ type: "object",
875
+ additionalProperties: false,
876
+ properties: {
877
+ action: { type: "string", required: true, enum: ["save", "discard", "archive"], description: 'save writes the candidate at `index` through the normal dedupe path (an existing row with the same key is merged, not duplicated); discard keeps it out and deletes nothing; archive hides the row at `id` (recoverable, and only legal for a row this report matched)' },
878
+ index: { type: "integer", description: "save | discard: the candidate index from the dryRun report" },
879
+ id: { type: "string", description: "archive: id of the matched row to archive" }
880
+ }
881
+ },
882
+ description: "apply only: one entry per candidate you judged. Entries whose index the dryRun never accepted are reported in `skipped`."
883
+ },
884
+ sensitivity: { type: "string", description: "dryRun only: payload-level default sensitivity label for candidates that do not set their own (also the scope dimension the comparison runs within)" },
885
+ agent_scope: { type: "string", description: "dryRun only: payload-level default agent scope for candidates that do not set their own. 'global' or '*' widens visibility to every agent; any other value narrows it. Defaults to this session's auto-stamped agent label when scope labeling is on (same rule as memory_save)." },
886
+ workspace_scope: { type: "string", description: "dryRun only: payload-level default workspace scope for candidates that do not set their own. 'global' or '*' widens visibility to every workspace; any other value narrows it. Defaults to this session's auto-stamped workspace label when scope labeling is on." }
887
+ },
888
+ output: {
889
+ schema: {
890
+ type: "object",
891
+ additionalProperties: false,
892
+ properties: {
893
+ // mode 是判别键:两种分支的返回键集不同,渲染与调用方都要靠它分流。
894
+ mode: { type: "string", required: true, enum: ["dryRun", "apply"] },
895
+ run_id: { type: "string", required: true },
896
+ status: { type: "string", required: true },
897
+ skipped: {
898
+ type: "array",
899
+ required: true,
900
+ items: {
901
+ type: "object",
902
+ additionalProperties: false,
903
+ properties: {
904
+ index: { type: "integer", required: true },
905
+ action: { type: "string" },
906
+ error: { type: "string", required: true },
907
+ ids: { type: "array", items: { type: "string" } }
908
+ }
909
+ }
910
+ },
911
+ // --- dryRun 分支 ---
912
+ created_at: { type: "string" },
913
+ counts: {
914
+ type: "object",
915
+ additionalProperties: false,
916
+ properties: {
917
+ total: { type: "integer", required: true },
918
+ exact: { type: "integer", required: true },
919
+ near: { type: "integer", required: true },
920
+ new: { type: "integer", required: true },
921
+ skipped: { type: "integer", required: true },
922
+ truncated: { type: "integer", required: true }
923
+ }
924
+ },
925
+ items: {
926
+ type: "array",
927
+ items: {
928
+ type: "object",
929
+ additionalProperties: false,
930
+ properties: {
931
+ index: { type: "integer", required: true },
932
+ type: { type: "string", required: true },
933
+ title: { type: "string", required: true },
934
+ verdict: { type: "string", required: true, enum: ["exact", "near", "new"] },
935
+ // match.sim 只在向量档命中时出现(exact 档无相似度可报);
936
+ // 归档目标必须是报告里出现过的 id,所以这条链接就是 archive 的凭据。
937
+ match: {
938
+ type: "object",
939
+ additionalProperties: false,
940
+ properties: {
941
+ id: { type: "string", required: true },
942
+ title: { type: "string", required: true },
943
+ sim: { type: "number" }
944
+ }
945
+ }
946
+ }
947
+ }
948
+ },
949
+ // --- apply 分支 ---
950
+ dry_run_id: { type: "string" },
951
+ saved: { type: "integer" },
952
+ merged: { type: "integer" },
953
+ discarded: { type: "integer" },
954
+ archived: { type: "integer" },
955
+ memory_ids: { type: "array", items: { type: "string" } },
956
+ degraded: { type: "boolean" }
957
+ }
958
+ },
959
+ render: (_args, value) => {
960
+ if (value.mode === "apply") {
961
+ return TEXT_OUTPUT(
962
+ `organize applied (${value.run_id}, report ${value.dry_run_id}): ${value.saved} saved, ${value.merged} merged, ` +
963
+ `${value.archived} archived, ${value.discarded} discarded${value.skipped.length ? ` | ${value.skipped.length} skipped` : ""}.`
964
+ );
965
+ }
966
+ const c = value.counts;
967
+ return TEXT_OUTPUT(
968
+ `organize dryRun ${value.run_id}: ${c.total} compared — ${c.new} new, ${c.exact} exact, ${c.near} near` +
969
+ `${c.skipped ? `, ${c.skipped} rejected` : ""}${c.truncated ? `, ${c.truncated} over the cap not compared` : ""}. ` +
970
+ `Nothing was written; pass this run_id with your decisions to memory_organize mode=apply.`
971
+ );
972
+ }
973
+ },
974
+ async execute(args, exec) {
975
+ const mode = String(args?.mode ?? "dryRun").trim();
976
+ const scope = resolveSessionScope(exec);
977
+ const autoStamping = config?.scopeEnabled === true;
978
+ // 载荷级缺省与 memory_save 同源:显式参数盖 explicit 章,否则吃会话自动标注
979
+ // 盖 auto 章。少了这一步,整理接口就成了第二条「写进库却不带 scope」的通道
980
+ // ——candidates 会全部落在未标注(全局可见)那一档。
981
+ const agentLabel = args.agent_scope !== undefined
982
+ ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
983
+ : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
984
+ const workspaceLabel = args.workspace_scope !== undefined
985
+ ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
986
+ : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
987
+ const hiddenIds = [];
988
+ if (mode === "apply" && config?.strictScope === true && scope && Array.isArray(args.decisions)) {
989
+ // #170 复核项 4 的口径延伸(register_document 的 hiddenEvidenceIds 同形):
990
+ // 他 scope 的 explicit 行按「不存在」处理,由**可信调用层**算好传入,绝不
991
+ // 取 payload 里的字段——那是调用方可自选的内容,不是授权。少了这一段,
992
+ // archive 就成了第二条绕过 scope 治理的改库通道。
993
+ for (const decision of args.decisions) {
994
+ if (String(decision?.action ?? "").trim() !== "archive") continue;
995
+ const id = String(decision?.id ?? "").trim();
996
+ if (!id) continue;
997
+ const row = service.getById(id);
998
+ if (row && !service.isVisibleInScope(row, scope)) hiddenIds.push(id);
999
+ }
1000
+ }
1001
+ const result = await service.organize(
1002
+ {
1003
+ mode,
1004
+ ...(args.candidates !== undefined ? { candidates: args.candidates } : {}),
1005
+ ...(args.run_id !== undefined ? { run_id: args.run_id } : {}),
1006
+ ...(args.decisions !== undefined ? { decisions: args.decisions } : {}),
1007
+ ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
1008
+ ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
1009
+ ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {})
1010
+ },
1011
+ { hiddenIds }
1012
+ );
1013
+ if (mode === "apply") {
1014
+ return {
1015
+ mode: "apply",
1016
+ run_id: result.run_id,
1017
+ dry_run_id: result.dry_run_id,
1018
+ status: result.status,
1019
+ saved: result.saved,
1020
+ merged: result.merged,
1021
+ discarded: result.discarded,
1022
+ archived: result.archived,
1023
+ memory_ids: result.memory_ids,
1024
+ skipped: result.skipped,
1025
+ degraded: result.degraded
1026
+ };
1027
+ }
1028
+ // dryRun 的落点必须过一遍调用方的可见性。`agent_scope` / `workspace_scope`
1029
+ // 是模型自己给的参数,而 `organize.dryRun` 的比对只看三列**值**(不看
1030
+ // `*_scope_source`、不调 `isVisibleInScope`)——不过这一关,dryRun 就成了
1031
+ // 「那一档有没有这个标题」的探测口:#170 复核项 4 给 memory_get / memory_delete
1032
+ // 的口径是「不存在」,这里也按不存在说,落点一个键都不带。
1033
+ // counts 跟着重算:留着引擎那份计数,`exact: 1` 配一个不带 match 的条目本身就是
1034
+ // 存在性oracle,等于把泄露从 id 挪到计数器。审计行仍存原始落点(那是给操作者看的
1035
+ // 证据面),apply 侧另有 hiddenIds 挡归档。
1036
+ const visibleItems = result.items.map((item) => {
1037
+ const match = item.match && visibleUnderStrictScope(service.getById(item.match.id), exec) ? item.match : null;
1038
+ return {
1039
+ index: item.index,
1040
+ type: item.type,
1041
+ title: item.title,
1042
+ verdict: match ? item.verdict : "new",
1043
+ ...(match ? { match: { id: match.id, title: match.title, ...(match.sim != null ? { sim: match.sim } : {}) } } : {})
1044
+ };
1045
+ });
1046
+ const verdictCount = (verdict) => visibleItems.filter((i) => i.verdict === verdict).length;
1047
+ return {
1048
+ mode: "dryRun",
1049
+ run_id: result.run_id,
1050
+ created_at: result.created_at,
1051
+ status: result.status,
1052
+ counts: {
1053
+ total: visibleItems.length,
1054
+ exact: verdictCount("exact"),
1055
+ near: verdictCount("near"),
1056
+ new: verdictCount("new"),
1057
+ skipped: result.counts.skipped,
1058
+ truncated: result.counts.truncated
1059
+ },
1060
+ items: visibleItems,
1061
+ skipped: result.skipped
1062
+ };
1063
+ }
1064
+ }),
1065
+
1066
+ // 运行时口子(issue #131 / PR-C)。
1067
+ //
1068
+ // 为什么要有这个工具:mneme 的取向是「本体保持完善但轻量;重的功能存在、默认不开、不被依赖」。
1069
+ // 本地向量化就是那个重功能 —— 它需要额外一份运行时(解包后数百 MB)。面板上有按钮,但用户
1070
+ // 可能根本不看面板;这时 agent 需要一个入口,能先查状态、把代价告诉用户,再按需取回。
1071
+ //
1072
+ // 关于「要不要直接 provision」:它会联网、可能传几十到上百 MB、耗时数分钟。所以工具描述里
1073
+ // 明确要求先告知用户;只有在用户已经表示要本地向量化时才直接动手。
1074
+ defineTool({
1075
+ name: "memory_runtime",
1076
+ description:
1077
+ "Inspect or provision the LOCAL inference runtime that dsh-mneme's local (offline) embedding and rerank need: " +
1078
+ "the transformers + onnxruntime dependency closure, hundreds of MB unpacked. It is deliberately NOT a default " +
1079
+ "dependency — mneme's core stays lightweight and local vectorization is opt-in — so this tool is the hook that " +
1080
+ "makes the heavy capability available on demand. Use action=status first: it is read-only and reports whether " +
1081
+ "the runtime is ready plus what provisioning would cost. action=provision tries, in order: (1) adopting an " +
1082
+ "existing copy from this profile's node_modules (no network; hardlinked when on the same volume, so no extra " +
1083
+ "disk), (2) a configured local .tgz directory, (3) downloading from the npm registry against a pinned manifest, " +
1084
+ "verifying every tarball's sha512. Provisioning can transfer tens to hundreds of MB and take minutes: unless " +
1085
+ "the user has already asked for local vectorization, tell them that cost before calling it. action=verify loads " +
1086
+ "the runtime and runs one real inference (strictly offline, so the model must already be cached).",
1087
+ parameters: {
1088
+ action: { type: "string", enum: ["status", "provision", "verify"], required: true, description: "status = read-only; provision = fetch/adopt the runtime; verify = run one real inference" },
1089
+ overwrite: { type: "boolean", description: "provision only: replace an existing payload (use when repairing a broken one)" }
1090
+ },
1091
+ output: {
1092
+ schema: {
1093
+ type: "object",
1094
+ additionalProperties: false,
1095
+ properties: {
1096
+ summary: { type: "string", required: true },
1097
+ status: { type: "string", required: true },
1098
+ cost: { type: "string", required: true },
1099
+ strategy: { type: "string" },
1100
+ payloadId: { type: "string" },
1101
+ packages: { type: "integer" },
1102
+ files: { type: "integer" },
1103
+ bytes: { type: "integer" },
1104
+ dimension: { type: "integer" },
1105
+ reason: { type: "string" }
1106
+ }
1107
+ },
1108
+ render: (_args, value) => TEXT_OUTPUT(value.summary)
1109
+ },
1110
+ async execute(args) {
1111
+ const runtimeDir = config?.runtimeDir ?? "";
1112
+ const manifest = loadRuntimeManifest();
1113
+ const forPlatform = Array.isArray(manifest?.packages) ? manifest.packages.filter((pkg) => matchesPlatform(pkg, process.platform, process.arch)) : null;
1114
+ const cost =
1115
+ `Local vectorization needs an extra local inference runtime (transformers + onnxruntime closure, ` +
1116
+ `hundreds of MB unpacked${forPlatform ? `, ${forPlatform.length} packages for this platform` : ""}). ` +
1117
+ `It is not a default dependency: provisioning adopts an existing copy when possible, otherwise downloads it.`;
1118
+
1119
+ if (args.action === "provision") {
1120
+ const result = await provisionRuntime({
1121
+ hostModulesDir: hostModulesDir(import.meta.url),
1122
+ runtimeDir,
1123
+ localTarballDir: config?.runtimeTarballDir ?? "",
1124
+ mirror: config?.runtimeMirror ?? "",
1125
+ overwrite: args.overwrite === true,
1126
+ manifest
1127
+ });
1128
+ return {
1129
+ summary: result.ok
1130
+ ? `Runtime ${result.strategy === "download" ? "downloaded from npm" : "adopted from this machine"}: ` +
1131
+ `${result.packages} packages / ${result.files} files. Local embedding can be used after a DSH reload.`
1132
+ : `Could not provision the runtime: ${result.reason}`,
1133
+ status: result.ok ? "available" : "failed",
1134
+ cost,
1135
+ strategy: result.strategy,
1136
+ ...(result.payloadId ? { payloadId: result.payloadId } : {}),
1137
+ ...(result.packages === undefined ? {} : { packages: result.packages }),
1138
+ ...(result.files === undefined ? {} : { files: result.files }),
1139
+ ...(result.bytes === undefined ? {} : { bytes: result.bytes }),
1140
+ ...(result.reason ? { reason: result.reason } : {})
1141
+ };
1142
+ }
1143
+
1144
+ if (args.action === "verify") {
1145
+ const candidate = resolveRuntimeEntry({ runtimeDir: runtimeDir || undefined });
1146
+ if (candidate === null) {
1147
+ return { summary: "No usable runtime payload to verify.", status: "missing", cost };
1148
+ }
1149
+ // 验的必须是用户真实在用的那一份:缓存目录与嵌入模型都跟配置走。空目录交给 verify
1150
+ // 自己补默认值(「空 = ~/.dsh/mneme/models」是配置与文档的约定,嵌入侧同一份解析);
1151
+ // 模型不给会让 verify 恒探默认小模型,用户换了模型时这份结论就不是他实际使用的那份(#387)。
1152
+ const report = await verifyPayload(candidate.dir, {
1153
+ cacheDir: config?.embedModelCacheDir,
1154
+ model: config?.localEmbedModel || undefined
1155
+ });
1156
+ return {
1157
+ summary: report.ok
1158
+ ? `Runtime verified: real inference succeeded (dim ${report.functional.dim}, ${report.functional.rows} rows, ` +
1159
+ `${report.functional.elapsedMs}ms, offline). Integrity: ${report.integrity.status}.`
1160
+ : `Runtime verification failed — structural: ${report.structural.ok}, functional: ${report.functional.ok} (${report.functional.reason}).`,
1161
+ status: report.ok ? "verified" : "failed",
1162
+ cost,
1163
+ payloadId: candidate.payloadId,
1164
+ ...(report.functional.dim ? { dimension: report.functional.dim } : {}),
1165
+ ...(report.ok ? {} : { reason: report.functional.reason })
1166
+ };
1167
+ }
1168
+
1169
+ // status:只读,且刻意不加载模型(那要几百毫秒且碰缓存)。报告要给到 agent 足够的信息去
1170
+ // 决定「要不要打扰用户」。
1171
+ const report = describeLocalRuntime({ runtimeDir: runtimeDir || defaultRuntimeDir() });
1172
+ return {
1173
+ summary:
1174
+ `Local inference runtime: ${report.status}` +
1175
+ (report.payloadId ? ` (${report.payloadId}, ${report.procedure ?? "?"}, ${report.materialize ?? "?"})` : "") +
1176
+ `. ${report.status === "available" ? "Local embedding/rerank can be used." : "Local embedding is unavailable — " + (report.hint ?? "")}`,
1177
+ status: report.status,
1178
+ cost,
1179
+ ...(report.payloadId ? { payloadId: report.payloadId } : {}),
1180
+ ...(forPlatform ? { packages: forPlatform.length } : {}),
1181
+ ...(report.reason ? { reason: report.reason } : {})
1182
+ };
1183
+ }
1184
+ }),
1185
+
1186
+ // --- chorography(仓库地志)只读工具(M1,spec §7)------------------
1187
+ // 三个全只读(红线 3:写操作一个不注册——生成只走 dsh-mneme-choro CLI,
1188
+ // 那是人按的按钮,不是模型的权利)。默认不在场:chorographyEnabled 关着时
1189
+ // 走下面的 hiddenTools 闸,模型连名字都看不到(与 memory_organize 同款反向
1190
+ // 语义)。执行器包 sessionGate 由注册循环统一做——仓库地志是文档不是会话
1191
+ // 派生内容,无痕会话里被一并关掉是保守取向,可接受。
1192
+ defineTool({
1193
+ name: "choro_module_map",
1194
+ description: "Show the chorography module map of a registered repository: module list (slug, title, file count, status) and cross-module dependency edges. Read-only. Use it to orient yourself in a codebase before reading pages; requires the user to have enabled chorography and generated the wiki (T0 skeleton).",
1195
+ parameters: {
1196
+ repo: { type: "string", description: "Repository id or display name; omit when exactly one repository is registered" }
1197
+ },
1198
+ output: {
1199
+ schema: {
1200
+ type: "object",
1201
+ additionalProperties: false,
1202
+ properties: {
1203
+ repo: { type: "string", required: true },
1204
+ modules: { type: "array", required: true, items: { type: "object", additionalProperties: true } },
1205
+ edges: { type: "array", required: true, items: { type: "object", additionalProperties: true } }
1206
+ }
1207
+ },
1208
+ render: (_args, value) => {
1209
+ const mods = value.modules ?? [];
1210
+ const edges = value.edges ?? [];
1211
+ const lines = mods.map((m) =>
1212
+ `- ${m.slug} — ${m.title}(${m.file_count} 文件${m.page_status ? `,页 ${m.page_status}` : ",无页"})`
1213
+ );
1214
+ for (const e of edges) lines.push(` ↳ ${e.from_slug} → ${e.to_slug} ×${e.weight}`);
1215
+ return TEXT_OUTPUT(`${mods.length} modules, ${edges.length} edges:\n${lines.join("\n")}`);
1216
+ }
1217
+ },
1218
+ async execute(args) {
1219
+ const repo = resolveChoroRepo(args?.repo);
1220
+ const { modules, edges } = choro.moduleMap(repo.id);
1221
+ return { repo: repo.name, modules, edges };
1222
+ }
1223
+ }),
1224
+
1225
+ defineTool({
1226
+ name: "choro_read_page",
1227
+ description: "Read one chorography wiki page (module skeleton: file list, entries, internal/external dependencies) of a registered repository by slug. Use choro_module_map first to learn the slugs. Read-only.",
1228
+ parameters: {
1229
+ slug: { type: "string", description: "Page slug as listed by choro_module_map" },
1230
+ repo: { type: "string", description: "Repository id or display name; omit when exactly one repository is registered" }
1231
+ },
1232
+ output: {
1233
+ schema: {
1234
+ type: "object",
1235
+ additionalProperties: false,
1236
+ properties: {
1237
+ slug: { type: "string", required: true },
1238
+ content: { type: "string", required: true }
1239
+ }
1240
+ },
1241
+ render: (_args, value) => TEXT_OUTPUT(value.content)
1242
+ },
1243
+ async execute(args) {
1244
+ const repo = resolveChoroRepo(args?.repo);
1245
+ const page = choro.readPage(repo.id, args?.slug);
1246
+ if (!page) {
1247
+ throw new Error(`Page ${JSON.stringify(args?.slug ?? "")} was not found. Use choro_module_map to list page slugs.`);
1248
+ }
1249
+ if (page.error === "page-missing") {
1250
+ throw new Error(`Page ${JSON.stringify(page.slug)} is missing from disk (${page.relPath}). Check the local checkout or run ${CHORO_CLI ? `\`${CHORO_CLI}\`` : "`dsh-mneme-choro <repo> --apply`"} to rebuild it.`);
1251
+ }
1252
+ if (page.error) {
1253
+ throw new Error(`Page ${JSON.stringify(page.slug)} could not be read (${page.relPath}). Check the local file and its permissions.`);
1254
+ }
1255
+ return { slug: page.slug, content: page.content };
1256
+ }
1257
+ }),
1258
+
1259
+ defineTool({
1260
+ name: "choro_search",
1261
+ description: "Keyword search over a repository's chorography wiki pages. Returns matching sections with page slug, section title, line number and excerpt (case-insensitive substring; matches frontmatter too — sections let you tell metadata hits from body hits). Read-only.",
1262
+ parameters: {
1263
+ query: { type: "string", description: "Keyword substring to search for" },
1264
+ repo: { type: "string", description: "Repository id or display name; omit when exactly one repository is registered" },
1265
+ module: { type: "string", description: "Restrict to one module slug" },
1266
+ limit: { type: "integer", description: "Max hits (default 20, cap 100)" }
1267
+ },
1268
+ output: {
1269
+ schema: {
1270
+ type: "object",
1271
+ additionalProperties: false,
1272
+ properties: {
1273
+ hits: { type: "array", required: true, items: { type: "object", additionalProperties: true } },
1274
+ unreadablePages: { type: "array", items: { type: "string" }, description: "Page slugs that could not be read during the search" }
1275
+ }
1276
+ },
1277
+ render: (_args, value) => {
1278
+ const { hits, unreadablePages } = value;
1279
+ if (hits.length === 0) return TEXT_OUTPUT("0 hits.");
1280
+ const lines = hits.map((hit) => `${hit.slug} · ${hit.section} · L${hit.line}: ${hit.excerpt}`);
1281
+ if (unreadablePages?.length) lines.push("", incompleteChoroSearch(unreadablePages));
1282
+ return TEXT_OUTPUT(lines.join("\n"));
1283
+ }
1284
+ },
1285
+ async execute(args) {
1286
+ const repo = resolveChoroRepo(args?.repo);
1287
+ const unreadablePages = [];
1288
+ const hits = choro.search(repo.id, args?.query, {
1289
+ moduleSlug: args?.module ?? null,
1290
+ limit: args?.limit,
1291
+ onUnreadablePage: (slug) => unreadablePages.push(slug)
1292
+ });
1293
+ if (unreadablePages.length === 0) return { hits };
1294
+ if (hits.length === 0) throw new Error(incompleteChoroSearch(unreadablePages));
1295
+ return { hits, unreadablePages };
1296
+ }
1297
+ })
1298
+ ];
1299
+
1300
+ // Tool-exposure gate (v0.8.5): 跨会话记忆已自动注入,memory_search /
1301
+ // memory_archive 在慢/轻量模型上是多余往返,面板开关可直接隐藏工具——
1302
+ // 模型看不到就不会调,比在描述里劝它少调用更可靠。注意:live patch reload
1303
+ // 下已注册的工具不会被宿主反注册,排除只对全新会话生效。
1304
+ const hiddenTools = new Set();
1305
+ if (config?.disableMemorySearch === true) hiddenTools.add("memory_search");
1306
+ if (config?.disableMemoryArchive === true) hiddenTools.add("memory_archive");
1307
+ // #231 第二批是**反向**语义:memory_organize 默认不在场,organizeEnabled 打开才
1308
+ // 注册。仍走同一个闸门而不是在数组里条件展开——模型看不到就不会调,这比在描述里
1309
+ // 劝它别用可靠(上面那段 v0.8.5 的定性对两个方向都成立)。
1310
+ if (config?.organizeEnabled !== true) hiddenTools.add("memory_organize");
1311
+ // chorography 三个只读工具(M1):默认不在场,chorographyEnabled 打开才注册。
1312
+ // 与 organizeEnabled 同款反向语义;queries 未装配(null)时同样藏——「开了开关
1313
+ // 但装配缺件」与「没开」对模型都是不可见,可区分性由面板路由的 409/503 负责。
1314
+ if (config?.chorographyEnabled !== true || !choro) {
1315
+ hiddenTools.add("choro_module_map");
1316
+ hiddenTools.add("choro_read_page");
1317
+ hiddenTools.add("choro_search");
1318
+ }
1319
+ // 知识库三工具(契约 §3.4):与 choro 同款反向语义。装配缺件(kb 为 null)与没开
1320
+ // 对模型同样不可见——可区分性归路由层(503 / 409),模型侧不需要看见半个知识库。
1321
+ if (config?.kbEnabled !== true || !kb) {
1322
+ hiddenTools.add("kb_list_collections");
1323
+ hiddenTools.add("kb_search");
1324
+ hiddenTools.add("kb_read_doc");
1325
+ }
1326
+
1327
+ // 知识库工具定义在 kb/tools.js。**必须过 defineTool**:那里返回的是「describe 形状」
1328
+ // (属性上的 required:true、output.schema 用 spec 写法),直接 ctx.tools.register
1329
+ // 会被宿主的 JSON Schema 校验拒("required is not supported on type string")——
1330
+ // 这是接线时踩到的真故障,不是可选加工。判定按 parameters.type==="object" 分:
1331
+ // 已经是 JSON Schema 的说明调用方自己包过,再包一次会把 schema 转坏。
1332
+ if (typeof kbToolDefinitions === "function") {
1333
+ for (const def of kbToolDefinitions({ kb, cfg: config })) {
1334
+ tools.push(def?.parameters?.type === "object" ? def : defineTool(def));
1335
+ }
1336
+ }
1337
+
1338
+ for (const tool of tools) {
1339
+ if (hiddenTools.has(tool.name)) {
1340
+ ctx.logger?.info?.(`[dsh-mneme] tool "${tool.name}" hidden by config (disableMemorySearch/disableMemoryArchive/organizeEnabled)`);
1341
+ continue;
1342
+ }
1343
+ if (registeredTools.has(tool.name)) {
1344
+ ctx.logger?.warn?.(`[dsh-mneme] tool "${tool.name}" already registered, skipping duplicate`);
1345
+ continue;
1346
+ }
1347
+ // #539:闸门包在**注册期**,而不是在 execute 内部各写一遍。已注册的执行器
1348
+ // 不会被宿主反注册(同上面 disableMemorySearch 那段 v0.8.5 的定性),所以
1349
+ // 包一层的意义在于:热重载后 registration.sessionGate 换成新实例,旧的执行器
1350
+ // 也跟着读新的闸门,不会拿着过期 config 继续放行。
1351
+ //
1352
+ // 取会话走 sessionOf(exec) = exec.agent.session。ToolExecutionInput.agent 在
1353
+ // 宿主类型里是**可选**的,PTC 内层派发可能压根不带 agent;这种调用会拿到
1354
+ // null → isOff(null) 为 false → 放行。这是有意的:不认识调用者的工具调用
1355
+ // 不能一律拒绝(那会把正常会话也打死),闸门只对「能证明自己是谁」的调用生效。
1356
+ if (typeof tool.execute === "function") {
1357
+ const execute = tool.execute.bind(tool);
1358
+ tool.execute = async (args, exec) => {
1359
+ if (registration.sessionGate?.isOff(sessionOf(exec))) {
1360
+ throw new Error("dsh-mneme: memory tools are disabled for this incognito session");
1361
+ }
1362
+ return execute(args, exec);
1363
+ };
1364
+ }
1365
+ registeredTools.add(tool.name);
1366
+ ctx.tools.register(tool);
1367
+ }
1368
+
1369
+ return tools;
1370
+ }