dsh-sixlayer-memory 0.0.0-stage → 2.0.3
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/CHANGELOG.md +123 -0
- package/README.md +292 -3
- package/catalog/.index.json +111704 -0
- package/catalog/parts.json +8808 -0
- package/cordis.patch.yml +8 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +51 -0
- package/docs//347/224/237/345/221/275/345/221/250/346/234/237-/350/207/252/345/212/250/345/217/254/345/233/236/344/270/216/345/200/231/351/200/211.md +103 -0
- package/icon.svg +8 -0
- package/lib/client.js +1209 -0
- package/lib/index.js +741 -0
- package/lib/memory/affect-alert.js +60 -0
- package/lib/memory/affect-events.js +201 -0
- package/lib/memory/affect-report.js +61 -0
- package/lib/memory/api.js +194 -0
- package/lib/memory/crypto.js +68 -0
- package/lib/memory/detail.js +43 -0
- package/lib/memory/embed.js +394 -0
- package/lib/memory/emotion.js +99 -0
- package/lib/memory/explain.js +207 -0
- package/lib/memory/importer.js +215 -0
- package/lib/memory/inject.js +193 -0
- package/lib/memory/ledger.js +101 -0
- package/lib/memory/lifecycle.js +491 -0
- package/lib/memory/notify.js +164 -0
- package/lib/memory/policy.js +182 -0
- package/lib/memory/qq-official.js +196 -0
- package/lib/memory/qq.js +326 -0
- package/lib/memory/recorder.js +241 -0
- package/lib/memory/redact.js +120 -0
- package/lib/memory/scanners.js +142 -0
- package/lib/memory/schema.js +205 -0
- package/lib/memory/service-plugin.js +69 -0
- package/lib/memory/service.js +123 -0
- package/lib/memory/shadow.js +133 -0
- package/lib/memory/store.js +1138 -0
- package/lib/memory/timeline.js +74 -0
- package/lib/memory/tokenize.js +66 -0
- package/lib/memory/tools.js +1371 -0
- package/lib/memory/util.js +129 -0
- package/lib/parts/index.js +154 -0
- package/lib/parts/installer.js +294 -0
- package/lib/parts/jobs.js +91 -0
- package/lib/parts/library.js +91 -0
- package/lib/probe-plugin.js +38 -0
- package/lib/voice/board-asr.js +31 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +114 -3
- package/tools/backfill-affect.mjs +82 -0
- package/tools/eval.mjs +88 -0
- package/tools/p1.mjs +108 -0
- package/tools/p10.mjs +36 -0
- package/tools/p11.mjs +51 -0
- package/tools/p12.mjs +53 -0
- package/tools/p13.mjs +65 -0
- package/tools/p14.mjs +66 -0
- package/tools/p15.mjs +43 -0
- package/tools/p16.mjs +42 -0
- package/tools/p17.mjs +29 -0
- package/tools/p18.mjs +48 -0
- package/tools/p19.mjs +50 -0
- package/tools/p2.mjs +59 -0
- package/tools/p20.mjs +54 -0
- package/tools/p21.mjs +42 -0
- package/tools/p22.mjs +32 -0
- package/tools/p23.mjs +43 -0
- package/tools/p24.mjs +40 -0
- package/tools/p25.mjs +151 -0
- package/tools/p26.mjs +113 -0
- package/tools/p27.mjs +89 -0
- package/tools/p28.mjs +60 -0
- package/tools/p3.mjs +54 -0
- package/tools/p4.mjs +73 -0
- package/tools/p5.mjs +117 -0
- package/tools/p6.mjs +122 -0
- package/tools/p8.mjs +50 -0
- package/tools/p9.mjs +35 -0
- package/tools/phase2.mjs +159 -0
- package/tools/preflight.mjs +320 -0
- package/tools/push-via-api.mjs +187 -0
- package/tools/quarterly.mjs +129 -0
- package/tools/refresh-catalog.mjs +60 -0
- package/tools/register-bundle.mjs +38 -0
- package/tools/review.mjs +156 -0
- package/tools/selfcheck.mjs +80 -0
- package/tools/smoke.mjs +112 -0
- package/tools/testset-v1.json +70 -0
- package/tools/validate-tools.mjs +150 -0
- package/tools/verify-all.mjs +39 -0
- package/tools/write-chain.mjs +139 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* schema.js — 六层记忆库 DDL 与迁移(schema v3)。
|
|
3
|
+
*
|
|
4
|
+
* 分层口径来自 luanyujia-workbench《总纲》:
|
|
5
|
+
* L0 宪法 / L1 共享层 / L2 场景私有 / L3 个人层 / L4 运行时 / L5 归档
|
|
6
|
+
* 本库只存 L1/L2/L3 的正文;L0 只存引用(版本号 + 哈希 + 指针),L4 只存能力实现标识,L5 是冷区。
|
|
7
|
+
*
|
|
8
|
+
* v1 → v2(W2):
|
|
9
|
+
* - records.scan_result 存扫描命中(JSON),便于事后回看"当时为什么这么判"
|
|
10
|
+
* - records.identity_id 调用方身份派生标识(owner / agent / unknown),不存原始凭证
|
|
11
|
+
* - review_queue 增加 note 列
|
|
12
|
+
*
|
|
13
|
+
* v2 → v3(二期):
|
|
14
|
+
* - records.legacy_ref / legacy_source 导入时保留"从哪来"的指针(不存正文)
|
|
15
|
+
* - traces 记录仪索引表(正文 JSONL 才是 append-only 真源,此表只做按 trace_id 查)
|
|
16
|
+
*
|
|
17
|
+
* v3 → v4(P1):
|
|
18
|
+
* - records.batch_id 同一会话/同一批写入的标识,用于 L2 组合攻击判定
|
|
19
|
+
*
|
|
20
|
+
* v4 → v5(迁移自 luanyujia-workbench 记忆机制):
|
|
21
|
+
* - handoffs 每个场景一份「§〇 交接」,覆盖写、≤4 KB、五小节
|
|
22
|
+
*
|
|
23
|
+
* v5 → v6(协作与派单机制):
|
|
24
|
+
* - tasks 派单台账:状态机 sent→delivered→acked→done/failed,超时进 overdue
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
export const SCHEMA_VERSION = 9
|
|
28
|
+
|
|
29
|
+
export const DDL = `
|
|
30
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
31
|
+
key TEXT PRIMARY KEY,
|
|
32
|
+
value TEXT NOT NULL
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
CREATE TABLE IF NOT EXISTS records (
|
|
36
|
+
record_id TEXT PRIMARY KEY,
|
|
37
|
+
layer TEXT NOT NULL, -- L0..L5
|
|
38
|
+
depth INTEGER NOT NULL DEFAULT 0, -- 0 = 摘要层
|
|
39
|
+
content TEXT NOT NULL,
|
|
40
|
+
summary TEXT,
|
|
41
|
+
content_hash TEXT NOT NULL,
|
|
42
|
+
sad_level TEXT NOT NULL DEFAULT 'A', -- S / A / D
|
|
43
|
+
trust_level TEXT NOT NULL DEFAULT 'unverified',
|
|
44
|
+
source_channel TEXT NOT NULL DEFAULT 'unknown',
|
|
45
|
+
origin TEXT NOT NULL DEFAULT 'manual',-- manual / legacy_import / shadow
|
|
46
|
+
principal_id TEXT,
|
|
47
|
+
identity_id TEXT, -- owner / agent / unknown(派生标识)
|
|
48
|
+
project_id TEXT,
|
|
49
|
+
session_id TEXT,
|
|
50
|
+
alpha REAL,
|
|
51
|
+
beta REAL,
|
|
52
|
+
scored INTEGER NOT NULL DEFAULT 0,
|
|
53
|
+
status TEXT NOT NULL DEFAULT 'active',-- active / pending / quarantined / archived / rejected
|
|
54
|
+
pending_review INTEGER NOT NULL DEFAULT 0,
|
|
55
|
+
conflict_of TEXT,
|
|
56
|
+
scan_result TEXT, -- JSON: {flags,injection,sensitive}
|
|
57
|
+
legacy_ref TEXT, -- 导入来源指针(如 memories.json#3),不存正文
|
|
58
|
+
legacy_source TEXT, -- 导入来源文件路径
|
|
59
|
+
batch_id TEXT, -- 同一会话/同一批写入(L2 组合判定)
|
|
60
|
+
affect_label TEXT, -- 情绪标签(neutral / positive / negative / urgent)
|
|
61
|
+
affect_valence REAL, -- 效价 -1..1
|
|
62
|
+
affect_arousal REAL, -- 唤醒度 0..1
|
|
63
|
+
importance REAL NOT NULL DEFAULT 0.5, -- 综合重要性 0..1(情绪 + 访问 + 时效)
|
|
64
|
+
created_at TEXT NOT NULL,
|
|
65
|
+
updated_at TEXT NOT NULL
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
CREATE INDEX IF NOT EXISTS idx_records_hash ON records(content_hash);
|
|
69
|
+
CREATE INDEX IF NOT EXISTS idx_records_layer ON records(layer, status);
|
|
70
|
+
CREATE INDEX IF NOT EXISTS idx_records_project ON records(project_id, created_at);
|
|
71
|
+
CREATE INDEX IF NOT EXISTS idx_records_status ON records(status, pending_review);
|
|
72
|
+
|
|
73
|
+
CREATE TABLE IF NOT EXISTS tags (
|
|
74
|
+
record_id TEXT NOT NULL,
|
|
75
|
+
tag TEXT NOT NULL,
|
|
76
|
+
PRIMARY KEY (record_id, tag)
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
-- 场景交接(来自 luanyujia-workbench 记忆机制):
|
|
80
|
+
-- 每个场景一份,覆盖写;sections 是 JSON,五小节固定键;
|
|
81
|
+
-- 体量上限 4 KB 由写入端强制,bytes 存实际字节数供体检。
|
|
82
|
+
CREATE TABLE IF NOT EXISTS handoffs (
|
|
83
|
+
scene TEXT PRIMARY KEY,
|
|
84
|
+
title TEXT,
|
|
85
|
+
sections TEXT NOT NULL,
|
|
86
|
+
bytes INTEGER NOT NULL,
|
|
87
|
+
updated_at TEXT NOT NULL,
|
|
88
|
+
updated_by TEXT
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
-- 派单台账(协作/派单机制):
|
|
92
|
+
-- 状态机 sent → delivered → acked → done / failed;超时由查询时判定为 overdue。
|
|
93
|
+
-- messages 用于执行「同一件事 ≤3 条消息」的上限。
|
|
94
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
95
|
+
task_id TEXT PRIMARY KEY,
|
|
96
|
+
kind TEXT NOT NULL, -- dispatch | notice
|
|
97
|
+
from_scene TEXT NOT NULL,
|
|
98
|
+
to_scene TEXT NOT NULL,
|
|
99
|
+
title TEXT NOT NULL,
|
|
100
|
+
phenomenon TEXT,
|
|
101
|
+
how_to TEXT,
|
|
102
|
+
how_verify TEXT,
|
|
103
|
+
need_reply INTEGER NOT NULL DEFAULT 1,
|
|
104
|
+
status TEXT NOT NULL, -- sent | delivered | acked | done | failed | closed
|
|
105
|
+
messages INTEGER NOT NULL DEFAULT 1,
|
|
106
|
+
created_at TEXT NOT NULL,
|
|
107
|
+
updated_at TEXT NOT NULL,
|
|
108
|
+
deadline_at TEXT,
|
|
109
|
+
ack_json TEXT
|
|
110
|
+
);
|
|
111
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_to ON tasks(to_scene, status);
|
|
112
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_from ON tasks(from_scene, status);
|
|
113
|
+
|
|
114
|
+
CREATE TABLE IF NOT EXISTS review_queue (
|
|
115
|
+
record_id TEXT PRIMARY KEY,
|
|
116
|
+
reason TEXT NOT NULL,
|
|
117
|
+
created_at TEXT NOT NULL,
|
|
118
|
+
decided_at TEXT,
|
|
119
|
+
decision TEXT,
|
|
120
|
+
note TEXT
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
-- 检索索引:正文按 bigram 分词后写入 body(见 tokenize.js)
|
|
124
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS records_fts USING fts5(
|
|
125
|
+
record_id UNINDEXED,
|
|
126
|
+
body,
|
|
127
|
+
tokenize='unicode61'
|
|
128
|
+
);
|
|
129
|
+
|
|
130
|
+
-- 记录仪索引:JSONL 是 append-only 真源,这张表只为了按 trace_id 快速回放
|
|
131
|
+
CREATE TABLE IF NOT EXISTS traces (
|
|
132
|
+
trace_id TEXT PRIMARY KEY,
|
|
133
|
+
seq INTEGER NOT NULL,
|
|
134
|
+
at TEXT NOT NULL,
|
|
135
|
+
op TEXT NOT NULL,
|
|
136
|
+
principal_id TEXT,
|
|
137
|
+
query_hash TEXT,
|
|
138
|
+
query_preview TEXT,
|
|
139
|
+
hits TEXT,
|
|
140
|
+
injected TEXT,
|
|
141
|
+
tokens_in INTEGER,
|
|
142
|
+
tokens_out INTEGER,
|
|
143
|
+
duration_ms INTEGER,
|
|
144
|
+
prev_hash TEXT,
|
|
145
|
+
hash TEXT NOT NULL
|
|
146
|
+
);
|
|
147
|
+
CREATE INDEX IF NOT EXISTS idx_traces_at ON traces(at);
|
|
148
|
+
CREATE INDEX IF NOT EXISTS idx_traces_op ON traces(op, at);
|
|
149
|
+
|
|
150
|
+
CREATE TABLE IF NOT EXISTS affect_events (
|
|
151
|
+
event_id TEXT PRIMARY KEY,
|
|
152
|
+
session_id TEXT,
|
|
153
|
+
source TEXT NOT NULL DEFAULT 'qq',
|
|
154
|
+
occurred_at TEXT NOT NULL,
|
|
155
|
+
label TEXT NOT NULL,
|
|
156
|
+
valence REAL,
|
|
157
|
+
arousal REAL,
|
|
158
|
+
excerpt TEXT,
|
|
159
|
+
excerpt_hash TEXT,
|
|
160
|
+
triggers TEXT,
|
|
161
|
+
created_at TEXT NOT NULL
|
|
162
|
+
);
|
|
163
|
+
CREATE INDEX IF NOT EXISTS idx_affect_events_time ON affect_events(occurred_at);
|
|
164
|
+
CREATE INDEX IF NOT EXISTS idx_affect_events_label ON affect_events(label, occurred_at);
|
|
165
|
+
|
|
166
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
167
|
+
from_id TEXT NOT NULL,
|
|
168
|
+
to_id TEXT NOT NULL,
|
|
169
|
+
kind TEXT NOT NULL,
|
|
170
|
+
weight REAL NOT NULL DEFAULT 1,
|
|
171
|
+
created_at TEXT NOT NULL,
|
|
172
|
+
PRIMARY KEY (from_id, to_id, kind)
|
|
173
|
+
);
|
|
174
|
+
CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(from_id, kind);
|
|
175
|
+
CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(to_id, kind);
|
|
176
|
+
`
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 逐版本升级语句。只在 meta.schema_version 小于代码版本时执行。
|
|
180
|
+
* 每条都必须是幂等的(SQLite 的 ADD COLUMN 不幂等,所以先查 pragma)。
|
|
181
|
+
*/
|
|
182
|
+
export const MIGRATIONS = {
|
|
183
|
+
9: [],
|
|
184
|
+
8: [],
|
|
185
|
+
7: [
|
|
186
|
+
{ table: 'records', column: 'affect_label', sql: 'ALTER TABLE records ADD COLUMN affect_label TEXT' },
|
|
187
|
+
{ table: 'records', column: 'affect_valence', sql: 'ALTER TABLE records ADD COLUMN affect_valence REAL' },
|
|
188
|
+
{ table: 'records', column: 'affect_arousal', sql: 'ALTER TABLE records ADD COLUMN affect_arousal REAL' },
|
|
189
|
+
{ table: 'records', column: 'importance', sql: 'ALTER TABLE records ADD COLUMN importance REAL NOT NULL DEFAULT 0.5' },
|
|
190
|
+
],
|
|
191
|
+
6: [],
|
|
192
|
+
5: [],
|
|
193
|
+
4: [
|
|
194
|
+
{ table: 'records', column: 'batch_id', sql: 'ALTER TABLE records ADD COLUMN batch_id TEXT' },
|
|
195
|
+
],
|
|
196
|
+
3: [
|
|
197
|
+
{ table: 'records', column: 'legacy_ref', sql: 'ALTER TABLE records ADD COLUMN legacy_ref TEXT' },
|
|
198
|
+
{ table: 'records', column: 'legacy_source', sql: 'ALTER TABLE records ADD COLUMN legacy_source TEXT' },
|
|
199
|
+
],
|
|
200
|
+
2: [
|
|
201
|
+
{ table: 'records', column: 'scan_result', sql: 'ALTER TABLE records ADD COLUMN scan_result TEXT' },
|
|
202
|
+
{ table: 'records', column: 'identity_id', sql: 'ALTER TABLE records ADD COLUMN identity_id TEXT' },
|
|
203
|
+
{ table: 'review_queue', column: 'note', sql: 'ALTER TABLE review_queue ADD COLUMN note TEXT' },
|
|
204
|
+
],
|
|
205
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* service-plugin.js — 服务化独立插件行(P6)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一行:
|
|
5
|
+
* 主插件(index.js)里调用 ctx.provide 一旦抛错,会把整个插件带崩,
|
|
6
|
+
* 连工具都不注册(2026-10-31 实测过一次)。拆成独立的插件行后:
|
|
7
|
+
* - 主插件只负责工具/注入/RPC,永远能加载;
|
|
8
|
+
* - 这一行只负责把记忆暴露成 Cordis 服务,挂了只少一个服务。
|
|
9
|
+
*
|
|
10
|
+
* 配置(cordis.patch.yml):
|
|
11
|
+
* - insert:
|
|
12
|
+
* - id: memory-core-service
|
|
13
|
+
* name: file:///D:/001/CH002/dsh-memory-core/lib/service-plugin.js
|
|
14
|
+
* config:
|
|
15
|
+
* dataDir: 'D:\001\CH002\dsh-memory-data'
|
|
16
|
+
* serviceName: memory
|
|
17
|
+
*/
|
|
18
|
+
import MemoryStore from './store.js'
|
|
19
|
+
import { buildService } from './service.js'
|
|
20
|
+
|
|
21
|
+
export const name = 'workbench-service'
|
|
22
|
+
|
|
23
|
+
export function apply(ctx, config = {}) {
|
|
24
|
+
const dataDir = String(config?.dataDir ?? 'D:\\001\\CH002\\dsh-memory-data')
|
|
25
|
+
const serviceName = String(config?.serviceName ?? 'workbench')
|
|
26
|
+
const logger = ctx.logger
|
|
27
|
+
|
|
28
|
+
let store = null
|
|
29
|
+
try {
|
|
30
|
+
store = new MemoryStore({ dataDir, authority: config?.authority ?? 'shadow' }).open()
|
|
31
|
+
} catch (error) {
|
|
32
|
+
logger?.warn?.(`workbench-service: 记忆库打不开,服务进入降级:${error?.message ?? error}`)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const service = buildService({ store })
|
|
36
|
+
// 一个大服务,两个命名空间:workbench.memory / workbench.parts
|
|
37
|
+
const workbench = {
|
|
38
|
+
...service,
|
|
39
|
+
memory: service,
|
|
40
|
+
parts: {
|
|
41
|
+
list: () => service.parts(),
|
|
42
|
+
compose: (options) => service.compose(options ?? {}),
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
ctx.provide(serviceName, workbench)
|
|
48
|
+
logger?.info?.(`workbench-service: 已提供服务 ${serviceName}(apiVersion 1)`)
|
|
49
|
+
} catch (error) {
|
|
50
|
+
logger?.warn?.(`workbench-service: 服务 ${serviceName} 注册失败:${error?.message ?? error}`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 兼容旧消费者:memory 别名指向同一个对象
|
|
54
|
+
if (serviceName !== 'memory') {
|
|
55
|
+
try {
|
|
56
|
+
ctx.provide('memory', workbench)
|
|
57
|
+
} catch (error) {
|
|
58
|
+
logger?.warn?.(`workbench-service: memory 别名注册失败:${error?.message ?? error}`)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
ctx.effect(() => () => {
|
|
63
|
+
try {
|
|
64
|
+
store?.close()
|
|
65
|
+
} catch {
|
|
66
|
+
/* 忽略 */
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* service.js — 记忆底座对外服务(P6 服务化)。
|
|
3
|
+
*
|
|
4
|
+
* 设计口径(docs/方案-服务化.md):
|
|
5
|
+
* - 只暴露窄契约:recall / remember / forget / status;
|
|
6
|
+
* - recall 只给指针,不给正文;S 级永不返回;未验证来源不给摘要;
|
|
7
|
+
* - remember 走完整写入链,不绕过闸门;
|
|
8
|
+
* - forget 只降层/归档,永不物理删除;
|
|
9
|
+
* - 库不可用时返回 { degraded: true },不抛异常。
|
|
10
|
+
*
|
|
11
|
+
* 这个文件不依赖 Cordis:传入 store 就能跑,便于单测。
|
|
12
|
+
*/
|
|
13
|
+
import { nowIso } from './util.js'
|
|
14
|
+
import { listParts, compose as composePack } from '../parts/index.js'
|
|
15
|
+
|
|
16
|
+
export const SERVICE_API_VERSION = 1
|
|
17
|
+
|
|
18
|
+
const POINTER_FIELDS = ['record_id', 'layer', 'sad_level', 'created_at']
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {{store: any, injector?: any}} options
|
|
22
|
+
*/
|
|
23
|
+
export function buildService({ store = null, injector = null } = {}) {
|
|
24
|
+
const degraded = (reason) => ({ pointers: [], degraded: true, reason: String(reason ?? 'store unavailable') })
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
apiVersion: SERVICE_API_VERSION,
|
|
28
|
+
|
|
29
|
+
/** 召回:只给指针。 */
|
|
30
|
+
recall({ query = '', principal = null, scope = 'personal', topK = 5 } = {}) {
|
|
31
|
+
if (!store) return degraded('记忆库不可用')
|
|
32
|
+
if (scope === 'group') {
|
|
33
|
+
// v1 没有群共享层:群聊一律拿不到个人记忆(策略矩阵的硬要求)
|
|
34
|
+
return { pointers: [], note: 'v1 暂无群共享层,群聊不返回个人记忆' }
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
const rows = store.search({ query: String(query ?? ''), topK, principalId: principal })
|
|
38
|
+
const pointers = rows.map((r) => {
|
|
39
|
+
const ptr = {}
|
|
40
|
+
for (const k of POINTER_FIELDS) ptr[k] = r[k]
|
|
41
|
+
// 未验证来源只给 id,不给摘要(公理 3)
|
|
42
|
+
if (r.trust_level !== 'unverified') ptr.summary = r.snippet
|
|
43
|
+
return ptr
|
|
44
|
+
})
|
|
45
|
+
return { pointers }
|
|
46
|
+
} catch (error) {
|
|
47
|
+
return degraded(error?.message ?? String(error))
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
/** 写入:走完整写入链(信任判定 → 扫描 → 分级 → 去重 → 闸门)。 */
|
|
52
|
+
remember({ content, source = 'plugin', principal = null, projectId = null, tags = [] } = {}) {
|
|
53
|
+
if (!store) return { degraded: true, reason: '记忆库不可用' }
|
|
54
|
+
const result = store.write({
|
|
55
|
+
content,
|
|
56
|
+
layer: 'L2',
|
|
57
|
+
sourceChannel: source,
|
|
58
|
+
origin: 'manual',
|
|
59
|
+
principalId: principal,
|
|
60
|
+
projectId,
|
|
61
|
+
tags: Array.isArray(tags) ? tags : [],
|
|
62
|
+
})
|
|
63
|
+
return {
|
|
64
|
+
record_id: result.record_id,
|
|
65
|
+
status: result.status,
|
|
66
|
+
trust_level: result.trust_level,
|
|
67
|
+
sad_level: result.sad_level,
|
|
68
|
+
dedup: Boolean(result.dedup),
|
|
69
|
+
skipped: Boolean(result.skipped),
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
/** 遗忘:只降层或归档,永不物理删除。 */
|
|
74
|
+
forget({ record_id, mode = 'archive' } = {}) {
|
|
75
|
+
if (!store) return { degraded: true, reason: '记忆库不可用' }
|
|
76
|
+
const id = String(record_id ?? '')
|
|
77
|
+
if (!id) throw new Error('memory.forget: 需要 record_id')
|
|
78
|
+
const row = store.db.prepare('SELECT record_id, status, depth FROM records WHERE record_id = ?').get(id)
|
|
79
|
+
if (!row) throw new Error('memory.forget: 没有记录 ' + id)
|
|
80
|
+
const now = nowIso()
|
|
81
|
+
if (mode === 'downgrade') {
|
|
82
|
+
store.db.prepare('UPDATE records SET depth = depth + 1, updated_at = ? WHERE record_id = ?').run(now, id)
|
|
83
|
+
return { record_id: id, status: 'downgraded', depth: row.depth + 1 }
|
|
84
|
+
}
|
|
85
|
+
store.db.prepare("UPDATE records SET status = 'archived', updated_at = ? WHERE record_id = ?").run(now, id)
|
|
86
|
+
return { record_id: id, status: 'archived' }
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
/** 健康摘要(给面板/监控)。 */
|
|
90
|
+
status() {
|
|
91
|
+
if (!store) return { degraded: true, reason: '记忆库不可用' }
|
|
92
|
+
try {
|
|
93
|
+
const s = store.stats()
|
|
94
|
+
return {
|
|
95
|
+
records: s.records,
|
|
96
|
+
active: s.active,
|
|
97
|
+
pending: s.pending,
|
|
98
|
+
sLevel: s.sLevel,
|
|
99
|
+
audit: s.audit,
|
|
100
|
+
schemaVersion: s.schemaVersion,
|
|
101
|
+
authority: s.authority,
|
|
102
|
+
}
|
|
103
|
+
} catch (error) {
|
|
104
|
+
return { degraded: true, reason: error?.message ?? String(error) }
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
/** 零件清单(理念:一切皆零件——记忆能力是可命名、可替换的小零件)。 */
|
|
109
|
+
parts() {
|
|
110
|
+
return listParts()
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
/** 按零件装配上下文包:给场景 + 零件列表,拼出可直接使用的记忆包。 */
|
|
114
|
+
compose({ scene = '', parts = null, seed = null, maxChars = 1200 } = {}) {
|
|
115
|
+
if (!store) return { degraded: true, reason: '记忆库不可用', text: '' }
|
|
116
|
+
try {
|
|
117
|
+
return composePack(store, { scene, parts, seed, maxChars })
|
|
118
|
+
} catch (error) {
|
|
119
|
+
return { degraded: true, reason: error?.message ?? String(error), text: '' }
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* shadow.js — 影子读:新旧两路并排,看新库有没有漏。
|
|
3
|
+
*
|
|
4
|
+
* 旧路 = `~\.mnemon` 的 memories.json(按 bigram 做轻量 BM25,不建索引、不改源);
|
|
5
|
+
* 新路 = 本地六层库的 search。
|
|
6
|
+
* 两路用"脱敏后内容的哈希"对齐到同一条记录,才能判"只有旧有 / 只有新有 / 都有"。
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { tokenize } from './tokenize.js'
|
|
12
|
+
import { redact, brief } from './redact.js'
|
|
13
|
+
import { sha256, normalizeContent } from './util.js'
|
|
14
|
+
|
|
15
|
+
export class LegacyIndex {
|
|
16
|
+
/** @param {{home?: string}} [options] */
|
|
17
|
+
constructor(options = {}) {
|
|
18
|
+
this.home = options.home ?? path.join(os.homedir(), '.mnemon')
|
|
19
|
+
this.entries = []
|
|
20
|
+
this.df = new Map()
|
|
21
|
+
this.loaded = false
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
load() {
|
|
25
|
+
if (this.loaded) return this
|
|
26
|
+
const file = path.join(this.home, 'runtime', 'memories.json')
|
|
27
|
+
let raw = []
|
|
28
|
+
if (fs.existsSync(file)) {
|
|
29
|
+
try {
|
|
30
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
31
|
+
raw = Array.isArray(parsed) ? parsed : parsed.entries ?? []
|
|
32
|
+
} catch {
|
|
33
|
+
raw = []
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (raw.length === 0) {
|
|
37
|
+
const md = path.join(this.home, 'runtime', 'MEMORY.md')
|
|
38
|
+
if (fs.existsSync(md)) {
|
|
39
|
+
raw = fs.readFileSync(md, 'utf8').split(/\n\s*§\s*\n/g).map((content) => ({ content }))
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
this.entries = raw
|
|
44
|
+
.filter((e) => e && typeof e.content === 'string' && e.content.trim())
|
|
45
|
+
.map((e, i) => {
|
|
46
|
+
const normalized = normalizeContent(e.content)
|
|
47
|
+
const sanitized = redact(normalized).text
|
|
48
|
+
const tokens = tokenize(`${brief(sanitized, 120)} ${sanitized}`)
|
|
49
|
+
return {
|
|
50
|
+
legacy_id: `L${String(i + 1).padStart(2, '0')}`,
|
|
51
|
+
target: e.target ?? 'memory',
|
|
52
|
+
sanitized,
|
|
53
|
+
content_hash: sha256(sanitized),
|
|
54
|
+
tokens: new Set(tokens),
|
|
55
|
+
length: tokens.length,
|
|
56
|
+
preview: brief(sanitized, 90),
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
for (const entry of this.entries) {
|
|
61
|
+
for (const token of entry.tokens) this.df.set(token, (this.df.get(token) ?? 0) + 1)
|
|
62
|
+
}
|
|
63
|
+
this.loaded = true
|
|
64
|
+
return this
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 轻量 BM25:idf × 命中率,够用来做一致性比对,不追求召回质量。 */
|
|
68
|
+
search(query, topK = 5) {
|
|
69
|
+
this.load()
|
|
70
|
+
const q = tokenize(String(query ?? ''))
|
|
71
|
+
if (q.length === 0) return []
|
|
72
|
+
const N = this.entries.length || 1
|
|
73
|
+
const rows = []
|
|
74
|
+
for (const entry of this.entries) {
|
|
75
|
+
let score = 0
|
|
76
|
+
let hit = 0
|
|
77
|
+
for (const token of q) {
|
|
78
|
+
if (!entry.tokens.has(token)) continue
|
|
79
|
+
hit += 1
|
|
80
|
+
const df = this.df.get(token) ?? 1
|
|
81
|
+
score += Math.log(1 + N / df)
|
|
82
|
+
}
|
|
83
|
+
if (hit === 0) continue
|
|
84
|
+
rows.push({
|
|
85
|
+
legacy_id: entry.legacy_id,
|
|
86
|
+
target: entry.target,
|
|
87
|
+
snippet: entry.preview,
|
|
88
|
+
score: score / Math.sqrt(Math.max(entry.length, 1)),
|
|
89
|
+
content_hash: entry.content_hash,
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
rows.sort((a, b) => b.score - a.score)
|
|
93
|
+
return rows.slice(0, topK)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
size() {
|
|
97
|
+
this.load()
|
|
98
|
+
return this.entries.length
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 影子读比对。
|
|
104
|
+
* @param {{store: any, index: LegacyIndex, query: string, topK?: number}} args
|
|
105
|
+
*/
|
|
106
|
+
export function shadowCompare({ store, index, query, topK = 5 }) {
|
|
107
|
+
const legacyHits = index.search(query, topK)
|
|
108
|
+
const newHits = store.search({ query, topK })
|
|
109
|
+
|
|
110
|
+
// 用 content_hash 把旧条目对齐到新记录
|
|
111
|
+
const byHash = new Map()
|
|
112
|
+
for (const hit of legacyHits) {
|
|
113
|
+
const row = store.db.prepare('SELECT record_id FROM records WHERE content_hash = ? LIMIT 1').get(hit.content_hash)
|
|
114
|
+
byHash.set(hit.legacy_id, row ? row.record_id : null)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const legacyIds = new Set(byHash.values())
|
|
118
|
+
const newIds = new Set(newHits.map((h) => h.record_id))
|
|
119
|
+
const both = newHits.filter((h) => legacyIds.has(h.record_id)).map((h) => h.record_id)
|
|
120
|
+
const onlyNew = newHits.filter((h) => !legacyIds.has(h.record_id)).map((h) => h.record_id)
|
|
121
|
+
const onlyLegacy = legacyHits.filter((h) => !byHash.get(h.legacy_id)).map((h) => h.legacy_id)
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
query,
|
|
125
|
+
legacy: legacyHits.map((h) => ({ ...h, record_id: byHash.get(h.legacy_id) ?? '' })),
|
|
126
|
+
mine: newHits.map((h) => ({ record_id: h.record_id, snippet: h.snippet, score: h.score })),
|
|
127
|
+
diff: { both, only_legacy: onlyLegacy, only_new: onlyNew },
|
|
128
|
+
consistent: onlyLegacy.length === 0,
|
|
129
|
+
legacy_count: index.size(),
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export default LegacyIndex
|