@modusensus/dsh-mneme 0.8.3 → 0.8.5

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