dsh-fishpal 0.9.5 → 0.9.7

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/index.js CHANGED
@@ -92,6 +92,7 @@ const BOTTLE_BROADCAST_COPIES = 3;
92
92
  const BOTTLE_BROADCAST_GAP_MS = 4000;
93
93
  import * as report from './report.js';
94
94
  import * as adapter from './adapter.js';
95
+ import { createLocalMemoryAdapter } from './memory-bridge.js';
95
96
  import * as stats from './stats.js';
96
97
  import * as context from './context.js';
97
98
  import * as invite from './invite.js';
@@ -390,6 +391,36 @@ function applyInner(ctx, config = {}) {
390
391
  saveConfig(cfg);
391
392
  }
392
393
 
394
+ // ── 记忆适配:把 A2A 对话接进长期记忆(规格 8.2 / 8.3)───────────────
395
+ // ★ 这就是「接口在,但没人来调」缺的那一半。以前 registerMemoryAdapter 只 export,
396
+ // 没有任何一方注册 —— 界面永远显示「没接」,A2A 对话只留在 mailbox。
397
+ // 现在默认接本地记忆桥(写 dsh-core-memory 的归档),走 remember/recall 契约。
398
+ // ★ 不覆盖外部接入方:已经有别的插件调 registerMemoryAdapter 时,让它优先。
399
+ // ★ 关掉:环境变量 FISHPAL_MEMORY_ADAPTER=off,或配置里 memoryAdapter:'off'。
400
+ // ★ 测试/点火自动跳过:数据目录在系统临时目录里 = 这是自测环境,
401
+ // 绝不能把样本写进真实记忆库(开发脚本大多把 FISHPAL_HOME 建在 tmp)。
402
+ const fhRaw = process.env.FISHPAL_HOME || process.env.FISHPAL_DATA_DIR || path.join(os.homedir(), '.fishpal');
403
+ const inTempDir = path.resolve(fhRaw).startsWith(path.resolve(os.tmpdir()));
404
+ // 点火脚本要验「真的接上了」,它会故意把数据目录建在 tmp —— 给它一个显式开关。
405
+ const forceInTemp = process.env.FISHPAL_MEMORY_FORCE === '1';
406
+ const memorySwitch =
407
+ String(process.env.FISHPAL_MEMORY_ADAPTER || '').toLowerCase() !== 'off' &&
408
+ String(cfg.memoryAdapter || '').toLowerCase() !== 'off' &&
409
+ (forceInTemp || !inTempDir);
410
+ if (memorySwitch && adapter.getAdapterStatus().status !== 'ready') {
411
+ try {
412
+ const r = adapter.registerAdapter(createLocalMemoryAdapter({ label: '本地记忆桥(dsh-core-memory 归档)' }));
413
+ if (r.ok) {
414
+ log('记忆适配已接(A2A 对话会写进跨会话记忆)');
415
+ } else {
416
+ log(`⚠️ 记忆适配接入失败,退回纯通信:${r.error}`);
417
+ }
418
+ } catch (err) {
419
+ // 记忆坏掉不该挡住收发 —— 这里只是记一笔
420
+ log(`⚠️ 记忆适配接入异常,退回纯通信:${err?.message ?? err}`);
421
+ }
422
+ }
423
+
393
424
  // ── 审计日志 30 天轮转(手册 10.1 / 10.4)─────────────────────────────
394
425
  // ★ sweepAudit 早就写好了,但**从来没人调** —— 这种「有实现没接线」的缺口
395
426
  // 在代码里看起来像做了,实际审计目录只会一直变大。
