engine7 7.1.132 → 7.1.136

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 (42) hide show
  1. package/README.md +1 -0
  2. package/dist/auth-server.mjs +632 -0
  3. package/dist/bg-worker.mjs +32198 -28733
  4. package/dist/cc-desktop.mjs +951 -0
  5. package/dist/cli.mjs +41391 -29912
  6. package/dist/engine-startup.mjs +68176 -54684
  7. package/dist/main.mjs +54090 -40596
  8. package/dist/recall-worker.mjs +20443 -0
  9. package/dist/sqlite-maintenance-worker.mjs +1163 -124
  10. package/dist/stop-history-worker.mjs +180 -0
  11. package/dist/topics-worker.mjs +3350 -1078
  12. package/dist/travel-authority.mjs +1068 -0
  13. package/dist/travel-console.mjs +2205 -0
  14. package/dist/travel-controller.mjs +1883 -0
  15. package/dist/travel-data.mjs +7250 -0
  16. package/dist/travel-gateway.mjs +3258 -0
  17. package/dist/travel-key-service.mjs +483 -0
  18. package/dist/travel-node-data.mjs +4930 -0
  19. package/dist/travel-node.mjs +21233 -0
  20. package/dist/travel-retire.mjs +1094 -0
  21. package/dist/web-console.mjs +2425 -0
  22. package/package.json +32 -17
  23. package/templates/config.template.json +45 -0
  24. package/templates/skills/auth-connect/SKILL.md +22 -0
  25. package/templates/skills/email/SKILL.md +119 -115
  26. package/templates/skills/email/scripts/email-config-path.test.js +52 -0
  27. package/templates/skills/email/scripts/email-config.d.ts +4 -0
  28. package/templates/skills/email/scripts/email-config.js +6 -3
  29. package/templates/skills/pptx/SKILL.md +5 -0
  30. package/templates/skills/pptx/assets/engine7-aurora/field.png +0 -0
  31. package/templates/skills/pptx/assets/engine7-aurora/hero.png +0 -0
  32. package/templates/skills/pptx/assets/engine7-aurora/wordmark.png +0 -0
  33. package/templates/skills/pptx/examples/engine7-aurora.cjs +190 -0
  34. package/templates/skills/pptx/package-lock.json +171 -0
  35. package/templates/skills/pptx/package.json +12 -0
  36. package/templates/skills/pptx/scripts/engine7-aurora.cjs +132 -0
  37. package/templates/skills/pptx/styles/engine7-aurora.md +136 -0
  38. package/templates/skills/pptx/tests/engine7-aurora.test.cjs +116 -0
  39. package/templates/workspace/AGENTS.md +2 -9
  40. package/templates/workspace/RULES.md +22 -0
  41. package/templates/workspace/hooks/loop-detector.mjs +37 -0
  42. package/templates/workspace/souls/unnamed.md +10 -0
@@ -9,6 +9,381 @@ var __export = (target, all) => {
9
9
  __defProp(target, name, { get: all[name], enumerable: true });
10
10
  };
11
11
 
