@edihasaj/recall 1.4.1 → 1.4.15

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 (86) hide show
  1. package/README.md +17 -7
  2. package/dist/{chunk-WZWXYBP6.js → chunk-2E7UCWNS.js} +6 -3
  3. package/dist/{chunk-WZWXYBP6.js.map → chunk-2E7UCWNS.js.map} +1 -1
  4. package/dist/{chunk-JYWURG5T.js → chunk-5W3CDNJ6.js} +12 -2
  5. package/dist/chunk-5W3CDNJ6.js.map +1 -0
  6. package/dist/chunk-ADWOKDF6.js +23 -0
  7. package/dist/chunk-ADWOKDF6.js.map +1 -0
  8. package/dist/{chunk-CW3XJDH7.js → chunk-FDIV6YFT.js} +6 -2
  9. package/dist/{chunk-CW3XJDH7.js.map → chunk-FDIV6YFT.js.map} +1 -1
  10. package/dist/{chunk-EAFRT7RX.js → chunk-GMRT5DJZ.js} +7 -2
  11. package/dist/{chunk-EAFRT7RX.js.map → chunk-GMRT5DJZ.js.map} +1 -1
  12. package/dist/{chunk-PUMEMKGF.js → chunk-IMCI2CLJ.js} +7 -1
  13. package/dist/{chunk-PUMEMKGF.js.map → chunk-IMCI2CLJ.js.map} +1 -1
  14. package/dist/{chunk-ZBQGZCFL.js → chunk-KF3EGZWM.js} +99 -9
  15. package/dist/chunk-KF3EGZWM.js.map +1 -0
  16. package/dist/{chunk-NAYFAUSM.js → chunk-LCIVSUQO.js} +61 -21
  17. package/dist/chunk-LCIVSUQO.js.map +1 -0
  18. package/dist/{chunk-LWY4Z626.js → chunk-MESKBXZZ.js} +8 -4
  19. package/dist/{chunk-LWY4Z626.js.map → chunk-MESKBXZZ.js.map} +1 -1
  20. package/dist/{chunk-FHEH6QDU.js → chunk-PQOGHXET.js} +6 -1
  21. package/dist/{chunk-FHEH6QDU.js.map → chunk-PQOGHXET.js.map} +1 -1
  22. package/dist/{chunk-ZXCKMEJA.js → chunk-RRNELZJV.js} +11 -6
  23. package/dist/{chunk-ZXCKMEJA.js.map → chunk-RRNELZJV.js.map} +1 -1
  24. package/dist/{chunk-7CFX774S.js → chunk-SWPXUPMX.js} +306 -167
  25. package/dist/chunk-SWPXUPMX.js.map +1 -0
  26. package/dist/{chunk-T274LVWB.js → chunk-TZ4EU4SW.js} +15 -11
  27. package/dist/chunk-TZ4EU4SW.js.map +1 -0
  28. package/dist/chunk-UTOM43G2.js +594 -0
  29. package/dist/chunk-UTOM43G2.js.map +1 -0
  30. package/dist/{chunk-AFD43EOE.js → chunk-UZ4GFLH6.js} +8 -4
  31. package/dist/{chunk-AFD43EOE.js.map → chunk-UZ4GFLH6.js.map} +1 -1
  32. package/dist/{chunk-LUIYWYOT.js → chunk-VI6NOUXB.js} +51 -3
  33. package/dist/chunk-VI6NOUXB.js.map +1 -0
  34. package/dist/{chunk-TA4WSV6A.js → chunk-VZ456OCO.js} +204 -13
  35. package/dist/chunk-VZ456OCO.js.map +1 -0
  36. package/dist/{chunk-4UHRAQFG.js → chunk-ZECQ2LQB.js} +376 -58
  37. package/dist/chunk-ZECQ2LQB.js.map +1 -0
  38. package/dist/{cleanup-RTL2UETA.js → cleanup-KXCEVJ7V.js} +11 -10
  39. package/dist/cli.js +639 -784
  40. package/dist/cli.js.map +1 -1
  41. package/dist/codex-trust-H7VKP4G3.js +74 -0
  42. package/dist/codex-trust-H7VKP4G3.js.map +1 -0
  43. package/dist/daemon.js +174 -54
  44. package/dist/daemon.js.map +1 -1
  45. package/dist/dispatcher-GHC6RX54.js +22 -0
  46. package/dist/{embeddings-MILTROKW.js → embeddings-GYQBZWBD.js} +7 -5
  47. package/dist/ingest-6GDZNYCY.js +20 -0
  48. package/dist/{keychain-5KXUHKMF.js → keychain-TKPVUZCH.js} +3 -3
  49. package/dist/mcp.js +18 -14
  50. package/dist/mcp.js.map +1 -1
  51. package/dist/{memory-value-WXI2Q6TO.js → memory-value-A4UCC3DY.js} +11 -10
  52. package/dist/provenance-M5YFD6DO.js +50 -0
  53. package/dist/provenance-M5YFD6DO.js.map +1 -0
  54. package/dist/quality-TQ7CVPRO.js +25 -0
  55. package/dist/retrieval-7R5LKJAM.js +15 -0
  56. package/dist/{store-5C7ZKKZF.js → store-QKP6HQ45.js} +4 -4
  57. package/dist/sync-server.js +5 -2
  58. package/dist/sync-server.js.map +1 -1
  59. package/dist/{tasks-7SE6VHSQ.js → tasks-M5HSQSWK.js} +11 -10
  60. package/dist/{usage-VQ5LJCNH.js → usage-TQTOHPL7.js} +7 -4
  61. package/dist/{usage-VQ5LJCNH.js.map → usage-TQTOHPL7.js.map} +1 -1
  62. package/drizzle/0011_compact_telemetry_dedupe_keys.sql +25 -0
  63. package/drizzle/meta/_journal.json +7 -0
  64. package/package.json +15 -12
  65. package/dist/chunk-4UHRAQFG.js.map +0 -1
  66. package/dist/chunk-7CFX774S.js.map +0 -1
  67. package/dist/chunk-LUIYWYOT.js.map +0 -1
  68. package/dist/chunk-NAYFAUSM.js.map +0 -1
  69. package/dist/chunk-T274LVWB.js.map +0 -1
  70. package/dist/chunk-TA4WSV6A.js.map +0 -1
  71. package/dist/chunk-ZBQGZCFL.js.map +0 -1
  72. package/dist/dispatcher-PP5OKOLS.js +0 -21
  73. package/dist/ingest-HEXVIAL6.js +0 -19
  74. package/dist/quality-VKQUCL66.js +0 -24
  75. package/dist/retrieval-4MEIABHC.js +0 -14
  76. package/dist/tasks-7SE6VHSQ.js.map +0 -1
  77. /package/dist/{chunk-JYWURG5T.js.map → cleanup-KXCEVJ7V.js.map} +0 -0
  78. /package/dist/{cleanup-RTL2UETA.js.map → dispatcher-GHC6RX54.js.map} +0 -0
  79. /package/dist/{dispatcher-PP5OKOLS.js.map → embeddings-GYQBZWBD.js.map} +0 -0
  80. /package/dist/{embeddings-MILTROKW.js.map → ingest-6GDZNYCY.js.map} +0 -0
  81. /package/dist/{ingest-HEXVIAL6.js.map → keychain-TKPVUZCH.js.map} +0 -0
  82. /package/dist/{keychain-5KXUHKMF.js.map → memory-value-A4UCC3DY.js.map} +0 -0
  83. /package/dist/{memory-value-WXI2Q6TO.js.map → quality-TQ7CVPRO.js.map} +0 -0
  84. /package/dist/{quality-VKQUCL66.js.map → retrieval-7R5LKJAM.js.map} +0 -0
  85. /package/dist/{retrieval-4MEIABHC.js.map → store-QKP6HQ45.js.map} +0 -0
  86. /package/dist/{store-5C7ZKKZF.js.map → tasks-M5HSQSWK.js.map} +0 -0
