engine7 7.1.138 → 7.1.141

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.
@@ -188,30 +188,30 @@ var init_legacy_sqlite_indexes = __esm({
188
188
  });
189
189
 
190
190
  // src/continuity/runtime-authority.ts
191
- import { randomUUID as randomUUID2, verify } from "node:crypto";
192
- import { constants as constants5, closeSync as closeSync4, existsSync, fstatSync as fstatSync3, fsyncSync as fsyncSync4, lstatSync as lstatSync5, mkdirSync as mkdirSync4, openSync as openSync5, readFileSync as readFileSync3, renameSync, writeFileSync as writeFileSync3 } from "node:fs";
193
- import { basename, dirname as dirname3, join as join5, resolve as resolve5 } from "node:path";
191
+ import { randomUUID as randomUUID3, verify } from "node:crypto";
192
+ import { constants as constants6, closeSync as closeSync4, existsSync, fstatSync as fstatSync3, fsyncSync as fsyncSync4, lstatSync as lstatSync5, mkdirSync as mkdirSync4, openSync as openSync5, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
193
+ import { basename, dirname as dirname4, join as join6, resolve as resolve5 } from "node:path";
194
194
  function assertPrivateDirectory2(path3) {
195
- const stat = lstatSync5(path3);
196
- if (!stat.isDirectory() || stat.isSymbolicLink() || process.platform !== "win32" && (stat.uid !== process.getuid() || stat.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
195
+ const stat2 = lstatSync5(path3);
196
+ if (!stat2.isDirectory() || stat2.isSymbolicLink() || process.platform !== "win32" && (stat2.uid !== process.getuid() || stat2.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
197
197
  }
198
198
  function readPrivateFile2(path3, maximum) {
199
199
  const before = lstatSync5(path3);
200
200
  if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
201
- const fd = openSync5(path3, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0));
201
+ const fd = openSync5(path3, constants6.O_RDONLY | (constants6.O_NOFOLLOW ?? 0));
202
202
  try {
203
203
  if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
204
- return readFileSync3(fd);
204
+ return readFileSync2(fd);
205
205
  } finally {
206
206
  closeSync4(fd);
207
207
  }
208
208
  }
209
209
  function writeControl(path3, value2) {
210
- const temporary = path3 + "." + randomUUID2() + ".tmp";
211
- writeFileSync3(temporary, JSON.stringify(value2), { mode: 384, flag: "wx", flush: true });
210
+ const temporary = path3 + "." + randomUUID3() + ".tmp";
211
+ writeFileSync2(temporary, JSON.stringify(value2), { mode: 384, flag: "wx", flush: true });
212
212
  renameSync(temporary, path3);
213
213
  if (process.platform !== "win32") {
214
- const fd = openSync5(dirname3(path3), "r");
214
+ const fd = openSync5(dirname4(path3), "r");
215
215
  try {
216
216
  fsyncSync4(fd);
217
217
  } finally {
@@ -223,14 +223,14 @@ function runtimeAuthorityFor(stateDir) {
223
223
  for (let root = resolve5(stateDir); ; ) {
224
224
  const existing = runtimes.get(root);
225
225
  if (existing) return existing;
226
- const file = join5(root, ".continuity", "travel-runtime.json");
226
+ const file = join6(root, ".continuity", "travel-runtime.json");
227
227
  if (existsSync(file)) {
228
228
  const enrollment = JSON.parse(readPrivateFile2(file, 16384).toString());
229
229
  if (enrollment.format !== "engine7-travel-runtime-v1") throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
230
230
  return new RuntimeAuthority({ stateDir: root, ...enrollment });
231
231
  }
232
- if (existsSync(join5(root, ".travel-active.json")) || existsSync(join5(root, ".travel-enrolled.json"))) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
233
- const parent = dirname3(root);
232
+ if (existsSync(join6(root, ".travel-active.json")) || existsSync(join6(root, ".travel-enrolled.json"))) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
233
+ const parent = dirname4(root);
234
234
  if (parent === root) return null;
235
235
  root = parent;
236
236
  }
@@ -242,12 +242,12 @@ function assertRuntimeAuthority(stateDir, operation) {
242
242
  function databaseRuntimeAuthorityFor(db) {
243
243
  const file = String(db.prepare("PRAGMA database_list").all().find((r) => r.name === "main")?.file ?? "");
244
244
  if (!file) return null;
245
- const parent = dirname3(file), name = basename(file);
245
+ const parent = dirname4(file), name = basename(file);
246
246
  let root;
247
- if (name === "mem7.db" && basename(parent) === "index" && basename(dirname3(parent)) === "mem7") root = dirname3(dirname3(parent));
248
- else if (name === "calendar.db" && basename(parent) === ".calendar" || name === "proactive.db" && basename(parent) === ".proactive" || name === "session-events.db" && basename(parent) === ".continuity") root = dirname3(parent);
249
- else if (name === "memory.db" && basename(parent) === "memory" && basename(dirname3(dirname3(parent))) === "agents") root = dirname3(dirname3(dirname3(parent)));
250
- else if (name === "vectors.db" && basename(dirname3(parent)) === "topics-history") root = dirname3(dirname3(parent));
247
+ if (name === "mem7.db" && basename(parent) === "index" && basename(dirname4(parent)) === "mem7") root = dirname4(dirname4(parent));
248
+ else if (name === "calendar.db" && basename(parent) === ".calendar" || name === "proactive.db" && basename(parent) === ".proactive" || name === "session-events.db" && basename(parent) === ".continuity") root = dirname4(parent);
249
+ else if (name === "memory.db" && basename(parent) === "memory" && basename(dirname4(dirname4(parent))) === "agents") root = dirname4(dirname4(dirname4(parent)));
250
+ else if (name === "vectors.db" && basename(dirname4(parent)) === "topics-history") root = dirname4(dirname4(parent));
251
251
  return root ? runtimeAuthorityFor(root) : null;
252
252
  }
253
253
  function assertDatabaseRuntimeAuthority(db, binding) {
@@ -270,7 +270,7 @@ var init_runtime_authority = __esm({
270
270
  cachedFloor = 0;
271
271
  constructor(options) {
272
272
  this.stateDir = resolve5(options.stateDir);
273
- this.directory = join5(this.stateDir, ".continuity");
273
+ this.directory = join6(this.stateDir, ".continuity");
274
274
  this.clock = options.monotonicNow ?? now;
275
275
  const tools = options.allowedTools ?? [];
276
276
  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");
@@ -278,10 +278,10 @@ var init_runtime_authority = __esm({
278
278
  if (options.initialize) {
279
279
  mkdirSync4(this.directory, { mode: 448, recursive: true });
280
280
  assertPrivateDirectory2(this.directory);
281
- const file = join5(this.directory, "travel-runtime.json");
282
- if (!existsSync(file)) writeFileSync3(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
283
- const marker = join5(this.stateDir, ".travel-enrolled.json");
284
- if (!existsSync(marker)) writeFileSync3(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
281
+ const file = join6(this.directory, "travel-runtime.json");
282
+ if (!existsSync(file)) writeFileSync2(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
283
+ const marker = join6(this.stateDir, ".travel-enrolled.json");
284
+ if (!existsSync(marker)) writeFileSync2(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
285
285
  }
286
286
  this.checkEnrollment();
287
287
  this.previous = runtimes.get(this.stateDir);
@@ -290,7 +290,7 @@ var init_runtime_authority = __esm({
290
290
  checkEnrollment() {
291
291
  try {
292
292
  assertPrivateDirectory2(this.directory);
293
- const existing = JSON.parse(readPrivateFile2(join5(this.directory, "travel-runtime.json"), 16384).toString());
293
+ const existing = JSON.parse(readPrivateFile2(join6(this.directory, "travel-runtime.json"), 16384).toString());
294
294
  if (!equal(existing, this.enrollment)) throw new Error("TRAVEL_RUNTIME_IDENTITY_MISMATCH");
295
295
  } catch (error) {
296
296
  throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED", { cause: error });
@@ -298,7 +298,7 @@ var init_runtime_authority = __esm({
298
298
  }
299
299
  grant() {
300
300
  this.checkEnrollment();
301
- const file = join5(this.directory, "travel-permit.json");
301
+ const file = join6(this.directory, "travel-permit.json");
302
302
  if (!existsSync(file)) return null;
303
303
  try {
304
304
  const grant = JSON.parse(readPrivateFile2(file, 16384).toString());
@@ -310,7 +310,7 @@ var init_runtime_authority = __esm({
310
310
  }
311
311
  writeGrant(grant) {
312
312
  this.checkEnrollment();
313
- writeControl(join5(this.directory, "travel-permit.json"), grant);
313
+ writeControl(join6(this.directory, "travel-permit.json"), grant);
314
314
  this.cachedGrant = grant;
315
315
  }
316
316
  validatePermit(permit) {
@@ -354,7 +354,7 @@ var init_runtime_authority = __esm({
354
354
  return grant.permit;
355
355
  }
356
356
  deletionFloor() {
357
- const file = join5(this.directory, "travel-deletion-floor.json");
357
+ const file = join6(this.directory, "travel-deletion-floor.json");
358
358
  if (!existsSync(file)) return 0;
359
359
  const value2 = JSON.parse(readPrivateFile2(file, 128).toString());
360
360
  if (!Number.isSafeInteger(value2) || value2 < 0) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
@@ -362,7 +362,7 @@ var init_runtime_authority = __esm({
362
362
  }
363
363
  advanceDeletionFloor(floor) {
364
364
  if (!Number.isSafeInteger(floor) || floor < this.deletionFloor()) throw new Error("TRAVEL_DELETION_ROLLBACK");
365
- writeControl(join5(this.directory, "travel-deletion-floor.json"), floor);
365
+ writeControl(join6(this.directory, "travel-deletion-floor.json"), floor);
366
366
  this.cachedFloor = floor;
367
367
  }
368
368
  freeze(frozen) {
@@ -396,7 +396,7 @@ var init_runtime_authority = __esm({
396
396
  import { createHash as createHash4 } from "node:crypto";
397
397
  import { createRequire } from "node:module";
398
398
  function sqliteConstants() {
399
- return constants6 ??= createRequire(import.meta.url)("node:sqlite").constants;
399
+ return constants7 ??= createRequire(import.meta.url)("node:sqlite").constants;
400
400
  }
401
401
  function bindingText(binding) {
402
402
  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");
@@ -568,7 +568,7 @@ function sourcePendingBytes(db, after, through) {
568
568
  if (!Number.isSafeInteger(bytes) || bytes < 0) throw new Error("REPLICATION_CORRUPT_CONTROL");
569
569
  return bytes;
570
570
  }
571
- var constants6, metadataTables, metadataColumns, guardPrefix, identifier, hash, digestPattern, SQLiteReplicationSourceReader, SQLiteReplicationSource, SQLiteReplicationReplica;
571
+ var constants7, metadataTables, metadataColumns, guardPrefix, identifier, hash, digestPattern, SQLiteReplicationSourceReader, SQLiteReplicationSource, SQLiteReplicationReplica;
572
572
  var init_sqlite_replication = __esm({
573
573
  "src/continuity/sqlite-replication.ts"() {
574
574
  "use strict";
@@ -807,7 +807,8 @@ var init_sqlite_replication = __esm({
807
807
  this.derived = inspectLegacySQLiteIndexes(db);
808
808
  this.tables = inspectTables(db, this.derived?.excludedTables);
809
809
  if (sqliteReplicationSchemaHash(db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
810
- if (db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("REPLICATION_INVALID_BASELINE: foreign key");
810
+ const initialized = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get() && db.prepare("SELECT 1 FROM e7_replication_control WHERE role='replica'").get());
811
+ if (!initialized && db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("REPLICATION_INVALID_BASELINE: foreign key");
811
812
  const allowed = new Set(options.suppressTriggers ?? []);
812
813
  if ([...allowed].some((name) => name.startsWith("writer_guard_"))) throw new Error("REPLICATION_WRITER_GUARD_MUST_REMAIN");
813
814
  this.triggers = schemaRows(db).filter((r) => r.type === "trigger" && !r.name.startsWith("writer_guard_"));
@@ -815,7 +816,6 @@ var init_sqlite_replication = __esm({
815
816
  throw new Error("REPLICATION_UNCLASSIFIED_TRIGGER");
816
817
  this.automaticTables = new Set(schemaRows(db).filter((r) => this.tables.has(r.name) && r.type === "table" && /\bAUTOINCREMENT\b/i.test(r.sql)).map((r) => r.name));
817
818
  db.function("engine7_replication_capture_active", () => this.applying ? 1 : 0);
818
- const initialized = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get() && db.prepare("SELECT 1 FROM e7_replication_control WHERE role='replica'").get());
819
819
  db.exec("BEGIN IMMEDIATE");
820
820
  try {
821
821
  if (!initialized) this.derived?.rebuild();
@@ -960,8 +960,8 @@ var init_sqlite_replication = __esm({
960
960
  });
961
961
 
962
962
  // src/continuity/runtime-replication.ts
963
- import { constants as constants7, lstatSync as lstatSync7, realpathSync as realpathSync3, mkdirSync as mkdirSync5, openSync as openSync7, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5, fsyncSync as fsyncSync6 } from "node:fs";
964
- import { basename as basename2, dirname as dirname5, join as join7, resolve as resolve6 } from "node:path";
963
+ import { constants as constants8, lstatSync as lstatSync7, realpathSync as realpathSync3, mkdirSync as mkdirSync5, openSync as openSync7, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync4, fsyncSync as fsyncSync6 } from "node:fs";
964
+ import { basename as basename2, dirname as dirname6, join as join8, resolve as resolve6 } from "node:path";
965
965
  function checkKey(component, key2) {
966
966
  if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
967
967
  if (component === "legacy-memory" && typeof key2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key2) && !/[. ]$/.test(key2) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key2)) return;
@@ -970,17 +970,17 @@ function checkKey(component, key2) {
970
970
  }
971
971
  function location2(stateDir, component, key2) {
972
972
  checkKey(component, key2);
973
- return join7(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
973
+ return join8(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
974
974
  }
975
975
  function runtimeReplicationFile(stateDir, component, key2) {
976
976
  checkKey(component, key2);
977
- if (component === "legacy-memory") return join7(stateDir, "agents", key2, "memory", "memory.db");
978
- if (component === "topics-vectors") return join7(stateDir, "topics-history", key2, "vectors.db");
979
- if (component === "session-events") return join7(stateDir, ".continuity", "session-events.db");
980
- return join7(stateDir, "." + component, component + ".db");
977
+ if (component === "legacy-memory") return join8(stateDir, "agents", key2, "memory", "memory.db");
978
+ if (component === "topics-vectors") return join8(stateDir, "topics-history", key2, "vectors.db");
979
+ if (component === "session-events") return join8(stateDir, ".continuity", "session-events.db");
980
+ return join8(stateDir, "." + component, component + ".db");
981
981
  }
982
982
  function runtimeReplicationLocation(stateDir, component, file) {
983
- const key2 = component === "legacy-memory" ? basename2(dirname5(dirname5(file))) : component === "topics-vectors" ? basename2(dirname5(file)) : void 0;
983
+ const key2 = component === "legacy-memory" ? basename2(dirname6(dirname6(file))) : component === "topics-vectors" ? basename2(dirname6(file)) : void 0;
984
984
  try {
985
985
  if (resolve6(file) !== resolve6(runtimeReplicationFile(stateDir, component, key2))) throw new Error();
986
986
  } catch (error) {
@@ -1000,15 +1000,15 @@ function directory(path3) {
1000
1000
  function readRuntimeReplicationRegistration(stateDir, component, key2) {
1001
1001
  const file = location2(stateDir, component, key2);
1002
1002
  try {
1003
- lstatSync7(dirname5(file));
1003
+ lstatSync7(dirname6(file));
1004
1004
  } catch (error) {
1005
1005
  if (error.code === "ENOENT") return null;
1006
1006
  throw error;
1007
1007
  }
1008
- directory(dirname5(file));
1008
+ directory(dirname6(file));
1009
1009
  let fd;
1010
1010
  try {
1011
- fd = openSync7(file, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
1011
+ fd = openSync7(file, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
1012
1012
  } catch (error) {
1013
1013
  if (error.code === "ENOENT") return null;
1014
1014
  throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
@@ -1016,7 +1016,7 @@ function readRuntimeReplicationRegistration(stateDir, component, key2) {
1016
1016
  try {
1017
1017
  const info = fstatSync4(fd);
1018
1018
  if (!info.isFile() || info.size > 4096 || realpathSync3(file) !== resolve6(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
1019
- return normalize2(JSON.parse(readFileSync4(fd, "utf8")));
1019
+ return normalize2(JSON.parse(readFileSync3(fd, "utf8")));
1020
1020
  } catch (error) {
1021
1021
  throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
1022
1022
  } finally {
@@ -1031,7 +1031,7 @@ function checkRuntimeReplicationFile(file, registration, initial = false) {
1031
1031
  info = lstatSync7(file);
1032
1032
  } catch (error) {
1033
1033
  if (registration || !initial || error.code !== "ENOENT") throw error;
1034
- let parent = dirname5(resolve6(file));
1034
+ let parent = dirname6(resolve6(file));
1035
1035
  for (; ; ) {
1036
1036
  try {
1037
1037
  const existing = lstatSync7(parent);
@@ -1039,7 +1039,7 @@ function checkRuntimeReplicationFile(file, registration, initial = false) {
1039
1039
  return;
1040
1040
  } catch (error2) {
1041
1041
  if (error2.code !== "ENOENT") throw error2;
1042
- parent = dirname5(parent);
1042
+ parent = dirname6(parent);
1043
1043
  }
1044
1044
  }
1045
1045
  }
@@ -1069,16 +1069,16 @@ function enrollRuntimeReplication(db, stateDir, component, binding, key2) {
1069
1069
  const input = normalize2({ binding, schemaHash: sqliteReplicationSchemaHash(db) });
1070
1070
  if (old && JSON.stringify(old) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
1071
1071
  if (!old) {
1072
- mkdirSync5(dirname5(file), { mode: 448, recursive: true });
1073
- directory(dirname5(file));
1072
+ mkdirSync5(dirname6(file), { mode: 448, recursive: true });
1073
+ directory(dirname6(file));
1074
1074
  try {
1075
- writeFileSync5(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1075
+ writeFileSync4(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1076
1076
  } catch (error) {
1077
1077
  if (error.code !== "EEXIST") throw error;
1078
1078
  if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
1079
1079
  }
1080
1080
  if (process.platform !== "win32") {
1081
- const fd = openSync7(dirname5(file), "r");
1081
+ const fd = openSync7(dirname6(file), "r");
1082
1082
  try {
1083
1083
  fsyncSync6(fd);
1084
1084
  } finally {
@@ -1097,10 +1097,10 @@ var init_runtime_replication = __esm({
1097
1097
  });
1098
1098
 
1099
1099
  // src/continuity/runtime-lock.ts
1100
- import { randomUUID as randomUUID3 } from "node:crypto";
1100
+ import { randomUUID as randomUUID4 } from "node:crypto";
1101
1101
  import { AsyncLocalStorage } from "node:async_hooks";
1102
- import { closeSync as closeSync7, lstatSync as lstatSync8, mkdirSync as mkdirSync6, openSync as openSync8, readFileSync as readFileSync5, realpathSync as realpathSync4 } from "node:fs";
1103
- import { join as join8 } from "node:path";
1102
+ import { closeSync as closeSync7, lstatSync as lstatSync8, mkdirSync as mkdirSync6, openSync as openSync8, readFileSync as readFileSync4, realpathSync as realpathSync4 } from "node:fs";
1103
+ import { join as join9 } from "node:path";
1104
1104
  import { createRequire as createRequire4 } from "node:module";
1105
1105
  function openSQLite(file, options = {}) {
1106
1106
  return new (sqlite ??= createRequire4(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
@@ -1109,11 +1109,11 @@ function openControl(stateDir, create = true, busyTimeoutMs = 0) {
1109
1109
  if (create) mkdirSync6(stateDir, { recursive: true });
1110
1110
  const state2 = realpathSync4(stateDir);
1111
1111
  if (process.platform !== "win32" && lstatSync8(state2).uid !== process.getuid()) throw new Error("CONTROL_OWNER_MISMATCH: run travel as the engine data owner, without sudo");
1112
- const directory2 = join8(state2, ".continuity");
1112
+ const directory2 = join9(state2, ".continuity");
1113
1113
  if (create) mkdirSync6(directory2, { recursive: true, mode: 448 });
1114
1114
  if (lstatSync8(directory2).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_DIRECTORY");
1115
1115
  assertControlPermissions(directory2);
1116
- const file = join8(directory2, "runtime.sqlite");
1116
+ const file = join9(directory2, "runtime.sqlite");
1117
1117
  if (create) {
1118
1118
  try {
1119
1119
  closeSync7(openSync8(file, "wx", 384));
@@ -1152,7 +1152,7 @@ function assertStateDirUsable(stateDir) {
1152
1152
  const initial = initialBaselineAdmission.getStore();
1153
1153
  if (initial?.active && initial.roots.has(realpathSync4(stateDir))) return;
1154
1154
  try {
1155
- lstatSync8(join8(stateDir, ".travel-restored.json"));
1155
+ lstatSync8(join9(stateDir, ".travel-restored.json"));
1156
1156
  throw new Error("TRAVEL_ACTIVATION_REQUIRED");
1157
1157
  } catch (error) {
1158
1158
  if (error.code !== "ENOENT") throw error;
@@ -1177,7 +1177,7 @@ function registerRuntimeWriter(stateDir, kind) {
1177
1177
  const recovery = recoveryWriterLocks.getStore();
1178
1178
  if (recovery?.active && recovery.roots.has(realpathSync4(stateDir))) return () => {
1179
1179
  };
1180
- const db = openControl(stateDir, true, 1e3), id2 = randomUUID3();
1180
+ const db = openControl(stateDir, true, 1e3), id2 = randomUUID4();
1181
1181
  try {
1182
1182
  db.exec("BEGIN IMMEDIATE");
1183
1183
  db.prepare("INSERT INTO writers VALUES (?, ?, ?, ?, ?)").run(id2, process.pid, bootId, kind, (/* @__PURE__ */ new Date()).toISOString());
@@ -1230,7 +1230,7 @@ async function withCheckpointLock(stateDir, operation) {
1230
1230
  for (const name of [".engine.pid", ".bg-worker.pid"]) {
1231
1231
  let value2;
1232
1232
  try {
1233
- value2 = readFileSync5(join8(stateDir, name), "utf8").trim();
1233
+ value2 = readFileSync4(join9(stateDir, name), "utf8").trim();
1234
1234
  } catch (error) {
1235
1235
  if (error.code === "ENOENT") continue;
1236
1236
  throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
@@ -1254,7 +1254,7 @@ var init_runtime_lock = __esm({
1254
1254
  "src/continuity/runtime-lock.ts"() {
1255
1255
  "use strict";
1256
1256
  init_runtime_authority();
1257
- bootId = randomUUID3();
1257
+ bootId = randomUUID4();
1258
1258
  releases = /* @__PURE__ */ new Set();
1259
1259
  checkpointHandles = /* @__PURE__ */ new Set();
1260
1260
  exitHookInstalled = false;
@@ -1591,7 +1591,7 @@ var init_historical_recall = __esm({
1591
1591
  });
1592
1592
 
1593
1593
  // src/memory/topics-history/cutoff.ts
1594
- import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
1594
+ import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1595
1595
  var init_cutoff = __esm({
1596
1596
  "src/memory/topics-history/cutoff.ts"() {
1597
1597
  "use strict";
@@ -1604,7 +1604,7 @@ var init_cutoff = __esm({
1604
1604
  });
1605
1605
 
1606
1606
  // src/memory/topics-history/index.ts
1607
- import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
1607
+ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
1608
1608
  var init_topics_history = __esm({
1609
1609
  "src/memory/topics-history/index.ts"() {
1610
1610
  "use strict";
@@ -1628,26 +1628,26 @@ var init_timing = __esm({
1628
1628
  });
1629
1629
 
1630
1630
  // src/continuity/publication-main.ts
1631
- import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
1632
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync16, lstatSync as lstatSync19, realpathSync as realpathSync14 } from "node:fs";
1633
- import { isAbsolute as isAbsolute5, resolve as resolve22, join as join23, dirname as dirname13 } from "node:path";
1631
+ import { DatabaseSync as DatabaseSync20 } from "node:sqlite";
1632
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync15, lstatSync as lstatSync19, realpathSync as realpathSync14 } from "node:fs";
1633
+ import { isAbsolute as isAbsolute5, resolve as resolve22, join as join24, dirname as dirname14 } from "node:path";
1634
1634
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1635
1635
  import { X509Certificate } from "node:crypto";
1636
1636
 
1637
1637
  // src/continuity/key-service-store.ts
1638
1638
  import { DatabaseSync } from "node:sqlite";
1639
1639
  import { constants, lstatSync, mkdirSync, openSync, closeSync, readFileSync, writeSync, fstatSync, fsyncSync, unlinkSync } from "node:fs";
1640
- function assertPrivateStat(stat, directory2) {
1641
- if ((directory2 ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1640
+ function assertPrivateStat(stat2, directory2) {
1641
+ if ((directory2 ? !stat2.isDirectory() : !stat2.isFile()) || process.platform !== "win32" && ((stat2.mode & 63) !== 0 || stat2.uid !== process.getuid?.()))
1642
1642
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
1643
1643
  }
1644
1644
  function readPrivateFile(path3, maximumBytes = 65536) {
1645
1645
  assertPrivateStat(lstatSync(path3), false);
1646
1646
  const fd = openSync(path3, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
1647
1647
  try {
1648
- const stat = fstatSync(fd);
1649
- assertPrivateStat(stat, false);
1650
- if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
1648
+ const stat2 = fstatSync(fd);
1649
+ assertPrivateStat(stat2, false);
1650
+ if (stat2.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
1651
1651
  return readFileSync(fd);
1652
1652
  } finally {
1653
1653
  closeSync(fd);
@@ -1663,21 +1663,19 @@ import {
1663
1663
  fstatSync as fstatSync2,
1664
1664
  fsyncSync as fsyncSync2,
1665
1665
  readSync,
1666
- writeSync as writeSync2,
1667
1666
  lstatSync as lstatSync2,
1668
1667
  realpathSync,
1669
- mkdirSync as mkdirSync2,
1670
- readFileSync as readFileSync2,
1671
- writeFileSync,
1672
- linkSync,
1673
- unlinkSync as unlinkSync2
1668
+ mkdirSync as mkdirSync2
1674
1669
  } from "node:fs";
1670
+ import { open, writeFile, link, unlink } from "node:fs/promises";
1675
1671
  import { join, dirname, resolve } from "node:path";
1676
1672
  import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
1673
+ import { setImmediate } from "node:timers/promises";
1677
1674
  var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
1678
1675
  var HASH = /^[a-f0-9]{64}$/;
1679
1676
  var OVERHEAD = 32;
1680
1677
  var MAGIC = Buffer.from("E7P1");
1678
+ var INLINE_BYTES = 64 * 1024;
1681
1679
  var sha = (body) => createHash("sha256").update(body).digest("hex");
1682
1680
  var noFollow = constants2.O_NOFOLLOW ?? 0;
1683
1681
  function validateObjectRef(ref) {
@@ -1753,15 +1751,24 @@ function preparePrivateDatabase(path3) {
1753
1751
  throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
1754
1752
  syncDir(dirname(path3));
1755
1753
  }
1756
- function exclusivePublish(path3, body) {
1754
+ async function syncDirAsync(path3) {
1755
+ if (process.platform === "win32") return;
1756
+ const fd = await open(path3, constants2.O_RDONLY);
1757
+ try {
1758
+ await fd.sync();
1759
+ } finally {
1760
+ await fd.close();
1761
+ }
1762
+ }
1763
+ async function exclusivePublish(path3, body, deferDirectorySync = false) {
1757
1764
  const temp = join(dirname(path3), "." + randomUUID() + ".partial");
1758
1765
  try {
1759
- writeFileSync(temp, body, { flag: "wx", mode: 384, flush: true });
1760
- linkSync(temp, path3);
1761
- syncDir(dirname(path3));
1766
+ await writeFile(temp, body, { flag: "wx", mode: 384, flush: true });
1767
+ await link(temp, path3);
1768
+ if (!deferDirectorySync) await syncDirAsync(dirname(path3));
1762
1769
  } finally {
1763
1770
  try {
1764
- unlinkSync2(temp);
1771
+ await unlink(temp);
1765
1772
  } catch (error) {
1766
1773
  if (error.code !== "ENOENT") throw error;
1767
1774
  }
@@ -1774,6 +1781,7 @@ var PublicationObjects = class _PublicationObjects {
1774
1781
  key;
1775
1782
  maximumBytes;
1776
1783
  closed = false;
1784
+ inlineReads = 0;
1777
1785
  constructor(options) {
1778
1786
  if (!(options.key instanceof Uint8Array) || options.key.length !== 32) throw new Error("PUBLICATION_INVALID_KEY");
1779
1787
  if (!options.identity || ["tenantId", "companionId", "seatId"].some((k) => typeof options.identity[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.identity[k])))
@@ -1792,7 +1800,7 @@ var PublicationObjects = class _PublicationObjects {
1792
1800
  this.db = new DatabaseSync2(file);
1793
1801
  this.db.exec(`PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
1794
1802
  CREATE TABLE IF NOT EXISTS identity (id INTEGER PRIMARY KEY CHECK(id=1), verifier BLOB NOT NULL);
1795
- CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0));`);
1803
+ CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0),ciphertext BLOB);`);
1796
1804
  this.db.exec("BEGIN IMMEDIATE");
1797
1805
  try {
1798
1806
  const row = this.db.prepare("SELECT verifier FROM identity WHERE id=1").get();
@@ -1803,6 +1811,13 @@ var PublicationObjects = class _PublicationObjects {
1803
1811
  throw new Error("PUBLICATION_KEY_OR_IDENTITY_MISMATCH");
1804
1812
  }
1805
1813
  } else this.db.prepare("INSERT INTO identity VALUES(1,?)").run(this.encrypt(Buffer.from("publication-object-key"), "identity"));
1814
+ if (!this.db.prepare("PRAGMA table_info(objects)").all().some((column) => column.name === "ciphertext"))
1815
+ this.db.exec("ALTER TABLE objects ADD COLUMN ciphertext BLOB");
1816
+ this.db.exec(`CREATE TABLE IF NOT EXISTS object_usage (id INTEGER PRIMARY KEY CHECK(id=1),objects INTEGER NOT NULL,bytes INTEGER NOT NULL);
1817
+ INSERT OR IGNORE INTO object_usage SELECT 1,count(*),coalesce(sum(bytes+32),0) FROM objects;
1818
+ CREATE TRIGGER IF NOT EXISTS objects_usage_insert AFTER INSERT ON objects BEGIN UPDATE object_usage SET objects=objects+1,bytes=bytes+NEW.bytes+32 WHERE id=1; END;
1819
+ CREATE TRIGGER IF NOT EXISTS objects_usage_delete AFTER DELETE ON objects BEGIN UPDATE object_usage SET objects=objects-1,bytes=bytes-OLD.bytes-32 WHERE id=1; END;
1820
+ CREATE TRIGGER IF NOT EXISTS objects_usage_resize AFTER UPDATE OF bytes ON objects BEGIN UPDATE object_usage SET bytes=bytes+NEW.bytes-OLD.bytes WHERE id=1; END;`);
1806
1821
  this.db.exec("COMMIT");
1807
1822
  syncDir(this.directory);
1808
1823
  } catch (error) {
@@ -1842,54 +1857,135 @@ var PublicationObjects = class _PublicationObjects {
1842
1857
  }
1843
1858
  usage() {
1844
1859
  this.active();
1845
- return this.db.prepare("SELECT count(*) objects,COALESCE(sum(bytes+32),0) bytes FROM objects").get();
1860
+ return this.db.prepare("SELECT objects,bytes FROM object_usage WHERE id=1").get();
1846
1861
  }
1847
- async put(body) {
1848
- this.active();
1849
- assertPrivateDirectory(this.directory);
1850
- assertPrivateDirectory(join(this.directory, "chunks"));
1851
- if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
1852
- throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
1853
- body = Buffer.from(body);
1854
- const ref = { sha256: sha(body), bytes: body.byteLength };
1862
+ reserve(refs) {
1855
1863
  this.db.exec("BEGIN IMMEDIATE");
1856
1864
  try {
1857
- const row = this.db.prepare("SELECT bytes FROM objects WHERE hash=?").get(ref.sha256);
1858
- if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1859
- if (!row) {
1860
- if (this.usage().bytes + ref.bytes + OVERHEAD > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
1861
- this.db.prepare("INSERT INTO objects VALUES(?,?)").run(ref.sha256, ref.bytes);
1865
+ let used = this.usage().bytes;
1866
+ const lookup = this.db.prepare("SELECT bytes FROM objects WHERE hash=?");
1867
+ const insert = this.db.prepare("INSERT INTO objects(hash,bytes) VALUES(?,?)");
1868
+ for (const ref of refs) {
1869
+ const row = lookup.get(ref.sha256);
1870
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1871
+ if (!row) {
1872
+ used += ref.bytes + OVERHEAD;
1873
+ if (used > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
1874
+ insert.run(ref.sha256, ref.bytes);
1875
+ }
1862
1876
  }
1863
1877
  this.db.exec("COMMIT");
1864
1878
  } catch (error) {
1865
1879
  this.db.exec("ROLLBACK");
1866
1880
  throw error;
1867
1881
  }
1868
- if (await this.has(ref)) return ref;
1882
+ }
1883
+ async put(body) {
1884
+ return this.putObject(body, false);
1885
+ }
1886
+ async putObject(body, deferDirectorySync) {
1887
+ this.active();
1888
+ assertPrivateDirectory(this.directory);
1889
+ assertPrivateDirectory(join(this.directory, "chunks"));
1890
+ if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
1891
+ throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
1892
+ body = Buffer.from(body);
1893
+ const ref = { sha256: sha(body), bytes: body.byteLength };
1894
+ this.reserve([ref]);
1895
+ await this.writeObject(ref, Buffer.from(body), deferDirectorySync);
1896
+ return ref;
1897
+ }
1898
+ async writeObject(ref, body, deferDirectorySync) {
1899
+ if (await this.has(ref)) return;
1869
1900
  try {
1870
- exclusivePublish(join(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256));
1901
+ await exclusivePublish(join(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256), deferDirectorySync);
1871
1902
  } catch (error) {
1872
1903
  if (error.code !== "EEXIST") throw error;
1873
1904
  }
1874
1905
  await this.read(ref);
1875
- return ref;
1906
+ }
1907
+ /** Same immutable chunk format and row digests, with one durable reservation
1908
+ * and directory barrier for a bounded batch. All started writes settle even
1909
+ * when one fails, so callers can safely close or retry the store. */
1910
+ async putContents(bodies) {
1911
+ return this.putContentsWith(bodies, false);
1912
+ }
1913
+ async putContentsWith(bodies, deferDirectorySync) {
1914
+ this.active();
1915
+ assertPrivateDirectory(this.directory);
1916
+ assertPrivateDirectory(join(this.directory, "chunks"));
1917
+ if (!Array.isArray(bodies) || bodies.length > 128 || bodies.some((body) => !(body instanceof Uint8Array)) || bodies.reduce((sum, body) => sum + body.byteLength, 0) > 8 * 1024 * 1024) throw new Error("PUBLICATION_BATCH_TOO_LARGE");
1918
+ const owned2 = bodies.map((body) => Buffer.from(body)), writes = /* @__PURE__ */ new Map();
1919
+ const files = owned2.map((body) => {
1920
+ const chunks = [];
1921
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
1922
+ const chunk = body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES), ref = { sha256: sha(chunk), bytes: chunk.length };
1923
+ chunks.push(ref);
1924
+ writes.set(ref.sha256, { ref, body: chunk });
1925
+ }
1926
+ return { sha256: sha(body), bytes: body.length, chunks };
1927
+ });
1928
+ const pending = [...writes.values()];
1929
+ if (!pending.length) return files;
1930
+ this.reserve(pending.map((item) => item.ref));
1931
+ const checked = await Promise.allSettled(pending.map(async (item) => ({ item, present: await this.has(item.ref) })));
1932
+ for (const result of checked) if (result.status === "rejected") throw result.reason;
1933
+ const missing = checked.flatMap((result) => result.status === "fulfilled" && !result.value.present ? [result.value.item] : []);
1934
+ const inline = missing.filter((item) => item.ref.bytes <= INLINE_BYTES), large = missing.filter((item) => item.ref.bytes > INLINE_BYTES);
1935
+ if (inline.length) {
1936
+ this.db.exec("BEGIN IMMEDIATE");
1937
+ try {
1938
+ const insert = this.db.prepare("UPDATE objects SET ciphertext=? WHERE hash=? AND ciphertext IS NULL");
1939
+ for (const item of inline) insert.run(this.encrypt(item.body, item.ref.sha256), item.ref.sha256);
1940
+ this.db.exec("COMMIT");
1941
+ } catch (error) {
1942
+ this.db.exec("ROLLBACK");
1943
+ throw error;
1944
+ }
1945
+ for (const item of inline) await this.read(item.ref);
1946
+ }
1947
+ try {
1948
+ for (let offset = 0; offset < large.length; offset += 8) {
1949
+ const results = await Promise.allSettled(large.slice(offset, offset + 8).map((item) => this.writeObject(item.ref, item.body, true)));
1950
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1951
+ }
1952
+ } finally {
1953
+ if (large.length && !deferDirectorySync) await syncDirAsync(join(this.directory, "chunks"));
1954
+ }
1955
+ return files;
1876
1956
  }
1877
1957
  async read(ref) {
1878
1958
  this.active();
1879
1959
  validateObjectRef(ref);
1960
+ if (++this.inlineReads >= 32) {
1961
+ this.inlineReads = 0;
1962
+ await setImmediate();
1963
+ this.active();
1964
+ }
1880
1965
  assertPrivateDirectory(this.directory);
1881
1966
  assertPrivateDirectory(join(this.directory, "chunks"));
1967
+ const row = this.db.prepare("SELECT bytes,ciphertext FROM objects WHERE hash=?").get(ref.sha256);
1968
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1969
+ if (row?.ciphertext !== void 0 && row.ciphertext !== null) {
1970
+ const cipher = Buffer.from(row.ciphertext);
1971
+ if (cipher.length !== ref.bytes + OVERHEAD) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1972
+ const plain = this.decrypt(cipher, ref.sha256);
1973
+ if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1974
+ return plain;
1975
+ }
1882
1976
  const path3 = join(this.directory, "chunks", ref.sha256);
1883
- const fd = openSync2(path3, constants2.O_RDONLY | noFollow);
1977
+ const file = await open(path3, constants2.O_RDONLY | noFollow);
1884
1978
  try {
1885
- const info = fstatSync2(fd);
1979
+ const info = await file.stat();
1886
1980
  if (!info.isFile() || info.size !== ref.bytes + OVERHEAD || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1887
1981
  throw new Error("PUBLICATION_OBJECT_CORRUPT");
1888
- const plain = this.decrypt(readFileSync2(fd), ref.sha256);
1982
+ const cipher = await file.readFile();
1983
+ this.active();
1984
+ const plain = this.decrypt(cipher, ref.sha256);
1889
1985
  if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1890
1986
  return plain;
1891
1987
  } finally {
1892
- closeSync2(fd);
1988
+ await file.close();
1893
1989
  }
1894
1990
  }
1895
1991
  async has(ref) {
@@ -1904,7 +2000,10 @@ var PublicationObjects = class _PublicationObjects {
1904
2000
  async putContent(body) {
1905
2001
  body = Buffer.from(body);
1906
2002
  const chunks = [];
1907
- for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
2003
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
2004
+ chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
2005
+ if (chunks.length % 32 === 0) await setImmediate();
2006
+ }
1908
2007
  return { bytes: body.length, sha256: sha(body), chunks };
1909
2008
  }
1910
2009
  async readContent(file, maximumBytes) {
@@ -1917,21 +2016,85 @@ var PublicationObjects = class _PublicationObjects {
1917
2016
  return body;
1918
2017
  }
1919
2018
  async captureFile(source) {
2019
+ return this.captureFileWith(source, (body) => this.put(body));
2020
+ }
2021
+ /** Every file is flushed before linking. One directory barrier makes the
2022
+ * whole batch durable before any references are returned to its caller.
2023
+ * Other puts on this handle retain their own immediate directory barrier. */
2024
+ async captureFiles(sources, onProgress, options = {}) {
2025
+ this.active();
2026
+ const chunkConcurrency = options.chunkConcurrency ?? 1;
2027
+ if (!Number.isSafeInteger(chunkConcurrency) || chunkConcurrency < 1 || chunkConcurrency > 8) throw new Error("PUBLICATION_BATCH_TOO_LARGE");
2028
+ const files = [];
2029
+ let completedBytes = 0, completedFiles = 0, wroteFiles = false;
2030
+ let pending = [];
2031
+ const put = (body) => new Promise((resolve23, reject) => {
2032
+ if (body.length > INLINE_BYTES) wroteFiles = true;
2033
+ pending.push({ body: Buffer.from(body), resolve: resolve23, reject });
2034
+ if (pending.length !== 1) return;
2035
+ queueMicrotask(() => {
2036
+ const batch = pending;
2037
+ pending = [];
2038
+ void (async () => {
2039
+ for (let offset = 0; offset < batch.length; ) {
2040
+ let end = offset, bytes = 0;
2041
+ while (end < batch.length && bytes + batch[end].body.length <= 8 * 1024 * 1024) bytes += batch[end++].body.length;
2042
+ const contents = await this.putContentsWith(batch.slice(offset, end).map((item) => item.body), true);
2043
+ for (let i = offset; i < end; i++) batch[i].resolve(contents[i - offset].chunks[0]);
2044
+ offset = end;
2045
+ }
2046
+ })().catch((error) => {
2047
+ for (const item of batch) item.reject(error);
2048
+ });
2049
+ });
2050
+ });
2051
+ try {
2052
+ for (let offset = 0; offset < sources.length; offset += 32) {
2053
+ const results = await Promise.allSettled(sources.slice(offset, offset + 32).map(async (source) => {
2054
+ let previousBytes = 0;
2055
+ const file = await this.captureFileWith(source, put, (bytes) => {
2056
+ completedBytes += bytes - previousBytes;
2057
+ previousBytes = bytes;
2058
+ onProgress?.({ completedFiles, completedBytes });
2059
+ }, chunkConcurrency);
2060
+ completedFiles++;
2061
+ if (completedFiles < sources.length) onProgress?.({ completedFiles, completedBytes });
2062
+ return file;
2063
+ }));
2064
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2065
+ for (const result of results) if (result.status === "fulfilled") files.push(result.value);
2066
+ }
2067
+ } finally {
2068
+ if (wroteFiles) await syncDirAsync(join(this.directory, "chunks"));
2069
+ }
2070
+ onProgress?.({ completedFiles: files.length, completedBytes });
2071
+ return files;
2072
+ }
2073
+ async captureFileWith(source, put, onBytes, chunkConcurrency = 1) {
1920
2074
  this.active();
1921
2075
  if (lstatSync2(source).isSymbolicLink() || realpathSync(dirname(source)) !== resolve(dirname(source))) throw new Error("SYMLINK_REFUSED");
1922
2076
  const fd = openSync2(source, constants2.O_RDONLY | noFollow);
1923
2077
  try {
1924
2078
  const before = fstatSync2(fd, { bigint: true });
1925
2079
  if (!before.isFile()) throw new Error("PUBLICATION_NOT_REGULAR_FILE");
1926
- const chunks = [], digest3 = createHash("sha256"), buffer = Buffer.alloc(PUBLICATION_CHUNK_BYTES);
2080
+ const chunks = [], digest3 = createHash("sha256"), buffer = Buffer.alloc(Math.min(PUBLICATION_CHUNK_BYTES, Number(before.size) || 1));
1927
2081
  let bytes = 0;
1928
2082
  for (; ; ) {
1929
- const count = readSync(fd, buffer, 0, buffer.length, null);
1930
- if (!count) break;
1931
- const chunk = buffer.subarray(0, count);
1932
- digest3.update(chunk);
1933
- bytes += count;
1934
- chunks.push(await this.put(chunk));
2083
+ const batch = [];
2084
+ for (let i = 0; i < chunkConcurrency; i++) {
2085
+ const count = readSync(fd, buffer, 0, buffer.length, null);
2086
+ if (!count) break;
2087
+ const chunk = Buffer.from(buffer.subarray(0, count));
2088
+ digest3.update(chunk);
2089
+ bytes += count;
2090
+ batch.push(chunk);
2091
+ }
2092
+ if (!batch.length) break;
2093
+ const results = await Promise.allSettled(batch.map(put));
2094
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2095
+ for (const result of results) if (result.status === "fulfilled") chunks.push(result.value);
2096
+ onBytes?.(bytes);
2097
+ if (chunks.length % 32 === 0) await setImmediate();
1935
2098
  }
1936
2099
  const after = fstatSync2(fd, { bigint: true }), path3 = lstatSync2(source, { bigint: true });
1937
2100
  if (path3.isSymbolicLink() || [after, path3].some((s) => ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((k) => s[k] !== before[k])) || BigInt(bytes) !== before.size) throw new Error("PUBLICATION_SOURCE_CHANGED");
@@ -1941,8 +2104,28 @@ var PublicationObjects = class _PublicationObjects {
1941
2104
  }
1942
2105
  }
1943
2106
  async restoreFile(file, destination) {
2107
+ return this.restoreFileWith(file, destination, false);
2108
+ }
2109
+ /** Private restore batches flush each file before linking it, then publish
2110
+ * the directory entries together. All started writers settle on failure. */
2111
+ async restoreFiles(files) {
2112
+ this.active();
2113
+ for (let offset = 0; offset < files.length; offset += 32) {
2114
+ const batch = files.slice(offset, offset + 32);
2115
+ const results = await Promise.allSettled(batch.map((file) => this.restoreFileWith(file.content, file.destination, true, file.mode)));
2116
+ const directories = [...new Set(batch.map((file) => dirname(file.destination)))];
2117
+ for (let i = 0; i < directories.length; i += 8) {
2118
+ const synced = await Promise.allSettled(directories.slice(i, i + 8).map(syncDirAsync));
2119
+ for (const result of synced) if (result.status === "rejected") throw result.reason;
2120
+ }
2121
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2122
+ }
2123
+ }
2124
+ async restoreFileWith(file, destination, deferDirectorySync, mode = 384) {
1944
2125
  this.active();
1945
2126
  validateFileContent(file);
2127
+ if (mode !== 384 && mode !== 448) throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
2128
+ file = { ...file, chunks: file.chunks.map((ref) => ({ ...ref })) };
1946
2129
  if (realpathSync(dirname(destination)) !== resolve(dirname(destination))) throw new Error("SYMLINK_REFUSED");
1947
2130
  try {
1948
2131
  lstatSync2(destination);
@@ -1951,26 +2134,27 @@ var PublicationObjects = class _PublicationObjects {
1951
2134
  if (error.code !== "ENOENT") throw error;
1952
2135
  }
1953
2136
  const temp = join(dirname(destination), "." + randomUUID() + ".partial"), digest3 = createHash("sha256");
1954
- const fd = openSync2(temp, "wx", 384);
2137
+ const fd = await open(temp, "wx", 384);
1955
2138
  try {
1956
2139
  for (const ref of file.chunks) {
1957
2140
  const body = await this.read(ref);
1958
2141
  digest3.update(body);
1959
2142
  let offset = 0;
1960
- while (offset < body.length) offset += writeSync2(fd, body, offset, body.length - offset);
2143
+ while (offset < body.length) offset += (await fd.write(body, offset, body.length - offset)).bytesWritten;
1961
2144
  }
1962
2145
  if (digest3.digest("hex") !== file.sha256) throw new Error("PUBLICATION_FILE_CORRUPT");
1963
- fsyncSync2(fd);
2146
+ if (mode !== 384) await fd.chmod(mode);
2147
+ await fd.sync();
1964
2148
  try {
1965
- linkSync(temp, destination);
2149
+ await link(temp, destination);
1966
2150
  } catch (error) {
1967
2151
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
1968
2152
  throw error;
1969
2153
  }
1970
- syncDir(dirname(destination));
2154
+ if (!deferDirectorySync) await syncDirAsync(dirname(destination));
1971
2155
  } finally {
1972
- closeSync2(fd);
1973
- unlinkSync2(temp);
2156
+ await fd.close();
2157
+ await unlink(temp);
1974
2158
  }
1975
2159
  }
1976
2160
  close() {
@@ -1986,8 +2170,188 @@ var PublicationObjects = class _PublicationObjects {
1986
2170
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
1987
2171
  import { createHash as createHash2 } from "node:crypto";
1988
2172
  import { lstatSync as lstatSync3 } from "node:fs";
1989
- import { join as join2, resolve as resolve2 } from "node:path";
1990
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
2173
+ import { join as join3, resolve as resolve3 } from "node:path";
2174
+
2175
+ // src/continuity/inventory.ts
2176
+ import { constants as constants3 } from "node:fs";
2177
+ import { lstat, open as open2, readdir, realpath } from "node:fs/promises";
2178
+ import { isAbsolute, join as join2, relative, resolve as resolve2, sep } from "node:path";
2179
+ 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(" "));
2180
+ var STATE_EXCLUDED = {
2181
+ ".continuity": "local runtime control; never business state",
2182
+ ".engine.pid": "local process identity",
2183
+ ".bg-worker.pid": "local process identity",
2184
+ ".travel-restored.json": "deployment activation gate; recreated on restore",
2185
+ ".travel-enrolled.json": "local runtime enrollment; recreated per node",
2186
+ ".travel-active.json": "local activation receipt; recreated per generation",
2187
+ ".git": "source control metadata",
2188
+ ".gitignore": "source control metadata",
2189
+ ".log-baseline.txt": "local diagnostics",
2190
+ logs: "local diagnostics; not authoritative history",
2191
+ diagnostics: "local diagnostics",
2192
+ backups: "historical recovery copies; not active state",
2193
+ "package.json": "installed application metadata",
2194
+ "start.sh": "local launcher; deployment must be reviewed separately",
2195
+ node_modules: "installed dependencies",
2196
+ install: "installed application",
2197
+ CogniFold: "installed optional runtime",
2198
+ "everos-venv": "installed Python runtime",
2199
+ "ollama-models": "installed model weights"
2200
+ };
2201
+ var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
2202
+ var WORKSPACE_DIAGNOSTICS = /* @__PURE__ */ new Set([".system-prompt.txt", ".context-debug.txt"]);
2203
+ var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
2204
+ var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
2205
+ var CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
2206
+ function coreReason(path3) {
2207
+ const name = path3.split("/").at(-1);
2208
+ if (CORE_OMITTED.has(name) || /(?:\.lance$|(?:^|[-.])bak(?:[-.]|$))/i.test(name)) return "optional attachments, historical copies or rebuildable indexes; outside core travel";
2209
+ if (/\.(?:mp4|mov|mkv|webm|avi|m4v|mp3|wav|ogg|opus|m4a|aac|flac|png|jpe?g|gif|webp|heic|bmp|tiff?|ico|pdf|docx?|pptx?|xlsx?|zip|gz|tgz|tar|7z|rar|dmg|exe|dll|so|dylib|bin|onnx|safetensors|gguf|vrm|glb|gltf|fbx|ttf|otf|woff2?|pyc|log|out)$/i.test(name) || name === ".DS_Store" || name === "package-lock.json" || name === ".context-debug.txt" || path3 === "mem7/spool/intake.failed.jsonl") return "attachments, installed binaries or diagnostics; outside core travel";
2210
+ }
2211
+ function stateReason(name, options) {
2212
+ if (options.selection === "core" && coreReason(name)) return coreReason(name);
2213
+ if (options.includeStateEntries?.includes(name)) return void 0;
2214
+ return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
2215
+ }
2216
+ function knownState(name) {
2217
+ return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
2218
+ }
2219
+ async function classifyState(options) {
2220
+ const result = { included: [], excluded: [], unclassified: [] };
2221
+ for (const name of (await readdir(options.stateDir)).sort()) {
2222
+ const reason = stateReason(name, options);
2223
+ if (reason) result.excluded.push({ path: name, reason });
2224
+ else if (options.selection === "core" || knownState(name) || options.includeStateEntries?.includes(name) || resolve2(options.stateDir, name) === resolve2(options.workspace ?? join2(options.stateDir, "workspace"))) result.included.push(name);
2225
+ else result.unclassified.push(name);
2226
+ }
2227
+ return result;
2228
+ }
2229
+ function validateRelativePath(path3) {
2230
+ if (typeof path3 !== "string" || !path3 || path3.length > 2048 || isAbsolute(path3)) throw new Error("INVALID_ARTIFACT_PATH");
2231
+ for (const part of path3.split("/")) {
2232
+ if (!part || part === "." || part === ".." || /[\x00-\x1f]/.test(part) || Buffer.byteLength(part) > 255 || process.platform === "win32" && (/[<>:"|?*\\]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part)))
2233
+ throw new Error("INVALID_ARTIFACT_PATH");
2234
+ }
2235
+ }
2236
+ function isWithin(root, candidate) {
2237
+ const rel = relative(resolve2(root), resolve2(candidate));
2238
+ return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2239
+ }
2240
+ async function collectInventory(options) {
2241
+ if (options.selection !== void 0 && options.selection !== "core") throw new Error("INVALID_INVENTORY_SELECTION");
2242
+ const state2 = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join2(state2, "workspace"));
2243
+ if (state2 === workspace || isWithin(workspace, state2)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
2244
+ const roots = { state: state2, workspace }, entries = [], exclusions2 = [], aliases = /* @__PURE__ */ new Set();
2245
+ const include = new Set(options.includeStateEntries ?? []);
2246
+ for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
2247
+ validateRelativePath(name);
2248
+ if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
2249
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2250
+ }
2251
+ for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
2252
+ for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
2253
+ validateRelativePath(name);
2254
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2255
+ if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
2256
+ }
2257
+ const classification = await classifyState(options);
2258
+ if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
2259
+ async function walk(root, directory2, prefix = "", ancestors = /* @__PURE__ */ new Set()) {
2260
+ const canonical3 = await realpath(directory2);
2261
+ if (ancestors.has(canonical3)) throw new Error(`SYMLINK_CYCLE: ${root}/${prefix}`);
2262
+ const parents = new Set(ancestors);
2263
+ parents.add(canonical3);
2264
+ for (const name of (await readdir(directory2)).sort()) {
2265
+ const path3 = prefix ? prefix + "/" + name : name;
2266
+ let source = join2(directory2, name);
2267
+ if (root === "state" && source === workspace) continue;
2268
+ let reason = NESTED_EXCLUDED[name];
2269
+ if (root === "state" && prefix) reason = options.excludeStateEntries?.[path3] ?? reason;
2270
+ if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path3] ?? reason;
2271
+ if (root === "workspace" && !prefix && WORKSPACE_DIAGNOSTICS.has(name)) reason = "generated runtime diagnostics; recreated on each node";
2272
+ if (!prefix && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
2273
+ if (root === "state" && !prefix) {
2274
+ reason = stateReason(name, options);
2275
+ if (!reason && options.selection !== "core" && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
2276
+ }
2277
+ if (options.selection === "core") reason = coreReason(path3) ?? reason;
2278
+ if (reason) {
2279
+ exclusions2.push({ root, path: path3, reason });
2280
+ continue;
2281
+ }
2282
+ validateRelativePath(path3);
2283
+ const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
2284
+ if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
2285
+ aliases.add(key2);
2286
+ let info = await lstat(source, { bigint: true }), linkSignature = "";
2287
+ if (options.selection === "core" && root === "workspace" && !prefix && !CORE_DIRECTORIES.has(name) && (info.isDirectory() || info.isSymbolicLink() && !/\.[a-z0-9]+$/i.test(name))) {
2288
+ exclusions2.push({ root, path: path3, reason: "optional workspace material; outside core travel" });
2289
+ continue;
2290
+ }
2291
+ if (info.isSymbolicLink()) {
2292
+ linkSignature = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":") + ":";
2293
+ try {
2294
+ source = await realpath(source);
2295
+ } catch {
2296
+ throw new Error(`SYMLINK_REFUSED: ${root}/${path3}`);
2297
+ }
2298
+ info = await lstat(source, { bigint: true });
2299
+ linkSignature += source + ":";
2300
+ }
2301
+ if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
2302
+ if (options.selection === "core" && root === "workspace" && !prefix && info.isDirectory() && !CORE_DIRECTORIES.has(name)) {
2303
+ exclusions2.push({ root, path: path3, reason: "optional workspace material; outside core travel" });
2304
+ continue;
2305
+ }
2306
+ if (info.isDirectory()) {
2307
+ try {
2308
+ const marker = await lstat(join2(source, "pyvenv.cfg"));
2309
+ if (marker.isFile() && !marker.isSymbolicLink()) {
2310
+ exclusions2.push({ root, path: path3, reason: "installed Python virtual environment; rebuild for the target platform" });
2311
+ continue;
2312
+ }
2313
+ } catch (error) {
2314
+ if (error.code !== "ENOENT") throw error;
2315
+ }
2316
+ }
2317
+ const entry = {
2318
+ root,
2319
+ path: path3,
2320
+ source,
2321
+ kind: info.isDirectory() ? "directory" : "file",
2322
+ bytes: Number(info.size),
2323
+ mode: Number(info.mode) & 448,
2324
+ signature: linkSignature + [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
2325
+ };
2326
+ entries.push(entry);
2327
+ if (info.isDirectory()) await walk(root, source, path3, parents);
2328
+ else {
2329
+ const h = await open2(source, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
2330
+ const header = Buffer.alloc(16);
2331
+ try {
2332
+ await h.read(header, 0, 16, 0);
2333
+ } finally {
2334
+ await h.close();
2335
+ }
2336
+ if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
2337
+ else if (info.size > 0n && /\.(db|sqlite|sqlite3)$/i.test(path3)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path3}`);
2338
+ }
2339
+ }
2340
+ }
2341
+ await walk("state", state2);
2342
+ await walk("workspace", workspace);
2343
+ const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
2344
+ for (const entry of entries) {
2345
+ if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
2346
+ if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
2347
+ entry.kind = "sidecar";
2348
+ }
2349
+ }
2350
+ return { entries, exclusions: exclusions2, roots };
2351
+ }
2352
+
2353
+ // src/continuity/publication.ts
2354
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
1991
2355
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
1992
2356
  var ZERO = "0".repeat(64);
1993
2357
  var HASH2 = /^[a-f0-9]{64}$/;
@@ -2028,8 +2392,12 @@ function normalizePublicationProfile(value2) {
2028
2392
  return Object.freeze(profile);
2029
2393
  }
2030
2394
  function validatePublicationPath(path3) {
2031
- if (typeof path3 !== "string" || !path3 || path3.length > 2048 || path3.normalize("NFC") !== path3 || /[\x00-\x1f<>:"|?*\\]/.test(path3) || path3.split("/").some((p) => !p || p === "." || p === ".." || /[. ]$/.test(p) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)))
2395
+ if (typeof path3 !== "string" || path3.normalize("NFC") !== path3) throw new Error("PUBLICATION_INVALID_PATH");
2396
+ try {
2397
+ validateRelativePath(path3);
2398
+ } catch {
2032
2399
  throw new Error("PUBLICATION_INVALID_PATH");
2400
+ }
2033
2401
  }
2034
2402
  function normalizePublication(value2) {
2035
2403
  if (!value2 || value2.format !== "engine7-publication-v1" || !natural(value2.sequence) || !value2.sequence || !HASH2.test(value2.parentDigest) || !natural(value2.deletionWatermark) || !Array.isArray(value2.databases) || !Array.isArray(value2.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
@@ -2134,9 +2502,9 @@ var PublicationReplica = class _PublicationReplica {
2134
2502
  if (b.databaseId !== databaseId || b.baselineId !== this.profile.baselineId || b.epoch !== this.profile.epoch || b.tenantId !== identity.tenantId || b.companionId !== identity.companionId || b.seatId !== identity.seatId)
2135
2503
  throw new Error("PUBLICATION_PROFILE_MISMATCH");
2136
2504
  }
2137
- const directory2 = resolve2(options.directory);
2505
+ const directory2 = resolve3(options.directory);
2138
2506
  preparePrivateDirectory(directory2);
2139
- const path3 = join2(directory2, "publications.sqlite");
2507
+ const path3 = join3(directory2, "publications.sqlite");
2140
2508
  preparePrivateDatabase(path3);
2141
2509
  this.journalFile = path3;
2142
2510
  const journalStat = lstatSync3(path3, { bigint: true });
@@ -2168,8 +2536,8 @@ var PublicationReplica = class _PublicationReplica {
2168
2536
  }
2169
2537
  assertJournal() {
2170
2538
  try {
2171
- const stat = lstatSync3(this.journalFile, { bigint: true });
2172
- if (!stat.isFile() || stat.isSymbolicLink() || `${stat.dev}:${stat.ino}` !== this.journalIncarnation) throw new Error();
2539
+ const stat2 = lstatSync3(this.journalFile, { bigint: true });
2540
+ if (!stat2.isFile() || stat2.isSymbolicLink() || `${stat2.dev}:${stat2.ino}` !== this.journalIncarnation) throw new Error();
2173
2541
  } catch {
2174
2542
  throw new Error("PUBLICATION_CORRUPT_CONTROL");
2175
2543
  }
@@ -2325,9 +2693,11 @@ var PublicationReplica = class _PublicationReplica {
2325
2693
  throw error;
2326
2694
  }
2327
2695
  }
2328
- async status() {
2696
+ // Paired control reads use the durable published cut. Original bytes are
2697
+ // verified when published and restored, rather than on every status poll.
2698
+ async status(verifyFiles = true) {
2329
2699
  const c = this.control(), manifest = c.head ? await this.manifest(c.head) : null;
2330
- const dataReady = manifest ? (await this.missing(manifest)).length === 0 : false;
2700
+ const dataReady = manifest ? (verifyFiles ? await this.missing(manifest) : this.databaseMissing(manifest)).length === 0 : false;
2331
2701
  const { applied } = await this.replicationStatus();
2332
2702
  const current2 = this.control();
2333
2703
  const stillReady = dataReady && manifest !== null && current2.head === c.head && current2.digest === c.digest && manifest.deletionWatermark >= current2.floor && this.databaseMissing(manifest).length === 0;
@@ -2371,18 +2741,18 @@ var PublicationReplica = class _PublicationReplica {
2371
2741
  };
2372
2742
 
2373
2743
  // src/continuity/publication-files.ts
2374
- import { DatabaseSync as DatabaseSync4, backup } from "node:sqlite";
2375
- import { lstatSync as lstatSync4, readdirSync, realpathSync as realpathSync2, mkdirSync as mkdirSync3, writeFileSync as writeFileSync2, chmodSync, openSync as openSync4, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "node:fs";
2376
- import { join as join4, resolve as resolve4, dirname as dirname2 } from "node:path";
2744
+ import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
2745
+ import { lstatSync as lstatSync4, readdirSync, realpathSync as realpathSync2, mkdirSync as mkdirSync3, writeFileSync, chmodSync, openSync as openSync4, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "node:fs";
2746
+ import { join as join5, resolve as resolve4, dirname as dirname3 } from "node:path";
2377
2747
 
2378
2748
  // src/continuity/crypto.ts
2379
- import { constants as constants3, createWriteStream, openSync as openSync3 } from "node:fs";
2380
- import { open, lstat, link, unlink, writeFile, appendFile } from "node:fs/promises";
2749
+ import { constants as constants4, createWriteStream, openSync as openSync3 } from "node:fs";
2750
+ import { open as open3, lstat as lstat2, link as link2, unlink as unlink2, writeFile as writeFile2, appendFile } from "node:fs/promises";
2381
2751
  var MAGIC2 = Buffer.from("E7OBJ001");
2382
2752
  var HEADER_SIZE = MAGIC2.length + 12;
2383
2753
  async function syncDirectory(directory2) {
2384
2754
  if (process.platform === "win32") return;
2385
- const handle = await open(directory2, constants3.O_RDONLY);
2755
+ const handle = await open3(directory2, constants4.O_RDONLY);
2386
2756
  try {
2387
2757
  await handle.sync();
2388
2758
  } finally {
@@ -2390,148 +2760,69 @@ async function syncDirectory(directory2) {
2390
2760
  }
2391
2761
  }
2392
2762
 
2393
- // src/continuity/inventory.ts
2394
- import { constants as constants4 } from "node:fs";
2395
- import { lstat as lstat2, open as open2, readdir, realpath } from "node:fs/promises";
2396
- import { isAbsolute, join as join3, relative, resolve as resolve3, sep } from "node:path";
2397
- 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(" "));
2398
- var STATE_EXCLUDED = {
2399
- ".continuity": "local runtime control; never business state",
2400
- ".engine.pid": "local process identity",
2401
- ".bg-worker.pid": "local process identity",
2402
- ".travel-restored.json": "deployment activation gate; recreated on restore",
2403
- ".travel-enrolled.json": "local runtime enrollment; recreated per node",
2404
- ".travel-active.json": "local activation receipt; recreated per generation",
2405
- ".git": "source control metadata",
2406
- ".gitignore": "source control metadata",
2407
- ".log-baseline.txt": "local diagnostics",
2408
- logs: "local diagnostics; not authoritative history",
2409
- diagnostics: "local diagnostics",
2410
- backups: "historical recovery copies; not active state",
2411
- "package.json": "installed application metadata",
2412
- "start.sh": "local launcher; deployment must be reviewed separately",
2413
- node_modules: "installed dependencies",
2414
- install: "installed application",
2415
- CogniFold: "installed optional runtime",
2416
- "everos-venv": "installed Python runtime",
2417
- "ollama-models": "installed model weights"
2418
- };
2419
- var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
2420
- var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
2421
- function stateReason(name, options) {
2422
- if (options.includeStateEntries?.includes(name)) return void 0;
2423
- return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
2424
- }
2425
- function knownState(name) {
2426
- return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
2427
- }
2428
- async function classifyState(options) {
2429
- const result = { included: [], excluded: [], unclassified: [] };
2430
- for (const name of (await readdir(options.stateDir)).sort()) {
2431
- const reason = stateReason(name, options);
2432
- if (reason) result.excluded.push({ path: name, reason });
2433
- else if (knownState(name) || options.includeStateEntries?.includes(name) || resolve3(options.stateDir, name) === resolve3(options.workspace ?? join3(options.stateDir, "workspace"))) result.included.push(name);
2434
- else result.unclassified.push(name);
2763
+ // src/continuity/native-database-snapshot.ts
2764
+ import { DatabaseSync as DatabaseSync4, backup } from "node:sqlite";
2765
+ import { lstat as lstat3 } from "node:fs/promises";
2766
+
2767
+ // src/continuity/native-file-copy.ts
2768
+ import { constants as constants5 } from "node:fs";
2769
+ import { copyFile, link as link3, rename, rm, stat } from "node:fs/promises";
2770
+ import { execFile } from "node:child_process";
2771
+ import { promisify } from "node:util";
2772
+ import { dirname as dirname2, join as join4 } from "node:path";
2773
+ import { randomUUID as randomUUID2 } from "node:crypto";
2774
+ var exec = promisify(execFile);
2775
+ async function copyNativeFile(source, destination, flags = constants5.COPYFILE_EXCL | constants5.COPYFILE_FICLONE, bytes) {
2776
+ if (process.platform !== "darwin") {
2777
+ await copyFile(source, destination, flags);
2778
+ return;
2435
2779
  }
2436
- return result;
2437
- }
2438
- function validateRelativePath(path3) {
2439
- if (typeof path3 !== "string" || !path3 || path3.length > 2048 || path3.includes("\\") || isAbsolute(path3)) throw new Error("INVALID_ARTIFACT_PATH");
2440
- for (const part of path3.split("/")) {
2441
- if (!part || part === "." || part === ".." || /[\x00-\x1f<>:"|?*]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part) || Buffer.byteLength(part) > 255)
2442
- throw new Error("INVALID_ARTIFACT_PATH");
2780
+ if ((bytes ?? (await stat(source)).size) < 1024 * 1024) {
2781
+ await copyFile(source, destination, flags);
2782
+ return;
2783
+ }
2784
+ const temporary = join4(dirname2(destination), ".e7-native-copy-" + randomUUID2());
2785
+ try {
2786
+ await exec("/bin/cp", ["-c", "-p", source, temporary], { maxBuffer: 8192 });
2787
+ if (flags & constants5.COPYFILE_EXCL) await link3(temporary, destination);
2788
+ else await rename(temporary, destination);
2789
+ } finally {
2790
+ await rm(temporary, { force: true });
2443
2791
  }
2444
2792
  }
2445
- function isWithin(root, candidate) {
2446
- const rel = relative(resolve3(root), resolve3(candidate));
2447
- return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2448
- }
2449
- async function collectInventory(options) {
2450
- const state2 = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join3(state2, "workspace"));
2451
- if (state2 === workspace || isWithin(workspace, state2)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
2452
- const roots = { state: state2, workspace }, entries = [], exclusions2 = [], aliases = /* @__PURE__ */ new Set();
2453
- const include = new Set(options.includeStateEntries ?? []);
2454
- for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
2455
- validateRelativePath(name);
2456
- if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
2457
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2793
+
2794
+ // src/continuity/native-database-snapshot.ts
2795
+ async function snapshotNativeDatabase(db, destination) {
2796
+ if (process.platform !== "darwin") {
2797
+ await backup(db, destination);
2798
+ return;
2458
2799
  }
2459
- for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
2460
- for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
2461
- validateRelativePath(name);
2462
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2463
- if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
2800
+ const file = String(db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? "");
2801
+ if (!file) {
2802
+ await backup(db, destination);
2803
+ return;
2464
2804
  }
2465
- const classification = await classifyState(options);
2466
- if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
2467
- async function walk(root, directory2, prefix = "") {
2468
- for (const name of (await readdir(directory2)).sort()) {
2469
- const path3 = prefix ? prefix + "/" + name : name, source = join3(directory2, name);
2470
- if (root === "state" && source === workspace) continue;
2471
- let reason = NESTED_EXCLUDED[name];
2472
- if (root === "state" && prefix) reason = options.excludeStateEntries?.[path3] ?? reason;
2473
- if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path3] ?? reason;
2474
- if (!prefix && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
2475
- if (root === "state" && !prefix) {
2476
- reason = stateReason(name, options);
2477
- if (!reason && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
2478
- }
2479
- if (reason) {
2480
- exclusions2.push({ root, path: path3, reason });
2481
- continue;
2482
- }
2483
- validateRelativePath(path3);
2484
- const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
2485
- if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
2486
- aliases.add(key2);
2487
- const info = await lstat2(source, { bigint: true });
2488
- if (info.isSymbolicLink()) throw new Error(`SYMLINK_REFUSED: ${root}/${path3}`);
2489
- if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
2490
- if (info.isDirectory()) {
2491
- try {
2492
- const marker = await lstat2(join3(source, "pyvenv.cfg"));
2493
- if (marker.isFile() && !marker.isSymbolicLink()) {
2494
- exclusions2.push({ root, path: path3, reason: "installed Python virtual environment; rebuild for the target platform" });
2495
- continue;
2496
- }
2497
- } catch (error) {
2498
- if (error.code !== "ENOENT") throw error;
2499
- }
2500
- }
2501
- const entry = {
2502
- root,
2503
- path: path3,
2504
- source,
2505
- kind: info.isDirectory() ? "directory" : "file",
2506
- bytes: Number(info.size),
2507
- mode: Number(info.mode) & 448,
2508
- signature: [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
2509
- };
2510
- entries.push(entry);
2511
- if (info.isDirectory()) await walk(root, source, path3);
2512
- else {
2513
- const h = await open2(source, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
2514
- const header = Buffer.alloc(16);
2515
- try {
2516
- await h.read(header, 0, 16, 0);
2517
- } finally {
2518
- await h.close();
2519
- }
2520
- if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
2521
- else if (/\.(db|sqlite|sqlite3)$/i.test(path3)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path3}`);
2522
- }
2805
+ const reader = new DatabaseSync4(file, { readOnly: true, allowExtension: true });
2806
+ try {
2807
+ reader.exec("BEGIN");
2808
+ reader.prepare("SELECT count(*) FROM sqlite_master").get();
2809
+ await copyNativeFile(file, destination);
2810
+ try {
2811
+ await lstat3(file + "-wal");
2812
+ await copyNativeFile(file + "-wal", destination + "-wal");
2813
+ } catch (error) {
2814
+ if (error.code !== "ENOENT") throw error;
2523
2815
  }
2816
+ reader.exec("ROLLBACK");
2817
+ } finally {
2818
+ reader.close();
2524
2819
  }
2525
- await walk("state", state2);
2526
- await walk("workspace", workspace);
2527
- const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
2528
- for (const entry of entries) {
2529
- if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
2530
- if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
2531
- entry.kind = "sidecar";
2532
- }
2820
+ const target = new DatabaseSync4(destination);
2821
+ try {
2822
+ if (Number(target.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()?.busy) !== 0) throw Error("DATABASE_SNAPSHOT_BUSY");
2823
+ } finally {
2824
+ target.close();
2533
2825
  }
2534
- return { entries, exclusions: exclusions2, roots };
2535
2826
  }
2536
2827
 
2537
2828
  // src/continuity/publication-files.ts
@@ -2539,7 +2830,7 @@ function inventory(root) {
2539
2830
  if (realpathSync2(root) !== resolve4(root)) throw new Error("SYMLINK_REFUSED");
2540
2831
  const entries = [];
2541
2832
  const visit = (path3) => {
2542
- const info = lstatSync4(join4(root, path3), { bigint: true });
2833
+ const info = lstatSync4(join5(root, path3), { bigint: true });
2543
2834
  if (info.isSymbolicLink()) throw new Error("SYMLINK_REFUSED");
2544
2835
  if (!info.isDirectory() && !info.isFile()) throw new Error("PUBLICATION_NOT_REGULAR_FILE");
2545
2836
  if (path3) validatePublicationPath(path3);
@@ -2550,7 +2841,7 @@ function inventory(root) {
2550
2841
  mode: info.mode & 0o100n ? 448 : 384,
2551
2842
  signature: [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs, info.mode].map(String).join(":")
2552
2843
  });
2553
- if (info.isDirectory()) for (const name of readdirSync(join4(root, path3)).sort()) visit(path3 ? path3 + "/" + name : name);
2844
+ if (info.isDirectory()) for (const name of readdirSync(join5(root, path3)).sort()) visit(path3 ? path3 + "/" + name : name);
2554
2845
  };
2555
2846
  visit("");
2556
2847
  if (!entries[0].directory) throw new Error("PUBLICATION_DIRECTORY_REQUIRED");
@@ -2571,7 +2862,7 @@ async function capturePublication(options) {
2571
2862
  for (const entry of entries) {
2572
2863
  if (!entry.path) continue;
2573
2864
  if (entry.directory) tree.directories.push(entry.path);
2574
- else tree.files.push({ path: entry.path, mode: entry.mode, content: await options.objects.captureFile(join4(root.path, entry.path)) });
2865
+ else tree.files.push({ path: entry.path, mode: entry.mode, content: await options.objects.captureFile(join5(root.path, entry.path)) });
2575
2866
  }
2576
2867
  trees.push(tree);
2577
2868
  }
@@ -2587,12 +2878,12 @@ async function capturePublication(options) {
2587
2878
  });
2588
2879
  }
2589
2880
  async function restorePublication(options) {
2590
- const { receiver } = options, status = await receiver.status();
2881
+ const { receiver } = options, status = await receiver.status(false);
2591
2882
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
2592
2883
  const manifest = await receiver.manifest(status.published.sequence);
2593
2884
  if (JSON.stringify(Object.keys(options.databases).sort()) !== JSON.stringify(manifest.profile.databaseIds)) throw new Error("PUBLICATION_INCOMPLETE_DATABASES");
2594
2885
  const destination = resolve4(options.destination);
2595
- if (realpathSync2(dirname2(destination)) !== dirname2(destination)) throw new Error("SYMLINK_REFUSED");
2886
+ if (realpathSync2(dirname3(destination)) !== dirname3(destination)) throw new Error("SYMLINK_REFUSED");
2596
2887
  if (isWithin(receiver.objects.directory, destination) || isWithin(destination, receiver.objects.directory)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
2597
2888
  try {
2598
2889
  mkdirSync3(destination, { mode: 448 });
@@ -2600,8 +2891,8 @@ async function restorePublication(options) {
2600
2891
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
2601
2892
  throw error;
2602
2893
  }
2603
- await syncDirectory(dirname2(destination));
2604
- writeFileSync2(join4(destination, ".travel-restored.json"), JSON.stringify({
2894
+ await syncDirectory(dirname3(destination));
2895
+ writeFileSync(join5(destination, ".travel-restored.json"), JSON.stringify({
2605
2896
  format: "engine7-publication-restore-v1",
2606
2897
  activationAllowed: false,
2607
2898
  sequence: manifest.sequence,
@@ -2611,25 +2902,25 @@ async function restorePublication(options) {
2611
2902
  const created = /* @__PURE__ */ new Set([destination]);
2612
2903
  const directory2 = (path3) => {
2613
2904
  const missing = [];
2614
- for (let current2 = path3; isWithin(destination, current2) && !created.has(current2); current2 = dirname2(current2)) missing.push(current2);
2905
+ for (let current2 = path3; isWithin(destination, current2) && !created.has(current2); current2 = dirname3(current2)) missing.push(current2);
2615
2906
  for (const current2 of missing.reverse()) {
2616
2907
  mkdirSync3(current2, { mode: 448 });
2617
2908
  created.add(current2);
2618
2909
  }
2619
2910
  };
2620
- directory2(join4(destination, "databases"));
2621
- directory2(join4(destination, "trees"));
2911
+ directory2(join5(destination, "databases"));
2912
+ directory2(join5(destination, "trees"));
2622
2913
  for (const item of manifest.databases) {
2623
- const path3 = join4(destination, "databases", item.databaseId + ".sqlite");
2624
- await backup(options.databases[item.databaseId], path3);
2914
+ const path3 = join5(destination, "databases", item.databaseId + ".sqlite");
2915
+ await snapshotNativeDatabase(options.databases[item.databaseId], path3);
2625
2916
  chmodSync(path3, 384);
2626
- const copy = new DatabaseSync4(path3, { readOnly: true });
2917
+ const copy = new DatabaseSync5(path3, { readOnly: true });
2627
2918
  try {
2628
2919
  const row = copy.prepare("SELECT head,digest,binding FROM e7_replication_control WHERE role='replica'").get();
2629
2920
  const identity = manifest.profile.identity;
2630
2921
  const wanted = [identity.tenantId, identity.companionId, identity.seatId, item.databaseId, manifest.profile.baselineId, manifest.profile.epoch];
2631
- const check = copy.prepare("PRAGMA quick_check").all();
2632
- if (!row || row.head !== item.head.sequence || row.digest !== item.head.digest || row.binding !== JSON.stringify(wanted) || check.length !== 1 || check[0].quick_check !== "ok") throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
2922
+ if (!row || row.head !== item.head.sequence || row.digest !== item.head.digest || row.binding !== JSON.stringify(wanted))
2923
+ throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
2633
2924
  } finally {
2634
2925
  copy.close();
2635
2926
  }
@@ -2640,27 +2931,27 @@ async function restorePublication(options) {
2640
2931
  closeSync3(fd);
2641
2932
  }
2642
2933
  }
2934
+ const files = [];
2643
2935
  for (const tree of manifest.trees) {
2644
- const root = join4(destination, "trees", tree.id);
2936
+ const root = join5(destination, "trees", tree.id);
2645
2937
  directory2(root);
2646
- for (const path3 of tree.directories) directory2(join4(root, path3));
2938
+ for (const path3 of tree.directories) directory2(join5(root, path3));
2647
2939
  for (const file of tree.files) {
2648
- const path3 = join4(root, file.path);
2649
- directory2(dirname2(path3));
2650
- await receiver.objects.restoreFile(file.content, path3);
2651
- chmodSync(path3, file.mode);
2652
- const fd = openSync4(path3, "r+");
2653
- try {
2654
- fsyncSync3(fd);
2655
- } finally {
2656
- closeSync3(fd);
2657
- }
2940
+ const path3 = join5(root, file.path);
2941
+ directory2(dirname3(path3));
2942
+ files.push({ content: file.content, destination: path3, mode: file.mode });
2658
2943
  }
2659
2944
  }
2660
- const after = await receiver.status();
2945
+ try {
2946
+ await receiver.objects.restoreFiles(files);
2947
+ } catch (error) {
2948
+ if (error.code === "ENOENT") throw new Error("PUBLICATION_NOT_READY");
2949
+ throw error;
2950
+ }
2951
+ const after = await receiver.status(false);
2661
2952
  if (!after.dataReady || after.published?.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
2662
2953
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
2663
- if (!options.deferReceipt) writeFileSync2(join4(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
2954
+ if (!options.deferReceipt) writeFileSync(join5(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
2664
2955
  await syncDirectory(destination);
2665
2956
  return status.published;
2666
2957
  }
@@ -2759,7 +3050,7 @@ function createPublicationServer(options) {
2759
3050
  };
2760
3051
  switch (value2.operation) {
2761
3052
  case "status":
2762
- result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
3053
+ result = preservePublished ? await mutate(() => receiver.status(false)) : await receiver.status(false);
2763
3054
  break;
2764
3055
  case "replication-status":
2765
3056
  result = await receiver.replicationStatus();
@@ -2767,7 +3058,6 @@ function createPublicationServer(options) {
2767
3058
  case "missing": {
2768
3059
  if (!Array.isArray(value2.refs) || value2.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
2769
3060
  const missing = await Promise.all(value2.refs.map(async (ref) => {
2770
- await check();
2771
3061
  validateObjectRef(ref);
2772
3062
  return await receiver.objects.has(ref) ? null : ref.sha256;
2773
3063
  }));
@@ -3056,13 +3346,13 @@ async function syncPublication(options) {
3056
3346
  init_sqlite_replication();
3057
3347
 
3058
3348
  // src/continuity/sqlite-store-location.ts
3059
- import { basename as basename3, dirname as dirname6, resolve as resolve7 } from "node:path";
3349
+ import { basename as basename3, dirname as dirname7, resolve as resolve7 } from "node:path";
3060
3350
 
3061
3351
  // src/continuity/mem7-replication.ts
3062
- import { closeSync as closeSync5, fsyncSync as fsyncSync5, lstatSync as lstatSync6, openSync as openSync6, writeFileSync as writeFileSync4 } from "node:fs";
3063
- import { dirname as dirname4, join as join6 } from "node:path";
3352
+ import { closeSync as closeSync5, fsyncSync as fsyncSync5, lstatSync as lstatSync6, openSync as openSync6, writeFileSync as writeFileSync3 } from "node:fs";
3353
+ import { dirname as dirname5, join as join7 } from "node:path";
3064
3354
  init_sqlite_replication();
3065
- var location = (stateDir) => join6(stateDir, ".continuity", "mem7-replication.json");
3355
+ var location = (stateDir) => join7(stateDir, ".continuity", "mem7-replication.json");
3066
3356
  function normalize(value2) {
3067
3357
  if (!value2 || !/^[a-f0-9]{64}$/.test(value2.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
3068
3358
  return Object.freeze({ binding: normalizeBinding(value2.binding), schemaHash: value2.schemaHash });
@@ -3079,7 +3369,7 @@ function hasMem7ReplicationRegistration(stateDir) {
3079
3369
  function readMem7ReplicationRegistration(stateDir) {
3080
3370
  if (!hasMem7ReplicationRegistration(stateDir)) return null;
3081
3371
  try {
3082
- assertPrivateDirectory(dirname4(location(stateDir)));
3372
+ assertPrivateDirectory(dirname5(location(stateDir)));
3083
3373
  return normalize(JSON.parse(readPrivateFile(location(stateDir), 4096).toString()));
3084
3374
  } catch {
3085
3375
  throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -3089,24 +3379,24 @@ function readMem7ReplicationRegistration(stateDir) {
3089
3379
  // src/continuity/sqlite-store-location.ts
3090
3380
  init_runtime_replication();
3091
3381
  function sqliteStoreLocation(file) {
3092
- const absolute4 = resolve7(file), parent = dirname6(absolute4), name = basename3(absolute4);
3093
- if (name === "mem7.db" && basename3(parent) === "index" && basename3(dirname6(parent)) === "mem7")
3094
- return { stateDir: dirname6(dirname6(parent)), component: "mem7" };
3382
+ const absolute4 = resolve7(file), parent = dirname7(absolute4), name = basename3(absolute4);
3383
+ if (name === "mem7.db" && basename3(parent) === "index" && basename3(dirname7(parent)) === "mem7")
3384
+ return { stateDir: dirname7(dirname7(parent)), component: "mem7" };
3095
3385
  let stateDir, component;
3096
3386
  if (name === "calendar.db" && basename3(parent) === ".calendar") {
3097
- stateDir = dirname6(parent);
3387
+ stateDir = dirname7(parent);
3098
3388
  component = "calendar";
3099
3389
  } else if (name === "proactive.db" && basename3(parent) === ".proactive") {
3100
- stateDir = dirname6(parent);
3390
+ stateDir = dirname7(parent);
3101
3391
  component = "proactive";
3102
3392
  } else if (name === "session-events.db" && basename3(parent) === ".continuity") {
3103
- stateDir = dirname6(parent);
3393
+ stateDir = dirname7(parent);
3104
3394
  component = "session-events";
3105
- } else if (name === "memory.db" && basename3(parent) === "memory" && basename3(dirname6(dirname6(parent))) === "agents") {
3106
- stateDir = dirname6(dirname6(dirname6(parent)));
3395
+ } else if (name === "memory.db" && basename3(parent) === "memory" && basename3(dirname7(dirname7(parent))) === "agents") {
3396
+ stateDir = dirname7(dirname7(dirname7(parent)));
3107
3397
  component = "legacy-memory";
3108
- } else if (name === "vectors.db" && basename3(dirname6(parent)) === "topics-history") {
3109
- stateDir = dirname6(dirname6(parent));
3398
+ } else if (name === "vectors.db" && basename3(dirname7(parent)) === "topics-history") {
3399
+ stateDir = dirname7(dirname7(parent));
3110
3400
  component = "topics-vectors";
3111
3401
  } else return null;
3112
3402
  return { stateDir, ...runtimeReplicationLocation(stateDir, component, absolute4) };
@@ -3170,15 +3460,15 @@ init_runtime_lock();
3170
3460
  init_schema_migrations();
3171
3461
 
3172
3462
  // src/continuity/runtime-artifact-cli.ts
3173
- import { DatabaseSync as DatabaseSync11 } from "node:sqlite";
3174
- import { isAbsolute as isAbsolute2, join as join14, resolve as resolve13 } from "node:path";
3463
+ import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
3464
+ import { isAbsolute as isAbsolute2, join as join15, resolve as resolve13 } from "node:path";
3175
3465
  import { lstatSync as lstatSync13, realpathSync as realpathSync9 } from "node:fs";
3176
3466
 
3177
3467
  // src/continuity/runtime-tree-source.ts
3178
- import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
3468
+ import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
3179
3469
  import { createHash as createHash5 } from "node:crypto";
3180
- import { existsSync as existsSync2, writeFileSync as writeFileSync6, openSync as openSync9, closeSync as closeSync8, fsyncSync as fsyncSync7 } from "node:fs";
3181
- import { join as join9, resolve as resolve8 } from "node:path";
3470
+ import { existsSync as existsSync2, writeFileSync as writeFileSync5, openSync as openSync9, closeSync as closeSync8, fsyncSync as fsyncSync7 } from "node:fs";
3471
+ import { join as join10, resolve as resolve8 } from "node:path";
3182
3472
  var ZERO2 = "0".repeat(64);
3183
3473
  var HASH3 = /^[a-f0-9]{64}$/;
3184
3474
  var schema = [
@@ -3210,7 +3500,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
3210
3500
  if (JSON.stringify(this.profile.identity) !== JSON.stringify(this.objects.identity)) throw new Error("TREE_SOURCE_PROFILE_MISMATCH");
3211
3501
  this.maximumBytes = options.maximumBytes ?? 64 * 1024 * 1024;
3212
3502
  if (!Number.isSafeInteger(this.maximumBytes) || this.maximumBytes < 1) throw new Error("TREE_SOURCE_INVALID_LIMIT");
3213
- const directory2 = resolve8(options.directory), marker = join9(directory2, "source.json"), file = join9(directory2, "trees.sqlite");
3503
+ const directory2 = resolve8(options.directory), marker = join10(directory2, "source.json"), file = join10(directory2, "trees.sqlite");
3214
3504
  if (options.initialize) preparePrivateDirectory(directory2);
3215
3505
  else {
3216
3506
  try {
@@ -3228,7 +3518,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
3228
3518
  }
3229
3519
  preparePrivateDatabase(file);
3230
3520
  try {
3231
- this.db = new DatabaseSync5(file);
3521
+ this.db = new DatabaseSync6(file);
3232
3522
  this.db.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000");
3233
3523
  if (fresh) {
3234
3524
  this.db.exec("BEGIN IMMEDIATE");
@@ -3241,7 +3531,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
3241
3531
  this.db.exec("ROLLBACK");
3242
3532
  throw error;
3243
3533
  }
3244
- writeFileSync6(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
3534
+ writeFileSync5(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
3245
3535
  if (process.platform !== "win32") {
3246
3536
  const fd = openSync9(directory2, "r");
3247
3537
  try {
@@ -3359,9 +3649,10 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
3359
3649
  // src/continuity/runtime-files.ts
3360
3650
  import { lstatSync as lstatSync9, realpathSync as realpathSync5 } from "node:fs";
3361
3651
  import { relative as relative2, resolve as resolve9 } from "node:path";
3362
- import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
3652
+ import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
3363
3653
  import { createHash as createHash6 } from "node:crypto";
3364
3654
  init_runtime_replication();
3655
+ import { setImmediate as setImmediate2 } from "node:timers/promises";
3365
3656
  async function runtimeFileEntries(options) {
3366
3657
  const state2 = resolve9(options.inventory.stateDir), workspace = resolve9(options.inventory.workspace ?? state2 + "/workspace");
3367
3658
  if (realpathSync5(state2) !== state2 || realpathSync5(workspace) !== workspace) throw new Error("SYMLINK_REFUSED");
@@ -3373,6 +3664,8 @@ async function runtimeFileEntries(options) {
3373
3664
  excludeStateEntries: { ...options.inventory.excludeStateEntries },
3374
3665
  excludeWorkspaceEntries: { ...options.inventory.excludeWorkspaceEntries }
3375
3666
  };
3667
+ for (const path3 of ["mem7/spool/intake.write.lock", "mem7/spool/intake.write.lock.reap"])
3668
+ inventoryOptions.excludeStateEntries[path3] = "local queue writer ownership; recreated per process";
3376
3669
  for (const directory2 of [...options.vectorDirectories, ...options.sessionDirectories].map(resolvePath)) {
3377
3670
  const info = lstatSync9(directory2);
3378
3671
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync5(directory2) !== directory2) throw new Error("SYMLINK_REFUSED");
@@ -3390,7 +3683,7 @@ async function runtimeFileEntries(options) {
3390
3683
  const registration = place?.component === "session-events" ? readSQLiteStoreRegistration(place) : null;
3391
3684
  if (!place || !registration || !isWithin(state2, place.stateDir) && !isWithin(workspace, place.stateDir)) throw new Error("RUNTIME_REGISTERED_PATH_MISSING");
3392
3685
  checkRuntimeReplicationFile(file, registration);
3393
- const db = new DatabaseSync6(file, { readOnly: true });
3686
+ const db = new DatabaseSync7(file, { readOnly: true });
3394
3687
  try {
3395
3688
  checkRuntimeReplicationDatabase(db, registration, "session-events", 1);
3396
3689
  } finally {
@@ -3406,7 +3699,13 @@ async function runtimeFileEntries(options) {
3406
3699
  };
3407
3700
  return await classify();
3408
3701
  }
3409
- var signatures = (entries) => entries.map((entry) => [entry.root, entry.path, entry.kind, entry.mode, entry.signature]);
3702
+ var signatures = (entries) => entries.map((entry) => [
3703
+ entry.root,
3704
+ entry.path,
3705
+ entry.kind,
3706
+ entry.mode,
3707
+ entry.kind === "directory" ? entry.signature.split(":").slice(0, -3).join(":") : entry.signature
3708
+ ]);
3410
3709
  async function runtimeFileFingerprint(options) {
3411
3710
  return createHash6("sha256").update(JSON.stringify(signatures(await runtimeFileEntries(options)))).digest("hex");
3412
3711
  }
@@ -3416,10 +3715,26 @@ async function captureRuntimeFiles(options) {
3416
3715
  { id: options.workspaceTreeId, files: [], directories: [] }
3417
3716
  ];
3418
3717
  if (!trees.every((tree) => /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(tree.id)) || trees[0].id === trees[1].id) throw new Error("PUBLICATION_INVALID_ID");
3419
- for (const entry of before) {
3718
+ const files = before.filter((entry) => entry.kind !== "directory");
3719
+ const progress = { completedFiles: 0, totalFiles: files.length, completedBytes: 0, totalBytes: files.reduce((n, e) => n + e.bytes, 0) };
3720
+ options.onProgress?.({ ...progress });
3721
+ for (const entry of before.filter((entry2) => entry2.kind === "directory")) {
3420
3722
  const tree = trees[entry.root === "state" ? 0 : 1];
3421
- if (entry.kind === "directory") tree.directories.push(entry.path);
3422
- else tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content: await options.objects.captureFile(entry.source) });
3723
+ tree.directories.push(entry.path);
3724
+ }
3725
+ for (let offset = 0; offset < files.length; offset += 32) {
3726
+ const batch = files.slice(offset, offset + 32);
3727
+ const bytesBefore = progress.completedBytes;
3728
+ const contents = await options.objects.captureFiles(batch.map((entry) => entry.source), (value2) => {
3729
+ progress.completedFiles = offset + value2.completedFiles;
3730
+ progress.completedBytes = bytesBefore + value2.completedBytes;
3731
+ options.onProgress?.({ ...progress });
3732
+ });
3733
+ for (const [index, entry] of batch.entries()) {
3734
+ const tree = trees[entry.root === "state" ? 0 : 1], content = contents[index];
3735
+ tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content });
3736
+ }
3737
+ await setImmediate2();
3423
3738
  }
3424
3739
  if (JSON.stringify(signatures(before)) !== JSON.stringify(signatures(await runtimeFileEntries(options)))) throw new Error("PUBLICATION_SOURCE_CHANGED");
3425
3740
  return trees;
@@ -3430,18 +3745,18 @@ function resolvePath(path3) {
3430
3745
 
3431
3746
  // src/continuity/lance-publication.ts
3432
3747
  import { createHash as createHash11 } from "node:crypto";
3433
- import { lstatSync as lstatSync10, readdirSync as readdirSync2, realpathSync as realpathSync6, mkdirSync as mkdirSync7, writeFileSync as writeFileSync8, openSync as openSync10, closeSync as closeSync9, fsyncSync as fsyncSync8, chmodSync as chmodSync2 } from "node:fs";
3434
- import { join as join11, resolve as resolve10, dirname as dirname8, relative as relative3 } from "node:path";
3748
+ import { lstatSync as lstatSync10, readdirSync as readdirSync2, realpathSync as realpathSync6, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7, openSync as openSync10, closeSync as closeSync9, fsyncSync as fsyncSync8, chmodSync as chmodSync2 } from "node:fs";
3749
+ import { join as join12, resolve as resolve10, dirname as dirname9, relative as relative3 } from "node:path";
3435
3750
  import { createRequire as createRequire5 } from "node:module";
3436
3751
 
3437
3752
  // src/mem7/core/vector-store.ts
3438
- import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
3753
+ import { DatabaseSync as DatabaseSync11 } from "node:sqlite";
3439
3754
 
3440
3755
  // src/mem7/core/store.ts
3441
3756
  init_runtime_lock();
3442
3757
  init_runtime_authority();
3443
3758
  init_sqlite_replication();
3444
- import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
3759
+ import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
3445
3760
  init_sqlite_autocommit();
3446
3761
  init_schema_migrations();
3447
3762
 
@@ -3458,8 +3773,8 @@ init_schema_migrations();
3458
3773
  init_scope();
3459
3774
 
3460
3775
  // src/mem7/core/change-feed.ts
3461
- import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
3462
- import { existsSync as existsSync3, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync7 } from "node:fs";
3776
+ import { createHash as createHash7, randomUUID as randomUUID5 } from "node:crypto";
3777
+ import { existsSync as existsSync3, readFileSync as readFileSync5, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6 } from "node:fs";
3463
3778
 
3464
3779
  // src/mem7/core/state/temporal.ts
3465
3780
  function canonicalJson(value2) {
@@ -3666,7 +3981,7 @@ var ChangeFeed = class _ChangeFeed {
3666
3981
  let ledger = {};
3667
3982
  if (ledgerPath) {
3668
3983
  try {
3669
- ledger = JSON.parse(readFileSync6(ledgerPath, "utf8"))?.heals ?? {};
3984
+ ledger = JSON.parse(readFileSync5(ledgerPath, "utf8"))?.heals ?? {};
3670
3985
  } catch {
3671
3986
  }
3672
3987
  if (Number.isFinite(ledger[key2])) {
@@ -3689,13 +4004,13 @@ var ChangeFeed = class _ChangeFeed {
3689
4004
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
3690
4005
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
3691
4006
  retained[key2] = now2;
3692
- const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
4007
+ const temp = `${ledgerPath}.${randomUUID5()}.tmp`;
3693
4008
  try {
3694
- writeFileSync7(temp, JSON.stringify({ version: 1, heals: retained }));
4009
+ writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
3695
4010
  renameSync2(temp, ledgerPath);
3696
4011
  } catch (error) {
3697
4012
  try {
3698
- if (existsSync3(temp)) unlinkSync3(temp);
4013
+ if (existsSync3(temp)) unlinkSync2(temp);
3699
4014
  } catch {
3700
4015
  }
3701
4016
  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}`);
@@ -3937,8 +4252,8 @@ var RecoveryDeletionGraph = class {
3937
4252
 
3938
4253
  // src/mem7/core/host-turns.ts
3939
4254
  init_scope();
3940
- import { randomUUID as randomUUID5, createHash as createHash10 } from "node:crypto";
3941
- var processOwnerId = randomUUID5();
4255
+ import { randomUUID as randomUUID6, createHash as createHash10 } from "node:crypto";
4256
+ var processOwnerId = randomUUID6();
3942
4257
  var currentSource = `EXISTS (SELECT 1 FROM memory_sources s WHERE s.scope_id=memory_host_turns.scope_id
3943
4258
  AND s.source_id=memory_host_turns.source_id AND s.role='user' AND s.origin_class='host_user' AND s.interpretation_status<>'deleted'
3944
4259
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id AND newer.origin_key=s.origin_key
@@ -3970,10 +4285,10 @@ init_read_guard();
3970
4285
  init_scope();
3971
4286
 
3972
4287
  // src/mem7/core/episode.ts
3973
- import { readFileSync as readFileSync7 } from "node:fs";
3974
- import { join as join10, dirname as dirname7 } from "node:path";
4288
+ import { readFileSync as readFileSync6 } from "node:fs";
4289
+ import { join as join11, dirname as dirname8 } from "node:path";
3975
4290
  import { fileURLToPath } from "node:url";
3976
- var PROMPT = readFileSync7(join10(dirname7(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
4291
+ var PROMPT = readFileSync6(join11(dirname8(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
3977
4292
 
3978
4293
  // src/mem7/core/relationship-cognition.ts
3979
4294
  init_scope();
@@ -4017,8 +4332,8 @@ init_scope();
4017
4332
 
4018
4333
  // src/mem7/core/job-retention.ts
4019
4334
  import { gzip, gunzipSync } from "node:zlib";
4020
- import { promisify } from "node:util";
4021
- var compress = promisify(gzip);
4335
+ import { promisify as promisify2 } from "node:util";
4336
+ var compress = promisify2(gzip);
4022
4337
  var kinds = [
4023
4338
  "boundary",
4024
4339
  "source.interpret",
@@ -4201,7 +4516,7 @@ function assertSource(directory2) {
4201
4516
  if (info.isSymbolicLink()) throw new Error("SYMLINK_REFUSED");
4202
4517
  if (!info.isDirectory() && !info.isFile()) throw new Error("LANCE_PUBLICATION_SPECIAL_FILE");
4203
4518
  signatures2.push([relative3(directory2, path3), ...[info.dev, info.ino, info.size, info.mode, info.mtimeNs, info.ctimeNs].map(String)]);
4204
- if (info.isDirectory()) for (const name of readdirSync2(path3).sort()) visit(join11(path3, name), depth + 1);
4519
+ if (info.isDirectory()) for (const name of readdirSync2(path3).sort()) visit(join12(path3, name), depth + 1);
4205
4520
  };
4206
4521
  visit(directory2, 0);
4207
4522
  return sha3(JSON.stringify(signatures2));
@@ -4234,7 +4549,7 @@ function durablePrivateTree(directory2) {
4234
4549
  const visit = (path3) => {
4235
4550
  const info = lstatSync10(path3);
4236
4551
  if (info.isSymbolicLink() || !info.isDirectory() && !info.isFile()) throw new Error("SYMLINK_REFUSED");
4237
- if (info.isDirectory()) for (const name of readdirSync2(path3)) visit(join11(path3, name));
4552
+ if (info.isDirectory()) for (const name of readdirSync2(path3)) visit(join12(path3, name));
4238
4553
  chmodSync2(path3, info.isDirectory() ? 448 : 384);
4239
4554
  if (process.platform !== "win32" || info.isFile()) {
4240
4555
  const fd = openSync10(path3, "r");
@@ -4281,14 +4596,28 @@ async function captureLancePublication(options) {
4281
4596
  const batchTable = new arrow.Table(batch);
4282
4597
  for (let start = 0; start < batchTable.numRows; start += batchRows) {
4283
4598
  const page = batchTable.slice(start, start + batchRows);
4599
+ let pending = [], pendingBytes = 0;
4600
+ const flush = async () => {
4601
+ if (!pending.length) return;
4602
+ const contents = await options.objects.putContents(pending.map((row) => row.bytes));
4603
+ for (let i = 0; i < pending.length; i++) tree.files.push({ path: pending[i].path, mode: 384, content: contents[i] });
4604
+ pending = [];
4605
+ pendingBytes = 0;
4606
+ };
4284
4607
  for (let index = 0; index < page.numRows; index++) {
4285
4608
  const one = page.slice(index, index + 1), path3 = rowPath(kind, one.getChild("id").get(0));
4286
4609
  if (seen.has(path3)) throw new Error("LANCE_PUBLICATION_DUPLICATE_ROW");
4287
4610
  seen.add(path3);
4288
4611
  const bytes = arrow.tableToIPC(one, "stream");
4289
- if (bytes.length > ROW_BYTES || tree.files.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
4290
- tree.files.push({ path: path3, mode: 384, content: await options.objects.putContent(bytes) });
4612
+ if (bytes.length > ROW_BYTES || tree.files.length + pending.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
4613
+ if (pending.length === 128 || pendingBytes + bytes.length > 8 * 1024 * 1024) await flush();
4614
+ if (bytes.length > 8 * 1024 * 1024) tree.files.push({ path: path3, mode: 384, content: await options.objects.putContent(bytes) });
4615
+ else {
4616
+ pending.push({ path: path3, bytes });
4617
+ pendingBytes += bytes.length;
4618
+ }
4291
4619
  }
4620
+ await flush();
4292
4621
  }
4293
4622
  }
4294
4623
  if (seen.size !== total) throw new Error("LANCE_PUBLICATION_ROW_COUNT_MISMATCH");
@@ -4332,7 +4661,7 @@ async function readManifest(tree, objects) {
4332
4661
  }
4333
4662
  async function restoreLancePublication(options) {
4334
4663
  const destination = resolve10(options.destination);
4335
- if (realpathSync6(dirname8(destination)) !== dirname8(destination)) throw new Error("SYMLINK_REFUSED");
4664
+ if (realpathSync6(dirname9(destination)) !== dirname9(destination)) throw new Error("SYMLINK_REFUSED");
4336
4665
  if (isWithin(destination, options.objects.directory) || isWithin(options.objects.directory, destination)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
4337
4666
  const { manifest, files } = await readManifest(options.tree, options.objects);
4338
4667
  const [lance, schemas] = await Promise.all([loadLance(), arrowSchemas()]);
@@ -4344,7 +4673,7 @@ async function restoreLancePublication(options) {
4344
4673
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
4345
4674
  throw error;
4346
4675
  }
4347
- writeFileSync8(join11(destination, ".travel-restored.json"), JSON.stringify({
4676
+ writeFileSync7(join12(destination, ".travel-restored.json"), JSON.stringify({
4348
4677
  format: "engine7-lance-logical-restore-v1",
4349
4678
  activationAllowed: false,
4350
4679
  identity: options.objects.identity,
@@ -4384,8 +4713,8 @@ async function restoreLancePublication(options) {
4384
4713
  connection.close();
4385
4714
  }
4386
4715
  durablePrivateTree(destination);
4387
- writeFileSync8(
4388
- join11(destination, ".lance-receipt.json"),
4716
+ writeFileSync7(
4717
+ join12(destination, ".lance-receipt.json"),
4389
4718
  JSON.stringify({ format: manifest.format, tables: manifest.tables, activationAllowed: false }),
4390
4719
  { flag: "wx", mode: 384, flush: true }
4391
4720
  );
@@ -4397,14 +4726,15 @@ init_schema_migrations();
4397
4726
  init_sqlite_replication();
4398
4727
  init_runtime_replication();
4399
4728
  init_runtime_lock();
4729
+ init_runtime_authority();
4400
4730
  import { createRequire as createRequire6 } from "node:module";
4401
4731
  import { createHash as createHash13 } from "node:crypto";
4402
- import { constants as constants9, lstatSync as lstatSync12, readdirSync as readdirSync3, realpathSync as realpathSync8, readFileSync as readFileSync8, writeFileSync as writeFileSync9, openSync as openSync12, closeSync as closeSync11, readSync as readSync2, chmodSync as chmodSync3, existsSync as existsSync4 } from "node:fs";
4403
- import { join as join13, resolve as resolve12, dirname as dirname10 } from "node:path";
4732
+ import { constants as constants10, lstatSync as lstatSync12, readdirSync as readdirSync3, realpathSync as realpathSync8, readFileSync as readFileSync7, writeFileSync as writeFileSync8, openSync as openSync12, closeSync as closeSync11, readSync as readSync2, chmodSync as chmodSync3, existsSync as existsSync4 } from "node:fs";
4733
+ import { join as join14, resolve as resolve12, dirname as dirname11 } from "node:path";
4404
4734
 
4405
4735
  // src/continuity/session-event-projection.ts
4406
4736
  import {
4407
- constants as constants8,
4737
+ constants as constants9,
4408
4738
  lstatSync as lstatSync11,
4409
4739
  realpathSync as realpathSync7,
4410
4740
  mkdirSync as mkdirSync8,
@@ -4414,14 +4744,14 @@ import {
4414
4744
  fstatSync as fstatSync5,
4415
4745
  appendFileSync,
4416
4746
  renameSync as renameSync3,
4417
- unlinkSync as unlinkSync4
4747
+ unlinkSync as unlinkSync3
4418
4748
  } from "node:fs";
4419
- import { basename as basename4, dirname as dirname9, join as join12, relative as relative4, resolve as resolve11 } from "node:path";
4420
- import { createHash as createHash12, randomUUID as randomUUID6 } from "node:crypto";
4749
+ import { basename as basename4, dirname as dirname10, join as join13, relative as relative4, resolve as resolve11 } from "node:path";
4750
+ import { createHash as createHash12, randomUUID as randomUUID7 } from "node:crypto";
4421
4751
  function sessionStateDir(fileOrDirectory) {
4422
4752
  const absolute4 = resolve11(fileOrDirectory);
4423
- const directory2 = ["sessions", "sessions-cron"].includes(basename4(absolute4)) ? absolute4 : dirname9(absolute4);
4424
- return ["sessions", "sessions-cron"].includes(basename4(directory2)) && basename4(dirname9(dirname9(directory2))) === "agents" ? dirname9(dirname9(dirname9(directory2))) : null;
4753
+ const directory2 = ["sessions", "sessions-cron"].includes(basename4(absolute4)) ? absolute4 : dirname10(absolute4);
4754
+ return ["sessions", "sessions-cron"].includes(basename4(directory2)) && basename4(dirname10(dirname10(directory2))) === "agents" ? dirname10(dirname10(dirname10(directory2))) : null;
4425
4755
  }
4426
4756
  function sessionFilePath(stateDir, file) {
4427
4757
  const path3 = relative4(stateDir, resolve11(file)).replace(/\\/g, "/");
@@ -4452,7 +4782,7 @@ function prepareSessionDirectory(directory2) {
4452
4782
  if (error.code !== "ENOENT") throw error;
4453
4783
  }
4454
4784
  missing.push(parent);
4455
- parent = dirname9(parent);
4785
+ parent = dirname10(parent);
4456
4786
  }
4457
4787
  if (realpathSync7(parent) !== parent || !lstatSync11(parent).isDirectory()) throw new Error("SESSION_SYMLINK_REFUSED");
4458
4788
  for (const path3 of missing.reverse()) {
@@ -4462,7 +4792,7 @@ function prepareSessionDirectory(directory2) {
4462
4792
  if (error.code !== "EEXIST") throw error;
4463
4793
  }
4464
4794
  if (!lstatSync11(path3).isDirectory() || realpathSync7(path3) !== path3) throw new Error("SESSION_SYMLINK_REFUSED");
4465
- syncSessionDirectory(dirname9(path3));
4795
+ syncSessionDirectory(dirname10(path3));
4466
4796
  }
4467
4797
  }
4468
4798
  function sessionFileSignature(file) {
@@ -4491,9 +4821,9 @@ function mapSessionIndex(bytes, db, path3, stateDir, sourceRoot, targetRoot) {
4491
4821
  const old = entry.file.replace(/\\/g, "/"), prefix = prefixes.find((value2) => old.startsWith(value2));
4492
4822
  if (!prefix) throw new Error("SESSION_INDEX_PATH_UNSUPPORTED");
4493
4823
  const local = old.slice(prefix.length);
4494
- sessionFilePath(stateDir, join12(stateDir, local));
4824
+ sessionFilePath(stateDir, join13(stateDir, local));
4495
4825
  if (!db.prepare("SELECT 1 FROM session_files WHERE path=? AND state='active'").get(local)) throw new Error("SESSION_INDEX_TARGET_MISSING");
4496
- entry.file = join12(targetRoot, local);
4826
+ entry.file = join13(targetRoot, local);
4497
4827
  }
4498
4828
  return Buffer.from(JSON.stringify(index, null, 2));
4499
4829
  }
@@ -4505,15 +4835,15 @@ function portableIndex(bytes, db, path3, sourceRoot, destination) {
4505
4835
  return mapSessionIndex(bytes, db, path3, destination, sourceRoot, destination);
4506
4836
  }
4507
4837
  function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
4508
- sessionFilePath(stateDir, join12(stateDir, path3));
4838
+ sessionFilePath(stateDir, join13(stateDir, path3));
4509
4839
  const record = db.prepare("SELECT * FROM session_files WHERE path=?").get(path3);
4510
4840
  if (!record) throw new Error("SESSION_FILE_NOT_REGISTERED");
4511
- const file = join12(stateDir, path3), signature = sessionFileSignature(file);
4512
- prepareSessionDirectory(dirname9(file));
4841
+ const file = join13(stateDir, path3), signature = sessionFileSignature(file);
4842
+ prepareSessionDirectory(dirname10(file));
4513
4843
  if (record.state === "removed") {
4514
4844
  if (signature !== null) {
4515
- unlinkSync4(file);
4516
- syncSessionDirectory(dirname9(file));
4845
+ unlinkSync3(file);
4846
+ syncSessionDirectory(dirname10(file));
4517
4847
  }
4518
4848
  cursors.prepare("DELETE FROM cursors WHERE path=?").run(path3);
4519
4849
  return;
@@ -4523,11 +4853,11 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
4523
4853
  const cursor = cursors.prepare("SELECT * FROM cursors WHERE path=?").get(path3);
4524
4854
  const incremental = record.kind === "jsonl" && cursor && cursor.generation === record.generation && cursor.signature === signature && Number(cursor.frames) <= count;
4525
4855
  if (incremental && cursor.revision === record.revision && Number(cursor.frames) === count) return;
4526
- const temp = join12(dirname9(file), ".session-" + randomUUID6() + ".partial");
4856
+ const temp = join13(dirname10(file), ".session-" + randomUUID7() + ".partial");
4527
4857
  const target = incremental ? file : temp, start = incremental ? Number(cursor.frames) : 0;
4528
4858
  let fd, complete = false;
4529
4859
  try {
4530
- fd = openSync11(target, (incremental ? constants8.O_WRONLY | constants8.O_APPEND : constants8.O_WRONLY | constants8.O_CREAT | constants8.O_EXCL) | (constants8.O_NOFOLLOW ?? 0), 384);
4860
+ fd = openSync11(target, (incremental ? constants9.O_WRONLY | constants9.O_APPEND : constants9.O_WRONLY | constants9.O_CREAT | constants9.O_EXCL) | (constants9.O_NOFOLLOW ?? 0), 384);
4531
4861
  let frames2 = start;
4532
4862
  const rows = db.prepare(`SELECT f.ordinal,e.body,e.digest FROM session_file_events f JOIN session_events e ON e.sequence=f.event_sequence
4533
4863
  WHERE f.path=? AND f.ordinal>? ORDER BY f.ordinal`).iterate(path3, start);
@@ -4548,7 +4878,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
4548
4878
  if (!incremental) renameSync3(temp, file);
4549
4879
  const after = sessionFileSignature(file);
4550
4880
  if (after === null || !after.startsWith(`${info.dev}:${info.ino}:${info.size}:`)) throw new Error("SESSION_PROJECTION_CHANGED");
4551
- syncSessionDirectory(dirname9(file));
4881
+ syncSessionDirectory(dirname10(file));
4552
4882
  cursors.prepare(`INSERT INTO cursors VALUES(?,?,?,?,?) ON CONFLICT(path) DO UPDATE SET generation=excluded.generation,
4553
4883
  revision=excluded.revision,frames=excluded.frames,signature=excluded.signature`).run(path3, record.generation, record.revision, count, after);
4554
4884
  complete = true;
@@ -4556,7 +4886,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
4556
4886
  if (fd !== void 0) closeSync10(fd);
4557
4887
  if (!incremental && !complete) {
4558
4888
  try {
4559
- unlinkSync4(temp);
4889
+ unlinkSync3(temp);
4560
4890
  } catch (error) {
4561
4891
  if (error.code !== "ENOENT") throw error;
4562
4892
  }
@@ -4587,8 +4917,8 @@ var schema2 = `
4587
4917
  CREATE TABLE session_file_events(path TEXT NOT NULL,ordinal INTEGER NOT NULL,event_sequence INTEGER NOT NULL,
4588
4918
  PRIMARY KEY(path,ordinal),FOREIGN KEY(path) REFERENCES session_files(path),FOREIGN KEY(event_sequence) REFERENCES session_events(sequence));`;
4589
4919
  function privateDatabase(file, create) {
4590
- prepareSessionDirectory(dirname10(file));
4591
- const directory2 = lstatSync12(dirname10(file));
4920
+ prepareSessionDirectory(dirname11(file));
4921
+ const directory2 = lstatSync12(dirname11(file));
4592
4922
  if (process.platform !== "win32" && (directory2.mode & 63 || directory2.uid !== process.getuid())) throw new Error("SESSION_PRIVATE_CONTROL_REQUIRED");
4593
4923
  for (const path3 of [file, file + "-journal", file + "-wal", file + "-shm"]) {
4594
4924
  try {
@@ -4601,7 +4931,7 @@ function privateDatabase(file, create) {
4601
4931
  if (create) {
4602
4932
  try {
4603
4933
  closeSync11(openSync12(file, "wx", 384));
4604
- syncSessionDirectory(dirname10(file));
4934
+ syncSessionDirectory(dirname11(file));
4605
4935
  } catch (error) {
4606
4936
  if (error.code !== "EEXIST") throw error;
4607
4937
  }
@@ -4616,7 +4946,7 @@ function privateDatabase(file, create) {
4616
4946
  }
4617
4947
  }
4618
4948
  function projectionDatabase(stateDir, binding) {
4619
- const db = privateDatabase(join13(stateDir, ".continuity/session-projection.sqlite"), true);
4949
+ const db = privateDatabase(join14(stateDir, ".continuity/session-projection.sqlite"), true);
4620
4950
  try {
4621
4951
  db.exec(`CREATE TABLE IF NOT EXISTS projection_control(singleton INTEGER PRIMARY KEY CHECK(singleton=1),binding TEXT NOT NULL);
4622
4952
  CREATE TABLE IF NOT EXISTS cursors(path TEXT PRIMARY KEY,generation INTEGER NOT NULL,revision INTEGER NOT NULL,frames INTEGER NOT NULL,signature TEXT NOT NULL);`);
@@ -4677,19 +5007,19 @@ function nextRevision(db) {
4677
5007
  return revision;
4678
5008
  }
4679
5009
  function inventory2(stateDir) {
4680
- const files = [], agents = join13(stateDir, "agents");
5010
+ const files = [], agents = join14(stateDir, "agents");
4681
5011
  if (!existsSync4(agents)) return files;
4682
5012
  if (realpathSync8(agents) !== agents || !lstatSync12(agents).isDirectory()) throw new Error("SESSION_SYMLINK_REFUSED");
4683
5013
  for (const agent of readdirSync3(agents).sort()) {
4684
- const agentDir = join13(agents, agent);
5014
+ const agentDir = join14(agents, agent);
4685
5015
  if (lstatSync12(agentDir).isSymbolicLink()) throw new Error("SESSION_SYMLINK_REFUSED");
4686
5016
  if (!lstatSync12(agentDir).isDirectory()) continue;
4687
5017
  for (const folder of ["sessions", "sessions-cron"]) {
4688
- const directory2 = join13(agentDir, folder);
5018
+ const directory2 = join14(agentDir, folder);
4689
5019
  if (!existsSync4(directory2)) continue;
4690
5020
  if (!lstatSync12(directory2).isDirectory() || realpathSync8(directory2) !== directory2) throw new Error("SESSION_SYMLINK_REFUSED");
4691
5021
  for (const name of readdirSync3(directory2).sort()) {
4692
- const file = join13(directory2, name);
5022
+ const file = join14(directory2, name);
4693
5023
  sessionFilePath(stateDir, file);
4694
5024
  const signature = sessionFileSignature(file);
4695
5025
  if (signature === null) throw new Error("SESSION_BASELINE_CHANGED");
@@ -4706,10 +5036,10 @@ function importFile(db, stateDir, file) {
4706
5036
  let ordinal = 0;
4707
5037
  const add = (body) => db.prepare("INSERT INTO session_file_events VALUES(?,?,?)").run(place.path, ++ordinal, rememberEvent(db, place.key, body, place.kind));
4708
5038
  if (place.kind !== "jsonl") {
4709
- add(readFileSync8(file));
5039
+ add(readFileSync7(file));
4710
5040
  return;
4711
5041
  }
4712
- const fd = openSync12(file, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0)), chunk = Buffer.alloc(1024 * 1024);
5042
+ const fd = openSync12(file, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0)), chunk = Buffer.alloc(1024 * 1024);
4713
5043
  let carry = Buffer.alloc(0);
4714
5044
  try {
4715
5045
  for (; ; ) {
@@ -4755,7 +5085,7 @@ async function enrollSessionEvents(stateDir, input, options = {}) {
4755
5085
  throw error;
4756
5086
  }
4757
5087
  enrollRuntimeReplication(db, root, "session-events", binding);
4758
- syncSessionDirectory(dirname10(file));
5088
+ syncSessionDirectory(dirname11(file));
4759
5089
  } finally {
4760
5090
  db.close();
4761
5091
  }
@@ -4772,9 +5102,9 @@ var SessionEventStore = class {
4772
5102
  const row = db.prepare("SELECT source_root,revision,limits FROM session_control WHERE singleton=1").get();
4773
5103
  let approvedSourceRoot = row?.source_root === stateDir;
4774
5104
  if (row && !approvedSourceRoot) {
4775
- const file = join13(stateDir, ".travel-active.json"), stat = lstatSync12(file);
4776
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4 * 1024 * 1024 || process.platform !== "win32" && (stat.mode & 63 || stat.uid !== process.getuid())) throw new Error("REPLICATION_RECOVERY_REQUIRED");
4777
- const activation = JSON.parse(readFileSync8(file, "utf8")), binding = registration.binding;
5105
+ const file = join14(stateDir, ".travel-active.json"), stat2 = lstatSync12(file);
5106
+ if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > 4 * 1024 * 1024 || process.platform !== "win32" && (stat2.mode & 63 || stat2.uid !== process.getuid())) throw new Error("REPLICATION_RECOVERY_REQUIRED");
5107
+ const activation = JSON.parse(readFileSync7(file, "utf8")), binding = registration.binding;
4778
5108
  approvedSourceRoot = activation.format === "engine7-runtime-activation-v1" && activation.destination === stateDir && activation.originalSessionRoots?.includes(row.source_root) && activation.profile?.baselineId === binding.baselineId && activation.profile?.epoch === binding.epoch && activation.identity?.tenantId === binding.tenantId && activation.identity?.companionId === binding.companionId && activation.identity?.seatId === binding.seatId;
4779
5109
  }
4780
5110
  if (!row || !approvedSourceRoot || !Number.isSafeInteger(row.revision) || Number(row.revision) < 0) throw new Error("REPLICATION_RECOVERY_REQUIRED");
@@ -5023,14 +5353,14 @@ async function restoreSessionEvents(options) {
5023
5353
  const control2 = options.db.prepare("SELECT binding,head,digest FROM e7_replication_control WHERE role=?").get(role);
5024
5354
  const wanted = JSON.stringify([binding.tenantId, binding.companionId, binding.seatId, binding.databaseId, binding.baselineId, binding.epoch]);
5025
5355
  if (!control2 || control2.binding !== wanted) throw new Error("REPLICATION_BINDING_MISMATCH");
5026
- if (realpathSync8(dirname10(destination)) !== dirname10(destination)) throw new Error("SESSION_SYMLINK_REFUSED");
5356
+ if (realpathSync8(dirname11(destination)) !== dirname11(destination)) throw new Error("SESSION_SYMLINK_REFUSED");
5027
5357
  if (existsSync4(destination)) throw new Error("CONTINUITY_DESTINATION_EXISTS");
5028
5358
  prepareSessionDirectory(destination);
5029
- writeFileSync9(join13(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-session-events-restore-v1", activationAllowed: false, binding }), { mode: 384, flag: "wx", flush: true });
5359
+ writeFileSync8(join14(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-session-events-restore-v1", activationAllowed: false, binding }), { mode: 384, flag: "wx", flush: true });
5030
5360
  syncSessionDirectory(destination);
5031
- const directory2 = join13(destination, ".continuity");
5361
+ const directory2 = join14(destination, ".continuity");
5032
5362
  prepareSessionDirectory(directory2);
5033
- const file = join13(directory2, "session-events.db");
5363
+ const file = join14(directory2, "session-events.db");
5034
5364
  await require4("node:sqlite").backup(options.db, file);
5035
5365
  chmodSync3(file, 384);
5036
5366
  const copy = privateDatabase(file, false), cursors = projectionDatabase(destination, binding);
@@ -5041,8 +5371,8 @@ async function restoreSessionEvents(options) {
5041
5371
  cursors.exec("BEGIN IMMEDIATE");
5042
5372
  for (const row of copy.prepare("SELECT path FROM session_files ORDER BY path").all()) projectSessionFile(copy, cursors, destination, String(row.path), root);
5043
5373
  cursors.exec("COMMIT");
5044
- writeFileSync9(
5045
- join13(destination, ".session-events-receipt.json"),
5374
+ writeFileSync8(
5375
+ join14(destination, ".session-events-receipt.json"),
5046
5376
  JSON.stringify({ binding, head: { sequence: control2.head, digest: control2.digest }, activationAllowed: false }),
5047
5377
  { mode: 384, flag: "wx", flush: true }
5048
5378
  );
@@ -5094,7 +5424,7 @@ async function runRuntimeArtifactCli(command, config) {
5094
5424
  });
5095
5425
  try {
5096
5426
  return {
5097
- file: join14(stateDir, ".continuity/session-events.db"),
5427
+ file: join15(stateDir, ".continuity/session-events.db"),
5098
5428
  binding: store.replication.binding,
5099
5429
  baseline: store.replication.head(),
5100
5430
  schemaHash: store.replication.schemaHash,
@@ -5105,13 +5435,13 @@ async function runRuntimeArtifactCli(command, config) {
5105
5435
  }
5106
5436
  }
5107
5437
  if (command === "restore-sessions") {
5108
- const marker = JSON.parse(readPrivateFile(join14(stateDir, ".travel-restored.json")).toString());
5438
+ const marker = JSON.parse(readPrivateFile(join15(stateDir, ".travel-restored.json")).toString());
5109
5439
  if (marker.activationAllowed !== false) throw new Error("PUBLICATION_STANDBY_GUARD_REQUIRED");
5110
5440
  const file = databaseFile(config.databaseFile), place = sqliteStoreLocation(file), destination = absolute(config.destination);
5111
5441
  if (!place || place.component !== "session-events" || place.stateDir !== stateDir) throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
5112
5442
  if (isWithin(stateDir, destination) || isWithin(destination, stateDir)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
5113
5443
  return await withCheckpointLock(stateDir, async () => {
5114
- const db = new DatabaseSync11(file, { readOnly: true });
5444
+ const db = new DatabaseSync12(file, { readOnly: true });
5115
5445
  try {
5116
5446
  await restoreSessionEvents({ db, binding: normalizeBinding(config.binding), destination });
5117
5447
  return { activationAllowed: false, published: false };
@@ -5139,7 +5469,7 @@ async function runRuntimeArtifactCli(command, config) {
5139
5469
  if (!place || !isWithin(stateDir, place.stateDir)) throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
5140
5470
  assertStateDirUsable(place.stateDir);
5141
5471
  runtimeRoots.add(place.stateDir);
5142
- const registration = readSQLiteStoreRegistration(place), db = new DatabaseSync11(file, { readOnly: true });
5472
+ const registration = readSQLiteStoreRegistration(place), db = new DatabaseSync12(file, { readOnly: true });
5143
5473
  try {
5144
5474
  const actual = readSQLiteReplicationSource(db);
5145
5475
  if (!registration || !actual || JSON.stringify(actual) !== JSON.stringify(registration)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
@@ -5157,9 +5487,9 @@ async function runRuntimeArtifactCli(command, config) {
5157
5487
  }
5158
5488
  for (const root of [...runtimeRoots].sort()) releases2.push(registerRuntimeWriter(root, "travel-data-runtime-capture"));
5159
5489
  } else if (command !== "restore-lance") throw new Error("PUBLICATION_INVALID_COMMAND");
5160
- objects = await PublicationObjects.open({ directory: join14(dataDir, "objects"), key: key2, identity: profile.identity, maximumBytes: config.maximumBytes });
5490
+ objects = await PublicationObjects.open({ directory: join15(dataDir, "objects"), key: key2, identity: profile.identity, maximumBytes: config.maximumBytes });
5161
5491
  source = await RuntimeTreeSource.open({
5162
- directory: join14(dataDir, "runtime-trees"),
5492
+ directory: join15(dataDir, "runtime-trees"),
5163
5493
  profile,
5164
5494
  objects,
5165
5495
  initialize: command === "capture-runtime" && config.initializeTreeSource === true,
@@ -5213,19 +5543,19 @@ async function runRuntimeArtifactCli(command, config) {
5213
5543
  }
5214
5544
 
5215
5545
  // src/continuity/runtime-sync-cli.ts
5216
- import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
5546
+ import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
5217
5547
  import { createHash as createHash18 } from "node:crypto";
5218
- import { lstatSync as lstatSync17, realpathSync as realpathSync12, readFileSync as readFileSync9 } from "node:fs";
5219
- import { isAbsolute as isAbsolute4, resolve as resolve19, join as join20 } from "node:path";
5548
+ import { lstatSync as lstatSync17, realpathSync as realpathSync12, readFileSync as readFileSync8 } from "node:fs";
5549
+ import { isAbsolute as isAbsolute4, resolve as resolve19, join as join21 } from "node:path";
5220
5550
 
5221
5551
  // src/continuity/runtime-publication-source.ts
5222
- import { DatabaseSync as DatabaseSync13 } from "node:sqlite";
5552
+ import { DatabaseSync as DatabaseSync14 } from "node:sqlite";
5223
5553
  import { createHash as createHash15 } from "node:crypto";
5224
- import { existsSync as existsSync5, lstatSync as lstatSync15, writeFileSync as writeFileSync10, openSync as openSync13, closeSync as closeSync12, fsyncSync as fsyncSync10 } from "node:fs";
5225
- import { join as join15, resolve as resolve15 } from "node:path";
5554
+ import { existsSync as existsSync5, lstatSync as lstatSync15, writeFileSync as writeFileSync9, openSync as openSync13, closeSync as closeSync12, fsyncSync as fsyncSync10 } from "node:fs";
5555
+ import { join as join16, resolve as resolve15 } from "node:path";
5226
5556
 
5227
5557
  // src/continuity/runtime-h-capture.ts
5228
- import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
5558
+ import { DatabaseSync as DatabaseSync13 } from "node:sqlite";
5229
5559
  import { createHash as createHash14 } from "node:crypto";
5230
5560
  import { lstatSync as lstatSync14, realpathSync as realpathSync10 } from "node:fs";
5231
5561
  import { resolve as resolve14, relative as relative5 } from "node:path";
@@ -5305,7 +5635,7 @@ async function capture(input, assertRoot) {
5305
5635
  throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
5306
5636
  if (process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
5307
5637
  assertRoot(place.stateDir);
5308
- const registration = readSQLiteStoreRegistration(place), probe = new DatabaseSync12(d.file, { readOnly: true });
5638
+ const registration = readSQLiteStoreRegistration(place), probe = new DatabaseSync13(d.file, { readOnly: true });
5309
5639
  try {
5310
5640
  const enrolled = readSQLiteReplicationSource(probe), b = d.source.binding, v = readSchemaVersion(probe);
5311
5641
  if (!registration || !same2(enrolled, registration) || !same2(enrolled, { binding: b, schemaHash: d.source.schemaHash }))
@@ -5335,9 +5665,9 @@ async function capture(input, assertRoot) {
5335
5665
  }
5336
5666
  for (const s of sessionTrees) {
5337
5667
  const head = before.heads.find((d) => d.databaseId === s.databaseId).head;
5338
- const metadata3 = { format: "engine7-session-events-publication-v1", databaseId: s.databaseId, binding: databases[s.databaseId].source.binding, head };
5339
- trees.push({ id: s.treeId, directories: [], files: [{ path: "manifest.json", mode: 384, content: await objects.putContent(Buffer.from(JSON.stringify(metadata3))) }] });
5340
- origins[s.treeId] = metadata3;
5668
+ const metadata4 = { format: "engine7-session-events-publication-v1", databaseId: s.databaseId, binding: databases[s.databaseId].source.binding, head };
5669
+ trees.push({ id: s.treeId, directories: [], files: [{ path: "manifest.json", mode: 384, content: await objects.putContent(Buffer.from(JSON.stringify(metadata4))) }] });
5670
+ origins[s.treeId] = metadata4;
5341
5671
  }
5342
5672
  if (!same2(before, await observe())) throw new Error("PUBLICATION_SOURCE_CHANGED");
5343
5673
  return {
@@ -5396,9 +5726,9 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5396
5726
  if (!HASH4.test(this.layoutDigest) || !natural2(this.maximumPendingCheckpoints) || this.maximumPendingCheckpoints < 1 || this.maximumPendingCheckpoints > 128 || !natural2(this.maximumPendingBytes) || this.maximumPendingBytes < 1 || this.maximumPendingBytes > 1024 * 1024 * 1024)
5397
5727
  throw new Error("RUNTIME_PUBLICATION_INVALID_LIMIT");
5398
5728
  if (!same3(this.objects.identity, this.profile.identity) || !same3(this.trees.profile, this.profile)) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
5399
- this.file = join15(this.directory, "source.sqlite");
5400
- this.senderFile = join15(this.directory, "sender.sqlite");
5401
- this.marker = join15(this.directory, "source.json");
5729
+ this.file = join16(this.directory, "source.sqlite");
5730
+ this.senderFile = join16(this.directory, "sender.sqlite");
5731
+ this.marker = join16(this.directory, "source.json");
5402
5732
  if (options.initialize) preparePrivateDirectory(this.directory);
5403
5733
  else {
5404
5734
  try {
@@ -5414,9 +5744,9 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5414
5744
  preparePrivateDatabase(this.senderFile);
5415
5745
  let sender;
5416
5746
  try {
5417
- this.db = new DatabaseSync13(this.file);
5747
+ this.db = new DatabaseSync14(this.file);
5418
5748
  this.db.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
5419
- sender = new DatabaseSync13(this.senderFile);
5749
+ sender = new DatabaseSync14(this.senderFile);
5420
5750
  sender.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=0");
5421
5751
  if (fresh) {
5422
5752
  this.db.exec("BEGIN IMMEDIATE");
@@ -5430,7 +5760,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5430
5760
  }
5431
5761
  sender.exec(senderSchema);
5432
5762
  sender.prepare("INSERT INTO sender VALUES(1,?,?)").run(JSON.stringify(this.profile), this.layoutDigest);
5433
- writeFileSync10(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
5763
+ writeFileSync9(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
5434
5764
  if (process.platform !== "win32") {
5435
5765
  const fd = openSync13(this.directory, "r");
5436
5766
  try {
@@ -5459,7 +5789,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5459
5789
  static async open(options) {
5460
5790
  const source = new _RuntimePublicationSource(options);
5461
5791
  try {
5462
- if (source.head().sequence) await source.read(source.head().sequence);
5792
+ if (source.head().sequence) await source.readManifest(source.head().sequence);
5463
5793
  return source;
5464
5794
  } catch (error) {
5465
5795
  source.close();
@@ -5510,6 +5840,15 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5510
5840
  };
5511
5841
  }
5512
5842
  async read(sequence) {
5843
+ return this.readPrepared(sequence, true);
5844
+ }
5845
+ /** Ancestry uses authenticated H metadata; payload availability is checked
5846
+ * when actual objects are transferred or restored, not for every old H. */
5847
+ async readManifest(sequence) {
5848
+ const { digest: digest3, manifest } = await this.readPrepared(sequence, false);
5849
+ return { digest: digest3, manifest };
5850
+ }
5851
+ async readPrepared(sequence, verifyDependencies) {
5513
5852
  const row = this.entry(sequence), ref = JSON.parse(row.content);
5514
5853
  validateFileContent(ref);
5515
5854
  const manifest = normalizePublication(JSON.parse((await this.objects.readContent(ref, PUBLICATION_MANIFEST_BYTES)).toString()));
@@ -5517,7 +5856,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5517
5856
  if (manifest.sequence !== sequence || !same3(manifest.profile, this.profile) || manifest.parentDigest !== parent || row.parent_digest !== parent || publicationDigest(manifest) !== row.digest || stateHash(manifest) !== row.state_hash) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
5518
5857
  const dependencies = JSON.parse(row.dependencies);
5519
5858
  if (!Array.isArray(dependencies) || !same3(dependencies.map((d) => d.treeId).sort(), this.profile.trees.map((t) => t.id))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
5520
- for (const d of dependencies) {
5859
+ if (verifyDependencies) for (const d of dependencies) {
5521
5860
  const tree = await this.trees.read(d.treeId, d.sequence);
5522
5861
  if (tree.digest !== d.digest || !same3(tree.tree, manifest.trees.find((t) => t.id === d.treeId))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
5523
5862
  }
@@ -5530,12 +5869,41 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5530
5869
  async prepare(options) {
5531
5870
  return this.prepareCapture(options, () => captureRuntimeH(options));
5532
5871
  }
5533
- /** The source business stores stay read-only and writer exclusion remains
5534
- * held until the caller durably seals its backup and archive receipt. */
5872
+ /** A first full baseline already lives in the bounded encrypted object store
5873
+ * and native SQLite snapshots. Only its envelope occupies the increment queue. */
5874
+ async prepareInitial(options) {
5875
+ if (this.control().head !== 0) throw new Error("RUNTIME_PUBLICATION_INITIAL_ALREADY_PREPARED");
5876
+ return this.prepareCapture(options, () => captureRuntimeH(options), true);
5877
+ }
5878
+ /** The final LOCAL original is archived independently of the transport queue.
5879
+ * Read-only stores and writer exclusion remain held through its durable seal. */
5535
5880
  async withStoppedPreparation(options, operation) {
5536
- return withStoppedRuntimeH(options, async (parts) => operation(await this.prepareCapture(options, async () => parts)));
5881
+ const before = this.control();
5882
+ if (!same3(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
5883
+ if (options.deletionWatermark < before.watermark) throw new Error("PUBLICATION_DELETION_REGRESSION");
5884
+ return withStoppedRuntimeH(options, async (parts) => {
5885
+ const manifest = normalizePublication({
5886
+ format: "engine7-publication-v1",
5887
+ profile: this.profile,
5888
+ sequence: before.head + 1,
5889
+ parentDigest: before.digest,
5890
+ databases: parts.databases,
5891
+ trees: parts.trees,
5892
+ deletionWatermark: parts.deletionWatermark
5893
+ });
5894
+ const old = before.head ? await this.readManifest(before.head) : null;
5895
+ if (old && manifest.deletionWatermark === old.manifest.deletionWatermark) {
5896
+ const present = new Set(manifest.trees.flatMap((tree) => tree.files.map((file) => tree.id + "/" + file.path)));
5897
+ if (old.manifest.trees.some((tree) => tree.files.some((file) => !present.has(tree.id + "/" + file.path)))) throw new Error("PUBLICATION_REMOVAL_REQUIRES_DELETION");
5898
+ }
5899
+ const current2 = this.control();
5900
+ if (current2.head !== before.head || current2.digest !== before.digest) throw new Error("RUNTIME_PUBLICATION_CONCURRENT_CHANGE");
5901
+ if (manifest.deletionWatermark < current2.watermark) throw new Error("PUBLICATION_DELETION_REGRESSION");
5902
+ if (old && stateHash(old.manifest) === stateHash(manifest)) return operation({ ...old, sequence: before.head, activationAllowed: false });
5903
+ return operation({ sequence: manifest.sequence, digest: publicationDigest(manifest), manifest, activationAllowed: false });
5904
+ });
5537
5905
  }
5538
- async prepareCapture(options, capture2) {
5906
+ async prepareCapture(options, capture2, initial = false) {
5539
5907
  const c = this.control(), pending = this.status();
5540
5908
  if (!same3(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
5541
5909
  if (pending.pendingCheckpoints >= this.maximumPendingCheckpoints || pending.pendingBytes >= this.maximumPendingBytes) throw new Error("RUNTIME_PUBLICATION_QUEUE_FULL");
@@ -5567,11 +5935,11 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5567
5935
  for (const tree of prepared.manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) known.add(ref.sha256);
5568
5936
  }
5569
5937
  let bytes = encoded.length + Buffer.byteLength(JSON.stringify(dependencies));
5570
- for (const tree of manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) if (!known.has(ref.sha256)) {
5938
+ for (const tree of manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) if (!initial && !known.has(ref.sha256)) {
5571
5939
  known.add(ref.sha256);
5572
5940
  bytes += ref.bytes;
5573
5941
  }
5574
- for (const d of manifest.databases) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
5942
+ for (const d of manifest.databases) if (!initial) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
5575
5943
  old?.manifest.databases.find((previous) => previous.databaseId === d.databaseId).head.sequence ?? 0,
5576
5944
  d.head.sequence
5577
5945
  );
@@ -5648,7 +6016,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5648
6016
  }
5649
6017
  async withSending(operation) {
5650
6018
  this.control();
5651
- const db = new DatabaseSync13(this.senderFile);
6019
+ const db = new DatabaseSync14(this.senderFile);
5652
6020
  try {
5653
6021
  db.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE");
5654
6022
  sendingHandles.add(db);
@@ -5886,9 +6254,9 @@ init_schema_migrations();
5886
6254
  init_runtime_lock();
5887
6255
 
5888
6256
  // src/continuity/recovery-archive.ts
5889
- import { DatabaseSync as DatabaseSync14, backup as backup2 } from "node:sqlite";
5890
- import { existsSync as existsSync6, lstatSync as lstatSync16, mkdtempSync, rmSync, writeFileSync as writeFileSync11, chmodSync as chmodSync4 } from "node:fs";
5891
- import { join as join16, resolve as resolve16 } from "node:path";
6257
+ import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
6258
+ import { existsSync as existsSync6, lstatSync as lstatSync16, mkdtempSync, rmSync, writeFileSync as writeFileSync10, chmodSync as chmodSync4 } from "node:fs";
6259
+ import { join as join17, resolve as resolve16 } from "node:path";
5892
6260
  init_sqlite_replication();
5893
6261
  import { createHash as createHash16 } from "node:crypto";
5894
6262
 
@@ -5926,7 +6294,8 @@ async function currentHDeletionCheckAsync(raw, control2, captured) {
5926
6294
  var schema4 = "CREATE TABLE archives(id TEXT PRIMARY KEY,kind TEXT NOT NULL,manifest_digest TEXT NOT NULL,content TEXT NOT NULL)";
5927
6295
  var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
5928
6296
  var FORMAT = "engine7-runtime-recovery-archive-v1";
5929
- var MAX_METADATA = 16 * 1024 * 1024;
6297
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
6298
+ var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
5930
6299
  var same5 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
5931
6300
  var incarnation2 = (file) => {
5932
6301
  const s = lstatSync16(file, { bigint: true });
@@ -5970,14 +6339,17 @@ async function checkRecoveryDeletionAsync(manifest, current2, previous = 0) {
5970
6339
  const floor = await current2();
5971
6340
  return checkRecoveryDeletion(manifest, () => floor, previous);
5972
6341
  }
5973
- function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2) {
6342
+ function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2, scan = true) {
5974
6343
  const d = manifest.databases.find((d2) => d2.databaseId === databaseId), p = manifest.profile;
5975
6344
  const control2 = db.prepare("SELECT binding,head,digest,schema_hash FROM e7_replication_control WHERE role=?").get(role);
5976
6345
  const binding = JSON.stringify([p.identity.tenantId, p.identity.companionId, p.identity.seatId, databaseId, p.baselineId, p.epoch]);
5977
6346
  if (!d || !control2 || control2.binding !== binding || control2.head !== d.head.sequence || control2.digest !== d.head.digest || schemaHash2 !== void 0 && control2.schema_hash !== schemaHash2) throw new Error("RECOVERY_DATABASE_SNAPSHOT_MISMATCH");
5978
6347
  const actual = sqliteReplicationSchemaHash(db);
5979
- const checks = db.prepare("PRAGMA quick_check").all();
5980
- if (actual !== control2.schema_hash || checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
6348
+ if (actual !== control2.schema_hash) throw new Error("RECOVERY_DATABASE_CORRUPT");
6349
+ if (scan) {
6350
+ const checks = db.prepare("PRAGMA quick_check").all();
6351
+ if (checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
6352
+ }
5981
6353
  return actual;
5982
6354
  }
5983
6355
  var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
@@ -5991,8 +6363,8 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
5991
6363
  constructor(options) {
5992
6364
  this.directory = resolve16(options.directory);
5993
6365
  this.objects = options.objects;
5994
- this.file = join16(this.directory, "archives.sqlite");
5995
- this.marker = join16(this.directory, "archive.json");
6366
+ this.file = join17(this.directory, "archives.sqlite");
6367
+ this.marker = join17(this.directory, "archive.json");
5996
6368
  if (options.initialize) preparePrivateDirectory(this.directory);
5997
6369
  else {
5998
6370
  try {
@@ -6006,11 +6378,11 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6006
6378
  if (!fresh) this.checkMarker();
6007
6379
  preparePrivateDatabase(this.file);
6008
6380
  try {
6009
- this.db = new DatabaseSync14(this.file);
6381
+ this.db = new DatabaseSync15(this.file);
6010
6382
  this.db.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
6011
6383
  if (fresh) {
6012
6384
  this.db.exec(schema4);
6013
- writeFileSync11(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
6385
+ writeFileSync10(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
6014
6386
  }
6015
6387
  if (!same5(this.db.prepare("SELECT sql FROM sqlite_master WHERE type='table'").all().map((r) => String(r.sql)), [schema4]) || this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("RECOVERY_ARCHIVE_REQUIRED");
6016
6388
  this.identity = incarnation2(this.file);
@@ -6100,6 +6472,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6100
6472
  this.active();
6101
6473
  const { id: id2, kind } = options, manifest = normalizePublication(options.manifest), digest3 = publicationDigest(manifest);
6102
6474
  if (typeof id2 !== "string" || !ID2.test(id2) || !["COMMON", "LOCAL", "REMOTE"].includes(kind)) throw new Error("RECOVERY_INVALID_ID");
6475
+ if (options.snapshotDatabase && (kind !== "LOCAL" || id2 !== "first-baseline" || manifest.sequence !== 1 || manifest.parentDigest !== "0".repeat(64))) throw new Error("RECOVERY_INVALID_SNAPSHOT");
6103
6476
  if (!same5(manifest.profile.identity, this.objects.identity)) throw new Error("RECOVERY_IDENTITY_MISMATCH");
6104
6477
  const deletion = async () => {
6105
6478
  const value2 = await options.deletionWatermark();
@@ -6119,38 +6492,51 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6119
6492
  if (old) {
6120
6493
  if (old.kind !== kind || old.manifest_digest !== digest3) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6121
6494
  const entry = await this.read(id2);
6122
- for (const d of entry.databases) await verifyContent(this.objects, d.content);
6123
- for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
6495
+ if (options.verifyRetained !== false) {
6496
+ for (const d of entry.databases) await verifyContent(this.objects, d.content);
6497
+ for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
6498
+ }
6124
6499
  await verify2();
6125
6500
  return entry.receipt;
6126
6501
  }
6127
6502
  let publication;
6128
6503
  if (kind !== "LOCAL") {
6129
- const status = await options.receiver?.status();
6504
+ const status = await options.receiver?.status(options.verifyRetained !== false);
6130
6505
  if (!status || !currentHCheck && !status.dataReady || status.published?.digest !== digest3 || !same5(status.profile, manifest.profile)) throw new Error("RECOVERY_COMMON_NOT_READY");
6131
6506
  publication = status.published;
6132
6507
  }
6133
6508
  if (!same5(Object.keys(options.databases).sort(), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
6134
6509
  const role = kind === "LOCAL" ? "source" : "replica";
6135
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
6136
- const temporary = mkdtempSync(join16(this.directory, ".capture-"));
6510
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
6511
+ const sibling = kind !== "LOCAL" && !currentHCheck ? this.db.prepare("SELECT id FROM archives WHERE manifest_digest=? AND kind IN ('COMMON','REMOTE') ORDER BY id LIMIT 1").get(digest3) : void 0;
6512
+ const retained = sibling ? await this.read(String(sibling.id)) : void 0;
6513
+ if (retained) {
6514
+ validateRecoveryArchiveEntry(retained, this.objects.identity);
6515
+ if (!same5(retained.manifest, manifest) || !same5(retained.publication, publication) || retained.databases.some((d) => d.role !== "replica")) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6516
+ }
6517
+ const temporary = mkdtempSync(join17(this.directory, ".capture-"));
6137
6518
  try {
6138
- writeFileSync11(join16(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6519
+ writeFileSync10(join17(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6139
6520
  const databases = [];
6140
- for (let offset = 0; offset < manifest.databases.length; offset += 6) {
6521
+ if (retained) {
6522
+ if (options.verifyRetained !== false) for (const database of retained.databases) await verifyContent(this.objects, database.content);
6523
+ databases.push(...retained.databases);
6524
+ }
6525
+ for (let offset = 0; !retained && offset < manifest.databases.length; offset += 6) {
6141
6526
  const results = await Promise.allSettled(manifest.databases.slice(offset, offset + 6).map(async (d) => {
6142
6527
  floor = Math.max(floor, await verify2());
6143
- const file = join16(temporary, d.databaseId + ".sqlite");
6144
- await backup2(options.databases[d.databaseId], file);
6528
+ const file = join17(temporary, d.databaseId + ".sqlite");
6529
+ if (options.snapshotDatabase) await options.snapshotDatabase(options.databases[d.databaseId], file, d.databaseId);
6530
+ else await snapshotNativeDatabase(options.databases[d.databaseId], file);
6145
6531
  chmodSync4(file, 384);
6146
- const copy = new DatabaseSync14(file, { readOnly: true });
6532
+ const copy = new DatabaseSync15(file, { readOnly: true });
6147
6533
  let schemaHash2;
6148
6534
  try {
6149
- schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role);
6535
+ schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role, void 0, false);
6150
6536
  } finally {
6151
6537
  copy.close();
6152
6538
  }
6153
- const content = await this.objects.captureFile(file);
6539
+ const [content] = await this.objects.captureFiles([file], void 0, { chunkConcurrency: 8 });
6154
6540
  return { databaseId: d.databaseId, role, schemaHash: schemaHash2, content };
6155
6541
  }));
6156
6542
  for (const result of results) {
@@ -6159,7 +6545,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6159
6545
  }
6160
6546
  }
6161
6547
  for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
6162
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
6548
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
6163
6549
  if (kind !== "LOCAL") {
6164
6550
  const status = await options.receiver.status();
6165
6551
  if (!currentHCheck && !status.dataReady || status.published?.digest !== digest3) throw new Error("RECOVERY_COMMON_NOT_READY");
@@ -6189,38 +6575,30 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6189
6575
  if (currentHCheck) await verify2();
6190
6576
  }
6191
6577
  }
6192
- /** The caller has fetched only refs from this authenticated original seal.
6193
- * No receipt is installed until every chunk and real SQLite snapshot passes. */
6194
- async import(entry, deletionWatermark) {
6578
+ /** Paired transfer verifies original bytes here and opens the native stores
6579
+ * once at seed. Offline imports can also validate the full SQLite snapshots. */
6580
+ async import(entry, deletionWatermark, verifyDatabases = true) {
6195
6581
  this.active();
6196
6582
  const { value: value2, body, receipt } = validateRecoveryArchiveEntry(entry, this.objects.identity);
6197
- let floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark);
6583
+ const floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark);
6198
6584
  const prior = this.db.prepare("SELECT kind,manifest_digest,content FROM archives WHERE id=?").get(value2.id);
6199
6585
  if (prior && (prior.kind !== value2.kind || prior.manifest_digest !== receipt.manifestDigest || JSON.parse(String(prior.content)).sha256 !== receipt.digest)) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6200
- const temporary = mkdtempSync(join16(this.directory, ".import-"));
6586
+ const temporary = verifyDatabases ? mkdtempSync(join17(this.directory, ".import-")) : void 0;
6201
6587
  try {
6202
- for (const db of value2.databases) {
6203
- floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
6204
- const file = join16(temporary, db.databaseId + ".sqlite");
6588
+ if (temporary) for (const db of value2.databases) {
6589
+ const file = join17(temporary, db.databaseId + ".sqlite");
6205
6590
  await this.objects.restoreFile(db.content, file);
6206
- const probe = new DatabaseSync14(file, { readOnly: true });
6591
+ const probe = new DatabaseSync15(file, { readOnly: true });
6207
6592
  try {
6208
6593
  validateRecoveryDatabase(probe, value2.manifest, db.databaseId, db.role, db.schemaHash);
6209
6594
  } finally {
6210
6595
  probe.close();
6211
6596
  }
6212
6597
  }
6213
- const files = value2.manifest.trees.flatMap((tree) => tree.files);
6214
- for (let offset = 0; offset < files.length; offset += 8) {
6215
- const results = await Promise.allSettled(files.slice(offset, offset + 8).map(async (file) => {
6216
- const current2 = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
6217
- await verifyContent(this.objects, file.content);
6218
- return current2;
6219
- }));
6220
- for (const result of results) {
6221
- if (result.status === "rejected") throw result.reason;
6222
- floor = Math.max(floor, result.value);
6223
- }
6598
+ const contents = [...temporary ? [] : value2.databases.map((db) => db.content), ...value2.manifest.trees.flatMap((tree) => tree.files.map((file) => file.content))];
6599
+ for (let offset = 0; offset < contents.length; offset += 8) {
6600
+ const results = await Promise.allSettled(contents.slice(offset, offset + 8).map((content) => verifyContent(this.objects, content)));
6601
+ for (const result of results) if (result.status === "rejected") throw result.reason;
6224
6602
  }
6225
6603
  const ref = await this.objects.putContent(body);
6226
6604
  await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
@@ -6237,7 +6615,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6237
6615
  }
6238
6616
  return (await this.read(value2.id)).receipt;
6239
6617
  } finally {
6240
- rmSync(temporary, { recursive: true, force: true });
6618
+ if (temporary) rmSync(temporary, { recursive: true, force: true });
6241
6619
  await syncDirectory(this.directory);
6242
6620
  }
6243
6621
  }
@@ -6255,13 +6633,13 @@ async function verifyContent(objects, content) {
6255
6633
  }
6256
6634
 
6257
6635
  // src/continuity/recovery-cli.ts
6258
- import { existsSync as existsSync7, writeFileSync as writeFileSync14 } from "node:fs";
6259
- import { dirname as dirname12, isAbsolute as isAbsolute3, join as join19, resolve as resolve18 } from "node:path";
6636
+ import { existsSync as existsSync7, writeFileSync as writeFileSync13 } from "node:fs";
6637
+ import { dirname as dirname13, isAbsolute as isAbsolute3, join as join20, resolve as resolve18 } from "node:path";
6260
6638
 
6261
6639
  // src/continuity/recovery-archive-restore.ts
6262
- import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
6263
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync12, chmodSync as chmodSync5, realpathSync as realpathSync11 } from "node:fs";
6264
- import { dirname as dirname11, join as join17, resolve as resolve17 } from "node:path";
6640
+ import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
6641
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync11, realpathSync as realpathSync11 } from "node:fs";
6642
+ import { dirname as dirname12, join as join18, resolve as resolve17 } from "node:path";
6265
6643
  init_sqlite_replication();
6266
6644
  async function restoreRecoveryArchive(options) {
6267
6645
  return restoreOriginal(options);
@@ -6272,7 +6650,7 @@ async function restoreOriginal(options, original, currentHCheck) {
6272
6650
  const verify2 = async () => currentHCheck ? currentHCheck() : await checkRecoveryDeletionAsync(manifest, options.deletionWatermark, floor);
6273
6651
  floor = await verify2();
6274
6652
  const destination = resolve17(options.destination);
6275
- if (realpathSync11(dirname11(destination)) !== dirname11(destination)) throw new Error("SYMLINK_REFUSED");
6653
+ if (realpathSync11(dirname12(destination)) !== dirname12(destination)) throw new Error("SYMLINK_REFUSED");
6276
6654
  for (const root of [objects.directory, options.archive.directory]) if (isWithin(root, destination) || isWithin(destination, root)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
6277
6655
  try {
6278
6656
  mkdirSync9(destination, { mode: 448 });
@@ -6280,76 +6658,74 @@ async function restoreOriginal(options, original, currentHCheck) {
6280
6658
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
6281
6659
  throw error;
6282
6660
  }
6283
- writeFileSync12(join17(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
6284
- await syncDirectory(dirname11(destination));
6661
+ writeFileSync11(join18(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
6662
+ await syncDirectory(dirname12(destination));
6285
6663
  await syncDirectory(destination);
6286
6664
  const created = /* @__PURE__ */ new Set([destination]);
6287
6665
  const directory2 = (path3) => {
6288
6666
  const missing = [];
6289
- for (let current2 = path3; !created.has(current2) && isWithin(destination, current2); current2 = dirname11(current2)) missing.push(current2);
6667
+ for (let current2 = path3; !created.has(current2) && isWithin(destination, current2); current2 = dirname12(current2)) missing.push(current2);
6290
6668
  for (const p of missing.reverse()) {
6291
6669
  mkdirSync9(p, { mode: 448 });
6292
6670
  created.add(p);
6293
6671
  }
6294
6672
  };
6295
- directory2(join17(destination, "databases"));
6296
- directory2(join17(destination, "trees"));
6673
+ directory2(join18(destination, "databases"));
6674
+ directory2(join18(destination, "trees"));
6675
+ await objects.restoreFiles(entry.databases.map((d) => ({ content: d.content, destination: join18(destination, "databases", d.databaseId + ".sqlite") })));
6297
6676
  for (const d of entry.databases) {
6298
- floor = await verify2();
6299
- const path3 = join17(destination, "databases", d.databaseId + ".sqlite");
6300
- await objects.restoreFile(d.content, path3);
6301
- const db = new DatabaseSync15(path3, { readOnly: true });
6677
+ const path3 = join18(destination, "databases", d.databaseId + ".sqlite");
6678
+ const db = new DatabaseSync16(path3, { readOnly: true });
6302
6679
  try {
6303
- validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash);
6680
+ validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash, options.verifyDatabases !== false);
6304
6681
  } finally {
6305
6682
  db.close();
6306
6683
  }
6307
6684
  }
6685
+ const files = [];
6308
6686
  for (const tree of manifest.trees) {
6309
- const root = join17(destination, "trees", tree.id);
6687
+ const root = join18(destination, "trees", tree.id);
6310
6688
  directory2(root);
6311
- for (const path3 of tree.directories) directory2(join17(root, path3));
6689
+ for (const path3 of tree.directories) directory2(join18(root, path3));
6312
6690
  for (const file of tree.files) {
6313
- floor = await verify2();
6314
- const path3 = join17(root, file.path);
6315
- directory2(dirname11(path3));
6316
- await objects.restoreFile(file.content, path3);
6317
- chmodSync5(path3, file.mode);
6691
+ const path3 = join18(root, file.path);
6692
+ directory2(dirname12(path3));
6693
+ files.push({ content: file.content, destination: path3, mode: file.mode });
6318
6694
  }
6319
6695
  }
6320
- directory2(join17(destination, "lance"));
6321
- directory2(join17(destination, "sessions"));
6696
+ await objects.restoreFiles(files);
6697
+ directory2(join18(destination, "lance"));
6698
+ directory2(join18(destination, "sessions"));
6322
6699
  for (const kind of manifest.profile.trees) {
6323
6700
  const tree = manifest.trees.find((t) => t.id === kind.id);
6324
- if (kind.kind === "vector") await restoreLancePublication({ tree, objects, destination: join17(destination, "lance", tree.id) });
6701
+ if (kind.kind === "vector") await restoreLancePublication({ tree, objects, destination: join18(destination, "lance", tree.id) });
6325
6702
  if (kind.kind === "session") {
6326
6703
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6327
- const metadata3 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
6328
- const d = entry.databases.find((d2) => d2.databaseId === metadata3.databaseId);
6329
- const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata3.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
6330
- if (metadata3.format !== "engine7-session-events-publication-v1" || !d || JSON.stringify(metadata3.binding) !== JSON.stringify(binding) || JSON.stringify(metadata3.head) !== JSON.stringify(manifest.databases.find((v) => v.databaseId === d.databaseId).head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6331
- const db = new DatabaseSync15(join17(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
6704
+ const metadata4 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
6705
+ const d = entry.databases.find((d2) => d2.databaseId === metadata4.databaseId);
6706
+ const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata4.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
6707
+ if (metadata4.format !== "engine7-session-events-publication-v1" || !d || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(manifest.databases.find((v) => v.databaseId === d.databaseId).head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6708
+ const db = new DatabaseSync16(join18(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
6332
6709
  try {
6333
- await restoreSessionEvents({ db, binding, destination: join17(destination, "sessions", tree.id), replicationRole: d.role });
6710
+ await restoreSessionEvents({ db, binding, destination: join18(destination, "sessions", tree.id), replicationRole: d.role });
6334
6711
  } finally {
6335
6712
  db.close();
6336
6713
  }
6337
6714
  }
6338
- floor = await verify2();
6339
6715
  }
6340
6716
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
6341
6717
  await verify2();
6342
- writeFileSync12(join17(destination, ".recovery-archive-receipt.json"), JSON.stringify(entry.receipt), { mode: 384, flag: "wx", flush: true });
6718
+ writeFileSync11(join18(destination, ".recovery-archive-receipt.json"), JSON.stringify(entry.receipt), { mode: 384, flag: "wx", flush: true });
6343
6719
  await syncDirectory(destination);
6344
6720
  await verify2();
6345
6721
  return entry.receipt;
6346
6722
  }
6347
6723
 
6348
6724
  // src/continuity/recovery-diff.ts
6349
- import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
6725
+ import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
6350
6726
  import { createHash as createHash17 } from "node:crypto";
6351
- import { mkdtempSync as mkdtempSync2, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
6352
- import { join as join18 } from "node:path";
6727
+ import { mkdtempSync as mkdtempSync2, rmSync as rmSync2, writeFileSync as writeFileSync12 } from "node:fs";
6728
+ import { join as join19 } from "node:path";
6353
6729
  init_legacy_sqlite_indexes();
6354
6730
  init_schema_migrations();
6355
6731
  var same6 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
@@ -6441,12 +6817,12 @@ async function compareRecoveryArchives(options) {
6441
6817
  try {
6442
6818
  for (let index = 0; index < entries.length; index++) {
6443
6819
  const entry = entries[index], ref = references[index], d = entry.databases.find((d2) => d2.databaseId === databaseId);
6444
- const temporary = mkdtempSync2(join18(ref.archive.directory, ".compare-"));
6820
+ const temporary = mkdtempSync2(join19(ref.archive.directory, ".compare-"));
6445
6821
  temporaries.push(temporary);
6446
- writeFileSync13(join18(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6447
- const file = join18(temporary, databaseId + ".sqlite");
6822
+ writeFileSync12(join19(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6823
+ const file = join19(temporary, databaseId + ".sqlite");
6448
6824
  await ref.archive.objects.restoreFile(d.content, file);
6449
- const db = new DatabaseSync16(file, { readOnly: true, allowExtension: true });
6825
+ const db = new DatabaseSync17(file, { readOnly: true, allowExtension: true });
6450
6826
  handles.push(db);
6451
6827
  validateRecoveryDatabase(db, entry.manifest, databaseId, d.role, d.schemaHash);
6452
6828
  if (readSchemaVersion(db)?.component === "legacy-memory") loadLegacySQLiteVectorExtension(db);
@@ -6666,41 +7042,41 @@ async function runRecoveryCli(command, config) {
6666
7042
  const deletionWatermark = recoveryDeletionReader(config);
6667
7043
  deletionWatermark();
6668
7044
  const handles = [], keys = [];
6669
- const open3 = async (c) => {
7045
+ const open5 = async (c) => {
6670
7046
  const dataDir = absolute2(c.dataDir), keyFile = absolute2(c.dataKeyFile);
6671
7047
  if (isWithin(dataDir, keyFile)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
6672
7048
  assertPrivateDirectory(dataDir);
6673
- if (!existsSync7(join19(dataDir, "objects/catalog.sqlite"))) throw new Error("RECOVERY_ARCHIVE_REQUIRED");
7049
+ if (!existsSync7(join20(dataDir, "objects/catalog.sqlite"))) throw new Error("RECOVERY_ARCHIVE_REQUIRED");
6674
7050
  const key2 = readPrivateFile(keyFile, 32);
6675
7051
  keys.push(key2);
6676
7052
  if (key2.length !== 32) throw new Error("PUBLICATION_INVALID_KEY");
6677
- const objects = await PublicationObjects.open({ directory: join19(dataDir, "objects"), key: key2, identity: c.identity });
7053
+ const objects = await PublicationObjects.open({ directory: join20(dataDir, "objects"), key: key2, identity: c.identity });
6678
7054
  handles.push(objects);
6679
- const archive = await RuntimeRecoveryArchive.open({ directory: join19(dataDir, "recovery"), objects });
7055
+ const archive = await RuntimeRecoveryArchive.open({ directory: join20(dataDir, "recovery"), objects });
6680
7056
  handles.push(archive);
6681
7057
  return { archive, id: c.archiveId };
6682
7058
  };
6683
7059
  try {
6684
7060
  if (command === "inspect-recovery") {
6685
- const ref = await open3(config);
7061
+ const ref = await open5(config);
6686
7062
  return await ref.archive.list();
6687
7063
  }
6688
7064
  if (command === "restore-recovery") {
6689
- const ref = await open3(config);
7065
+ const ref = await open5(config);
6690
7066
  return await restoreRecoveryArchive({ ...ref, destination: absolute2(config.destination), deletionWatermark });
6691
7067
  }
6692
- const common = await open3(config.common), local = await open3(config.local), remote = await open3(config.remote);
7068
+ const common = await open5(config.common), local = await open5(config.local), remote = await open5(config.remote);
6693
7069
  const report = await compareRecoveryArchives({ common, local, remote, deletionWatermark, maximumRows: config.maximumRows, maximumBytes: config.maximumBytes });
6694
7070
  const reportFile = absolute2(config.reportFile);
6695
- assertPrivateDirectory(dirname12(reportFile));
7071
+ assertPrivateDirectory(dirname13(reportFile));
6696
7072
  for (const c of [config.common, config.local, config.remote]) if (isWithin(absolute2(c.dataDir), reportFile) || reportFile === absolute2(c.dataKeyFile)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
6697
7073
  const content = await common.archive.objects.putContent(Buffer.from(JSON.stringify(report)));
6698
7074
  for (const ref of [common, local, remote]) checkRecoveryDeletion((await ref.archive.read(ref.id)).manifest, deletionWatermark);
6699
7075
  const pointer = { format: "engine7-recovery-diff-reference-v1", identity: common.archive.objects.identity, digest: report.digest, content };
6700
7076
  if (existsSync7(reportFile)) {
6701
7077
  if (JSON.stringify(JSON.parse(readPrivateFile(reportFile, 1024 * 1024).toString())) !== JSON.stringify(pointer)) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6702
- } else writeFileSync14(reportFile, JSON.stringify(pointer), { mode: 384, flag: "wx", flush: true });
6703
- await syncDirectory(dirname12(reportFile));
7078
+ } else writeFileSync13(reportFile, JSON.stringify(pointer), { mode: 384, flag: "wx", flush: true });
7079
+ await syncDirectory(dirname13(reportFile));
6704
7080
  for (const ref of [common, local, remote]) checkRecoveryDeletion((await ref.archive.read(ref.id)).manifest, deletionWatermark);
6705
7081
  return { digest: report.digest, reportFile, counts: report.counts, scannedRecords: report.scannedRecords, admissionAllowed: false, activationAllowed: false };
6706
7082
  } finally {
@@ -6805,7 +7181,7 @@ async function runRuntimeSyncCli(command, config) {
6805
7181
  releases2.push(registerRuntimeWriter(root, "travel-data-runtime-sync"));
6806
7182
  }
6807
7183
  for (const d of descriptors) {
6808
- const place = sqliteStoreLocation(d.file), probe = new DatabaseSync17(d.file, { readOnly: true });
7184
+ const place = sqliteStoreLocation(d.file), probe = new DatabaseSync18(d.file, { readOnly: true });
6809
7185
  let component;
6810
7186
  try {
6811
7187
  component = readSchemaVersion(probe)?.component;
@@ -6814,7 +7190,7 @@ async function runRuntimeSyncCli(command, config) {
6814
7190
  }
6815
7191
  if (component !== place.component) throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
6816
7192
  const stopped = command === "preserve-local-runtime";
6817
- const db = new DatabaseSync17(d.file, { readOnly: stopped, allowExtension: !stopped && component === "legacy-memory" });
7193
+ const db = new DatabaseSync18(d.file, { readOnly: stopped, allowExtension: !stopped && component === "legacy-memory" });
6818
7194
  handles.push(db);
6819
7195
  databaseHandles[d.id] = db;
6820
7196
  if (!stopped && component === "legacy-memory") loadLegacySQLiteVectorExtension(db, d.sqliteVecExtensionFile === void 0 ? void 0 : absolute3(d.sqliteVecExtensionFile));
@@ -6829,11 +7205,11 @@ async function runRuntimeSyncCli(command, config) {
6829
7205
  if (stopped) databases[d.id] = { file: d.file, source: new SQLiteReplicationSourceReader(db, binding) };
6830
7206
  else databases[d.id] = writableDatabases[d.id] = { file: d.file, source: new SQLiteReplicationSource(db, binding) };
6831
7207
  }
6832
- objects = await PublicationObjects.open({ directory: join20(dataDir, "objects"), key: key2, identity: profile.identity, maximumBytes: config.maximumBytes });
7208
+ objects = await PublicationObjects.open({ directory: join21(dataDir, "objects"), key: key2, identity: profile.identity, maximumBytes: config.maximumBytes });
6833
7209
  const initialize2 = command === "prepare-runtime";
6834
- trees = await RuntimeTreeSource.open({ directory: join20(dataDir, "runtime-trees"), profile, objects, initialize: initialize2 && config.initializeTreeSource === true, maximumBytes: config.maximumTreeBytes });
7210
+ trees = await RuntimeTreeSource.open({ directory: join21(dataDir, "runtime-trees"), profile, objects, initialize: initialize2 && config.initializeTreeSource === true, maximumBytes: config.maximumTreeBytes });
6835
7211
  source = await RuntimePublicationSource.open({
6836
- directory: join20(dataDir, "runtime-publications"),
7212
+ directory: join21(dataDir, "runtime-publications"),
6837
7213
  profile,
6838
7214
  objects,
6839
7215
  trees,
@@ -6868,7 +7244,7 @@ async function runRuntimeSyncCli(command, config) {
6868
7244
  const deletionWatermark = recoveryDeletionReader(config);
6869
7245
  if (deletionWatermark() > capture2.deletionWatermark) throw new Error("RECOVERY_DELETION_BARRIER");
6870
7246
  return await source.withStoppedPreparation(capture2, async (h) => {
6871
- const archive = await RuntimeRecoveryArchive.open({ directory: join20(dataDir, "recovery"), objects, initialize: config.initializeRecoveryArchive === true });
7247
+ const archive = await RuntimeRecoveryArchive.open({ directory: join21(dataDir, "recovery"), objects, initialize: config.initializeRecoveryArchive === true });
6872
7248
  try {
6873
7249
  return await archive.preserve({ id: config.archiveId, kind: "LOCAL", manifest: h.manifest, databases: databaseHandles, deletionWatermark });
6874
7250
  } finally {
@@ -6885,8 +7261,8 @@ async function runRuntimeSyncCli(command, config) {
6885
7261
  url: config.url,
6886
7262
  profile,
6887
7263
  timeoutMs: config.timeoutMs,
6888
- ca: readFileSync9(absolute3(config.caFile)),
6889
- cert: readFileSync9(absolute3(config.certificateFile)),
7264
+ ca: readFileSync8(absolute3(config.caFile)),
7265
+ cert: readFileSync8(absolute3(config.certificateFile)),
6890
7266
  key: readPrivateFile(absolute3(config.privateKeyFile))
6891
7267
  });
6892
7268
  const sync = { source, client, objects, databases: writableDatabases, maximumObjects: config.maximumObjects, maximumCommits: config.maximumCommits, maximumBytes: config.maximumDrainBytes };
@@ -6936,50 +7312,68 @@ async function runRuntimeSyncCli(command, config) {
6936
7312
  }
6937
7313
 
6938
7314
  // src/continuity/runtime-publication-restore.ts
6939
- import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
6940
- import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync15 } from "node:fs";
6941
- import { join as join22, resolve as resolve21 } from "node:path";
7315
+ import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
7316
+ import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync14 } from "node:fs";
7317
+ import { join as join23, resolve as resolve21 } from "node:path";
6942
7318
  init_sqlite_replication();
6943
7319
 
6944
7320
  // src/continuity/generation-integrity.ts
6945
7321
  import { createHash as createHash19 } from "node:crypto";
6946
- import { constants as constants10, closeSync as closeSync13, fstatSync as fstatSync6, lstatSync as lstatSync18, openSync as openSync14, readSync as readSync3, readdirSync as readdirSync4, realpathSync as realpathSync13 } from "node:fs";
6947
- import { join as join21, resolve as resolve20 } from "node:path";
6948
- function runtimeGenerationIntegrity(directory2) {
6949
- const root = resolve20(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
7322
+ import { constants as constants11, closeSync as closeSync13, fstatSync as fstatSync6, lstatSync as lstatSync18, openSync as openSync14, readSync as readSync3, readdirSync as readdirSync4, realpathSync as realpathSync13 } from "node:fs";
7323
+ import { join as join22, resolve as resolve20 } from "node:path";
7324
+ import { open as open4 } from "node:fs/promises";
7325
+ var recentSeals = /* @__PURE__ */ new Map();
7326
+ function rememberSeal(root, integrity, files) {
7327
+ recentSeals.delete(root);
7328
+ recentSeals.set(root, { integrity: JSON.stringify(integrity), metadata: fileMetadata(files) });
7329
+ if (recentSeals.size > 4) recentSeals.delete(recentSeals.keys().next().value);
7330
+ }
7331
+ var metadata3 = (stat2) => [stat2.dev, stat2.ino, stat2.size, stat2.mode, stat2.mtimeNs, stat2.ctimeNs].join(":");
7332
+ function generationFiles(root) {
7333
+ const files = [];
6950
7334
  if (realpathSync13(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6951
7335
  const visit = (path3) => {
6952
7336
  if (path3 === ".runtime-publication-receipt.json") return;
6953
- const file = join21(root, path3), before = lstatSync18(file, { bigint: true });
6954
- if (before.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6955
- if (before.isDirectory()) {
7337
+ const file = join22(root, path3), stat2 = lstatSync18(file, { bigint: true });
7338
+ if (stat2.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
7339
+ if (stat2.isDirectory()) {
6956
7340
  for (const name of readdirSync4(file).sort()) visit(path3 ? path3 + "/" + name : name);
6957
7341
  return;
6958
7342
  }
6959
- if (!before.isFile() || before.size > BigInt(Number.MAX_SAFE_INTEGER) || result.length >= 1e5) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6960
- const fd = openSync14(file, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0)), hash2 = createHash19("sha256");
7343
+ if (!stat2.isFile() || stat2.size > BigInt(Number.MAX_SAFE_INTEGER) || files.length >= 1e5) throw new Error("TRAVEL_GENERATION_INTEGRITY");
7344
+ files.push({ path: path3, stat: stat2 });
7345
+ };
7346
+ visit("");
7347
+ return files.sort((a, b) => a.path.localeCompare(b.path, "en"));
7348
+ }
7349
+ var fileMetadata = (files) => JSON.stringify(files.map((file) => [file.path, metadata3(file.stat)]));
7350
+ async function runtimeGenerationIntegrityAsync(directory2) {
7351
+ const root = resolve20(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
7352
+ const files = generationFiles(root);
7353
+ for (const { path: path3, stat: before } of files) {
7354
+ const file = join22(root, path3), handle = await open4(file, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash2 = createHash19("sha256");
6961
7355
  let bytes = 0;
6962
7356
  try {
6963
7357
  while (true) {
6964
- const size = readSync3(fd, buffer);
6965
- if (!size) break;
6966
- hash2.update(buffer.subarray(0, size));
6967
- bytes += size;
7358
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
7359
+ if (!bytesRead) break;
7360
+ hash2.update(buffer.subarray(0, bytesRead));
7361
+ bytes += bytesRead;
6968
7362
  }
6969
- const after = fstatSync6(fd, { bigint: true });
6970
- if ([before.dev, before.ino, before.size, before.mtimeNs, before.ctimeNs].join(":") !== [after.dev, after.ino, after.size, after.mtimeNs, after.ctimeNs].join(":") || BigInt(bytes) !== before.size) throw new Error("TRAVEL_GENERATION_INTEGRITY");
7363
+ const after = await handle.stat({ bigint: true });
7364
+ if (metadata3(before) !== metadata3(after) || metadata3(before) !== metadata3(lstatSync18(file, { bigint: true })) || BigInt(bytes) !== before.size) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6971
7365
  result.push({ path: path3, bytes, mode: Number(before.mode & 0o777n), sha256: hash2.digest("hex") });
6972
7366
  } finally {
6973
- closeSync13(fd);
7367
+ await handle.close();
6974
7368
  }
6975
- };
6976
- visit("");
6977
- return result.sort((a, b) => a.path.localeCompare(b.path, "en"));
7369
+ }
7370
+ rememberSeal(root, result, files);
7371
+ return result;
6978
7372
  }
6979
7373
 
6980
7374
  // src/continuity/runtime-publication-restore.ts
6981
7375
  async function restoreRuntimePublication(options) {
6982
- const { receiver } = options, status = await receiver.status();
7376
+ const { receiver } = options, status = await receiver.status(false);
6983
7377
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
6984
7378
  if (options.sequence !== void 0 && options.sequence !== status.published.sequence) throw new Error("PUBLICATION_STALE_PUBLICATION");
6985
7379
  const manifest = await receiver.manifest(status.published.sequence), destination = resolve21(options.destination);
@@ -6987,31 +7381,31 @@ async function restoreRuntimePublication(options) {
6987
7381
  for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "session")) {
6988
7382
  const tree = manifest.trees.find((tree2) => tree2.id === kind.id);
6989
7383
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6990
- const metadata3 = JSON.parse((await receiver.objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
6991
- const database = manifest.databases.find((d) => d.databaseId === metadata3.databaseId);
7384
+ const metadata4 = JSON.parse((await receiver.objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
7385
+ const database = manifest.databases.find((d) => d.databaseId === metadata4.databaseId);
6992
7386
  const binding = normalizeBinding({
6993
7387
  ...manifest.profile.identity,
6994
- databaseId: metadata3.databaseId,
7388
+ databaseId: metadata4.databaseId,
6995
7389
  baselineId: manifest.profile.baselineId,
6996
7390
  epoch: manifest.profile.epoch
6997
7391
  });
6998
- if (metadata3.format !== "engine7-session-events-publication-v1" || !database || JSON.stringify(metadata3.binding) !== JSON.stringify(binding) || JSON.stringify(metadata3.head) !== JSON.stringify(database.head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
7392
+ if (metadata4.format !== "engine7-session-events-publication-v1" || !database || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(database.head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6999
7393
  sessions.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
7000
7394
  }
7001
7395
  await restorePublication({ ...options, destination, deferReceipt: true });
7002
7396
  const lance = [], sessionStates = [];
7003
7397
  for (const directory2 of ["lance", "sessions"]) {
7004
- mkdirSync10(join22(destination, directory2), { mode: 448 });
7398
+ mkdirSync10(join23(destination, directory2), { mode: 448 });
7005
7399
  await syncDirectory(destination);
7006
7400
  }
7007
7401
  for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "vector")) {
7008
- const tree = manifest.trees.find((tree2) => tree2.id === kind.id), directory2 = join22(destination, "lance", tree.id);
7402
+ const tree = manifest.trees.find((tree2) => tree2.id === kind.id), directory2 = join23(destination, "lance", tree.id);
7009
7403
  await restoreLancePublication({ tree, objects: receiver.objects, destination: directory2 });
7010
- await syncDirectory(join22(destination, "lance"));
7404
+ await syncDirectory(join23(destination, "lance"));
7011
7405
  lance.push({ treeId: tree.id, directory: `lance/${tree.id}` });
7012
7406
  }
7013
7407
  for (const session of sessions) {
7014
- const directory2 = join22(destination, "sessions", session.treeId), db = new DatabaseSync18(join22(destination, "databases", session.databaseId + ".sqlite"), { readOnly: true });
7408
+ const directory2 = join23(destination, "sessions", session.treeId), db = new DatabaseSync19(join23(destination, "databases", session.databaseId + ".sqlite"), { readOnly: true });
7015
7409
  try {
7016
7410
  const head = db.prepare("SELECT head,digest FROM e7_replication_control WHERE role='replica'").get();
7017
7411
  if (head?.head !== session.head.sequence || head.digest !== session.head.digest) throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
@@ -7019,20 +7413,20 @@ async function restoreRuntimePublication(options) {
7019
7413
  } finally {
7020
7414
  db.close();
7021
7415
  }
7022
- await syncDirectory(join22(destination, "sessions"));
7416
+ await syncDirectory(join23(destination, "sessions"));
7023
7417
  sessionStates.push({ treeId: session.treeId, databaseId: session.databaseId, directory: `sessions/${session.treeId}` });
7024
7418
  }
7025
- const after = await receiver.status();
7419
+ const after = await receiver.status(false);
7026
7420
  if (!after.dataReady || after.published?.sequence !== manifest.sequence || after.published.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
7027
- writeFileSync15(join22(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
7028
- writeFileSync15(join22(destination, ".runtime-publication-receipt.json"), JSON.stringify({
7421
+ writeFileSync14(join23(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
7422
+ writeFileSync14(join23(destination, ".runtime-publication-receipt.json"), JSON.stringify({
7029
7423
  format: "engine7-runtime-publication-restore-v1",
7030
7424
  profile: manifest.profile,
7031
7425
  receipt: status.published,
7032
7426
  databases: manifest.databases,
7033
7427
  lance,
7034
7428
  sessions: sessionStates,
7035
- integrity: runtimeGenerationIntegrity(destination),
7429
+ integrity: await runtimeGenerationIntegrityAsync(destination),
7036
7430
  activationAllowed: false
7037
7431
  }), { flag: "wx", mode: 384, flush: true });
7038
7432
  await syncDirectory(destination);
@@ -7052,7 +7446,7 @@ function databaseFile2(value2) {
7052
7446
  }
7053
7447
  function requireStandby(stateDir) {
7054
7448
  try {
7055
- const marker = JSON.parse(readPrivateFile(join23(stateDir, ".travel-restored.json")).toString());
7449
+ const marker = JSON.parse(readPrivateFile(join24(stateDir, ".travel-restored.json")).toString());
7056
7450
  if (marker.activationAllowed !== false) throw new Error();
7057
7451
  } catch {
7058
7452
  throw new Error("PUBLICATION_STANDBY_GUARD_REQUIRED");
@@ -7092,20 +7486,20 @@ async function runPublicationCli(args) {
7092
7486
  }
7093
7487
  try {
7094
7488
  const operate = async () => {
7095
- const objects = await PublicationObjects.open({ directory: join23(dataDir, "objects"), key: key2, identity: profile.identity, maximumBytes: config.maximumBytes });
7489
+ const objects = await PublicationObjects.open({ directory: join24(dataDir, "objects"), key: key2, identity: profile.identity, maximumBytes: config.maximumBytes });
7096
7490
  const databases = /* @__PURE__ */ Object.create(null);
7097
7491
  const sources = /* @__PURE__ */ Object.create(null), replicas = /* @__PURE__ */ Object.create(null);
7098
7492
  let receiver;
7099
7493
  try {
7100
7494
  for (let i = 0; i < config.databases.length; i++) {
7101
- const d = config.databases[i], probe = new DatabaseSync19(databasePaths[i], { readOnly: true });
7495
+ const d = config.databases[i], probe = new DatabaseSync20(databasePaths[i], { readOnly: true });
7102
7496
  let component;
7103
7497
  try {
7104
7498
  component = readSchemaVersion(probe)?.component;
7105
7499
  } finally {
7106
7500
  probe.close();
7107
7501
  }
7108
- const db = new DatabaseSync19(databasePaths[i], { allowExtension: component === "legacy-memory" });
7502
+ const db = new DatabaseSync20(databasePaths[i], { allowExtension: component === "legacy-memory" });
7109
7503
  databases[d.id] = db;
7110
7504
  if (component === "legacy-memory") loadLegacySQLiteVectorExtension(db, d.sqliteVecExtensionFile === void 0 ? void 0 : path2(d.sqliteVecExtensionFile));
7111
7505
  if (d.writerSchemaVersion !== void 0) {
@@ -7131,13 +7525,13 @@ async function runPublicationCli(args) {
7131
7525
  }
7132
7526
  if (command === "prepare") {
7133
7527
  const manifestFile = path2(config.manifestFile);
7134
- if (realpathSync14(dirname13(manifestFile)) !== dirname13(manifestFile)) throw new Error("SYMLINK_REFUSED");
7528
+ if (realpathSync14(dirname14(manifestFile)) !== dirname14(manifestFile)) throw new Error("SYMLINK_REFUSED");
7135
7529
  if (!Array.isArray(config.roots)) throw new Error("PUBLICATION_INCOMPLETE_TREES");
7136
7530
  const roots = config.roots.map((r) => ({ id: r.id, path: path2(r.path) }));
7137
7531
  for (const r of roots) if (!isWithin(stateDir, r.path) || isWithin(r.path, manifestFile) || isWithin(r.path, keyFile)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
7138
7532
  const manifest = await capturePublication({ profile, roots, objects, sources, sequence: config.sequence, parentDigest: config.parentDigest, deletionWatermark: config.deletionWatermark });
7139
- writeFileSync16(manifestFile, JSON.stringify(manifest), { mode: 384, flag: "wx", flush: true });
7140
- await syncDirectory(dirname13(manifestFile));
7533
+ writeFileSync15(manifestFile, JSON.stringify(manifest), { mode: 384, flag: "wx", flush: true });
7534
+ await syncDirectory(dirname14(manifestFile));
7141
7535
  return { sequence: manifest.sequence, files: manifest.trees.reduce((n, t) => n + t.files.length, 0), activationAllowed: false };
7142
7536
  }
7143
7537
  if (command === "sync" || command === "drain") {
@@ -7145,8 +7539,8 @@ async function runPublicationCli(args) {
7145
7539
  url: config.url,
7146
7540
  profile,
7147
7541
  timeoutMs: config.timeoutMs,
7148
- ca: readFileSync10(path2(config.caFile)),
7149
- cert: readFileSync10(path2(config.certificateFile)),
7542
+ ca: readFileSync9(path2(config.caFile)),
7543
+ cert: readFileSync9(path2(config.certificateFile)),
7150
7544
  key: readPrivateFile(path2(config.privateKeyFile))
7151
7545
  });
7152
7546
  try {
@@ -7163,11 +7557,11 @@ async function runPublicationCli(args) {
7163
7557
  client.close();
7164
7558
  }
7165
7559
  }
7166
- receiver = await PublicationReplica.open({ directory: join23(dataDir, "publications"), profile, objects, replicas, minimumDeletionWatermark: config.minimumDeletionWatermark });
7560
+ receiver = await PublicationReplica.open({ directory: join24(dataDir, "publications"), profile, objects, replicas, minimumDeletionWatermark: config.minimumDeletionWatermark });
7167
7561
  if (command === "inspect") return await receiver.status();
7168
7562
  if (preserveReplicaCommands.includes(command)) {
7169
7563
  const deletionWatermark = recoveryDeletionReader(config);
7170
- const archive = await RuntimeRecoveryArchive.open({ directory: join23(dataDir, "recovery"), objects, initialize: config.initializeRecoveryArchive === true });
7564
+ const archive = await RuntimeRecoveryArchive.open({ directory: join24(dataDir, "recovery"), objects, initialize: config.initializeRecoveryArchive === true });
7171
7565
  try {
7172
7566
  let manifest;
7173
7567
  try {
@@ -7194,12 +7588,12 @@ async function runPublicationCli(args) {
7194
7588
  if (command === "restore") return await restorePublication({ receiver, databases, destination: path2(config.destination) });
7195
7589
  if (command === "restore-runtime") return await restoreRuntimePublication({ receiver, databases, destination: path2(config.destination), sequence: config.sequence });
7196
7590
  if (typeof config.host !== "string" || !Number.isInteger(config.port) || config.port < 0 || config.port > 65535) throw new Error("PUBLICATION_INVALID_LISTENER");
7197
- const certificate = new X509Certificate(readFileSync10(path2(config.allowedClientCertificateFile)));
7591
+ const certificate = new X509Certificate(readFileSync9(path2(config.allowedClientCertificateFile)));
7198
7592
  const server = createPublicationServer({
7199
7593
  receiver,
7200
7594
  allowedFingerprint: certificate.fingerprint256,
7201
- ca: readFileSync10(path2(config.clientCaFile)),
7202
- cert: readFileSync10(path2(config.certificateFile)),
7595
+ ca: readFileSync9(path2(config.clientCaFile)),
7596
+ cert: readFileSync9(path2(config.certificateFile)),
7203
7597
  key: readPrivateFile(path2(config.privateKeyFile))
7204
7598
  });
7205
7599
  try {