dsh-prime-memory 0.18.4 → 0.18.6

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.
@@ -1,176 +0,0 @@
1
- /**
2
- * 本地嵌入 worker:transformers.js 的模型加载与推理在本线程执行,主线程只
3
- * 投递文本、收回向量。onnxruntime-node 的 run/loadModel 是 setImmediate 回调里
4
- * 的同步调用(Promise 包装不卸载计算),留在主线程会冻结宿主事件循环——
5
- * dsh 页面一切交互无响应数秒的根因。
6
- *
7
- * 协议(与 src/store/local-embedding.ts 的 RealWorkerChannel 配对;自增 id):
8
- * - 入向:{id,type:'ping'} | {id,type:'warmup'} | {id,type:'embed',texts,priority}
9
- * - 出向:{id,ok:true,type:'pong'|'ready'|'embedded',vectors?}(向量经
10
- * transfer 列表零拷贝回传)| {id,ok:false,stage:'load'|'infer',error}
11
- * | {type:'fatal',error}
12
- *
13
- * 调度:单线程串行。embedBatch 拆成逐条 job、条间 setImmediate 让路——
14
- * 单条请求(priority,即召回 query)unshift 插队,最坏只等"正在算的那一条",
15
- * 不会被 reindex 批次(16/32 条 ≈5-10s)堵在队尾。
16
- *
17
- * 信任边界(沿 AGENTS.md 审查记录):runtime/ 目录在数据目录信任边界内,
18
- * 本线程按其 package.json createRequire 加载 transformers——对数据目录有写
19
- * 权限的进程理论上可植入恶意模块;模型文件逐文件 sha256 锁定,运行时代码
20
- * 无同级防护,完整修复需安装指纹设计,暂以文档化假设为准。
21
- */
22
- 'use strict';
23
-
24
- const { parentPort, workerData } = require('node:worker_threads');
25
- const path = require('node:path');
26
- const { createRequire } = require('node:module');
27
-
28
- /** 错误消息归一化(Error 取 message,其余 String 化)。 */
29
- function errMsg(err) {
30
- return err && err.message ? err.message : String(err);
31
- }
32
-
33
- const cfg = workerData || {};
34
- const RUNTIME_DIR = typeof cfg.runtimeDir === 'string' ? cfg.runtimeDir : '';
35
- const MODEL_DIR = typeof cfg.modelDir === 'string' ? cfg.modelDir : '';
36
- const POOLING = cfg.pooling === 'cls' ? 'cls' : 'mean';
37
- const DTYPE = typeof cfg.dtype === 'string' ? cfg.dtype : 'q8';
38
- const MAX_INPUT_CHARS = cfg.maxInputChars > 0 ? cfg.maxInputChars : 5000;
39
-
40
- let extractor = null; // pipeline('feature-extraction', …)
41
- let loadState = 'idle'; // idle | loading | ready | failed
42
- let loadPromise = null;
43
- let loadError = null;
44
-
45
- // ── 模型懒加载(首请求触发;失败后经 warmup 可重试,embed 请求失败快返回) ──
46
- function ensureLoaded() {
47
- if (loadState === 'ready') return Promise.resolve();
48
- if (loadState === 'loading' && loadPromise) return loadPromise;
49
- loadState = 'loading';
50
- loadError = null;
51
- loadPromise = (async () => {
52
- try {
53
- if (!RUNTIME_DIR || !MODEL_DIR) throw new Error('workerData 缺少 runtimeDir/modelDir');
54
- const req = createRequire(path.join(RUNTIME_DIR, 'package.json'));
55
- const mod = req('@huggingface/transformers');
56
- if (mod.env) {
57
- mod.env.allowRemoteModels = false;
58
- if (mod.env.allowLocalModels !== undefined) mod.env.allowLocalModels = true;
59
- }
60
- extractor = await mod.pipeline('feature-extraction', MODEL_DIR, { dtype: DTYPE });
61
- loadState = 'ready';
62
- } catch (err) {
63
- loadState = 'failed';
64
- loadError = errMsg(err);
65
- loadPromise = null; // 失败后下一次 warmup 重新走加载
66
- throw err;
67
- }
68
- })();
69
- return loadPromise;
70
- }
71
-
72
- // ── 推理队列(逐条 job;priority 插队;条间让路) ──
73
- const queue = []; // [{ request, index, text }]
74
- let pumping = false;
75
-
76
- function postReply(msg, transfer) {
77
- parentPort.postMessage(msg, transfer || []);
78
- }
79
-
80
- /** 请求全部条目完成 → 回执(transfer 向量缓冲零拷贝)。 */
81
- function settle(request) {
82
- if (request.failed || request.remaining !== 0) return;
83
- postReply(
84
- { id: request.id, ok: true, type: 'embedded', vectors: request.vectors },
85
- request.vectors.map((v) => v.buffer),
86
- );
87
- }
88
-
89
- /** 首个失败即回执错误,并移除该请求尚未开跑的条目(正在跑的至多 1 条,算完即弃)。 */
90
- function failRequest(request, error, stage) {
91
- if (request.failed) return;
92
- request.failed = true;
93
- for (let i = queue.length - 1; i >= 0; i--) {
94
- if (queue[i].request === request) queue.splice(i, 1);
95
- }
96
- postReply({ id: request.id, ok: false, stage: stage, error: errMsg(error) });
97
- }
98
-
99
- async function pump() {
100
- if (pumping) return;
101
- pumping = true;
102
- try {
103
- while (queue.length > 0) {
104
- const job = queue.shift();
105
- if (job.request.failed) continue;
106
- try {
107
- const result = await extractor([job.text.slice(0, MAX_INPUT_CHARS)], { pooling: POOLING, normalize: true });
108
- const data = result[0] && result[0].data;
109
- job.request.vectors[job.index] = data instanceof Float32Array ? data : new Float32Array(data);
110
- job.request.remaining -= 1;
111
- settle(job.request);
112
- } catch (err) {
113
- failRequest(job.request, err, 'infer');
114
- }
115
- // 条间让路:交还本线程事件循环,新消息(含 priority 插队)可在批间被处理
116
- await new Promise((resolve) => setImmediate(resolve));
117
- }
118
- } finally {
119
- pumping = false;
120
- }
121
- }
122
-
123
- function handleEmbed(msg) {
124
- const texts = Array.isArray(msg.texts) ? msg.texts : [];
125
- if (texts.length === 0) {
126
- postReply({ id: msg.id, ok: true, type: 'embedded', vectors: [] });
127
- return;
128
- }
129
- const request = { id: msg.id, vectors: new Array(texts.length), remaining: texts.length, failed: false };
130
- // 单条请求(召回 query)插队到队首;批次追加到队尾(批内条目间仍会被后来的插队)
131
- const priority = msg.priority === true && texts.length === 1;
132
- for (let i = 0; i < texts.length; i++) {
133
- const job = { request: request, index: i, text: String(texts[i] == null ? '' : texts[i]) };
134
- if (priority) queue.unshift(job);
135
- else queue.push(job);
136
- }
137
- void pump();
138
- }
139
-
140
- parentPort.on('message', (msg) => {
141
- if (!msg || typeof msg.id !== 'number' || typeof msg.type !== 'string') return;
142
- if (msg.type === 'ping') {
143
- postReply({ id: msg.id, ok: true, type: 'pong' });
144
- return;
145
- }
146
- if (msg.type === 'warmup') {
147
- ensureLoaded().then(
148
- () => postReply({ id: msg.id, ok: true, type: 'ready' }),
149
- () => postReply({ id: msg.id, ok: false, stage: 'load', error: loadError ?? '模型加载失败' }),
150
- );
151
- return;
152
- }
153
- if (msg.type === 'embed') {
154
- void (async () => {
155
- try {
156
- await ensureLoaded();
157
- } catch {
158
- postReply({ id: msg.id, ok: false, stage: 'load', error: loadError ?? '模型加载失败' });
159
- return;
160
- }
161
- handleEmbed(msg);
162
- })();
163
- return;
164
- }
165
- });
166
-
167
- // 未捕获异常:尽力通知主线程后强制退出(主线程的 exit 处理会拒绝全部 pending
168
- // 并转入 failed 态)。不保持半死状态——半死的 worker 只会让调用方挂到超时。
169
- process.on('uncaughtException', (err) => {
170
- try {
171
- postReply({ type: 'fatal', error: errMsg(err) });
172
- } catch {
173
- /* 端口已坏,exit 处理兜底 */
174
- }
175
- setTimeout(() => process.exit(1), 50);
176
- });
@@ -1,33 +0,0 @@
1
- /**
2
- * 存量未打标记录的一键回填(task_15):从 HallWheel"未打标 M"入口触发,
3
- * 对 metadata 无 hall 的 L1 记录按 8 角词表批量补打标签(复用 L1 抽取的打标路径:
4
- * 同一候选词表与措辞,经既有蒸馏 LLM 路由)。
5
- *
6
- * 安全边界:
7
- * - **单飞**:同时最多一个回填任务,重复触发直接返回 running(不排队不叠加);
8
- * - **后台执行**:端点立即返回,逐块推进(每块 20 条),不阻塞 RPC/管线;
9
- * - **失败可退**:LLM 失败/输出不合法只跳过当前块,原记录零改动(标签只写成功的);
10
- * - **有界**:单次任务最多处理 MAX_RECORDS 条,防止一次跑飞;其余可再次触发。
11
- */
12
- import type { Context } from '@deepseek-ai/cordis';
13
- import { type MemoryLogger } from './types.js';
14
- import type { L1Store } from './store/l1.js';
15
- import type { MemoryConfig } from './config.js';
16
- export interface HallBackfillDeps {
17
- ctx: Context;
18
- cfg: MemoryConfig;
19
- l1: L1Store;
20
- logger: MemoryLogger;
21
- }
22
- export interface HallBackfillState {
23
- running: boolean;
24
- /** 本进程累计成功打标条数(重启归零;仅作观测,不作账)。 */
25
- updated: number;
26
- failed: number;
27
- }
28
- export declare function hallBackfillState(): HallBackfillState;
29
- /** 启动后台回填;已在运行返回 false(单飞)。 */
30
- export declare function startHallBackfill(deps: HallBackfillDeps): {
31
- started: boolean;
32
- running: boolean;
33
- };
@@ -1,95 +0,0 @@
1
- import { callLLM } from './llm.js';
2
- import { normHallEnabled } from './config.js';
3
- import { HALL_FALLBACK } from './types.js';
4
- import { parseJsonLogged } from './llm.js';
5
- /** 单次任务处理上限(524 条存量一次跑完约为 LLM 成本大头;分批触发,可重复执行)。 */
6
- const MAX_RECORDS = 300;
7
- /** 每块条数(一次 LLM 调用判定的记录数)。 */
8
- const CHUNK = 20;
9
- const state = { running: false, updated: 0, failed: 0 };
10
- export function hallBackfillState() {
11
- return { ...state };
12
- }
13
- const SYSTEM_PROMPT = '你是记忆库的域标注器。给你若干条记忆(带 id),为每条判断其内容属于哪个 Hall 域,输出 JSON 数组:' +
14
- '[{"id":"<原id>","hall":"<域id>"}]。hall 只能从给定候选列表中选;横跨多域或确实无法归入任何角时选 general。' +
15
- '只输出 JSON,不要多余文字。';
16
- /** 启动后台回填;已在运行返回 false(单飞)。 */
17
- export function startHallBackfill(deps) {
18
- if (state.running)
19
- return { started: false, running: true };
20
- state.running = true;
21
- state.updated = 0;
22
- state.failed = 0;
23
- void run(deps).finally(() => {
24
- state.running = false;
25
- deps.logger.info(`[memory] hall 回填结束:成功 ${state.updated} 条,失败 ${state.failed} 条`);
26
- });
27
- return { started: true, running: true };
28
- }
29
- async function run(deps) {
30
- const { ctx, cfg, l1, logger } = deps;
31
- const halls = normHallEnabled(cfg.hall?.enabled);
32
- if (halls.length === 0) {
33
- logger.warn('[memory] hall 回填跳过:hall.enabled 为空(打标功能已关闭)');
34
- return;
35
- }
36
- const candidates = [...halls, HALL_FALLBACK].join(' / ');
37
- // 未打标集:主表全量里的 null hall(含 retired 行——restore 后标签已补,不重扫)
38
- const all = l1.all();
39
- const pending = all.filter((r) => !(r.metadata && typeof r.metadata.hall === 'string' && r.metadata.hall !== ''));
40
- let budget = Math.min(pending.length, MAX_RECORDS);
41
- logger.info(`[memory] hall 回填启动:未打标 ${pending.length} 条,本次上限 ${budget} 条(候选 ${candidates})`);
42
- for (let offset = 0; offset < pending.length && budget > 0; offset += CHUNK) {
43
- const chunk = pending.slice(offset, offset + CHUNK).filter(pickChunk);
44
- if (chunk.length === 0)
45
- continue;
46
- budget -= chunk.length;
47
- const labeled = await labelChunk(ctx, cfg, logger, chunk, candidates);
48
- for (const { record, hall } of labeled) {
49
- // 原记录最小改动:metadata.hall 单键写入,其余字段原样 upsert(同 id 版本不变语义)
50
- const next = { ...record, metadata: { ...(record.metadata ?? {}), hall } };
51
- try {
52
- await l1.upsert(next);
53
- state.updated++;
54
- }
55
- catch {
56
- state.failed++;
57
- }
58
- }
59
- }
60
- }
61
- /** 回填只处理活跃记录可安全加速,但 retired 行的 metadata_json 同样保留且 restore 后可见——
62
- * upsert 对 retired 行的行为由存储层保证(同 id 覆盖不复活),这里不做活性过滤,口径与迁移一致(全量)。 */
63
- function pickChunk(_r) {
64
- return true;
65
- }
66
- async function labelChunk(ctx, cfg, logger, chunk, candidates) {
67
- const list = chunk.map((r, i) => `${i + 1}. id=${r.id}\n${r.content.slice(0, 300)}`).join('\n\n');
68
- const user = `候选 Hall:${candidates}\n\n记忆列表:\n${list}`;
69
- try {
70
- const raw = await callLLM(ctx, cfg, {
71
- system: SYSTEM_PROMPT,
72
- user,
73
- maxTokens: 4096,
74
- layer: 'l1-extract',
75
- logger,
76
- });
77
- const parsed = parseJsonLogged(raw, 'hall 回填', logger);
78
- if (!Array.isArray(parsed))
79
- return [];
80
- const byId = new Map(chunk.map((r) => [r.id, r]));
81
- const out = [];
82
- for (const item of parsed) {
83
- const record = typeof item?.id === 'string' ? byId.get(item.id) : undefined;
84
- const hall = typeof item?.hall === 'string' ? item.hall.trim() : '';
85
- if (record && hall)
86
- out.push({ record, hall });
87
- }
88
- return out;
89
- }
90
- catch (err) {
91
- logger.warn(`[memory] hall 回填块失败(跳过 ${chunk.length} 条,原记录未改): ${err instanceof Error ? err.message : String(err)}`);
92
- state.failed += chunk.length;
93
- return [];
94
- }
95
- }
@@ -1,32 +0,0 @@
1
- import type { MemoryLogger } from './types.js';
2
- /** 新词表下的全部合法 hall 值(8 角 + 跨域兜底)。 */
3
- export declare const HALL_VALID_VALUES: readonly string[];
4
- export interface HallMigrationReport {
5
- dbPath: string;
6
- dryRun: boolean;
7
- /** 主表全量行数(含 retired;与 hallL1Counts 的扫描口径一致)。 */
8
- total: number;
9
- /** retired 行数(valid_to 非空或带退场标记——迁移**不加过滤**,全量扫描自动覆盖)。 */
10
- retired: number;
11
- active: number;
12
- /** 逐值计数(含 retired 行;null 单列)。 */
13
- byHall: Record<string, number>;
14
- unlabeled: number;
15
- /** 不在新词表内的历史值(按 R10 不删已有标签,仅报告)。 */
16
- unknownValues: Record<string, number>;
17
- /** metadata 解析失败的行数(备份仍写入原始 JSON)。 */
18
- corruptMetadata: number;
19
- /** apply 模式写出的备份文件路径(dry-run 为 null)。 */
20
- backupPath: string | null;
21
- /** 结论:expected = 全部值合法(迁移无需改写);unknown = 存在历史遗留值(已报告,保留)。 */
22
- verdict: 'expected' | 'unknown-values';
23
- }
24
- export interface HallMigrationOptions {
25
- dbPath: string;
26
- /** true = 只读报告,不写备份;false = 先备份 metadata_json 再出报告。 */
27
- dryRun?: boolean;
28
- /** 备份输出目录(缺省 = db 同目录 hall-migrate-backup/)。 */
29
- backupDir?: string;
30
- logger?: MemoryLogger;
31
- }
32
- export declare function runHallMigration(opts: HallMigrationOptions): HallMigrationReport;
@@ -1,88 +0,0 @@
1
- /**
2
- * hall 词表迁移(task_14):v0.12 5 值词表 → 8 角 + general 跨域兜底的**有界 targeted pass**。
3
- *
4
- * 关键事实(决定本迁移的形态):
5
- * - 4 个保留 id(work/relationships/finance/journey)在新词表下仍是合法角,**存量标签零改动**;
6
- * - `general` 保留为跨域兜底值(不重写、不删除);
7
- * - 4 个新角无存量。因此本迁移**不改任何行的 hall 值**——它做的是:
8
- * ① 备份 metadata_json(apply 模式);② **扫 L1 主表全量(含 retired 行)**逐行核对;
9
- * ③ 落报告:逐值计数(含 null)/活性与 retired 拆分/未知值清单。
10
- *
11
- * 幂等:连续执行两次报告一致(扫描是纯读)。共享扫描函数 = `MemoryDb.scanL1Metadata`
12
- * (单一所有者;计划 B 的引用门禁复用同一函数,不写第二份扫描)。
13
- */
14
- import { openSync, closeSync, writeSync, existsSync, mkdirSync } from 'node:fs';
15
- import * as path from 'node:path';
16
- import { MemoryDb } from './store/sqlite.js';
17
- import { HALL_CATALOG, HALL_FALLBACK } from './types.js';
18
- /** 新词表下的全部合法 hall 值(8 角 + 跨域兜底)。 */
19
- export const HALL_VALID_VALUES = [...HALL_CATALOG.map((h) => h.id), HALL_FALLBACK];
20
- export function runHallMigration(opts) {
21
- const db = new MemoryDb(opts.dbPath, 0, opts.logger);
22
- // 开库即建表/补列(CREATE TABLE IF NOT EXISTS 惯例);未 init 则句柄未打开,扫描恒 0
23
- db.init();
24
- try {
25
- const report = {
26
- dbPath: opts.dbPath,
27
- dryRun: !!opts.dryRun,
28
- total: 0,
29
- retired: 0,
30
- active: 0,
31
- byHall: {},
32
- unlabeled: 0,
33
- unknownValues: {},
34
- corruptMetadata: 0,
35
- backupPath: null,
36
- verdict: 'expected',
37
- };
38
- let backupFd = null;
39
- if (!report.dryRun) {
40
- const dir = opts.backupDir ?? path.join(path.dirname(opts.dbPath), 'hall-migrate-backup');
41
- if (!existsSync(dir))
42
- mkdirSync(dir, { recursive: true });
43
- const backupPath = path.join(dir, `metadata-backup-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`);
44
- backupFd = openSync(backupPath, 'w');
45
- report.backupPath = backupPath;
46
- }
47
- try {
48
- report.total = db.scanL1Metadata((recordId, metadata) => {
49
- const hall = metadata && typeof metadata.hall === 'string' && metadata.hall !== '' ? metadata.hall : null;
50
- // metadata 缺失/解析失败与"无 hall"同样计入未打标(存量 524 null 的主口径)
51
- // 备份:原始 metadata_json 原样落盘(apply 模式;dry-run 不写任何文件)
52
- if (backupFd !== null) {
53
- writeSync(backupFd, JSON.stringify({ recordId, metadata }) + '\n');
54
- }
55
- if (hall === null) {
56
- report.unlabeled++;
57
- }
58
- else {
59
- report.byHall[hall] = (report.byHall[hall] ?? 0) + 1;
60
- if (!HALL_VALID_VALUES.includes(hall)) {
61
- report.unknownValues[hall] = (report.unknownValues[hall] ?? 0) + 1;
62
- }
63
- }
64
- });
65
- // retired 拆分:退场判定与存储层同口径(valid_to 非空 ∨ dsh_superseded 标记)。
66
- // 扫描本身**不加过滤**(全表 SELECT 自动覆盖 retired),这里仅分类计数。
67
- report.active = report.total - countRetired(db);
68
- report.retired = report.total - report.active;
69
- }
70
- finally {
71
- if (backupFd !== null)
72
- closeSync(backupFd);
73
- }
74
- report.verdict = Object.keys(report.unknownValues).length > 0 ? 'unknown-values' : 'expected';
75
- return report;
76
- }
77
- finally {
78
- db.close();
79
- }
80
- }
81
- /** retired 行计数(与 sqlite 层退场判定同口径;用于验证"全量扫描不漏 retired")。 */
82
- function countRetired(db) {
83
- // 借道 scanL1Metadata 之外的轻量路径不可得(retired 判定在行级字段),
84
- // 这里直接用 hallL1Counts 的同族 SQL:valid_to 非空 ∨ metadata 带 dsh_superseded。
85
- // 为保持"单一所有者",经由 scanL1Metadata 之外不再开第二条 SQL——改为返回占位 0,
86
- // 由 retire 拆分调用方(db.retiredL1Count)提供。
87
- return db.retiredL1Count();
88
- }