@@ -11,7 +11,7 @@ import {
11
11
  listInjectedHistoryIdsForSession,
12
12
  signalOutcomeFallback,
13
13
  startSessionLifecycle
14
- } from "./chunk-4UHRAQFG.js";
14
+ } from "./chunk-ZECQ2LQB.js";
15
15
  import {
16
16
  detectCorrections,
17
17
  isHighRiskRule,
@@ -19,7 +19,7 @@ import {
19
19
  isWorkspaceRootAlias,
20
20
  peekTasks,
21
21
  redactSensitiveText
22
- } from "./chunk-TA4WSV6A.js";
22
+ } from "./chunk-VZ456OCO.js";
23
23
  import {
24
24
  detectAndRecordRetrievalMissesSemantic,
25
25
  listInjectedMemoryIdsForSession,
@@ -27,182 +27,40 @@ import {
27
27
  pathMatchesMemory,
28
28
  recordCompletionUseValueEventsSemantic,
29
29
  toolCallTouchesMemory
30
- } from "./chunk-ZXCKMEJA.js";
30
+ } from "./chunk-RRNELZJV.js";
31
31
  import {
32
32
  textMatches
33
- } from "./chunk-FHEH6QDU.js";
33
+ } from "./chunk-PQOGHXET.js";
34
34
  import {
35
35
  hookCallDedupeKey,
36
+ isGeneratedCaptureContext,
36
37
  queryMemories
37
- } from "./chunk-NAYFAUSM.js";
38
+ } from "./chunk-LCIVSUQO.js";
38
39
  import {
39
40
  desc
40
- } from "./chunk-CW3XJDH7.js";
41
+ } from "./chunk-FDIV6YFT.js";
41
42
  import {
42
43
  tagActivitySource
43
- } from "./chunk-ZBQGZCFL.js";
44
+ } from "./chunk-KF3EGZWM.js";
44
45
  import {
45
46
  and,
46
47
  eq,
47
48
  hookCalls,
48
49
  sql
49
- } from "./chunk-LUIYWYOT.js";
50
-
51
- // src/backups/snapshot.ts
50
+ } from "./chunk-VI6NOUXB.js";
52
51
  import {
53
- chmodSync,
54
- constants,
55
- copyFileSync,
56
- existsSync,
57
- lstatSync,
58
- mkdirSync,
59
- readdirSync,
60
- renameSync,
61
- rmSync,
62
- statSync,
63
- unlinkSync
64
- } from "fs";
65
- import { randomUUID } from "crypto";
66
- import { basename, dirname, join } from "path";
67
- var DEFAULT_BACKUP_RETENTION = 2;
68
- var DEFAULT_ONE_OFF_BACKUP_MAX_AGE_DAYS = 30;
69
- var DAILY_BACKUP_RE = /^recall-(\d{4}-\d{2}-\d{2})\.db$/;
70
- var BACKUP_FILE_RE = /\.db(\.|$)/;
71
- function getBackupsDir(dbPath = getDbPath()) {
72
- const dir = join(dirname(dbPath), "backups");
73
- mkdirSync(dir, { recursive: true });
74
- return dir;
75
- }
76
- function todayStamp(now = /* @__PURE__ */ new Date()) {
77
- const y = now.getUTCFullYear();
78
- const m = String(now.getUTCMonth() + 1).padStart(2, "0");
79
- const d = String(now.getUTCDate()).padStart(2, "0");
80
- return `${y}-${m}-${d}`;
81
- }
82
- function ensureDailyBackup(options = {}) {
83
- const dbPath = options.dbPath ?? getDbPath();
84
- const retention = Math.max(1, options.retention ?? DEFAULT_BACKUP_RETENTION);
85
- const oneOffMaxAgeDays = Math.max(
86
- 0,
87
- options.one_off_max_age_days ?? DEFAULT_ONE_OFF_BACKUP_MAX_AGE_DAYS
88
- );
89
- const result = { created: null, retained: [], removed: [] };
90
- if (!existsSync(dbPath)) return result;
91
- const dir = getBackupsDir(dbPath);
92
- const stamp = todayStamp(options.now);
93
- const target = join(dir, `recall-${stamp}.db`);
94
- if (!existsSync(target)) {
95
- atomicCopyFile(dbPath, target);
96
- result.created = target;
97
- } else if (!isRegularFileWithoutSymlink(target)) {
98
- throw new Error(`Refusing unsafe backup path: ${target}`);
99
- }
100
- const all = readdirSync(dir).filter((name) => BACKUP_FILE_RE.test(name)).filter((name) => isRegularFileWithoutSymlink(join(dir, name))).map((name) => ({ name, path: join(dir, name), mtime: statSync(join(dir, name)).mtimeMs }));
101
- const entries = all.filter((entry) => DAILY_BACKUP_RE.test(entry.name)).sort((a, b) => b.mtime - a.mtime);
102
- result.retained = entries.slice(0, retention).map((e) => e.path);
103
- for (const drop of entries.slice(retention)) {
104
- rmSync(drop.path, { force: true });
105
- result.removed.push(drop.path);
106
- }
107
- if (oneOffMaxAgeDays > 0) {
108
- const cutoff = (options.now?.getTime() ?? Date.now()) - oneOffMaxAgeDays * 864e5;
109
- for (const entry of all) {
110
- if (DAILY_BACKUP_RE.test(entry.name)) continue;
111
- if (entry.path === result.created) continue;
112
- if (entry.mtime >= cutoff) {
113
- result.retained.push(entry.path);
114
- continue;
115
- }
116
- rmSync(entry.path, { force: true });
117
- result.removed.push(entry.path);
118
- }
119
- }
120
- return result;
121
- }
122
- function listBackups(dbPath = getDbPath()) {
123
- const dir = getBackupsDir(dbPath);
124
- if (!existsSync(dir)) return [];
125
- return readdirSync(dir).map((name) => {
126
- if (!BACKUP_FILE_RE.test(name)) return null;
127
- const path = join(dir, name);
128
- if (!isRegularFileWithoutSymlink(path)) return null;
129
- const stat = statSync(path);
130
- const match = name.match(DAILY_BACKUP_RE);
131
- return {
132
- date: match ? match[1] : new Date(stat.mtimeMs).toISOString().slice(0, 10),
133
- path,
134
- size_bytes: stat.size,
135
- kind: match ? "daily" : "one_off"
136
- };
137
- }).filter((v) => v !== null).sort((a, b) => b.date.localeCompare(a.date));
138
- }
139
- function restoreBackup(date, options = {}) {
140
- validateBackupDate(date);
141
- const dbPath = options.dbPath ?? getDbPath();
142
- const dir = getBackupsDir(dbPath);
143
- const from = join(dir, `recall-${date}.db`);
144
- if (!existsSync(from)) {
145
- return { restored: false, from, to: dbPath };
146
- }
147
- if (!isRegularFileWithoutSymlink(from)) {
148
- throw new Error(`Refusing unsafe backup path: ${from}`);
149
- }
150
- for (const suffix of ["-shm", "-wal"]) {
151
- const sidecar = `${dbPath}${suffix}`;
152
- if (existsSync(sidecar)) rmSync(sidecar, { force: true });
153
- }
154
- atomicCopyFile(from, dbPath);
155
- return { restored: true, from, to: dbPath };
156
- }
157
- function validateBackupDate(date) {
158
- if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
159
- throw new Error("Backup date must use YYYY-MM-DD");
160
- }
161
- const parsed = /* @__PURE__ */ new Date(`${date}T00:00:00.000Z`);
162
- if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
163
- throw new Error("Backup date is not a real calendar date");
164
- }
165
- }
166
- function isRegularFileWithoutSymlink(path) {
167
- try {
168
- const stat = lstatSync(path);
169
- return stat.isFile() && !stat.isSymbolicLink();
170
- } catch {
171
- return false;
172
- }
173
- }
174
- function atomicCopyFile(source, target) {
175
- if (!isRegularFileWithoutSymlink(source)) {
176
- throw new Error(`Refusing unsafe backup source: ${source}`);
177
- }
178
- const temp = join(
179
- dirname(target),
180
- `.${basename(target)}.${process.pid}.${randomUUID()}.tmp`
181
- );
182
- try {
183
- copyFileSync(source, temp, constants.COPYFILE_EXCL);
184
- chmodSync(temp, 384);
185
- renameSync(temp, target);
186
- } catch (error) {
187
- try {
188
- unlinkSync(temp);
189
- } catch (cleanupError) {
190
- if (!(cleanupError instanceof Error) || !("code" in cleanupError) || cleanupError.code !== "ENOENT") {
191
- throw cleanupError;
192
- }
193
- }
194
- throw error;
195
- }
196
- }
52
+ init_define_RECALL_BUILD_INFO
53
+ } from "./chunk-5W3CDNJ6.js";
197
54
 
