advisers 0.2.2 → 0.3.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 (70) hide show
  1. package/LICENSE +0 -0
  2. package/NOTICE +0 -0
  3. package/README-zh.md +11 -7
  4. package/README.md +16 -8
  5. package/THIRD-PARTY-NOTICES.md +1 -1
  6. package/bin/advisers.js +6347 -542
  7. package/index.js +1 -1
  8. package/lib/agent.js +529 -80
  9. package/lib/attachments.js +0 -0
  10. package/lib/audit-anchor.js +683 -0
  11. package/lib/backup.js +1345 -0
  12. package/lib/capture.js +0 -0
  13. package/lib/context-window.js +0 -0
  14. package/lib/digest.js +0 -0
  15. package/lib/doc-review.js +0 -0
  16. package/lib/egress.js +0 -0
  17. package/lib/error-codes.js +1373 -0
  18. package/lib/evidence.js +352 -43
  19. package/lib/fs-safe.js +347 -0
  20. package/lib/ical.js +0 -0
  21. package/lib/imap.js +6 -2
  22. package/lib/importers.js +0 -0
  23. package/lib/learning.js +0 -0
  24. package/lib/ledger-read.js +608 -0
  25. package/lib/mcp-server.js +331 -50
  26. package/lib/model.js +73 -1
  27. package/lib/node-warning-filter.js +15 -0
  28. package/lib/notify.js +13 -3
  29. package/lib/nudge.js +0 -0
  30. package/lib/ocr.js +29 -9
  31. package/lib/pdf.js +0 -0
  32. package/lib/pet-brief-store.js +0 -0
  33. package/lib/pet-brief.js +126 -64
  34. package/lib/receipt-verify.js +213 -15
  35. package/lib/relative-date.js +0 -0
  36. package/lib/remind.js +91 -36
  37. package/lib/research.js +0 -0
  38. package/lib/review.js +0 -0
  39. package/lib/routine.js +0 -0
  40. package/lib/safety/classifier.js +55 -2
  41. package/lib/safety/explain.js +0 -0
  42. package/lib/safety/index.js +0 -0
  43. package/lib/safety/redact.js +0 -0
  44. package/lib/safety/rules.js +28 -0
  45. package/lib/scheduler.js +0 -0
  46. package/lib/source.js +0 -0
  47. package/lib/sqlite.js +2302 -55
  48. package/lib/sync.js +398 -71
  49. package/lib/text-safe.js +229 -0
  50. package/lib/timestamp.js +29 -9
  51. package/lib/tos/index.js +1 -1
  52. package/lib/tos/manifest.json +6 -6
  53. package/lib/tos/privacy.zh-CN.md +12 -9
  54. package/lib/tos/safety.zh-CN.md +4 -3
  55. package/lib/tos/summary.zh-CN.md +3 -3
  56. package/lib/tos/terms.zh-CN.md +8 -6
  57. package/lib/tui/color.js +164 -0
  58. package/lib/tui/index.js +33 -0
  59. package/lib/tui/json.js +124 -0
  60. package/lib/tui/labels.js +50 -0
  61. package/lib/tui/policy.js +108 -0
  62. package/lib/tui/render.js +371 -0
  63. package/lib/tui/sanitize.js +142 -0
  64. package/lib/tui/text-file.js +116 -0
  65. package/lib/tui/width.js +577 -0
  66. package/lib/ui.js +0 -0
  67. package/lib/undo.js +0 -0
  68. package/lib/untrusted.js +186 -0
  69. package/lib/vault.js +0 -0
  70. package/package.json +6 -5
