@modusensus/dsh-mneme 0.8.14 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +660 -654
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +691 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -151
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +275 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/DISTILL.md +162 -0
  12. package/docs/ENTITIES.md +245 -0
  13. package/docs/LOCAL_MODEL.md +222 -0
  14. package/docs/SEMANTIC.md +256 -0
  15. package/docs/SLEEP.md +164 -0
  16. package/docs/STORAGE.md +98 -0
  17. package/lib/api-standalone.js +656 -673
  18. package/lib/api.js +1605 -1433
  19. package/lib/bootstrap.js +211 -211
  20. package/lib/client.js +6354 -5296
  21. package/lib/commands.js +95 -95
  22. package/lib/config.js +947 -843
  23. package/lib/content-hash.js +54 -54
  24. package/lib/continuity.js +220 -220
  25. package/lib/document-index.js +94 -94
  26. package/lib/document.js +303 -303
  27. package/lib/dream/clustering.js +118 -118
  28. package/lib/dream/decisions.js +694 -674
  29. package/lib/dream/narratives.js +44 -44
  30. package/lib/dream/sleep.js +819 -819
  31. package/lib/dream.js +1503 -1501
  32. package/lib/embedding.js +177 -177
  33. package/lib/entities/extractor.js +252 -252
  34. package/lib/graph/anchoring.js +179 -179
  35. package/lib/guide.js +74 -74
  36. package/lib/heat.js +144 -144
  37. package/lib/hot-memory.js +108 -46
  38. package/lib/index.js +552 -503
  39. package/lib/inject.js +428 -450
  40. package/lib/lang.js +248 -229
  41. package/lib/local-embedder.js +358 -358
  42. package/lib/maintenance.js +162 -142
  43. package/lib/mirror.js +330 -330
  44. package/lib/organize.js +450 -450
  45. package/lib/peak-hours.js +117 -117
  46. package/lib/placement.js +13 -0
  47. package/lib/pre-inject-gate.js +340 -0
  48. package/lib/quality-filter.js +126 -126
  49. package/lib/recall-stats.js +190 -175
  50. package/lib/reclaim-http.js +150 -0
  51. package/lib/reranker.js +269 -269
  52. package/lib/runtime/adopt.js +176 -176
  53. package/lib/runtime/closure.js +172 -172
  54. package/lib/runtime/download.js +247 -247
  55. package/lib/runtime/layout.js +265 -265
  56. package/lib/runtime/loader.js +252 -252
  57. package/lib/runtime/model-fetch.js +361 -361
  58. package/lib/runtime/provision.js +237 -237
  59. package/lib/runtime/tarball.js +130 -130
  60. package/lib/runtime/verify.js +223 -204
  61. package/lib/safe-slice.js +18 -0
  62. package/lib/scope.js +146 -146
  63. package/lib/search/adaptive.js +60 -60
  64. package/lib/search/bm25.js +96 -96
  65. package/lib/semantic.js +229 -229
  66. package/lib/sensitive-scan.js +209 -209
  67. package/lib/serve.js +215 -215
  68. package/lib/service.js +2688 -2605
  69. package/lib/settings.js +528 -511
  70. package/lib/store.js +3196 -3007
  71. package/lib/summarize.js +1039 -856
  72. package/lib/tools.js +743 -737
  73. package/lib/vector-index.js +110 -110
  74. package/lib/version-check.js +122 -122
  75. package/lib/write-admission.js +402 -402
  76. package/locale/en.json +6 -6
  77. package/locale/zh.json +6 -6
  78. package/package.json +118 -118
  79. package/runtime-manifest.json +526 -526
  80. package/scripts/benchmark-embed.js +201 -201
  81. package/scripts/benchmark-recall.js +249 -249
  82. package/scripts/benchmark-rerank.js +166 -166
  83. package/scripts/build-runtime-manifest.mjs +224 -224
  84. package/scripts/changelog-prep.mjs +36 -36
  85. package/scripts/check-sync.js +42 -42
  86. package/scripts/e2e-dsh.js +220 -220
  87. package/scripts/mneme-runtime.mjs +277 -277
  88. package/scripts/stress-dsh.js +255 -255
  89. package/scripts/sync-lib.js +47 -47
  90. package/scripts/sync-test-badge.mjs +69 -69
  91. package/scripts/test-count-sync.mjs +44 -44
  92. package/src/api-standalone.js +656 -673
  93. package/src/api.js +1605 -1433
  94. package/src/bootstrap.js +211 -211
  95. package/src/commands.js +95 -95
  96. package/src/config.js +947 -843
  97. package/src/content-hash.js +54 -54
  98. package/src/continuity.js +220 -220
  99. package/src/document-index.js +94 -94
  100. package/src/document.js +303 -303
  101. package/src/dream/clustering.js +118 -118
  102. package/src/dream/decisions.js +694 -674
  103. package/src/dream/narratives.js +44 -44
  104. package/src/dream/sleep.js +819 -819
  105. package/src/dream.js +1503 -1501
  106. package/src/embedding.js +177 -177
  107. package/src/entities/extractor.js +252 -252
  108. package/src/graph/anchoring.js +179 -179
  109. package/src/guide.js +74 -74
  110. package/src/heat.js +144 -144
  111. package/src/hot-memory.js +108 -46
  112. package/src/index.js +552 -503
  113. package/src/inject.js +428 -450
  114. package/src/lang.js +248 -229
  115. package/src/local-embedder.js +358 -358
  116. package/src/maintenance.js +162 -142
  117. package/src/mirror.js +330 -330
  118. package/src/organize.js +450 -450
  119. package/src/peak-hours.js +117 -117
  120. package/src/placement.js +13 -0
  121. package/src/pre-inject-gate.js +340 -0
  122. package/src/quality-filter.js +126 -126
  123. package/src/recall-stats.js +190 -175
  124. package/src/reclaim-http.js +150 -0
  125. package/src/reranker.js +269 -269
  126. package/src/runtime/adopt.js +176 -176
  127. package/src/runtime/closure.js +172 -172
  128. package/src/runtime/download.js +247 -247
  129. package/src/runtime/layout.js +265 -265
  130. package/src/runtime/loader.js +252 -252
  131. package/src/runtime/model-fetch.js +361 -361
  132. package/src/runtime/provision.js +237 -237
  133. package/src/runtime/tarball.js +130 -130
  134. package/src/runtime/verify.js +223 -204
  135. package/src/safe-slice.js +18 -0
  136. package/src/scope.js +146 -146
  137. package/src/search/adaptive.js +60 -60
  138. package/src/search/bm25.js +96 -96
  139. package/src/semantic.js +229 -229
  140. package/src/sensitive-scan.js +209 -209
  141. package/src/serve.js +215 -215
  142. package/src/service.js +2688 -2605
  143. package/src/settings.js +528 -511
  144. package/src/store.js +3196 -3007
  145. package/src/summarize.js +1039 -856
  146. package/src/tools.js +743 -737
  147. package/src/vector-index.js +110 -110
  148. package/src/version-check.js +122 -122
  149. package/src/write-admission.js +402 -402
  150. package/test/adaptive-inject-budget.test.js +85 -85
  151. package/test/api-routes-gaps.test.js +899 -218
  152. package/test/api.test.js +1725 -1690
  153. package/test/audit.test.js +448 -448
  154. package/test/baseline-persist.test.js +248 -248
  155. package/test/benchmark.test.js +94 -94
  156. package/test/bootstrap.test.js +220 -220
  157. package/test/changelog-prep.test.js +60 -60
  158. package/test/client.test.js +1582 -1169
  159. package/test/clustering.test.js +100 -100
  160. package/test/commands.test.js +106 -106
  161. package/test/config.test.js +66 -66
  162. package/test/conflict-freeze.test.js +300 -300
  163. package/test/content-hash.test.js +204 -204
  164. package/test/continuity.test.js +333 -333
  165. package/test/contrast.test.js +314 -0
  166. package/test/document-dir.test.js +233 -233
  167. package/test/document.test.js +671 -671
  168. package/test/dream-archive-guardrail.test.js +116 -116
  169. package/test/dream-candidate-hybrid.test.js +281 -281
  170. package/test/dream-coverage-degrade.test.js +86 -86
  171. package/test/dream-failure-backoff.test.js +173 -173
  172. package/test/dream-merge-guardrail.test.js +219 -0
  173. package/test/dream-peak-hours.test.js +194 -194
  174. package/test/dream.test.js +1385 -1383
  175. package/test/embedding-ready.test.js +196 -196
  176. package/test/entities.test.js +627 -547
  177. package/test/entity-recall.test.js +179 -179
  178. package/test/epistemic.test.js +325 -325
  179. package/test/fnew-0112.test.js +311 -311
  180. package/test/fnew-03.test.js +422 -422
  181. package/test/graph-anchoring.test.js +184 -184
  182. package/test/graph-api.test.js +175 -175
  183. package/test/graph-inject-budget.test.js +103 -103
  184. package/test/graph-passive-confirm.test.js +91 -91
  185. package/test/graph-weight-evolution.test.js +104 -104
  186. package/test/heat.test.js +175 -175
  187. package/test/helpers/dream-mock.js +82 -82
  188. package/test/helpers/peer-worker.mjs +25 -25
  189. package/test/helpers/runtime-source.js +60 -60
  190. package/test/helpers/tar-builder.js +80 -80
  191. package/test/helpers/write-admission-samples.js +308 -308
  192. package/test/hot-memory.test.js +211 -145
  193. package/test/inject-content-cap.test.js +91 -91
  194. package/test/inject-first-round-bm25.test.js +89 -89
  195. package/test/inject-heat.test.js +77 -77
  196. package/test/inject-parent-gate.test.js +106 -106
  197. package/test/inject-pools.test.js +194 -194
  198. package/test/inject-recall.test.js +144 -105
  199. package/test/inject-rotation.test.js +161 -161
  200. package/test/inject.test.js +443 -420
  201. package/test/lang.test.js +87 -87
  202. package/test/lastrunat-persist.test.js +101 -101
  203. package/test/lib-smoke.test.js +96 -96
  204. package/test/llm-audit.test.js +696 -598
  205. package/test/llm-message-source.test.js +207 -207
  206. package/test/local-embedder.test.js +292 -292
  207. package/test/maintenance.test.js +501 -391
  208. package/test/mcp-stdio.test.js +385 -385
  209. package/test/mirror-dirty.test.js +424 -424
  210. package/test/mirror-edit-digest.test.js +187 -187
  211. package/test/mirror-generation.test.js +499 -499
  212. package/test/mirror-types.test.js +208 -208
  213. package/test/mirror.test.js +249 -249
  214. package/test/narrative-bars.test.js +162 -162
  215. package/test/organize.test.js +418 -418
  216. package/test/peer-blockers.test.js +193 -193
  217. package/test/placement.test.js +36 -0
  218. package/test/policy-epoch.test.js +259 -259
  219. package/test/pre-inject-gate.test.js +444 -0
  220. package/test/quality-filter.test.js +186 -186
  221. package/test/reasoning-effort.test.js +752 -752
  222. package/test/recall-anti-update.test.js +82 -82
  223. package/test/recall-evals.test.js +253 -253
  224. package/test/recall-layer.test.js +326 -326
  225. package/test/recall-stats.test.js +274 -189
  226. package/test/receipt-chain.test.js +451 -451
  227. package/test/reclaim-http.test.js +209 -0
  228. package/test/reflection.test.js +226 -226
  229. package/test/reindex-backfill.test.js +62 -62
  230. package/test/reranker-single-logit.test.js +73 -73
  231. package/test/reranker.test.js +197 -197
  232. package/test/resident-status.test.js +83 -83
  233. package/test/runtime-adopt.test.js +206 -206
  234. package/test/runtime-cli.test.js +89 -89
  235. package/test/runtime-closure.test.js +193 -193
  236. package/test/runtime-download.test.js +302 -302
  237. package/test/runtime-layout.test.js +163 -163
  238. package/test/runtime-loader.test.js +255 -255
  239. package/test/runtime-manifest.test.js +159 -159
  240. package/test/runtime-model-fetch.test.js +348 -348
  241. package/test/runtime-provision.test.js +101 -101
  242. package/test/runtime-tarball.test.js +81 -81
  243. package/test/runtime-verify.test.js +319 -279
  244. package/test/scope-candidates.test.js +239 -239
  245. package/test/scope-explicit.test.js +452 -452
  246. package/test/scope-inject-soft.test.js +106 -106
  247. package/test/scope-retrieval.test.js +197 -197
  248. package/test/scope-storage.test.js +255 -255
  249. package/test/scope-strict.test.js +367 -367
  250. package/test/search-fusion.test.js +90 -90
  251. package/test/semantic.test.js +124 -124
  252. package/test/sensitive-scan.test.js +207 -207
  253. package/test/serve-bin.test.js +121 -121
  254. package/test/serve.test.js +196 -196
  255. package/test/service-search.test.js +174 -174
  256. package/test/service.test.js +410 -405
  257. package/test/settings.test.js +269 -261
  258. package/test/skip-invalid-restore.test.js +262 -262
  259. package/test/sleep-action-set.test.js +422 -422
  260. package/test/sleep-heat.test.js +126 -126
  261. package/test/sleep-scheduler-rearm.test.js +89 -89
  262. package/test/sleep.test.js +527 -527
  263. package/test/standalone-api.test.js +751 -751
  264. package/test/store-vector-cache.test.js +98 -98
  265. package/test/store.test.js +504 -396
  266. package/test/stress.test.js +209 -209
  267. package/test/summarize-occurred-at.test.js +127 -0
  268. package/test/summarize-reasoning-effort.test.js +189 -189
  269. package/test/summarize.test.js +1639 -1465
  270. package/test/supersede-state-tracking.test.js +394 -0
  271. package/test/test-count-sync.test.js +60 -60
  272. package/test/tools-dto-schema-matrix.test.js +325 -325
  273. package/test/tools-memory-get-schema.test.js +65 -65
  274. package/test/tools.test.js +428 -374
  275. package/test/updated-at-semantics.test.js +113 -113
  276. package/test/vector-index.test.js +221 -221
  277. package/test/version-check.test.js +152 -152
  278. package/test/webServer-optional.test.js +82 -82
  279. package/test/write-admission.test.js +668 -668