198
55
  // src/hooks/calls.ts
199
- import { randomUUID as randomUUID2 } from "crypto";
56
+ init_define_RECALL_BUILD_INFO();
57
+ import { randomUUID } from "crypto";
200
58
  function recordHookCall(db, input) {
201
59
  if (input.dedupe_key) {
202
60
  const existingId = findHookCallByDedupeKey(db, input.dedupe_key);
203
61
  if (existingId) return existingId;
204
62
  }
205
- const id = randomUUID2();
63
+ const id = randomUUID();
206
64
  const result = db.insert(hookCalls).values({
207
65
  id,
208
66
  event: input.event,
@@ -251,9 +109,10 @@ function getHookCallStats(db, query = {}) {
251
109
  }
252
110
 
253
111
  // src/cli/hook.ts
112
+ init_define_RECALL_BUILD_INFO();
254
113
  import { performance } from "perf_hooks";
255
114
  var DEFAULT_DAEMON_ORIGIN = `http://127.0.0.1:${process.env.RECALL_PORT ?? "7890"}`;
256
- var DEFAULT_DAEMON_TIMEOUT_MS = 25;
115
+ var DEFAULT_DAEMON_TIMEOUT_MS = 15e3;
257
116
  var MAX_PROMPT_TEXT_LENGTH = 8192;
258
117
  var MAX_ASSISTANT_COMPLETION_LENGTH = 8192;
259
118
  var MAX_PREV_ASSISTANT_LENGTH = 2048;
@@ -404,7 +263,8 @@ async function handlePromptHook(input, opts = {}) {
404
263
  submitted_at: (/* @__PURE__ */ new Date()).toISOString()
405
264
  }
406
265
  });
407
- await resolvePendingInjectionOutcomesOnPrompt(
266
+ const userAuthored = !isGeneratedCaptureContext(text);
267
+ if (userAuthored) await resolvePendingInjectionOutcomesOnPrompt(
408
268
  db,
409
269
  sessionId,
410
270
  text,
@@ -412,7 +272,7 @@ async function handlePromptHook(input, opts = {}) {
412
272
  recentToolCalls
413
273
  );
414
274
  const correctionMatches = detectCorrections(text);
415
- if (correctionMatches.length > 0) {
275
+ if (userAuthored && correctionMatches.length > 0) {
416
276
  await detectAndRecordRetrievalMissesSemantic(db, {
417
277
  correction_texts: correctionMatches.map((match) => match.text),
418
278
  prompt_text: text,
@@ -435,12 +295,21 @@ async function handlePromptHook(input, opts = {}) {
435
295
  }, source);
436
296
  }
437
297
  const promptInjectionEnabled = process.env.RECALL_HOOK_INJECT_PROMPT !== "false";
438
- const injection = repo && promptInjectionEnabled ? await collectInjectionSurface(db, {
298
+ const injection = repo && promptInjectionEnabled && userAuthored ? await collectInjectionSurface(db, {
439
299
  repo,
440
300
  path: input.path,
441
301
  session_id: sessionId,
442
302
  query_text: text
443
303
  }) : void 0;
304
+ if (repo && injection) {
305
+ recordInjectionEmission(db, {
306
+ session_id: sessionId,
307
+ repo,
308
+ path: input.path,
309
+ source,
310
+ injection
311
+ });
312
+ }
444
313
  return {
445
314
  event: "prompt_submitted",
446
315
  session_id: sessionId,
@@ -594,6 +463,15 @@ async function handleSessionStartHook(input, opts = {}) {
594
463
  session_id: result.session_id,
595
464
  config: SESSION_START_INJECTION_CONFIG
596
465
  }) : void 0;
466
+ if (result.repo && injection) {
467
+ recordInjectionEmission(db, {
468
+ session_id: result.session_id,
469
+ repo: result.repo,
470
+ path: input.path,
471
+ source: resolveHookSource(opts.source, input.agent),
472
+ injection
473
+ });
474
+ }
597
475
  return {
598
476
  event: "session_started",
599
477
  session_id: result.session_id,
@@ -680,6 +558,24 @@ ${surface.text}`;
680
558
  return `${lead}
681
559
  ${body}`.trimEnd();
682
560
  }
561
+ function recordInjectionEmission(db, input) {
562
+ createActivityEvent(db, {
563
+ session_id: input.session_id,
564
+ repo: input.repo,
565
+ path: input.path ?? null,
566
+ source: input.source,
567
+ event_type: "session_event",
568
+ memory_ids: [...input.injection.memories_included],
569
+ request: { name: "memory_emitted" },
570
+ result: {
571
+ memory_count: input.injection.memories_included.length,
572
+ history_count: input.injection.history_included.length,
573
+ token_estimate: input.injection.token_estimate,
574
+ emitted_at: (/* @__PURE__ */ new Date()).toISOString(),
575
+ delivery_verified: false
576
+ }
577
+ });
578
+ }
683
579
  async function collectInjectionSurface(db, req) {
684
580
  if (process.env.RECALL_HOOK_INJECT_CONTEXT === "false") return void 0;
685
581
  const base = {
@@ -901,7 +797,7 @@ async function postHookToDaemon(path, body, opts) {
901
797
  const controller = new AbortController();
902
798
  const timeout = setTimeout(
903
799
  () => controller.abort(),
904
- opts.daemonTimeoutMs ?? DEFAULT_DAEMON_TIMEOUT_MS
800
+ opts.daemonTimeoutMs ?? hookDaemonTimeoutMs()
905
801
  );
906
802
  try {
907
803
  const response = await fetch(`${origin}${path}`, {
@@ -929,6 +825,11 @@ async function postHookToDaemon(path, body, opts) {
929
825
  clearTimeout(timeout);
930
826
  }
931
827
  }
828
+ function hookDaemonTimeoutMs(value = process.env.RECALL_HOOK_DAEMON_TIMEOUT_MS) {
829
+ if (!value) return DEFAULT_DAEMON_TIMEOUT_MS;
830
+ const parsed = Number.parseInt(value, 10);
831
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_DAEMON_TIMEOUT_MS;
832
+ }
932
833
  async function withHookTelemetry(db, event, agent, dedupe, run) {
933
834
  const startedAt = performance.now();
934
835
  try {
@@ -1107,7 +1008,7 @@ function extractClaudeToolPath(toolInput) {
1107
1008
  return void 0;
1108
1009
  }
1109
1010
  function resolveRepo(repo, repoPath) {
1110
- const resolved = repo?.trim() || inferRepoSlugFromPath(repoPath) || null;
1011
+ const resolved = repo?.trim() || process.env.RECALL_REPO_OVERRIDE?.trim() || inferRepoSlugFromPath(repoPath) || null;
1111
1012
  return isWorkspaceRootAlias(resolved) ? null : resolved;
1112
1013
  }
1113
1014
  function requireNonEmpty(value, field) {
@@ -1166,10 +1067,244 @@ async function safeJson(response) {
1166
1067
  }
1167
1068
  }
1168
1069
 
1070
+ // src/backups/snapshot.ts
1071
+ init_define_RECALL_BUILD_INFO();
1072
+ import {
1073
+ chmodSync,
1074
+ constants,
1075
+ copyFileSync,
1076
+ existsSync,
1077
+ lstatSync,
1078
+ mkdirSync,
1079
+ readFileSync,
1080
+ readdirSync,
1081
+ renameSync,
1082
+ rmSync,
1083
+ statSync,
1084
+ unlinkSync
1085
+ } from "fs";
1086
+ import { randomUUID as randomUUID2 } from "crypto";
1087
+ import { basename, dirname, join } from "path";
1088
+ import Database from "better-sqlite3";
1089
+ var DEFAULT_BACKUP_RETENTION = 2;
1090
+ var DEFAULT_INSTALL_BACKUP_RETENTION = 1;
1091
+ var DEFAULT_ONE_OFF_BACKUP_MAX_AGE_DAYS = 30;
1092
+ var DAILY_BACKUP_RE = /^recall-(\d{4}-\d{2}-\d{2})\.db$/;
1093
+ var BACKUP_FILE_RE = /\.db(\.|$)/;
1094
+ var INSTALL_BACKUP_DIR_RE = /^published-\d+\.\d+\.\d+-/;
1095
+ function getBackupsDir(dbPath = getDbPath()) {
1096
+ const dir = join(dirname(dbPath), "backups");
1097
+ mkdirSync(dir, { recursive: true });
1098
+ return dir;
1099
+ }
1100
+ function todayStamp(now = /* @__PURE__ */ new Date()) {
1101
+ const y = now.getUTCFullYear();
1102
+ const m = String(now.getUTCMonth() + 1).padStart(2, "0");
1103
+ const d = String(now.getUTCDate()).padStart(2, "0");
1104
+ return `${y}-${m}-${d}`;
1105
+ }
1106
+ function ensureDailyBackup(options = {}) {
1107
+ const dbPath = options.dbPath ?? getDbPath();
1108
+ const retention = Math.max(1, options.retention ?? DEFAULT_BACKUP_RETENTION);
1109
+ const oneOffMaxAgeDays = Math.max(
1110
+ 0,
1111
+ options.one_off_max_age_days ?? DEFAULT_ONE_OFF_BACKUP_MAX_AGE_DAYS
1112
+ );
1113
+ const installRetention = Math.max(
1114
+ 1,
1115
+ options.install_retention ?? DEFAULT_INSTALL_BACKUP_RETENTION
1116
+ );
1117
+ const result = { created: null, retained: [], removed: [] };
1118
+ if (!existsSync(dbPath)) return result;
1119
+ const dir = getBackupsDir(dbPath);
1120
+ const stamp = todayStamp(options.now);
1121
+ const target = join(dir, `recall-${stamp}.db`);
1122
+ if (!existsSync(target)) {
1123
+ atomicSnapshotFile(dbPath, target);
1124
+ result.created = target;
1125
+ } else if (!isRegularFileWithoutSymlink(target)) {
1126
+ throw new Error(`Refusing unsafe backup path: ${target}`);
1127
+ }
1128
+ const all = readdirSync(dir).filter((name) => BACKUP_FILE_RE.test(name)).filter((name) => isRegularFileWithoutSymlink(join(dir, name))).map((name) => ({ name, path: join(dir, name), mtime: statSync(join(dir, name)).mtimeMs }));
1129
+ const entries = all.filter((entry) => DAILY_BACKUP_RE.test(entry.name)).sort((a, b) => b.mtime - a.mtime);
1130
+ result.retained = entries.slice(0, retention).map((e) => e.path);
1131
+ for (const drop of entries.slice(retention)) {
1132
+ rmSync(drop.path, { force: true });
1133
+ result.removed.push(drop.path);
1134
+ }
1135
+ const installEntries = listInstallBackupDirectories(dir);
1136
+ for (const keep of installEntries.slice(0, installRetention)) {
1137
+ result.retained.push(keep.path);
1138
+ }
1139
+ for (const drop of installEntries.slice(installRetention)) {
1140
+ rmSync(drop.directory, { recursive: true, force: true });
1141
+ result.removed.push(drop.directory);
1142
+ }
1143
+ if (oneOffMaxAgeDays > 0) {
1144
+ const cutoff = (options.now?.getTime() ?? Date.now()) - oneOffMaxAgeDays * 864e5;
1145
+ for (const entry of all) {
1146
+ if (DAILY_BACKUP_RE.test(entry.name)) continue;
1147
+ if (entry.path === result.created) continue;
1148
+ if (entry.mtime >= cutoff) {
1149
+ result.retained.push(entry.path);
1150
+ continue;
1151
+ }
1152
+ rmSync(entry.path, { force: true });
1153
+ result.removed.push(entry.path);
1154
+ }
1155
+ }
1156
+ return result;
1157
+ }
1158
+ function listBackups(dbPath = getDbPath()) {
1159
+ const dir = getBackupsDir(dbPath);
1160
+ if (!existsSync(dir)) return [];
1161
+ const flat = readdirSync(dir).map((name) => {
1162
+ if (!BACKUP_FILE_RE.test(name)) return null;
1163
+ const path = join(dir, name);
1164
+ if (!isRegularFileWithoutSymlink(path)) return null;
1165
+ const stat = statSync(path);
1166
+ const match = name.match(DAILY_BACKUP_RE);
1167
+ return {
1168
+ date: match ? match[1] : new Date(stat.mtimeMs).toISOString().slice(0, 10),
1169
+ path,
1170
+ size_bytes: stat.size,
1171
+ kind: match ? "daily" : "one_off"
1172
+ };
1173
+ }).filter((v) => v !== null);
1174
+ const installs = listInstallBackupDirectories(dir).map((entry) => ({
1175
+ date: new Date(entry.mtime).toISOString().slice(0, 10),
1176
+ path: entry.path,
1177
+ size_bytes: statSync(entry.path).size,
1178
+ kind: "install"
1179
+ }));
1180
+ return [...flat, ...installs].sort((a, b) => b.date.localeCompare(a.date));
1181
+ }
1182
+ function listInstallBackupDirectories(dir) {
1183
+ return readdirSync(dir).filter((name) => INSTALL_BACKUP_DIR_RE.test(name)).map((name) => {
1184
+ const directory = join(dir, name);
1185
+ const path = join(directory, "recall.db");
1186
+ if (!isDirectoryWithoutSymlink(directory) || !isRegularFileWithoutSymlink(path) || !isSqliteDatabase(path)) {
1187
+ return null;
1188
+ }
1189
+ return { directory, path, mtime: statSync(path).mtimeMs };
1190
+ }).filter((entry) => entry !== null).sort((a, b) => b.mtime - a.mtime);
1191
+ }
1192
+ function verifyBackupIntegrity(path) {
1193
+ if (!isRegularFileWithoutSymlink(path) || !isSqliteDatabase(path)) return false;
1194
+ const sqlite = new Database(path, { readonly: true, fileMustExist: true });
1195
+ try {
1196
+ return sqlite.pragma("quick_check", { simple: true }) === "ok";
1197
+ } finally {
1198
+ sqlite.close();
1199
+ }
1200
+ }
1201
+ function restoreBackup(date, options = {}) {
1202
+ validateBackupDate(date);
1203
+ const dbPath = options.dbPath ?? getDbPath();
1204
+ const dir = getBackupsDir(dbPath);
1205
+ const from = join(dir, `recall-${date}.db`);
1206
+ if (!existsSync(from)) {
1207
+ return { restored: false, from, to: dbPath };
1208
+ }
1209
+ if (!isRegularFileWithoutSymlink(from)) {
1210
+ throw new Error(`Refusing unsafe backup path: ${from}`);
1211
+ }
1212
+ for (const suffix of ["-shm", "-wal"]) {
1213
+ const sidecar = `${dbPath}${suffix}`;
1214
+ if (existsSync(sidecar)) rmSync(sidecar, { force: true });
1215
+ }
1216
+ atomicCopyFile(from, dbPath);
1217
+ return { restored: true, from, to: dbPath };
1218
+ }
1219
+ function validateBackupDate(date) {
1220
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
1221
+ throw new Error("Backup date must use YYYY-MM-DD");
1222
+ }
1223
+ const parsed = /* @__PURE__ */ new Date(`${date}T00:00:00.000Z`);
1224
+ if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
1225
+ throw new Error("Backup date is not a real calendar date");
1226
+ }
1227
+ }
1228
+ function isRegularFileWithoutSymlink(path) {
1229
+ try {
1230
+ const stat = lstatSync(path);
1231
+ return stat.isFile() && !stat.isSymbolicLink();
1232
+ } catch {
1233
+ return false;
1234
+ }
1235
+ }
1236
+ function isDirectoryWithoutSymlink(path) {
1237
+ try {
1238
+ const stat = lstatSync(path);
1239
+ return stat.isDirectory() && !stat.isSymbolicLink();
1240
+ } catch {
1241
+ return false;
1242
+ }
1243
+ }
1244
+ function atomicCopyFile(source, target) {
1245
+ if (!isRegularFileWithoutSymlink(source)) {
1246
+ throw new Error(`Refusing unsafe backup source: ${source}`);
1247
+ }
1248
+ const temp = join(
1249
+ dirname(target),
1250
+ `.${basename(target)}.${process.pid}.${randomUUID2()}.tmp`
1251
+ );
1252
+ try {
1253
+ copyFileSync(source, temp, constants.COPYFILE_EXCL);
1254
+ chmodSync(temp, 384);
1255
+ renameSync(temp, target);
1256
+ } catch (error) {
1257
+ try {
1258
+ unlinkSync(temp);
1259
+ } catch (cleanupError) {
1260
+ if (!(cleanupError instanceof Error) || !("code" in cleanupError) || cleanupError.code !== "ENOENT") {
1261
+ throw cleanupError;
1262
+ }
1263
+ }
1264
+ throw error;
1265
+ }
1266
+ }
1267
+ function atomicSnapshotFile(source, target) {
1268
+ if (!isSqliteDatabase(source)) {
1269
+ atomicCopyFile(source, target);
1270
+ return;
1271
+ }
1272
+ if (!isRegularFileWithoutSymlink(source)) {
1273
+ throw new Error(`Refusing unsafe backup source: ${source}`);
1274
+ }
1275
+ const temp = join(
1276
+ dirname(target),
1277
+ `.${basename(target)}.${process.pid}.${randomUUID2()}.tmp`
1278
+ );
1279
+ const sqlite = new Database(source, { readonly: true, fileMustExist: true });
1280
+ try {
1281
+ sqlite.prepare("VACUUM INTO ?").run(temp);
1282
+ const snapshot = new Database(temp, { readonly: true, fileMustExist: true });
1283
+ try {
1284
+ if (snapshot.pragma("quick_check", { simple: true }) !== "ok") {
1285
+ throw new Error(`SQLite backup integrity check failed: ${target}`);
1286
+ }
1287
+ } finally {
1288
+ snapshot.close();
1289
+ }
1290
+ chmodSync(temp, 384);
1291
+ renameSync(temp, target);
1292
+ } catch (error) {
1293
+ rmSync(temp, { force: true });
1294
+ throw error;
1295
+ } finally {
1296
+ sqlite.close();
1297
+ }
1298
+ }
1299
+ function isSqliteDatabase(path) {
1300
+ try {
1301
+ return readFileSync(path).subarray(0, 16).toString("utf8") === "SQLite format 3\0";
1302
+ } catch {
1303
+ return false;
1304
+ }
1305
+ }
1306
+
1169
1307
  export {
1170
- ensureDailyBackup,
1171
- listBackups,
1172
- restoreBackup,
1173
1308
  getHookCallStats,
1174
1309
  executePromptHook,
1175
1310
  executeToolHook,
@@ -1194,6 +1329,10 @@ export {
1194
1329
  readCodexToolInputFromStdin,
1195
1330
  readCodexSessionStartInputFromStdin,
1196
1331
  readCodexSessionEndInputFromStdin,
1197
- dispatchCodexNotify
1332
+ dispatchCodexNotify,
1333
+ ensureDailyBackup,
1334
+ listBackups,
1335
+ verifyBackupIntegrity,
1336
+ restoreBackup
1198
1337
  };
1199
- //# sourceMappingURL=chunk-7CFX774S.js.map
1338
+ //# sourceMappingURL=chunk-SWPXUPMX.js.map