package/lib/backup.js ADDED
@@ -0,0 +1,1345 @@
1
+ /**
2
+ * Backup rotation + verified restore (Advisers 0.3.0 operations library).
3
+ *
4
+ * This module is the recovery half of 0.3.0 "Trustworthy Delivery": the CLI
5
+ * used to have a one-shot `backup <path>` copy with no restore, no rotation and
6
+ * no sidecars (04-0.3-research §2.2/§4.3, 05-0.3.0-planning P0-D2). What it adds:
7
+ *
8
+ * - createBackup(): checkpoint WAL -> copy to a same-directory temp file ->
9
+ * fsync -> verify the COPY itself (quick_check, schema, audit head, sampled
10
+ * row counts vs the live DB) -> atomic rename. A backup that cannot be
11
+ * verified is removed and the command fails closed; an existing target is
12
+ * never clobbered unless explicit overwrite:true.
13
+ * - inspectBackup(): read-only verification of a .db file (quick_check,
14
+ * schema compatibility, audit chain/head, sampled row counts, adjacent WAL).
15
+ * - GFS / keep-N rotation with dry-run by default. Rotation only ever
16
+ * touches `<home>/backups/state-*.db` + their sidecars, always keeps the
17
+ * newest backup and the newest readable backup, and refuses paths that
18
+ * resolve outside the managed directory (never deletes a bad backup).
19
+ * - restore: planRestore() validates a backup + anchor first; restoreBackup()
20
+ * checkpoints/closes the live store, writes a pre-restore backup, installs
21
+ * the verified backup via atomic rename, re-verifies, and rolls back to the
22
+ * pre-restore copy if the installed file does not verify. The original
23
+ * database is untouched on every failure before the rename.
24
+ * - sidecars: `<backup>.sha256` (coreutils format) and
25
+ * `<backup>.anchor.json` (the audit tail anchor, §4.7).
26
+ * - audit anchor interop: a backup older than the audit anchor requires an
27
+ * explicit allowAnchorBehind (`restore --allow-anchor-behind`), while a
28
+ * live database whose count is below the anchor is a tail truncation.
29
+ *
30
+ * Failure matrix covered by test/backup.test.js + test/restore-drill.test.js:
31
+ * missing/empty/corrupt/WAL-carrying/newer-schema backup, busy checkpoint,
32
+ * pre-restore copy failure, copy verification failure, rename failure (original
33
+ * intact), post-install verification failure (rollback), anchor-behind gate,
34
+ * rotation dry-run/containment/unreadable protection.
35
+ *
36
+ * Library-only: no bin/ wiring (Wave 2), no network, no new dependency. Uses
37
+ * only node:fs/node:crypto/node:sqlite (through lib/sqlite.js) and lib/fs-safe.
38
+ */
39
+ import { createHash } from 'node:crypto'
40
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
41
+ import * as nodeFs from 'node:fs'
42
+ import { basename, dirname, join, resolve } from 'node:path'
43
+ import {
44
+ atomicWriteFileSync,
45
+ copyFileWithRetrySync,
46
+ fsyncDirSync,
47
+ fsyncFileSync,
48
+ mkdirWithRetrySync,
49
+ renameWithRetrySync,
50
+ rmWithRetrySync,
51
+ tempPathForSync,
52
+ } from './fs-safe.js'
53
+ import { SCHEMA_VERSION, SqliteStore } from './sqlite.js'
54
+ import {
55
+ readAuditAnchor,
56
+ readAuditHead,
57
+ resolveAuditAnchorKey,
58
+ verifyAuditAnchor,
59
+ verifyRestoreAnchor,
60
+ writeAuditAnchor,
61
+ } from './audit-anchor.js'
62
+
63
+ export const BACKUP_DIR_NAME = 'backups'
64
+ export const BACKUP_SHA256_SUFFIX = '.sha256'
65
+ export const BACKUP_ANCHOR_SUFFIX = '.anchor.json'
66
+ /** Managed backup file names: state-<UTC YYYYMMDDTHHMMSS[mmm]Z>[-tag].db. */
67
+ export const BACKUP_FILE_RE = /^state-(\d{8}T\d{6}(?:\d{3})?Z)(?:-([a-z0-9][a-z0-9-]{0,31}))?\.db$/
68
+ /** GFS retention defaults from 04-0.3-research §4.3 (daily=7 weekly=4 monthly=3). */
69
+ export const DEFAULT_KEEP_POLICY = Object.freeze({ daily: 7, weekly: 4, monthly: 3 })
70
+ /** Always protect at least this many newest backups from rotation. */
71
+ const PROTECT_NEWEST = 1
72
+ const MAX_TAG_CHARS = 32
73
+ const HASH_CHUNK_BYTES = 1024 * 1024
74
+ /** Tables whose row counts are compared after a backup copy (same set as sqlite.js). */
75
+ const BACKUP_SAMPLE_TABLES = ['matters', 'facts', 'commitments', 'preferences', 'audit']
76
+
77
+ function failure(code, message, extra = {}) {
78
+ return { ok: false, code, errors: message ? [message] : [], warnings: [], ...extra }
79
+ }
80
+
81
+ function isMissingError(error) {
82
+ return error?.code === 'ENOENT'
83
+ }
84
+
85
+ function fsExists(fs, file) {
86
+ const exists = typeof fs?.existsSync === 'function' ? fs.existsSync : existsSync
87
+ try { return Boolean(exists(file)) } catch { return false }
88
+ }
89
+
90
+ function fsStat(fs, file) {
91
+ const stat = typeof fs?.statSync === 'function' ? fs.statSync : statSync
92
+ return stat(file)
93
+ }
94
+
95
+ function fsReadDir(fs, dir) {
96
+ const readdir = typeof fs?.readdirSync === 'function' ? fs.readdirSync : readdirSync
97
+ return readdir(dir, { withFileTypes: true })
98
+ }
99
+
100
+ function fsRm(fs, file) {
101
+ try { rmWithRetrySync(file, { fs: fs ?? nodeFs }) } catch {}
102
+ }
103
+
104
+ /** UTC compact stamp used in backup file names: 20261119T154512345Z. */
105
+ export function backupTimestamp(at = new Date(), { ms = true } = {}) {
106
+ const date = at instanceof Date ? at : new Date(at)
107
+ if (Number.isNaN(date.getTime())) throw new TypeError('backupTimestamp requires a valid Date')
108
+ const iso = date.toISOString()
109
+ if (ms) return iso.replace(/[-:]/g, '').replace('.', '')
110
+ return iso.slice(0, 19).replace(/[-:]/g, '') + 'Z'
111
+ }
112
+
113
+ /** Parse the UTC compact stamp back to a Date (invalid input -> null). */
114
+ export function parseBackupTimestamp(value) {
115
+ if (typeof value !== 'string' || !/^\d{8}T\d{6}(?:\d{3})?Z$/.test(value)) return null
116
+ const year = Number(value.slice(0, 4))
117
+ const month = Number(value.slice(4, 6))
118
+ const day = Number(value.slice(6, 8))
119
+ const hour = Number(value.slice(9, 11))
120
+ const minute = Number(value.slice(11, 13))
121
+ const second = Number(value.slice(13, 15))
122
+ const millis = value.length === 18 ? Number(value.slice(15, 18)) : 0
123
+ const date = new Date(Date.UTC(year, month - 1, day, hour, minute, second, millis))
124
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null
125
+ if (date.getUTCHours() !== hour || date.getUTCMinutes() !== minute || date.getUTCSeconds() !== second) return null
126
+ if (date.getUTCMilliseconds() !== millis) return null
127
+ return date
128
+ }
129
+
130
+ /** Validate + normalize a backup tag; returns {ok, tag}. */
131
+ export function normalizeBackupTag(tag) {
132
+ if (tag === undefined || tag === null || tag === '') return { ok: true, tag: null }
133
+ const normalized = String(tag).trim().toLowerCase()
134
+ if (normalized.length === 0) return { ok: true, tag: null }
135
+ if (normalized.length > MAX_TAG_CHARS || !/^[a-z0-9][a-z0-9-]*$/.test(normalized)) {
136
+ return { ok: false, tag: normalized, error: 'backup tag must be 1-' + MAX_TAG_CHARS + ' lowercase letters/digits/hyphens and start with a letter/digit' }
137
+ }
138
+ return { ok: true, tag: normalized }
139
+ }
140
+
141
+ /** Managed backup file name for a timestamp + optional tag. */
142
+ export function backupFileName({ at = new Date(), tag = null, ms = true } = {}) {
143
+ const checked = normalizeBackupTag(tag)
144
+ if (!checked.ok) throw new TypeError(checked.error)
145
+ const stamp = backupTimestamp(at, { ms })
146
+ return 'state-' + stamp + (checked.tag ? '-' + checked.tag : '') + '.db'
147
+ }
148
+
149
+ /** <home>/backups (the only directory rotation is allowed to delete from). */
150
+ export function backupDir({ home } = {}) {
151
+ if (!home) throw new TypeError('backupDir requires {home}')
152
+ return join(home, BACKUP_DIR_NAME)
153
+ }
154
+
155
+ export function backupPathFor({ home, at = new Date(), tag = null, ms = true } = {}) {
156
+ return join(backupDir({ home }), backupFileName({ at, tag, ms }))
157
+ }
158
+
159
+ export function backupSha256Path(backupPath) {
160
+ return String(backupPath) + BACKUP_SHA256_SUFFIX
161
+ }
162
+
163
+ export function backupAnchorPath(backupPath) {
164
+ return String(backupPath) + BACKUP_ANCHOR_SUFFIX
165
+ }
166
+
167
+ /** Parse a managed backup name into {name, atIso, atMs, tag} or null. */
168
+ export function parseBackupFileName(name) {
169
+ if (typeof name !== 'string') return null
170
+ const match = BACKUP_FILE_RE.exec(name)
171
+ if (!match) return null
172
+ const at = parseBackupTimestamp(match[1])
173
+ if (!at) return null
174
+ return { name, timestamp: match[1], atIso: at.toISOString(), atMs: at.getTime(), tag: match[2] ?? null }
175
+ }
176
+
177
+ /** Streaming synchronous sha256 of a file (1 MiB chunks; bounded memory). */
178
+ export function sha256FileSync(file, { fs = nodeFs, chunkSize = HASH_CHUNK_BYTES } = {}) {
179
+ const open = fs.openSync
180
+ const read = fs.readSync
181
+ const close = fs.closeSync
182
+ const hash = createHash('sha256')
183
+ const buffer = Buffer.allocUnsafe(Math.max(4096, Math.min(chunkSize, HASH_CHUNK_BYTES)))
184
+ let bytes = 0
185
+ const fd = open(file, 'r')
186
+ try {
187
+ for (;;) {
188
+ const count = read(fd, buffer, 0, buffer.length, null)
189
+ if (!count) break
190
+ hash.update(buffer.subarray(0, count))
191
+ bytes += count
192
+ }
193
+ } finally {
194
+ try { close(fd) } catch {}
195
+ }
196
+ return { sha256: hash.digest('hex'), bytes }
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // Listing + GFS / keep-N rotation
201
+ // ---------------------------------------------------------------------------
202
+
203
+ /**
204
+ * List managed backups in <home>/backups (or an explicit dir), newest first.
205
+ * Symlinks and non-matching names are ignored; a missing directory is an empty
206
+ * list, not an error. `sidecars` says which optional files exist.
207
+ */
208
+ export function listBackups({ home, dir, fs = nodeFs } = {}) {
209
+ const directory = resolve(String(dir ?? backupDir({ home })))
210
+ const result = { ok: true, dir: directory, entries: [], errors: [], warnings: [] }
211
+ let dirents
212
+ try {
213
+ dirents = fsReadDir(fs, directory)
214
+ } catch (error) {
215
+ if (isMissingError(error)) return result
216
+ result.ok = false
217
+ result.errors.push('cannot list backup directory ' + directory + ': ' + String(error?.code ?? error?.message ?? error))
218
+ return result
219
+ }
220
+ for (const dirent of dirents) {
221
+ if (!dirent.isFile() || dirent.isSymbolicLink()) continue
222
+ const parsed = parseBackupFileName(dirent.name)
223
+ if (!parsed) continue
224
+ const path = join(directory, dirent.name)
225
+ let info
226
+ try { info = fsStat(fs, path) } catch { continue }
227
+ if (!info.isFile()) continue
228
+ result.entries.push({
229
+ path,
230
+ name: dirent.name,
231
+ tag: parsed.tag,
232
+ createdAt: parsed.atIso,
233
+ atMs: parsed.atMs,
234
+ size: info.size,
235
+ mtimeMs: info.mtimeMs,
236
+ sidecars: {
237
+ sha256: fsExists(fs, backupSha256Path(path)),
238
+ anchor: fsExists(fs, backupAnchorPath(path)),
239
+ },
240
+ })
241
+ }
242
+ result.entries.sort((left, right) => (right.atMs - left.atMs) || (left.name < right.name ? 1 : -1))
243
+ return result
244
+ }
245
+
246
+ /** Merge a keep policy with defaults. Number N => keep the newest N; object => GFS. */
247
+ export function normalizeKeepPolicy(keep) {
248
+ if (keep === undefined || keep === null) {
249
+ return { ok: true, policy: { mode: 'gfs', ...DEFAULT_KEEP_POLICY } }
250
+ }
251
+ if (typeof keep === 'number') {
252
+ if (!Number.isFinite(keep) || keep < 1) return { ok: false, error: 'keep must be a positive number of backups' }
253
+ return { ok: true, policy: { mode: 'count', count: Math.floor(keep) } }
254
+ }
255
+ if (typeof keep === 'string') {
256
+ const parsed = {}
257
+ for (const part of keep.split(',')) {
258
+ const [rawKey, rawValue] = part.split('=')
259
+ const key = String(rawKey ?? '').trim().toLowerCase()
260
+ const value = Number(String(rawValue ?? '').trim())
261
+ if (!['daily', 'weekly', 'monthly'].includes(key) || !Number.isInteger(value) || value < 0) {
262
+ return { ok: false, error: 'invalid keep policy "' + keep + '": expected "daily=7,weekly=4,monthly=3" or a number' }
263
+ }
264
+ parsed[key] = value
265
+ }
266
+ if (Object.keys(parsed).length === 0) return { ok: false, error: 'invalid empty keep policy' }
267
+ return { ok: true, policy: { mode: 'gfs', ...DEFAULT_KEEP_POLICY, ...parsed } }
268
+ }
269
+ if (typeof keep === 'object') {
270
+ if ('count' in keep) {
271
+ const count = Number(keep.count)
272
+ if (!Number.isInteger(count) || count < 1) return { ok: false, error: 'keep.count must be a positive integer' }
273
+ return { ok: true, policy: { mode: 'count', count } }
274
+ }
275
+ const policy = { mode: 'gfs', ...DEFAULT_KEEP_POLICY }
276
+ for (const key of ['daily', 'weekly', 'monthly']) {
277
+ if (!(key in keep)) continue
278
+ const value = Number(keep[key])
279
+ if (!Number.isInteger(value) || value < 0) return { ok: false, error: 'keep.' + key + ' must be a non-negative integer' }
280
+ policy[key] = value
281
+ }
282
+ return { ok: true, policy }
283
+ }
284
+ return { ok: false, error: 'keep must be a number, an object or a "daily=..,weekly=.." string' }
285
+ }
286
+
287
+ /** ISO-8601 week key (UTC) used by the GFS weekly bucket. */
288
+ export function isoWeekKey(ms) {
289
+ const date = new Date(ms)
290
+ const target = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()))
291
+ const dayNumber = (target.getUTCDay() + 6) % 7
292
+ target.setUTCDate(target.getUTCDate() - dayNumber + 3)
293
+ const firstThursday = new Date(Date.UTC(target.getUTCFullYear(), 0, 4))
294
+ const firstDayNumber = (firstThursday.getUTCDay() + 6) % 7
295
+ firstThursday.setUTCDate(firstThursday.getUTCDate() - firstDayNumber + 3)
296
+ const week = 1 + Math.round((target.getTime() - firstThursday.getTime()) / (7 * 86400000))
297
+ return target.getUTCFullYear() + '-W' + String(week).padStart(2, '0')
298
+ }
299
+
300
+ /**
301
+ * Pure rotation planner. Never deletes anything; returns the keep/victim split.
302
+ *
303
+ * Invariants (04-0.3-research §4.3): the newest backup is ALWAYS kept, the
304
+ * newest entry explicitly marked `readable:true` (last quick_check that passed)
305
+ * is ALWAYS kept, and a count policy always keeps `count` entries. Deletion
306
+ * safety (path containment, sidecars) lives in applyBackupRotation.
307
+ */
308
+ export function planBackupRotation({ entries, keep, now = Date.now() } = {}) {
309
+ const normalized = normalizeKeepPolicy(keep)
310
+ if (!normalized.ok) return failure('E_BACKUP_KEEP_INVALID', normalized.error)
311
+ const policy = normalized.policy
312
+ const sorted = [...(Array.isArray(entries) ? entries : [])]
313
+ .filter((entry) => entry && typeof entry.path === 'string')
314
+ .sort((left, right) => (Number(right.atMs ?? right.mtimeMs ?? 0) - Number(left.atMs ?? left.mtimeMs ?? 0)))
315
+ const result = { ok: true, policy, kept: [], protected: [], victims: [], wouldDelete: [], warnings: [] }
316
+ if (sorted.length === 0) return result
317
+ const kept = new Set()
318
+ const protect = (entry) => {
319
+ if (!entry || kept.has(entry)) return
320
+ kept.add(entry)
321
+ result.protected.push(entry.path)
322
+ }
323
+ if (policy.mode === 'count') {
324
+ for (const entry of sorted.slice(0, policy.count)) protect(entry)
325
+ } else {
326
+ const seenDays = new Set()
327
+ const seenWeeks = new Set()
328
+ const seenMonths = new Set()
329
+ let daily = 0
330
+ let weekly = 0
331
+ let monthly = 0
332
+ for (const entry of sorted) {
333
+ if (kept.has(entry)) continue
334
+ const atMs = Number(entry.atMs ?? entry.mtimeMs ?? now)
335
+ const dayKey = new Date(atMs).toISOString().slice(0, 10)
336
+ if (daily < policy.daily && !seenDays.has(dayKey)) {
337
+ seenDays.add(dayKey)
338
+ daily++
339
+ protect(entry)
340
+ continue
341
+ }
342
+ const weekKey = isoWeekKey(atMs)
343
+ if (weekly < policy.weekly && !seenWeeks.has(weekKey)) {
344
+ seenWeeks.add(weekKey)
345
+ weekly++
346
+ protect(entry)
347
+ continue
348
+ }
349
+ const monthKey = new Date(atMs).toISOString().slice(0, 7)
350
+ if (monthly < policy.monthly && !seenMonths.has(monthKey)) {
351
+ seenMonths.add(monthKey)
352
+ monthly++
353
+ protect(entry)
354
+ }
355
+ }
356
+ }
357
+ // Safety net on top of the policy: the newest backup and the newest backup
358
+ // whose quick_check passed are always kept, even if the policy buckets would
359
+ // have dropped them (a readable backup is the actual rollback path).
360
+ for (let index = 0; index < Math.min(PROTECT_NEWEST, sorted.length); index++) protect(sorted[index])
361
+ protect(sorted.find((entry) => entry.readable === true))
362
+ result.kept = sorted.filter((entry) => kept.has(entry))
363
+ result.victims = sorted.filter((entry) => !kept.has(entry))
364
+ result.wouldDelete = result.victims.map((entry) => entry.path)
365
+ return result
366
+ }
367
+
368
+ function assertManagedPath(directory, file) {
369
+ const resolvedDir = resolve(directory)
370
+ const resolved = resolve(String(file))
371
+ if (dirname(resolved) !== resolvedDir) {
372
+ return { ok: false, code: 'E_BACKUP_PATH_UNSAFE', error: 'refusing to delete ' + resolved + ': it is not directly inside the managed backup directory ' + resolvedDir }
373
+ }
374
+ if (!BACKUP_FILE_RE.test(basename(resolved))) {
375
+ return { ok: false, code: 'E_BACKUP_PATH_UNSAFE', error: 'refusing to delete ' + resolved + ': not a managed backup file name' }
376
+ }
377
+ return { ok: true, path: resolved }
378
+ }
379
+
380
+ /** Cheap read-only readability probe: open + PRAGMA quick_check, no chain pass. */
381
+ export function probeBackupReadable(backupPath, { fs = nodeFs } = {}) {
382
+ let store = null
383
+ const before = {
384
+ wal: fsExists(fs, String(backupPath) + '-wal'),
385
+ shm: fsExists(fs, String(backupPath) + '-shm'),
386
+ }
387
+ try {
388
+ store = new SqliteStore(String(backupPath), { readOnly: true })
389
+ const verdict = String(store.db.prepare('PRAGMA quick_check').get()?.quick_check ?? 'unknown')
390
+ return { ok: verdict === 'ok', quickCheck: verdict }
391
+ } catch (error) {
392
+ return { ok: false, quickCheck: null, code: error?.code === 'E_DB_CORRUPT' ? 'E_BACKUP_CORRUPT' : 'E_BACKUP_OPEN_FAILED', error: String(error?.message ?? error).slice(0, 200) }
393
+ } finally {
394
+ try { store?.close() } catch {}
395
+ cleanupVerificationArtifacts(String(backupPath), before, fs)
396
+ }
397
+ }
398
+
399
+ function cleanupVerificationArtifacts(path, before, fs) {
400
+ for (const suffix of ['-wal', '-shm']) {
401
+ if (before?.[suffix.slice(1)]) continue
402
+ const file = path + suffix
403
+ try { if (fsExists(fs, file)) { const raw = typeof fs?.rmSync === 'function' ? fs.rmSync : nodeFs.rmSync; raw(file, { force: true }) } } catch {}
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Apply a rotation plan. Dry-run by default (pass dryRun:false to delete).
409
+ * Every victim is re-resolved and checked to be a direct child of `dir` with a
410
+ * managed name; symlinks are refused. Backup + sidecars are removed together.
411
+ */
412
+ export function applyBackupRotation({ home, dir, entries, keep, now = Date.now(), dryRun = true, fs = nodeFs, probeReadable = true, maxProbe = 3 } = {}) {
413
+ const directory = resolve(String(dir ?? (home ? backupDir({ home }) : '')))
414
+ if (!directory) return failure('E_BACKUP_DIR_REQUIRED', 'applyBackupRotation requires {dir} or {home}')
415
+ let candidates = entries
416
+ if (!Array.isArray(candidates)) {
417
+ const listed = listBackups({ dir: directory, fs })
418
+ if (!listed.ok) return failure('E_BACKUP_LIST_FAILED', listed.errors.join('; '))
419
+ candidates = listed.entries
420
+ }
421
+ if (probeReadable) {
422
+ candidates = candidates.map((entry) => ({ ...entry }))
423
+ for (let index = 0; index < Math.min(maxProbe, candidates.length); index++) {
424
+ if (typeof candidates[index].readable === 'boolean') continue
425
+ candidates[index].readable = probeBackupReadable(candidates[index].path, { fs }).ok
426
+ }
427
+ }
428
+ const plan = planBackupRotation({ entries: candidates, keep, now })
429
+ if (!plan.ok) return plan
430
+ const result = {
431
+ ok: true,
432
+ dryRun: Boolean(dryRun),
433
+ dir: directory,
434
+ kept: plan.kept.map((entry) => entry.path),
435
+ protected: plan.protected,
436
+ deleted: [],
437
+ wouldDelete: [],
438
+ failed: [],
439
+ errors: [],
440
+ warnings: [],
441
+ plan,
442
+ }
443
+ const victims = plan.victims.map((entry) => entry.path)
444
+ if (dryRun) { result.wouldDelete = victims; return result }
445
+ for (const victim of victims) {
446
+ const checked = assertManagedPath(directory, victim)
447
+ if (!checked.ok) { result.errors.push(checked.error); result.failed.push({ path: victim, error: checked.error }); continue }
448
+ try {
449
+ const info = (typeof fs.lstatSync === 'function' ? fs.lstatSync : nodeFs.lstatSync)(checked.path)
450
+ if (info.isSymbolicLink()) {
451
+ const error = 'refusing to delete symlink ' + checked.path
452
+ result.errors.push(error)
453
+ result.failed.push({ path: checked.path, error })
454
+ continue
455
+ }
456
+ } catch (error) {
457
+ if (!isMissingError(error)) result.warnings.push('cannot stat ' + checked.path + ': ' + String(error?.code ?? error?.message ?? error))
458
+ }
459
+ for (const file of [checked.path, backupSha256Path(checked.path), backupAnchorPath(checked.path)]) {
460
+ if (!fsExists(fs, file)) continue
461
+ try {
462
+ rmWithRetrySync(file, { fs })
463
+ if (file === checked.path) result.deleted.push(file)
464
+ } catch (error) {
465
+ const message = 'cannot remove ' + file + ': ' + String(error?.code ?? error?.message ?? error)
466
+ result.errors.push(message)
467
+ result.failed.push({ path: file, error: message })
468
+ }
469
+ }
470
+ }
471
+ result.ok = result.errors.length === 0
472
+ return result
473
+ }
474
+
475
+ /**
476
+ * One-call managed rotation: list <home>/backups, plan, apply.
477
+ * Defaults to a dry run: the CLI decides when `--yes` turns it into deletion.
478
+ */
479
+ export function rotateManagedBackups({ home, keep, now = Date.now(), dryRun = true, fs = nodeFs } = {}) {
480
+ if (!home) return failure('E_BACKUP_DIR_REQUIRED', 'rotateManagedBackups requires {home}')
481
+ return applyBackupRotation({ home, dir: backupDir({ home }), keep, now, dryRun, fs })
482
+ }
483
+
484
+ // ---------------------------------------------------------------------------
485
+ // sha256 sidecar
486
+ // ---------------------------------------------------------------------------
487
+
488
+ /** Write `<backup>.sha256` in coreutils format ("<hex> <basename>\n"), 0600. */
489
+ export function writeBackupSha256(backupPath, { fs = nodeFs, mode = 0o600 } = {}) {
490
+ const file = String(backupPath)
491
+ if (!fsExists(fs, file)) return failure('E_BACKUP_MISSING', 'backup file not found: ' + file)
492
+ const hashed = sha256FileSync(file, { fs })
493
+ const target = backupSha256Path(file)
494
+ const content = hashed.sha256 + ' ' + basename(file) + '\n'
495
+ try {
496
+ atomicWriteFileSync(target, content, { fs, mode })
497
+ } catch (error) {
498
+ return failure(error?.code ?? 'E_BACKUP_SIDECAR_FAILED', 'cannot write ' + target + ': ' + String(error?.message ?? error).slice(0, 200))
499
+ }
500
+ return { ok: true, path: target, sha256: hashed.sha256, bytes: hashed.bytes }
501
+ }
502
+
503
+ /** Read `<backup>.sha256`; {found:false} when absent. */
504
+ export function readBackupSha256(backupPath, { fs = nodeFs } = {}) {
505
+ const target = backupSha256Path(String(backupPath))
506
+ const result = { ok: false, found: false, path: target, sha256: null, recordedName: null, errors: [] }
507
+ let text
508
+ try { text = (typeof fs.readFileSync === 'function' ? fs.readFileSync : readFileSync)(target, 'utf8') } catch (error) {
509
+ if (isMissingError(error)) { result.ok = true; return result }
510
+ result.errors.push('cannot read ' + target + ': ' + String(error?.code ?? error?.message ?? error))
511
+ return result
512
+ }
513
+ result.found = true
514
+ const match = /^([0-9a-f]{64}) (.+)\n?$/.exec(text)
515
+ if (!match) { result.errors.push('malformed sha256 sidecar: ' + target); return result }
516
+ result.sha256 = match[1]
517
+ result.recordedName = match[2]
518
+ result.ok = true
519
+ return result
520
+ }
521
+
522
+ /** Verify a backup file against its .sha256 sidecar (and its name). */
523
+ export function verifyBackupSha256(backupPath, { fs = nodeFs, hash = null } = {}) {
524
+ const file = String(backupPath)
525
+ const sidecar = readBackupSha256(file, { fs })
526
+ const result = { ok: false, found: sidecar.found, path: backupSha256Path(file), expected: sidecar.sha256, actual: null, errors: [...sidecar.errors], warnings: [] }
527
+ if (!sidecar.found) { result.ok = true; return result }
528
+ if (!sidecar.ok) return result
529
+ if (sidecar.recordedName !== basename(file)) {
530
+ result.errors.push('sha256 sidecar names ' + sidecar.recordedName + ' but the backup is ' + basename(file))
531
+ return result
532
+ }
533
+ try {
534
+ result.actual = hash?.sha256 ?? sha256FileSync(file, { fs }).sha256
535
+ } catch (error) {
536
+ result.errors.push('cannot hash ' + file + ': ' + String(error?.code ?? error?.message ?? error))
537
+ return result
538
+ }
539
+ if (result.actual !== sidecar.sha256) {
540
+ result.errors.push('sha256 mismatch for ' + basename(file) + ': sidecar ' + sidecar.sha256 + ', actual ' + result.actual)
541
+ return result
542
+ }
543
+ result.ok = true
544
+ return result
545
+ }
546
+
547
+ // ---------------------------------------------------------------------------
548
+ // Backup inspection
549
+ // ---------------------------------------------------------------------------
550
+
551
+ function hasTable(store, name) {
552
+ try {
553
+ return Boolean(store.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(name))
554
+ } catch { return false }
555
+ }
556
+
557
+ function sampleTableCounts(store) {
558
+ const counts = {}
559
+ for (const table of BACKUP_SAMPLE_TABLES) {
560
+ if (!hasTable(store, table)) continue
561
+ try { counts[table] = Number(store.db.prepare('SELECT COUNT(*) AS n FROM ' + table).get()?.n ?? 0) } catch { counts[table] = null }
562
+ }
563
+ return counts
564
+ }
565
+
566
+ function compareCounts(expected, actual) {
567
+ const mismatched = []
568
+ for (const [table, count] of Object.entries(expected ?? {})) {
569
+ if (count === null || count === undefined) continue
570
+ if ((actual ?? {})[table] !== count) mismatched.push(table + ': source ' + count + ', backup ' + ((actual ?? {})[table] ?? 'missing'))
571
+ }
572
+ return mismatched
573
+ }
574
+
575
+ /**
576
+ * Verify a .db backup read-only, without touching the file (except deleting the
577
+ * -wal/-shm sidecars SQLite creates for a read-only open of a WAL database).
578
+ *
579
+ * Checks: exists/size, no adjacent -wal, opens as SQLite, PRAGMA quick_check,
580
+ * meta.schema_version vs currentSchemaVersion (a newer backup is refused), the
581
+ * audit table/chain/head (when verifyChain) and sampled row counts.
582
+ * `audit` is always the cheap head (count/lastSeq/headHash/dbId) so restore can
583
+ * compare it with an anchor even when chain verification is waived.
584
+ */
585
+ export function inspectBackup(backupPath, { currentSchemaVersion = null, verifyChain = true, fs = nodeFs } = {}) {
586
+ const path = resolve(String(backupPath))
587
+ const result = {
588
+ ok: false,
589
+ codes: [],
590
+ path,
591
+ size: 0,
592
+ sha256: null,
593
+ quickCheck: null,
594
+ schemaVersion: null,
595
+ schemaStatus: 'unknown',
596
+ audit: null,
597
+ chain: null,
598
+ chainVerified: false,
599
+ counts: null,
600
+ code: null,
601
+ errors: [],
602
+ warnings: [],
603
+ }
604
+ const addError = (code, message) => {
605
+ if (!result.codes.includes(code)) result.codes.push(code)
606
+ if (result.code === null) result.code = code
607
+ result.errors.push(message)
608
+ }
609
+ let info
610
+ try { info = fsStat(fs, path) } catch (error) {
611
+ if (isMissingError(error)) addError('E_BACKUP_MISSING', 'backup file not found: ' + path)
612
+ else addError('E_BACKUP_UNREADABLE', 'cannot stat backup ' + path + ': ' + String(error?.code ?? error?.message ?? error))
613
+ return result
614
+ }
615
+ if (!info.isFile()) { addError('E_BACKUP_INVALID', 'backup path is not a regular file: ' + path); return result }
616
+ result.size = info.size
617
+ if (info.size === 0) { addError('E_BACKUP_EMPTY', 'backup file is empty: ' + path); return result }
618
+ const adjacentWal = path + '-wal'
619
+ if (fsExists(fs, adjacentWal)) {
620
+ let walSize = 0
621
+ try { walSize = fsStat(fs, adjacentWal).size } catch {}
622
+ if (walSize > 0) {
623
+ addError('E_BACKUP_HAS_WAL', 'backup has a non-empty ' + basename(adjacentWal) + ' (' + walSize + ' bytes): it was copied without a WAL checkpoint, so committed rows may be missing from the main file')
624
+ return result
625
+ }
626
+ }
627
+ const before = { wal: fsExists(fs, path + '-wal'), shm: fsExists(fs, path + '-shm') }
628
+ let store = null
629
+ try {
630
+ try {
631
+ store = new SqliteStore(path, { readOnly: true })
632
+ } catch (error) {
633
+ addError(error?.code === 'E_DB_CORRUPT' ? 'E_BACKUP_CORRUPT' : 'E_BACKUP_OPEN_FAILED', 'cannot open backup ' + path + ': ' + String(error?.message ?? error).slice(0, 200))
634
+ return result
635
+ }
636
+ try {
637
+ const verdict = String(store.db.prepare('PRAGMA quick_check').get()?.quick_check ?? 'unknown')
638
+ result.quickCheck = verdict
639
+ if (verdict !== 'ok') addError('E_BACKUP_CORRUPT', 'PRAGMA quick_check on the backup reported "' + verdict + '"')
640
+ } catch (error) {
641
+ result.quickCheck = 'error'
642
+ addError('E_BACKUP_CORRUPT', 'PRAGMA quick_check failed on the backup: ' + String(error?.message ?? error).slice(0, 200))
643
+ }
644
+ const isLedger = ['meta', 'matters', 'facts', 'commitments', 'audit'].some((table) => hasTable(store, table))
645
+ if (!isLedger) {
646
+ addError('E_BACKUP_NOT_ADVISERS_DB', 'backup has no Advisers tables (meta/matters/facts/commitments/audit); refusing to treat it as a ledger backup')
647
+ return result
648
+ }
649
+ try { result.schemaVersion = store.schemaVersion() } catch (error) { result.warnings.push('cannot read schema_version: ' + String(error?.message ?? error).slice(0, 160)) }
650
+ if (currentSchemaVersion !== null && currentSchemaVersion !== undefined && result.schemaVersion !== null) {
651
+ if (result.schemaVersion > Number(currentSchemaVersion)) {
652
+ result.schemaStatus = 'newer'
653
+ addError('E_BACKUP_SCHEMA_NEWER', 'backup schema v' + result.schemaVersion + ' is newer than this CLI (v' + currentSchemaVersion + '); upgrade advisers instead of restoring')
654
+ } else if (result.schemaVersion < Number(currentSchemaVersion)) {
655
+ result.schemaStatus = 'older'
656
+ result.warnings.push('backup schema v' + result.schemaVersion + ' is older than the current v' + currentSchemaVersion + '; it will be migrated on the next writable open')
657
+ } else {
658
+ result.schemaStatus = 'current'
659
+ }
660
+ }
661
+ if (!hasTable(store, 'audit')) {
662
+ result.warnings.push('backup has no audit table (pre-audit schema); audit anchor checks are skipped')
663
+ } else {
664
+ const cheap = readAuditHead(store, { verifyChain: false })
665
+ if (cheap.ok) result.audit = cheap
666
+ else addError(cheap.code ?? 'E_BACKUP_AUDIT_UNREADABLE', 'cannot read the backup audit head: ' + (cheap.errors[0] ?? 'unknown error'))
667
+ if (verifyChain) {
668
+ const chain = readAuditHead(store, { verifyChain: true })
669
+ result.chain = { ok: chain.ok, count: chain.count, brokenAt: chain.brokenAt }
670
+ if (!chain.ok) {
671
+ addError('E_BACKUP_AUDIT_CHAIN_BROKEN', 'backup audit chain is broken' + (chain.brokenAt === null || chain.brokenAt === undefined ? '' : ' at seq ' + chain.brokenAt) + '; restoring it would keep the broken chain')
672
+ } else if (result.audit && (chain.count !== result.audit.count || chain.headHash !== result.audit.headHash)) {
673
+ addError('E_BACKUP_AUDIT_CHAIN_BROKEN', 'backup audit head disagrees with the verified chain')
674
+ } else {
675
+ result.chainVerified = true
676
+ }
677
+ }
678
+ }
679
+ result.counts = sampleTableCounts(store)
680
+ } finally {
681
+ try { store?.close() } catch {}
682
+ cleanupVerificationArtifacts(path, before, fs)
683
+ }
684
+ result.ok = result.errors.length === 0
685
+ return result
686
+ }
687
+
688
+ /** Write `<backup>.anchor.json` from a cheap audit head (04 §4.7 sidecar). */
689
+ export function writeBackupAnchorSidecar({ backupPath, head, key, home, env, generator = 'advisers', createdAt = new Date().toISOString() } = {}) {
690
+ if (!head || head.ok !== true) {
691
+ return failure('E_BACKUP_ANCHOR_HEAD_MISSING', 'cannot write a backup audit anchor without a verified audit head')
692
+ }
693
+ const anchorPath = backupAnchorPath(backupPath)
694
+ const keyInfo = resolveAuditAnchorKey({ home, key, env })
695
+ const written = writeAuditAnchor({ file: anchorPath, head, key: keyInfo.key, generator, createdAt })
696
+ return { ...written, anchorPath }
697
+ }
698
+
699
+ /** Verify the optional backup sidecars (.sha256 and .anchor.json). */
700
+ export function verifyBackupSidecars({ backupPath, head = null, key, home, env, fs = nodeFs } = {}) {
701
+ const file = String(backupPath)
702
+ const result = {
703
+ ok: true,
704
+ path: file,
705
+ sha256: { found: false, ok: null, path: backupSha256Path(file), expected: null, actual: null },
706
+ anchor: { found: false, ok: null, path: backupAnchorPath(file), code: null, errors: [], warnings: [] },
707
+ errors: [],
708
+ warnings: [],
709
+ }
710
+ const sha = verifyBackupSha256(file, { fs })
711
+ result.sha256 = { found: sha.found, ok: sha.found ? sha.ok : null, path: sha.path, expected: sha.expected, actual: sha.actual }
712
+ if (sha.found && !sha.ok) { result.errors.push(...sha.errors) }
713
+ const read = readAuditAnchor({ file: backupAnchorPath(file) })
714
+ if (read.errors.length && read.code !== 'E_AUDIT_ANCHOR_INVALID') result.errors.push(...read.errors)
715
+ if (read.found && !read.ok) {
716
+ result.anchor.found = true
717
+ result.anchor.ok = false
718
+ result.anchor.code = read.code
719
+ result.anchor.errors = read.errors
720
+ result.errors.push(...read.errors)
721
+ } else if (read.found && read.ok) {
722
+ result.anchor.found = true
723
+ const keyInfo = resolveAuditAnchorKey({ home, key, env })
724
+ const compareHead = head ?? { count: read.anchor.count, lastSeq: read.anchor.lastSeq, headHash: read.anchor.headHash, dbId: read.anchor.dbId }
725
+ const verified = verifyAuditAnchor({ anchor: read.anchor, head: compareHead, key: keyInfo.key })
726
+ result.anchor.ok = verified.ok
727
+ result.anchor.code = verified.code
728
+ result.anchor.hmacVerified = verified.hmacVerified
729
+ result.anchor.errors = verified.errors
730
+ result.anchor.warnings = [...read.warnings, ...verified.warnings]
731
+ if (!verified.ok) result.errors.push(...verified.errors)
732
+ result.warnings.push(...result.anchor.warnings)
733
+ }
734
+ result.ok = result.errors.length === 0
735
+ return result
736
+ }
737
+
738
+ /**
739
+ * `backups verify` convenience: inspect every managed backup (default: all,
740
+ * capped by `limit`) and check its optional .sha256/.anchor.json sidecars.
741
+ * Read-only; an unreadable/corrupt backup is reported, never deleted.
742
+ */
743
+ export function verifyBackups({ home, dir, verifyChain = true, currentSchemaVersion = SCHEMA_VERSION, fs = nodeFs, key, env = process.env, limit = 100 } = {}) {
744
+ const listed = listBackups({ home, dir, fs })
745
+ if (!listed.ok) return { ok: false, dir: listed.dir, count: 0, results: [], errors: [...listed.errors], warnings: [] }
746
+ const selected = listed.entries.slice(0, Math.max(1, Math.floor(limit)))
747
+ const warnings = []
748
+ const errors = []
749
+ const results = selected.map((entry) => {
750
+ const inspection = inspectBackup(entry.path, { currentSchemaVersion, verifyChain, fs })
751
+ const sidecars = verifyBackupSidecars({ backupPath: entry.path, head: inspection.audit, key, home, env, fs })
752
+ const ok = inspection.ok && sidecars.ok
753
+ if (!ok) errors.push(...inspection.errors, ...sidecars.errors)
754
+ if (inspection.warnings.length || sidecars.warnings.length) warnings.push(...inspection.warnings, ...sidecars.warnings)
755
+ return { path: entry.path, name: entry.name, ok, inspection, sidecars }
756
+ })
757
+ return { ok: errors.length === 0, dir: listed.dir, count: results.length, results, errors, warnings }
758
+ }
759
+
760
+ /** One-line actionable hint per stable backup/restore code (bin/ messages). */
761
+ export const BACKUP_ERROR_HINTS = Object.freeze({
762
+ E_BACKUP_MISSING: 'the backup file does not exist; check the path or list <home>/backups',
763
+ E_BACKUP_EMPTY: 'the backup file is empty; it cannot be restored — take a fresh backup after recovering the ledger',
764
+ E_BACKUP_CORRUPT: 'the backup fails SQLite quick_check; do not restore it — try an older backup and keep this file for forensics',
765
+ E_BACKUP_HAS_WAL: 'the backup was copied without a WAL checkpoint; take a fresh backup with `advisers backup` (it checkpoints first)',
766
+ E_BACKUP_SCHEMA_NEWER: 'the backup is from a newer Advisers; upgrade the CLI instead of restoring it',
767
+ E_BACKUP_NOT_ADVISERS_DB: 'the file is not an Advisers ledger database; check the path',
768
+ E_BACKUP_BUSY: 'another connection blocked the WAL checkpoint; close other advisers processes (ui/mcp/bridge) and retry',
769
+ E_BACKUP_EXISTS: 'the target backup file already exists; choose another name or pass overwrite explicitly',
770
+ E_BACKUP_VERIFY_FAILED: 'the copied backup did not verify, so it was removed and no backup was installed; the live database is unchanged',
771
+ E_RESTORE_BUSY: 'another connection blocked the pre-restore checkpoint; close other advisers processes and retry',
772
+ E_RESTORE_WAL_OPEN: 'the database still has a non-empty WAL; checkpoint and close every connection before restoring',
773
+ E_RESTORE_PRERESTORE_FAILED: 'the pre-restore safety backup failed, so nothing was replaced; free disk space/permissions and retry',
774
+ E_RESTORE_INSTALL_FAILED: 'the atomic install failed, so the live database is unchanged; retry after closing programs that hold the file (antivirus/OneDrive)',
775
+ E_RESTORE_VERIFY_FAILED: 'the installed database did not verify; the pre-restore backup was used to roll back',
776
+ E_RESTORE_ROLLBACK_FAILED: 'the installed database did not verify AND rollback failed: stop, keep the pre-restore backup, and recover manually',
777
+ E_BACKUP_AUDIT_CHAIN_BROKEN: 'the backup audit chain is broken; restore only with explicit allowBrokenAuditChain after exporting evidence',
778
+ E_BACKUP_AUDIT_UNREADABLE: 'the backup audit head cannot be read; the file may be corrupt',
779
+ E_AUDIT_ANCHOR_ABSENT: 'no audit anchor was found, so the backup could not be anchor-checked; restore is allowed but not anchored',
780
+ E_AUDIT_ANCHOR_BEHIND: 'the backup is older than the audit anchor; pass --allow-anchor-behind only if this time-travel is intended',
781
+ E_BACKUP_ANCHOR_MISMATCH: 'the backup\'s own .anchor.json sidecar does not match the backup audit head; the backup or its sidecar was modified',
782
+ E_BACKUP_PATH_UNSAFE: 'refusing to delete a path outside the managed backup directory',
783
+ E_BACKUP_KEEP_INVALID: 'invalid keep policy; use a count or daily=7,weekly=4,monthly=3',
784
+ E_BACKUP_SIDECAR_FAILED: 'the .sha256 sidecar could not be written; the backup exists but its checksum file is missing',
785
+ E_RESTORE_TARGET_UNSAFE: 'the restore target path is not a regular .db path; refusing to replace it',
786
+ })
787
+
788
+ export function describeBackupCode(code) {
789
+ return BACKUP_ERROR_HINTS[code] ?? ('backup/restore failed: ' + String(code ?? 'unknown error'))
790
+ }
791
+
792
+ /**
793
+ * Create a verified backup of dbPath at targetPath.
794
+ *
795
+ * Steps: optional checkpoint(TRUNCATE) on the live store -> copy to a
796
+ * same-directory temp -> fsync -> read-only verification of the copy -> compare
797
+ * sampled row counts with the live DB -> sha256 -> atomic rename into place.
798
+ * The live database is only read. A failed verification removes the temp file
799
+ * and leaves an existing target untouched (E_BACKUP_VERIFY_FAILED).
800
+ */
801
+ export function createBackup({
802
+ dbPath,
803
+ targetPath,
804
+ store = null,
805
+ checkpoint = true,
806
+ verify = true,
807
+ verifyChain = false,
808
+ currentSchemaVersion = SCHEMA_VERSION,
809
+ expectedCounts = null,
810
+ overwrite = false,
811
+ writeSha256 = false,
812
+ tag = null,
813
+ at = new Date(),
814
+ fs = nodeFs,
815
+ mode = 0o600,
816
+ } = {}) {
817
+ if (!dbPath) return failure('E_BACKUP_SOURCE_MISSING', 'createBackup requires {dbPath}')
818
+ if (!targetPath) return failure('E_BACKUP_TARGET_MISSING', 'createBackup requires {targetPath}')
819
+ const source = resolve(String(dbPath))
820
+ const target = resolve(String(targetPath))
821
+ const warnings = []
822
+ const steps = []
823
+ let sourceInfo
824
+ try { sourceInfo = fsStat(fs, source) } catch (error) { return failure('E_BACKUP_SOURCE_MISSING', 'cannot stat the live database ' + source + ': ' + String(error?.code ?? error?.message ?? error)) }
825
+ if (!sourceInfo.isFile()) return failure('E_BACKUP_SOURCE_MISSING', 'live database path is not a regular file: ' + source)
826
+ const tagCheck = normalizeBackupTag(tag)
827
+ if (!tagCheck.ok) return failure('E_BACKUP_TAG_INVALID', tagCheck.error)
828
+ let checkpointInfo = null
829
+ if (checkpoint && store) {
830
+ if (typeof store.checkpoint !== 'function') return failure('E_BACKUP_STORE_INVALID', 'store does not implement checkpoint(); pass {checkpoint:false} if the WAL is already flushed')
831
+ try { checkpointInfo = store.checkpoint({ mode: 'TRUNCATE' }) } catch (error) {
832
+ return failure(error?.code ?? 'E_BACKUP_CHECKPOINT_FAILED', 'cannot checkpoint the WAL before backing up: ' + String(error?.message ?? error).slice(0, 200))
833
+ }
834
+ if (checkpointInfo?.busy) {
835
+ return failure('E_BACKUP_BUSY', 'another connection blocked the WAL checkpoint; the backup was not taken. Close other advisers processes and retry')
836
+ }
837
+ steps.push('checkpoint: TRUNCATE (busy=false)')
838
+ }
839
+ const liveCounts = expectedCounts ?? (store && store.db ? sampleTableCounts(store) : null)
840
+ const existedBefore = fsExists(fs, target)
841
+ if (existedBefore && !overwrite) {
842
+ return failure('E_BACKUP_EXISTS', 'refusing to overwrite the existing file ' + target + '; choose another name or pass overwrite:true', { path: target })
843
+ }
844
+ try { mkdirWithRetrySync(dirname(target), { fs }) } catch (error) {
845
+ return failure('E_BACKUP_DIR_FAILED', 'cannot create the backup directory ' + dirname(target) + ': ' + String(error?.message ?? error).slice(0, 200))
846
+ }
847
+ const temp = tempPathForSync(target)
848
+ try {
849
+ copyFileWithRetrySync(source, temp, { fs, mode })
850
+ steps.push('copy -> temp')
851
+ fsyncFileSync(temp, { fs })
852
+ try { fs.chmodSync?.(temp, mode) } catch {}
853
+ steps.push('fsync temp')
854
+ let inspection = null
855
+ if (verify) {
856
+ inspection = inspectBackup(temp, { currentSchemaVersion, verifyChain, fs })
857
+ if (!inspection.ok) {
858
+ const detail = inspection.errors.join('; ').slice(0, 400)
859
+ fsRm(fs, temp)
860
+ return failure('E_BACKUP_VERIFY_FAILED', 'the copied backup did not verify, so it was removed and the existing target (if any) is untouched: ' + detail, { codes: inspection.codes })
861
+ }
862
+ if (liveCounts) {
863
+ const mismatched = compareCounts(liveCounts, inspection.counts)
864
+ if (mismatched.length) {
865
+ fsRm(fs, temp)
866
+ return failure('E_BACKUP_VERIFY_FAILED', 'the backup row counts do not match the live database (' + mismatched.join(', ') + '); the backup was removed')
867
+ }
868
+ steps.push('row counts match the live database')
869
+ }
870
+ steps.push('verify: quick_check ok, schema v' + (inspection.schemaVersion ?? 'unknown'))
871
+ }
872
+ const hashed = sha256FileSync(temp, { fs })
873
+ try { fs.chmodSync?.(temp, mode) } catch {}
874
+ try {
875
+ renameWithRetrySync(temp, target, { fs })
876
+ } catch (error) {
877
+ fsRm(fs, temp)
878
+ return failure('E_BACKUP_INSTALL_FAILED', 'cannot install the verified backup at ' + target + ': ' + String(error?.message ?? error).slice(0, 200))
879
+ }
880
+ try { fs.chmodSync?.(target, mode) } catch {}
881
+ try { fsyncDirSync(dirname(target), { fs }) } catch {}
882
+ steps.push('atomic rename into place')
883
+ const result = {
884
+ ok: true,
885
+ code: null,
886
+ path: target,
887
+ bytes: hashed.bytes,
888
+ sha256: hashed.sha256,
889
+ schemaVersion: inspection?.schemaVersion ?? null,
890
+ audit: inspection?.audit ?? null,
891
+ chainVerified: inspection?.chainVerified ?? false,
892
+ counts: inspection?.counts ?? null,
893
+ checkpoint: checkpointInfo,
894
+ sidecars: { sha256: null, anchor: null },
895
+ steps,
896
+ warnings,
897
+ errors: [],
898
+ }
899
+ if (writeSha256) {
900
+ const written = writeBackupSha256(target, { fs })
901
+ if (written.ok) result.sidecars.sha256 = written.path
902
+ else warnings.push(written.errors[0] ?? 'could not write the sha256 sidecar')
903
+ }
904
+ if (!result.audit) warnings.push('backup audit head unavailable; no audit anchor sidecar can certify this backup')
905
+ return result
906
+ } catch (error) {
907
+ fsRm(fs, temp)
908
+ return failure(error?.code ?? 'E_BACKUP_FAILED', 'backup failed: ' + String(error?.message ?? error).slice(0, 300))
909
+ }
910
+ }
911
+
912
+ /**
913
+ * Create a backup in <home>/backups with the managed name, .sha256 and
914
+ * .anchor.json sidecars, then optionally rotate. Wave 2 bin/ glue: choose
915
+ * `rotate:true` only on the explicit `backup` command (not on `--out` paths,
916
+ * which never participate in rotation).
917
+ */
918
+ export function createManagedBackup({
919
+ home,
920
+ dbPath,
921
+ store = null,
922
+ tag = null,
923
+ at = new Date(),
924
+ keep = null,
925
+ rotate = false,
926
+ rotateDryRun = false,
927
+ anchorKey,
928
+ env = process.env,
929
+ generator = 'advisers',
930
+ writeSha256 = true,
931
+ writeAnchor = true,
932
+ verifyChain = false,
933
+ fs = nodeFs,
934
+ } = {}) {
935
+ if (!home) return failure('E_BACKUP_DIR_REQUIRED', 'createManagedBackup requires {home}')
936
+ const tagCheck = normalizeBackupTag(tag)
937
+ if (!tagCheck.ok) return failure('E_BACKUP_TAG_INVALID', tagCheck.error)
938
+ const finalTarget = backupPathFor({ home, at, tag: tagCheck.tag })
939
+ const created = createBackup({
940
+ dbPath,
941
+ targetPath: finalTarget,
942
+ store,
943
+ verify: true,
944
+ verifyChain,
945
+ writeSha256,
946
+ fs,
947
+ })
948
+ if (!created.ok) return created
949
+ if (writeAnchor && created.audit) {
950
+ const anchor = writeBackupAnchorSidecar({ backupPath: finalTarget, head: created.audit, key: anchorKey, home, env, generator })
951
+ if (anchor.ok) created.sidecars.anchor = anchor.anchorPath
952
+ else created.warnings.push(anchor.errors?.[0] ?? 'could not write the audit anchor sidecar')
953
+ }
954
+ created.managedDir = backupDir({ home })
955
+ if (rotate) {
956
+ const rotation = rotateManagedBackups({ home, keep, dryRun: rotateDryRun, fs })
957
+ created.rotation = rotation
958
+ if (!rotation.ok) created.warnings.push(...(rotation.errors ?? ['rotation failed']))
959
+ else if (rotation.dryRun) created.warnings.push('rotation dry-run: would delete ' + rotation.wouldDelete.length + ' backup(s)')
960
+ }
961
+ return created
962
+ }
963
+
964
+ // ---------------------------------------------------------------------------
965
+ // Restore
966
+ // ---------------------------------------------------------------------------
967
+
968
+ function defaultPreRestorePath({ dbPath, home, at }) {
969
+ if (home) return backupPathFor({ home, at, tag: 'pre-restore' })
970
+ return String(dbPath) + '.before-restore-' + backupTimestamp(at)
971
+ }
972
+
973
+ function uniquePath(path, fs) {
974
+ if (!fsExists(fs, path)) return path
975
+ const stem = path.endsWith('.db') ? path.slice(0, -3) : path
976
+ const suffix = path.endsWith('.db') ? '.db' : ''
977
+ for (let index = 2; index < 1000; index++) {
978
+ const candidate = stem + '-' + index + suffix
979
+ if (!fsExists(fs, candidate)) return candidate
980
+ }
981
+ return path
982
+ }
983
+
984
+ /**
985
+ * Validate a backup + audit anchor BEFORE touching the live database.
986
+ * This is the `restore --dry-run` path: no file is modified.
987
+ */
988
+ export function planRestore({
989
+ backupPath,
990
+ dbPath,
991
+ currentSchemaVersion = SCHEMA_VERSION,
992
+ anchor = null,
993
+ anchorPath = null,
994
+ allowAnchorBehind = false,
995
+ allowBrokenAuditChain = false,
996
+ requireAnchor = false,
997
+ key,
998
+ home,
999
+ env = process.env,
1000
+ fs = nodeFs,
1001
+ } = {}) {
1002
+ if (!backupPath) return failure('E_BACKUP_MISSING', 'planRestore requires {backupPath}')
1003
+ const inspection = inspectBackup(backupPath, { currentSchemaVersion, verifyChain: true, fs })
1004
+ const warnings = [...inspection.warnings]
1005
+ if (!inspection.ok) {
1006
+ const blocking = inspection.codes.filter((code) => !(allowBrokenAuditChain && code === 'E_BACKUP_AUDIT_CHAIN_BROKEN'))
1007
+ if (blocking.length) {
1008
+ return {
1009
+ ok: false,
1010
+ code: blocking[0],
1011
+ codes: blocking,
1012
+ path: inspection.path,
1013
+ inspection,
1014
+ errors: [...inspection.errors],
1015
+ warnings,
1016
+ }
1017
+ }
1018
+ warnings.push('restoring a backup whose audit chain is broken was explicitly allowed; the restored ledger will keep the broken chain')
1019
+ }
1020
+ let anchorRead = null
1021
+ let resolvedAnchor = anchor
1022
+ if (!resolvedAnchor) {
1023
+ const target = anchorPath ?? (home ? resolve(join(home, 'audit-anchor.json')) : null)
1024
+ if (target) {
1025
+ anchorRead = readAuditAnchor({ file: target })
1026
+ if (anchorRead.found && !anchorRead.ok) {
1027
+ if (allowBrokenAuditChain && !requireAnchor) {
1028
+ warnings.push('the audit anchor is unreadable (' + anchorRead.code + ') but rescue mode (allowBrokenAuditChain) proceeds without it; the restore will not be anchor-checked')
1029
+ } else {
1030
+ return { ok: false, code: anchorRead.code, path: inspection.path, inspection, errors: [...anchorRead.errors], warnings }
1031
+ }
1032
+ }
1033
+ if (anchorRead.found && anchorRead.ok) resolvedAnchor = anchorRead.anchor
1034
+ }
1035
+ }
1036
+ let anchorVerification = null
1037
+ if (resolvedAnchor) {
1038
+ if (!inspection.audit) {
1039
+ if (requireAnchor) return { ok: false, code: 'E_BACKUP_AUDIT_UNREADABLE', path: inspection.path, inspection, errors: ['the backup has no readable audit head, so the audit anchor cannot be checked'], warnings }
1040
+ warnings.push('the backup has no readable audit head; audit anchor comparison skipped')
1041
+ } else {
1042
+ const keyInfo = resolveAuditAnchorKey({ home, key, env })
1043
+ anchorVerification = verifyRestoreAnchor({ anchor: resolvedAnchor, head: inspection.audit, key: keyInfo.key, allowAnchorBehind })
1044
+ warnings.push(...anchorVerification.warnings)
1045
+ if (!anchorVerification.ok) {
1046
+ if (allowBrokenAuditChain && !requireAnchor) {
1047
+ warnings.push('the audit anchor check failed (' + anchorVerification.code + ') but rescue mode (allowBrokenAuditChain) proceeds: ' + (anchorVerification.errors[0] ?? 'anchor mismatch'))
1048
+ } else {
1049
+ return {
1050
+ ok: false,
1051
+ code: anchorVerification.code,
1052
+ path: inspection.path,
1053
+ inspection,
1054
+ anchor: resolvedAnchor,
1055
+ anchorVerification,
1056
+ errors: [...anchorVerification.errors],
1057
+ warnings,
1058
+ }
1059
+ }
1060
+ }
1061
+ }
1062
+ } else if (requireAnchor) {
1063
+ return { ok: false, code: 'E_AUDIT_ANCHOR_ABSENT', path: inspection.path, inspection, errors: ['no audit anchor found and requireAnchor is set'], warnings }
1064
+ } else {
1065
+ warnings.push('no audit anchor found: the restore cannot be checked against an audit baseline (yellow, not a failure)')
1066
+ }
1067
+ // A managed backup also carries its own <backup>.anchor.json. It cannot prove
1068
+ // the backup is recent (both files travel together), but it does detect a
1069
+ // backup or sidecar edited after the fact, so check it too when present.
1070
+ let sidecarAnchor = null
1071
+ if (inspection.audit) {
1072
+ const sidecarRead = readAuditAnchor({ file: backupAnchorPath(inspection.path) })
1073
+ if (sidecarRead.found && sidecarRead.ok) {
1074
+ const sidecarKey = resolveAuditAnchorKey({ home, key, env })
1075
+ const sidecarVerification = verifyAuditAnchor({ anchor: sidecarRead.anchor, head: inspection.audit, key: sidecarKey.key })
1076
+ if (!sidecarVerification.ok) {
1077
+ if (allowBrokenAuditChain && !requireAnchor) {
1078
+ warnings.push('the backup sidecar anchor check failed (' + sidecarVerification.code + ') but rescue mode (allowBrokenAuditChain) proceeds: ' + (sidecarVerification.errors[0] ?? 'anchor mismatch'))
1079
+ } else {
1080
+ return {
1081
+ ok: false,
1082
+ code: 'E_BACKUP_ANCHOR_MISMATCH',
1083
+ path: inspection.path,
1084
+ inspection,
1085
+ anchor: resolvedAnchor ?? null,
1086
+ anchorVerification,
1087
+ errors: [...sidecarVerification.errors],
1088
+ warnings,
1089
+ }
1090
+ }
1091
+ }
1092
+ sidecarAnchor = { anchor: sidecarRead.anchor, verification: sidecarVerification }
1093
+ warnings.push(...sidecarVerification.warnings)
1094
+ } else if (sidecarRead.found && !sidecarRead.ok) {
1095
+ if (allowBrokenAuditChain && !requireAnchor) {
1096
+ warnings.push('the backup sidecar anchor is unreadable (' + sidecarRead.code + ') but rescue mode (allowBrokenAuditChain) proceeds without it')
1097
+ } else {
1098
+ return { ok: false, code: sidecarRead.code, path: inspection.path, inspection, errors: [...sidecarRead.errors], warnings }
1099
+ }
1100
+ }
1101
+ }
1102
+ const resolvedDbPath = dbPath ? resolve(String(dbPath)) : null
1103
+ const steps = [
1104
+ 'verify backup: quick_check/schema/audit' + (inspection.chainVerified ? ' chain verified' : ''),
1105
+ 'check audit anchor' + (resolvedAnchor ? (allowAnchorBehind ? ' (anchor-behind allowed)' : '') : ' (none found)') + (sidecarAnchor ? ' + backup sidecar anchor' : ''),
1106
+ 'checkpoint + close the live store',
1107
+ 'write pre-restore backup',
1108
+ 'remove stale -wal/-shm, install backup via atomic rename',
1109
+ 'verify restored database and roll back on failure',
1110
+ ]
1111
+ return {
1112
+ ok: true,
1113
+ path: inspection.path,
1114
+ dbPath: resolvedDbPath,
1115
+ inspection,
1116
+ anchor: resolvedAnchor ?? null,
1117
+ anchorVerification,
1118
+ sidecarAnchor,
1119
+ warnings,
1120
+ errors: [],
1121
+ steps,
1122
+ }
1123
+ }
1124
+
1125
+ function verifyDatabaseFile(path, { expectedSchemaVersion = null, expectedHead = null, fs = nodeFs } = {}) {
1126
+ const before = { wal: fsExists(fs, path + '-wal'), shm: fsExists(fs, path + '-shm') }
1127
+ let store = null
1128
+ const result = { ok: false, code: null, quickCheck: null, schemaVersion: null, audit: null, errors: [] }
1129
+ try {
1130
+ store = new SqliteStore(path, { readOnly: true })
1131
+ try {
1132
+ const verdict = String(store.db.prepare('PRAGMA quick_check').get()?.quick_check ?? 'unknown')
1133
+ result.quickCheck = verdict
1134
+ if (verdict !== 'ok') { result.code = 'E_RESTORE_VERIFY_FAILED'; result.errors.push('quick_check reported "' + verdict + '"') }
1135
+ } catch (error) {
1136
+ result.code = 'E_RESTORE_VERIFY_FAILED'
1137
+ result.errors.push('quick_check failed: ' + String(error?.message ?? error).slice(0, 200))
1138
+ }
1139
+ try { result.schemaVersion = store.schemaVersion() } catch {}
1140
+ if (expectedSchemaVersion !== null && expectedSchemaVersion !== undefined && result.schemaVersion !== null && result.schemaVersion !== expectedSchemaVersion) {
1141
+ result.code = 'E_RESTORE_VERIFY_FAILED'
1142
+ result.errors.push('restored schema v' + result.schemaVersion + ' does not match the backup schema v' + expectedSchemaVersion)
1143
+ }
1144
+ if (expectedHead) {
1145
+ const head = readAuditHead(store, { verifyChain: false })
1146
+ if (!head.ok) {
1147
+ result.code = 'E_RESTORE_VERIFY_FAILED'
1148
+ result.errors.push('cannot read the restored audit head: ' + (head.errors[0] ?? 'unknown error'))
1149
+ } else {
1150
+ result.audit = head
1151
+ if (head.count !== expectedHead.count || head.lastSeq !== expectedHead.lastSeq || head.headHash !== expectedHead.headHash) {
1152
+ result.code = 'E_RESTORE_VERIFY_FAILED'
1153
+ result.errors.push('restored audit head does not match the backup (count ' + head.count + ' vs ' + expectedHead.count + ')')
1154
+ }
1155
+ }
1156
+ }
1157
+ } catch (error) {
1158
+ result.code = error?.code === 'E_DB_CORRUPT' ? 'E_RESTORE_VERIFY_FAILED' : (error?.code ?? 'E_RESTORE_VERIFY_FAILED')
1159
+ result.errors.push('cannot open the installed database: ' + String(error?.message ?? error).slice(0, 200))
1160
+ } finally {
1161
+ try { store?.close() } catch {}
1162
+ cleanupVerificationArtifacts(path, before, fs)
1163
+ }
1164
+ result.ok = result.code === null && result.errors.length === 0
1165
+ return result
1166
+ }
1167
+
1168
+ /**
1169
+ * Restore a verified backup over dbPath (fail-safe, rollback capable).
1170
+ *
1171
+ * Preconditions: the caller has validated the backup (or passes options so
1172
+ * planRestore runs first) and holds the HOME instance lock. Passing `store`
1173
+ * lets the library checkpoint(TRUNCATE) and close it before the copy; without a
1174
+ * store the caller must have checkpointed and closed every connection, and a
1175
+ * non-empty -wal file is refused with E_RESTORE_WAL_OPEN.
1176
+ *
1177
+ * Returns {ok:true, restoredFrom, preRestoreBackup, audit, ...} or a failure with
1178
+ * `originalIntact` / `rolledBack` flags. The caller writes the `db.restore` audit
1179
+ * row and a fresh anchor after reopening the restored store.
1180
+ */
1181
+ export function restoreBackup({
1182
+ plan = null,
1183
+ backupPath = null,
1184
+ dbPath,
1185
+ store = null,
1186
+ closeStore = null,
1187
+ home = null,
1188
+ anchor = null,
1189
+ anchorPath = null,
1190
+ key,
1191
+ env = process.env,
1192
+ allowAnchorBehind = false,
1193
+ allowBrokenAuditChain = false,
1194
+ requireAnchor = false,
1195
+ currentSchemaVersion = SCHEMA_VERSION,
1196
+ preRestorePath = null,
1197
+ expectSameBytes = true,
1198
+ verifyAfter = true,
1199
+ fs = nodeFs,
1200
+ now = Date.now(),
1201
+ } = {}) {
1202
+ let restorePlan = plan
1203
+ if (!restorePlan) {
1204
+ restorePlan = planRestore({ backupPath, dbPath, currentSchemaVersion, anchor, anchorPath, allowAnchorBehind, allowBrokenAuditChain, requireAnchor, key, home, env, fs })
1205
+ }
1206
+ if (!restorePlan.ok) return { ...restorePlan, originalIntact: true, storeClosed: false }
1207
+ const targetDb = restorePlan.dbPath ?? (dbPath ? resolve(String(dbPath)) : null)
1208
+ if (!targetDb) return failure('E_RESTORE_TARGET_MISSING', 'restoreBackup requires {dbPath}')
1209
+ if (!/\.db$/i.test(basename(targetDb))) return failure('E_RESTORE_TARGET_UNSAFE', 'restore target must be a .db file: ' + targetDb)
1210
+ const backup = restorePlan.path
1211
+ const backupInfo = restorePlan.inspection
1212
+ const steps = [...(restorePlan.steps ?? [])]
1213
+ const warnings = [...(restorePlan.warnings ?? [])]
1214
+ const ts = new Date(now)
1215
+ let storeClosed = false
1216
+ // 1. Quiesce the live store.
1217
+ if (store) {
1218
+ try {
1219
+ const checkpoint = typeof store.checkpoint === 'function' ? store.checkpoint({ mode: 'TRUNCATE' }) : null
1220
+ if (checkpoint?.busy) return failure('E_RESTORE_BUSY', 'another connection blocked the pre-restore WAL checkpoint; close other advisers processes and retry', { storeClosed: false, originalIntact: true })
1221
+ } catch (error) {
1222
+ return failure(error?.code ?? 'E_RESTORE_CHECKPOINT_FAILED', 'cannot checkpoint the live database before restore: ' + String(error?.message ?? error).slice(0, 200), { storeClosed: false, originalIntact: true })
1223
+ }
1224
+ }
1225
+ try {
1226
+ if (typeof closeStore === 'function') closeStore()
1227
+ else if (store && typeof store.close === 'function') store.close()
1228
+ storeClosed = Boolean(store || closeStore)
1229
+ } catch (error) {
1230
+ return failure('E_RESTORE_CLOSE_FAILED', 'cannot close the live database before restore: ' + String(error?.message ?? error).slice(0, 200), { storeClosed: false, originalIntact: true })
1231
+ }
1232
+ steps.push('live store checkpointed and closed')
1233
+ const walFile = targetDb + '-wal'
1234
+ if (fsExists(fs, walFile)) {
1235
+ let walSize = 0
1236
+ try { walSize = fsStat(fs, walFile).size } catch {}
1237
+ if (walSize > 0) {
1238
+ return failure('E_RESTORE_WAL_OPEN', 'the live database still has a non-empty -wal file (' + walSize + ' bytes): checkpoint and close every connection before restoring', { storeClosed, originalIntact: true })
1239
+ }
1240
+ }
1241
+ // 2. Pre-restore safety backup of the current database (rollback source).
1242
+ const liveExists = fsExists(fs, targetDb)
1243
+ let preRestore = null
1244
+ if (liveExists) {
1245
+ const candidate = preRestorePath ?? defaultPreRestorePath({ dbPath: targetDb, home, at: ts })
1246
+ preRestore = uniquePath(candidate, fs)
1247
+ try {
1248
+ try { mkdirWithRetrySync(dirname(preRestore), { fs }) } catch {}
1249
+ copyFileWithRetrySync(targetDb, preRestore, { fs, mode: 0o600 })
1250
+ fsyncFileSync(preRestore, { fs })
1251
+ try { fs.chmodSync?.(preRestore, 0o600) } catch {}
1252
+ try { fsyncDirSync(dirname(preRestore), { fs }) } catch {}
1253
+ } catch (error) {
1254
+ fsRm(fs, preRestore)
1255
+ preRestore = null
1256
+ return failure('E_RESTORE_PRERESTORE_FAILED', 'cannot write the pre-restore safety backup ' + candidate + ': ' + String(error?.message ?? error).slice(0, 200), { storeClosed, originalIntact: true })
1257
+ }
1258
+ steps.push('pre-restore backup -> ' + preRestore)
1259
+ const verifiedPre = probeBackupReadable(preRestore, { fs })
1260
+ if (!verifiedPre.ok) warnings.push('the current database does not pass quick_check either, so the pre-restore backup is kept for forensics but may not open (' + (verifiedPre.error ?? verifiedPre.quickCheck ?? 'unknown') + ')')
1261
+ } else {
1262
+ steps.push('no live database: fresh install')
1263
+ }
1264
+ // 3. Remove stale WAL/SHM of the old database (they must not be applied to the new file).
1265
+ for (const suffix of ['-wal', '-shm']) {
1266
+ const stale = targetDb + suffix
1267
+ if (fsExists(fs, stale)) {
1268
+ try { rmWithRetrySync(stale, { fs }) } catch (error) {
1269
+ return failure('E_RESTORE_WAL_OPEN', 'cannot remove stale ' + basename(stale) + ': ' + String(error?.message ?? error).slice(0, 200), { storeClosed, originalIntact: true, preRestoreBackup: preRestore })
1270
+ }
1271
+ }
1272
+ }
1273
+ // 4. Copy the backup to a same-directory temp file and verify the copy.
1274
+ const temp = tempPathForSync(targetDb)
1275
+ let tempBytes = 0
1276
+ try {
1277
+ copyFileWithRetrySync(backup, temp, { fs, mode: 0o600 })
1278
+ fsyncFileSync(temp, { fs })
1279
+ try { fs.chmodSync?.(temp, 0o600) } catch {}
1280
+ tempBytes = fsStat(fs, temp).size
1281
+ if (expectSameBytes && tempBytes !== backupInfo.size) {
1282
+ fsRm(fs, temp)
1283
+ return failure('E_RESTORE_VERIFY_FAILED', 'the copied backup is ' + tempBytes + ' bytes but the source is ' + backupInfo.size + '; the copy was removed and the live database is unchanged', { storeClosed, originalIntact: true, preRestoreBackup: preRestore })
1284
+ }
1285
+ const tempVerification = verifyDatabaseFile(temp, { expectedSchemaVersion: backupInfo.schemaVersion, expectedHead: backupInfo.audit, fs })
1286
+ if (!tempVerification.ok) {
1287
+ fsRm(fs, temp)
1288
+ return failure('E_RESTORE_VERIFY_FAILED', 'the copied backup did not verify (' + tempVerification.errors.join('; ').slice(0, 300) + '); the copy was removed and the live database is unchanged', { storeClosed, originalIntact: true, preRestoreBackup: preRestore })
1289
+ }
1290
+ steps.push('copy verified before install')
1291
+ } catch (error) {
1292
+ fsRm(fs, temp)
1293
+ return failure(error?.code ?? 'E_RESTORE_COPY_FAILED', 'cannot copy the backup into place: ' + String(error?.message ?? error).slice(0, 200), { storeClosed, originalIntact: true, preRestoreBackup: preRestore })
1294
+ }
1295
+ // 5. Atomic install.
1296
+ try {
1297
+ renameWithRetrySync(temp, targetDb, { fs })
1298
+ try { fs.chmodSync?.(targetDb, 0o600) } catch {}
1299
+ try { fsyncDirSync(dirname(targetDb), { fs }) } catch {}
1300
+ steps.push('backup installed via atomic rename')
1301
+ } catch (error) {
1302
+ fsRm(fs, temp)
1303
+ return failure('E_RESTORE_INSTALL_FAILED', 'cannot install the restore at ' + targetDb + ': ' + String(error?.message ?? error).slice(0, 200) + '; the live database is unchanged', { storeClosed, originalIntact: true, preRestoreBackup: preRestore })
1304
+ }
1305
+ // 6. Post-install verification with rollback to the pre-restore copy.
1306
+ const installed = verifyAfter
1307
+ ? verifyDatabaseFile(targetDb, { expectedSchemaVersion: backupInfo.schemaVersion, expectedHead: backupInfo.audit, fs })
1308
+ : { ok: true, errors: [], audit: backupInfo.audit }
1309
+ if (!installed.ok) {
1310
+ for (const suffix of ['-wal', '-shm']) fsRm(fs, targetDb + suffix)
1311
+ let rolledBack = false
1312
+ let rollbackError = null
1313
+ try {
1314
+ if (preRestore) {
1315
+ renameWithRetrySync(preRestore, targetDb, { fs })
1316
+ try { fsyncDirSync(dirname(targetDb), { fs }) } catch {}
1317
+ rolledBack = true
1318
+ } else {
1319
+ rmWithRetrySync(targetDb, { fs })
1320
+ rolledBack = true
1321
+ }
1322
+ } catch (error) {
1323
+ rollbackError = String(error?.message ?? error).slice(0, 300)
1324
+ }
1325
+ if (rollbackError) {
1326
+ return failure('E_RESTORE_ROLLBACK_FAILED', 'the restored database did not verify AND rollback failed: ' + rollbackError + '. The pre-restore backup is at ' + (preRestore ?? '(none)') + '; recover manually and keep evidence', { storeClosed, originalIntact: false, preRestoreBackup: preRestore })
1327
+ }
1328
+ return failure('E_RESTORE_VERIFY_FAILED', 'the restored database did not verify (' + installed.errors.join('; ').slice(0, 300) + '); ' + (rolledBack ? 'the pre-restore backup was rolled back' : 'the partial file was removed'), { storeClosed, originalIntact: true, rolledBack, preRestoreBackup: preRestore })
1329
+ }
1330
+ steps.push('restored database verified')
1331
+ return {
1332
+ ok: true,
1333
+ code: null,
1334
+ dbPath: targetDb,
1335
+ restoredFrom: backup,
1336
+ preRestoreBackup: preRestore,
1337
+ schemaVersion: installed.schemaVersion ?? backupInfo.schemaVersion,
1338
+ audit: installed.audit ?? backupInfo.audit,
1339
+ storeClosed,
1340
+ allowAnchorBehind: Boolean(allowAnchorBehind),
1341
+ steps,
1342
+ warnings,
1343
+ errors: [],
1344
+ }
1345
+ }