package/src/tools.js CHANGED
@@ -1,737 +1,743 @@
1
- import { defineTool } from "@deepseek-ai/dsh-tools";
2
- import { createScopeResolver, normalizeExplicitScope, sessionKeyOf } 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
-
11
- const TEXT_OUTPUT = (text) => [{ type: "text", text }];
12
- // Per-registry tool-name registry: guards against duplicate registration on
13
- // live patch reload (DSH Desktop `patchReload: "live"`) where a plugin may be
14
- // re-applied on the same tools registry without an intervening unregister.
15
- const REGISTERED_TOOLS = new WeakMap();
16
-
17
- // Wire shape emitted by service.toApiList: shared by memory_search and
18
- // memory_list so their output schemas always declare every key the runtime
19
- // value carries (additionalProperties: false would reject undeclared keys).
20
- const MEMORY_ITEM_SCHEMA = {
21
- type: "object",
22
- additionalProperties: false,
23
- properties: {
24
- id: { type: "string", required: true },
25
- type: { type: "string", required: true },
26
- title: { type: "string", required: true },
27
- content: { type: "string", required: true },
28
- tags: { type: "array", items: { type: "string" } },
29
- importance: { type: "integer", required: true },
30
- source: { type: "string" },
31
- // v0.8.0 A2:scope 标注与事件发生时间随行透出(未标注时缺省,可选属性)。
32
- // v0.8.1 底座:scope 来源(auto/explicit)与决策时间随行透出(同样可选)。
33
- agent_scope: { type: "string" },
34
- workspace_scope: { type: "string" },
35
- agent_scope_source: { type: "string" },
36
- workspace_scope_source: { type: "string" },
37
- scope_decided_at: { type: "string" },
38
- sensitivity: { type: "string" },
39
- occurred_at: { type: "string" },
40
- // #230:document 指针行的文件定位——「全文按需读」的入口;普通行缺省。
41
- doc_path: { type: "string" },
42
- created_at: { type: "string", required: true },
43
- updated_at: { type: "string", required: true }
44
- }
45
- };
46
- // 导出供回归测试断言 memory_get 与共享 schema 同源(#184 防漂移护栏)。
47
- export { MEMORY_ITEM_SCHEMA };
48
-
49
- // v0.8.0 A2:occurred 时间窗参数 → store 过滤选项(list/count 同口径);
50
- // 未传参返回空对象,既有调用方不受影响。(A3 复核:此处入参仅含 occurred 边界。)
51
- function occurredWindow(args) {
52
- const from = args?.occurred_from ?? null;
53
- const to = args?.occurred_to ?? null;
54
- return from !== null || to !== null ? { occurredFrom: from, occurredTo: to } : {};
55
- }
56
-
57
- // v0.8.0 A3:strictScope 硬过滤的 visibility 选项(store.list/count 同口径)。
58
- // flag 关或会话 scope 未解析出(flag 关时解析器返回 null)→ 空对象不过滤;
59
- // scope 为 {null,null}(匿名会话)时照传——store 侧 fail-closed 只放行未标注行。
60
- function strictVisibility(config, scope) {
61
- if (config?.strictScope !== true || !scope) return {};
62
- return { visibility: { agentScope: scope.agent_scope, workspaceScope: scope.workspace_scope } };
63
- }
64
-
65
- // v0.8.0 A2:检索结果的 provenance 附加段——只在有标注时出现,未标注行渲染
66
- // 与 A2 前逐字节一致。
67
- const MEMORY_PROVENANCE = (m) => {
68
- const parts = [];
69
- if (m.occurred_at) parts.push(`occurred: ${m.occurred_at}`);
70
- if (m.agent_scope || m.workspace_scope) {
71
- parts.push(`scope: ${m.agent_scope ?? "global"} / ${m.workspace_scope ?? "global"}`);
72
- }
73
- if (m.sensitivity) parts.push(`sensitivity: ${m.sensitivity}`);
74
- return parts.length ? ` | ${parts.join(" | ")}` : "";
75
- };
76
-
77
- export function createTools(ctx, service, config, embedder) {
78
- const toolsRegistry = ctx.tools;
79
- let registeredTools = REGISTERED_TOOLS.get(toolsRegistry);
80
- if (!registeredTools) {
81
- registeredTools = new Set();
82
- REGISTERED_TOOLS.set(toolsRegistry, registeredTools);
83
- }
84
- // v0.8.0 A1/A2(issue #17):会话 scope 解析(agentPreset + workspace 反查)。
85
- // flag 关闭时恒返回 null——写入不标注,检索不加权,行为与 A1 前完全一致。
86
- // logger 透传:registry 反查失败时 warnOnce 才有出口(否则静默降级无观测)。
87
- const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
88
- // #249 能力说明(injectGuidanceEnabled):开启时给「何时用」最有歧义的两个
89
- // 工具补一句判断指引。工具描述常驻、不进每轮上下文,这个位子零注入成本;
90
- // 关闭时描述逐字节不变,也不动其他工具的文案。
91
- // 它是注入父开关的子项(#249 第二批):`autoInject` 关掉时这里同样不生效——
92
- // 工具描述是这个子项唯一住在注入器之外的落点,不在闸门内就漏了。
93
- // #249 N3 降级路径(continuityRescueEnabled):宿主若不提供可挂钩的压缩前时机,
94
- // 双落点里的注入那一半就没有触发者,这时把规则交给 agent 自判(见 CONTINUITY_TOOL_RULE)。
95
- // 与能力说明各自独立:任一开关关闭时描述逐字节不变。
96
- // 本批不做宿主能力探测(没有可靠的探测口),所以子开关打开时这条规则常驻,与自动双落点并存。
97
- const withToolGuide = (name, description) => {
98
- let text = description;
99
- if (injectChildEnabled(config, "injectGuidanceEnabled") && TOOL_GUIDE[name]) text += TOOL_GUIDE[name];
100
- if (injectChildEnabled(config, "continuityRescueEnabled") && CONTINUITY_TOOL_RULE[name]) text += CONTINUITY_TOOL_RULE[name];
101
- return text;
102
- };
103
-
104
- // 复核项 4(issue #170):strictScope 下他 scope(explicit)的行对工具侧按
105
- // 「不存在」处理——update/delete 与 memory_get 同款无存在性泄漏。strictScope
106
- // 关、或会话身份取不到(scope 为 null)时恒可见(与 get 的短路语义一致)。
107
- const visibleUnderStrictScope = (memory, exec) => {
108
- if (config?.strictScope !== true) return true;
109
- const scope = resolveSessionScope(exec);
110
- return !scope || service.isVisibleInScope(memory, scope);
111
- };
112
- // 在调用点以「展开恒为 undefined」的形态前置校验(抛错即中止写入)。
113
- const assertVisibleForTool = (id, exec) => {
114
- const memory = id ? service.getById(id) : undefined;
115
- if (!visibleUnderStrictScope(memory, exec)) throw new Error("memory not found");
116
- return undefined;
117
- };
118
- // delete 侧需要目标行本身判断存在性(不可见 = 视作不存在,不抛错)。
119
- const visibleForTool = (id, exec) => {
120
- const memory = id ? service.getById(id) : undefined;
121
- return visibleUnderStrictScope(memory, exec) ? memory : undefined;
122
- };
123
- const tools = [
124
- defineTool({
125
- name: "memory_save",
126
- description: withToolGuide(
127
- "memory_save",
128
- "Persist one memory entry for future sessions (user preferences, project state, decisions). " +
129
- "Call this when the user states a durable preference, a project decision is made, or a lesson is learned. " +
130
- "Merges into an existing entry of the same type when the title matches."
131
- ),
132
- parameters: {
133
- // document 不在此列(#230):document 行只能经 memory_register_document
134
- // 铸造(注册校验 + doc_path + evidence),防止 memory_save 造出无指针
135
- // 无回链的伪行。
136
- 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" },
137
- title: { type: "string", required: true, description: "Short unique title" },
138
- content: { type: "string", required: true, description: "Memory body" },
139
- tags: { type: "array", items: { type: "string" }, description: "Optional tags" },
140
- importance: { type: "integer", description: "1-5; >= threshold auto-injects into future sessions" },
141
- source: { type: "string", description: "Optional provenance" },
142
- sensitivity: { type: "string", description: "Optional sensitivity label (free-form, e.g. personal). Same-title entries with different sensitivity stay separate instead of merging." },
143
- occurred_at: { type: "string", description: "Optional ISO-8601 instant the remembered event happened (differs from write time). Invalid values are ignored." },
144
- 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." },
145
- 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." }
146
- },
147
- output: {
148
- schema: {
149
- type: "object",
150
- additionalProperties: false,
151
- properties: {
152
- action: { type: "string", required: true, enum: ["created", "merged", "denied"] },
153
- // denied 时压根没有行可指,所以 id 缺省而不是空串:空串会让「写成功但
154
- // id 为空」与「根本没写」在读回执时长得一样,与 #254 验收第 2 条
155
- // (被拒写入可解释、不静默丢弃)相悖。
156
- id: { type: "string", description: "Row id; absent when action=denied." },
157
- reason: { type: "string", description: "Rejection reason when action=denied: blank | noise | sensitive." }
158
- }
159
- },
160
- render: (_args, value) => TEXT_OUTPUT(value.action === "denied"
161
- ? `memory save rejected (${value.reason ?? "denied"}): nothing was written`
162
- : `memory ${value.action}: ${value.id}`)
163
- },
164
- async execute(args, exec) {
165
- // scope 标注(v0.8.1 底座,issue #170):默认由会话身份解析(载体自动
166
- // 标注,盖 auto 章);显式 agent_scope/workspace_scope 参数逐维覆盖并盖
167
- // explicit 章。解析绝不抛错、取不到落 NULL。
168
- // 复核项 2(#170):scopeEnabled 只门控「自动标注」分支——显式声明与
169
- // 读取身份(search/list/get/注入经同一解析器)不受 flag 限制,否则
170
- // strictScope 硬墙会被 flag 静默拆掉(fail-open)。
171
- // (存储 NULL,由 source 列与「从未标注」区分)。非字符串参数在工具
172
- // 入参 schema 层即被拒(type: "string")——脏值到不了归一化,无静默放宽。
173
- const scope = resolveSessionScope(exec);
174
- const autoStamping = config?.scopeEnabled === true;
175
- const agentLabel = args.agent_scope !== undefined
176
- ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
177
- : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
178
- const workspaceLabel = args.workspace_scope !== undefined
179
- ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
180
- : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
181
- const result = service.saveWithDedupe({
182
- // #254 写入准入的计数单位:会话键作为瞬时字段随写入传递(与 _mergeInto /
183
- // _overwrite 同款约定,不落库)。缺会话身份的宿主返回 null = 这次写入不进
184
- // 预算;系统写入(dream / summarize / organize)从不带这个字段。
185
- _sessionKey: sessionKeyOf(exec),
186
- type: args.type,
187
- title: args.title,
188
- content: args.content,
189
- tags: args.tags ?? [],
190
- importance: args.importance ?? 3,
191
- source: args.source ?? "tool",
192
- ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
193
- ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {}),
194
- ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
195
- ...(args.occurred_at !== undefined ? { occurred_at: args.occurred_at } : {})
196
- });
197
- // #254 第 1 级硬拒:工具层是模型唯一能看到这次失败的地方,必须显式回一句
198
- // 可行动的拒绝理由。静默返回成功会让模型以为记住了,然后永远不再重写。
199
- if (result.action === "denied") return { action: "denied", reason: result.reason };
200
- return { action: result.action, id: result.memory.id };
201
- }
202
- }),
203
-
204
- defineTool({
205
- name: "memory_search",
206
- description: withToolGuide(
207
- "memory_search",
208
- "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."
209
- ),
210
- // A2 检索接线:occurred 时间窗 + 会话 scope 加成(见 execute)。
211
- parameters: {
212
- query: { type: "string", required: true, description: "Search text; substring match over title/content/tags" },
213
- limit: { type: "integer", description: "Max results (default 20)" },
214
- 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" },
215
- semantic: { type: "boolean", description: "Shorthand: enable semantic (vector) recall (same as mode=vector when true)" },
216
- rerank: { type: "boolean", description: "Run cross-encoder rerank over candidates when a local reranker is configured (default true)" },
217
- 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." },
218
- 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." }
219
- },
220
- output: {
221
- schema: {
222
- type: "object",
223
- additionalProperties: false,
224
- properties: {
225
- items: {
226
- type: "array", required: true,
227
- items: MEMORY_ITEM_SCHEMA
228
- }
229
- }
230
- },
231
- render: (_args, value) => {
232
- const items = value.items ?? [];
233
- if (items.length === 0) return TEXT_OUTPUT("No memory entries found.");
234
- const body = items
235
- .map((m, i) => {
236
- const preview = (m.content ?? "").replace(/\s+/g, " ").trim();
237
- const cut = preview.length > 200 ? `${preview.slice(0, 200)}…` : preview;
238
- return `[${i + 1}] ${m.title}\n ID: ${m.id} | type: ${m.type} | importance: ${m.importance} | updated: ${m.updated_at}${MEMORY_PROVENANCE(m)}\n ${cut}`;
239
- })
240
- .join("\n\n");
241
- return TEXT_OUTPUT(`Found ${items.length} memory entr${items.length === 1 ? "y" : "ies"}:\n\n${body}`);
242
- }
243
- },
244
- async execute(args, exec) {
245
- const limit = args.limit ?? 20;
246
- const mode = args.semantic === true && !args.mode ? "vector" : args.mode ?? "auto";
247
- // v0.8.0 A2(issue #17):scope 检索加权 + occurred 时间窗的检索接线。
248
- // flag 关闭或解析不出 scope 时为 null,检索行为与 A2 前一致。
249
- const scope = resolveSessionScope(exec);
250
- const occurredFrom = args.occurred_from ?? null;
251
- const occurredTo = args.occurred_to ?? null;
252
- const rows = await service.searchMemories(args.query, {
253
- mode,
254
- topK: limit,
255
- useRerank: args.rerank !== false,
256
- ...(scope ? { scope } : {}),
257
- ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
258
- });
259
- return { items: service.toApiList(rows) };
260
- }
261
- }),
262
-
263
- defineTool({
264
- name: "memory_list",
265
- 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.",
266
- parameters: {
267
- 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" },
268
- limit: { type: "integer", description: "Page size (default 50)" },
269
- offset: { type: "integer", description: "Page offset (default 0)" },
270
- include_archived: { type: "boolean", description: "Include archived (hidden) entries so they can be found and restored (default false)" },
271
- 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." },
272
- 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." }
273
- },
274
- output: {
275
- schema: {
276
- type: "object",
277
- additionalProperties: false,
278
- properties: {
279
- items: {
280
- type: "array", required: true,
281
- items: MEMORY_ITEM_SCHEMA
282
- },
283
- total: { type: "integer", required: true }
284
- }
285
- },
286
- render: (_args, value) => {
287
- const items = value.items ?? [];
288
- if (items.length === 0) return TEXT_OUTPUT(`0 memory entries (of ${value.total}).`);
289
- const body = items
290
- .map((m, i) => `[${i + 1}] ${m.title} (type=${m.type}, importance=${m.importance})\n ID: ${m.id} | updated: ${m.updated_at}${MEMORY_PROVENANCE(m)}`)
291
- .join("\n\n");
292
- return TEXT_OUTPUT(`${items.length} memory entries (of ${value.total}):\n\n${body}`);
293
- }
294
- },
295
- async execute(args) {
296
- const includeArchived = args.include_archived === true;
297
- const rows = service.toApiList(service.list({
298
- type: args.type,
299
- limit: args.limit ?? 50,
300
- offset: args.offset ?? 0,
301
- includeArchived,
302
- ...occurredWindow(args),
303
- // A3:strict 开启时按会话 scope 硬过滤(宿主按 (args, runContext) 调用,
304
- // 从 arguments 取第二参)。
305
- ...strictVisibility(config, resolveSessionScope(arguments[1]))
306
- }));
307
- return { items: rows, total: service.count(args.type, { includeArchived, ...occurredWindow(args), ...strictVisibility(config, resolveSessionScope(arguments[1])) }) };
308
- }
309
- }),
310
-
311
- defineTool({
312
- name: "memory_get",
313
- description: "Fetch one memory entry by ID and return its full content as text. Use after memory_list to read a specific entry.",
314
- parameters: {
315
- id: { type: "string", required: true, description: "Memory id" }
316
- },
317
- output: {
318
- schema: {
319
- type: "object",
320
- additionalProperties: false,
321
- properties: {
322
- // 与 memory_search / memory_list 共用同一份 item schema——DTO 由
323
- // toApiList 统一产出,内联副本曾漏掉 v0.8.1 的 scope 来源三键,
324
- // 任何被标注过的行都过不了 in-process 校验(#184)。
325
- memory: MEMORY_ITEM_SCHEMA
326
- }
327
- },
328
- render: (_args, value) => {
329
- const m = value.memory;
330
- // #230:document 指针行把文件路径亮在首行——「全文按需读」从这里拿路径。
331
- const doc = m.doc_path ? ` | doc: ${m.doc_path}` : "";
332
- return TEXT_OUTPUT(`${m.title}\nID: ${m.id} | type: ${m.type} | importance: ${m.importance}${doc}${MEMORY_PROVENANCE(m)}\n\n${m.content}`);
333
- }
334
- },
335
- async execute(args) {
336
- const memory = service.getById(args.id);
337
- if (memory === undefined) throw new Error("memory not found");
338
- // v0.8.0 A3:strictScope 下他 scope 的行按不存在处理(无存在性泄漏)。
339
- // 宿主注册表按 (args, runContext) 两参调用处理器,从 arguments 取第二参。
340
- const runContext = arguments[1];
341
- const scope = resolveSessionScope(runContext);
342
- if (config.strictScope === true && scope && !service.isVisibleInScope(memory, scope)) {
343
- throw new Error("memory not found");
344
- }
345
- return { memory: service.toApiList([memory])[0] };
346
- }
347
- }),
348
-
349
- defineTool({
350
- name: "memory_update",
351
- description: "Modify an existing memory entry (title, content, type, tags, importance).",
352
- parameters: {
353
- id: { type: "string", required: true, description: "Memory id" },
354
- title: { type: "string" },
355
- content: { type: "string" },
356
- // document 不在此列(#230):type 不许改入 document——既有 document 行
357
- // 的摘要修复(只改 content/title)不受影响。
358
- type: { type: "string", enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint"] },
359
- tags: { type: "array", items: { type: "string" } },
360
- importance: { type: "integer", description: "1-5" },
361
- reason: { type: "string", description: "Optional context for the correction (what the user actually said/wanted), recorded for reflection" },
362
- 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)." },
363
- 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)." }
364
- },
365
- output: {
366
- schema: {
367
- type: "object",
368
- additionalProperties: false,
369
- properties: {
370
- memory: {
371
- type: "object",
372
- additionalProperties: false,
373
- properties: {
374
- id: { type: "string", required: true },
375
- title: { type: "string", required: true },
376
- content: { type: "string", required: true }
377
- }
378
- }
379
- }
380
- },
381
- render: (_args, value) => TEXT_OUTPUT(`Updated memory ${value.memory.id}: ${value.memory.title}`)
382
- },
383
- async execute(args) {
384
- const memory = service.update(args.id, {
385
- title: args.title,
386
- content: args.content,
387
- type: args.type,
388
- tags: args.tags,
389
- importance: args.importance,
390
- // 复核项 4(#170):strictScope 下他 scope 的行按「不存在」处理(与 get 对齐),
391
- // 展开恒为 undefined,仅承担写入前校验。
392
- ...(assertVisibleForTool(args.id, arguments[1])),
393
- ...(args.agent_scope !== undefined ? { agent_scope: args.agent_scope } : {}),
394
- ...(args.workspace_scope !== undefined ? { workspace_scope: args.workspace_scope } : {})
395
- }, { query: args.reason });
396
- return { memory: { id: memory.id, title: memory.title, content: memory.content } };
397
- }
398
- }),
399
-
400
- defineTool({
401
- name: "memory_delete",
402
- description: "Permanently delete a memory entry.",
403
- parameters: {
404
- id: { type: "string", required: true }
405
- },
406
- output: {
407
- schema: {
408
- type: "object",
409
- additionalProperties: false,
410
- properties: { deleted: { type: "boolean", required: true } }
411
- },
412
- render: (_args, value) => TEXT_OUTPUT(value.deleted ? "Memory deleted." : "Memory not found.")
413
- },
414
- async execute(args) {
415
- // 复核项 4(#170):不可见(explicit 他 scope)= 视作不存在,无存在性泄漏。
416
- const target = visibleForTool(args.id, arguments[1]);
417
- if (target) service.remove(args.id);
418
- return { deleted: !!target };
419
- }
420
- }),
421
-
422
- defineTool({
423
- name: "memory_forget",
424
- description:
425
- "Stop a memory from being auto-injected and from appearing in searches and lists without deleting it. " +
426
- "The entry stays in storage; pass forgotten: false to restore it.",
427
- parameters: {
428
- id: { type: "string", required: true },
429
- forgotten: { type: "boolean", description: "Suppress (true, default) or restore (false) the entry's visibility" }
430
- },
431
- output: {
432
- schema: {
433
- type: "object",
434
- additionalProperties: false,
435
- properties: {
436
- memory: {
437
- type: "object",
438
- additionalProperties: false,
439
- properties: {
440
- id: { type: "string", required: true },
441
- forgotten: { type: "boolean", required: true }
442
- }
443
- }
444
- }
445
- },
446
- render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} injection ${value.memory.forgotten ? "suppressed" : "restored"}.`)
447
- },
448
- async execute(args) {
449
- if (service.getById(args.id) === undefined) {
450
- throw new Error("memory not found");
451
- }
452
- const memory = service.setForget(args.id, args.forgotten ?? true);
453
- return { memory: { id: memory.id, forgotten: memory.forgotten } };
454
- }
455
- }),
456
-
457
- defineTool({
458
- name: "memory_archive",
459
- description:
460
- "Archive a memory (hide it from active lists, search, injection and dream consolidation) or restore it. " +
461
- "Archived entries stay in storage and are recoverable: pass archived=false to restore, and use memory_list with " +
462
- "include_archived=true to find archived entries. " +
463
- "Only archive when the user asks, or an entry is clearly stale/no longer relevant — do not archive proactively mid-session to tidy up.",
464
- parameters: {
465
- id: { type: "string", required: true, description: "Memory id" },
466
- archived: { type: "boolean", description: "Archive (true, default) or restore (false) the entry" }
467
- },
468
- output: {
469
- schema: {
470
- type: "object",
471
- additionalProperties: false,
472
- properties: {
473
- memory: {
474
- type: "object",
475
- additionalProperties: false,
476
- properties: {
477
- id: { type: "string", required: true },
478
- archived: { type: "boolean", required: true }
479
- }
480
- }
481
- }
482
- },
483
- render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} ${value.memory.archived ? "archived" : "restored"}.`)
484
- },
485
- async execute(args) {
486
- if (service.getById(args.id) === undefined) {
487
- throw new Error("memory not found");
488
- }
489
- const memory = service.setArchived(args.id, args.archived ?? true);
490
- return { memory: { id: memory.id, archived: memory.archived } };
491
- }
492
- }),
493
-
494
- // #230(#164 设计稿评审线):document 型记忆注册——agent 产长文档的指针
495
- // 行铸造口。写入权分离:全文归 agent(管线对文件零读零写零改),库里只
496
- // 存摘要 + doc_path + evidence 三样;C2 比对去重、supersede 记账在
497
- // service.registerDocument(src/document.js)内完成。判断指引:调研报告/
498
- // 设计稿/长整理产物「存外档」用本工具;原子事实(偏好/决策/教训)仍走
499
- // memory_save;tag 与章节名建议用英文(跨语言稳定键),摘要正文可多语言。
500
- defineTool({
501
- name: "memory_register_document",
502
- description:
503
- "Register an agent-authored document (research report, design doc, long digest) into memory as a pointer row. " +
504
- "Write-ownership split: the full text stays agent-owned on disk — the pipeline never reads or rewrites it; the DB " +
505
- "stores only the summary + doc_path + evidence. Validates the file exists (absolute path, non-empty regular file), " +
506
- "intersects evidence with real memory ids (all-fabricated evidence is rejected; unknown ids are dropped and the row " +
507
- "is tagged evidence_degraded), and dedupes: re-registering the same path or title supersedes the old row (the old " +
508
- "file is never touched; content_history stays traceable), while a merely near-duplicate summary of a different " +
509
- "document row is rejected — update that row instead. On success the absorbed atomic evidence rows leave the active " +
510
- "face in the same transaction (recoverable, nothing deleted); constraint/preference rows and other " +
511
- "document/summary rows are never auto-archived, and keep_evidence_active: true opts out. Ids this same document " +
512
- "absorbed on an earlier version still count as its evidence, so re-registering a new version is not read as " +
513
- "fabricated evidence. Use for 'where is the conclusion doc for this project?' " +
514
- "lookups; atomic facts still go to memory_save.",
515
- parameters: {
516
- 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." },
517
- title: { type: "string", required: true, description: "Short unique title (English recommended: it is the cross-language stable dedupe/supersede key)" },
518
- summary: { type: "string", required: true, description: "One-paragraph summary stored in the DB and used for injection (any language)" },
519
- tags: { type: "array", items: { type: "string" }, description: "Optional tags (English recommended)" },
520
- importance: { type: "integer", description: "1-5 (default 3); the summary row injects at the next-priority tier within documentInjectBudget when importance >= threshold" },
521
- 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." },
522
- 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)." },
523
- source: { type: "string", description: "Optional provenance" },
524
- 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." },
525
- 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." },
526
- 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." }
527
- },
528
- output: {
529
- schema: {
530
- type: "object",
531
- additionalProperties: false,
532
- properties: {
533
- action: { type: "string", required: true, enum: ["created", "superseded"] },
534
- id: { type: "string", required: true },
535
- superseded_id: { type: "string" },
536
- evidence_kept: { type: "integer", required: true },
537
- evidence_dropped: { type: "integer", required: true },
538
- evidence_archived: { type: "integer", required: true },
539
- degraded: { type: "boolean", required: true }
540
- }
541
- },
542
- render: (_args, value) => {
543
- const sup = value.superseded_id ? ` (supersedes ${value.superseded_id})` : "";
544
- const ev = ` | evidence: ${value.evidence_kept} kept, ${value.evidence_dropped} dropped, ${value.evidence_archived} archived${value.degraded ? " [degraded]" : ""}`;
545
- return TEXT_OUTPUT(`document ${value.action}: ${value.id}${sup}${ev}`);
546
- }
547
- },
548
- async execute(args, exec) {
549
- // scope 标注与 memory_save 同款(#170):默认会话身份自动标注,显式
550
- // 参数逐维覆盖。校验/去重/supersede 全在 service.registerDocument。
551
- const scope = resolveSessionScope(exec);
552
- const autoStamping = config?.scopeEnabled === true;
553
- const agentLabel = args.agent_scope !== undefined
554
- ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
555
- : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
556
- const workspaceLabel = args.workspace_scope !== undefined
557
- ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
558
- : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
559
- // strictScope(#170 复核项 4 同款无存在性泄漏):他 scope 的 evidence id
560
- // 按「不存在」处理——注册器用全局 getById 求交,看不见的行在这里先标出,
561
- // 与 unknown/archived 同落 dropped,不进持久化 evidence(不得为跨 scope
562
- // id 建立引用)。
563
- const hiddenEvidence = [];
564
- if (config?.strictScope === true && scope && Array.isArray(args.evidence)) {
565
- for (const raw of args.evidence) {
566
- const id = String(raw ?? "").trim();
567
- if (!id) continue;
568
- const row = service.getById(id);
569
- if (row && !service.isVisibleInScope(row, scope)) hiddenEvidence.push(id);
570
- }
571
- }
572
- const result = await service.registerDocument({
573
- path: args.path,
574
- title: args.title,
575
- summary: args.summary,
576
- tags: args.tags ?? [],
577
- ...(args.importance !== undefined ? { importance: args.importance } : {}),
578
- evidence: args.evidence ?? [],
579
- source: args.source ?? "tool",
580
- ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
581
- ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
582
- ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {})
583
- }, {
584
- hiddenEvidenceIds: hiddenEvidence,
585
- // 默认开着归档(#275 拍板 5);agent 显式要保留活跃面时走 keep_evidence_active。
586
- archiveEvidence: args.keep_evidence_active !== true
587
- });
588
- return {
589
- action: result.action,
590
- id: result.memory.id,
591
- ...(result.superseded ? { superseded_id: result.superseded.id } : {}),
592
- evidence_kept: result.evidence_kept,
593
- evidence_dropped: result.evidence_dropped,
594
- evidence_archived: result.evidence_archived,
595
- degraded: result.degraded
596
- };
597
- }
598
- }),
599
-
600
- // 运行时口子(issue #131 / PR-C)。
601
- //
602
- // 为什么要有这个工具:mneme 的取向是「本体保持完善但轻量;重的功能存在、默认不开、不被依赖」。
603
- // 本地向量化就是那个重功能 —— 它需要额外一份运行时(解包后数百 MB)。面板上有按钮,但用户
604
- // 可能根本不看面板;这时 agent 需要一个入口,能先查状态、把代价告诉用户,再按需取回。
605
- //
606
- // 关于「要不要直接 provision」:它会联网、可能传几十到上百 MB、耗时数分钟。所以工具描述里
607
- // 明确要求先告知用户;只有在用户已经表示要本地向量化时才直接动手。
608
- defineTool({
609
- name: "memory_runtime",
610
- description:
611
- "Inspect or provision the LOCAL inference runtime that dsh-mneme's local (offline) embedding and rerank need: " +
612
- "the transformers + onnxruntime dependency closure, hundreds of MB unpacked. It is deliberately NOT a default " +
613
- "dependency — mneme's core stays lightweight and local vectorization is opt-in — so this tool is the hook that " +
614
- "makes the heavy capability available on demand. Use action=status first: it is read-only and reports whether " +
615
- "the runtime is ready plus what provisioning would cost. action=provision tries, in order: (1) adopting an " +
616
- "existing copy from this profile's node_modules (no network; hardlinked when on the same volume, so no extra " +
617
- "disk), (2) a configured local .tgz directory, (3) downloading from the npm registry against a pinned manifest, " +
618
- "verifying every tarball's sha512. Provisioning can transfer tens to hundreds of MB and take minutes: unless " +
619
- "the user has already asked for local vectorization, tell them that cost before calling it. action=verify loads " +
620
- "the runtime and runs one real inference (strictly offline, so the model must already be cached).",
621
- parameters: {
622
- action: { type: "string", enum: ["status", "provision", "verify"], required: true, description: "status = read-only; provision = fetch/adopt the runtime; verify = run one real inference" },
623
- overwrite: { type: "boolean", description: "provision only: replace an existing payload (use when repairing a broken one)" }
624
- },
625
- output: {
626
- schema: {
627
- type: "object",
628
- additionalProperties: false,
629
- properties: {
630
- summary: { type: "string", required: true },
631
- status: { type: "string", required: true },
632
- cost: { type: "string", required: true },
633
- strategy: { type: "string" },
634
- payloadId: { type: "string" },
635
- packages: { type: "integer" },
636
- files: { type: "integer" },
637
- bytes: { type: "integer" },
638
- dimension: { type: "integer" },
639
- reason: { type: "string" }
640
- }
641
- },
642
- render: (_args, value) => TEXT_OUTPUT(value.summary)
643
- },
644
- async execute(args) {
645
- const runtimeDir = config?.runtimeDir ?? "";
646
- const manifest = loadRuntimeManifest();
647
- const forPlatform = Array.isArray(manifest?.packages) ? manifest.packages.filter((pkg) => matchesPlatform(pkg, process.platform, process.arch)) : null;
648
- const cost =
649
- `Local vectorization needs an extra local inference runtime (transformers + onnxruntime closure, ` +
650
- `hundreds of MB unpacked${forPlatform ? `, ${forPlatform.length} packages for this platform` : ""}). ` +
651
- `It is not a default dependency: provisioning adopts an existing copy when possible, otherwise downloads it.`;
652
-
653
- if (args.action === "provision") {
654
- const result = await provisionRuntime({
655
- hostModulesDir: hostModulesDir(import.meta.url),
656
- runtimeDir,
657
- localTarballDir: config?.runtimeTarballDir ?? "",
658
- mirror: config?.runtimeMirror ?? "",
659
- overwrite: args.overwrite === true,
660
- manifest
661
- });
662
- return {
663
- summary: result.ok
664
- ? `Runtime ${result.strategy === "download" ? "downloaded from npm" : "adopted from this machine"}: ` +
665
- `${result.packages} packages / ${result.files} files. Local embedding can be used after a DSH reload.`
666
- : `Could not provision the runtime: ${result.reason}`,
667
- status: result.ok ? "available" : "failed",
668
- cost,
669
- strategy: result.strategy,
670
- ...(result.payloadId ? { payloadId: result.payloadId } : {}),
671
- ...(result.packages === undefined ? {} : { packages: result.packages }),
672
- ...(result.files === undefined ? {} : { files: result.files }),
673
- ...(result.bytes === undefined ? {} : { bytes: result.bytes }),
674
- ...(result.reason ? { reason: result.reason } : {})
675
- };
676
- }
677
-
678
- if (args.action === "verify") {
679
- const candidate = resolveRuntimeEntry({ runtimeDir: runtimeDir || undefined });
680
- if (candidate === null) {
681
- return { summary: "No usable runtime payload to verify.", status: "missing", cost };
682
- }
683
- const report = await verifyPayload(candidate.dir, { cacheDir: config?.embedModelCacheDir || undefined });
684
- return {
685
- summary: report.ok
686
- ? `Runtime verified: real inference succeeded (dim ${report.functional.dim}, ${report.functional.rows} rows, ` +
687
- `${report.functional.elapsedMs}ms, offline). Integrity: ${report.integrity.status}.`
688
- : `Runtime verification failed — structural: ${report.structural.ok}, functional: ${report.functional.ok} (${report.functional.reason}).`,
689
- status: report.ok ? "verified" : "failed",
690
- cost,
691
- payloadId: candidate.payloadId,
692
- ...(report.functional.dim ? { dimension: report.functional.dim } : {}),
693
- ...(report.ok ? {} : { reason: report.functional.reason })
694
- };
695
- }
696
-
697
- // status:只读,且刻意不加载模型(那要几百毫秒且碰缓存)。报告要给到 agent 足够的信息去
698
- // 决定「要不要打扰用户」。
699
- const report = describeLocalRuntime({ runtimeDir: runtimeDir || defaultRuntimeDir() });
700
- return {
701
- summary:
702
- `Local inference runtime: ${report.status}` +
703
- (report.payloadId ? ` (${report.payloadId}, ${report.procedure ?? "?"}, ${report.materialize ?? "?"})` : "") +
704
- `. ${report.status === "available" ? "Local embedding/rerank can be used." : "Local embedding is unavailable — " + (report.hint ?? "")}`,
705
- status: report.status,
706
- cost,
707
- ...(report.payloadId ? { payloadId: report.payloadId } : {}),
708
- ...(forPlatform ? { packages: forPlatform.length } : {}),
709
- ...(report.reason ? { reason: report.reason } : {})
710
- };
711
- }
712
- })
713
- ];
714
-
715
- // Tool-exposure gate (v0.8.5): 跨会话记忆已自动注入,memory_search /
716
- // memory_archive 在慢/轻量模型上是多余往返,面板开关可直接隐藏工具——
717
- // 模型看不到就不会调,比在描述里劝它少调用更可靠。注意:live patch reload
718
- // 下已注册的工具不会被宿主反注册,排除只对全新会话生效。
719
- const hiddenTools = new Set();
720
- if (config?.disableMemorySearch === true) hiddenTools.add("memory_search");
721
- if (config?.disableMemoryArchive === true) hiddenTools.add("memory_archive");
722
-
723
- for (const tool of tools) {
724
- if (hiddenTools.has(tool.name)) {
725
- ctx.logger?.info?.(`[dsh-mneme] tool "${tool.name}" hidden by config (disableMemorySearch/disableMemoryArchive)`);
726
- continue;
727
- }
728
- if (registeredTools.has(tool.name)) {
729
- ctx.logger?.warn?.(`[dsh-mneme] tool "${tool.name}" already registered, skipping duplicate`);
730
- continue;
731
- }
732
- registeredTools.add(tool.name);
733
- ctx.tools.register(tool);
734
- }
735
-
736
- return tools;
737
- }
1
+ import { defineTool } from "@deepseek-ai/dsh-tools";
2
+ import { createScopeResolver, normalizeExplicitScope, sessionKeyOf } 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
+
11
+ const TEXT_OUTPUT = (text) => [{ type: "text", text }];
12
+ // Per-registry tool-name registry: guards against duplicate registration on
13
+ // live patch reload (DSH Desktop `patchReload: "live"`) where a plugin may be
14
+ // re-applied on the same tools registry without an intervening unregister.
15
+ const REGISTERED_TOOLS = new WeakMap();
16
+
17
+ // Wire shape emitted by service.toApiList: shared by memory_search and
18
+ // memory_list so their output schemas always declare every key the runtime
19
+ // value carries (additionalProperties: false would reject undeclared keys).
20
+ const MEMORY_ITEM_SCHEMA = {
21
+ type: "object",
22
+ additionalProperties: false,
23
+ properties: {
24
+ id: { type: "string", required: true },
25
+ type: { type: "string", required: true },
26
+ title: { type: "string", required: true },
27
+ content: { type: "string", required: true },
28
+ tags: { type: "array", items: { type: "string" } },
29
+ importance: { type: "integer", required: true },
30
+ source: { type: "string" },
31
+ // v0.8.0 A2:scope 标注与事件发生时间随行透出(未标注时缺省,可选属性)。
32
+ // v0.8.1 底座:scope 来源(auto/explicit)与决策时间随行透出(同样可选)。
33
+ agent_scope: { type: "string" },
34
+ workspace_scope: { type: "string" },
35
+ agent_scope_source: { type: "string" },
36
+ workspace_scope_source: { type: "string" },
37
+ scope_decided_at: { type: "string" },
38
+ sensitivity: { type: "string" },
39
+ occurred_at: { type: "string" },
40
+ // #230:document 指针行的文件定位——「全文按需读」的入口;普通行缺省。
41
+ doc_path: { type: "string" },
42
+ created_at: { type: "string", required: true },
43
+ updated_at: { type: "string", required: true }
44
+ }
45
+ };
46
+ // 导出供回归测试断言 memory_get 与共享 schema 同源(#184 防漂移护栏)。
47
+ export { MEMORY_ITEM_SCHEMA };
48
+
49
+ // v0.8.0 A2:occurred 时间窗参数 → store 过滤选项(list/count 同口径);
50
+ // 未传参返回空对象,既有调用方不受影响。(A3 复核:此处入参仅含 occurred 边界。)
51
+ function occurredWindow(args) {
52
+ const from = args?.occurred_from ?? null;
53
+ const to = args?.occurred_to ?? null;
54
+ return from !== null || to !== null ? { occurredFrom: from, occurredTo: to } : {};
55
+ }
56
+
57
+ // v0.8.0 A3:strictScope 硬过滤的 visibility 选项(store.list/count 同口径)。
58
+ // flag 关或会话 scope 未解析出(flag 关时解析器返回 null)→ 空对象不过滤;
59
+ // scope 为 {null,null}(匿名会话)时照传——store 侧 fail-closed 只放行未标注行。
60
+ function strictVisibility(config, scope) {
61
+ if (config?.strictScope !== true || !scope) return {};
62
+ return { visibility: { agentScope: scope.agent_scope, workspaceScope: scope.workspace_scope } };
63
+ }
64
+
65
+ // v0.8.0 A2:检索结果的 provenance 附加段——只在有标注时出现,未标注行渲染
66
+ // 与 A2 前逐字节一致。
67
+ const MEMORY_PROVENANCE = (m) => {
68
+ const parts = [];
69
+ if (m.occurred_at) parts.push(`occurred: ${m.occurred_at}`);
70
+ if (m.agent_scope || m.workspace_scope) {
71
+ parts.push(`scope: ${m.agent_scope ?? "global"} / ${m.workspace_scope ?? "global"}`);
72
+ }
73
+ if (m.sensitivity) parts.push(`sensitivity: ${m.sensitivity}`);
74
+ return parts.length ? ` | ${parts.join(" | ")}` : "";
75
+ };
76
+
77
+ export function createTools(ctx, service, config, embedder) {
78
+ const toolsRegistry = ctx.tools;
79
+ let registeredTools = REGISTERED_TOOLS.get(toolsRegistry);
80
+ if (!registeredTools) {
81
+ registeredTools = new Set();
82
+ REGISTERED_TOOLS.set(toolsRegistry, registeredTools);
83
+ }
84
+ // v0.8.0 A1/A2(issue #17):会话 scope 解析(agentPreset + workspace 反查)。
85
+ // flag 关闭时恒返回 null——写入不标注,检索不加权,行为与 A1 前完全一致。
86
+ // logger 透传:registry 反查失败时 warnOnce 才有出口(否则静默降级无观测)。
87
+ const resolveSessionScope = createScopeResolver({ ctx, config, logger: ctx.logger });
88
+ // #249 能力说明(injectGuidanceEnabled):开启时给「何时用」最有歧义的两个
89
+ // 工具补一句判断指引。工具描述常驻、不进每轮上下文,这个位子零注入成本;
90
+ // 关闭时描述逐字节不变,也不动其他工具的文案。
91
+ // 它是注入父开关的子项(#249 第二批):`autoInject` 关掉时这里同样不生效——
92
+ // 工具描述是这个子项唯一住在注入器之外的落点,不在闸门内就漏了。
93
+ // #249 N3 降级路径(continuityRescueEnabled):宿主若不提供可挂钩的压缩前时机,
94
+ // 双落点里的注入那一半就没有触发者,这时把规则交给 agent 自判(见 CONTINUITY_TOOL_RULE)。
95
+ // 与能力说明各自独立:任一开关关闭时描述逐字节不变。
96
+ // 本批不做宿主能力探测(没有可靠的探测口),所以子开关打开时这条规则常驻,与自动双落点并存。
97
+ const withToolGuide = (name, description) => {
98
+ let text = description;
99
+ if (injectChildEnabled(config, "injectGuidanceEnabled") && TOOL_GUIDE[name]) text += TOOL_GUIDE[name];
100
+ if (injectChildEnabled(config, "continuityRescueEnabled") && CONTINUITY_TOOL_RULE[name]) text += CONTINUITY_TOOL_RULE[name];
101
+ return text;
102
+ };
103
+
104
+ // 复核项 4(issue #170):strictScope 下他 scope(explicit)的行对工具侧按
105
+ // 「不存在」处理——update/delete 与 memory_get 同款无存在性泄漏。strictScope
106
+ // 关、或会话身份取不到(scope 为 null)时恒可见(与 get 的短路语义一致)。
107
+ const visibleUnderStrictScope = (memory, exec) => {
108
+ if (config?.strictScope !== true) return true;
109
+ const scope = resolveSessionScope(exec);
110
+ return !scope || service.isVisibleInScope(memory, scope);
111
+ };
112
+ // 在调用点以「展开恒为 undefined」的形态前置校验(抛错即中止写入)。
113
+ const assertVisibleForTool = (id, exec) => {
114
+ const memory = id ? service.getById(id) : undefined;
115
+ if (!visibleUnderStrictScope(memory, exec)) throw new Error("memory not found");
116
+ return undefined;
117
+ };
118
+ // delete 侧需要目标行本身判断存在性(不可见 = 视作不存在,不抛错)。
119
+ const visibleForTool = (id, exec) => {
120
+ const memory = id ? service.getById(id) : undefined;
121
+ return visibleUnderStrictScope(memory, exec) ? memory : undefined;
122
+ };
123
+ const tools = [
124
+ defineTool({
125
+ name: "memory_save",
126
+ description: withToolGuide(
127
+ "memory_save",
128
+ "Persist one memory entry for future sessions (user preferences, project state, decisions). " +
129
+ "Call this when the user states a durable preference, a project decision is made, or a lesson is learned. " +
130
+ "Merges into an existing entry of the same type when the title matches."
131
+ ),
132
+ parameters: {
133
+ // document 不在此列(#230):document 行只能经 memory_register_document
134
+ // 铸造(注册校验 + doc_path + evidence),防止 memory_save 造出无指针
135
+ // 无回链的伪行。
136
+ 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" },
137
+ title: { type: "string", required: true, description: "Short unique title" },
138
+ content: { type: "string", required: true, description: "Memory body" },
139
+ tags: { type: "array", items: { type: "string" }, description: "Optional tags" },
140
+ importance: { type: "integer", description: "1-5; >= threshold auto-injects into future sessions" },
141
+ source: { type: "string", description: "Optional provenance" },
142
+ sensitivity: { type: "string", description: "Optional sensitivity label (free-form, e.g. personal). Same-title entries with different sensitivity stay separate instead of merging." },
143
+ occurred_at: { type: "string", description: "Optional ISO-8601 instant the remembered event happened (differs from write time). Invalid values are ignored." },
144
+ 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." },
145
+ 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." }
146
+ },
147
+ output: {
148
+ schema: {
149
+ type: "object",
150
+ additionalProperties: false,
151
+ properties: {
152
+ action: { type: "string", required: true, enum: ["created", "merged", "denied"] },
153
+ // denied 时压根没有行可指,所以 id 缺省而不是空串:空串会让「写成功但
154
+ // id 为空」与「根本没写」在读回执时长得一样,与 #254 验收第 2 条
155
+ // (被拒写入可解释、不静默丢弃)相悖。
156
+ id: { type: "string", description: "Row id; absent when action=denied." },
157
+ reason: { type: "string", description: "Rejection reason when action=denied: blank | noise | sensitive." }
158
+ }
159
+ },
160
+ render: (_args, value) => TEXT_OUTPUT(value.action === "denied"
161
+ ? `memory save rejected (${value.reason ?? "denied"}): nothing was written`
162
+ : `memory ${value.action}: ${value.id}`)
163
+ },
164
+ async execute(args, exec) {
165
+ // scope 标注(v0.8.1 底座,issue #170):默认由会话身份解析(载体自动
166
+ // 标注,盖 auto 章);显式 agent_scope/workspace_scope 参数逐维覆盖并盖
167
+ // explicit 章。解析绝不抛错、取不到落 NULL。
168
+ // 复核项 2(#170):scopeEnabled 只门控「自动标注」分支——显式声明与
169
+ // 读取身份(search/list/get/注入经同一解析器)不受 flag 限制,否则
170
+ // strictScope 硬墙会被 flag 静默拆掉(fail-open)。
171
+ // (存储 NULL,由 source 列与「从未标注」区分)。非字符串参数在工具
172
+ // 入参 schema 层即被拒(type: "string")——脏值到不了归一化,无静默放宽。
173
+ const scope = resolveSessionScope(exec);
174
+ const autoStamping = config?.scopeEnabled === true;
175
+ const agentLabel = args.agent_scope !== undefined
176
+ ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
177
+ : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
178
+ const workspaceLabel = args.workspace_scope !== undefined
179
+ ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
180
+ : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
181
+ const result = service.saveWithDedupe({
182
+ // #254 写入准入的计数单位:会话键作为瞬时字段随写入传递(与 _mergeInto /
183
+ // _overwrite 同款约定,不落库)。缺会话身份的宿主返回 null = 这次写入不进
184
+ // 预算;系统写入(dream / summarize / organize)从不带这个字段。
185
+ _sessionKey: sessionKeyOf(exec),
186
+ type: args.type,
187
+ title: args.title,
188
+ content: args.content,
189
+ tags: args.tags ?? [],
190
+ importance: args.importance ?? 3,
191
+ source: args.source ?? "tool",
192
+ ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
193
+ ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {}),
194
+ ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
195
+ ...(args.occurred_at !== undefined ? { occurred_at: args.occurred_at } : {})
196
+ });
197
+ // #254 第 1 级硬拒:工具层是模型唯一能看到这次失败的地方,必须显式回一句
198
+ // 可行动的拒绝理由。静默返回成功会让模型以为记住了,然后永远不再重写。
199
+ if (result.action === "denied") return { action: "denied", reason: result.reason };
200
+ return { action: result.action, id: result.memory.id };
201
+ }
202
+ }),
203
+
204
+ defineTool({
205
+ name: "memory_search",
206
+ description: withToolGuide(
207
+ "memory_search",
208
+ "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."
209
+ ),
210
+ // A2 检索接线:occurred 时间窗 + 会话 scope 加成(见 execute)。
211
+ parameters: {
212
+ query: { type: "string", required: true, description: "Search text; substring match over title/content/tags" },
213
+ limit: { type: "integer", description: "Max results (default 20)" },
214
+ 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" },
215
+ semantic: { type: "boolean", description: "Shorthand: enable semantic (vector) recall (same as mode=vector when true)" },
216
+ rerank: { type: "boolean", description: "Run cross-encoder rerank over candidates when a local reranker is configured (default true)" },
217
+ 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." },
218
+ 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." }
219
+ },
220
+ output: {
221
+ schema: {
222
+ type: "object",
223
+ additionalProperties: false,
224
+ properties: {
225
+ items: {
226
+ type: "array", required: true,
227
+ items: MEMORY_ITEM_SCHEMA
228
+ }
229
+ }
230
+ },
231
+ render: (_args, value) => {
232
+ const items = value.items ?? [];
233
+ if (items.length === 0) return TEXT_OUTPUT("No memory entries found.");
234
+ const body = items
235
+ .map((m, i) => {
236
+ const preview = (m.content ?? "").replace(/\s+/g, " ").trim();
237
+ const cut = preview.length > 200 ? `${preview.slice(0, 200)}…` : preview;
238
+ return `[${i + 1}] ${m.title}\n ID: ${m.id} | type: ${m.type} | importance: ${m.importance} | updated: ${m.updated_at}${MEMORY_PROVENANCE(m)}\n ${cut}`;
239
+ })
240
+ .join("\n\n");
241
+ return TEXT_OUTPUT(`Found ${items.length} memory entr${items.length === 1 ? "y" : "ies"}:\n\n${body}`);
242
+ }
243
+ },
244
+ async execute(args, exec) {
245
+ const limit = args.limit ?? 20;
246
+ const mode = args.semantic === true && !args.mode ? "vector" : args.mode ?? "auto";
247
+ // v0.8.0 A2(issue #17):scope 检索加权 + occurred 时间窗的检索接线。
248
+ // flag 关闭或解析不出 scope 时为 null,检索行为与 A2 前一致。
249
+ const scope = resolveSessionScope(exec);
250
+ const occurredFrom = args.occurred_from ?? null;
251
+ const occurredTo = args.occurred_to ?? null;
252
+ const rows = await service.searchMemories(args.query, {
253
+ mode,
254
+ topK: limit,
255
+ useRerank: args.rerank !== false,
256
+ ...(scope ? { scope } : {}),
257
+ ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
258
+ });
259
+ return { items: service.toApiList(rows) };
260
+ }
261
+ }),
262
+
263
+ defineTool({
264
+ name: "memory_list",
265
+ 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.",
266
+ parameters: {
267
+ 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" },
268
+ limit: { type: "integer", description: "Page size (default 50)" },
269
+ offset: { type: "integer", description: "Page offset (default 0)" },
270
+ include_archived: { type: "boolean", description: "Include archived (hidden) entries so they can be found and restored (default false)" },
271
+ 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." },
272
+ 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." }
273
+ },
274
+ output: {
275
+ schema: {
276
+ type: "object",
277
+ additionalProperties: false,
278
+ properties: {
279
+ items: {
280
+ type: "array", required: true,
281
+ items: MEMORY_ITEM_SCHEMA
282
+ },
283
+ total: { type: "integer", required: true }
284
+ }
285
+ },
286
+ render: (_args, value) => {
287
+ const items = value.items ?? [];
288
+ if (items.length === 0) return TEXT_OUTPUT(`0 memory entries (of ${value.total}).`);
289
+ const body = items
290
+ .map((m, i) => `[${i + 1}] ${m.title} (type=${m.type}, importance=${m.importance})\n ID: ${m.id} | updated: ${m.updated_at}${MEMORY_PROVENANCE(m)}`)
291
+ .join("\n\n");
292
+ return TEXT_OUTPUT(`${items.length} memory entries (of ${value.total}):\n\n${body}`);
293
+ }
294
+ },
295
+ async execute(args) {
296
+ const includeArchived = args.include_archived === true;
297
+ const rows = service.toApiList(service.list({
298
+ type: args.type,
299
+ limit: args.limit ?? 50,
300
+ offset: args.offset ?? 0,
301
+ includeArchived,
302
+ ...occurredWindow(args),
303
+ // A3:strict 开启时按会话 scope 硬过滤(宿主按 (args, runContext) 调用,
304
+ // 从 arguments 取第二参)。
305
+ ...strictVisibility(config, resolveSessionScope(arguments[1]))
306
+ }));
307
+ return { items: rows, total: service.count(args.type, { includeArchived, ...occurredWindow(args), ...strictVisibility(config, resolveSessionScope(arguments[1])) }) };
308
+ }
309
+ }),
310
+
311
+ defineTool({
312
+ name: "memory_get",
313
+ description: "Fetch one memory entry by ID and return its full content as text. Use after memory_list to read a specific entry.",
314
+ parameters: {
315
+ id: { type: "string", required: true, description: "Memory id" }
316
+ },
317
+ output: {
318
+ schema: {
319
+ type: "object",
320
+ additionalProperties: false,
321
+ properties: {
322
+ // 与 memory_search / memory_list 共用同一份 item schema——DTO 由
323
+ // toApiList 统一产出,内联副本曾漏掉 v0.8.1 的 scope 来源三键,
324
+ // 任何被标注过的行都过不了 in-process 校验(#184)。
325
+ memory: MEMORY_ITEM_SCHEMA
326
+ }
327
+ },
328
+ render: (_args, value) => {
329
+ const m = value.memory;
330
+ // #230:document 指针行把文件路径亮在首行——「全文按需读」从这里拿路径。
331
+ const doc = m.doc_path ? ` | doc: ${m.doc_path}` : "";
332
+ return TEXT_OUTPUT(`${m.title}\nID: ${m.id} | type: ${m.type} | importance: ${m.importance}${doc}${MEMORY_PROVENANCE(m)}\n\n${m.content}`);
333
+ }
334
+ },
335
+ async execute(args) {
336
+ const memory = service.getById(args.id);
337
+ if (memory === undefined) throw new Error("memory not found");
338
+ // v0.8.0 A3:strictScope 下他 scope 的行按不存在处理(无存在性泄漏)。
339
+ // 宿主注册表按 (args, runContext) 两参调用处理器,从 arguments 取第二参。
340
+ const runContext = arguments[1];
341
+ const scope = resolveSessionScope(runContext);
342
+ if (config.strictScope === true && scope && !service.isVisibleInScope(memory, scope)) {
343
+ throw new Error("memory not found");
344
+ }
345
+ return { memory: service.toApiList([memory])[0] };
346
+ }
347
+ }),
348
+
349
+ defineTool({
350
+ name: "memory_update",
351
+ description: "Modify an existing memory entry (title, content, type, tags, importance).",
352
+ parameters: {
353
+ id: { type: "string", required: true, description: "Memory id" },
354
+ title: { type: "string" },
355
+ content: { type: "string" },
356
+ // document 不在此列(#230):type 不许改入 document——既有 document 行
357
+ // 的摘要修复(只改 content/title)不受影响。
358
+ type: { type: "string", enum: ["preference", "project", "decision", "history", "rejected_solution", "pitfall", "constraint"] },
359
+ tags: { type: "array", items: { type: "string" } },
360
+ importance: { type: "integer", description: "1-5" },
361
+ reason: { type: "string", description: "Optional context for the correction (what the user actually said/wanted), recorded for reflection" },
362
+ 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)." },
363
+ 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)." }
364
+ },
365
+ output: {
366
+ schema: {
367
+ type: "object",
368
+ additionalProperties: false,
369
+ properties: {
370
+ memory: {
371
+ type: "object",
372
+ additionalProperties: false,
373
+ properties: {
374
+ id: { type: "string", required: true },
375
+ title: { type: "string", required: true },
376
+ content: { type: "string", required: true }
377
+ }
378
+ }
379
+ }
380
+ },
381
+ render: (_args, value) => TEXT_OUTPUT(`Updated memory ${value.memory.id}: ${value.memory.title}`)
382
+ },
383
+ async execute(args) {
384
+ const memory = service.update(args.id, {
385
+ title: args.title,
386
+ content: args.content,
387
+ type: args.type,
388
+ tags: args.tags,
389
+ importance: args.importance,
390
+ // 复核项 4(#170):strictScope 下他 scope 的行按「不存在」处理(与 get 对齐),
391
+ // 展开恒为 undefined,仅承担写入前校验。
392
+ ...(assertVisibleForTool(args.id, arguments[1])),
393
+ ...(args.agent_scope !== undefined ? { agent_scope: args.agent_scope } : {}),
394
+ ...(args.workspace_scope !== undefined ? { workspace_scope: args.workspace_scope } : {})
395
+ }, { query: args.reason });
396
+ return { memory: { id: memory.id, title: memory.title, content: memory.content } };
397
+ }
398
+ }),
399
+
400
+ defineTool({
401
+ name: "memory_delete",
402
+ description: "Permanently delete a memory entry.",
403
+ parameters: {
404
+ id: { type: "string", required: true }
405
+ },
406
+ output: {
407
+ schema: {
408
+ type: "object",
409
+ additionalProperties: false,
410
+ properties: { deleted: { type: "boolean", required: true } }
411
+ },
412
+ render: (_args, value) => TEXT_OUTPUT(value.deleted ? "Memory deleted." : "Memory not found.")
413
+ },
414
+ async execute(args) {
415
+ // 复核项 4(#170):不可见(explicit 他 scope)= 视作不存在,无存在性泄漏。
416
+ const target = visibleForTool(args.id, arguments[1]);
417
+ if (target) service.remove(args.id);
418
+ return { deleted: !!target };
419
+ }
420
+ }),
421
+
422
+ defineTool({
423
+ name: "memory_forget",
424
+ description:
425
+ "Stop a memory from being auto-injected and from appearing in searches and lists without deleting it. " +
426
+ "The entry stays in storage; pass forgotten: false to restore it.",
427
+ parameters: {
428
+ id: { type: "string", required: true },
429
+ forgotten: { type: "boolean", description: "Suppress (true, default) or restore (false) the entry's visibility" }
430
+ },
431
+ output: {
432
+ schema: {
433
+ type: "object",
434
+ additionalProperties: false,
435
+ properties: {
436
+ memory: {
437
+ type: "object",
438
+ additionalProperties: false,
439
+ properties: {
440
+ id: { type: "string", required: true },
441
+ forgotten: { type: "boolean", required: true }
442
+ }
443
+ }
444
+ }
445
+ },
446
+ render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} injection ${value.memory.forgotten ? "suppressed" : "restored"}.`)
447
+ },
448
+ async execute(args) {
449
+ if (service.getById(args.id) === undefined) {
450
+ throw new Error("memory not found");
451
+ }
452
+ const memory = service.setForget(args.id, args.forgotten ?? true);
453
+ return { memory: { id: memory.id, forgotten: memory.forgotten } };
454
+ }
455
+ }),
456
+
457
+ defineTool({
458
+ name: "memory_archive",
459
+ description:
460
+ "Archive a memory (hide it from active lists, search, injection and dream consolidation) or restore it. " +
461
+ "Archived entries stay in storage and are recoverable: pass archived=false to restore, and use memory_list with " +
462
+ "include_archived=true to find archived entries. " +
463
+ "Only archive when the user asks, or an entry is clearly stale/no longer relevant — do not archive proactively mid-session to tidy up.",
464
+ parameters: {
465
+ id: { type: "string", required: true, description: "Memory id" },
466
+ archived: { type: "boolean", description: "Archive (true, default) or restore (false) the entry" }
467
+ },
468
+ output: {
469
+ schema: {
470
+ type: "object",
471
+ additionalProperties: false,
472
+ properties: {
473
+ memory: {
474
+ type: "object",
475
+ additionalProperties: false,
476
+ properties: {
477
+ id: { type: "string", required: true },
478
+ archived: { type: "boolean", required: true }
479
+ }
480
+ }
481
+ }
482
+ },
483
+ render: (_args, value) => TEXT_OUTPUT(`Memory ${value.memory.id} ${value.memory.archived ? "archived" : "restored"}.`)
484
+ },
485
+ async execute(args) {
486
+ if (service.getById(args.id) === undefined) {
487
+ throw new Error("memory not found");
488
+ }
489
+ const memory = service.setArchived(args.id, args.archived ?? true);
490
+ return { memory: { id: memory.id, archived: memory.archived } };
491
+ }
492
+ }),
493
+
494
+ // #230(#164 设计稿评审线):document 型记忆注册——agent 产长文档的指针
495
+ // 行铸造口。写入权分离:全文归 agent(管线对文件零读零写零改),库里只
496
+ // 存摘要 + doc_path + evidence 三样;C2 比对去重、supersede 记账在
497
+ // service.registerDocument(src/document.js)内完成。判断指引:调研报告/
498
+ // 设计稿/长整理产物「存外档」用本工具;原子事实(偏好/决策/教训)仍走
499
+ // memory_save;tag 与章节名建议用英文(跨语言稳定键),摘要正文可多语言。
500
+ defineTool({
501
+ name: "memory_register_document",
502
+ description:
503
+ "Register an agent-authored document (research report, design doc, long digest) into memory as a pointer row. " +
504
+ "Write-ownership split: the full text stays agent-owned on disk — the pipeline never reads or rewrites it; the DB " +
505
+ "stores only the summary + doc_path + evidence. Validates the file exists (absolute path, non-empty regular file), " +
506
+ "intersects evidence with real memory ids (all-fabricated evidence is rejected; unknown ids are dropped and the row " +
507
+ "is tagged evidence_degraded), and dedupes: re-registering the same path or title supersedes the old row (the old " +
508
+ "file is never touched; content_history stays traceable), while a merely near-duplicate summary of a different " +
509
+ "document row is rejected — update that row instead. On success the absorbed atomic evidence rows leave the active " +
510
+ "face in the same transaction (recoverable, nothing deleted); constraint/preference rows and other " +
511
+ "document/summary rows are never auto-archived, and keep_evidence_active: true opts out. Ids this same document " +
512
+ "absorbed on an earlier version still count as its evidence, so re-registering a new version is not read as " +
513
+ "fabricated evidence. Use for 'where is the conclusion doc for this project?' " +
514
+ "lookups; atomic facts still go to memory_save.",
515
+ parameters: {
516
+ 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." },
517
+ title: { type: "string", required: true, description: "Short unique title (English recommended: it is the cross-language stable dedupe/supersede key)" },
518
+ summary: { type: "string", required: true, description: "One-paragraph summary stored in the DB and used for injection (any language)" },
519
+ tags: { type: "array", items: { type: "string" }, description: "Optional tags (English recommended)" },
520
+ importance: { type: "integer", description: "1-5 (default 3); the summary row injects at the next-priority tier within documentInjectBudget when importance >= threshold" },
521
+ 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." },
522
+ 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)." },
523
+ source: { type: "string", description: "Optional provenance" },
524
+ 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." },
525
+ 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." },
526
+ 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." }
527
+ },
528
+ output: {
529
+ schema: {
530
+ type: "object",
531
+ additionalProperties: false,
532
+ properties: {
533
+ action: { type: "string", required: true, enum: ["created", "superseded"] },
534
+ id: { type: "string", required: true },
535
+ superseded_id: { type: "string" },
536
+ evidence_kept: { type: "integer", required: true },
537
+ evidence_dropped: { type: "integer", required: true },
538
+ evidence_archived: { type: "integer", required: true },
539
+ degraded: { type: "boolean", required: true }
540
+ }
541
+ },
542
+ render: (_args, value) => {
543
+ const sup = value.superseded_id ? ` (supersedes ${value.superseded_id})` : "";
544
+ const ev = ` | evidence: ${value.evidence_kept} kept, ${value.evidence_dropped} dropped, ${value.evidence_archived} archived${value.degraded ? " [degraded]" : ""}`;
545
+ return TEXT_OUTPUT(`document ${value.action}: ${value.id}${sup}${ev}`);
546
+ }
547
+ },
548
+ async execute(args, exec) {
549
+ // scope 标注与 memory_save 同款(#170):默认会话身份自动标注,显式
550
+ // 参数逐维覆盖。校验/去重/supersede 全在 service.registerDocument。
551
+ const scope = resolveSessionScope(exec);
552
+ const autoStamping = config?.scopeEnabled === true;
553
+ const agentLabel = args.agent_scope !== undefined
554
+ ? { value: normalizeExplicitScope(args.agent_scope), source: "explicit" }
555
+ : autoStamping && scope ? { value: scope.agent_scope, source: "auto" } : null;
556
+ const workspaceLabel = args.workspace_scope !== undefined
557
+ ? { value: normalizeExplicitScope(args.workspace_scope), source: "explicit" }
558
+ : autoStamping && scope ? { value: scope.workspace_scope, source: "auto" } : null;
559
+ // strictScope(#170 复核项 4 同款无存在性泄漏):他 scope 的 evidence id
560
+ // 按「不存在」处理——注册器用全局 getById 求交,看不见的行在这里先标出,
561
+ // 与 unknown/archived 同落 dropped,不进持久化 evidence(不得为跨 scope
562
+ // id 建立引用)。
563
+ const hiddenEvidence = [];
564
+ if (config?.strictScope === true && scope && Array.isArray(args.evidence)) {
565
+ for (const raw of args.evidence) {
566
+ const id = String(raw ?? "").trim();
567
+ if (!id) continue;
568
+ const row = service.getById(id);
569
+ if (row && !service.isVisibleInScope(row, scope)) hiddenEvidence.push(id);
570
+ }
571
+ }
572
+ const result = await service.registerDocument({
573
+ path: args.path,
574
+ title: args.title,
575
+ summary: args.summary,
576
+ tags: args.tags ?? [],
577
+ ...(args.importance !== undefined ? { importance: args.importance } : {}),
578
+ evidence: args.evidence ?? [],
579
+ source: args.source ?? "tool",
580
+ ...(args.sensitivity !== undefined ? { sensitivity: args.sensitivity } : {}),
581
+ ...(agentLabel ? { agent_scope: agentLabel.value, agent_scope_source: agentLabel.source } : {}),
582
+ ...(workspaceLabel ? { workspace_scope: workspaceLabel.value, workspace_scope_source: workspaceLabel.source } : {})
583
+ }, {
584
+ hiddenEvidenceIds: hiddenEvidence,
585
+ // 默认开着归档(#275 拍板 5);agent 显式要保留活跃面时走 keep_evidence_active。
586
+ archiveEvidence: args.keep_evidence_active !== true
587
+ });
588
+ return {
589
+ action: result.action,
590
+ id: result.memory.id,
591
+ ...(result.superseded ? { superseded_id: result.superseded.id } : {}),
592
+ evidence_kept: result.evidence_kept,
593
+ evidence_dropped: result.evidence_dropped,
594
+ evidence_archived: result.evidence_archived,
595
+ degraded: result.degraded
596
+ };
597
+ }
598
+ }),
599
+
600
+ // 运行时口子(issue #131 / PR-C)。
601
+ //
602
+ // 为什么要有这个工具:mneme 的取向是「本体保持完善但轻量;重的功能存在、默认不开、不被依赖」。
603
+ // 本地向量化就是那个重功能 —— 它需要额外一份运行时(解包后数百 MB)。面板上有按钮,但用户
604
+ // 可能根本不看面板;这时 agent 需要一个入口,能先查状态、把代价告诉用户,再按需取回。
605
+ //
606
+ // 关于「要不要直接 provision」:它会联网、可能传几十到上百 MB、耗时数分钟。所以工具描述里
607
+ // 明确要求先告知用户;只有在用户已经表示要本地向量化时才直接动手。
608
+ defineTool({
609
+ name: "memory_runtime",
610
+ description:
611
+ "Inspect or provision the LOCAL inference runtime that dsh-mneme's local (offline) embedding and rerank need: " +
612
+ "the transformers + onnxruntime dependency closure, hundreds of MB unpacked. It is deliberately NOT a default " +
613
+ "dependency — mneme's core stays lightweight and local vectorization is opt-in — so this tool is the hook that " +
614
+ "makes the heavy capability available on demand. Use action=status first: it is read-only and reports whether " +
615
+ "the runtime is ready plus what provisioning would cost. action=provision tries, in order: (1) adopting an " +
616
+ "existing copy from this profile's node_modules (no network; hardlinked when on the same volume, so no extra " +
617
+ "disk), (2) a configured local .tgz directory, (3) downloading from the npm registry against a pinned manifest, " +
618
+ "verifying every tarball's sha512. Provisioning can transfer tens to hundreds of MB and take minutes: unless " +
619
+ "the user has already asked for local vectorization, tell them that cost before calling it. action=verify loads " +
620
+ "the runtime and runs one real inference (strictly offline, so the model must already be cached).",
621
+ parameters: {
622
+ action: { type: "string", enum: ["status", "provision", "verify"], required: true, description: "status = read-only; provision = fetch/adopt the runtime; verify = run one real inference" },
623
+ overwrite: { type: "boolean", description: "provision only: replace an existing payload (use when repairing a broken one)" }
624
+ },
625
+ output: {
626
+ schema: {
627
+ type: "object",
628
+ additionalProperties: false,
629
+ properties: {
630
+ summary: { type: "string", required: true },
631
+ status: { type: "string", required: true },
632
+ cost: { type: "string", required: true },
633
+ strategy: { type: "string" },
634
+ payloadId: { type: "string" },
635
+ packages: { type: "integer" },
636
+ files: { type: "integer" },
637
+ bytes: { type: "integer" },
638
+ dimension: { type: "integer" },
639
+ reason: { type: "string" }
640
+ }
641
+ },
642
+ render: (_args, value) => TEXT_OUTPUT(value.summary)
643
+ },
644
+ async execute(args) {
645
+ const runtimeDir = config?.runtimeDir ?? "";
646
+ const manifest = loadRuntimeManifest();
647
+ const forPlatform = Array.isArray(manifest?.packages) ? manifest.packages.filter((pkg) => matchesPlatform(pkg, process.platform, process.arch)) : null;
648
+ const cost =
649
+ `Local vectorization needs an extra local inference runtime (transformers + onnxruntime closure, ` +
650
+ `hundreds of MB unpacked${forPlatform ? `, ${forPlatform.length} packages for this platform` : ""}). ` +
651
+ `It is not a default dependency: provisioning adopts an existing copy when possible, otherwise downloads it.`;
652
+
653
+ if (args.action === "provision") {
654
+ const result = await provisionRuntime({
655
+ hostModulesDir: hostModulesDir(import.meta.url),
656
+ runtimeDir,
657
+ localTarballDir: config?.runtimeTarballDir ?? "",
658
+ mirror: config?.runtimeMirror ?? "",
659
+ overwrite: args.overwrite === true,
660
+ manifest
661
+ });
662
+ return {
663
+ summary: result.ok
664
+ ? `Runtime ${result.strategy === "download" ? "downloaded from npm" : "adopted from this machine"}: ` +
665
+ `${result.packages} packages / ${result.files} files. Local embedding can be used after a DSH reload.`
666
+ : `Could not provision the runtime: ${result.reason}`,
667
+ status: result.ok ? "available" : "failed",
668
+ cost,
669
+ strategy: result.strategy,
670
+ ...(result.payloadId ? { payloadId: result.payloadId } : {}),
671
+ ...(result.packages === undefined ? {} : { packages: result.packages }),
672
+ ...(result.files === undefined ? {} : { files: result.files }),
673
+ ...(result.bytes === undefined ? {} : { bytes: result.bytes }),
674
+ ...(result.reason ? { reason: result.reason } : {})
675
+ };
676
+ }
677
+
678
+ if (args.action === "verify") {
679
+ const candidate = resolveRuntimeEntry({ runtimeDir: runtimeDir || undefined });
680
+ if (candidate === null) {
681
+ return { summary: "No usable runtime payload to verify.", status: "missing", cost };
682
+ }
683
+ // 验的必须是用户真实在用的那一份:缓存目录与嵌入模型都跟配置走。空目录交给 verify
684
+ // 自己补默认值(「空 = ~/.dsh/mneme/models」是配置与文档的约定,嵌入侧同一份解析);
685
+ // 模型不给会让 verify 恒探默认小模型,用户换了模型时这份结论就不是他实际使用的那份(#387)。
686
+ const report = await verifyPayload(candidate.dir, {
687
+ cacheDir: config?.embedModelCacheDir,
688
+ model: config?.localEmbedModel || undefined
689
+ });
690
+ return {
691
+ summary: report.ok
692
+ ? `Runtime verified: real inference succeeded (dim ${report.functional.dim}, ${report.functional.rows} rows, ` +
693
+ `${report.functional.elapsedMs}ms, offline). Integrity: ${report.integrity.status}.`
694
+ : `Runtime verification failed — structural: ${report.structural.ok}, functional: ${report.functional.ok} (${report.functional.reason}).`,
695
+ status: report.ok ? "verified" : "failed",
696
+ cost,
697
+ payloadId: candidate.payloadId,
698
+ ...(report.functional.dim ? { dimension: report.functional.dim } : {}),
699
+ ...(report.ok ? {} : { reason: report.functional.reason })
700
+ };
701
+ }
702
+
703
+ // status:只读,且刻意不加载模型(那要几百毫秒且碰缓存)。报告要给到 agent 足够的信息去
704
+ // 决定「要不要打扰用户」。
705
+ const report = describeLocalRuntime({ runtimeDir: runtimeDir || defaultRuntimeDir() });
706
+ return {
707
+ summary:
708
+ `Local inference runtime: ${report.status}` +
709
+ (report.payloadId ? ` (${report.payloadId}, ${report.procedure ?? "?"}, ${report.materialize ?? "?"})` : "") +
710
+ `. ${report.status === "available" ? "Local embedding/rerank can be used." : "Local embedding is unavailable — " + (report.hint ?? "")}`,
711
+ status: report.status,
712
+ cost,
713
+ ...(report.payloadId ? { payloadId: report.payloadId } : {}),
714
+ ...(forPlatform ? { packages: forPlatform.length } : {}),
715
+ ...(report.reason ? { reason: report.reason } : {})
716
+ };
717
+ }
718
+ })
719
+ ];
720
+
721
+ // Tool-exposure gate (v0.8.5): 跨会话记忆已自动注入,memory_search /
722
+ // memory_archive 在慢/轻量模型上是多余往返,面板开关可直接隐藏工具——
723
+ // 模型看不到就不会调,比在描述里劝它少调用更可靠。注意:live patch reload
724
+ // 下已注册的工具不会被宿主反注册,排除只对全新会话生效。
725
+ const hiddenTools = new Set();
726
+ if (config?.disableMemorySearch === true) hiddenTools.add("memory_search");
727
+ if (config?.disableMemoryArchive === true) hiddenTools.add("memory_archive");
728
+
729
+ for (const tool of tools) {
730
+ if (hiddenTools.has(tool.name)) {
731
+ ctx.logger?.info?.(`[dsh-mneme] tool "${tool.name}" hidden by config (disableMemorySearch/disableMemoryArchive)`);
732
+ continue;
733
+ }
734
+ if (registeredTools.has(tool.name)) {
735
+ ctx.logger?.warn?.(`[dsh-mneme] tool "${tool.name}" already registered, skipping duplicate`);
736
+ continue;
737
+ }
738
+ registeredTools.add(tool.name);
739
+ ctx.tools.register(tool);
740
+ }
741
+
742
+ return tools;
743
+ }