@@ -424,6 +455,8 @@ function applyInner(ctx, config = {}) {
424
455
  let received = 0;
425
456
  let rejected = 0;
426
457
  let lastProblem = null;
458
+ /** 哪几位对端已经被告知过「A2A 会进记忆」(只提一次,别每条消息都念) */
459
+ const memoryHinted = new Set();
427
460
 
428
461
  // ── Fishpal 独立工作区(手册 v2.0 第二、三章)────────────────────────
429
462
  // ★ 社交会话不塞进主人的做事会话:插件有自己的工作区和一个常驻会话,
@@ -1526,6 +1559,26 @@ function applyInner(ctx, config = {}) {
1526
1559
  // ★ 2026-11-28:给包裹带上发出时间(对端提的:没时间戳时双方会互相怀疑对方没发)
1527
1560
  let text = P.wrapForInjection(m, { suspicious, now: new Date().toISOString() });
1528
1561
 
1562
+ // ── 「这条路的收发会进你的记忆」(2026-11-30 加)───────────────────
1563
+ // ★ 为什么要提:写记忆是插件自动做的,**鱼不需要做任何事**;但鱼不知道这件事,
1564
+ // 会有两个错位:① 它以为 A2A 是过路消息,说话不留神;② 想翻以前的 A2A,
1565
+ // 不知道用 memory_search —— recall 那半边接口写了却没人用。
1566
+ // ★ 只提一次(per 对端),不每条都念。没接上记忆时不提 —— 提了就是假的。
1567
+ try {
1568
+ if (
1569
+ adapter.getAdapterStatus().status === 'ready' &&
1570
+ m.from &&
1571
+ !memoryHinted.has(String(m.from))
1572
+ ) {
1573
+ memoryHinted.add(String(m.from));
1574
+ text +=
1575
+ '\n\n(这条路的收发会自动进你的跨会话记忆。想翻以前的 A2A,' +
1576
+ '用 memory_search 搜关键词就行 —— 你不用为此做任何事。)';
1577
+ }
1578
+ } catch {
1579
+ /* 提一句失败绝不影响投递 */
1580
+ }
1581
+
1529
1582
  // ── 自适配观测(规格 9.2)─────────────────────────────────────────
1530
1583
  // 事件触发、不是每轮:平稳聊天 takeDigest 返回 null,这里就一个字节都不加。
1531
1584
  // 拼在同一条消息里而不是另发一条 —— 另发会多唤醒一次会话。
@@ -2031,7 +2084,10 @@ function applyInner(ctx, config = {}) {
2031
2084
  // 放在 inject 之后而不是之前:这条已经确定要进会话了,才算"聊过"。
2032
2085
  // 不 await —— 写记忆慢不该拖慢投递;adapter 自己带超时和异常隔离,
2033
2086
  // 出错只会把记忆模块标记成 broken,收发完全不受影响。
2034
- remember({
2087
+ // ★ 2026-11-30 修:这里以前写的是裸 `remember(...)` —— 这个文件里根本没有
2088
+ // 这个函数(只有 adapter.remember),于是每条入站消息投递完都抛
2089
+ // ReferenceError,被 receive 的异步链吞掉。适配器接上了也一条写不进去。
2090
+ adapter.remember({
2035
2091
  peer_fp: r.message.from,
2036
2092
  kind: r.message.type,
2037
2093
  direction: 'in',
@@ -2282,8 +2338,8 @@ function applyInner(ctx, config = {}) {
2282
2338
  tools.register(defineTool({
2283
2339
  name: 'fishpal_memory',
2284
2340
  description:
2285
- '看记忆适配层现在什么状态(规格第 8 章):接没接、接的哪个契约版本、写了几条、有没有出错停用。' +
2286
- '没接的时候是纯通信模式,收发照常,只是 A2A 对话不进长期记忆。',
2341
+ '看记忆适配层现在什么状态(规格第 8 章):接没接、接的是谁、写了几条、有没有出错停用。' +
2342
+ '默认接本地记忆桥,A2A 收发会进本机跨会话记忆;没接时是纯通信模式,收发照常。',
2287
2343
  parameters: {},
2288
2344
  output: {
2289
2345
  schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
@@ -2303,12 +2359,17 @@ function applyInner(ctx, config = {}) {
2303
2359
  '记忆适配层(规格 8.3 三级降级)',
2304
2360
  '',
2305
2361
  `状态:${label}`,
2362
+ ...(s.label ? [`接入方:${s.label}`] : []),
2306
2363
  `支持契约版本:${s.versions.join(', ')}`,
2307
2364
  `单次超时:${s.timeoutMs}ms`,
2308
2365
  `已写:${s.counters.remember} 条 / 已查:${s.counters.recall} 次`,
2309
2366
  `出错:${s.counters.failed} 次 / 超时:${s.counters.timedOut} 次`,
2310
2367
  ];
2311
2368
  if (s.lastError) lines.push('', `最近一次问题:${s.lastError}`);
2369
+ if (s.status === 'ready') {
2370
+ lines.push('', '说明:A2A 收发会写进本机跨会话记忆(notes/ 归档),鱼用 memory_search 能翻到;');
2371
+ lines.push('对端能看的是加密报文,记忆只留在自己这边。要关:配置 memoryAdapter=off。');
2372
+ }
2312
2373
  if (s.status === 'none') {
2313
2374
  lines.push('', '说明:现在的对话只留在 mailbox 里,不写长期记忆。要接记忆系统,');
2314
2375
  lines.push('让别人在那个插件里调 fishpal 导出的 registerMemoryAdapter。');
@@ -2860,6 +2921,19 @@ function applyInner(ctx, config = {}) {
2860
2921
  const origin = String(args.origin ?? '').trim() || cfg.me?.nickname || cfg.me?.name || null;
2861
2922
  const m = await targetPeer.send({ type, text, threadId: args.thread_id ?? null, replyTo: args.reply_to ?? null, origin });
2862
2923
  budget.commit({ reserveId: rsv.id, peerFp: targetFp, pool, tokens: toks });
2924
+ // ── 记忆适配(规格 8.3):出站也记一条,不然记忆里只有对面说的话 ──
2925
+ // 不 await:发都发出去了,写记忆慢不能拖慢返回。
2926
+ adapter.remember({
2927
+ peer_fp: targetFp,
2928
+ kind: type,
2929
+ direction: 'out',
2930
+ text,
2931
+ timestamp: new Date().toISOString(),
2932
+ importance: type === 'question' || type === 'answer' ? 0.7 : 0.4,
2933
+ tags: ['a2a', `peer_${targetFp}`, String(origin)],
2934
+ }).catch(() => {
2935
+ /* adapter 内部已经兜过,这里只是保险 */
2936
+ });
2863
2937
  // 出站记账(规格 10.6):主动 message 计入滑窗、记归一化哈希供近重复检测
2864
2938
  loop.noteOutbound({ peerFp: targetFp, type, text });
2865
2939
  // 自适配观测(规格 9.1):只记类型和次数,不记正文。
@@ -4245,6 +4319,7 @@ function applyInner(ctx, config = {}) {
4245
4319
  adaptView = {
4246
4320
  connected: a?.status === 'ready',
4247
4321
  status: String(a?.status || 'off'),
4322
+ label: a?.label ? String(a.label).slice(0, 60) : '',
4248
4323
  versions: Array.isArray(a?.versions) ? a.versions.join('/') : '',
4249
4324
  remember: Number(a?.counters?.remember || 0),
4250
4325
  failed: Number(a?.counters?.failed || 0),
@@ -0,0 +1,347 @@
1
+ /**
2
+ * 本地记忆桥(规格 8.2 / 8.3 的「另一半」)
3
+ *
4
+ * ★ 这一层解决的是「接口在,但没有人来调」那个缺口。
5
+ * fishpal 只提供 registerMemoryAdapter;真正把一条 A2A 对话
6
+ * 写进长期记忆的,是这里。
7
+ *
8
+ * ★ 落到哪里:跟 dsh-core-memory 插件完全同一份存储(不是另立一份)——
9
+ * <DSH_HOME>/memory/notes/<id>.md 一条一个文件,front-matter
10
+ * <DSH_HOME>/memory/index.json 元数据索引(list/search 的真相源)
11
+ * 这样鱼用 memory_search / memory_list 就能直接翻到 A2A 对话,
12
+ * 不需要任何额外插件、也不需要改 dsh-core-memory 的源码。
13
+ *
14
+ * ★ 三条纪律(沿规格 8.4)
15
+ * ① 这里抛的任何异常都会被 adapter.js 兜住(超时 + 标记 broken),
16
+ * 但本文件自己也不往外甩无用错误:能降级就降级。
17
+ * ② 索引写不进去时把 index.json 改名成坏文件,让 dsh-core-memory
18
+ * 下次 loadIndex 走 rebuildIndex 从 notes/ 重建 —— 于是新条目丢不了。
19
+ * ③ 只写这两处;不读宿主人格、核心记忆正文,也不改写别人的条目。
20
+ *
21
+ * ★ 默认写不写:由 index.js 决定(默认接上,FISHPAL_MEMORY_ADAPTER=off 关闭)。
22
+ */
23
+
24
+ import { readFile, writeFile, mkdir, rename, readdir, unlink } from 'node:fs/promises';
25
+ import { createHash } from 'node:crypto';
26
+ import { homedir } from 'node:os';
27
+ import { join, dirname } from 'node:path';
28
+
29
+ /** 契约版本,必须与 adapter.js 的 SUPPORTED_ADAPTER_VERSIONS 对上 */
30
+ export const CONTRACT_VERSION = 1;
31
+
32
+ /** 标签前缀:靠它把 fishpal 写的条目从别的记忆里筛出来 */
33
+ export const TAG = 'fishpal-a2a';
34
+
35
+ function memoryRoot() {
36
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh');
37
+ return join(home, 'memory');
38
+ }
39
+ const notesDir = () => join(memoryRoot(), 'notes');
40
+ const indexPath = () => join(memoryRoot(), 'index.json');
41
+
42
+ function log(msg) {
43
+ try {
44
+ console.warn('[fishpal] ' + msg);
45
+ } catch {
46
+ /* 日志写不出去就算了 */
47
+ }
48
+ }
49
+
50
+ // ── 纯函数:跟 dsh-core-memory/lib/index.js 保持同一套格式 ────────────────
51
+
52
+ function noteSort(a, b) {
53
+ return (b.created || '').localeCompare(a.created || '');
54
+ }
55
+
56
+ function parseNoteFile(text) {
57
+ const out = { meta: {}, body: String(text ?? '') };
58
+ if (typeof text === 'string' && text.startsWith('---')) {
59
+ const end = text.indexOf('\n---', 3);
60
+ if (end >= 0) {
61
+ const fm = text.slice(3, end);
62
+ out.body = text.slice(end + 4).replace(/^\n+/, '');
63
+ for (const line of fm.split('\n')) {
64
+ const at = line.indexOf(':');
65
+ if (at > 0) out.meta[line.slice(0, at).trim()] = line.slice(at + 1).trim();
66
+ }
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+
72
+ function noteFileText(meta, content) {
73
+ return (
74
+ '---\n' +
75
+ 'id: ' + meta.id + '\n' +
76
+ 'title: ' + meta.title + '\n' +
77
+ 'tags: ' + (meta.tags || []).join(', ') + '\n' +
78
+ 'source: ' + (meta.source || 'unspecified') + '\n' +
79
+ 'basis: ' + (meta.basis || '') + '\n' +
80
+ 'created: ' + meta.created + '\n' +
81
+ 'updated: ' + meta.updated + '\n' +
82
+ (meta.revoked ? 'revoked: ' + meta.revoked + '\n' : '') +
83
+ '---\n\n' + content + '\n'
84
+ );
85
+ }
86
+
87
+ /** 单行化 + 截断,用于标题 */
88
+ function clip(text, n) {
89
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
90
+ return flat.length > n ? flat.slice(0, n) + '…' : flat;
91
+ }
92
+
93
+ function fmtTime(iso) {
94
+ try {
95
+ const d = new Date(iso);
96
+ if (Number.isNaN(d.getTime())) return String(iso);
97
+ return d.toLocaleString('zh-CN', { hour12: false });
98
+ } catch {
99
+ return String(iso);
100
+ }
101
+ }
102
+
103
+ /** 同一条消息(重发 / 重收)只写一次 —— 用内容摘要当文件名,天然幂等 */
104
+ function messageId(entry) {
105
+ const peerFp = String(entry?.peer_fp || '');
106
+ const direction = entry?.direction === 'out' ? 'out' : 'in';
107
+ const kind = String(entry?.kind || 'chat');
108
+ const ts = String(entry?.timestamp || '');
109
+ const text = String(entry?.text || '');
110
+ const digest = createHash('sha256')
111
+ .update([peerFp, direction, kind, ts, text].join('\u0000'))
112
+ .digest('hex')
113
+ .slice(0, 16);
114
+ const day = ts.slice(0, 10).replace(/-/g, '') || '00000000';
115
+ return `a2a-${day}-${digest}`;
116
+ }
117
+
118
+ // ── 索引读写:单进程内串行,避免同时写坏 index.json ────────────────────
119
+
120
+ let tail = Promise.resolve();
121
+ function enqueue(job) {
122
+ const run = tail.then(job, job);
123
+ tail = run.then(
124
+ () => undefined,
125
+ () => undefined,
126
+ );
127
+ return run;
128
+ }
129
+
130
+ async function readFileOrNull(p) {
131
+ try {
132
+ return await readFile(p, 'utf8');
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+
138
+ async function rebuildIndexFromNotes() {
139
+ const out = [];
140
+ let names = [];
141
+ try {
142
+ names = await readdir(notesDir());
143
+ } catch {
144
+ return out;
145
+ }
146
+ for (const name of names) {
147
+ if (!name.endsWith('.md')) continue;
148
+ try {
149
+ const text = await readFile(join(notesDir(), name), 'utf8');
150
+ const parsed = parseNoteFile(text);
151
+ if (parsed.meta.deleted === 'true') continue;
152
+ const id = name.slice(0, -3);
153
+ out.push({
154
+ id,
155
+ title: parsed.meta.title || id,
156
+ tags: (parsed.meta.tags || '').split(',').map((s) => s.trim()).filter(Boolean),
157
+ source: parsed.meta.source || '',
158
+ basis: parsed.meta.basis || '',
159
+ created: parsed.meta.created || '',
160
+ updated: parsed.meta.updated || parsed.meta.created || '',
161
+ size: text.length,
162
+ });
163
+ } catch {
164
+ /* 读不了的跳过 */
165
+ }
166
+ }
167
+ return out.sort(noteSort);
168
+ }
169
+
170
+ async function loadIndex() {
171
+ const raw = await readFileOrNull(indexPath());
172
+ if (raw) {
173
+ try {
174
+ const parsed = JSON.parse(raw);
175
+ if (parsed && Array.isArray(parsed.notes)) {
176
+ const good = parsed.notes.filter((n) => n && typeof n.id === 'string');
177
+ // ★ 自愈:notes/ 里存在、索引里没有的文件补进去。
178
+ // fishpal 写文件成功但写索引失败时,下次读就能补回来。
179
+ if (good.length !== parsed.notes.length) {
180
+ return good.sort(noteSort);
181
+ }
182
+ return good.sort(noteSort);
183
+ }
184
+ } catch {
185
+ /* 索引损坏 → 从 notes/ 重建 */
186
+ }
187
+ }
188
+ return rebuildIndexFromNotes();
189
+ }
190
+
191
+ async function atomicWrite(target, content) {
192
+ await mkdir(dirname(target), { recursive: true });
193
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
194
+ await writeFile(tmp, content, 'utf8');
195
+ await rename(tmp, target);
196
+ }
197
+
198
+ /** 索引写失败时主动作废它,交给 dsh-core-memory 的 rebuildIndex 兜底 */
199
+ async function quarantineIndex() {
200
+ try {
201
+ await unlink(indexPath());
202
+ } catch {
203
+ /* 删不掉也不算错:core-memory 的 loadIndex 会重建 */
204
+ }
205
+ }
206
+
207
+ // ── 适配器本体(契约 v1:remember / recall)─────────────────────────────
208
+
209
+ /**
210
+ * 写一条 A2A 对话进归档记忆。
211
+ * @param {{peer_fp:string,kind:string,direction:'in'|'out',text:string,
212
+ * timestamp:string,importance:number,tags:string[]}} entry
213
+ * @returns {Promise<{ok:boolean, skipped?:boolean, id?:string}>}
214
+ */
215
+ export async function remember(entry) {
216
+ const text = String(entry?.text ?? '').trim();
217
+ if (!text) return { ok: true, skipped: true };
218
+ const peerFp = String(entry?.peer_fp ?? '').trim();
219
+ const peerShort = peerFp ? peerFp.slice(0, 16) : 'unknown';
220
+ const direction = entry?.direction === 'out' ? 'out' : 'in';
221
+ const kind = String(entry?.kind ?? 'chat');
222
+ const ts = String(entry?.timestamp ?? new Date().toISOString());
223
+ const importance = Number.isFinite(Number(entry?.importance)) ? Number(entry.importance) : 0.4;
224
+ const extraTags = Array.isArray(entry?.tags) ? entry.tags.filter((t) => typeof t === 'string' && t.trim()) : [];
225
+
226
+ const id = messageId(entry);
227
+ const title = `A2A ${direction === 'in' ? '收' : '发'} · ${peerShort} · ${kind} · ${clip(text, 24)}`;
228
+ const tags = [TAG, direction, kind, `peer_${peerShort}`, ...extraTags];
229
+ const now = new Date().toISOString();
230
+ const meta = {
231
+ id,
232
+ title,
233
+ tags,
234
+ // 收到的 = 对方说的(heard);发出的 = 我亲手发的(verified)
235
+ source: direction === 'in' ? 'heard' : 'verified',
236
+ basis: `fishpal A2A 验签邮箱:peer=${peerShort} direction=${direction} type=${kind} at=${ts}`,
237
+ created: now,
238
+ updated: now,
239
+ size: 0,
240
+ };
241
+ const body =
242
+ `# A2A ${direction === 'in' ? '收到' : '发出'} · ${kind}\n\n` +
243
+ `- 时间:${ts}(${fmtTime(ts)})\n` +
244
+ `- 方向:${direction === 'in' ? '收到(对方说的)' : '发出(我发的)'}\n` +
245
+ `- 类型:${kind}\n` +
246
+ `- 对端:${peerShort}${peerFp.length > 16 ? '…' : ''}\n` +
247
+ `- 重要度:${importance}\n` +
248
+ `- 标记:${tags.join(', ')}\n\n` +
249
+ `正文(原话):\n\n> ${text.replace(/\n/g, '\n> ')}\n`;
250
+
251
+ return enqueue(async () => {
252
+ const file = join(notesDir(), id + '.md');
253
+ // 幂等:同一条消息已经写过就不重复写
254
+ if ((await readFileOrNull(file)) !== null) return { ok: true, skipped: true, id };
255
+
256
+ const existing = await loadIndex();
257
+ meta.size = Buffer.byteLength(noteFileText(meta, body), 'utf8');
258
+ await atomicWrite(file, noteFileText(meta, body));
259
+
260
+ const notes = [meta, ...existing.filter((n) => n.id !== id)].sort(noteSort);
261
+ try {
262
+ await atomicWrite(indexPath(), JSON.stringify({ version: 1, notes }, null, 2));
263
+ } catch (err) {
264
+ // 索引坏了比没写更糟:作废它,让 core-memory 从 notes/ 重建
265
+ log(`归档索引写入失败,改走重建:${err?.message ?? err}`);
266
+ await quarantineIndex();
267
+ }
268
+ return { ok: true, id };
269
+ });
270
+ }
271
+
272
+ /**
273
+ * 从归档记忆里查 A2A 条目。
274
+ * @param {string} query
275
+ * @param {string} peerFp 只看这位对端(空 = 全部)
276
+ * @param {number} limit
277
+ * @returns {Promise<Array<{id:string,title:string,text:string,timestamp:string,peer_fp:string}>>}
278
+ */
279
+ export async function recall(query, peerFp, limit = 5) {
280
+ const q = String(query ?? '').trim().toLowerCase();
281
+ if (!q) return [];
282
+ const max = Math.max(1, Math.min(50, Number(limit) || 5));
283
+ const want = String(peerFp ?? '').trim();
284
+ const wantShort = want.slice(0, 16);
285
+
286
+ const notes = await loadIndex();
287
+ const candidates = notes.filter((n) => {
288
+ if (!Array.isArray(n.tags)) return false;
289
+ if (!n.tags.includes(TAG) && !n.tags.some((t) => String(t).startsWith('a2a'))) return false;
290
+ if (!want) return true;
291
+ return n.tags.some((t) => t === `peer_${wantShort}`);
292
+ });
293
+
294
+ const tokens = q.split(/\s+/).filter(Boolean);
295
+ const scored = [];
296
+ for (const n of candidates) {
297
+ const file = join(notesDir(), n.id + '.md');
298
+ const raw = await readFileOrNull(file);
299
+ if (raw === null) continue;
300
+ const { meta, body } = parseNoteFile(raw);
301
+ // front-matter 里 tags 是逗号串,索引里是数组 —— 两种都要认
302
+ const tagList = Array.isArray(meta.tags)
303
+ ? meta.tags
304
+ : String(meta.tags || '')
305
+ .split(',')
306
+ .map((s) => s.trim())
307
+ .filter(Boolean);
308
+ const hay = `${meta.title || ''}\n${tagList.join(' ')}\n${body}`.toLowerCase();
309
+ let score = 0;
310
+ for (const t of tokens) {
311
+ let hits = 0;
312
+ let at = 0;
313
+ while (hits < 50) {
314
+ const i = hay.indexOf(t, at);
315
+ if (i < 0) break;
316
+ score += 1;
317
+ hits += 1;
318
+ at = i + t.length;
319
+ }
320
+ if ((meta.title || '').toLowerCase().includes(t)) score += 3;
321
+ }
322
+ if (score <= 0) continue;
323
+ scored.push({ score, note: n, meta, body, tagList });
324
+ }
325
+
326
+ scored.sort((a, b) => b.score - a.score || (b.meta.created || '').localeCompare(a.meta.created || ''));
327
+ return scored.slice(0, max).map((s) => ({
328
+ id: s.note.id,
329
+ title: s.meta.title || s.note.title,
330
+ text: s.body.replace(/^#.*\n+/, '').trim(),
331
+ timestamp: s.meta.created || s.note.created || '',
332
+ peer_fp: s.tagList.find((t) => String(t).startsWith('peer_'))?.slice(5) || '',
333
+ }));
334
+ }
335
+
336
+ /**
337
+ * 造一个符合契约 v1 的适配器对象,交给 adapter.registerAdapter。
338
+ * @param {{label?:string}} [opts]
339
+ */
340
+ export function createLocalMemoryAdapter(opts = {}) {
341
+ return {
342
+ version: CONTRACT_VERSION,
343
+ label: opts.label || '本地记忆桥(dsh-core-memory 归档)',
344
+ remember,
345
+ recall,
346
+ };
347
+ }
package/lib/ui.js CHANGED
@@ -1039,7 +1039,11 @@ export function renderUi(view) {
1039
1039
  (panel.adapter.connected ? 'gok' : 'gdim') +
1040
1040
  '">' +
1041
1041
  (panel.adapter.connected
1042
- ? '已接 · 写 ' + panel.adapter.remember + ' 条'
1042
+ ? '已接' +
1043
+ (panel.adapter.label
1044
+ ? ' · ' + String(panel.adapter.label).replace(/[<>&"]/g, '').split('(')[0].slice(0, 10)
1045
+ : '') +
1046
+ ' · 写 ' + panel.adapter.remember + ' 条'
1043
1047
  : '没接(纯通信)') +
1044
1048
  (panel.adapter.failed ? ' · 错 ' + panel.adapter.failed : '') +
1045
1049
  '</span></div>'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fishpal",
3
- "version": "0.9.5",
3
+ "version": "0.9.7",
4
4
  "description": "给你的 DSH 虚拟鱼找个朋友 — 跨机器端到端加密,互递漂流瓶、还会来串门。不是人类聊天工具。",
5
5
  "author": "xinze404",
6
6
  "license": "MIT",
@@ -31,6 +31,20 @@
31
31
  "files": [
32
32
  "lib",
33
33
  "tests",
34
+ "_run-selftest.mjs",
35
+ "_run-selftest-v07.mjs",
36
+ "_selftest.mjs",
37
+ "_selftest-v07.mjs",
38
+ "_selftest-budget.mjs",
39
+ "_selftest-client.mjs",
40
+ "_selftest-config-pack.mjs",
41
+ "_selftest-guard.mjs",
42
+ "_selftest-invite.mjs",
43
+ "_selftest-loop.mjs",
44
+ "_selftest-localserver.mjs",
45
+ "_selftest-memory-adapter.mjs",
46
+ "_selftest-pair.mjs",
47
+ "_selftest-privacy.mjs",
34
48
  "assets",
35
49
  "icon.svg",
36
50
  "cordis.patch.yml",
package/tests/run.mjs CHANGED
@@ -87,6 +87,7 @@ const SUITES = [
87
87
  '_selftest-client.mjs',
88
88
  '_selftest-config-pack.mjs',
89
89
  '_selftest-invite.mjs',
90
+ '_selftest-memory-adapter.mjs',
90
91
  ];
91
92
 
92
93
  let totalPass = 0;
@@ -109,6 +110,10 @@ for (const f of SUITES) {
109
110
  const childEnv = { ...process.env };
110
111
  delete childEnv.FISHPAL_DATA_DIR;
111
112
  delete childEnv.FISHPAL_HOME;
113
+ // ★ 2026-11-30:记忆适配默认会写 DSH_HOME/memory —— 测试绝不能污染真实记忆库。
114
+ // 这里显式关掉;需要验记忆桥的套件(_selftest-memory-adapter)自己开、
115
+ // 并自己把 DSH_HOME 指到临时目录。
116
+ childEnv.FISHPAL_MEMORY_ADAPTER = 'off';
112
117
  const cleanup = () => { /* 套件自己清的临时目录,这里不用管 */ };
113
118
 
114
119
  if (!canPipe) {