@imliulian/dsh-zeromem 0.1.0 → 0.2.1
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 +24 -0
- package/NOTICE +17 -0
- package/README.md +44 -13
- package/README.zh.md +44 -13
- package/assets/panel.js +110 -4
- package/bin/dsh-zeromem.mjs +187 -0
- package/lib/contracts.mjs +253 -2
- package/lib/expiry.mjs +105 -1
- package/lib/hooks.mjs +29 -6
- package/lib/index.mjs +4 -1
- package/lib/llm.mjs +6 -2
- package/lib/memory.mjs +263 -5
- package/lib/portability.mjs +819 -0
- package/lib/store.mjs +268 -28
- package/lib/tools.mjs +101 -7
- package/lib/web.mjs +86 -8
- package/package.json +8 -4
|
@@ -0,0 +1,819 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only Markdown export (Obsidian/Git friendly) and SQLite Online Backup snapshots.
|
|
3
|
+
*
|
|
4
|
+
* Parity with Python ZeroMem (`v2mem/portability.py`), zero third-party dependencies:
|
|
5
|
+
* 1. `exportMarkdown`:
|
|
6
|
+
* - 100% read-only: opens SQLite read-only with `PRAGMA query_only = ON`, never mutates DB.
|
|
7
|
+
* - Zero LLM calls; defense-in-depth credential redaction via `redactCredentials`.
|
|
8
|
+
* - Preserves bound original evidence quotes, timeline fields (`occurred_start` / `occurred_end`),
|
|
9
|
+
* supersession lineage (`supersedes_fact_id` / `superseded_by`), and `until:` expiry status.
|
|
10
|
+
* - Supports in-memory stdout mode, single file (`outputPath`), or per-namespace Obsidian/Git
|
|
11
|
+
* directory (`outputDir` with `INDEX.md`).
|
|
12
|
+
* 2. `backupDatabase`:
|
|
13
|
+
* - Uses Node built-in `node:sqlite` Online Backup API (`backup`) so active WAL readers/writers
|
|
14
|
+
* are never blocked or corrupted.
|
|
15
|
+
* - Flattens the destination snapshot to `PRAGMA journal_mode = DELETE`, guaranteeing a clean
|
|
16
|
+
* single-file snapshot with zero `-wal`/`-shm` sidecars (safe for OneDrive/BaiduSyncdisk/iCloud).
|
|
17
|
+
* - Verifies `PRAGMA integrity_check === 'ok'`, computes SHA-256, and publishes atomically.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import fs from "node:fs";
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
import { DatabaseSync, backup as sqliteOnlineBackup } from "node:sqlite";
|
|
24
|
+
|
|
25
|
+
import { expandHome } from "./config.mjs";
|
|
26
|
+
import { redactCredentials } from "./contracts.mjs";
|
|
27
|
+
import {
|
|
28
|
+
evaluateExpiry,
|
|
29
|
+
factMatchesOccurredRange,
|
|
30
|
+
normalizeOccurredRange,
|
|
31
|
+
parseUntilDate,
|
|
32
|
+
resolveAsOfDate,
|
|
33
|
+
} from "./expiry.mjs";
|
|
34
|
+
import { APP_FORMAT_ID } from "./store.mjs";
|
|
35
|
+
|
|
36
|
+
const UNSAFE_FILENAME_RE = /[<>:"/\\|?*\x00-\x1f]+/g;
|
|
37
|
+
const RESERVED_STEMS = new Set([
|
|
38
|
+
"CON", "PRN", "AUX", "NUL",
|
|
39
|
+
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
|
|
40
|
+
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
|
|
41
|
+
"INDEX",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
function utcNowIso() {
|
|
45
|
+
return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function sha256File(filePath) {
|
|
49
|
+
const hash = createHash("sha256");
|
|
50
|
+
const fd = fs.openSync(filePath, "r");
|
|
51
|
+
try {
|
|
52
|
+
const buf = Buffer.allocUnsafe(65536);
|
|
53
|
+
while (true) {
|
|
54
|
+
const n = fs.readSync(fd, buf, 0, buf.length, null);
|
|
55
|
+
if (n <= 0) break;
|
|
56
|
+
hash.update(n === buf.length ? buf : buf.subarray(0, n));
|
|
57
|
+
}
|
|
58
|
+
} finally {
|
|
59
|
+
fs.closeSync(fd);
|
|
60
|
+
}
|
|
61
|
+
return hash.digest("hex");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function safeJsonParse(raw, fallback) {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(raw);
|
|
67
|
+
} catch {
|
|
68
|
+
return fallback;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function hasTable(db, tableName) {
|
|
73
|
+
const row = db
|
|
74
|
+
.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?")
|
|
75
|
+
.get(String(tableName));
|
|
76
|
+
return Boolean(row);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function openReadOnlyDb(dbFile) {
|
|
80
|
+
let db;
|
|
81
|
+
try {
|
|
82
|
+
db = new DatabaseSync(dbFile, { readOnly: true, timeout: 15_000 });
|
|
83
|
+
db.exec("PRAGMA query_only = ON;");
|
|
84
|
+
// Touch sqlite_master to confirm readable even if WAL lacks -shm
|
|
85
|
+
db.prepare("SELECT 1 AS ok FROM sqlite_master LIMIT 1").get();
|
|
86
|
+
return db;
|
|
87
|
+
} catch {
|
|
88
|
+
try {
|
|
89
|
+
if (db) db.close();
|
|
90
|
+
} catch {
|
|
91
|
+
// ignore
|
|
92
|
+
}
|
|
93
|
+
const fallback = new DatabaseSync(dbFile, { timeout: 15_000 });
|
|
94
|
+
fallback.exec("PRAGMA query_only = ON;");
|
|
95
|
+
fallback.exec("PRAGMA busy_timeout = 15000;");
|
|
96
|
+
return fallback;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function atomicWriteText(targetPath, text) {
|
|
101
|
+
const dir = path.dirname(targetPath);
|
|
102
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
103
|
+
const base = path.basename(targetPath);
|
|
104
|
+
const tmpPath = path.join(dir, `.${base}.tmp.${process.pid}.${Date.now()}`);
|
|
105
|
+
try {
|
|
106
|
+
const fd = fs.openSync(tmpPath, "w", 0o600);
|
|
107
|
+
try {
|
|
108
|
+
fs.writeSync(fd, text, 0, "utf8");
|
|
109
|
+
fs.fsyncSync(fd);
|
|
110
|
+
} finally {
|
|
111
|
+
fs.closeSync(fd);
|
|
112
|
+
}
|
|
113
|
+
fs.renameSync(tmpPath, targetPath);
|
|
114
|
+
} catch (err) {
|
|
115
|
+
try {
|
|
116
|
+
if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath);
|
|
117
|
+
} catch {
|
|
118
|
+
// ignore cleanup error
|
|
119
|
+
}
|
|
120
|
+
throw err;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function safeNamespaceStem(namespace, usedSet) {
|
|
125
|
+
let cleaned = String(namespace || "")
|
|
126
|
+
.trim()
|
|
127
|
+
.replace(UNSAFE_FILENAME_RE, "_")
|
|
128
|
+
.replace(/^[ .]+|[ .]+$/g, "");
|
|
129
|
+
if (!cleaned || RESERVED_STEMS.has(cleaned.toUpperCase())) {
|
|
130
|
+
cleaned = `ns_${cleaned || "default"}`;
|
|
131
|
+
}
|
|
132
|
+
cleaned = cleaned.slice(0, 80);
|
|
133
|
+
let candidate = cleaned;
|
|
134
|
+
if (usedSet.has(candidate.toLowerCase())) {
|
|
135
|
+
const digest = createHash("sha256").update(String(namespace), "utf8").digest("hex").slice(0, 6);
|
|
136
|
+
candidate = `${cleaned}_${digest}`;
|
|
137
|
+
}
|
|
138
|
+
usedSet.add(candidate.toLowerCase());
|
|
139
|
+
return candidate;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function yamlScalar(value) {
|
|
143
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
144
|
+
if (typeof value === "number") return String(value);
|
|
145
|
+
return JSON.stringify(String(value));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function formatBlockquote(prefix, text) {
|
|
149
|
+
const safeText = redactCredentials(String(text || ""))
|
|
150
|
+
.replace(/\r\n/g, "\n")
|
|
151
|
+
.replace(/\r/g, "\n")
|
|
152
|
+
.trim();
|
|
153
|
+
const lines = safeText ? safeText.split("\n") : [""];
|
|
154
|
+
const out = [`> ${prefix}${lines[0]}`];
|
|
155
|
+
for (let i = 1; i < lines.length; i++) {
|
|
156
|
+
out.push(lines[i] ? `> ${lines[i]}` : ">");
|
|
157
|
+
}
|
|
158
|
+
return out.join("\n");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function renderFactMarkdown(fact) {
|
|
162
|
+
const fid = fact.fact_id;
|
|
163
|
+
const badges = [`\`${fact.type}\``];
|
|
164
|
+
if (fact.action === "revise") badges.push("`已纠错`");
|
|
165
|
+
if (fact.supersedes_fact_id !== null && fact.supersedes_fact_id !== undefined) {
|
|
166
|
+
badges.push(`\`替代 #${fact.supersedes_fact_id}\``);
|
|
167
|
+
}
|
|
168
|
+
if (Array.isArray(fact.superseded_by) && fact.superseded_by.length) {
|
|
169
|
+
const supRefs = fact.superseded_by.map((x) => `#${x}`).join(", ");
|
|
170
|
+
badges.push(`\`已被 ${supRefs} 替代\``);
|
|
171
|
+
}
|
|
172
|
+
if (fact.until_expiry?.label) {
|
|
173
|
+
badges.push(`\`${fact.until_expiry.label}\``);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const lines = [`### Fact #${fid} ${badges.join(" ")}`, ""];
|
|
177
|
+
lines.push(redactCredentials(fact.text));
|
|
178
|
+
lines.push("");
|
|
179
|
+
|
|
180
|
+
const metaParts = [];
|
|
181
|
+
if (fact.occurred_start) {
|
|
182
|
+
let occ = String(fact.occurred_start);
|
|
183
|
+
if (fact.occurred_end && String(fact.occurred_end) !== occ) {
|
|
184
|
+
occ = `${occ} ~ ${fact.occurred_end}`;
|
|
185
|
+
}
|
|
186
|
+
metaParts.push(`**发生时间**: \`${occ}\``);
|
|
187
|
+
}
|
|
188
|
+
metaParts.push(`**记录时间**: \`${fact.mentioned_at}\``);
|
|
189
|
+
if (fact.where) {
|
|
190
|
+
metaParts.push(`**地点/环境**: ${redactCredentials(String(fact.where))}`);
|
|
191
|
+
}
|
|
192
|
+
let srcRef = `\`${fact.doc_id}\``;
|
|
193
|
+
if (fact.source_id) {
|
|
194
|
+
srcRef += ` (${redactCredentials(String(fact.source_id))})`;
|
|
195
|
+
}
|
|
196
|
+
metaParts.push(`**来源**: ${srcRef}`);
|
|
197
|
+
lines.push(`- ${metaParts.join(" | ")}`);
|
|
198
|
+
|
|
199
|
+
if (Array.isArray(fact.entities) && fact.entities.length) {
|
|
200
|
+
const entStr = fact.entities.map((e) => `\`${redactCredentials(String(e))}\``).join(" ");
|
|
201
|
+
lines.push(`- **实体/标签**: ${entStr}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (fact.supersedes_fact_id !== null && fact.supersedes_fact_id !== undefined) {
|
|
205
|
+
lines.push(`- **演化关系**: 替代旧事实 \`Fact #${fact.supersedes_fact_id}\``);
|
|
206
|
+
}
|
|
207
|
+
if (Array.isArray(fact.superseded_by) && fact.superseded_by.length) {
|
|
208
|
+
const newer = fact.superseded_by.map((x) => `\`Fact #${x}\``).join(", ");
|
|
209
|
+
lines.push(`- **历史状态**: 已被更新事实 ${newer} 替代`);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (Array.isArray(fact.evidence) && fact.evidence.length) {
|
|
213
|
+
lines.push("");
|
|
214
|
+
for (const ev of fact.evidence) {
|
|
215
|
+
const rolePart = ev.role ? ` · \`${ev.role}\`` : "";
|
|
216
|
+
lines.push(formatBlockquote(`**原文证据 (\`${ev.id}\`${rolePart})**: `, String(ev.text || "")));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
lines.push("");
|
|
221
|
+
return lines.join("\n");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function renderEvictedSection(evictedRows) {
|
|
225
|
+
if (!Array.isArray(evictedRows) || !evictedRows.length) return "";
|
|
226
|
+
const lines = [
|
|
227
|
+
"---",
|
|
228
|
+
"",
|
|
229
|
+
"## 回收站归档记录(`evicted_records`)",
|
|
230
|
+
"",
|
|
231
|
+
"| 批次 ID | 类型 | 记录 ID | 空间 | 原因 | 淘汰时间 | SHA-256 (前12位) |",
|
|
232
|
+
"| :--- | :--- | :--- | :--- | :--- | :--- | :--- |",
|
|
233
|
+
];
|
|
234
|
+
for (const r of evictedRows) {
|
|
235
|
+
lines.push(
|
|
236
|
+
`| \`${r.batch_id}\` | \`${r.record_kind}\` | \`${r.record_id}\` | ` +
|
|
237
|
+
`\`${r.namespace}\` | ${redactCredentials(String(r.reason))} | ` +
|
|
238
|
+
`\`${r.evicted_at}\` | \`${String(r.content_sha256).slice(0, 12)}\` |`
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
lines.push("");
|
|
242
|
+
return lines.join("\n");
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function loadExportData(
|
|
246
|
+
dbFile,
|
|
247
|
+
{
|
|
248
|
+
namespace = null,
|
|
249
|
+
fromDate = null,
|
|
250
|
+
toDate = null,
|
|
251
|
+
asOfDate,
|
|
252
|
+
includeSuperseded = true,
|
|
253
|
+
includeEvicted = false,
|
|
254
|
+
}
|
|
255
|
+
) {
|
|
256
|
+
const db = openReadOnlyDb(dbFile);
|
|
257
|
+
let factRows = [];
|
|
258
|
+
let docRows = [];
|
|
259
|
+
const segCache = new Map();
|
|
260
|
+
const supersedesMap = new Map();
|
|
261
|
+
const supersededByMap = new Map();
|
|
262
|
+
let evictedBatches = [];
|
|
263
|
+
|
|
264
|
+
try {
|
|
265
|
+
if (namespace) {
|
|
266
|
+
factRows = db
|
|
267
|
+
.prepare(
|
|
268
|
+
`SELECT * FROM facts WHERE namespace = ?
|
|
269
|
+
ORDER BY namespace ASC, COALESCE(occurred_start, mentioned_at) DESC, fact_id ASC`
|
|
270
|
+
)
|
|
271
|
+
.all(namespace)
|
|
272
|
+
.map((r) => ({ ...r }));
|
|
273
|
+
docRows = db
|
|
274
|
+
.prepare("SELECT doc_id, source_id FROM documents WHERE namespace = ?")
|
|
275
|
+
.all(namespace)
|
|
276
|
+
.map((r) => ({ ...r }));
|
|
277
|
+
} else {
|
|
278
|
+
factRows = db
|
|
279
|
+
.prepare(
|
|
280
|
+
`SELECT * FROM facts
|
|
281
|
+
ORDER BY namespace ASC, COALESCE(occurred_start, mentioned_at) DESC, fact_id ASC`
|
|
282
|
+
)
|
|
283
|
+
.all()
|
|
284
|
+
.map((r) => ({ ...r }));
|
|
285
|
+
docRows = db
|
|
286
|
+
.prepare("SELECT doc_id, source_id FROM documents")
|
|
287
|
+
.all()
|
|
288
|
+
.map((r) => ({ ...r }));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const docIds = [...new Set(factRows.map((r) => String(r.doc_id)))].sort();
|
|
292
|
+
const segStmt = db.prepare("SELECT seg_id, role, text FROM segments WHERE doc_id = ?");
|
|
293
|
+
for (const did of docIds) {
|
|
294
|
+
const m = new Map();
|
|
295
|
+
for (const sr of segStmt.all(did)) {
|
|
296
|
+
m.set(String(sr.seg_id), {
|
|
297
|
+
id: String(sr.seg_id),
|
|
298
|
+
role: sr.role ?? null,
|
|
299
|
+
text: String(sr.text),
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
segCache.set(did, m);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (factRows.length && hasTable(db, "fact_supersessions")) {
|
|
306
|
+
for (const srow of db
|
|
307
|
+
.prepare("SELECT new_fact_id, old_fact_id FROM fact_supersessions ORDER BY old_fact_id ASC")
|
|
308
|
+
.all()) {
|
|
309
|
+
const nid = Number(srow.new_fact_id);
|
|
310
|
+
const oid = Number(srow.old_fact_id);
|
|
311
|
+
if (!supersedesMap.has(nid)) supersedesMap.set(nid, []);
|
|
312
|
+
supersedesMap.get(nid).push(oid);
|
|
313
|
+
}
|
|
314
|
+
for (const srow of db
|
|
315
|
+
.prepare(
|
|
316
|
+
`SELECT fs.old_fact_id, fs.new_fact_id FROM fact_supersessions fs
|
|
317
|
+
JOIN facts nf ON nf.fact_id = fs.new_fact_id ORDER BY fs.new_fact_id ASC`
|
|
318
|
+
)
|
|
319
|
+
.all()) {
|
|
320
|
+
const oid = Number(srow.old_fact_id);
|
|
321
|
+
const nid = Number(srow.new_fact_id);
|
|
322
|
+
if (!supersededByMap.has(oid)) supersededByMap.set(oid, []);
|
|
323
|
+
supersededByMap.get(oid).push(nid);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (includeEvicted && hasTable(db, "evicted_records")) {
|
|
328
|
+
const erows = namespace
|
|
329
|
+
? db
|
|
330
|
+
.prepare(
|
|
331
|
+
`SELECT batch_id, record_kind, record_id, namespace, reason, evicted_at, content_sha256
|
|
332
|
+
FROM evicted_records WHERE namespace = ? ORDER BY evicted_at DESC, batch_id ASC`
|
|
333
|
+
)
|
|
334
|
+
.all(namespace)
|
|
335
|
+
: db
|
|
336
|
+
.prepare(
|
|
337
|
+
`SELECT batch_id, record_kind, record_id, namespace, reason, evicted_at, content_sha256
|
|
338
|
+
FROM evicted_records ORDER BY evicted_at DESC, batch_id ASC`
|
|
339
|
+
)
|
|
340
|
+
.all();
|
|
341
|
+
evictedBatches = erows.map((r) => ({ ...r }));
|
|
342
|
+
}
|
|
343
|
+
} finally {
|
|
344
|
+
db.close();
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const docSourceMap = new Map(docRows.map((r) => [String(r.doc_id), r.source_id ?? null]));
|
|
348
|
+
const byNs = new Map();
|
|
349
|
+
const referencedDocs = new Set();
|
|
350
|
+
let supersededCnt = 0;
|
|
351
|
+
let expiredCnt = 0;
|
|
352
|
+
let totalFacts = 0;
|
|
353
|
+
|
|
354
|
+
for (const row of factRows) {
|
|
355
|
+
if (
|
|
356
|
+
!factMatchesOccurredRange(row.occurred_start, row.occurred_end, {
|
|
357
|
+
fromDate,
|
|
358
|
+
toDate,
|
|
359
|
+
})
|
|
360
|
+
) {
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const fid = Number(row.fact_id);
|
|
364
|
+
const supBy = supersededByMap.get(fid) || null;
|
|
365
|
+
if (!includeSuperseded && supBy) continue;
|
|
366
|
+
|
|
367
|
+
const did = String(row.doc_id);
|
|
368
|
+
const ns = String(row.namespace);
|
|
369
|
+
const evIds = safeJsonParse(row.evidence_ids_json || "[]", []);
|
|
370
|
+
const entities = safeJsonParse(row.entities_json || "[]", []);
|
|
371
|
+
const segMap = segCache.get(did) || new Map();
|
|
372
|
+
const evClean = (Array.isArray(evIds) ? evIds : [])
|
|
373
|
+
.map((eid) => segMap.get(String(eid)))
|
|
374
|
+
.filter(Boolean);
|
|
375
|
+
|
|
376
|
+
const untilDate = parseUntilDate({
|
|
377
|
+
tags: entities,
|
|
378
|
+
text: String(row.text || ""),
|
|
379
|
+
evidence: evClean,
|
|
380
|
+
});
|
|
381
|
+
const expiryInfo = evaluateExpiry(untilDate, asOfDate);
|
|
382
|
+
|
|
383
|
+
const item = {
|
|
384
|
+
fact_id: fid,
|
|
385
|
+
doc_id: did,
|
|
386
|
+
source_id: docSourceMap.get(did) ?? null,
|
|
387
|
+
namespace: ns,
|
|
388
|
+
text: String(row.text),
|
|
389
|
+
type: String(row.type),
|
|
390
|
+
occurred_start: row.occurred_start ?? null,
|
|
391
|
+
occurred_end: row.occurred_end ?? null,
|
|
392
|
+
where: row.where_loc ?? null,
|
|
393
|
+
entities: Array.isArray(entities) ? entities : [],
|
|
394
|
+
evidence: evClean,
|
|
395
|
+
action: String(row.action),
|
|
396
|
+
mentioned_at: String(row.mentioned_at),
|
|
397
|
+
until_expiry: expiryInfo,
|
|
398
|
+
supersedes_fact_id: supersedesMap.has(fid) ? supersedesMap.get(fid)[0] : null,
|
|
399
|
+
superseded_by: supBy,
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
if (!byNs.has(ns)) byNs.set(ns, []);
|
|
403
|
+
byNs.get(ns).push(item);
|
|
404
|
+
referencedDocs.add(did);
|
|
405
|
+
totalFacts += 1;
|
|
406
|
+
if (supBy) supersededCnt += 1;
|
|
407
|
+
if (expiryInfo) expiredCnt += 1;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return {
|
|
411
|
+
byNs,
|
|
412
|
+
evictedRows: evictedBatches,
|
|
413
|
+
counts: {
|
|
414
|
+
facts_exported: totalFacts,
|
|
415
|
+
documents_referenced: referencedDocs.size,
|
|
416
|
+
superseded_facts: supersededCnt,
|
|
417
|
+
expired_facts: expiredCnt,
|
|
418
|
+
evicted_records: evictedBatches.length,
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Read-only export of ZeroMem SQLite facts and bound original evidence to Obsidian/Git Markdown.
|
|
425
|
+
*/
|
|
426
|
+
export function exportMarkdown({
|
|
427
|
+
dbPath,
|
|
428
|
+
outputPath = null,
|
|
429
|
+
outputDir = null,
|
|
430
|
+
namespace = null,
|
|
431
|
+
occurredFrom = null,
|
|
432
|
+
occurredTo = null,
|
|
433
|
+
asOf = null,
|
|
434
|
+
includeSuperseded = true,
|
|
435
|
+
includeEvicted = false,
|
|
436
|
+
frontmatter = true,
|
|
437
|
+
} = {}) {
|
|
438
|
+
if (outputPath !== null && outputPath !== undefined && outputDir !== null && outputDir !== undefined) {
|
|
439
|
+
throw new Error("export-target-conflict: specify either outputPath or outputDir, not both");
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const dbFile = expandHome(dbPath);
|
|
443
|
+
if (!dbFile || !fs.existsSync(dbFile) || !fs.statSync(dbFile).isFile()) {
|
|
444
|
+
throw new Error(`db-not-found: ${dbFile || dbPath}`);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const { fromDate, toDate } = normalizeOccurredRange(occurredFrom, occurredTo);
|
|
448
|
+
const asOfDate = resolveAsOfDate(asOf);
|
|
449
|
+
const exportedAt = utcNowIso();
|
|
450
|
+
|
|
451
|
+
const { byNs, evictedRows, counts } = loadExportData(dbFile, {
|
|
452
|
+
namespace: namespace || null,
|
|
453
|
+
fromDate,
|
|
454
|
+
toDate,
|
|
455
|
+
asOfDate,
|
|
456
|
+
includeSuperseded: Boolean(includeSuperseded),
|
|
457
|
+
includeEvicted: Boolean(includeEvicted),
|
|
458
|
+
});
|
|
459
|
+
const namespaces = [...byNs.keys()].sort();
|
|
460
|
+
|
|
461
|
+
if (outputDir !== null && outputDir !== undefined) {
|
|
462
|
+
const outRoot = expandHome(outputDir);
|
|
463
|
+
fs.mkdirSync(outRoot, { recursive: true });
|
|
464
|
+
const usedStems = new Set();
|
|
465
|
+
const writtenFiles = [];
|
|
466
|
+
const indexRows = [];
|
|
467
|
+
|
|
468
|
+
for (const ns of namespaces) {
|
|
469
|
+
const facts = byNs.get(ns);
|
|
470
|
+
const stem = safeNamespaceStem(ns, usedStems);
|
|
471
|
+
const nsFile = path.join(outRoot, `${stem}.md`);
|
|
472
|
+
const nsDocs = new Set(facts.map((f) => f.doc_id)).size;
|
|
473
|
+
const nsSup = facts.filter((f) => Array.isArray(f.superseded_by) && f.superseded_by.length).length;
|
|
474
|
+
const nsExp = facts.filter((f) => Boolean(f.until_expiry)).length;
|
|
475
|
+
|
|
476
|
+
const parts = [];
|
|
477
|
+
if (frontmatter) {
|
|
478
|
+
parts.push(
|
|
479
|
+
"---",
|
|
480
|
+
`generator: ${yamlScalar("ZeroMem")}`,
|
|
481
|
+
"read_only: true",
|
|
482
|
+
`namespace: ${yamlScalar(ns)}`,
|
|
483
|
+
`exported_at: ${yamlScalar(exportedAt)}`,
|
|
484
|
+
`as_of: ${yamlScalar(asOfDate)}`,
|
|
485
|
+
`facts: ${facts.length}`,
|
|
486
|
+
`documents: ${nsDocs}`,
|
|
487
|
+
`superseded_facts: ${nsSup}`,
|
|
488
|
+
`expired_facts: ${nsExp}`,
|
|
489
|
+
"---",
|
|
490
|
+
""
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
parts.push(`# ZeroMem 空间:${ns}`, "");
|
|
494
|
+
const rangeNote =
|
|
495
|
+
fromDate || toDate ? ` · 时间过滤 \`${fromDate || "*"} ~ ${toDate || "*"}\`` : "";
|
|
496
|
+
parts.push(
|
|
497
|
+
`> 只读导出快照 · 导出时间 \`${exportedAt}\` · 事实 \`${facts.length}\` 条 · 文档 \`${nsDocs}\` 篇${rangeNote}`,
|
|
498
|
+
""
|
|
499
|
+
);
|
|
500
|
+
for (const f of facts) parts.push(renderFactMarkdown(f));
|
|
501
|
+
const nsEvicted = evictedRows.filter((r) => String(r.namespace) === ns);
|
|
502
|
+
if (nsEvicted.length) parts.push(renderEvictedSection(nsEvicted));
|
|
503
|
+
|
|
504
|
+
atomicWriteText(nsFile, `${parts.join("\n").trimEnd()}\n`);
|
|
505
|
+
writtenFiles.push(nsFile);
|
|
506
|
+
indexRows.push(`| [${ns}](./${stem}.md) | ${facts.length} | ${nsDocs} | ${nsSup} | ${nsExp} |`);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const idxParts = [];
|
|
510
|
+
if (frontmatter) {
|
|
511
|
+
idxParts.push(
|
|
512
|
+
"---",
|
|
513
|
+
`generator: ${yamlScalar("ZeroMem")}`,
|
|
514
|
+
"read_only: true",
|
|
515
|
+
`exported_at: ${yamlScalar(exportedAt)}`,
|
|
516
|
+
`as_of: ${yamlScalar(asOfDate)}`,
|
|
517
|
+
`namespaces: ${namespaces.length}`,
|
|
518
|
+
`facts: ${counts.facts_exported}`,
|
|
519
|
+
`documents: ${counts.documents_referenced}`,
|
|
520
|
+
"---",
|
|
521
|
+
""
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
idxParts.push(
|
|
525
|
+
"# ZeroMem 本地记忆只读索引",
|
|
526
|
+
"",
|
|
527
|
+
`- **导出时间**:\`${exportedAt}\``,
|
|
528
|
+
`- **基准日期 (\`as_of\`)**:\`${asOfDate}\``,
|
|
529
|
+
`- **命名空间数**:\`${namespaces.length}\` · **事实总数**:\`${counts.facts_exported}\` · **关联文档**:\`${counts.documents_referenced}\``,
|
|
530
|
+
""
|
|
531
|
+
);
|
|
532
|
+
if (indexRows.length) {
|
|
533
|
+
idxParts.push(
|
|
534
|
+
"| 空间 | 事实数 | 文档数 | 已替代 | 已过期 |",
|
|
535
|
+
"| :--- | :---: | :---: | :---: | :---: |",
|
|
536
|
+
...indexRows,
|
|
537
|
+
""
|
|
538
|
+
);
|
|
539
|
+
} else {
|
|
540
|
+
idxParts.push("_当前筛选条件下无匹配记忆。_\n");
|
|
541
|
+
}
|
|
542
|
+
if (evictedRows.length) idxParts.push(renderEvictedSection(evictedRows));
|
|
543
|
+
|
|
544
|
+
const idxFile = path.join(outRoot, "INDEX.md");
|
|
545
|
+
atomicWriteText(idxFile, `${idxParts.join("\n").trimEnd()}\n`);
|
|
546
|
+
writtenFiles.unshift(idxFile);
|
|
547
|
+
|
|
548
|
+
return {
|
|
549
|
+
ok: true,
|
|
550
|
+
mode: "directory",
|
|
551
|
+
format: "markdown",
|
|
552
|
+
read_only: true,
|
|
553
|
+
db_path: dbFile,
|
|
554
|
+
output_dir: outRoot,
|
|
555
|
+
exported_at: exportedAt,
|
|
556
|
+
as_of: asOfDate,
|
|
557
|
+
occurred_from: fromDate,
|
|
558
|
+
occurred_to: toDate,
|
|
559
|
+
namespaces,
|
|
560
|
+
...counts,
|
|
561
|
+
files_written: writtenFiles,
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const parts = [];
|
|
566
|
+
if (frontmatter) {
|
|
567
|
+
parts.push(
|
|
568
|
+
"---",
|
|
569
|
+
`generator: ${yamlScalar("ZeroMem")}`,
|
|
570
|
+
"read_only: true",
|
|
571
|
+
`exported_at: ${yamlScalar(exportedAt)}`,
|
|
572
|
+
`as_of: ${yamlScalar(asOfDate)}`,
|
|
573
|
+
`namespaces: ${namespaces.length}`,
|
|
574
|
+
`facts: ${counts.facts_exported}`,
|
|
575
|
+
`documents: ${counts.documents_referenced}`,
|
|
576
|
+
`superseded_facts: ${counts.superseded_facts}`,
|
|
577
|
+
`expired_facts: ${counts.expired_facts}`,
|
|
578
|
+
"---",
|
|
579
|
+
""
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
parts.push("# ZeroMem 本地记忆只读导出", "");
|
|
583
|
+
const rangeNote =
|
|
584
|
+
fromDate || toDate ? ` · 事件时间过滤 \`${fromDate || "*"} ~ ${toDate || "*"}\`` : "";
|
|
585
|
+
parts.push(
|
|
586
|
+
`> 导出时间 \`${exportedAt}\` · 空间 \`${namespaces.length}\` 个 · 事实 \`${counts.facts_exported}\` 条 · 文档 \`${counts.documents_referenced}\` 篇${rangeNote}`,
|
|
587
|
+
""
|
|
588
|
+
);
|
|
589
|
+
if (!namespaces.length) {
|
|
590
|
+
parts.push("_当前筛选条件下无匹配记忆。_", "");
|
|
591
|
+
}
|
|
592
|
+
for (const ns of namespaces) {
|
|
593
|
+
const facts = byNs.get(ns);
|
|
594
|
+
parts.push(`## 空间:\`${ns}\`(${facts.length} 条)`, "");
|
|
595
|
+
for (const f of facts) parts.push(renderFactMarkdown(f));
|
|
596
|
+
}
|
|
597
|
+
if (evictedRows.length) parts.push(renderEvictedSection(evictedRows));
|
|
598
|
+
|
|
599
|
+
const mdText = `${parts.join("\n").trimEnd()}\n`;
|
|
600
|
+
const writtenFiles = [];
|
|
601
|
+
let outFileStr = null;
|
|
602
|
+
if (outputPath !== null && outputPath !== undefined) {
|
|
603
|
+
const outFile = expandHome(outputPath);
|
|
604
|
+
atomicWriteText(outFile, mdText);
|
|
605
|
+
outFileStr = outFile;
|
|
606
|
+
writtenFiles.push(outFileStr);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const res = {
|
|
610
|
+
ok: true,
|
|
611
|
+
mode: outputPath !== null && outputPath !== undefined ? "file" : "stdout",
|
|
612
|
+
format: "markdown",
|
|
613
|
+
read_only: true,
|
|
614
|
+
db_path: dbFile,
|
|
615
|
+
output_path: outFileStr,
|
|
616
|
+
exported_at: exportedAt,
|
|
617
|
+
as_of: asOfDate,
|
|
618
|
+
occurred_from: fromDate,
|
|
619
|
+
occurred_to: toDate,
|
|
620
|
+
namespaces,
|
|
621
|
+
...counts,
|
|
622
|
+
files_written: writtenFiles,
|
|
623
|
+
};
|
|
624
|
+
if (outputPath === null || outputPath === undefined) {
|
|
625
|
+
res.markdown = mdText;
|
|
626
|
+
}
|
|
627
|
+
return res;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function sameFilePath(a, b) {
|
|
631
|
+
const pa = path.resolve(a);
|
|
632
|
+
const pb = path.resolve(b);
|
|
633
|
+
return process.platform === "win32" ? pa.toLowerCase() === pb.toLowerCase() : pa === pb;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function formatBackupStamp(dt) {
|
|
637
|
+
const p2 = (n) => String(n).padStart(2, "0");
|
|
638
|
+
return (
|
|
639
|
+
`${dt.getUTCFullYear()}${p2(dt.getUTCMonth() + 1)}${p2(dt.getUTCDate())}-` +
|
|
640
|
+
`${p2(dt.getUTCHours())}${p2(dt.getUTCMinutes())}${p2(dt.getUTCSeconds())}`
|
|
641
|
+
);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Create a clean, self-contained SQLite Online Backup snapshot (journal_mode=DELETE, zero WAL sidecars).
|
|
646
|
+
*/
|
|
647
|
+
export async function backupDatabase({
|
|
648
|
+
dbPath,
|
|
649
|
+
outputPath = null,
|
|
650
|
+
overwrite = false,
|
|
651
|
+
verify = true,
|
|
652
|
+
writeSha256 = false,
|
|
653
|
+
pages = 256,
|
|
654
|
+
} = {}) {
|
|
655
|
+
const started = performance.now();
|
|
656
|
+
const dbFile = expandHome(dbPath);
|
|
657
|
+
if (!dbFile || !fs.existsSync(dbFile) || !fs.statSync(dbFile).isFile()) {
|
|
658
|
+
throw new Error(`db-not-found: ${dbFile || dbPath}`);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const nowDt = new Date();
|
|
662
|
+
const stamp = formatBackupStamp(nowDt);
|
|
663
|
+
const defaultName = `zeromem-backup-${stamp}.db`;
|
|
664
|
+
|
|
665
|
+
let dest;
|
|
666
|
+
if (outputPath === null || outputPath === undefined || !String(outputPath).trim()) {
|
|
667
|
+
dest = path.resolve(path.dirname(dbFile), "backups", defaultName);
|
|
668
|
+
} else {
|
|
669
|
+
const rawOut = String(outputPath).trim();
|
|
670
|
+
const cand = expandHome(rawOut);
|
|
671
|
+
const isDir = (fs.existsSync(cand) && fs.statSync(cand).isDirectory()) || rawOut.endsWith("/") || rawOut.endsWith("\\");
|
|
672
|
+
dest = isDir ? path.resolve(cand, defaultName) : path.resolve(cand);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
if (sameFilePath(dest, dbFile)) {
|
|
676
|
+
throw new Error("backup-target-equals-source: destination must be different from active database");
|
|
677
|
+
}
|
|
678
|
+
if (fs.existsSync(dest) && !overwrite) {
|
|
679
|
+
throw new Error(`backup-target-exists: ${dest} (pass overwrite=true to replace)`);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
683
|
+
const tmpPath = path.join(
|
|
684
|
+
path.dirname(dest),
|
|
685
|
+
`.${path.basename(dest)}.tmp.${process.pid}.${Date.now()}`
|
|
686
|
+
);
|
|
687
|
+
|
|
688
|
+
let srcDb = null;
|
|
689
|
+
let dstDb = null;
|
|
690
|
+
let finalJmode = "delete";
|
|
691
|
+
let integrity = "skipped";
|
|
692
|
+
let appId = 0;
|
|
693
|
+
let schemaVer = null;
|
|
694
|
+
let counts = {
|
|
695
|
+
documents: 0,
|
|
696
|
+
segments: 0,
|
|
697
|
+
facts: 0,
|
|
698
|
+
evicted_records: 0,
|
|
699
|
+
supersessions: 0,
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
try {
|
|
703
|
+
// Open source read-only via query_only pragma (safe over active WAL databases)
|
|
704
|
+
srcDb = new DatabaseSync(dbFile, { timeout: 20_000 });
|
|
705
|
+
srcDb.exec("PRAGMA query_only = ON;");
|
|
706
|
+
srcDb.exec("PRAGMA busy_timeout = 20000;");
|
|
707
|
+
|
|
708
|
+
await sqliteOnlineBackup(srcDb, tmpPath, {
|
|
709
|
+
rate: Math.max(1, Math.trunc(Number(pages) || 256)),
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
srcDb.close();
|
|
713
|
+
srcDb = null;
|
|
714
|
+
|
|
715
|
+
// Flatten WAL into a clean single file safe for cloud drives (OneDrive/BaiduSyncdisk/iCloud)
|
|
716
|
+
dstDb = new DatabaseSync(tmpPath, { timeout: 20_000 });
|
|
717
|
+
dstDb.exec("PRAGMA busy_timeout = 20000;");
|
|
718
|
+
const jmodeRow = dstDb.prepare("PRAGMA journal_mode = DELETE").get();
|
|
719
|
+
finalJmode = jmodeRow ? String(Object.values(jmodeRow)[0]).toLowerCase() : "delete";
|
|
720
|
+
|
|
721
|
+
if (verify) {
|
|
722
|
+
const icRows = dstDb.prepare("PRAGMA integrity_check").all();
|
|
723
|
+
const icVals = icRows.map((r) => String(Object.values(r)[0]));
|
|
724
|
+
if (icVals.length !== 1 || icVals[0].toLowerCase() !== "ok") {
|
|
725
|
+
throw new Error(`backup-integrity-failed: ${JSON.stringify(icVals.slice(0, 5))}`);
|
|
726
|
+
}
|
|
727
|
+
integrity = "ok";
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
const appRow = dstDb.prepare("PRAGMA application_id").get();
|
|
731
|
+
appId = appRow ? Number(Object.values(appRow)[0]) : 0;
|
|
732
|
+
if (hasTable(dstDb, "meta")) {
|
|
733
|
+
const srow = dstDb.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
734
|
+
schemaVer = srow ? String(srow.value) : null;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
counts = {
|
|
738
|
+
documents: hasTable(dstDb, "documents")
|
|
739
|
+
? Number(dstDb.prepare("SELECT COUNT(*) AS c FROM documents").get().c)
|
|
740
|
+
: 0,
|
|
741
|
+
segments: hasTable(dstDb, "segments")
|
|
742
|
+
? Number(dstDb.prepare("SELECT COUNT(*) AS c FROM segments").get().c)
|
|
743
|
+
: 0,
|
|
744
|
+
facts: hasTable(dstDb, "facts")
|
|
745
|
+
? Number(dstDb.prepare("SELECT COUNT(*) AS c FROM facts").get().c)
|
|
746
|
+
: 0,
|
|
747
|
+
evicted_records: hasTable(dstDb, "evicted_records")
|
|
748
|
+
? Number(dstDb.prepare("SELECT COUNT(*) AS c FROM evicted_records").get().c)
|
|
749
|
+
: 0,
|
|
750
|
+
supersessions: hasTable(dstDb, "fact_supersessions")
|
|
751
|
+
? Number(dstDb.prepare("SELECT COUNT(*) AS c FROM fact_supersessions").get().c)
|
|
752
|
+
: 0,
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
dstDb.close();
|
|
756
|
+
dstDb = null;
|
|
757
|
+
|
|
758
|
+
for (const suf of ["-wal", "-shm"]) {
|
|
759
|
+
const sidecar = `${tmpPath}${suf}`;
|
|
760
|
+
if (fs.existsSync(sidecar)) fs.unlinkSync(sidecar);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
fs.renameSync(tmpPath, dest);
|
|
764
|
+
} catch (err) {
|
|
765
|
+
if (srcDb) {
|
|
766
|
+
try {
|
|
767
|
+
srcDb.close();
|
|
768
|
+
} catch {
|
|
769
|
+
// ignore
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
if (dstDb) {
|
|
773
|
+
try {
|
|
774
|
+
dstDb.close();
|
|
775
|
+
} catch {
|
|
776
|
+
// ignore
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
for (const p of [tmpPath, `${tmpPath}-wal`, `${tmpPath}-shm`]) {
|
|
780
|
+
try {
|
|
781
|
+
if (fs.existsSync(p)) fs.unlinkSync(p);
|
|
782
|
+
} catch {
|
|
783
|
+
// ignore
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
throw err;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const walSidecars = ["-wal", "-shm"].some((suf) => fs.existsSync(`${dest}${suf}`));
|
|
790
|
+
const digest = sha256File(dest);
|
|
791
|
+
const sizeBytes = fs.statSync(dest).size;
|
|
792
|
+
|
|
793
|
+
let shaFilePath = null;
|
|
794
|
+
if (writeSha256) {
|
|
795
|
+
const shaTarget = `${dest}.sha256`;
|
|
796
|
+
atomicWriteText(shaTarget, `${digest} ${path.basename(dest)}\n`);
|
|
797
|
+
shaFilePath = shaTarget;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
const elapsedMs = Number((performance.now() - started).toFixed(2));
|
|
801
|
+
return {
|
|
802
|
+
ok: true,
|
|
803
|
+
method: "sqlite_online_backup",
|
|
804
|
+
source_db: dbFile,
|
|
805
|
+
backup_path: dest,
|
|
806
|
+
created_at: nowDt.toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
807
|
+
journal_mode: finalJmode,
|
|
808
|
+
wal_sidecars_present: walSidecars,
|
|
809
|
+
integrity_check: integrity,
|
|
810
|
+
application_id: appId,
|
|
811
|
+
application_id_valid: appId === APP_FORMAT_ID,
|
|
812
|
+
schema_version: schemaVer,
|
|
813
|
+
size_bytes: sizeBytes,
|
|
814
|
+
sha256: digest,
|
|
815
|
+
sha256_file: shaFilePath,
|
|
816
|
+
counts,
|
|
817
|
+
elapsed_ms: elapsedMs,
|
|
818
|
+
};
|
|
819
|
+
}
|