mindferry 0.0.0-stage → 0.2.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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -2
  3. package/README.zh-CN.md +165 -0
  4. package/bin/mindferry.mjs +301 -0
  5. package/examples/demo-en/chatgpt-conversations.json +72 -0
  6. package/examples/demo-en/chatgpt-copied.txt +8 -0
  7. package/examples/demo-en/claude-conversations.json +25 -0
  8. package/examples/demo-en/claude-memories.json +6 -0
  9. package/examples/demo-en/deepseek-conversations.json +39 -0
  10. package/examples/demo-en/gemini-MyActivity.json +18 -0
  11. package/examples/demo-en/grok-export.json +27 -0
  12. package/examples/exports/README.md +4 -0
  13. package/examples/exports/chatgpt-conversations.json +21 -0
  14. package/examples/exports/claude-conversations.json +13 -0
  15. package/examples/exports/claude-memories.json +3 -0
  16. package/examples/exports/deepseek-conversations.json +12 -0
  17. package/examples/exports/gemini-MyActivity.json +5 -0
  18. package/examples/exports/grok-export.json +11 -0
  19. package/examples/exports/open-webui-export.json +13 -0
  20. package/examples/scheduler/crontab.txt +2 -0
  21. package/examples/scheduler/io.github.mindferry.sync.plist +18 -0
  22. package/examples/single-chats/chatgpt-copied.txt +8 -0
  23. package/examples/single-chats/chatgpt-saved-page.html +4 -0
  24. package/examples/single-chats/claude-chat.md +7 -0
  25. package/package.json +55 -4
  26. package/src/connect.mjs +204 -0
  27. package/src/core/archive.mjs +144 -0
  28. package/src/core/card.mjs +64 -0
  29. package/src/core/classify.mjs +81 -0
  30. package/src/core/clients.mjs +63 -0
  31. package/src/core/errors.mjs +146 -0
  32. package/src/core/export.mjs +53 -0
  33. package/src/core/extract.mjs +183 -0
  34. package/src/core/generator.mjs +98 -0
  35. package/src/core/hub.mjs +637 -0
  36. package/src/core/llm.mjs +77 -0
  37. package/src/core/merge.mjs +95 -0
  38. package/src/core/profile.mjs +175 -0
  39. package/src/core/rules.mjs +88 -0
  40. package/src/core/store.mjs +109 -0
  41. package/src/core/text.mjs +82 -0
  42. package/src/demo.mjs +30 -0
  43. package/src/importers/index.mjs +366 -0
  44. package/src/importers/zip.mjs +48 -0
  45. package/src/mcp/server.mjs +272 -0
  46. package/src/remote.mjs +180 -0
  47. package/src/ui/server.mjs +281 -0
  48. package/src/ui/static/app.js +1037 -0
  49. package/src/ui/static/index.html +269 -0
  50. package/src/ui/static/logo.svg +16 -0
  51. package/src/ui/static/mascot-busy.svg +35 -0
  52. package/src/ui/static/mascot-happy.svg +27 -0
  53. package/src/ui/static/mascot-idle.svg +26 -0
  54. package/src/ui/static/mascot-oops.svg +26 -0
  55. package/src/ui/static/style.css +382 -0
  56. package/src/version.mjs +1 -0
  57. package/src/watch.mjs +80 -0