12
+ // src/continuity/runtime-authority.ts
13
+ import { randomUUID, verify } from "node:crypto";
14
+ import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
15
+ import { basename, dirname, join, resolve } from "node:path";
16
+ function assertPrivateDirectory(path2) {
17
+ const stat = lstatSync(path2);
18
+ if (!stat.isDirectory() || stat.isSymbolicLink() || process.platform !== "win32" && (stat.uid !== process.getuid() || stat.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
19
+ }
20
+ function readPrivateFile(path2, maximum) {
21
+ const before = lstatSync(path2);
22
+ if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
23
+ const fd = openSync(path2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
24
+ try {
25
+ if (fstatSync(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
26
+ return readFileSync(fd);
27
+ } finally {
28
+ closeSync(fd);
29
+ }
30
+ }
31
+ function writeControl(path2, value) {
32
+ const temporary = path2 + "." + randomUUID() + ".tmp";
33
+ writeFileSync(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
34
+ renameSync(temporary, path2);
35
+ if (process.platform !== "win32") {
36
+ const fd = openSync(dirname(path2), "r");
37
+ try {
38
+ fsyncSync(fd);
39
+ } finally {
40
+ closeSync(fd);
41
+ }
42
+ }
43
+ }
44
+ function runtimeAuthorityFor(stateDir) {
45
+ for (let root = resolve(stateDir); ; ) {
46
+ const existing = runtimes.get(root);
47
+ if (existing) return existing;
48
+ const file = join(root, ".continuity", "travel-runtime.json");
49
+ if (existsSync(file)) {
50
+ const enrollment = JSON.parse(readPrivateFile(file, 16384).toString());
51
+ if (enrollment.format !== "engine7-travel-runtime-v1") throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
52
+ return new RuntimeAuthority({ stateDir: root, ...enrollment });
53
+ }
54
+ if (existsSync(join(root, ".travel-active.json")) || existsSync(join(root, ".travel-enrolled.json"))) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
55
+ const parent = dirname(root);
56
+ if (parent === root) return null;
57
+ root = parent;
58
+ }
59
+ }
60
+ function assertRuntimeAuthority(stateDir, operation) {
61
+ const root = stateDir || process.env.ENGINE7_TRAVEL_STATE_DIR || process.env.ENGINE_STATE_DIR;
62
+ if (root) runtimeAuthorityFor(root)?.assert(operation);
63
+ }
64
+ var runtimes, now, equal, RuntimeAuthority;
65
+ var init_runtime_authority = __esm({
66
+ "src/continuity/runtime-authority.ts"() {
67
+ "use strict";
68
+ runtimes = /* @__PURE__ */ new Map();
69
+ now = () => Number(process.hrtime.bigint() / 1000000n);
70
+ equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
71
+ RuntimeAuthority = class {
72
+ stateDir;
73
+ enrollment;
74
+ directory;
75
+ clock;
76
+ previous;
77
+ cachedGrant = null;
78
+ cachedFloor = 0;
79
+ constructor(options) {
80
+ this.stateDir = resolve(options.stateDir);
81
+ this.directory = join(this.stateDir, ".continuity");
82
+ this.clock = options.monotonicNow ?? now;
83
+ const tools = options.allowedTools ?? [];
84
+ if (!Array.isArray(tools) || tools.length > 1024 || tools.some((t) => typeof t !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(t))) throw new Error("TRAVEL_INVALID_CAPABILITIES");
85
+ this.enrollment = { format: "engine7-travel-runtime-v1", identity: options.identity, nodeId: options.nodeId, bootId: options.bootId, publicKey: options.publicKey, allowedTools: [...new Set(tools)].sort() };
86
+ if (options.initialize) {
87
+ mkdirSync(this.directory, { mode: 448, recursive: true });
88
+ assertPrivateDirectory(this.directory);
89
+ const file = join(this.directory, "travel-runtime.json");
90
+ if (!existsSync(file)) writeFileSync(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
91
+ const marker = join(this.stateDir, ".travel-enrolled.json");
92
+ if (!existsSync(marker)) writeFileSync(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
93
+ }
94
+ this.checkEnrollment();
95
+ this.previous = runtimes.get(this.stateDir);
96
+ runtimes.set(this.stateDir, this);
97
+ }
98
+ checkEnrollment() {
99
+ try {
100
+ assertPrivateDirectory(this.directory);
101
+ const existing = JSON.parse(readPrivateFile(join(this.directory, "travel-runtime.json"), 16384).toString());
102
+ if (!equal(existing, this.enrollment)) throw new Error("TRAVEL_RUNTIME_IDENTITY_MISMATCH");
103
+ } catch (error) {
104
+ throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED", { cause: error });
105
+ }
106
+ }
107
+ grant() {
108
+ this.checkEnrollment();
109
+ const file = join(this.directory, "travel-permit.json");
110
+ if (!existsSync(file)) return null;
111
+ try {
112
+ const grant = JSON.parse(readPrivateFile(file, 16384).toString());
113
+ if (typeof grant.frozen !== "boolean" || grant.inputPaused !== void 0 && typeof grant.inputPaused !== "boolean" || !Number.isSafeInteger(grant.epoch) || grant.epoch < 1 || !Number.isSafeInteger(grant.leaseSequence) || grant.leaseSequence < 1 || !Number.isFinite(grant.requestStartedAt)) throw new Error();
114
+ return grant;
115
+ } catch (error) {
116
+ throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED", { cause: error });
117
+ }
118
+ }
119
+ writeGrant(grant) {
120
+ this.checkEnrollment();
121
+ writeControl(join(this.directory, "travel-permit.json"), grant);
122
+ this.cachedGrant = grant;
123
+ }
124
+ validatePermit(permit) {
125
+ try {
126
+ const { signature, ...body } = permit;
127
+ if (!verify(null, Buffer.from(JSON.stringify(body)), this.enrollment.publicKey, Buffer.from(signature, "base64"))) throw new Error();
128
+ } catch {
129
+ throw new Error("TRAVEL_INVALID_PERMIT");
130
+ }
131
+ const { identity, nodeId, bootId: bootId2 } = this.enrollment;
132
+ if (permit.nodeId !== nodeId || permit.bootId !== bootId2 || permit.tenantId !== identity.tenantId || permit.companionId !== identity.companionId || permit.seatId !== identity.seatId) throw new Error("TRAVEL_PERMIT_IDENTITY_MISMATCH");
133
+ if (!Number.isSafeInteger(permit.validForMs) || permit.validForMs < 1 || permit.validForMs > 3e5 || !Number.isSafeInteger(permit.epoch) || permit.epoch < 1 || !Number.isSafeInteger(permit.deletionWatermark) || permit.deletionWatermark < 0 || !Number.isSafeInteger(permit.leaseSequence) || permit.leaseSequence < 1) throw new Error("TRAVEL_INVALID_PERMIT");
134
+ }
135
+ acceptPermit(permit, requestStartedAt) {
136
+ this.validatePermit(permit);
137
+ const current2 = this.grant();
138
+ if (current2 && (permit.epoch < current2.epoch || permit.authorityBootId === current2.authorityBootId && permit.leaseSequence <= current2.leaseSequence)) throw new Error("TRAVEL_PERMIT_REPLAY");
139
+ const receivedAt = this.clock();
140
+ if (!Number.isFinite(requestStartedAt) || requestStartedAt > receivedAt || receivedAt >= requestStartedAt + permit.validForMs) throw new Error("TRAVEL_LEASE_EXPIRED");
141
+ this.writeGrant({ permit, requestStartedAt, frozen: current2?.frozen ?? false, inputPaused: current2?.inputPaused ?? false, epoch: permit.epoch, authorityBootId: permit.authorityBootId, leaseSequence: permit.leaseSequence });
142
+ }
143
+ assert(operation, binding) {
144
+ const grant = this.grant();
145
+ if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
146
+ this.validatePermit(grant.permit);
147
+ this.cachedFloor = this.deletionFloor();
148
+ this.cachedGrant = grant;
149
+ return this.assertFast(operation, binding);
150
+ }
151
+ /** Only for a synchronous SQLite capture whose BEGIN and COMMIT re-read the
152
+ * control files. In-transaction rows never publish past a changed barrier. */
153
+ assertFast(operation, binding) {
154
+ const grant = this.cachedGrant;
155
+ if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
156
+ const current2 = this.clock(), deadline = grant.requestStartedAt + grant.permit.validForMs;
157
+ if (current2 < grant.requestStartedAt || current2 >= deadline) throw new Error("TRAVEL_LEASE_EXPIRED");
158
+ if (operation !== "CONTROL" && grant.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
159
+ if (operation === "INPUT" && grant.inputPaused) throw new Error("TRAVEL_INPUT_PAUSED");
160
+ if (operation !== "CONTROL" && grant.permit.deletionWatermark !== this.cachedFloor) throw new Error("TRAVEL_DELETION_BARRIER");
161
+ if (binding && (binding.tenantId !== grant.permit.tenantId || binding.companionId !== grant.permit.companionId || binding.seatId !== grant.permit.seatId || binding.epoch !== grant.permit.epoch)) throw new Error("TRAVEL_STALE_WRITER_EPOCH");
162
+ return grant.permit;
163
+ }
164
+ deletionFloor() {
165
+ const file = join(this.directory, "travel-deletion-floor.json");
166
+ if (!existsSync(file)) return 0;
167
+ const value = JSON.parse(readPrivateFile(file, 128).toString());
168
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
169
+ return value;
170
+ }
171
+ advanceDeletionFloor(floor) {
172
+ if (!Number.isSafeInteger(floor) || floor < this.deletionFloor()) throw new Error("TRAVEL_DELETION_ROLLBACK");
173
+ writeControl(join(this.directory, "travel-deletion-floor.json"), floor);
174
+ this.cachedFloor = floor;
175
+ }
176
+ freeze(frozen) {
177
+ const grant = this.grant();
178
+ if (!grant) throw new Error("TRAVEL_PERMIT_REQUIRED");
179
+ if (grant.permit) this.validatePermit(grant.permit);
180
+ this.writeGrant({ ...grant, frozen });
181
+ }
182
+ pauseInput(paused) {
183
+ if (typeof paused !== "boolean") throw new Error("TRAVEL_INVALID_CONTROL");
184
+ const grant = this.grant();
185
+ if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
186
+ this.validatePermit(grant.permit);
187
+ this.writeGrant({ ...grant, inputPaused: paused });
188
+ }
189
+ revoke() {
190
+ const grant = this.grant();
191
+ if (grant) this.writeGrant({ ...grant, permit: null });
192
+ }
193
+ close() {
194
+ if (runtimes.get(this.stateDir) === this) {
195
+ if (this.previous) runtimes.set(this.stateDir, this.previous);
196
+ else runtimes.delete(this.stateDir);
197
+ }
198
+ }
199
+ };
200
+ }
201
+ });
202
+
203
+ // src/continuity/runtime-lock.ts
204
+ import { randomUUID as randomUUID2 } from "node:crypto";
205
+ import { AsyncLocalStorage } from "node:async_hooks";
206
+ import { closeSync as closeSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, realpathSync } from "node:fs";
207
+ import { join as join2 } from "node:path";
208
+ import { createRequire } from "node:module";
209
+ function openSQLite(file, options = {}) {
210
+ return new (sqlite ??= createRequire(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
211
+ }
212
+ function openControl(stateDir, create = true, busyTimeoutMs = 0) {
213
+ if (create) mkdirSync2(stateDir, { recursive: true });
214
+ const state = realpathSync(stateDir);
215
+ if (process.platform !== "win32" && lstatSync2(state).uid !== process.getuid()) throw new Error("CONTROL_OWNER_MISMATCH: run travel as the engine data owner, without sudo");
216
+ const directory2 = join2(state, ".continuity");
217
+ if (create) mkdirSync2(directory2, { recursive: true, mode: 448 });
218
+ if (lstatSync2(directory2).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_DIRECTORY");
219
+ assertControlPermissions(directory2);
220
+ const file = join2(directory2, "runtime.sqlite");
221
+ if (create) {
222
+ try {
223
+ closeSync2(openSync2(file, "wx", 384));
224
+ } catch (error) {
225
+ if (error.code !== "EEXIST") throw error;
226
+ }
227
+ }
228
+ assertControlPermissions(file);
229
+ for (const name of [file, file + "-journal", file + "-wal", file + "-shm"]) {
230
+ try {
231
+ if (!lstatSync2(name).isFile() || lstatSync2(name).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_FILE");
232
+ } catch (error) {
233
+ if (error.code !== "ENOENT") throw error;
234
+ }
235
+ }
236
+ const db = openSQLite(file);
237
+ try {
238
+ db.exec(`PRAGMA busy_timeout=${busyTimeoutMs}; PRAGMA synchronous=FULL;
239
+ CREATE TABLE IF NOT EXISTS writers (
240
+ id TEXT PRIMARY KEY, pid INTEGER NOT NULL, boot_id TEXT NOT NULL,
241
+ kind TEXT NOT NULL, registered_at TEXT NOT NULL
242
+ )`);
243
+ return db;
244
+ } catch (error) {
245
+ db.close();
246
+ throw normalize(error);
247
+ }
248
+ }
249
+ function assertControlPermissions(file) {
250
+ const info = lstatSync2(file);
251
+ if (process.platform !== "win32" && (info.uid !== process.getuid() || info.mode & 63))
252
+ throw new Error("CONTROL_PERMISSIONS: use the engine data owner; repair .continuity ownership and private permissions while stopped");
253
+ }
254
+ function assertStateDirUsable(stateDir) {
255
+ if (typeof stateDir !== "string" || !stateDir.trim()) throw new Error("RUNTIME_STATE_DIR_REQUIRED");
256
+ try {
257
+ lstatSync2(join2(stateDir, ".travel-restored.json"));
258
+ throw new Error("TRAVEL_ACTIVATION_REQUIRED");
259
+ } catch (error) {
260
+ if (error.code !== "ENOENT") throw error;
261
+ }
262
+ assertRuntimeAuthority(stateDir, "WRITE");
263
+ }
264
+ function normalize(error) {
265
+ return /database is locked|database table is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error)) ? new Error("CHECKPOINT_BUSY", { cause: error }) : error;
266
+ }
267
+ function registerRuntimeWriter(stateDir, kind) {
268
+ assertStateDirUsable(stateDir);
269
+ const recovery = recoveryWriterLocks.getStore();
270
+ if (recovery?.active && recovery.roots.has(realpathSync(stateDir))) return () => {
271
+ };
272
+ const db = openControl(stateDir, true, 1e3), id = randomUUID2();
273
+ try {
274
+ db.exec("BEGIN IMMEDIATE");
275
+ db.prepare("INSERT INTO writers VALUES (?, ?, ?, ?, ?)").run(id, process.pid, bootId, kind, (/* @__PURE__ */ new Date()).toISOString());
276
+ db.exec("COMMIT");
277
+ } catch (error) {
278
+ throw normalize(error);
279
+ } finally {
280
+ db.close();
281
+ }
282
+ let released = false;
283
+ const release = () => {
284
+ if (released) return;
285
+ let control;
286
+ try {
287
+ control = openControl(stateDir, false, 1e3);
288
+ } catch (error) {
289
+ if (error.code !== "ENOENT") throw error;
290
+ released = true;
291
+ releases.delete(release);
292
+ return;
293
+ }
294
+ try {
295
+ control.prepare("DELETE FROM writers WHERE id=? AND boot_id=?").run(id, bootId);
296
+ } finally {
297
+ control.close();
298
+ }
299
+ released = true;
300
+ releases.delete(release);
301
+ };
302
+ releases.add(release);
303
+ if (!exitHookInstalled) {
304
+ exitHookInstalled = true;
305
+ process.once("exit", () => {
306
+ for (const stop of releases) {
307
+ try {
308
+ stop();
309
+ } catch {
310
+ }
311
+ }
312
+ });
313
+ }
314
+ return release;
315
+ }
316
+ var sqlite, bootId, releases, exitHookInstalled, recoveryWriterLocks;
317
+ var init_runtime_lock = __esm({
318
+ "src/continuity/runtime-lock.ts"() {
319
+ "use strict";
320
+ init_runtime_authority();
321
+ bootId = randomUUID2();
322
+ releases = /* @__PURE__ */ new Set();
323
+ exitHookInstalled = false;
324
+ recoveryWriterLocks = new AsyncLocalStorage();
325
+ }
326
+ });
327
+
328
+ // src/continuity/key-service-store.ts
329
+ import { DatabaseSync } from "node:sqlite";
330
+ import { constants as constants2, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync3, closeSync as closeSync3, readFileSync as readFileSync3, writeSync, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync } from "node:fs";
331
+ function assertPrivateStat(stat, directory2) {
332
+ if ((directory2 ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
333
+ throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
334
+ }
335
+ function readPrivateFile2(path2, maximumBytes = 65536) {
336
+ assertPrivateStat(lstatSync3(path2), false);
337
+ const fd = openSync3(path2, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
338
+ try {
339
+ const stat = fstatSync2(fd);
340
+ assertPrivateStat(stat, false);
341
+ if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
342
+ return readFileSync3(fd);
343
+ } finally {
344
+ closeSync3(fd);
345
+ }
346
+ }
347
+ var init_key_service_store = __esm({
348
+ "src/continuity/key-service-store.ts"() {
349
+ "use strict";
350
+ }
351
+ });
352
+
353
+ // src/continuity/publication-objects.ts
354
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
355
+ import {
356
+ constants as constants3,
357
+ openSync as openSync4,
358
+ closeSync as closeSync4,
359
+ fstatSync as fstatSync3,
360
+ fsyncSync as fsyncSync3,
361
+ readSync,
362
+ writeSync as writeSync2,
363
+ lstatSync as lstatSync4,
364
+ realpathSync as realpathSync2,
365
+ mkdirSync as mkdirSync4,
366
+ readFileSync as readFileSync4,
367
+ writeFileSync as writeFileSync2,
368
+ linkSync,
369
+ unlinkSync as unlinkSync2
370
+ } from "node:fs";
371
+ import { join as join3, dirname as dirname2, resolve as resolve2 } from "node:path";
372
+ function assertPrivateDirectory2(path2) {
373
+ const info = lstatSync4(path2);
374
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path2) !== resolve2(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
375
+ throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
376
+ }
377
+ var PUBLICATION_CHUNK_BYTES, MAGIC, noFollow;
378
+ var init_publication_objects = __esm({
379
+ "src/continuity/publication-objects.ts"() {
380
+ "use strict";
381
+ PUBLICATION_CHUNK_BYTES = 1024 * 1024;
382
+ MAGIC = Buffer.from("E7P1");
383
+ noFollow = constants3.O_NOFOLLOW ?? 0;
384
+ }
385
+ });
386
+
12
387
  // src/memory/schema-migrations.ts
13
388
  function authorizeMemoryWriter(db, supportedVersion) {
14
389
  db.function("engine_memory_writer_version", () => supportedVersion);
@@ -28,39 +403,410 @@ var init_schema_migrations = __esm({
28
403
  }
29
404
  });
30
405
 
406
+ // src/continuity/legacy-sqlite-indexes.ts
407
+ var init_legacy_sqlite_indexes = __esm({
408
+ "src/continuity/legacy-sqlite-indexes.ts"() {
409
+ "use strict";
410
+ init_schema_migrations();
411
+ }
412
+ });
413
+
414
+ // src/continuity/sqlite-replication.ts
415
+ import { createHash } from "node:crypto";
416
+ function bindingText(binding) {
417
+ if (!binding || ["tenantId", "companionId", "seatId", "databaseId", "baselineId"].some((k) => typeof binding[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(String(binding[k]))) || !Number.isSafeInteger(binding.epoch) || binding.epoch < 1) throw new Error("REPLICATION_INVALID_BINDING");
418
+ return JSON.stringify([binding.tenantId, binding.companionId, binding.seatId, binding.databaseId, binding.baselineId, binding.epoch]);
419
+ }
420
+ function normalizeBinding(binding) {
421
+ const [tenantId, companionId, seatId, databaseId, baselineId, epoch] = JSON.parse(bindingText(binding));
422
+ return Object.freeze({ tenantId, companionId, seatId, databaseId, baselineId, epoch });
423
+ }
424
+ function readSQLiteReplicationSource(db) {
425
+ if (!validateMetadata(db)) return null;
426
+ const rows = db.prepare("SELECT role,binding,schema_hash FROM e7_replication_control").all();
427
+ if (rows.length !== 1 || rows[0].role !== "source") throw new Error("REPLICATION_SOURCE_REQUIRED");
428
+ const row = rows[0];
429
+ try {
430
+ const fields = JSON.parse(String(row.binding));
431
+ if (!Array.isArray(fields) || fields.length !== 6 || !digestPattern.test(String(row.schema_hash))) throw new Error();
432
+ const [tenantId, companionId, seatId, databaseId, baselineId, epoch] = fields;
433
+ return { binding: normalizeBinding({ tenantId, companionId, seatId, databaseId, baselineId, epoch }), schemaHash: String(row.schema_hash) };
434
+ } catch {
435
+ throw new Error("REPLICATION_REGISTRATION_INVALID");
436
+ }
437
+ }
438
+ function schemaRows(db) {
439
+ return db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_master WHERE sql IS NOT NULL AND name NOT GLOB 'sqlite_*' ORDER BY type,name").all().filter((r) => !metadataTables.has(r.tbl_name) && !r.name.startsWith(guardPrefix));
440
+ }
441
+ function sqliteReplicationSchemaHash(db) {
442
+ return hash(JSON.stringify(schemaRows(db)));
443
+ }
444
+ function validateMetadata(db) {
445
+ const rows = db.prepare("SELECT name,type FROM sqlite_master WHERE name IN (?,?,?)").all(...metadataTables);
446
+ if (!rows.length) return false;
447
+ if (rows.length !== metadataTables.size || rows.some((row) => row.type !== "table"))
448
+ throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: new Error("incomplete replication metadata") });
449
+ for (const [table, expected] of Object.entries(metadataColumns)) {
450
+ const columns = db.prepare(`PRAGMA table_xinfo(${identifier(table)})`).all();
451
+ if (columns.length !== expected.length || columns.some((column, index) => {
452
+ const [name, type, notnull, pk] = expected[index];
453
+ return column.name !== name || String(column.type).toUpperCase() !== type || Number(column.notnull) !== notnull || Number(column.pk) !== pk || Number(column.hidden) !== 0 || column.dflt_value !== null;
454
+ })) throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: new Error("invalid replication metadata " + table) });
455
+ }
456
+ return true;
457
+ }
458
+ var metadataTables, metadataColumns, guardPrefix, identifier, hash, digestPattern;
459
+ var init_sqlite_replication = __esm({
460
+ "src/continuity/sqlite-replication.ts"() {
461
+ "use strict";
462
+ init_legacy_sqlite_indexes();
463
+ init_runtime_authority();
464
+ metadataTables = /* @__PURE__ */ new Set(["e7_replication_control", "e7_replication_outbox", "e7_replication_inbox"]);
465
+ metadataColumns = {
466
+ e7_replication_control: [
467
+ ["role", "TEXT", 0, 1],
468
+ ["binding", "TEXT", 1, 0],
469
+ ["schema_hash", "TEXT", 1, 0],
470
+ ["head", "INTEGER", 1, 0],
471
+ ["digest", "TEXT", 1, 0],
472
+ ["ack_seq", "INTEGER", 1, 0],
473
+ ["ack_digest", "TEXT", 1, 0],
474
+ ["pending_bytes", "INTEGER", 1, 0]
475
+ ],
476
+ e7_replication_outbox: [
477
+ ["sequence", "INTEGER", 0, 1],
478
+ ["parent_digest", "TEXT", 1, 0],
479
+ ["changeset", "BLOB", 1, 0],
480
+ ["sequences", "TEXT", 1, 0],
481
+ ["digest", "TEXT", 1, 0]
482
+ ],
483
+ e7_replication_inbox: [
484
+ ["sequence", "INTEGER", 0, 1],
485
+ ["parent_digest", "TEXT", 1, 0],
486
+ ["changeset", "BLOB", 0, 0],
487
+ ["sequences", "TEXT", 1, 0],
488
+ ["digest", "TEXT", 1, 0],
489
+ ["state", "TEXT", 1, 0]
490
+ ]
491
+ };
492
+ guardPrefix = "writer_guard_replication_";
493
+ identifier = (s) => '"' + s.replaceAll('"', '""') + '"';
494
+ hash = (s) => createHash("sha256").update(s).digest("hex");
495
+ digestPattern = /^[a-f0-9]{64}$/;
496
+ }
497
+ });
498
+
499
+ // src/continuity/mem7-replication.ts
500
+ import { closeSync as closeSync5, fsyncSync as fsyncSync4, lstatSync as lstatSync5, openSync as openSync5, writeFileSync as writeFileSync3 } from "node:fs";
501
+ import { dirname as dirname3, join as join4 } from "node:path";
502
+ function normalize2(value) {
503
+ if (!value || !/^[a-f0-9]{64}$/.test(value.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
504
+ return Object.freeze({ binding: normalizeBinding(value.binding), schemaHash: value.schemaHash });
505
+ }
506
+ function hasMem7ReplicationRegistration(stateDir) {
507
+ try {
508
+ lstatSync5(location(stateDir));
509
+ return true;
510
+ } catch (error) {
511
+ if (error.code === "ENOENT") return false;
512
+ throw error;
513
+ }
514
+ }
515
+ function readMem7ReplicationRegistration(stateDir) {
516
+ if (!hasMem7ReplicationRegistration(stateDir)) return null;
517
+ try {
518
+ assertPrivateDirectory2(dirname3(location(stateDir)));
519
+ return normalize2(JSON.parse(readPrivateFile2(location(stateDir), 4096).toString()));
520
+ } catch {
521
+ throw new Error("REPLICATION_REGISTRATION_INVALID");
522
+ }
523
+ }
524
+ var location;
525
+ var init_mem7_replication = __esm({
526
+ "src/continuity/mem7-replication.ts"() {
527
+ "use strict";
528
+ init_key_service_store();
529
+ init_publication_objects();
530
+ init_sqlite_replication();
531
+ location = (stateDir) => join4(stateDir, ".continuity", "mem7-replication.json");
532
+ }
533
+ });
534
+
535
+ // src/continuity/runtime-replication.ts
536
+ import { constants as constants4, lstatSync as lstatSync6, realpathSync as realpathSync3, mkdirSync as mkdirSync5, openSync as openSync6, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4, fsyncSync as fsyncSync5 } from "node:fs";
537
+ import { basename as basename2, dirname as dirname4, join as join5, resolve as resolve3 } from "node:path";
538
+ function checkKey(component, key) {
539
+ if (component === "topics-vectors" && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) return;
540
+ if (component === "legacy-memory" && typeof key === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key) && !/[. ]$/.test(key) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key)) return;
541
+ if (["calendar", "proactive", "session-events"].includes(component) && key === void 0) return;
542
+ throw new Error("REPLICATION_REGISTRATION_INVALID");
543
+ }
544
+ function location2(stateDir, component, key) {
545
+ checkKey(component, key);
546
+ return join5(stateDir, ".continuity", component + (key === void 0 ? "" : "-" + key) + "-replication.json");
547
+ }
548
+ function runtimeReplicationFile(stateDir, component, key) {
549
+ checkKey(component, key);
550
+ if (component === "legacy-memory") return join5(stateDir, "agents", key, "memory", "memory.db");
551
+ if (component === "topics-vectors") return join5(stateDir, "topics-history", key, "vectors.db");
552
+ if (component === "session-events") return join5(stateDir, ".continuity", "session-events.db");
553
+ return join5(stateDir, "." + component, component + ".db");
554
+ }
555
+ function runtimeReplicationLocation(stateDir, component, file) {
556
+ const key = component === "legacy-memory" ? basename2(dirname4(dirname4(file))) : component === "topics-vectors" ? basename2(dirname4(file)) : void 0;
557
+ try {
558
+ if (resolve3(file) !== resolve3(runtimeReplicationFile(stateDir, component, key))) throw new Error();
559
+ } catch (error) {
560
+ throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED", { cause: error });
561
+ }
562
+ return { component, ...key === void 0 ? {} : { key } };
563
+ }
564
+ function normalize3(input) {
565
+ if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
566
+ return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
567
+ }
568
+ function directory(path2) {
569
+ const info = lstatSync6(path2);
570
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync3(path2) !== resolve3(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
571
+ throw new Error("REPLICATION_REGISTRATION_INVALID");
572
+ }
573
+ function readRuntimeReplicationRegistration(stateDir, component, key) {
574
+ const file = location2(stateDir, component, key);
575
+ try {
576
+ lstatSync6(dirname4(file));
577
+ } catch (error) {
578
+ if (error.code === "ENOENT") return null;
579
+ throw error;
580
+ }
581
+ directory(dirname4(file));
582
+ let fd;
583
+ try {
584
+ fd = openSync6(file, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
585
+ } catch (error) {
586
+ if (error.code === "ENOENT") return null;
587
+ throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
588
+ }
589
+ try {
590
+ const info = fstatSync4(fd);
591
+ if (!info.isFile() || info.size > 4096 || realpathSync3(file) !== resolve3(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
592
+ return normalize3(JSON.parse(readFileSync5(fd, "utf8")));
593
+ } catch (error) {
594
+ throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
595
+ } finally {
596
+ closeSync6(fd);
597
+ }
598
+ }
599
+ function checkRuntimeReplicationFile(file, registration, initial = false) {
600
+ if (!registration && !initial) return;
601
+ try {
602
+ let info;
603
+ try {
604
+ info = lstatSync6(file);
605
+ } catch (error) {
606
+ if (registration || !initial || error.code !== "ENOENT") throw error;
607
+ let parent = dirname4(resolve3(file));
608
+ for (; ; ) {
609
+ try {
610
+ const existing = lstatSync6(parent);
611
+ if (!existing.isDirectory() || existing.isSymbolicLink() || realpathSync3(parent) !== parent) throw new Error();
612
+ return;
613
+ } catch (error2) {
614
+ if (error2.code !== "ENOENT") throw error2;
615
+ parent = dirname4(parent);
616
+ }
617
+ }
618
+ }
619
+ if (!info.isFile() || info.isSymbolicLink() || realpathSync3(file) !== resolve3(file)) throw new Error();
620
+ } catch (error) {
621
+ throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: error });
622
+ }
623
+ }
624
+ var init_runtime_replication = __esm({
625
+ "src/continuity/runtime-replication.ts"() {
626
+ "use strict";
627
+ init_schema_migrations();
628
+ init_sqlite_replication();
629
+ }
630
+ });
631
+
31
632
  // src/memory/topics-cleaning/materials.ts
32
- import { createHash, randomUUID } from "node:crypto";
33
- import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
34
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
633
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
634
+ import { existsSync as existsSync2, lstatSync as lstatSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync5 } from "node:fs";
635
+ import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute2, join as join7, relative as relative2, resolve as resolve7, sep as sep2 } from "node:path";
35
636
  function canonical(value) {
36
637
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
37
638
  if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
38
639
  return JSON.stringify(value);
39
640
  }
40
- function safeRelative(path) {
41
- return typeof path === "string" && !!path && !isAbsolute(path) && !/[:\\\x00-\x1f]/.test(path) && path.split("/").every((p) => p && p !== "." && p !== "..");
641
+ function safeRelative(path2) {
642
+ return typeof path2 === "string" && !!path2 && !isAbsolute2(path2) && !/[:\\\x00-\x1f]/.test(path2) && path2.split("/").every((p) => p && p !== "." && p !== "..");
42
643
  }
43
- function unlinked(path) {
44
- let cursor = resolve(path);
644
+ function unlinked(path2) {
645
+ let cursor = resolve7(path2);
45
646
  for (; ; ) {
46
647
  try {
47
- if (lstatSync(cursor).isSymbolicLink()) throw new Error("SYMLINK_PATH");
648
+ if (lstatSync8(cursor).isSymbolicLink()) throw new Error("SYMLINK_PATH");
48
649
  } catch (e) {
49
650
  if (e.code !== "ENOENT") throw e;
50
651
  }
51
- const parent = dirname(cursor);
52
- if (parent === cursor) return resolve(path);
652
+ const parent = dirname6(cursor);
653
+ if (parent === cursor) return resolve7(path2);
53
654
  cursor = parent;
54
655
  }
55
656
  }
56
- function readJson(path) {
57
- return JSON.parse(readFileSync(unlinked(path), "utf8").replace(/^\uFEFF/, ""));
657
+ function readJson(path2) {
658
+ return JSON.parse(readFileSync6(unlinked(path2), "utf8").replace(/^\uFEFF/, ""));
58
659
  }
59
660
  var digest;
60
661
  var init_materials = __esm({
61
662
  "src/memory/topics-cleaning/materials.ts"() {
62
663
  "use strict";
63
- digest = (value) => createHash("sha256").update(value).digest("hex");
664
+ digest = (value) => createHash2("sha256").update(value).digest("hex");
665
+ }
666
+ });
667
+
668
+ // src/continuity/sqlite-autocommit.ts
669
+ var init_sqlite_autocommit = __esm({
670
+ "src/continuity/sqlite-autocommit.ts"() {
671
+ "use strict";
672
+ }
673
+ });
674
+
675
+ // src/config/writer.ts
676
+ import fs from "node:fs";
677
+ import path from "node:path";
678
+ function isNormalized(text) {
679
+ if (text === "") return true;
680
+ if (text.includes("\r")) return false;
681
+ let minIndent = Infinity;
682
+ for (const line of text.split("\n")) {
683
+ const m = /^( +)\S/.exec(line);
684
+ if (!m) continue;
685
+ const width = m[1].length;
686
+ if (width % 2 !== 0) return false;
687
+ if (width < minIndent) minIndent = width;
688
+ }
689
+ return minIndent === 2 || minIndent === Infinity;
690
+ }
691
+ function rotateBaks(filePath) {
692
+ const dir = path.dirname(filePath);
693
+ const base = path.basename(filePath);
694
+ const baks = fs.readdirSync(dir).filter((n) => n.startsWith(base + ".bak-")).sort();
695
+ while (baks.length >= KEEP_BAKS) {
696
+ const victim = baks.shift();
697
+ try {
698
+ fs.unlinkSync(path.join(dir, victim));
699
+ } catch {
700
+ }
701
+ }
702
+ }
703
+ function sleepSync(ms) {
704
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
705
+ }
706
+ function errCode(err) {
707
+ return err?.code ?? "";
708
+ }
709
+ function writeFailure(filePath, primary, extra) {
710
+ const code = errCode(primary);
711
+ const reason = RETRYABLE_CODES.has(code) ? `\u76EE\u6807\u6587\u4EF6\u88AB\u5360\u7528\u6216\u4E0D\u53EF\u5199\uFF08${code}\uFF09\u2014\u2014\u8BF7\u5173\u95ED\u6B63\u5728\u4F7F\u7528\u5B83\u7684\u7A0B\u5E8F\uFF08\u7F16\u8F91\u5668\u3001\u6740\u6BD2\u3001\u540C\u6B65\u76D8\u7B49\uFF09\u540E\u91CD\u8BD5` : `\u5199\u5165\u5931\u8D25${code ? `\uFF08${code}\uFF09` : ""}\uFF1A${primary?.message ?? String(primary)}`;
712
+ return new ConfigWriteError(`\u65E0\u6CD5\u5199\u5165 ${filePath}\uFF1A${reason}${extra ? `\uFF1B${extra}` : ""}`, code, primary);
713
+ }
714
+ function renameWithRetry(from, to) {
715
+ for (let attempt = 1; ; attempt++) {
716
+ try {
717
+ fs.renameSync(from, to);
718
+ return;
719
+ } catch (err) {
720
+ if (attempt >= RENAME_ATTEMPTS || !RETRYABLE_CODES.has(errCode(err))) throw err;
721
+ sleepSync(RENAME_RETRY_MS);
722
+ }
723
+ }
724
+ }
725
+ function commitFile(tmp, filePath) {
726
+ try {
727
+ renameWithRetry(tmp, filePath);
728
+ return;
729
+ } catch (primaryErr) {
730
+ const old = `${filePath}.old`;
731
+ try {
732
+ fs.renameSync(filePath, old);
733
+ } catch (err) {
734
+ throw writeFailure(filePath, primaryErr, `\u6539\u540D .old \u5907\u4EFD\u4E5F\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
735
+ }
736
+ try {
737
+ fs.renameSync(tmp, filePath);
738
+ } catch (err) {
739
+ try {
740
+ fs.renameSync(old, filePath);
741
+ } catch {
742
+ throw writeFailure(filePath, primaryErr, `\u65B0\u5185\u5BB9\u843D\u76D8\u4E0E\u56DE\u6EDA\u90FD\u5931\u8D25\uFF0C\u65E7\u5185\u5BB9\u7559\u5728 ${old}`);
743
+ }
744
+ throw writeFailure(filePath, primaryErr, `\u6362\u540D\u843D\u76D8\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
745
+ }
746
+ try {
747
+ fs.unlinkSync(old);
748
+ } catch {
749
+ }
750
+ }
751
+ }
752
+ function writeConfigAtomic(filePath, obj) {
753
+ const existed = fs.existsSync(filePath);
754
+ let prevText = "";
755
+ let fileMode;
756
+ if (existed) {
757
+ try {
758
+ prevText = fs.readFileSync(filePath, "utf-8");
759
+ fileMode = fs.statSync(filePath).mode & 511;
760
+ } catch (err) {
761
+ throw writeFailure(filePath, err);
762
+ }
763
+ }
764
+ const normalized = !existed || !isNormalized(prevText);
765
+ if (prevText) {
766
+ try {
767
+ fs.copyFileSync(filePath, `${filePath}.bak-${Date.now()}`);
768
+ } catch {
769
+ }
770
+ rotateBaks(filePath);
771
+ }
772
+ const content = JSON.stringify(obj, null, 2) + "\n";
773
+ const tmp = path.join(path.dirname(filePath), `.${path.basename(filePath)}.tmp-${process.pid}`);
774
+ try {
775
+ const fd = fs.openSync(tmp, "w", fileMode);
776
+ try {
777
+ if (fileMode !== void 0) fs.fchmodSync(fd, fileMode);
778
+ fs.writeFileSync(fd, content, "utf-8");
779
+ fs.fsyncSync(fd);
780
+ } finally {
781
+ fs.closeSync(fd);
782
+ }
783
+ commitFile(tmp, filePath);
784
+ } catch (err) {
785
+ throw err instanceof ConfigWriteError ? err : writeFailure(filePath, err);
786
+ } finally {
787
+ try {
788
+ fs.unlinkSync(tmp);
789
+ } catch {
790
+ }
791
+ }
792
+ return { normalized };
793
+ }
794
+ var KEEP_BAKS, RENAME_ATTEMPTS, RENAME_RETRY_MS, RETRYABLE_CODES, ConfigWriteError;
795
+ var init_writer = __esm({
796
+ "src/config/writer.ts"() {
797
+ "use strict";
798
+ KEEP_BAKS = 3;
799
+ RENAME_ATTEMPTS = 5;
800
+ RENAME_RETRY_MS = 50;
801
+ RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
802
+ ConfigWriteError = class extends Error {
803
+ code;
804
+ constructor(message, code, cause) {
805
+ super(message, { cause });
806
+ this.name = "ConfigWriteError";
807
+ this.code = code;
808
+ }
809
+ };
64
810
  }
65
811
  });
66
812
 
@@ -72,6 +818,7 @@ var LiveConfigClass, liveConfig, selfWrite;
72
818
  var init_live = __esm({
73
819
  "src/config/live.ts"() {
74
820
  "use strict";
821
+ init_writer();
75
822
  LiveConfigClass = class {
76
823
  current = null;
77
824
  /** 启动时注入(替代 registry.config = config) */
@@ -120,7 +867,7 @@ var init_live = __esm({
120
867
  * "免费档补齐 xxx" 的成功日志 ⇒ 配置**没写进文件**却被读成"写好了":进程内生效、托盘
121
868
  * 读文件还是旧值、下次启动重放同一句——正是本仓最恨的假信号。
122
869
  */
123
- async set(dotPath, val) {
870
+ async set(dotPath, val, options) {
124
871
  if (!this.current) throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
125
872
  const keys = dotPath.split(".");
126
873
  const dangerous = keys.find((k) => k === "__proto__" || k === "constructor" || k === "prototype");
@@ -131,18 +878,18 @@ var init_live = __esm({
131
878
  obj = obj[keys[i]];
132
879
  }
133
880
  obj[keys[keys.length - 1]] = val;
134
- return this.persistToFile(dotPath, val);
881
+ return this.persistToFile(dotPath, val, options?.atomic === true);
135
882
  }
136
883
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
137
- async persistToFile(dotPath, val) {
138
- const fs = await import("node:fs");
884
+ async persistToFile(dotPath, val, atomic = false) {
885
+ const fs2 = await import("node:fs");
139
886
  const cfgPath = this.current?._configFilePath;
140
- if (!cfgPath || !fs.existsSync(cfgPath)) {
887
+ if (!cfgPath || !fs2.existsSync(cfgPath)) {
141
888
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
142
889
  return false;
143
890
  }
144
891
  try {
145
- const raw = JSON.parse(fs.readFileSync(cfgPath, "utf-8"));
892
+ const raw = JSON.parse(fs2.readFileSync(cfgPath, "utf-8"));
146
893
  const keys = dotPath.split(".");
147
894
  let o = raw;
148
895
  for (let i = 0; i < keys.length - 1; i++) {
@@ -150,7 +897,9 @@ var init_live = __esm({
150
897
  o = o[keys[i]];
151
898
  }
152
899
  o[keys[keys.length - 1]] = val;
153
- fs.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
900
+ if (atomic) {
901
+ writeConfigAtomic(cfgPath, raw);
902
+ } else fs2.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
154
903
  const lastKey = keys[keys.length - 1].toLowerCase();
155
904
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
156
905
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -172,11 +921,19 @@ var init_live = __esm({
172
921
  }
173
922
  });
174
923
 
924
+ // src/time/wall-parts.ts
925
+ var init_wall_parts = __esm({
926
+ "src/time/wall-parts.ts"() {
927
+ "use strict";
928
+ }
929
+ });
930
+
175
931
  // src/time/clock.ts
176
932
  var init_clock = __esm({
177
933
  "src/time/clock.ts"() {
178
934
  "use strict";
179
935
  init_live();
936
+ init_wall_parts();
180
937
  }
181
938
  });
182
939
 
@@ -197,12 +954,12 @@ var init_scope = __esm({
197
954
 
198
955
  // src/mem7/core/state/temporal.ts
199
956
  function canonicalJson(value) {
200
- const normalize = (input) => {
201
- if (Array.isArray(input)) return input.map(normalize);
202
- if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, normalize(entry)]));
957
+ const normalize4 = (input) => {
958
+ if (Array.isArray(input)) return input.map(normalize4);
959
+ if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, normalize4(entry)]));
203
960
  return input;
204
961
  };
205
- const json = JSON.stringify(normalize(value));
962
+ const json = JSON.stringify(normalize4(value));
206
963
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
207
964
  return json;
208
965
  }
@@ -301,8 +1058,8 @@ var init_dependencies = __esm({
301
1058
  });
302
1059
 
303
1060
  // src/mem7/core/change-feed.ts
304
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
305
- import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
1061
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
1062
+ import { existsSync as existsSync3, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync6 } from "node:fs";
306
1063
  function isBusyError(error) {
307
1064
  if (!error || typeof error !== "object") return false;
308
1065
  if (error.errcode === 5) return true;
@@ -326,7 +1083,7 @@ function appendMemoryChange(db, input, requestKey) {
326
1083
  sourceIds: [...new Set(input.sourceIds)].sort(),
327
1084
  ...input.changedEntityIds ? { changedEntityIds: [...new Set(input.changedEntityIds)].sort() } : {}
328
1085
  };
329
- const eventId = `evt_${createHash2("sha256").update(canonicalJson([input.scopeId, input.kind, requestKey])).digest("hex")}`;
1086
+ const eventId = `evt_${createHash3("sha256").update(canonicalJson([input.scopeId, input.kind, requestKey])).digest("hex")}`;
330
1087
  const previous = db.prepare("SELECT payload_json FROM memory_state_outbox WHERE event_id=?").get(eventId);
331
1088
  if (previous) {
332
1089
  const event2 = JSON.parse(previous.payload_json);
@@ -387,7 +1144,7 @@ var init_change_feed = __esm({
387
1144
  SELECT ?,event_id,scope_id FROM memory_state_outbox WHERE rowid>? AND rowid<=?`).run(sinkId, watermark.seq, max);
388
1145
  this.db.prepare("UPDATE memory_projection_sink_watermarks SET seq=? WHERE sink_id=?").run(max, sinkId);
389
1146
  }
390
- pending(sinkId, limit = 50, now = Date.now()) {
1147
+ pending(sinkId, limit = 50, now2 = Date.now()) {
391
1148
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) throw new Error("INVALID_DELIVERY_LIMIT");
392
1149
  this.register(sinkId);
393
1150
  const rows = this.db.prepare(`WITH heads AS (
@@ -398,7 +1155,7 @@ var init_change_feed = __esm({
398
1155
  JOIN memory_state_outbox event ON event.scope_id=heads.scope_id AND event.event_seq=heads.event_seq
399
1156
  JOIN memory_projection_deliveries delivery ON delivery.event_id=event.event_id AND delivery.sink_id=?
400
1157
  WHERE delivery.next_run_at<=?
401
- ORDER BY event.created_at,event.scope_id,event.event_seq LIMIT ?`).all(sinkId, sinkId, now, limit);
1158
+ ORDER BY event.created_at,event.scope_id,event.event_seq LIMIT ?`).all(sinkId, sinkId, now2, limit);
402
1159
  return rows.map((row) => JSON.parse(row.payload_json));
403
1160
  }
404
1161
  pendingWindow(sinkId, head, limit) {
@@ -423,9 +1180,9 @@ var init_change_feed = __esm({
423
1180
  return true;
424
1181
  });
425
1182
  }
426
- retry(sinkId, eventId, reason, now = Date.now()) {
1183
+ retry(sinkId, eventId, reason, now2 = Date.now()) {
427
1184
  this.db.prepare(`UPDATE memory_projection_deliveries SET attempts=attempts+1,last_error=?,
428
- next_run_at=?+MIN(300000,1000*(1 << MIN(attempts,8))) WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(reason.slice(0, 300), now, sinkId, eventId);
1185
+ next_run_at=?+MIN(300000,1000*(1 << MIN(attempts,8))) WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(reason.slice(0, 300), now2, sinkId, eventId);
429
1186
  }
430
1187
  /** 1027 小柯事故自愈:迁移/换新图(图 inbox 全新、position=0)撞上生产端带 ack 前缀 →
431
1188
  * 队头永久 PROJECTION_SEQUENCE_GAP,投递与死信 skip 同检连坐、零进展直到人工介入。
@@ -435,14 +1192,14 @@ var init_change_feed = __esm({
435
1192
  * 回滚后的生产端,只能人工重放。死信行复活时保留 attempts(妹妹 review P2-5:已知毒
436
1193
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
437
1194
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
438
- reenqueueGapPrefix(sinkId, head, now = Date.now()) {
1195
+ reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
439
1196
  const key = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
440
1197
  if (this.healedGaps.has(key)) return;
441
1198
  const ledgerPath = this.gapHealLedgerPath;
442
1199
  let ledger = {};
443
1200
  if (ledgerPath) {
444
1201
  try {
445
- ledger = JSON.parse(readFileSync2(ledgerPath, "utf8"))?.heals ?? {};
1202
+ ledger = JSON.parse(readFileSync7(ledgerPath, "utf8"))?.heals ?? {};
446
1203
  } catch {
447
1204
  }
448
1205
  if (Number.isFinite(ledger[key])) {
@@ -462,25 +1219,25 @@ var init_change_feed = __esm({
462
1219
  });
463
1220
  this.healedGaps.add(key);
464
1221
  if (!ledgerPath) return;
465
- const cutoff = now - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
1222
+ const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
466
1223
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
467
- retained[key] = now;
468
- const temp = `${ledgerPath}.${randomUUID2()}.tmp`;
1224
+ retained[key] = now2;
1225
+ const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
469
1226
  try {
470
- writeFileSync2(temp, JSON.stringify({ version: 1, heals: retained }));
471
- renameSync2(temp, ledgerPath);
1227
+ writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
1228
+ renameSync3(temp, ledgerPath);
472
1229
  } catch (error) {
473
1230
  try {
474
- if (existsSync2(temp)) unlinkSync(temp);
1231
+ if (existsSync3(temp)) unlinkSync3(temp);
475
1232
  } catch {
476
1233
  }
477
1234
  console.warn(`[mem7] \u7F3A\u53E3\u81EA\u6108\u8D26\u672C\u5199\u5165\u5931\u8D25\uFF08\u672C\u8FDB\u7A0B\u5185\u4ECD\u53BB\u91CD\uFF0C\u91CD\u542F\u540E\u53EF\u80FD\u591A\u6CBB\u4E00\u6B21\uFF0C\u5E42\u7B49\u65E0\u5BB3\uFF09\uFF1A${error.message}`);
478
1235
  }
479
1236
  }
480
1237
  /** busy:只推后下次到期,attempts 不动(死信预算只留给真失败)。 */
481
- retryTransient(sinkId, eventId, now) {
1238
+ retryTransient(sinkId, eventId, now2) {
482
1239
  this.db.prepare(`UPDATE memory_projection_deliveries SET last_error='SQLITE_BUSY',next_run_at=?
483
- WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(now + _ChangeFeed.BUSY_RETRY_MS, sinkId, eventId);
1240
+ WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(now2 + _ChangeFeed.BUSY_RETRY_MS, sinkId, eventId);
484
1241
  }
485
1242
  /** 满次数转死信终态(置 acked_at 解除队头阻塞),返回是否已转。must be head-of-line:
486
1243
  * pending() 只出同 scope 队头,走到这里的失败事件前面不存在未 ack 事件,直接置终态
@@ -488,7 +1245,7 @@ var init_change_feed = __esm({
488
1245
  * 1020 astra review P1:生产端终态 ≠ 消费者序号已前进——onDead(消费者 skip 协议)
489
1246
  * 必须先落库再置终态,否则同 scope 后续正常事件全部 PROJECTION_SEQUENCE_GAP 连坐。
490
1247
  * skip 失败 = 不死信、下轮重试(此时 attempts 已超帽,每轮退避重试 skip,响亮留痕)。 */
491
- async deadLetter(sinkId, event, reason, now, onDead) {
1248
+ async deadLetter(sinkId, event, reason, now2, onDead) {
492
1249
  const row = this.db.prepare("SELECT attempts FROM memory_projection_deliveries WHERE sink_id=? AND event_id=?").get(sinkId, event.eventId);
493
1250
  if (!row || Number(row.attempts) + 1 < _ChangeFeed.DEAD_LETTER_ATTEMPTS) return false;
494
1251
  if (onDead) {
@@ -504,7 +1261,7 @@ var init_change_feed = __esm({
504
1261
  }
505
1262
  this.transaction(() => {
506
1263
  this.db.prepare(`UPDATE memory_projection_deliveries SET attempts=attempts+1,last_error=?,acked_at=?,next_run_at=?
507
- WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(`dead:${reason.slice(0, 290)}`, new Date(now).toISOString(), now, sinkId, event.eventId);
1264
+ WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(`dead:${reason.slice(0, 290)}`, new Date(now2).toISOString(), now2, sinkId, event.eventId);
508
1265
  });
509
1266
  console.warn(`[mem7] delivery dead-lettered ${event.kind} ${event.eventId.slice(0, 24)} after ${_ChangeFeed.DEAD_LETTER_ATTEMPTS} attempts: ${reason}\uFF08\u91CD\u653E\uFF1A\u6682\u505C\u6295\u9012\u5E76\u4FEE\u597D\u6839\u56E0\uFF0C\u91CD\u7F6E\u540C sink/scope \u4ECE seq=${event.eventSeq} \u8D77\u7684\u5168\u90E8\u6295\u9012\u884C\uFF0C\u5220\u540C scope \u8BE5\u6BB5 inbox \u6536\u636E\uFF0Cposition \u56DE\u9000\u81F3 ${event.eventSeq - 1}\uFF1B\u4FDD\u7559 heads \u5E76\u6309\u5E8F\u6062\u590D\uFF09`);
510
1267
  return true;
@@ -518,21 +1275,21 @@ var init_change_feed = __esm({
518
1275
  return { pending: Number(row.pending ?? 0), delivered: Number(row.delivered ?? 0), failed: Number(row.failed ?? 0) };
519
1276
  }
520
1277
  async deliver(sinkId, receive, options = {}) {
521
- const now = options.now ?? Date.now();
1278
+ const now2 = options.now ?? Date.now();
522
1279
  const limit = options.limit ?? 100;
523
1280
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) throw new Error("INVALID_DELIVERY_LIMIT");
524
1281
  let delivered = 0;
525
1282
  let attempted = 0;
526
1283
  const blockedScopes = /* @__PURE__ */ new Set();
527
1284
  while (attempted < limit) {
528
- const pending = this.pending(sinkId, limit, now).filter((event) => !blockedScopes.has(event.scopeId));
1285
+ const pending = this.pending(sinkId, limit, now2).filter((event) => !blockedScopes.has(event.scopeId));
529
1286
  if (!pending.length) break;
530
1287
  const perScope = Math.max(1, Math.floor((limit - attempted) / pending.length));
531
1288
  const windows = pending.map((head) => this.pendingWindow(sinkId, head, perScope));
532
1289
  const batch = Array.from({ length: perScope }, (_, index) => windows.flatMap((window) => window[index] ? [window[index]] : [])).flat();
533
1290
  for (const { event, dueAt } of batch) {
534
1291
  if (blockedScopes.has(event.scopeId)) continue;
535
- if (dueAt > now) {
1292
+ if (dueAt > now2) {
536
1293
  blockedScopes.add(event.scopeId);
537
1294
  continue;
538
1295
  }
@@ -543,11 +1300,11 @@ var init_change_feed = __esm({
543
1300
  } catch (error) {
544
1301
  const reason = deliveryReasonCode(error);
545
1302
  if (isBusyError(error)) {
546
- this.retryTransient(sinkId, event.eventId, now);
1303
+ this.retryTransient(sinkId, event.eventId, now2);
547
1304
  } else {
548
1305
  console.warn(`[mem7] delivery failed ${event.kind} ${event.eventId.slice(0, 24)}: ${reason} ${(error instanceof Error ? error.message : String(error)).slice(0, 300)}`);
549
1306
  if (reason === "PROJECTION_SEQUENCE_GAP") this.reenqueueGapPrefix(sinkId, event);
550
- if (!await this.deadLetter(sinkId, event, reason, now, options.onDead)) this.retry(sinkId, event.eventId, reason, now);
1307
+ if (!await this.deadLetter(sinkId, event, reason, now2, options.onDead)) this.retry(sinkId, event.eventId, reason, now2);
551
1308
  }
552
1309
  blockedScopes.add(event.scopeId);
553
1310
  }
@@ -575,6 +1332,13 @@ var init_interpretation_impact = __esm({
575
1332
  }
576
1333
  });
577
1334
 
1335
+ // src/mem7/core/conversation-text.ts
1336
+ var init_conversation_text = __esm({
1337
+ "src/mem7/core/conversation-text.ts"() {
1338
+ "use strict";
1339
+ }
1340
+ });
1341
+
578
1342
  // src/mem7/core/source-store.ts
579
1343
  var init_source_store = __esm({
580
1344
  "src/mem7/core/source-store.ts"() {
@@ -585,6 +1349,7 @@ var init_source_store = __esm({
585
1349
  init_knowledge_history();
586
1350
  init_read_budget();
587
1351
  init_interpretation_impact();
1352
+ init_conversation_text();
588
1353
  }
589
1354
  });
590
1355
 
@@ -595,23 +1360,39 @@ var init_schema = __esm({
595
1360
  }
596
1361
  });
597
1362
 
1363
+ // src/continuity/recovery-deletion-sources.ts
1364
+ var init_recovery_deletion_sources = __esm({
1365
+ "src/continuity/recovery-deletion-sources.ts"() {
1366
+ "use strict";
1367
+ }
1368
+ });
1369
+
1370
+ // src/continuity/recovery-deletion.ts
1371
+ var init_recovery_deletion = __esm({
1372
+ "src/continuity/recovery-deletion.ts"() {
1373
+ "use strict";
1374
+ init_recovery_deletion_sources();
1375
+ }
1376
+ });
1377
+
598
1378
  // src/mem7/core/state/tombstones.ts
599
1379
  var init_tombstones = __esm({
600
1380
  "src/mem7/core/state/tombstones.ts"() {
601
1381
  "use strict";
602
1382
  init_scope();
603
1383
  init_change_feed();
1384
+ init_recovery_deletion();
604
1385
  }
605
1386
  });
606
1387
 
607
1388
  // src/mem7/core/host-turns.ts
608
- import { randomUUID as randomUUID3, createHash as createHash3 } from "node:crypto";
1389
+ import { randomUUID as randomUUID5, createHash as createHash4 } from "node:crypto";
609
1390
  var processOwnerId, currentSource, owned;
610
1391
  var init_host_turns = __esm({
611
1392
  "src/mem7/core/host-turns.ts"() {
612
1393
  "use strict";
613
1394
  init_scope();
614
- processOwnerId = randomUUID3();
1395
+ processOwnerId = randomUUID5();
615
1396
  currentSource = `EXISTS (SELECT 1 FROM memory_sources s WHERE s.scope_id=memory_host_turns.scope_id
616
1397
  AND s.source_id=memory_host_turns.source_id AND s.role='user' AND s.origin_class='host_user' AND s.interpretation_status<>'deleted'
617
1398
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id AND newer.origin_key=s.origin_key
@@ -725,8 +1506,8 @@ var init_job_runner = __esm({
725
1506
  });
726
1507
 
727
1508
  // src/mem7/core/episode.ts
728
- import { readFileSync as readFileSync3 } from "node:fs";
729
- import { join as join2, dirname as dirname2 } from "node:path";
1509
+ import { readFileSync as readFileSync8 } from "node:fs";
1510
+ import { join as join8, dirname as dirname7 } from "node:path";
730
1511
  import { fileURLToPath } from "node:url";
731
1512
  var PROMPT;
732
1513
  var init_episode = __esm({
@@ -734,7 +1515,7 @@ var init_episode = __esm({
734
1515
  "use strict";
735
1516
  init_prompt_render();
736
1517
  init_job_runner();
737
- PROMPT = readFileSync3(join2(dirname2(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
1518
+ PROMPT = readFileSync8(join8(dirname7(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
738
1519
  }
739
1520
  });
740
1521
 
@@ -767,11 +1548,82 @@ var init_types = __esm({
767
1548
  }
768
1549
  });
769
1550
 
1551
+ // src/memory/topics-history/dates.ts
1552
+ var init_dates = __esm({
1553
+ "src/memory/topics-history/dates.ts"() {
1554
+ "use strict";
1555
+ init_clock();
1556
+ }
1557
+ });
1558
+
1559
+ // src/mem7/core/tokenizer.ts
1560
+ import { Jieba } from "@node-rs/jieba";
1561
+ import { dict } from "@node-rs/jieba/dict.js";
1562
+ var init_tokenizer = __esm({
1563
+ "src/mem7/core/tokenizer.ts"() {
1564
+ "use strict";
1565
+ }
1566
+ });
1567
+
1568
+ // src/mem7/core/historical-recall.ts
1569
+ var init_historical_recall = __esm({
1570
+ "src/mem7/core/historical-recall.ts"() {
1571
+ "use strict";
1572
+ init_scope();
1573
+ init_read_guard();
1574
+ init_read_budget();
1575
+ }
1576
+ });
1577
+
1578
+ // src/memory/topics-history/cutoff.ts
1579
+ import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
1580
+ var init_cutoff = __esm({
1581
+ "src/memory/topics-history/cutoff.ts"() {
1582
+ "use strict";
1583
+ init_historical_recall();
1584
+ init_scope();
1585
+ init_clock();
1586
+ init_materials();
1587
+ init_dates();
1588
+ }
1589
+ });
1590
+
1591
+ // src/memory/topics-history/index.ts
1592
+ import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
1593
+ var init_topics_history = __esm({
1594
+ "src/memory/topics-history/index.ts"() {
1595
+ "use strict";
1596
+ init_materials();
1597
+ init_dates();
1598
+ init_tokenizer();
1599
+ init_cutoff();
1600
+ init_clock();
1601
+ init_runtime_replication();
1602
+ }
1603
+ });
1604
+
1605
+ // src/memory/memdir/memoryAge.ts
1606
+ var init_memoryAge = __esm({
1607
+ "src/memory/memdir/memoryAge.ts"() {
1608
+ "use strict";
1609
+ }
1610
+ });
1611
+
1612
+ // src/messages/attachments.ts
1613
+ var init_attachments = __esm({
1614
+ "src/messages/attachments.ts"() {
1615
+ "use strict";
1616
+ init_topics_history();
1617
+ init_memoryAge();
1618
+ }
1619
+ });
1620
+
770
1621
  // src/compact/tokenEstimate.ts
771
1622
  var init_tokenEstimate = __esm({
772
1623
  "src/compact/tokenEstimate.ts"() {
773
1624
  "use strict";
774
1625
  init_types();
1626
+ init_attachments();
775
1627
  }
776
1628
  });
777
1629
 
@@ -900,6 +1752,13 @@ var init_migrations = __esm({
900
1752
  }
901
1753
  });
902
1754
 
1755
+ // src/mem7/core/snapshot-reads.ts
1756
+ var init_snapshot_reads = __esm({
1757
+ "src/mem7/core/snapshot-reads.ts"() {
1758
+ "use strict";
1759
+ }
1760
+ });
1761
+
903
1762
  // src/mem7/core/state/basis-check.ts
904
1763
  var init_basis_check = __esm({
905
1764
  "src/mem7/core/state/basis-check.ts"() {
@@ -963,16 +1822,23 @@ var init_retire_graph_audits = __esm({
963
1822
  });
964
1823
 
965
1824
  // src/mem7/core/store.ts
966
- import { DatabaseSync } from "node:sqlite";
1825
+ import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
967
1826
  var STALE_ARTIFACT_FORCE_MS;
968
1827
  var init_store = __esm({
969
1828
  "src/mem7/core/store.ts"() {
970
1829
  "use strict";
1830
+ init_runtime_lock();
1831
+ init_runtime_authority();
1832
+ init_sqlite_replication();
1833
+ init_mem7_replication();
1834
+ init_sqlite_autocommit();
1835
+ init_schema_migrations();
971
1836
  init_vector_store();
972
1837
  init_prompt_render();
973
1838
  init_clock();
974
1839
  init_migrations();
975
1840
  init_source_store();
1841
+ init_snapshot_reads();
976
1842
  init_entities();
977
1843
  init_facts();
978
1844
  init_change_feed();
@@ -997,15 +1863,6 @@ var init_store = __esm({
997
1863
  }
998
1864
  });
999
1865
 
1000
- // src/mem7/core/tokenizer.ts
1001
- import { Jieba } from "@node-rs/jieba";
1002
- import { dict } from "@node-rs/jieba/dict.js";
1003
- var init_tokenizer = __esm({
1004
- "src/mem7/core/tokenizer.ts"() {
1005
- "use strict";
1006
- }
1007
- });
1008
-
1009
1866
  // src/mem7/core/filters.ts
1010
1867
  var init_filters = __esm({
1011
1868
  "src/mem7/core/filters.ts"() {
@@ -1015,17 +1872,17 @@ var init_filters = __esm({
1015
1872
  });
1016
1873
 
1017
1874
  // src/mem7/core/search/timing.ts
1018
- import { AsyncLocalStorage } from "node:async_hooks";
1875
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
1019
1876
  var current;
1020
1877
  var init_timing = __esm({
1021
1878
  "src/mem7/core/search/timing.ts"() {
1022
1879
  "use strict";
1023
- current = new AsyncLocalStorage();
1880
+ current = new AsyncLocalStorage2();
1024
1881
  }
1025
1882
  });
1026
1883
 
1027
1884
  // src/mem7/core/vector-store.ts
1028
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
1885
+ import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
1029
1886
  function lanceSpecifierFor(platform, arch) {
1030
1887
  return platform === "darwin" && arch === "x64" ? "@engine7/lancedb-intel" : "@lancedb/lancedb";
1031
1888
  }
@@ -1040,6 +1897,7 @@ var init_vector_store = __esm({
1040
1897
  init_dependencies();
1041
1898
  init_read_guard();
1042
1899
  init_timing();
1900
+ init_runtime_authority();
1043
1901
  isIntelMac = process.platform === "darwin" && process.arch === "x64";
1044
1902
  bootAt = Date.now();
1045
1903
  }
@@ -1050,15 +1908,15 @@ var validate_legacy_backup_exports = {};
1050
1908
  __export(validate_legacy_backup_exports, {
1051
1909
  validateLegacyTopicsBackup: () => validateLegacyTopicsBackup
1052
1910
  });
1053
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
1911
+ import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1054
1912
  import { open, readdir } from "node:fs/promises";
1055
- import { basename as basename2, join as join3 } from "node:path";
1056
- async function validateLegacyTopicsBackup(state, directory, history) {
1913
+ import { basename as basename5, join as join9 } from "node:path";
1914
+ async function validateLegacyTopicsBackup(state, directory2, history) {
1057
1915
  unlinked(state);
1058
- unlinked(directory);
1916
+ unlinked(directory2);
1059
1917
  unlinked(history);
1060
- const snapshot = new DatabaseSync3(unlinked(join3(directory, "mem7.db")), { readOnly: true });
1061
- const live = new DatabaseSync3(unlinked(join3(state, "mem7", "index", "mem7.db")), { readOnly: true });
1918
+ const snapshot = new DatabaseSync8(unlinked(join9(directory2, "mem7.db")), { readOnly: true });
1919
+ const live = new DatabaseSync8(unlinked(join9(state, "mem7", "index", "mem7.db")), { readOnly: true });
1062
1920
  try {
1063
1921
  snapshot.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=0");
1064
1922
  const schema = readSchemaVersion(snapshot);
@@ -1067,14 +1925,14 @@ async function validateLegacyTopicsBackup(state, directory, history) {
1067
1925
  let bound = false;
1068
1926
  for (const scope of scopes) {
1069
1927
  if (!live.prepare("SELECT 1 FROM memory_scopes WHERE scope_id=? AND owner_id=? AND app_id=? AND project_id=?").get(scope.scope_id, scope.owner_id, scope.app_id, scope.project_id)) throw new Error("LEGACY_BACKUP_SCOPE_MISMATCH");
1070
- if (basename2(history) === digest(canonical({ ownerId: scope.owner_id, appId: scope.app_id, projectId: scope.project_id }))) bound = true;
1928
+ if (basename5(history) === digest(canonical({ ownerId: scope.owner_id, appId: scope.app_id, projectId: scope.project_id }))) bound = true;
1071
1929
  }
1072
1930
  if (!bound) throw new Error("LEGACY_BACKUP_HISTORY_MISMATCH");
1073
1931
  for (const row of snapshot.prepare("SELECT DISTINCT path FROM memory_artifact_publications WHERE medium='markdown' AND path IS NOT NULL").all()) {
1074
1932
  const rel = String(row.path);
1075
1933
  if (!safeRelative(rel)) throw new Error("LEGACY_BACKUP_PUBLICATION_PATH_INVALID");
1076
1934
  if (!rel.startsWith("users/")) continue;
1077
- const file = await open(unlinked(join3(directory, rel)), "r");
1935
+ const file = await open(unlinked(join9(directory2, rel)), "r");
1078
1936
  await file.close();
1079
1937
  }
1080
1938
  } finally {
@@ -1083,10 +1941,10 @@ async function validateLegacyTopicsBackup(state, directory, history) {
1083
1941
  }
1084
1942
  const readTree = async (root) => {
1085
1943
  for (const entry of await readdir(unlinked(root), { withFileTypes: true })) {
1086
- const path = unlinked(join3(root, entry.name));
1087
- if (entry.isDirectory()) await readTree(path);
1944
+ const path2 = unlinked(join9(root, entry.name));
1945
+ if (entry.isDirectory()) await readTree(path2);
1088
1946
  else if (entry.isFile()) {
1089
- const file = await open(path, "r");
1947
+ const file = await open(path2, "r");
1090
1948
  try {
1091
1949
  const buffer = Buffer.allocUnsafe(64 * 1024);
1092
1950
  while ((await file.read(buffer)).bytesRead > 0) {
@@ -1097,10 +1955,10 @@ async function validateLegacyTopicsBackup(state, directory, history) {
1097
1955
  } else throw new Error("LEGACY_BACKUP_UNSUPPORTED_FILE");
1098
1956
  }
1099
1957
  };
1100
- await readTree(join3(directory, "users"));
1101
- await readTree(join3(directory, "lancedb"));
1958
+ await readTree(join9(directory2, "users"));
1959
+ await readTree(join9(directory2, "lancedb"));
1102
1960
  const loaded = await import(lanceSpecifierFor(process.platform, process.arch)), lance = loaded.connect ? loaded : loaded.default;
1103
- const connection = await lance.connect(join3(directory, "lancedb"));
1961
+ const connection = await lance.connect(join9(directory2, "lancedb"));
1104
1962
  try {
1105
1963
  for (const name of await connection.tableNames()) {
1106
1964
  const table = await connection.openTable(name);
@@ -1129,35 +1987,35 @@ var validate_import_live_exports = {};
1129
1987
  __export(validate_import_live_exports, {
1130
1988
  validateCompletedTopicsImport: () => validateCompletedTopicsImport
1131
1989
  });
1132
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
1133
- import { existsSync as existsSync3 } from "node:fs";
1990
+ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
1991
+ import { existsSync as existsSync4 } from "node:fs";
1134
1992
  import { open as open2, readFile, readdir as readdir2 } from "node:fs/promises";
1135
- import { basename as basename3, join as join4 } from "node:path";
1993
+ import { basename as basename6, join as join10 } from "node:path";
1136
1994
  async function validateCompletedTopicsImport(state, history) {
1137
- const root = unlinked(join4(state, "mem7")), marker = readJson(join4(history, "topics-import.json"));
1138
- if (marker.report?.failed !== 0 || !Number.isFinite(Date.parse(marker.completedAt)) || !Array.isArray(marker.hashes) || marker.hashes.some((hash) => typeof hash !== "string" || !/^[a-f0-9]{64}$/.test(hash)))
1995
+ const root = unlinked(join10(state, "mem7")), marker = readJson(join10(history, "topics-import.json"));
1996
+ if (marker.report?.failed !== 0 || !Number.isFinite(Date.parse(marker.completedAt)) || !Array.isArray(marker.hashes) || marker.hashes.some((hash2) => typeof hash2 !== "string" || !/^[a-f0-9]{64}$/.test(hash2)))
1139
1997
  throw new Error("TOPICS_IMPORT_COMPLETION_INVALID");
1140
1998
  if (!marker.hashes.length && (marker.report.imported > 0 || marker.report.skipped > 0)) throw new Error("TOPICS_IMPORT_COMPLETION_INVALID");
1141
- const db = new DatabaseSync4(unlinked(join4(root, "index", "mem7.db")), { readOnly: true });
1999
+ const db = new DatabaseSync9(unlinked(join10(root, "index", "mem7.db")), { readOnly: true });
1142
2000
  let owner;
1143
2001
  try {
1144
2002
  db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=0");
1145
2003
  if (readSchemaVersion(db)?.component !== "mem7" || db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("TOPICS_IMPORT_LIVE_DATABASE_INVALID");
1146
- const scope = db.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes").all().find((row) => basename3(history) === digest(canonical({ ownerId: row.owner_id, appId: row.app_id, projectId: row.project_id })));
2004
+ const scope = db.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes").all().find((row) => basename6(history) === digest(canonical({ ownerId: row.owner_id, appId: row.app_id, projectId: row.project_id })));
1147
2005
  if (!scope) throw new Error("TOPICS_IMPORT_LIVE_SCOPE_MISMATCH");
1148
2006
  owner = String(scope.owner_id);
1149
2007
  for (const row of db.prepare("SELECT DISTINCT path FROM memory_artifact_publications WHERE medium='markdown' AND path IS NOT NULL").all()) {
1150
2008
  if (!safeRelative(row.path)) throw new Error("TOPICS_IMPORT_LIVE_PUBLICATION_PATH_INVALID");
1151
- const file = await open2(unlinked(join4(root, row.path)), "r");
2009
+ const file = await open2(unlinked(join10(root, row.path)), "r");
1152
2010
  await file.close();
1153
2011
  }
1154
2012
  } finally {
1155
2013
  db.close();
1156
2014
  }
1157
2015
  const prose = /* @__PURE__ */ new Map(), idsByHash = /* @__PURE__ */ new Map();
1158
- const scan = async (path2) => {
1159
- for (const entry of await readdir2(unlinked(path2), { withFileTypes: true })) {
1160
- const file = unlinked(join4(path2, entry.name));
2016
+ const scan = async (path3) => {
2017
+ for (const entry of await readdir2(unlinked(path3), { withFileTypes: true })) {
2018
+ const file = unlinked(join10(path3, entry.name));
1161
2019
  if (entry.isDirectory()) await scan(file);
1162
2020
  else if (entry.isFile() && entry.name.endsWith(".md")) {
1163
2021
  const text = await readFile(file, "utf8");
@@ -1169,19 +2027,19 @@ async function validateCompletedTopicsImport(state, history) {
1169
2027
  const content = match[2].slice(start + "\n### Content\n".length).replace(/\r?\n$/, "");
1170
2028
  prose.set(match[1], content);
1171
2029
  const body = content.startsWith("[\u65E7 topics\uFF5C") ? content.slice(content.indexOf("\n\n") + 2) : content;
1172
- for (const hash of [digest(body), digest(body.trim())]) {
1173
- const ids = idsByHash.get(hash) ?? /* @__PURE__ */ new Set();
2030
+ for (const hash2 of [digest(body), digest(body.trim())]) {
2031
+ const ids = idsByHash.get(hash2) ?? /* @__PURE__ */ new Set();
1174
2032
  ids.add(match[1]);
1175
- idsByHash.set(hash, ids);
2033
+ idsByHash.set(hash2, ids);
1176
2034
  }
1177
2035
  }
1178
2036
  }
1179
2037
  }
1180
2038
  };
1181
- if (existsSync3(join4(root, "users"))) await scan(join4(root, "users"));
1182
- const cachePath = join4(history, "vectors.db");
1183
- if (existsSync3(cachePath)) {
1184
- const cache = new DatabaseSync4(unlinked(cachePath), { readOnly: true });
2039
+ if (existsSync4(join10(root, "users"))) await scan(join10(root, "users"));
2040
+ const cachePath = join10(history, "vectors.db");
2041
+ if (existsSync4(cachePath)) {
2042
+ const cache = new DatabaseSync9(unlinked(cachePath), { readOnly: true });
1185
2043
  try {
1186
2044
  if (cache.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='hash_aliases'").get())
1187
2045
  for (const row of cache.prepare("SELECT old_hash,hash FROM hash_aliases").all()) {
@@ -1193,9 +2051,9 @@ async function validateCompletedTopicsImport(state, history) {
1193
2051
  }
1194
2052
  }
1195
2053
  const loaded = await import(lanceSpecifierFor(process.platform, process.arch)), lance = loaded.connect ? loaded : loaded.default;
1196
- const path = unlinked(join4(root, "index", "lancedb"));
1197
- if (!existsSync3(path)) throw new Error("TOPICS_IMPORT_LIVE_VECTORS_MISSING");
1198
- const connection = await lance.connect(path), vectorIds = /* @__PURE__ */ new Set();
2054
+ const path2 = unlinked(join10(root, "index", "lancedb"));
2055
+ if (!existsSync4(path2)) throw new Error("TOPICS_IMPORT_LIVE_VECTORS_MISSING");
2056
+ const connection = await lance.connect(path2), vectorIds = /* @__PURE__ */ new Set();
1199
2057
  try {
1200
2058
  for (const name of await connection.tableNames()) {
1201
2059
  const table = await connection.openTable(name);
@@ -1212,8 +2070,8 @@ async function validateCompletedTopicsImport(state, history) {
1212
2070
  table.close();
1213
2071
  }
1214
2072
  }
1215
- for (const hash of marker.hashes)
1216
- if (![...idsByHash.get(hash) ?? []].some((id) => vectorIds.has(id))) throw new Error("TOPICS_IMPORT_LIVE_HISTORY_MISSING");
2073
+ for (const hash2 of marker.hashes)
2074
+ if (![...idsByHash.get(hash2) ?? []].some((id) => vectorIds.has(id))) throw new Error("TOPICS_IMPORT_LIVE_HISTORY_MISSING");
1217
2075
  } finally {
1218
2076
  connection.close();
1219
2077
  }
@@ -1228,43 +2086,207 @@ var init_validate_import_live = __esm({
1228
2086
  });
1229
2087
 
1230
2088
  // src/mem7/sqlite-maintenance-worker.ts
1231
- init_schema_migrations();
1232
- import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
2089
+ init_runtime_lock();
1233
2090
  import { statSync, statfsSync } from "node:fs";
1234
- import { dirname as dirname3, join as join5, resolve as resolve2 } from "node:path";
2091
+ import { dirname as dirname8, join as join11, resolve as resolve8 } from "node:path";
1235
2092
  import { setImmediate as yieldToIntake } from "node:timers/promises";
1236
2093
  import { Worker } from "node:worker_threads";
1237
- function intakePendingForDatabase(path) {
1238
- const spool = join5(dirname3(dirname3(path)), "spool");
2094
+
2095
+ // src/continuity/sqlite-physical-maintenance.ts
2096
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
2097
+ import { lstatSync as lstatSync7 } from "node:fs";
2098
+ import { resolve as resolve6 } from "node:path";
2099
+
2100
+ // src/continuity/sqlite-store-location.ts
2101
+ init_mem7_replication();
2102
+ init_runtime_replication();
2103
+ import { basename as basename3, dirname as dirname5, resolve as resolve4 } from "node:path";
2104
+ function sqliteStoreLocation(file) {
2105
+ const absolute = resolve4(file), parent = dirname5(absolute), name = basename3(absolute);
2106
+ if (name === "mem7.db" && basename3(parent) === "index" && basename3(dirname5(parent)) === "mem7")
2107
+ return { stateDir: dirname5(dirname5(parent)), component: "mem7" };
2108
+ let stateDir, component;
2109
+ if (name === "calendar.db" && basename3(parent) === ".calendar") {
2110
+ stateDir = dirname5(parent);
2111
+ component = "calendar";
2112
+ } else if (name === "proactive.db" && basename3(parent) === ".proactive") {
2113
+ stateDir = dirname5(parent);
2114
+ component = "proactive";
2115
+ } else if (name === "session-events.db" && basename3(parent) === ".continuity") {
2116
+ stateDir = dirname5(parent);
2117
+ component = "session-events";
2118
+ } else if (name === "memory.db" && basename3(parent) === "memory" && basename3(dirname5(dirname5(parent))) === "agents") {
2119
+ stateDir = dirname5(dirname5(dirname5(parent)));
2120
+ component = "legacy-memory";
2121
+ } else if (name === "vectors.db" && basename3(dirname5(parent)) === "topics-history") {
2122
+ stateDir = dirname5(dirname5(parent));
2123
+ component = "topics-vectors";
2124
+ } else return null;
2125
+ return { stateDir, ...runtimeReplicationLocation(stateDir, component, absolute) };
2126
+ }
2127
+ function readSQLiteStoreRegistration(place) {
2128
+ return place.component === "mem7" ? readMem7ReplicationRegistration(place.stateDir) : readRuntimeReplicationRegistration(place.stateDir, place.component, place.key);
2129
+ }
2130
+
2131
+ // src/continuity/sqlite-physical-maintenance.ts
2132
+ init_runtime_replication();
2133
+ init_sqlite_replication();
2134
+
2135
+ // src/continuity/legacy-memory-replication.ts
2136
+ import { createRequire as createRequire3 } from "node:module";
2137
+ init_schema_migrations();
2138
+
2139
+ // src/memory/host/sqlite-vec-platform-variant.ts
2140
+ import { createRequire as createRequire2 } from "node:module";
2141
+ var PLATFORM_VARIANTS = {
2142
+ "linux-x64": { pkg: "sqlite-vec-linux-x64", file: "vec0.so" },
2143
+ "linux-arm64": { pkg: "sqlite-vec-linux-arm64", file: "vec0.so" },
2144
+ "darwin-x64": { pkg: "sqlite-vec-darwin-x64", file: "vec0.dylib" },
2145
+ "darwin-arm64": { pkg: "sqlite-vec-darwin-arm64", file: "vec0.dylib" },
2146
+ "win32-x64": { pkg: "sqlite-vec-windows-x64", file: "vec0.dll" }
2147
+ };
2148
+ function resolveSqliteVecPlatformVariant() {
2149
+ const entry = PLATFORM_VARIANTS[`${process.platform}-${process.arch}`];
2150
+ if (!entry) {
2151
+ return void 0;
2152
+ }
2153
+ try {
2154
+ const require_ = createRequire2(import.meta.url);
2155
+ const extensionPath = require_.resolve(`${entry.pkg}/${entry.file}`);
2156
+ return { pkg: entry.pkg, extensionPath };
2157
+ } catch {
2158
+ return void 0;
2159
+ }
2160
+ }
2161
+
2162
+ // src/continuity/legacy-memory-replication.ts
2163
+ init_runtime_replication();
2164
+ init_sqlite_replication();
2165
+ var require2 = createRequire3(import.meta.url);
2166
+ function loadLegacySQLiteVectorExtension(db, extensionPath) {
2167
+ db.enableLoadExtension(true);
2168
+ if (extensionPath) {
2169
+ db.loadExtension(extensionPath);
2170
+ return;
2171
+ }
2172
+ let module;
2173
+ try {
2174
+ module = require2("sqlite-vec");
2175
+ } catch (error) {
2176
+ if (error.code !== "MODULE_NOT_FOUND") throw error;
2177
+ const variant = resolveSqliteVecPlatformVariant();
2178
+ if (!variant) throw new Error("REPLICATION_LEGACY_VECTOR_MODULE_REQUIRED", { cause: error });
2179
+ db.loadExtension(variant.extensionPath);
2180
+ return;
2181
+ }
2182
+ module.load(db);
2183
+ }
2184
+
2185
+ // src/continuity/sqlite-physical-maintenance.ts
2186
+ init_runtime_lock();
2187
+ init_schema_migrations();
2188
+
2189
+ // src/continuity/inventory.ts
2190
+ import { isAbsolute, join as join6, relative, resolve as resolve5, sep } from "node:path";
2191
+ var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
2192
+ function isWithin(root, candidate) {
2193
+ const rel = relative(resolve5(root), resolve5(candidate));
2194
+ return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2195
+ }
2196
+
2197
+ // src/continuity/sqlite-physical-maintenance.ts
2198
+ function openPhysicalMaintenanceDatabase(file, stateDir) {
2199
+ const absolute = resolve6(file), place = sqliteStoreLocation(absolute);
2200
+ const registration = place ? readSQLiteStoreRegistration(place) : null;
2201
+ if (stateDir && !isWithin(stateDir, absolute)) throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
2202
+ const runtimeRoots = [.../* @__PURE__ */ new Set([...stateDir ? [resolve6(stateDir)] : [], ...place ? [place.stateDir] : []])].sort();
2203
+ for (const root of runtimeRoots) assertStateDirUsable(root);
2204
+ try {
2205
+ const info = lstatSync7(absolute);
2206
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error();
2207
+ } catch (error) {
2208
+ throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: error });
2209
+ }
2210
+ checkRuntimeReplicationFile(absolute, registration);
2211
+ const releases2 = [];
2212
+ const release = () => {
2213
+ while (releases2.length) releases2.pop()();
2214
+ };
2215
+ let db;
2216
+ try {
2217
+ for (const root of runtimeRoots) releases2.push(registerRuntimeWriter(root, "sqlite-physical-maintenance"));
2218
+ db = new DatabaseSync3(absolute, { allowExtension: place?.component === "legacy-memory" });
2219
+ } catch (error) {
2220
+ release();
2221
+ throw error;
2222
+ }
2223
+ try {
2224
+ if (place?.component === "legacy-memory") loadLegacySQLiteVectorExtension(db);
2225
+ const enrolled = readSQLiteReplicationSource(db), schema = readSchemaVersion(db);
2226
+ if (registration && (!enrolled || JSON.stringify(enrolled) !== JSON.stringify(registration))) throw new Error("REPLICATION_RECOVERY_REQUIRED");
2227
+ if (enrolled && !registration) throw new Error("REPLICATION_REGISTRATION_REQUIRED");
2228
+ if (registration && (schema?.component !== place.component || sqliteReplicationSchemaHash(db) !== registration.schemaHash)) throw new Error("REPLICATION_SCHEMA_MISMATCH");
2229
+ if (schema) authorizeMemoryWriter(db, schema.version);
2230
+ if (enrolled) db.function("engine7_replication_capture_active", () => 0);
2231
+ const execute = db.exec.bind(db), prepare = db.prepare.bind(db), close = db.close.bind(db);
2232
+ db.exec = (sql) => {
2233
+ const text = sql.trim().replace(/;$/, "").trim();
2234
+ if (!/^PRAGMA busy_timeout\s*=\s*\d+$/i.test(text) && !/^PRAGMA optimize$/i.test(text) && !/^PRAGMA auto_vacuum\s*=\s*INCREMENTAL\s*;\s*VACUUM$/i.test(text)) throw new Error("REPLICATION_PHYSICAL_SQL_REQUIRED");
2235
+ execute(sql);
2236
+ };
2237
+ db.prepare = (sql) => {
2238
+ if (!/^\s*(?:SELECT\b|PRAGMA\s+(?:auto_vacuum|wal_checkpoint|page_size|page_count|freelist_count|incremental_vacuum)\b)/i.test(sql))
2239
+ throw new Error("REPLICATION_PHYSICAL_SQL_REQUIRED");
2240
+ return prepare(sql);
2241
+ };
2242
+ db.close = () => {
2243
+ try {
2244
+ close();
2245
+ } finally {
2246
+ release();
2247
+ }
2248
+ };
2249
+ return db;
2250
+ } catch (error) {
2251
+ try {
2252
+ db.close();
2253
+ } finally {
2254
+ release();
2255
+ }
2256
+ throw error;
2257
+ }
2258
+ }
2259
+
2260
+ // src/mem7/sqlite-maintenance-worker.ts
2261
+ function intakePendingForDatabase(path2) {
2262
+ const spool = join11(dirname8(dirname8(path2)), "spool");
1239
2263
  return ["intake.jsonl", "intake.processing.jsonl"].some((name) => {
1240
2264
  try {
1241
- return statSync(join5(spool, name)).size > 0;
2265
+ return statSync(join11(spool, name)).size > 0;
1242
2266
  } catch (e) {
1243
2267
  if (e.code !== "ENOENT") throw e;
1244
2268
  return false;
1245
2269
  }
1246
2270
  });
1247
2271
  }
1248
- var bytes = (path) => {
2272
+ var bytes = (path2) => {
1249
2273
  try {
1250
- return statSync(path).size;
2274
+ return statSync(path2).size;
1251
2275
  } catch (e) {
1252
2276
  if (e.code !== "ENOENT") throw e;
1253
2277
  return 0;
1254
2278
  }
1255
2279
  };
1256
- async function runSqlitePhysicalMaintenance(path, options = {}) {
2280
+ async function runSqlitePhysicalMaintenance(path2, options = {}) {
1257
2281
  const minimum = options.minFreeBytes ?? 32 * 1024 * 1024, ratio = options.minFreeRatio ?? 0.05;
1258
2282
  if (!Number.isFinite(minimum) || minimum < 0 || !Number.isFinite(ratio) || ratio < 0 || ratio > 1) throw new Error("INVALID_SQLITE_RETENTION_THRESHOLD");
1259
- const before = bytes(path) + bytes(path + "-wal"), started = performance.now();
1260
- const allowed = () => options.shouldRun?.() !== false && !intakePendingForDatabase(path);
1261
- const db = new DatabaseSync5(path);
2283
+ const before = bytes(path2) + bytes(path2 + "-wal"), started = performance.now();
2284
+ const allowed = () => options.shouldRun?.() !== false && !intakePendingForDatabase(path2);
2285
+ const db = openPhysicalMaintenanceDatabase(path2, options.stateDir);
1262
2286
  let mode = "bootstrap";
1263
- const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(path) - bytes(path + "-wal")) });
2287
+ const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(path2) - bytes(path2 + "-wal")) });
1264
2288
  try {
1265
2289
  db.exec("PRAGMA busy_timeout=0");
1266
- const schema = readSchemaVersion(db);
1267
- if (schema) authorizeMemoryWriter(db, schema.version);
1268
2290
  mode = Number(db.prepare("PRAGMA auto_vacuum").get().auto_vacuum) === 2 ? "incremental" : "bootstrap";
1269
2291
  if (!allowed()) return report("deferred");
1270
2292
  const checkpoint = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
@@ -1272,10 +2294,10 @@ async function runSqlitePhysicalMaintenance(path, options = {}) {
1272
2294
  const pageSize = Number(db.prepare("PRAGMA page_size").get().page_size);
1273
2295
  const pages = Number(db.prepare("PRAGMA page_count").get().page_count);
1274
2296
  const free = Number(db.prepare("PRAGMA freelist_count").get().freelist_count);
1275
- const oversized = bytes(path) > pages * pageSize + 1024 * 1024;
2297
+ const oversized = bytes(path2) > pages * pageSize + 1024 * 1024;
1276
2298
  if (!oversized && (free * pageSize < minimum || free / Math.max(1, pages) < ratio)) return report("idle");
1277
2299
  if (mode === "bootstrap" || oversized) {
1278
- const disk = statfsSync(dirname3(path));
2300
+ const disk = statfsSync(dirname8(path2));
1279
2301
  if (disk.bavail * disk.bsize < (pages - free) * pageSize * 2 + 64 * 1024 * 1024) return report("deferred");
1280
2302
  if (!allowed()) return report("deferred");
1281
2303
  options.onPhase?.("vacuum");
@@ -1294,7 +2316,7 @@ async function runSqlitePhysicalMaintenance(path, options = {}) {
1294
2316
  }
1295
2317
  const finalCheckpoint = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
1296
2318
  const finalPages = Number(db.prepare("PRAGMA page_count").get().page_count);
1297
- if (finalCheckpoint.busy || bytes(path) > finalPages * pageSize + 1024 * 1024) return report("deferred");
2319
+ if (finalCheckpoint.busy || bytes(path2) > finalPages * pageSize + 1024 * 1024) return report("deferred");
1298
2320
  return report("complete");
1299
2321
  } catch (error) {
1300
2322
  if (/database is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error))) return report("deferred");
@@ -1303,10 +2325,27 @@ async function runSqlitePhysicalMaintenance(path, options = {}) {
1303
2325
  db.close();
1304
2326
  }
1305
2327
  }
2328
+ if (process.argv.includes("--sqlite-checkpoint")) {
2329
+ const flag = process.argv.indexOf("--sqlite-checkpoint");
2330
+ const path2 = process.argv[flag + 1], stateDir = process.argv[flag + 2];
2331
+ registerRuntimeWriter(stateDir, "sqlite-checkpoint");
2332
+ const db = openPhysicalMaintenanceDatabase(path2, stateDir);
2333
+ try {
2334
+ db.exec("PRAGMA busy_timeout=15000");
2335
+ console.log("wal checkpoint " + JSON.stringify(db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()));
2336
+ const started = Date.now();
2337
+ db.exec("PRAGMA optimize");
2338
+ console.log("pragma optimize " + (Date.now() - started) + "ms");
2339
+ } finally {
2340
+ db.close();
2341
+ }
2342
+ }
1306
2343
  if (process.argv.includes("--sqlite-maintenance")) {
1307
- const flag = process.argv.indexOf("--sqlite-maintenance"), path = resolve2(process.argv[flag + 1] ?? "");
2344
+ const flag = process.argv.indexOf("--sqlite-maintenance"), path2 = resolve8(process.argv[flag + 1] ?? "");
1308
2345
  if (!process.argv[flag + 1]) throw new Error("SQLITE_MAINTENANCE_PATH_REQUIRED");
1309
2346
  const config = process.argv[flag + 2] ? JSON.parse(process.argv[flag + 2]) : {};
2347
+ if (!config.stateDir) throw new Error("SQLITE_MAINTENANCE_STATE_DIR_REQUIRED");
2348
+ registerRuntimeWriter(config.stateDir, "sqlite-maintenance");
1310
2349
  const watchdog = new Worker(`
1311
2350
  const { workerData } = require('node:worker_threads')
1312
2351
  const { statSync } = require('node:fs')
@@ -1322,9 +2361,9 @@ if (process.argv.includes("--sqlite-maintenance")) {
1322
2361
  }
1323
2362
  if (cancel) process.kill(process.pid, 'SIGTERM')
1324
2363
  }, 100)
1325
- `, { eval: true, workerData: { path, ownerPid: process.connected ? process.ppid : null } });
2364
+ `, { eval: true, workerData: { path: path2, ownerPid: process.connected ? process.ppid : null } });
1326
2365
  try {
1327
- console.log(JSON.stringify(await runSqlitePhysicalMaintenance(path, {
2366
+ console.log(JSON.stringify(await runSqlitePhysicalMaintenance(path2, {
1328
2367
  ...config,
1329
2368
  onPhase: (phase) => {
1330
2369
  if (process.connected) process.send?.({ type: "sqliteMaintenancePhase", phase });