dsh-lm-memory 0.18.1 → 0.19.0

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.
package/README.md CHANGED
@@ -156,9 +156,9 @@ claude mcp add lm_memory -s user -- node /path/to/lm-memory/server/memory-server
156
156
 
157
157
  ### DSH
158
158
 
159
- 正式版 `0.18.1`(GitHub Release 附安装包;npm 同名版本同步发布)。先核对 DSH 版本满足 `>=0.2.2-rc.3 <0.3.0`;在隔离环境打开 **插件 → 添加插件**,输入 `file:` 加下载到的 `dsh-lm-memory-0.18.1.tgz` 绝对路径(Windows 例:`file:C:/LM-Test/dsh-lm-memory-0.18.1.tgz`),按宿主提示重启。包只包含插件;安装依赖可能需要联网,且插件仍需要独立 Node.js ≥22.16。不要因此同意不明构建脚本或版本兼容豁免。
159
+ 正式版 `0.19.0`(GitHub Release 附安装包;npm 同名版本同步发布)。先核对 DSH 版本满足 `>=0.2.2-rc.3 <0.3.0`;在隔离环境打开 **插件 → 添加插件**,输入 `file:` 加下载到的 `dsh-lm-memory-0.19.0.tgz` 绝对路径(Windows 例:`file:C:/LM-Test/dsh-lm-memory-0.19.0.tgz`),按宿主提示重启。包只包含插件;安装依赖可能需要联网,且插件仍需要独立 Node.js ≥22.16。不要因此同意不明构建脚本或版本兼容豁免。
160
160
 
161
- 0.18.1 的默认行为与 0.17.3 相同:按 Git 仓库隔离的项目记忆、用户确认结论/修复经验、事实有效日期、任务候选提示,全部需要显式开启,默认关闭,说明与限制见 `docs/project-memory.md`。
161
+ 0.19.0 的默认行为与 0.17.3 相同:按 Git 仓库隔离的项目记忆、用户确认结论/修复经验、事实有效日期、任务候选提示,全部需要显式开启,默认关闭,说明与限制见 `docs/project-memory.md`。
162
162
 
163
163
  以下是已发布稳定版示例。profile 的 `package.json` 加依赖(建议用 tag 固定版本):
164
164
 
@@ -192,6 +192,10 @@ extract: true # false = 关闭自动提炼
192
192
 
193
193
  自动候选提示与 `refresh` 变更热流相互独立。启用方式、隐私与验收边界见[任务召回指针实验](docs/task-recall-experiment.md)。
194
194
 
195
+ ### 功能开关(设置页)
196
+
197
+ **设置 → 记忆库** 里可以开关:项目记忆、确认结论入库、允许外发提炼、任务候选提示(含授权会话 ID)。改动写入 `<memoryDir>/settings.json`,重启 DSH 生效;文件存在时以它为准,其余配置(模型、端口、数据目录)仍来自 `cordis.patch.yml`。不想用页面时二者等价,手写 YAML 仍有效。
198
+
195
199
  ### 项目记忆(可选)
196
200
 
197
201
  按 Git 仓库隔离记忆,默认关闭:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lm-memory",
3
- "version": "0.18.1",
3
+ "version": "0.19.0",
4
4
  "description": "本地优先的 Agent 长期记忆:MCP server(SQLite+FTS5+双语语义+遗忘曲线+统一提交入口)+ DSH 采集插件(外发前脱敏/事件时间锚/会话指纹二采)",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/plugin/client.js CHANGED