@@ -0,0 +1,637 @@
1
+ // The Hub: the one API that MCP, importers, CLI and UI all go through.
2
+ //
3
+ // Sync model ("sync once, chat separately, sync again later"):
4
+ // ingest()/submit() — a source hands in conversations or statements → archive + inbox
5
+ // sync() — inbox → classify → merge (newer wins, conflicts flagged)
6
+ // → per-AI outbox counts, last sync time, new counts
7
+ // pull() — an AI receives its context card + what's new for it (marks delivered)
8
+ // search()/read() — an AI with "Everything" access searches the raw archive
9
+ // Every delivery to an AI is written to the access log ("who took what").
10
+ import { Store, defaultDataDir, emptyState } from './store.mjs';
11
+ import { Archive } from './archive.mjs';
12
+ import { classify, CATEGORIES, SENSITIVITY } from './classify.mjs';
13
+ import { extractStatements, slotOf } from './extract.mjs';
14
+ import { mergeStatement } from './merge.mjs';
15
+ import { CLIENTS, ensureClient, clientInfo, clientName } from './clients.mjs';
16
+ import { outbox, normalizeRule, ruleFor, allowed, defaultRule, everythingRule } from './rules.mjs';
17
+ import { buildCard, buildDelta } from './card.mjs';
18
+ import { maskSecrets, hash, normalize, newId, sentences } from './text.mjs';
19
+ import { FriendlyError } from './errors.mjs';
20
+ import { tokens } from './archive.mjs';
21
+ import { buildProfile, firstPerson } from './profile.mjs';
22
+ import { candidates, renderProfile, SUGGESTED_CHARS, PURPOSES } from './generator.mjs';
23
+ import { mkdirSync, renameSync, existsSync, readdirSync, rmSync, statSync, copyFileSync, readFileSync, writeFileSync } from 'node:fs';
24
+ import { join } from 'node:path';
25
+
26
+ const MAX_LOG = 200;
27
+ const MAX_ACCESS_LOG = 1000;
28
+ const MAX_TEXT = 500;
29
+ const MAX_TRASH = 500;
30
+ const UNDO_MAX_ITEMS = 20000;
31
+ const DELETED_KEEP_DAYS = 7;
32
+
33
+ export class Hub {
34
+ constructor(dir = defaultDataDir()) {
35
+ this.store = new Store(dir);
36
+ this.archive = new Archive(dir);
37
+ this.dir = dir;
38
+ }
39
+
40
+ read() { return this.store.read(); }
41
+
42
+ /**
43
+ * Hand in statements from a source. Only new material is queued.
44
+ * @param {string} clientId
45
+ * @param {Array<string|{text:string, category?:string, sensitivity?:string, observedAt?:string}>} entries
46
+ * @param {{raw?: boolean, now?: string}} [opts] raw=true: entries are free text to extract from
47
+ */
48
+ async submit(clientId, entries, opts = {}) {
49
+ const now = opts.now || new Date().toISOString();
50
+ return this.store.update((state) => this.#queue(state, clientId, entries, opts, now));
51
+ }
52
+
53
+ #queue(state, clientId, entries, opts, now) {
54
+ const c = ensureClient(state, clientId);
55
+ c.enabled = true;
56
+ c.lastSeenAt = now;
57
+ let accepted = 0, duplicates = 0;
58
+ for (const e of entries) {
59
+ const base = typeof e === 'string' ? { text: e } : e;
60
+ const texts = opts.raw ? extractStatements(base.text).map((s) => s.text) : [base.text];
61
+ for (const raw of texts) {
62
+ if (!raw || !String(raw).trim()) continue;
63
+ const text = maskSecrets(String(raw).trim().slice(0, MAX_TEXT)).text; // mask before disk
64
+ const key = hash(clientId + '|' + normalize(text));
65
+ if (state.seen[key]) { duplicates++; continue; }
66
+ if (state.forgotten?.length && Hub.forgetKeys(text).some((k) => state.forgotten.includes(k))) continue;
67
+ state.seen[key] = now.slice(0, 10);
68
+ state.inbox.push({
69
+ id: newId('in'), client: clientId, text,
70
+ category: base.category, sensitivity: base.sensitivity,
71
+ observedAt: base.observedAt || now, receivedAt: now,
72
+ });
73
+ accepted++;
74
+ }
75
+ }
76
+ return { accepted, duplicates, inbox: state.inbox.length };
77
+ }
78
+
79
+ /**
80
+ * Ingest parsed conversations from one source: archive every message, queue facts
81
+ * from the user's own messages (and vendor memory notes).
82
+ * @param {string} clientId
83
+ * @param {{messages: {role, text, at?, conv?, title?}[], memories?: {text, at?}[]}} parsed
84
+ */
85
+ async ingest(clientId, parsed, opts = {}) {
86
+ const now = opts.now || new Date().toISOString();
87
+ return this.store.update((state) => {
88
+ ensureClient(state, clientId);
89
+ const forgotten = new Set(state.forgotten || []);
90
+ parsed = { ...parsed, messages: parsed.messages.map((m) => ({ ...m, text: Hub.scrub(m.text, forgotten) })) };
91
+ const archived = this.archive.add(parsed.messages.map((m) => ({ ...m, client: clientId })));
92
+ const entries = [];
93
+ for (const m of parsed.messages) {
94
+ if (m.role === 'assistant') continue;
95
+ for (const s of extractStatements(m.text)) entries.push({ text: s.text, observedAt: m.at || undefined });
96
+ }
97
+ for (const m of parsed.memories || []) {
98
+ for (const line of String(m.text).split(/\n+|(?<=[.。])\s+/)) {
99
+ const t = firstPerson(line.replace(/^[-*•]\s*/, ''));
100
+ if (t.length >= 3) entries.push({ text: t, observedAt: m.at || undefined });
101
+ }
102
+ }
103
+ const q = this.#queue(state, clientId, entries, {}, now);
104
+ return { messages: parsed.messages.length, archived, statements: entries.length, new: q.accepted, duplicates: q.duplicates };
105
+ });
106
+ }
107
+
108
+ /** Run one sync. */
109
+ async sync(opts = {}) {
110
+ const now = opts.now || new Date().toISOString();
111
+ return this.store.update((state) => {
112
+ // Keep what the facts looked like before, so this sync can be undone with one click.
113
+ if (state.inbox.length && state.items.length <= UNDO_MAX_ITEMS) {
114
+ state.undo = { at: now, items: JSON.parse(JSON.stringify(state.items)), entries: state.inbox.map((e) => ({ client: e.client, text: e.text })) };
115
+ }
116
+ const counts = { processed: 0, added: 0, updated: 0, touched: 0, stale: 0, conflicts: 0 };
117
+ const inByClient = {};
118
+ const inbox = state.inbox.sort((a, b) => (a.observedAt < b.observedAt ? -1 : 1));
119
+ for (const e of inbox) {
120
+ const c = classify(e.text, { category: e.category, sensitivity: e.sensitivity });
121
+ const sv = slotOf(c.text);
122
+ const r = mergeStatement(state.items, { ...c, slot: sv?.slot, value: sv?.value, client: e.client, observedAt: e.observedAt }, now);
123
+ counts.processed++;
124
+ counts[r.action]++;
125
+ if (r.action === 'updated' && r.item.conflict) counts.conflicts++;
126
+ if (r.action === 'added' || r.action === 'updated') inByClient[e.client] = (inByClient[e.client] || 0) + 1;
127
+ }
128
+ state.inbox = [];
129
+
130
+ const perClient = {};
131
+ for (const info of CLIENTS) {
132
+ const cs = state.clients[info.id];
133
+ if (!cs?.enabled) continue;
134
+ const pending = outbox(state, info.id).length;
135
+ cs.lastSyncAt = now;
136
+ cs.lastIn = inByClient[info.id] || 0;
137
+ cs.lastOut = pending;
138
+ cs.pendingOut = pending;
139
+ perClient[info.id] = { in: cs.lastIn, out: pending };
140
+ }
141
+ const active = state.items.filter((i) => i.status === 'active');
142
+ const shareable = active.filter((i) => ['public', 'personal'].includes(i.sensitivity) && !['health', 'finance', 'ids', 'others', 'contact'].includes(i.category)).length;
143
+ const entry = { at: now, ...counts, perClient, total: active.length, kept: active.length - shareable, ais: Object.keys(perClient).length, canUndo: !!state.undo && state.undo.at === now };
144
+ state.syncLog.unshift(entry);
145
+ state.syncLog.length = Math.min(state.syncLog.length, MAX_LOG);
146
+ state.lastSyncAt = now;
147
+ return entry;
148
+ });
149
+ }
150
+
151
+ #log(state, clientId, action, count, detail) {
152
+ state.accessLog.unshift({ at: new Date().toISOString(), client: clientId, action, count, detail: detail ? String(detail).slice(0, 120) : undefined });
153
+ state.accessLog.length = Math.min(state.accessLog.length, MAX_ACCESS_LOG);
154
+ }
155
+
156
+ /**
157
+ * Deliver to a client: full context card + delta since its last delivery.
158
+ * Marks everything currently allowed as delivered and logs it.
159
+ */
160
+ async pull(clientId, opts = {}) {
161
+ const now = opts.now || new Date().toISOString();
162
+ const mark = opts.markDelivered !== false;
163
+ return this.store.update((state) => {
164
+ const c = ensureClient(state, clientId);
165
+ c.enabled = true;
166
+ c.lastSeenAt = now;
167
+ if (c.paused) return { client: clientId, paused: true, card: '', delta: '', newCount: 0, newItems: [], lastSyncAt: c.lastSyncAt };
168
+ const fresh = outbox(state, clientId);
169
+ const first = !c.lastDeliveredAt;
170
+ const card = buildCard(state, clientId, now);
171
+ if (mark) {
172
+ const rule = ruleFor(c);
173
+ for (const i of state.items) if (allowed(i, clientId, rule)) c.delivered[i.id] = i.updatedAt;
174
+ const ids = new Set(state.items.map((i) => i.id));
175
+ for (const k of Object.keys(c.delivered)) if (!ids.has(k)) delete c.delivered[k];
176
+ c.pendingOut = 0;
177
+ c.lastDeliveredAt = now;
178
+ this.#log(state, clientId, opts.action || 'pull', card.itemIds.length);
179
+ }
180
+ return {
181
+ client: clientId,
182
+ card: card.text,
183
+ lang: card.lang,
184
+ delta: first ? (card.lang === 'zh' ? '(这是第一次读取,上面全部都是新的。)' : '(First pull: everything above is new.)') : buildDelta(fresh, card.lang),
185
+ newCount: fresh.length,
186
+ newItems: fresh.map((i) => ({ id: i.id, text: i.text, category: i.category, replaces: i.conflict?.previousText || null })),
187
+ lastSyncAt: c.lastSyncAt,
188
+ };
189
+ });
190
+ }
191
+
192
+ /** Search for a client: allowed facts always; raw conversations only with archive access. */
193
+ async search(clientId, query, { limit = 10 } = {}) {
194
+ return this.store.update((state) => {
195
+ const c = ensureClient(state, clientId);
196
+ c.enabled = true;
197
+ c.lastSeenAt = new Date().toISOString();
198
+ if (c.paused) throw new FriendlyError('PAUSED', { client: clientName(clientId) }, 403);
199
+ const rule = ruleFor(c);
200
+ const toks = tokens(query);
201
+ const facts = state.items
202
+ .filter((i) => allowed(i, clientId, rule))
203
+ .map((i) => ({ i, n: toks.filter((t) => i.text.toLowerCase().includes(t)).length }))
204
+ .filter((x) => x.n > 0)
205
+ .sort((a, b) => b.n - a.n)
206
+ .slice(0, limit)
207
+ .map(({ i }) => ({ text: i.text, category: i.category, sources: i.sources.map((s) => s.client) }));
208
+ const conversations = rule.archiveAccess ? this.archive.search(query, { limit }) : null;
209
+ this.#log(state, clientId, 'search', facts.length + (conversations?.length || 0), query);
210
+ return { facts, conversations, archiveAccess: rule.archiveAccess };
211
+ });
212
+ }
213
+
214
+ /** Read one archived conversation (archive access only). */
215
+ async readConversation(clientId, source, conv) {
216
+ return this.store.update((state) => {
217
+ const c = ensureClient(state, clientId);
218
+ if (c.paused) throw new FriendlyError('PAUSED', { client: clientName(clientId) }, 403);
219
+ if (!ruleFor(c).archiveAccess) throw new FriendlyError('ACCESS_FACTS_ONLY', { client: clientName(clientId) }, 403);
220
+ const msgs = this.archive.conversation(source, conv);
221
+ this.#log(state, clientId, 'read', msgs.length, `${source}/${conv}`);
222
+ return msgs;
223
+ });
224
+ }
225
+
226
+ status() {
227
+ const s = this.read();
228
+ const clients = CLIENTS.map((info) => {
229
+ const cs = s.clients[info.id];
230
+ return {
231
+ id: info.id,
232
+ kind: info.kind,
233
+ name: info.name,
234
+ note: info.note || null,
235
+ enabled: !!cs?.enabled,
236
+ paused: !!cs?.paused,
237
+ lastSyncAt: cs?.lastSyncAt || null,
238
+ lastSeenAt: cs?.lastSeenAt || null,
239
+ connectedAt: cs?.connectedAt || null,
240
+ lastDeliveredAt: cs?.lastDeliveredAt || null,
241
+ lastIn: cs?.lastIn || 0,
242
+ lastOut: cs?.lastOut || 0,
243
+ pendingOut: cs?.enabled ? outbox(s, info.id).length : 0,
244
+ known: s.items.filter((i) => i.status === 'active' && i.sources.some((x) => x.client === info.id)).length,
245
+ rule: ruleFor(cs, info.id),
246
+ customRule: !!cs?.rule,
247
+ };
248
+ });
249
+ const active = s.items.filter((i) => i.status === 'active');
250
+ const bySensitivity = Object.fromEntries(SENSITIVITY.map((k) => [k, active.filter((i) => i.sensitivity === k).length]));
251
+ const byCategory = Object.fromEntries(CATEGORIES.map((k) => [k, active.filter((i) => i.category === k).length]));
252
+ return {
253
+ dataDir: this.dir,
254
+ lastSyncAt: s.lastSyncAt || null,
255
+ inbox: s.inbox.length,
256
+ items: active.length,
257
+ conflicts: active.filter((i) => i.conflict && !i.conflict.acknowledged).length,
258
+ bySensitivity,
259
+ byCategory,
260
+ archive: this.archive.stats(),
261
+ clients,
262
+ settings: s.settings,
263
+ lastSync: s.syncLog[0] || null,
264
+ recovered: this.store.lastRecovery || null,
265
+ };
266
+ }
267
+
268
+ /** "How each AI sees you": active facts grouped by the AI they came from. */
269
+ views() {
270
+ const s = this.read();
271
+ const out = {};
272
+ for (const i of s.items) {
273
+ if (i.status !== 'active') continue;
274
+ for (const src of i.sources) {
275
+ (out[src.client] ||= []).push({ id: i.id, text: i.text, category: i.category, sensitivity: i.sensitivity });
276
+ }
277
+ }
278
+ return out;
279
+ }
280
+
281
+ accessLog({ client, limit = 100 } = {}) {
282
+ const s = this.read();
283
+ return s.accessLog.filter((e) => !client || e.client === client).slice(0, limit);
284
+ }
285
+
286
+ async setRule(clientId, rule) {
287
+ return this.store.update((state) => {
288
+ const c = ensureClient(state, clientId);
289
+ if (rule === null || rule?.preset === 'summary') c.rule = null;
290
+ else if (rule?.preset === 'everything') c.rule = everythingRule({ lang: rule.lang });
291
+ else c.rule = normalizeRule({ ...rule, preset: 'custom' }, clientId);
292
+ return ruleFor(c);
293
+ });
294
+ }
295
+
296
+ async setEnabled(clientId, enabled) {
297
+ return this.store.update((state) => { ensureClient(state, clientId).enabled = !!enabled; });
298
+ }
299
+
300
+ /** Record that MindFerry registered itself in a local app's config (or removed itself). */
301
+ async setConnected(clientId, on) {
302
+ return this.store.update((state) => {
303
+ const c = ensureClient(state, clientId);
304
+ c.connectedAt = on ? new Date().toISOString() : null;
305
+ if (on) c.enabled = true;
306
+ else c.lastSeenAt = null;
307
+ });
308
+ }
309
+
310
+ async setPaused(clientId, paused) {
311
+ return this.store.update((state) => {
312
+ const c = ensureClient(state, clientId);
313
+ c.paused = !!paused;
314
+ this.#log(state, clientId, paused ? 'paused' : 'resumed', 0);
315
+ return { paused: c.paused };
316
+ });
317
+ }
318
+
319
+ async updateItem(id, patch) {
320
+ return this.store.update((state) => {
321
+ const i = state.items.find((x) => x.id === id);
322
+ if (!i) throw new FriendlyError('ITEM_NOT_FOUND', {}, 404);
323
+ const now = new Date().toISOString();
324
+ if (patch.delete) {
325
+ state.items = state.items.filter((x) => x.id !== id);
326
+ state.trash ||= [];
327
+ state.trash.unshift({ deletedAt: now, item: i });
328
+ state.trash.length = Math.min(state.trash.length, MAX_TRASH);
329
+ return { deleted: true, canRestore: true };
330
+ }
331
+ if (typeof patch.profileHidden === 'boolean') i.profileHidden = patch.profileHidden;
332
+ if (patch.category && CATEGORIES.includes(patch.category)) i.category = patch.category;
333
+ if (patch.sensitivity && SENSITIVITY.includes(patch.sensitivity) && i.sensitivity !== 'secret' && patch.sensitivity !== 'secret') i.sensitivity = patch.sensitivity;
334
+ if (typeof patch.locked === 'boolean') i.locked = patch.locked;
335
+ if (typeof patch.text === 'string' && patch.text.trim()) i.text = maskSecrets(patch.text.trim().slice(0, MAX_TEXT)).text;
336
+ if (patch.ackConflict && i.conflict) i.conflict.acknowledged = true;
337
+ if (patch.category || patch.sensitivity || patch.text) i.userEdited = true;
338
+ i.updatedAt = now;
339
+ return i;
340
+ });
341
+ }
342
+
343
+ async updateSettings(patch) {
344
+ return this.store.update((state) => {
345
+ if (patch.autoSyncMinutes !== undefined) state.settings.autoSyncMinutes = Math.max(0, Math.min(10080, Number(patch.autoSyncMinutes) || 0));
346
+ if (patch.uiLang && ['zh', 'en'].includes(patch.uiLang)) state.settings.uiLang = patch.uiLang;
347
+ if (typeof patch.watchDownloads === 'boolean') {
348
+ if (patch.watchDownloads && !state.settings.watchDownloads) state.settings.watchSince = new Date().toISOString();
349
+ state.settings.watchDownloads = patch.watchDownloads;
350
+ }
351
+ // Only an AI app on this computer may tidy up: a web AI would read raw chats over the internet.
352
+ if (patch.organizer !== undefined) state.settings.organizer = patch.organizer && clientInfo(patch.organizer)?.kind === 'mcp' ? patch.organizer : null;
353
+ if (typeof patch.watchDir === 'string' && patch.watchDir.trim()) state.settings.watchDir = patch.watchDir.trim();
354
+ return state.settings;
355
+ });
356
+ }
357
+
358
+ /** Delete everything MindFerry stored (facts, archive, logs). Rules/settings reset too. */
359
+ async wipe({ keepCopy = true } = {}) {
360
+ const r = await this.store.update((state) => {
361
+ let copy = null;
362
+ if (keepCopy && (state.items.length || this.archive.stats().messages)) {
363
+ copy = join(this.dir, 'deleted-' + new Date().toISOString().replace(/[:.]/g, '-'));
364
+ mkdirSync(copy, { recursive: true, mode: 0o700 });
365
+ // The store file is rewritten below; copy what it holds now.
366
+ this.store.write(state);
367
+ copyFileSync(this.store.file, join(copy, 'store.json'));
368
+ if (existsSync(this.archive.file)) copyFileSync(this.archive.file, join(copy, 'archive.jsonl'));
369
+ }
370
+ if (!keepCopy) this.purgeDeleted(0);
371
+ const forgotten = state.forgotten || [];
372
+ for (const k of Object.keys(state)) delete state[k];
373
+ Object.assign(state, emptyState());
374
+ // Fingerprints (not words) of what was deleted for good survive, so re-importing an old
375
+ // export after "Delete everything" doesn't bring those sentences back.
376
+ if (forgotten.length) state.forgotten = forgotten;
377
+ this.archive.clear();
378
+ return { wiped: true, recoverable: !!copy, keepDays: DELETED_KEEP_DAYS };
379
+ });
380
+ this.store.dropPrev();
381
+ return r;
382
+ }
383
+
384
+ /** Copies kept by wipe(), newest first. */
385
+ deletedCopies() {
386
+ if (!existsSync(this.dir)) return [];
387
+ return readdirSync(this.dir).filter((f) => f.startsWith('deleted-')).sort().reverse()
388
+ .map((f) => ({ name: f, at: statSync(join(this.dir, f)).mtime.toISOString() }));
389
+ }
390
+
391
+ /** Bring back the most recent wiped copy (replaces what is there now). */
392
+ async restoreDeleted() {
393
+ const [latest] = this.deletedCopies();
394
+ if (!latest) throw new FriendlyError('NOTHING_TO_UNDO', {}, 409);
395
+ const dir = join(this.dir, latest.name);
396
+ await this.store.lock();
397
+ try {
398
+ const keep = this.read().forgotten || [];
399
+ copyFileSync(join(dir, 'store.json'), this.store.file);
400
+ if (keep.length) { const st = JSON.parse(readFileSync(this.store.file, 'utf8')); st.forgotten = [...new Set([...(st.forgotten || []), ...keep])]; writeFileSync(this.store.file, JSON.stringify(st), { mode: 0o600 }); }
401
+ if (existsSync(join(dir, 'archive.jsonl'))) copyFileSync(join(dir, 'archive.jsonl'), this.archive.file);
402
+ this.archive.reload?.();
403
+ rmSync(dir, { recursive: true, force: true });
404
+ } finally { this.store.unlock(); }
405
+ return { restored: true };
406
+ }
407
+
408
+ /** Remove wiped copies older than `days` (0 = all). */
409
+ purgeDeleted(days = DELETED_KEEP_DAYS) {
410
+ const cut = Date.now() - days * 86400000;
411
+ for (const d of this.deletedCopies()) {
412
+ const p = join(this.dir, d.name);
413
+ if (days === 0 || statSync(p).mtimeMs < cut) rmSync(p, { recursive: true, force: true });
414
+ }
415
+ }
416
+
417
+ /** Undo the most recent sync: facts go back to how they were; its statements are forgotten. */
418
+ async undoSync() {
419
+ return this.store.update((state) => {
420
+ const u = state.undo;
421
+ if (!u) throw new FriendlyError('NOTHING_TO_UNDO', {}, 409);
422
+ const before = state.items.filter((i) => i.status === 'active').length;
423
+ // Facts this undo takes away go to "Recently deleted", so undoing can itself be undone.
424
+ const kept = new Set(u.items.map((i) => i.id));
425
+ const gone = state.items.filter((i) => !kept.has(i.id) && i.status === 'active');
426
+ state.trash ||= [];
427
+ for (const i of gone) state.trash.unshift({ deletedAt: new Date().toISOString(), item: i, by: 'undo' });
428
+ state.trash.length = Math.min(state.trash.length, MAX_TRASH);
429
+ state.items = u.items;
430
+ for (const e of u.entries) delete state.seen[hash(e.client + '|' + normalize(e.text))];
431
+ delete state.undo;
432
+ const after = state.items.filter((i) => i.status === 'active').length;
433
+ if (state.syncLog[0]?.at === u.at) state.syncLog[0].undone = true;
434
+ for (const cs of Object.values(state.clients)) if (cs.enabled) cs.pendingOut = outbox(state, cs.id).length;
435
+ return { removed: Math.max(0, before - after), at: u.at, facts: gone.map((i) => i.text) };
436
+ });
437
+ }
438
+
439
+ /** Recently deleted facts (can be restored). */
440
+ trash() {
441
+ return (this.read().trash || []).map((t) => ({ id: t.item.id, text: t.item.text, category: t.item.category, deletedAt: t.deletedAt }));
442
+ }
443
+
444
+ /** Fingerprints of a sentence, with and without "I"/"我" in front (see forgetForGood). */
445
+ static forgetKeys(text) {
446
+ const t = String(text).trim();
447
+ return [t, t.replace(/^(?:我|I(?:'m| am)?\s)/i, '')].map((x) => hash('forgot|' + normalize(x))).filter((x, i, a) => a.indexOf(x) === i);
448
+ }
449
+
450
+ /** Replace sentences the user deleted for good with "[removed]" (new imports included). */
451
+ static scrub(text, forgotten) {
452
+ if (!forgotten?.size) return text;
453
+ let hit = false;
454
+ // Line breaks inside a sentence and lead-ins ("Ugh, I take…") must not hide it: check the
455
+ // whole sentence and each clause of it.
456
+ const flat = String(text).replace(/\s*\n\s*(?=[a-z\u4e00-\u9fff])/g, ' ');
457
+ const out = sentences(flat).map((sen) => {
458
+ const parts = [sen, ...sen.split(/[,,;;::—–]\s*/)];
459
+ return parts.some((x) => Hub.forgetKeys(x).some((k) => forgotten.has(k))) ? ((hit = true), '[removed]') : sen;
460
+ });
461
+ return hit ? out.join(' ') : text;
462
+ }
463
+
464
+ /** Delete a fact for good: out of the facts and the trash, and its words out of the chat archive. */
465
+ async forgetForGood(id) {
466
+ const r = await this.store.update((state) => {
467
+ const texts = [];
468
+ const k = (state.trash || []).findIndex((t) => t.item.id === id);
469
+ if (k >= 0) { texts.push(state.trash[k].item.text, ...(state.trash[k].item.history || []).map((h) => h.text || '')); state.trash.splice(k, 1); }
470
+ const j = state.items.findIndex((i) => i.id === id);
471
+ if (j >= 0) { texts.push(state.items[j].text, ...(state.items[j].history || []).map((h) => h.text || '')); state.items.splice(j, 1); }
472
+ if (!texts.length) throw new FriendlyError('ITEM_NOT_FOUND', { id }, 404);
473
+ if (state.undo) state.undo = null; // an undo snapshot would bring it back
474
+ // Remember a fingerprint (not the words) so a later import of the same chat can't bring it back.
475
+ state.forgotten = [...new Set([...(state.forgotten || []), ...texts.filter(Boolean).flatMap((x) => Hub.forgetKeys(x))])].slice(-5000);
476
+ const words = texts.filter(Boolean);
477
+ // Copies kept by "Delete everything" may hold it too.
478
+ const keys = new Set(words.map((x) => normalize(x)));
479
+ for (const d of this.deletedCopies()) {
480
+ const dir = join(this.dir, d.name);
481
+ new Archive(dir).redact(words);
482
+ const f = join(dir, 'store.json');
483
+ try {
484
+ const old = JSON.parse(readFileSync(f, 'utf8'));
485
+ old.items = (old.items || []).filter((i) => !keys.has(normalize(i.text)));
486
+ old.trash = (old.trash || []).filter((t) => !keys.has(normalize(t.item?.text)));
487
+ old.undo = null;
488
+ writeFileSync(f + '.tmp', JSON.stringify(old), { mode: 0o600 }); renameSync(f + '.tmp', f);
489
+ } catch {}
490
+ }
491
+ return { removed: true, archiveChanged: this.archive.redact(words) };
492
+ });
493
+ this.store.dropPrev();
494
+ return r;
495
+ }
496
+
497
+ async restoreItem(id) {
498
+ return this.store.update((state) => {
499
+ const k = (state.trash || []).findIndex((t) => t.item.id === id);
500
+ if (k < 0) throw new FriendlyError('ITEM_NOT_FOUND', {}, 404);
501
+ const [t] = state.trash.splice(k, 1);
502
+ t.item.updatedAt = new Date().toISOString();
503
+ state.items.push(t.item);
504
+ return { restored: true };
505
+ });
506
+ }
507
+
508
+ /** "About me": the short profile any AI can read first. With clientId: what that AI may see. */
509
+ profile(clientId = null, opts = {}) {
510
+ const s = this.read();
511
+ if (clientId && !clientInfo(clientId)) throw new FriendlyError('UNKNOWN_CLIENT', { id: clientId });
512
+ return buildProfile(s, { clientId, ...(SUGGESTED_CHARS[clientId] ? { maxChars: SUGGESTED_CHARS[clientId] } : {}), ...opts });
513
+ }
514
+
515
+ /** Hide / show one fact in the "About me" profile (it stays in memory). */
516
+ async setProfileHidden(id, hidden) {
517
+ return this.updateItem(id, { profileHidden: !!hidden });
518
+ }
519
+
520
+ /** Overview for an AI: what categories it may see, with counts and a few titles. */
521
+ catalog(clientId) {
522
+ const s = this.read();
523
+ const rule = ruleFor(s.clients[clientId], clientId);
524
+ const items = s.items.filter((i) => allowed(i, clientId, rule));
525
+ const byCat = {};
526
+ for (const i of items) (byCat[i.category] ||= []).push(i);
527
+ return Object.entries(byCat).map(([category, list]) => ({
528
+ category, count: list.length,
529
+ latest: list.sort((a, b) => (b.observedAt > a.observedAt ? 1 : -1)).slice(0, 3).map((i) => i.text.slice(0, 80)),
530
+ })).sort((a, b) => b.count - a.count);
531
+ }
532
+
533
+ /** Allowed facts of one category (or all), newest first, for an AI that wants more detail. */
534
+ async browse(clientId, category, { limit = 30 } = {}) {
535
+ return this.store.update((state) => {
536
+ const c = ensureClient(state, clientId);
537
+ c.enabled = true;
538
+ c.lastSeenAt = new Date().toISOString();
539
+ if (c.paused) throw new FriendlyError('PAUSED', { client: clientName(clientId) }, 403);
540
+ const rule = ruleFor(c, clientId);
541
+ const list = state.items
542
+ .filter((i) => allowed(i, clientId, rule) && (!category || category === 'all' || i.category === category))
543
+ .sort((a, b) => (b.observedAt > a.observedAt ? 1 : -1))
544
+ .slice(0, limit)
545
+ .map((i) => ({ id: i.id, text: i.text, category: i.category, date: (i.observedAt || '').slice(0, 10), sensitivity: i.sensitivity }));
546
+ this.#log(state, clientId, 'browse', list.length, category || 'all');
547
+ return list;
548
+ });
549
+ }
550
+
551
+ /** Profile generator: candidates for a target AI and purpose (remembers the last choice). */
552
+ generator(clientId = 'new-ai', purpose = null, lang = null) {
553
+ const s = this.read();
554
+ const saved = s.picks?.[clientId] || null;
555
+ const p = PURPOSES.includes(purpose) ? purpose : (saved?.purpose || 'all');
556
+ const list = candidates(s, p, saved);
557
+ const L = lang || (s.settings?.uiLang === 'zh' ? 'zh' : 'en');
558
+ const maxChars = SUGGESTED_CHARS[clientId] || SUGGESTED_CHARS.default;
559
+ return { clientId, purpose: p, items: list, maxChars, ...renderProfile(list, { lang: L, maxChars }) };
560
+ }
561
+
562
+ /** Save the user's ticks for a target AI and render the final text. Logs a copy for web AIs. */
563
+ async generate(clientId, { purpose = 'all', on = [], off = [], lang = 'en', copied = false } = {}) {
564
+ return this.store.update((state) => {
565
+ state.picks ||= {};
566
+ const saved = { purpose, on: on.slice(0, 5000), off: off.slice(0, 5000), seen: state.items.filter((i) => i.status === 'active').map((i) => i.id) };
567
+ const prev = state.picks[clientId];
568
+ const list = candidates(state, purpose, { ...saved, seen: prev?.seen || saved.seen });
569
+ state.picks[clientId] = saved;
570
+ const maxChars = SUGGESTED_CHARS[clientId] || SUGGESTED_CHARS.default;
571
+ const r = renderProfile(list, { lang, maxChars });
572
+ if (copied && clientInfo(clientId)) {
573
+ const c = ensureClient(state, clientId);
574
+ c.enabled = true;
575
+ for (const id of r.itemIds) { const it = state.items.find((i) => i.id === id); if (it) c.delivered[id] = it.updatedAt; }
576
+ c.pendingOut = 0;
577
+ c.lastDeliveredAt = new Date().toISOString();
578
+ this.#log(state, clientId, 'card copied', r.itemIds.length);
579
+ }
580
+ return { ...r, maxChars, purpose };
581
+ });
582
+ }
583
+
584
+ /**
585
+ * "Let an AI tidy up": the one AI the user picked (settings.organizer) reads not-yet-tidied
586
+ * messages the user wrote, a batch at a time, and saves the facts it finds with memory_push.
587
+ * Off unless the user turned it on for exactly this AI.
588
+ */
589
+ async organizeBatch(clientId, n = 20) {
590
+ return this.store.update((state) => {
591
+ if (state.settings?.organizer !== clientId || clientInfo(clientId)?.kind !== 'mcp') throw new FriendlyError('ORGANIZE_OFF', { client: clientName(clientId) }, 403);
592
+ const c = state.clients[clientId];
593
+ if (c?.paused) throw new FriendlyError('PAUSED', { client: clientName(clientId) }, 403);
594
+ // The organizer reads only what its own rule lets it see: each sentence is classified and
595
+ // blanked unless that AI could have received it as a fact. ID numbers are always masked.
596
+ const rule = ruleFor(c, clientId);
597
+ const clean = (text) => String(text).split(/(?<=[.!?。!?\n])\s*/).map((sen) => {
598
+ const k = classify(sen);
599
+ // Sentences the rules can't place ("uncertain") are what tidying up is for, so they pass;
600
+ // anything placed in a category or topic this AI may not see is blanked.
601
+ const ok = (k.sensitivity === 'uncertain' && k.category === 'other') || allowed({ ...k, status: 'active', sources: [{ client: clientId }] }, clientId, rule);
602
+ return ok ? k.text : '[private, not shared]';
603
+ }).join(' ');
604
+ const tidied = new Set(state.tidied || []);
605
+ for (const h of state.organizePending?.[clientId] || []) tidied.add(h);
606
+ const batch = [];
607
+ let remaining = 0;
608
+ for (const m of this.archive.iter()) {
609
+ if (m.role !== 'user' || tidied.has(m.h) || String(m.text).trim().length < 12) continue;
610
+ if (batch.length < n) batch.push(m); else remaining++;
611
+ }
612
+ state.tidied = [...tidied].slice(-50000);
613
+ state.organizePending = { ...(state.organizePending || {}), [clientId]: batch.map((m) => m.h) };
614
+ this.#log(state, clientId, 'organize', batch.length);
615
+ return { messages: batch.map((m) => ({ from: m.client, chat: m.title || m.conv, at: m.at, text: clean(String(m.text).slice(0, 2000)) })), remaining };
616
+ });
617
+ }
618
+
619
+ /** Everything MindFerry holds, as plain data (for export / leaving). */
620
+ exportAll() {
621
+ const s = this.read();
622
+ return {
623
+ exportedAt: new Date().toISOString(), app: 'MindFerry', storeVersion: s.version,
624
+ facts: s.items, rules: Object.fromEntries(Object.entries(s.clients).map(([k, v]) => [k, { rule: ruleFor(v, k), paused: !!v.paused }])),
625
+ settings: s.settings, syncLog: s.syncLog, accessLog: s.accessLog,
626
+ conversations: this.archive.all ? this.archive.all() : [],
627
+ };
628
+ }
629
+
630
+ card(clientId) {
631
+ const s = this.read();
632
+ if (!clientInfo(clientId)) throw new FriendlyError('UNKNOWN_CLIENT', { id: clientId });
633
+ return buildCard(s, clientId);
634
+ }
635
+ }
636
+
637
+ export { defaultRule };