@modusensus/dsh-mneme 0.8.2 → 0.8.4

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -633
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4362
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -500
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -513
  22. package/lib/inject.js +299 -253
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -308
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -260
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -0
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2071
  42. package/lib/settings.js +430 -419
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -500
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -513
  75. package/src/inject.js +299 -253
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -308
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -260
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -0
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2071
  95. package/src/settings.js +430 -419
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1481
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -0
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -229
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -0
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
package/lib/tools.js CHANGED
@@ -1,574 +1,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
-
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
+
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
+ }