dsh-memorytree-rule 0.0.0-stage → 1.0.2

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/lib/vector.mjs ADDED
@@ -0,0 +1,51 @@
1
+ // lib/vector.mjs — 离线字面向量(hashed char n-gram,非神经网络嵌入)。
2
+ //
3
+ // 诚实说明:这不是 bge/text-embedding 那种语义向量,它衡量的是「字面相近」。
4
+ // 它的价值:拼错、词序变化、长词截断、换说法时仍能召回;与 BM25 互补。
5
+ // 选择它的理由:零依赖、零模型下载、毫秒级、在中文短文本上稳定;
6
+ // 若将来接入真正的 embedding,只需替换 embed() 的实现与 DIM,存储格式不用动。
7
+ import { tokenize } from "./text.mjs";
8
+
9
+ export const VEC_DIM = 256;
10
+ export const VEC_KIND = "hash-char-ngram-v1";
11
+
12
+ function fnv1a(str) {
13
+ let h = 0x811c9dc5;
14
+ for (let i = 0; i < str.length; i++) {
15
+ h ^= str.charCodeAt(i);
16
+ h = Math.imul(h, 0x01000193) >>> 0;
17
+ }
18
+ return h >>> 0;
19
+ }
20
+
21
+ /** 文本 → L2 归一化的 Float32Array(VEC_DIM)。相同文本永远得到相同向量。 */
22
+ export function embed(text) {
23
+ const v = new Float32Array(VEC_DIM);
24
+ for (const [term, w] of tokenize(text)) {
25
+ const h = fnv1a(term);
26
+ const idx = h % VEC_DIM;
27
+ const sign = (h >>> 9) & 1 ? 1 : -1; // 带符号哈希,降低碰撞同号放大的偏差
28
+ v[idx] += sign * w;
29
+ }
30
+ let norm = 0;
31
+ for (let i = 0; i < VEC_DIM; i++) norm += v[i] * v[i];
32
+ norm = Math.sqrt(norm);
33
+ if (norm > 0) for (let i = 0; i < VEC_DIM; i++) v[i] /= norm;
34
+ return v;
35
+ }
36
+
37
+ export function cosine(a, b) {
38
+ if (!a || !b || a.length !== b.length) return 0;
39
+ let dot = 0;
40
+ for (let i = 0; i < a.length; i++) dot += a[i] * b[i];
41
+ return dot; // 两边都已归一化,点积即余弦
42
+ }
43
+
44
+ export function pack(vec) {
45
+ return Buffer.from(new Float32Array(vec).buffer);
46
+ }
47
+
48
+ export function unpack(buf) {
49
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
50
+ return new Float32Array(ab);
51
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "记忆树",
4
+ "description": "四枝分层的本地记忆索引:主干/情感枝/任务枝/判断叶,按作用域隔离,逐字证据与审计可查。离线 BM25 + 字符 n-gram 检索,无命中就如实说没有;DSH 左侧栏「记忆树」入口、交互星图看板、判断叶归枝与每日日记索引。不联网、不调 LLM、零外部服务。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "记忆树",
4
+ "description": "四枝分层的本地记忆索引:主干/情感枝/任务枝/判断叶,按作用域隔离,逐字证据与审计可查。离线 BM25 + 字符 n-gram 检索,无命中就如实说没有;DSH 左侧栏「记忆树」入口、交互星图看板、判断叶归枝与每日日记索引。不联网、不调 LLM、零外部服务。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
- {
2
- "name": "dsh-memorytree-rule",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-memorytree-rule",
3
+ "version": "1.0.2",
4
+ "description": "Memorytree:DSH 本地记忆树插件。四枝分层(主干/情感枝/任务枝/判断叶)、按作用域隔离、逐字证据与审计、离线 BM25 + 字符 n-gram 检索、星图看板与日记索引;可选本地情感候选采集(默认关闭、不调 LLM);不联网、零外部服务。",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./icon": "./icon.svg",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "client.js",
18
+ "lib",
19
+ "bin",
20
+ "docs",
21
+ "examples",
22
+ "tests",
23
+ "locale",
24
+ "icon.svg",
25
+ "cordis.patch.yml",
26
+ "README.md",
27
+ "CHANGELOG.md",
28
+ "LICENSE"
29
+ ],
30
+ "keywords": [
31
+ "dsh",
32
+ "dsh-plugin",
33
+ "memory",
34
+ "memory-tree",
35
+ "knowledge-base",
36
+ "sqlite",
37
+ "bm25",
38
+ "local-first",
39
+ "agents"
40
+ ],
41
+ "license": "MIT",
42
+ "author": "Memorytree contributors",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/ninihao1743/dsh-memorytree-rule.git"
46
+ },
47
+ "homepage": "https://github.com/ninihao1743/dsh-memorytree-rule#readme",
48
+ "bugs": {
49
+ "url": "https://github.com/ninihao1743/dsh-memorytree-rule/issues"
50
+ },
51
+ "engines": {
52
+ "node": ">=22.13.0"
53
+ },
54
+ "scripts": {
55
+ "test": "node --test tests/memory-tree.test.mjs tests/renumber.test.mjs tests/trunk-bucket.test.mjs tests/regressions.test.mjs tests/emotion.test.mjs",
56
+ "migrate": "node bin/mt.mjs migrate --apply",
57
+ "doctor": "node bin/mt.mjs doctor",
58
+ "report": "node bin/mt.mjs report",
59
+ "diary": "node bin/mt.mjs diary auto"
60
+ },
61
+ "peerDependencies": {
62
+ "@deepseek-ai/dsh-tools": ">=0.2.0-rc.2 <0.3.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "@deepseek-ai/dsh-tools": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "dsh": {
70
+ "bundle": {
71
+ "patch": "./cordis.patch.yml"
72
+ },
73
+ "client": {
74
+ "platform": "web",
75
+ "immediately": true,
76
+ "inject": [
77
+ "@deepseek-ai/dsh-client-ui-slots"
78
+ ]
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,215 @@
1
+ // tests/emotion.test.mjs — 情感枝自动收录:采集、打分、脱敏、候选表、预算与迁移。
2
+ import test from "node:test";
3
+ import assert from "node:assert/strict";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { DatabaseSync } from "node:sqlite";
8
+ import { openMemoryDb } from "../lib/db.mjs";
9
+ import { MemoryStore } from "../lib/store.mjs";
10
+ import { currentVersion, SCHEMA_VERSION } from "../lib/schema.mjs";
11
+ import { localDate } from "../lib/diary.mjs";
12
+ import {
13
+ budgetFor,
14
+ candidateStats,
15
+ captureEmotionEvent,
16
+ classifyEvent,
17
+ extractText,
18
+ listCandidates,
19
+ markCandidates,
20
+ recordReview,
21
+ redactForCandidate,
22
+ scoreCandidate,
23
+ } from "../lib/emotion.mjs";
24
+
25
+ function makeRuntime(config = {}) {
26
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-emo-"));
27
+ const rt = {
28
+ config: { emotionCapture: true, emotionMinScore: 35, emotionPluginCwdPatterns: ["plugins"], ...config },
29
+ paths: { home: dir },
30
+ _emotionContext: new Map(),
31
+ open() {
32
+ if (!this._store) {
33
+ const db = openMemoryDb(path.join(dir, "memory.db"));
34
+ this._store = new MemoryStore(db, { clock: () => Date.now() });
35
+ }
36
+ return this._store;
37
+ },
38
+ close() {
39
+ try {
40
+ this._store?.close();
41
+ } catch {
42
+ /* 忽略 */
43
+ }
44
+ this._store = null;
45
+ },
46
+ };
47
+ return {
48
+ rt,
49
+ dir,
50
+ cleanup() {
51
+ rt.close();
52
+ fs.rmSync(dir, { recursive: true, force: true });
53
+ },
54
+ };
55
+ }
56
+
57
+ const mainSession = { header: { id: "s-main", cwd: "C:\\work\\main" } };
58
+ const pluginSession = { header: { id: "s-plugin", cwd: "C:\\work\\plugins\\chat" } };
59
+
60
+ function userEvent(text, sourceKind = "user") {
61
+ return { type: "user/message", data: { role: "user", source: { kind: sourceKind }, content: [{ type: "text", text }] } };
62
+ }
63
+
64
+ function assistantEvent(text) {
65
+ return { type: "assistant/message", data: { message: { role: "assistant", content: [{ type: "text", text }] } } };
66
+ }
67
+
68
+ test("提取正文:只取 text 块,跳过运行时上下文与纯代码围栏", () => {
69
+ assert.equal(extractText(userEvent("我今天有点难过")), "我今天有点难过");
70
+ assert.equal(extractText(assistantEvent("我在想,也许你说得对。")), "我在想,也许你说得对。");
71
+ assert.equal(extractText(userEvent("Current runtime context. 当前时间 2026-11-18")), "");
72
+ assert.equal(extractText(userEvent("```\nconst x = 1\n```")), "");
73
+ });
74
+
75
+ test("打分:相处/工作/插件三类都能过 35 分门槛", () => {
76
+ const relationship = scoreCandidate("我今天很难过,想起以前的事,眼泪止不住。", "user", "relationship");
77
+ assert.ok(relationship.score >= 35, JSON.stringify(relationship));
78
+ const work = scoreCandidate("又崩了,搞了一晚上还是失败,白忙。", "assistant", "work");
79
+ assert.ok(work.score >= 35, JSON.stringify(work));
80
+ const plugin = scoreCandidate("这条我不回,太像挑事了,访客又在挑衅。", "assistant", "plugin");
81
+ assert.ok(plugin.score >= 35, JSON.stringify(plugin));
82
+ assert.ok(scoreCandidate("你好", "user", "relationship").score < 35);
83
+ });
84
+
85
+ test("分类:主会话用户 / 插件 cwd / 助手工作复盘", () => {
86
+ assert.equal(classifyEvent(mainSession, userEvent("我今天很难过,想起以前的事。")).category, "relationship");
87
+ assert.equal(classifyEvent(mainSession, userEvent("调度器发来的提醒,今天该做日结了。", "schedule")).category, "work");
88
+ assert.equal(
89
+ classifyEvent(pluginSession, userEvent("[访客甲 (0123456789ABCDEF0123456789ABCDEF)] 你好"), "x", { pluginCwdPatterns: ["plugins"] }).category,
90
+ "plugin",
91
+ );
92
+ assert.equal(classifyEvent(mainSession, assistantEvent("又崩了,报错修了一晚上,还是失败。")).category, "work");
93
+ });
94
+
95
+ test("默认关闭:没有显式 emotionCapture:true 时不采集", () => {
96
+ const { rt, cleanup } = makeRuntime({ emotionCapture: false });
97
+ try {
98
+ const res = captureEmotionEvent(rt, mainSession, userEvent("我今天很难过,想起以前的事。"));
99
+ assert.equal(res.ok, false);
100
+ assert.equal(res.skipped, "disabled");
101
+ } finally {
102
+ cleanup();
103
+ }
104
+ });
105
+
106
+ test("噪声:系统提醒与调度包装不进候选", () => {
107
+ assert.equal(extractText(userEvent("<system-reminder>\nThe following workspace instructions may be relevant.")), "");
108
+ assert.equal(extractText(userEvent("[SCHEDULE REMINDER]\nThis is a scheduled message from the user\nreminder_prompt_json: \"...\"")), "");
109
+ });
110
+
111
+ test("脱敏:访客昵称+OpenID 变访客,@提及变某人", () => {
112
+ const out = redactForCandidate("[你好 (0123456789ABCDEF0123456789ABCDEF)] 你好 (@you) 我的邮箱 a@b.com");
113
+ assert.match(out, /\[访客\]/);
114
+ assert.match(out, /@某人/);
115
+ assert.doesNotMatch(out, /0123456789ABCDEF0123456789ABCDEF/);
116
+ assert.doesNotMatch(out, /a@b\.com/);
117
+ });
118
+
119
+ test("采集:入表、去重、列表、标记、统计", () => {
120
+ const { rt, dir, cleanup } = makeRuntime();
121
+ try {
122
+ const event = userEvent("我今天很难过,想起以前的事,眼泪止不住。");
123
+ const first = captureEmotionEvent(rt, mainSession, event);
124
+ assert.equal(first.ok, true, JSON.stringify(first));
125
+ const again = captureEmotionEvent(rt, mainSession, event);
126
+ assert.equal(again.skipped, "duplicate");
127
+ const rows = listCandidates(rt.open().db, { day: first.day });
128
+ assert.equal(rows.length, 1);
129
+ const marked = markCandidates(rt.open().db, [rows[0].id], "accepted", [99]);
130
+ assert.equal(marked.updated, 1);
131
+ const accepted = listCandidates(rt.open().db, { day: first.day, status: "accepted" });
132
+ assert.equal(accepted[0].nodeId, 99);
133
+ const stats = candidateStats(rt.open().db, first.day);
134
+ assert.equal(stats.total, 1);
135
+ assert.equal(stats.byCategory.relationship, 1);
136
+ assert.equal(stats.byStatus.accepted, 1);
137
+ assert.ok(fs.existsSync(path.join(dir, "memory.db")));
138
+ } finally {
139
+ cleanup();
140
+ }
141
+ });
142
+
143
+ test("上限:同一会话最多 6 条,插件类别最多 4 条", () => {
144
+ const { rt, cleanup } = makeRuntime();
145
+ try {
146
+ for (let i = 0; i < 7; i++) {
147
+ captureEmotionEvent(rt, mainSession, userEvent("我今天很难过,想起以前的事,第" + i + "次。"));
148
+ }
149
+ const relationshipRows = listCandidates(rt.open().db, { day: localDate() });
150
+ assert.equal(relationshipRows.length, 6);
151
+
152
+ for (let i = 0; i < 6; i++) {
153
+ captureEmotionEvent(rt, pluginSession, assistantEvent("这条我不回,太像挑事了,访客又在挑衅,第" + i + "次。"));
154
+ }
155
+ const all = listCandidates(rt.open().db, { day: localDate() });
156
+ assert.equal(all.length, 10); // 6 relationship + 4 plugin
157
+ } finally {
158
+ cleanup();
159
+ }
160
+ });
161
+
162
+ test("预算与日结记账:账本缺失时不冒充有账本", () => {
163
+ const { rt, cleanup } = makeRuntime();
164
+ try {
165
+ const b = budgetFor(rt, {});
166
+ assert.equal(b.ok, true);
167
+ assert.equal(b.ledger, false);
168
+ assert.equal(b.over, false);
169
+ assert.equal(b.capCny, 0.3);
170
+ const r = recordReview(rt.open().db, {
171
+ day: "2026-11-18",
172
+ candidates: 3,
173
+ written: 1,
174
+ dismissed: 2,
175
+ costCny: 0.01,
176
+ tokens: 123,
177
+ note: "测试",
178
+ });
179
+ assert.ok(r.id > 0);
180
+ } finally {
181
+ cleanup();
182
+ }
183
+ });
184
+
185
+ test("迁移:新库 v6 有候选表/ review 表,v5 空库能升到 v6", () => {
186
+ const { rt, cleanup } = makeRuntime();
187
+ try {
188
+ const store = rt.open();
189
+ assert.equal(currentVersion(store.db), SCHEMA_VERSION);
190
+ assert.equal(SCHEMA_VERSION, 6);
191
+ const tables = new Set(
192
+ store.db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((r) => r.name),
193
+ );
194
+ assert.ok(tables.has("emotion_candidate"));
195
+ assert.ok(tables.has("emotion_review"));
196
+ } finally {
197
+ cleanup();
198
+ }
199
+
200
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-emo-mig-"));
201
+ const file = path.join(dir, "memory.db");
202
+ const old = new DatabaseSync(file);
203
+ old.exec("PRAGMA user_version = 5");
204
+ old.close();
205
+ const db = openMemoryDb(file);
206
+ try {
207
+ assert.equal(currentVersion(db), 6);
208
+ const names = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((r) => r.name));
209
+ assert.ok(names.has("emotion_candidate"));
210
+ assert.ok(names.has("emotion_review"));
211
+ } finally {
212
+ db.close();
213
+ fs.rmSync(dir, { recursive: true, force: true });
214
+ }
215
+ });