dsh-lm-memory 0.17.3 → 0.18.1

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.
@@ -0,0 +1,58 @@
1
+ import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ // Call only with the Host-owned identity, not a tool argument. Refuse links
5
+ // inside our store root so an accidental alias cannot join two projects.
6
+ export async function projectDirectory(memoryDir, identity) {
7
+ if (!path.isAbsolute(memoryDir) || !/^[a-f\d]{64}$/.test(identity?.id ?? '')) return null;
8
+ try {
9
+ const base = await realpath(memoryDir);
10
+ return await containedDirectory(await containedDirectory(base, 'projects-v1'), identity.id);
11
+ } catch { return null; }
12
+ }
13
+
14
+ export async function personalDirectory(memoryDir) {
15
+ if (typeof memoryDir !== 'string' || !path.isAbsolute(memoryDir)) return null;
16
+ try { return await containedDirectory(await realpath(memoryDir), 'personal-v1'); }
17
+ catch { return null; }
18
+ }
19
+
20
+ async function containedDirectory(parent, name) {
21
+ const candidate = path.join(parent, name);
22
+ try { await mkdir(candidate, { mode: 0o700 }); }
23
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
24
+ const info = await lstat(candidate);
25
+ if (!info.isDirectory() || info.isSymbolicLink()) throw Error('Untrusted project store entry');
26
+ const actual = await realpath(candidate);
27
+ if (path.relative(parent, actual) !== name) throw Error('Project store escaped its parent');
28
+ return actual;
29
+ }
30
+
31
+ // A resumed conversation cannot be rebound to another project. Only a Host
32
+ // caller that establishes fresh-session eligibility may pass create=true.
33
+ export async function bindProjectSession(memoryDir, sessionId, identity, { create = false } = {}) {
34
+ if (!path.isAbsolute(memoryDir) || !/^session-[a-f\d-]{36}$/.test(sessionId ?? '') ||
35
+ !/^[a-f\d]{64}$/.test(identity?.id ?? '')) return null;
36
+ try {
37
+ const base = await realpath(memoryDir);
38
+ const registry = await containedDirectory(base, 'project-sessions-v1');
39
+ const binding = path.join(registry, sessionId);
40
+ const expected = `${identity.id}\n`;
41
+ async function matches() {
42
+ const info = await lstat(binding);
43
+ if (!info.isFile() || info.isSymbolicLink() || info.size !== expected.length) return false;
44
+ return await readFile(binding, 'utf8') === expected;
45
+ }
46
+ let accepted;
47
+ try { accepted = await matches(); }
48
+ catch (error) {
49
+ if (error.code !== 'ENOENT' || !create) return null;
50
+ try {
51
+ // Exclusive create is atomic on every platform; no hard link needed.
52
+ await writeFile(binding, expected, { flag: 'wx', mode: 0o600 });
53
+ } catch (conflict) { if (conflict.code !== 'EEXIST') throw conflict; }
54
+ accepted = await matches();
55
+ }
56
+ return accepted ? await projectDirectory(base, identity) : null;
57
+ } catch { return null; }
58
+ }
@@ -0,0 +1,339 @@
1
+ [
2
+ {
3
+ "name": "memory_remember",
4
+ "description": "写入一条持久记忆。kind: preference(偏好)/fact(事实)/procedure(经验)/episode(事件)。",
5
+ "inputSchema": {
6
+ "type": "object",
7
+ "properties": {
8
+ "content": {
9
+ "type": "string",
10
+ "minLength": 3,
11
+ "maxLength": 2000,
12
+ "description": "记忆内容,一句原子主张,含必要前提"
13
+ },
14
+ "kind": {
15
+ "type": "string",
16
+ "enum": [
17
+ "preference",
18
+ "fact",
19
+ "episode",
20
+ "procedure",
21
+ "todo"
22
+ ],
23
+ "default": "fact"
24
+ },
25
+ "tags": {
26
+ "type": "string",
27
+ "maxLength": 200,
28
+ "default": "",
29
+ "description": "逗号分隔标签,可选"
30
+ },
31
+ "event_date": {
32
+ "type": "string",
33
+ "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
34
+ "description": "事件发生/观察日(YYYY-MM-DD);缺省=今天。date 字段是稳定观察锚,不自动等于来源认证的事件日"
35
+ },
36
+ "valid_from": {
37
+ "type": "string",
38
+ "description": "已确认事实开始生效的日期;不同于观察日期,不从对话推断。"
39
+ }
40
+ },
41
+ "required": [
42
+ "content"
43
+ ],
44
+ "additionalProperties": false,
45
+ "$schema": "http://json-schema.org/draft-07/schema#"
46
+ }
47
+ },
48
+ {
49
+ "name": "memory_batch_remember",
50
+ "description": "最多50条;逐条使用相同写入防线与事务,逐条返回结果;批次不是全有或全无,索引/图谱批末刷新一次。",
51
+ "inputSchema": {
52
+ "type": "object",
53
+ "properties": {
54
+ "items": {
55
+ "type": "array",
56
+ "items": {
57
+ "type": "object",
58
+ "properties": {
59
+ "content": {
60
+ "type": "string",
61
+ "minLength": 3,
62
+ "maxLength": 2000
63
+ },
64
+ "kind": {
65
+ "type": "string",
66
+ "enum": [
67
+ "preference",
68
+ "fact",
69
+ "episode",
70
+ "procedure",
71
+ "todo"
72
+ ],
73
+ "default": "fact"
74
+ },
75
+ "tags": {
76
+ "type": "string",
77
+ "maxLength": 200,
78
+ "default": ""
79
+ },
80
+ "event_date": {
81
+ "type": "string",
82
+ "pattern": "^\\d{4}-\\d{2}-\\d{2}$"
83
+ }
84
+ },
85
+ "required": [
86
+ "content"
87
+ ],
88
+ "additionalProperties": false
89
+ },
90
+ "minItems": 1,
91
+ "maxItems": 50
92
+ }
93
+ },
94
+ "required": [
95
+ "items"
96
+ ],
97
+ "additionalProperties": false,
98
+ "$schema": "http://json-schema.org/draft-07/schema#"
99
+ }
100
+ },
101
+ {
102
+ "name": "memory_recall",
103
+ "description": "按 query 检索或按 id(也可 query=#123)精确读取全文。默认只返回 active;scope 可显式搜索 dormant/all(不自动唤醒)。搜索受 max_bytes 预算约束,id 取全文不截断。",
104
+ "inputSchema": {
105
+ "type": "object",
106
+ "properties": {
107
+ "query": {
108
+ "type": "string",
109
+ "minLength": 1,
110
+ "maxLength": 500,
111
+ "description": "自然语言查询或 #id;与 id 二选一"
112
+ },
113
+ "id": {
114
+ "type": "integer",
115
+ "exclusiveMinimum": 0,
116
+ "description": "精确读取索引指针全文;与 query 二选一"
117
+ },
118
+ "limit": {
119
+ "type": "integer",
120
+ "minimum": 1,
121
+ "maximum": 20,
122
+ "default": 5
123
+ },
124
+ "kind": {
125
+ "type": "string",
126
+ "enum": [
127
+ "preference",
128
+ "fact",
129
+ "episode",
130
+ "procedure",
131
+ "todo"
132
+ ]
133
+ },
134
+ "scope": {
135
+ "type": "string",
136
+ "enum": [
137
+ "active",
138
+ "dormant",
139
+ "all"
140
+ ],
141
+ "default": "active",
142
+ "description": "休眠记忆必须显式选择 dormant/all;不唤醒、不延寿"
143
+ },
144
+ "max_bytes": {
145
+ "type": "integer",
146
+ "minimum": 512,
147
+ "maximum": 65536,
148
+ "default": 16384,
149
+ "description": "搜索结果 JSON 字节预算;超额返回 hits/related/budget 对象,id 精确读取不受限"
150
+ },
151
+ "expand": {
152
+ "type": "boolean",
153
+ "default": false,
154
+ "description": "图谱扩展:附带命中条目的一跳关联记忆(co_tag/similar/ref 边),实体中心问题用"
155
+ },
156
+ "as_of": {
157
+ "type": "string",
158
+ "description": "仅配合当前版本 ID,按显式有效区间读取该事实版本;不推断。"
159
+ }
160
+ },
161
+ "additionalProperties": false,
162
+ "$schema": "http://json-schema.org/draft-07/schema#"
163
+ }
164
+ },
165
+ {
166
+ "name": "memory_feedback",
167
+ "description": "仅在记忆被实际使用且有帮助时续租;返回/曝光不再续租。错误或无关不续租。",
168
+ "inputSchema": {
169
+ "type": "object",
170
+ "properties": {
171
+ "id": {
172
+ "type": "integer",
173
+ "exclusiveMinimum": 0
174
+ },
175
+ "useful": {
176
+ "type": "boolean"
177
+ }
178
+ },
179
+ "required": [
180
+ "id",
181
+ "useful"
182
+ ],
183
+ "additionalProperties": false,
184
+ "$schema": "http://json-schema.org/draft-07/schema#"
185
+ }
186
+ },
187
+ {
188
+ "name": "memory_source",
189
+ "description": "读取 active/dormant 记忆的提炼输入窗口(已脱敏,长消息可能有中段省略),用于核验摘要。来源存在不代表主张已被验证。",
190
+ "inputSchema": {
191
+ "type": "object",
192
+ "properties": {
193
+ "id": {
194
+ "type": "integer",
195
+ "exclusiveMinimum": 0
196
+ }
197
+ },
198
+ "required": [
199
+ "id"
200
+ ],
201
+ "additionalProperties": false,
202
+ "$schema": "http://json-schema.org/draft-07/schema#"
203
+ }
204
+ },
205
+ {
206
+ "name": "memory_correct",
207
+ "description": "修正一条记忆:生成新版本并取代旧版。必须带当前 expected_version(乐观并发)。",
208
+ "inputSchema": {
209
+ "type": "object",
210
+ "properties": {
211
+ "id": {
212
+ "type": "integer",
213
+ "exclusiveMinimum": 0
214
+ },
215
+ "expected_version": {
216
+ "type": "integer",
217
+ "exclusiveMinimum": 0
218
+ },
219
+ "content": {
220
+ "type": "string",
221
+ "minLength": 3,
222
+ "maxLength": 2000
223
+ },
224
+ "reason": {
225
+ "type": "string",
226
+ "maxLength": 500,
227
+ "default": ""
228
+ },
229
+ "effective_from": {
230
+ "type": "string",
231
+ "description": "事实变更生效日;省略表示纠正原说法,不保留错误版本的有效区间。"
232
+ }
233
+ },
234
+ "required": [
235
+ "id",
236
+ "expected_version",
237
+ "content"
238
+ ],
239
+ "additionalProperties": false,
240
+ "$schema": "http://json-schema.org/draft-07/schema#"
241
+ }
242
+ },
243
+ {
244
+ "name": "memory_forget",
245
+ "description": "删除一条记忆。默认逻辑删除(保留 tombstone 供审计,不再被召回);hard=true 物理擦除该行(隐私purge)。active 与 dormant 均可删。",
246
+ "inputSchema": {
247
+ "type": "object",
248
+ "properties": {
249
+ "id": {
250
+ "type": "integer",
251
+ "exclusiveMinimum": 0
252
+ },
253
+ "reason": {
254
+ "type": "string",
255
+ "maxLength": 500,
256
+ "default": ""
257
+ },
258
+ "hard": {
259
+ "type": "boolean",
260
+ "default": false,
261
+ "description": "物理删除该行(含已休眠/已接棒的行),用于隐私擦除;默认 false 为可逆逻辑删除"
262
+ }
263
+ },
264
+ "required": [
265
+ "id"
266
+ ],
267
+ "additionalProperties": false,
268
+ "$schema": "http://json-schema.org/draft-07/schema#"
269
+ }
270
+ },
271
+ {
272
+ "name": "memory_list",
273
+ "description": "按种类列出最近的有效记忆。",
274
+ "inputSchema": {
275
+ "type": "object",
276
+ "properties": {
277
+ "kind": {
278
+ "type": "string",
279
+ "enum": [
280
+ "preference",
281
+ "fact",
282
+ "episode",
283
+ "procedure",
284
+ "todo"
285
+ ]
286
+ },
287
+ "limit": {
288
+ "type": "integer",
289
+ "minimum": 1,
290
+ "maximum": 1000,
291
+ "default": 20
292
+ }
293
+ },
294
+ "additionalProperties": false,
295
+ "$schema": "http://json-schema.org/draft-07/schema#"
296
+ }
297
+ },
298
+ {
299
+ "name": "memory_pin",
300
+ "description": "管理记忆生命周期:pin 置顶(永不休眠)/ unpin 取消置顶 / wake 唤醒休眠记忆。对休眠记忆置顶会同时唤醒。",
301
+ "inputSchema": {
302
+ "type": "object",
303
+ "properties": {
304
+ "id": {
305
+ "type": "integer",
306
+ "exclusiveMinimum": 0
307
+ },
308
+ "action": {
309
+ "type": "string",
310
+ "enum": [
311
+ "pin",
312
+ "unpin",
313
+ "wake"
314
+ ]
315
+ },
316
+ "reason": {
317
+ "type": "string",
318
+ "maxLength": 500,
319
+ "default": ""
320
+ }
321
+ },
322
+ "required": [
323
+ "id",
324
+ "action"
325
+ ],
326
+ "additionalProperties": false,
327
+ "$schema": "http://json-schema.org/draft-07/schema#"
328
+ }
329
+ },
330
+ {
331
+ "name": "memory_sleep",
332
+ "description": "手动执行一轮 sleep-time 整理:长期未被召回且未置顶的记忆转入休眠(可唤醒、可审计);顺带跑一轮冲突消解扫描(v0.14,只读),疑似过时对经热流播报。",
333
+ "inputSchema": {
334
+ "type": "object",
335
+ "properties": {},
336
+ "$schema": "http://json-schema.org/draft-07/schema#"
337
+ }
338
+ }
339
+ ]
@@ -0,0 +1,58 @@
1
+ import path from 'node:path';
2
+ import { bindProjectSession, personalDirectory } from './project-storage.mjs';
3
+ import { resolveProjectIdentity } from './project-identity.mjs';
4
+ import catalog from './project-tool-catalog.json' with { type: 'json' };
5
+
6
+ export function createProjectRouter(base, freshSince = Date.now()) {
7
+ const bindings = new WeakMap();
8
+ return {
9
+ personal: () => personalDirectory(base),
10
+ bind(session) {
11
+ if (!session || typeof session !== 'object') return Promise.resolve(null);
12
+ const meta = session.header ?? session.meta;
13
+ if (!meta || meta.id !== session.id || meta.isSeeded !== false || meta.parentSession || meta.origin ||
14
+ typeof meta.createdAt !== 'number') return Promise.resolve(null);
15
+ if (!bindings.has(session)) bindings.set(session, (async () => {
16
+ const identity = await resolveProjectIdentity(meta.cwd);
17
+ return identity && await bindProjectSession(base, session.id, identity, { create: meta.createdAt >= freshSince });
18
+ })());
19
+ return bindings.get(session);
20
+ },
21
+ };
22
+ }
23
+
24
+ // Personal and project tools have distinct names, so a numeric ID returned by
25
+ // one library is not silently used for the other. Neither accepts a path.
26
+ export function registerScopedTools(ctx, router, backends, signal) {
27
+ signal.throwIfAborted();
28
+ const disposers = [];
29
+ try {
30
+ for (const tool of catalog) {
31
+ if (!/^memory_[a-z_]+$/.test(tool.name) || tool.inputSchema?.type !== 'object') throw Error('Unsupported memory tool schema');
32
+ for (const scope of ['personal', 'project']) {
33
+ disposers.push(ctx.tools.register({
34
+ name: `mcp__lm_${scope}__${tool.name}`,
35
+ description: `${scope === 'project' ? '当前项目库' : '个人通用库'}(各库编号独立)。${tool.description ?? ''}`,
36
+ parameters: tool.inputSchema,
37
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
38
+ execute: async (args, execution) => {
39
+ if (!execution?.agent?.session) throw Error('Memory requires an active Host session');
40
+ const combined = AbortSignal.any([signal, execution.signal]);
41
+ combined.throwIfAborted();
42
+ const directory = scope === 'personal' ? await router.personal() : await router.bind(execution.agent.session);
43
+ if (typeof directory !== 'string' || !path.isAbsolute(directory)) throw Error('Memory not bound; start a fresh session in this Git project');
44
+ combined.throwIfAborted();
45
+ const result = await backends.call(directory, tool.name, args, combined);
46
+ const text = result.content?.filter(x => x.type === 'text' && typeof x.text === 'string').map(x => x.text).join('\n');
47
+ if (result.isError || typeof text !== 'string') throw Error('Memory tool failed in the bound store');
48
+ return text;
49
+ },
50
+ }));
51
+ }
52
+ }
53
+ return () => { for (const dispose of disposers) dispose(); };
54
+ } catch (error) {
55
+ for (const dispose of disposers) dispose();
56
+ throw error;
57
+ }
58
+ }
@@ -0,0 +1,50 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ // The child must be a real, standalone Node with SQLite, not just an existing GUI shim.
5
+ const PROBE = `let sqlite = false;
6
+ try { sqlite = typeof require('node:sqlite').DatabaseSync === 'function' } catch {}
7
+ console.log(JSON.stringify({ version: process.versions.node, execPath: process.execPath, sqlite, electron: process.versions.electron }));`;
8
+
9
+ export function resolveNode({ env = process.env, execPath = process.execPath, platform = process.platform, log = () => {} } = {}) {
10
+ const candidates = new Set([
11
+ env.DSH_NODE,
12
+ /[\\/]node(?:\.exe)?$/i.test(execPath) ? execPath : null,
13
+ ...(platform === "darwin" ? ["/opt/homebrew/bin/node", "/usr/local/bin/node"] : []),
14
+ ...(platform === "win32" ? [...new Set([env.ProgramW6432, env.ProgramFiles, "C:\\Program Files"])]
15
+ .filter(Boolean).map((dir) => path.win32.join(dir, "nodejs", "node.exe")) : []),
16
+ "node",
17
+ ].filter(Boolean));
18
+ // DSH's stdio transport can scrub DSH_* variables, so return the discovered absolute
19
+ // executable rather than a shim that would still need those variables in the child.
20
+ const tried = [];
21
+ for (const candidate of candidates) {
22
+ try {
23
+ const result = spawnSync(candidate, ["-e", PROBE], { env, encoding: "utf8", timeout: 1500, maxBuffer: 8192, windowsHide: true });
24
+ const info = result.status === 0 ? JSON.parse(result.stdout.trim()) : null;
25
+ const [major, minor] = /^\d+\.\d+\.\d+$/.test(info?.version) ? info.version.split(".").map(Number) : [];
26
+ if (info?.sqlite === true && !info.electron && (major > 22 || (major === 22 && minor >= 16)) && path.isAbsolute(info.execPath)) return info.execPath;
27
+ tried.push(`${candidate} (${info?.version ?? result.error?.code ?? "probe failed"})`);
28
+ } catch { tried.push(`${candidate} (invalid probe response)`); }
29
+ }
30
+ log(`no usable Node.js ≥22.16 with node:sqlite; set DSH_NODE to its executable and restart DSH. Tried: ${tried.join(", ")}`);
31
+ return null;
32
+ }
33
+
34
+ export function viewerPort(configured) {
35
+ const port = typeof configured === "string" && /^\d+$/.test(configured) ? Number(configured) : configured;
36
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
37
+ }
38
+
39
+ export const viewerArgs = (viewerPath, port) => [viewerPath, String(port), "--lm-memory-managed"];
40
+
41
+ export function spawnViewer(node, viewerPath, port, env, log) {
42
+ try {
43
+ const child = spawn(node, viewerArgs(viewerPath, port), { detached: true, stdio: "ignore", env, windowsHide: true });
44
+ // Synchronous try/catch does not handle ENOENT/EACCES emitted on ChildProcess.
45
+ child.on("error", (error) => log(`viewer spawn error on ${port}: ${error.code ?? error.message}`));
46
+ child.once("spawn", () => log(`viewer process started on ${port}`));
47
+ child.once("exit", (code) => { if (code) log(`viewer on ${port} exited (${code})`); });
48
+ child.unref();
49
+ } catch (error) { log(`viewer spawn error on ${port}: ${error?.message ?? error}`); }
50
+ }
@@ -0,0 +1,31 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { checkSecret, OPTOUT_RE } from '../../server/guards.mjs';
3
+
4
+ // No server startup, index rebuild, queue drain, embeddings, network or
5
+ // feedback. An unavailable SQLite/FTS index is an abstention, not a full scan.
6
+ function lookup({ dbPath, terms }) {
7
+ const { DatabaseSync } = process.getBuiltinModule('node:sqlite') ?? {};
8
+ if (!DatabaseSync || !Array.isArray(terms) || terms.length < 1 || terms.length > 2 ||
9
+ terms.some(term => typeof term !== 'string' || !/^[\p{L}\p{N} ._-]{4,40}$/u.test(term))) return null;
10
+ const db = new DatabaseSync(dbPath, { readOnly: true });
11
+ try {
12
+ const match = `content : (${terms.map(t => `"${t}"`).join(' AND ')})`;
13
+ const rows = db.prepare(`SELECT m.id, m.content FROM memories_fts
14
+ JOIN memories m ON m.id = memories_fts.rowid
15
+ WHERE memories_fts MATCH ? AND m.status='active'
16
+ AND m.kind IN ('fact','preference','procedure') LIMIT 2`).all(match);
17
+ if (rows.length !== 1) return null;
18
+ const [{ id, content }] = rows;
19
+ if (checkSecret(content) || OPTOUT_RE.test(content)) return null;
20
+ for (const term of terms) {
21
+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
22
+ if (/^[a-z0-9 ._-]+$/i.test(term) &&
23
+ !new RegExp(`(?:^|[^a-z0-9_-])${escaped}(?:$|[^a-z0-9_-])`, 'i').test(content)) return null;
24
+ }
25
+ return Number.isSafeInteger(id) && id > 0 ? id : null;
26
+ } finally { db.close(); }
27
+ }
28
+
29
+ let id = null;
30
+ try { id = lookup(workerData); } catch {} // Never log a user query or a memory.
31
+ parentPort.postMessage(id);
@@ -0,0 +1,128 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { Worker } from 'node:worker_threads';
5
+ import { checkSecret, OPTOUT_RE } from '../../server/guards.mjs';
6
+
7
+ const MESSAGE_BYTES = 1024;
8
+ const HINT_BYTES = 512;
9
+ const SESSION_MESSAGES = 128;
10
+ const TIMEOUT_MS = 200;
11
+ const STOP = new Set('please could would should about after before still previous earlier remember project workspace system memory which where there these those what when which this that from with have know used using latest current model result issue'.split(' '));
12
+ const OPT_OUT = /(?:不要|不用|别|禁止)(?:自动)?(?:查(?:记忆|库)|回忆|召回|检索记忆)|(?:no|do not|don.t) (?:auto[- ]?)?(?:recall|look up memory|use memory)/i;
13
+ const HISTORICAL = /之前|上次|上回|以前|当时|此前|曾经|原来|还记得|先前|\b(?:previously|earlier|last time|we used|used to|remember|did we)\b/i;
14
+
15
+ // Conservative experiment: a reference to prior context AND either a quoted
16
+ // literal or two distinct anchors. No general short-query fallback.
17
+ export function taskRecallAnchors(text) {
18
+ if (typeof text !== 'string' || Buffer.byteLength(text) > MESSAGE_BYTES ||
19
+ checkSecret(text) || OPTOUT_RE.test(text) || OPT_OUT.test(text) || !HISTORICAL.test(text)) return null;
20
+ const quoted = [...text.matchAll(/"([\p{L}\p{N}][\p{L}\p{N} ._-]{2,38})"|「([\p{L}\p{N}][\p{L}\p{N} ._-]{2,38})」|`([\p{L}\p{N}][\p{L}\p{N} ._-]{2,38})`/gu)]
21
+ .map(m => (m[1] ?? m[2] ?? m[3]).trim().toLowerCase())
22
+ .filter(t => t.length >= 4 && /\p{L}/u.test(t) && !STOP.has(t));
23
+ if (quoted.length === 1) return quoted;
24
+ const terms = text.match(/[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*/gi) ?? [];
25
+ const candidates = [...new Set(terms.map(t => t.toLowerCase()).filter(t => t.length >= 4 && t.length <= 40 && !STOP.has(t)))];
26
+ if (candidates.length !== 2 || candidates.some((t, i) => t.includes(candidates[1 - i]))) return null;
27
+ return candidates;
28
+ }
29
+
30
+ // A single worker per plugin instance; no queue. A timed-out worker occupies
31
+ // its slot until exit, so a stalled SQLite read cannot pile up more workers.
32
+ export function createTaskLookup(dbPath, { timeoutMs = TIMEOUT_MS } = {}) {
33
+ let busy = false;
34
+ return (terms, signal, dir) => {
35
+ if (busy || signal?.aborted) return Promise.resolve(null);
36
+ return new Promise(resolve => {
37
+ let worker;
38
+ try {
39
+ worker = new Worker(new URL('./task-recall-worker.mjs', import.meta.url), {
40
+ workerData: { dbPath: dbPath ?? path.join(dir, 'memory.db'), terms }, execArgv: [], env: {},
41
+ });
42
+ } catch { resolve(null); return; }
43
+ busy = true;
44
+ let done = false;
45
+ const settle = (result) => {
46
+ if (done) return;
47
+ done = true;
48
+ clearTimeout(timer);
49
+ signal?.removeEventListener('abort', abort);
50
+ resolve(result);
51
+ };
52
+ const abort = () => {
53
+ settle(null);
54
+ void worker.terminate().catch(() => {});
55
+ };
56
+ const timer = setTimeout(abort, timeoutMs);
57
+ worker.once('message', settle);
58
+ worker.on('error', () => settle(null));
59
+ worker.once('exit', () => { busy = false; settle(null); });
60
+ signal?.addEventListener('abort', abort, { once: true });
61
+ if (signal?.aborted) abort();
62
+ });
63
+ };
64
+ }
65
+
66
+ const EVENTS = 'task-recall-events.jsonl';
67
+ const EVENTS_LIMIT = 1_048_576;
68
+ // Experiment evidence without content: which candidate was offered, or why none
69
+ // was. Bounded so an unattended profile cannot grow one file without limit; a
70
+ // failed write never blocks the request.
71
+ function recordEvent(dir, fields) {
72
+ try {
73
+ if (typeof dir !== 'string' || !path.isAbsolute(dir)) return;
74
+ const file = path.join(dir, EVENTS);
75
+ let size = 0;
76
+ try { size = fs.statSync(file).size; } catch {}
77
+ if (size > EVENTS_LIMIT) return;
78
+ fs.appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), ...fields }) + '\n');
79
+ } catch {}
80
+ }
81
+
82
+ export function createTaskRecallHook(config, memoryDir, lookup = undefined) {
83
+ const scoped = typeof memoryDir === 'function';
84
+ const options = config?.taskRecall;
85
+ // Exact, explicit consent for individual sessions. Not a database ACL.
86
+ const sessions = Array.isArray(options?.sessionIds) && options.sessionIds.length <= 32
87
+ ? new Set(options.sessionIds.filter(id => typeof id === 'string' && id && id.length <= 160)) : new Set();
88
+ if (options?.enabled !== true || !sessions.size || config?.allowRemote === false ||
89
+ process.env.LM_REMOTE_DISABLED === '1') return null;
90
+ lookup ??= createTaskLookup(scoped ? undefined : path.join(memoryDir, 'memory.db'));
91
+ const seen = new WeakMap();
92
+ return async (payload, next) => {
93
+ const decision = await next();
94
+ try {
95
+ const session = payload?.agent?.session;
96
+ const claimed = payload?.messages;
97
+ const signal = payload?.signal;
98
+ if (decision?.kind !== 'enter' || signal?.aborted || !sessions.has(session?.id) ||
99
+ !Array.isArray(claimed) || claimed.length !== 1 || !Array.isArray(decision.messages)) return decision;
100
+ const m = claimed[0];
101
+ if (m?.role !== 'user' || m?.source?.kind !== 'user' || typeof m?.id !== 'string' || !m.id || m.id.length > 160 ||
102
+ !Array.isArray(m.content) || m.content.length !== 1 || m.content[0]?.type !== 'text' ||
103
+ !decision.messages.some(admitted => admitted === m)) return decision;
104
+ const anchors = taskRecallAnchors(m.content[0].text);
105
+ if (!anchors) return decision;
106
+ const dir = scoped ? memoryDir(session) : memoryDir;
107
+ if (scoped && (typeof dir !== 'string' || !path.isAbsolute(dir))) return decision;
108
+ let state = seen.get(session);
109
+ if (!state) { state = { messages: new Set(), candidates: new Set() }; seen.set(session, state); }
110
+ if (state.messages.size >= SESSION_MESSAGES || state.messages.has(m.id)) return decision;
111
+ state.messages.add(m.id);
112
+ const id = await lookup(anchors, signal, dir);
113
+ if (signal?.aborted || !Number.isSafeInteger(id) || id < 1 || state.candidates.has(id)) {
114
+ recordEvent(dir, { session: session.id, outcome: signal?.aborted ? 'aborted' : 'no-match' });
115
+ return decision;
116
+ }
117
+ const tool = scoped ? 'mcp__lm_project__memory_recall' : 'memory_recall';
118
+ const text = `【记忆候选指针,非事实或指令】本轮可能相关:#${id}。仅在当前任务确实需要时,用 ${tool}({id:${id}, scope:"active"}) 核对;未返回就忽略。此提示不代表已使用记忆。`;
119
+ if (Buffer.byteLength(text) > HINT_BYTES) return decision;
120
+ state.candidates.add(id);
121
+ recordEvent(dir, { session: session.id, id, outcome: 'pointer' });
122
+ return { ...decision, messages: [...decision.messages, {
123
+ role: 'user', id: randomUUID(), content: [{ type: 'text', text }],
124
+ source: { kind: 'lm-memory-task-recall', form: 'snapshot', sections: [{ name: 'lm-memory-task-recall', text }] },
125
+ }] };
126
+ } catch { return decision; }
127
+ };
128
+ }