@@ -15,11 +15,45 @@ window.__ModuleLoader__.load({
15
15
  return response.json();
16
16
  }
17
17
 
18
+ async function postJSON(url, body, signal) {
19
+ const response = await fetch(url, {
20
+ method: "POST", signal, redirect: "error", cache: "no-store",
21
+ headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
22
+ });
23
+ const data = await response.json().catch(() => ({}));
24
+ if (!response.ok) throw new Error(data?.error ?? "HTTP " + response.status);
25
+ return data;
26
+ }
27
+
28
+ const SWITCHES = [
29
+ { key: "projectMemory", label: "项目记忆", hint: "按 Git 仓库隔离;开启后不再启用旧 MCP、旧采集与完整管理页" },
30
+ { key: "confirmedOutcomes", label: "确认结论入库", hint: "允许用「确认结论:/确认修复:」把上一轮助手原句存为项目事实或经验(需项目记忆)" },
31
+ { key: "allowRemote", label: "允许外发提炼", hint: "关闭时完全不出网;开启后才会把复盘交给模型提炼" },
32
+ ];
33
+
34
+ function Switch(props) {
35
+ return createElement("label", {
36
+ style: { display: "flex", gap: 10, alignItems: "flex-start", padding: "8px 0", cursor: "pointer" },
37
+ },
38
+ createElement("input", {
39
+ type: "checkbox", checked: props.checked, disabled: props.disabled,
40
+ onChange: (event) => props.onChange(event.target.checked),
41
+ style: { marginTop: 3 },
42
+ }),
43
+ createElement("span", null,
44
+ createElement("span", { style: { fontWeight: 500, fontSize: 13 } }, props.label),
45
+ createElement("span", { style: { display: "block", fontSize: 12, color: "#777", lineHeight: 1.6 } }, props.hint))
46
+ );
47
+ }
48
+
18
49
  function MemorySection() {
19
50
  const [state, setState] = react.useState({ status: "loading", address: null, items: [] });
51
+ const [form, setForm] = react.useState(null);
52
+ const [notice, setNotice] = react.useState(null);
53
+ const local = () => (window.location.protocol === "dsh-app:" && window.location.hostname === "app") ||
54
+ ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname);
20
55
  react.useEffect(() => {
21
- if (!((window.location.protocol === "dsh-app:" && window.location.hostname === "app") ||
22
- ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname))) {
56
+ if (!local()) {
23
57
  setState({ status: "remote", address: null, items: [] });
24
58
  return;
25
59
  }
@@ -27,6 +61,18 @@ window.__ModuleLoader__.load({
27
61
  const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);
28
62
  const update = (next) => { if (!controller.signal.aborted) setState(next); };
29
63
  let address = null;
64
+ readJSON("./api/lm-memory-settings", signal).then((data) => {
65
+ if (controller.signal.aborted) return;
66
+ setForm({
67
+ projectMemory: data?.settings?.projectMemory === true,
68
+ confirmedOutcomes: data?.settings?.confirmedOutcomes === true,
69
+ allowRemote: data?.settings?.allowRemote === true,
70
+ taskRecallEnabled: data?.settings?.taskRecall?.enabled === true,
71
+ sessionIds: (data?.settings?.taskRecall?.sessionIds ?? []).join(","),
72
+ });
73
+ if (data?.restartRequired) setNotice({ kind: "warn", text: "设置已保存,重启 DSH 后生效。" });
74
+ else if (data?.error) setNotice({ kind: "warn", text: data.error });
75
+ }).catch(() => { if (!controller.signal.aborted) setNotice({ kind: "warn", text: "无法读取功能开关" }); });
30
76
  readJSON("./api/lm-memory-viewer", signal).then(async ({ port, status }) => {
31
77
  if (status === "disabled" && port === null) { update({ status, address, items: [] }); return; }
32
78
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("invalid viewer port");
@@ -50,6 +96,20 @@ window.__ModuleLoader__.load({
50
96
  remote: "管理页仅限运行 DSH 的本机访问",
51
97
  };
52
98
  const kindLabel = { preference: "偏好", fact: "事实", procedure: "经验", todo: "待办", episode: "会话" };
99
+ const update = (patch) => setForm({ ...form, ...patch });
100
+ const save = async () => {
101
+ const ids = String(form.sessionIds ?? "").split(/[\s,]+/).filter(Boolean);
102
+ setNotice({ kind: "info", text: "保存中…" });
103
+ try {
104
+ const data = await postJSON("./api/lm-memory-settings", {
105
+ projectMemory: form.projectMemory,
106
+ confirmedOutcomes: form.confirmedOutcomes,
107
+ allowRemote: form.allowRemote,
108
+ taskRecall: { enabled: form.taskRecallEnabled, sessionIds: ids },
109
+ });
110
+ setNotice({ kind: "ok", text: data?.restartRequired === false ? "已保存(无需重启)。" : "已保存,重启 DSH 后生效。" });
111
+ } catch (error) { setNotice({ kind: "warn", text: "保存失败:" + (error?.message ?? "未知错误") }); }
112
+ };
53
113
  return createElement("div", { style: { display: "flex", flexDirection: "column", gap: 16, padding: "0 24px 24px" } },
54
114
  createElement("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
55
115
  createElement("div", { style: { fontWeight: 600, fontSize: 14 } }, "记忆库"),
@@ -61,6 +121,39 @@ window.__ModuleLoader__.load({
61
121
  style: { cursor: "pointer", fontSize: 13, padding: "6px 16px", borderRadius: 8, border: "1px solid rgba(128,128,128,.4)", background: "transparent", color: "inherit" },
62
122
  href: state.address, target: "_blank", rel: "noopener noreferrer",
63
123
  }, "打开完整管理页(搜索 · 修正 · 删除 · 用户画像)")) : null,
124
+ form ? createElement("div", { style: { borderTop: "1px solid rgba(128,128,128,.25)", paddingTop: 12 } },
125
+ createElement("div", { style: { fontWeight: 600, fontSize: 13, marginBottom: 4 } }, "功能开关"),
126
+ createElement("div", { style: { fontSize: 12, color: "#777", marginBottom: 6 } }, "默认全部关闭,行为与旧版本一致。改动写入 memoryDir/settings.json,重启 DSH 后生效。"),
127
+ SWITCHES.map((item) => createElement(Switch, {
128
+ key: item.key, label: item.label, hint: item.hint,
129
+ checked: form[item.key] === true, disabled: false,
130
+ onChange: (value) => update({ [item.key]: value }),
131
+ })),
132
+ createElement("div", { style: { padding: "8px 0" } },
133
+ createElement("label", { style: { display: "flex", gap: 10, alignItems: "flex-start", cursor: "pointer" } },
134
+ createElement("input", {
135
+ type: "checkbox", checked: form.taskRecallEnabled,
136
+ onChange: (event) => update({ taskRecallEnabled: event.target.checked }),
137
+ style: { marginTop: 3 },
138
+ }),
139
+ createElement("span", null,
140
+ createElement("span", { style: { fontWeight: 500, fontSize: 13 } }, "任务候选提示(实验)"),
141
+ createElement("span", { style: { display: "block", fontSize: 12, color: "#777", lineHeight: 1.6 } },
142
+ "回溯型任务出现唯一字面锚点时,追加一个候选编号。改述、同义提问基本不命中,收益未验证。"))),
143
+ createElement("input", {
144
+ type: "text", value: form.sessionIds,
145
+ placeholder: "授权会话 ID,逗号分隔(留空即不生效)",
146
+ onChange: (event) => update({ sessionIds: event.target.value }),
147
+ style: { marginTop: 6, width: "100%", fontSize: 12, padding: "6px 8px", borderRadius: 6, border: "1px solid rgba(128,128,128,.4)", background: "transparent", color: "inherit" },
148
+ })),
149
+ createElement("div", { style: { display: "flex", gap: 10, alignItems: "center", marginTop: 4 } },
150
+ createElement("button", {
151
+ onClick: save,
152
+ style: { cursor: "pointer", fontSize: 13, padding: "6px 16px", borderRadius: 8, border: "1px solid rgba(128,128,128,.4)", background: "transparent", color: "inherit" },
153
+ }, "保存设置"),
154
+ notice ? createElement("span", {
155
+ style: { fontSize: 12, color: notice.kind === "warn" ? "#b26a00" : notice.kind === "ok" ? "#2e7d32" : "#666" },
156
+ }, notice.text) : null)) : null,
64
157
  state.items.length ? createElement("div", { style: { fontSize: 12.5, color: "#666" } },
65
158
  "最近记忆:",
66
159
  createElement("div", { style: { marginTop: 6, display: "flex", flexDirection: "column", gap: 4 } },
@@ -9,6 +9,7 @@ import { createTaskRecallHook } from "./task-recall.mjs";
9
9
  import { createProjectRouter, registerScopedTools } from './project-tools.mjs';
10
10
  import { createProjectBackends } from './project-backends.mjs';
11
11
  import { confirmedOutcomes, isOutcomeConfirmation } from './confirmed-outcomes.mjs';
12
+ import { mergeConfig, readSettings, saveSettings, settingsPath } from './settings.mjs';
12
13
  import { filterTextsForLLM } from "../../server/guards.mjs"; // v0.15 外发前脱敏/剔除(与 server/helper 同源)
13
14
  import { createHash } from "node:crypto";
14
15
  import { execFileSync } from "node:child_process";
@@ -174,6 +175,53 @@ async function ensureFreshViewer(port, node, viewerPath, want) {
174
175
  return false;
175
176
  }
176
177
 
178
+ // Owner-only bridge for the Settings page: read the switches, save them, and
179
+ // say whether a restart is needed. Nothing here reads memories or the viewer.
180
+ function registerSettingsApi(ctx, applied) {
181
+ const snapshot = JSON.stringify(applied.settings);
182
+ const state = () => {
183
+ const current = readSettings(MEM_DIR);
184
+ return {
185
+ settings: current.settings,
186
+ error: current.error,
187
+ applied: {
188
+ projectMemory: applied.settings.projectMemory,
189
+ confirmedOutcomes: applied.settings.confirmedOutcomes,
190
+ allowRemote: applied.settings.allowRemote,
191
+ taskRecall: applied.settings.taskRecall,
192
+ },
193
+ restartRequired: JSON.stringify(current.settings) !== snapshot,
194
+ file: settingsPath(MEM_DIR),
195
+ };
196
+ };
197
+ try {
198
+ ctx.inject?.(["connection"], (host) => {
199
+ const dispose = host.connection.fetch?.register({
200
+ path: "/api/lm-memory-settings",
201
+ methods: ["GET", "POST"],
202
+ requestBody: "buffered",
203
+ fetch: async (request) => {
204
+ if (request.method === "GET") return Response.json(state(), { headers: { "Cache-Control": "no-store" } });
205
+ let body;
206
+ try { body = await request.json(); } catch { return Response.json({ error: "请求体不是合法 JSON" }, { status: 400 }); }
207
+ if (body && typeof body === "object" && typeof body.reset === "boolean") {
208
+ const current = readSettings(MEM_DIR).settings;
209
+ const blank = { ...current };
210
+ for (const key of ["projectMemory", "confirmedOutcomes", "allowRemote"]) blank[key] = false;
211
+ blank.taskRecall = { enabled: false, sessionIds: [] };
212
+ const reset = saveSettings(MEM_DIR, blank);
213
+ return reset.ok ? Response.json(state()) : Response.json({ error: reset.error }, { status: 400 });
214
+ }
215
+ const result = saveSettings(MEM_DIR, body);
216
+ if (!result.ok) return Response.json({ error: result.error, fields: result.fields }, { status: 400 });
217
+ return Response.json(state());
218
+ },
219
+ });
220
+ if (dispose && host.effect) host.effect(() => dispose);
221
+ });
222
+ } catch (error) { log(`settings bridge unavailable: ${error?.message ?? error}`); }
223
+ }
224
+
177
225
  function initializeStartup(ctx, config) {
178
226
  const port = viewerPort(config?.viewer);
179
227
  if (config?.viewer && !port) log("viewer disabled: expected an integer port from 1 to 65535");
@@ -448,6 +496,13 @@ function startProjectTools(ctx, config, signal) {
448
496
 
449
497
  export default function apply(ctx, config) {
450
498
  try {
499
+ if (config?.memoryDir) MEM_DIR = String(config.memoryDir);
500
+ // The settings page writes settings.json; it only overrides the switches it
501
+ // owns, and takes effect on the next start.
502
+ const state = readSettings(MEM_DIR);
503
+ if (!legacyCapture || legacyCapture.dir !== MEM_DIR) legacyCapture = captureStore(MEM_DIR);
504
+ config = mergeConfig(config ?? {}, state);
505
+ registerSettingsApi(ctx, state);
451
506
  if (config?.projectMemory === true) {
452
507
  // No legacy startup service, capture, global deltas or Viewer in scoped mode.
453
508
  ctx.inject(['tools'], scoped => scoped.effect(() => {
@@ -458,8 +513,6 @@ export default function apply(ctx, config) {
458
513
  }));
459
514
  return;
460
515
  }
461
- if (config?.memoryDir) MEM_DIR = String(config.memoryDir);
462
- if (!legacyCapture || legacyCapture.dir !== MEM_DIR) legacyCapture = captureStore(MEM_DIR);
463
516
  try { initializeStartup(ctx, config); }
464
517
  catch (error) { log(`startup error: ${error?.message ?? error}`); }
465
518
  // 悬浮按钮已移除:设置 → 记忆库 是正式入口(用户反馈悬浮球多余)
@@ -0,0 +1,92 @@
1
+ // Plugin-owned switches that the Settings page can change without editing YAML.
2
+ // The file wins over cordis config only when it exists, so an untouched install
3
+ // keeps behaving exactly like its declared config.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ export const SETTINGS_VERSION = 1;
8
+ const BOOLEANS = ['projectMemory', 'confirmedOutcomes', 'allowRemote'];
9
+ const SESSION_ID = /^[\x21-\x7e]{1,160}$/;
10
+
11
+ export const defaults = () => ({ version: SETTINGS_VERSION, projectMemory: false, confirmedOutcomes: false, allowRemote: false, taskRecall: { enabled: false, sessionIds: [] } });
12
+
13
+ export const settingsPath = memoryDir => path.join(memoryDir, 'settings.json');
14
+
15
+ function validate(input) {
16
+ const fields = {};
17
+ const out = {};
18
+ if (input == null || typeof input !== 'object' || Array.isArray(input)) return { fields: { $: '主体必须是对象' }, value: null };
19
+ for (const key of BOOLEANS) {
20
+ if (input[key] === undefined) continue;
21
+ if (typeof input[key] !== 'boolean') { fields[key] = '必须是 true 或 false'; continue; }
22
+ out[key] = input[key];
23
+ }
24
+ if (input.taskRecall !== undefined) {
25
+ const value = input.taskRecall;
26
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) fields.taskRecall = '必须是对象';
27
+ else {
28
+ const next = {};
29
+ if (value.enabled !== undefined) {
30
+ if (typeof value.enabled !== 'boolean') fields['taskRecall.enabled'] = '必须是 true 或 false';
31
+ else next.enabled = value.enabled;
32
+ }
33
+ if (value.sessionIds !== undefined) {
34
+ if (!Array.isArray(value.sessionIds) || value.sessionIds.length > 32 || value.sessionIds.some(id => typeof id !== 'string' || !SESSION_ID.test(id)))
35
+ fields['taskRecall.sessionIds'] = '最多 32 个会话 ID,每个 1–160 个可见字符';
36
+ else next.sessionIds = [...new Set(value.sessionIds)];
37
+ }
38
+ if (!Object.keys(fields).some(key => key.startsWith('taskRecall'))) out.taskRecall = next;
39
+ }
40
+ }
41
+ return { fields, value: out };
42
+ }
43
+
44
+ export function readSettings(memoryDir) {
45
+ const file = settingsPath(memoryDir);
46
+ let raw;
47
+ try { raw = fs.readFileSync(file, 'utf8'); }
48
+ catch (error) {
49
+ if (error.code === 'ENOENT') return { present: false, settings: defaults(), error: null };
50
+ return { present: false, settings: defaults(), error: `无法读取 ${file}` };
51
+ }
52
+ let parsed;
53
+ try { parsed = JSON.parse(raw); }
54
+ catch { return { present: true, settings: defaults(), error: 'settings.json 不是合法 JSON,已按默认值运行' }; }
55
+ const { fields, value } = validate(parsed);
56
+ if (Object.keys(fields).length) return { present: true, settings: defaults(), error: `settings.json 字段无效:${Object.keys(fields).join('、')}` };
57
+ return { present: true, settings: { ...defaults(), ...value }, error: null };
58
+ }
59
+
60
+ export function saveSettings(memoryDir, input) {
61
+ const current = readSettings(memoryDir).settings;
62
+ const { fields, value } = validate(input);
63
+ if (Object.keys(fields).length) return { ok: false, error: 'invalid', fields };
64
+ const next = {
65
+ version: SETTINGS_VERSION,
66
+ ...BOOLEANS.reduce((acc, key) => ({ ...acc, [key]: value[key] ?? current[key] }), {}),
67
+ taskRecall: {
68
+ enabled: value.taskRecall?.enabled ?? current.taskRecall.enabled,
69
+ sessionIds: value.taskRecall?.sessionIds ?? current.taskRecall.sessionIds,
70
+ },
71
+ };
72
+ try {
73
+ fs.mkdirSync(memoryDir, { recursive: true, mode: 0o700 });
74
+ const file = settingsPath(memoryDir);
75
+ const temp = `${file}.${process.pid}.tmp`;
76
+ fs.writeFileSync(temp, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
77
+ fs.renameSync(temp, file);
78
+ } catch (error) { return { ok: false, error: `无法写入设置:${error?.message ?? error}`, fields: {} }; }
79
+ return { ok: true, settings: next };
80
+ }
81
+
82
+ // Only the four keys above are taken from the file; everything else (llm,
83
+ // viewer port, memoryDir…) stays exactly as configured.
84
+ export function mergeConfig(config, state) {
85
+ if (!state.present) return config;
86
+ const merged = { ...config };
87
+ for (const key of BOOLEANS) merged[key] = state.settings[key];
88
+ merged.taskRecall = state.settings.taskRecall.enabled
89
+ ? { enabled: true, sessionIds: state.settings.taskRecall.sessionIds }
90
+ : undefined;
91
+ return merged;
92
+ }