engine7 7.1.138 → 7.1.140

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.
@@ -58,7 +58,7 @@ function assertRuntimeAuthority(stateDir, operation) {
58
58
  }
59
59
  function validateTravelChannelConfiguration(channels) {
60
60
  for (const [name, value2] of Object.entries(channels ?? {})) {
61
- if (value2?.enabled !== true) continue;
61
+ if (name === "emotion" || value2?.enabled !== true) continue;
62
62
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
63
63
  if (value2.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
64
64
  const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key2, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key2) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
@@ -412,7 +412,7 @@ var init_legacy_sqlite_indexes = __esm({
412
412
  import { createHash as createHash3 } from "node:crypto";
413
413
  import { createRequire } from "node:module";
414
414
  function sqliteConstants() {
415
- return constants3 ??= createRequire(import.meta.url)("node:sqlite").constants;
415
+ return constants4 ??= createRequire(import.meta.url)("node:sqlite").constants;
416
416
  }
417
417
  function bindingText(binding) {
418
418
  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");
@@ -584,7 +584,7 @@ function sourcePendingBytes(db, after, through) {
584
584
  if (!Number.isSafeInteger(bytes) || bytes < 0) throw new Error("REPLICATION_CORRUPT_CONTROL");
585
585
  return bytes;
586
586
  }
587
- var constants3, metadataTables, metadataColumns, guardPrefix, identifier, hash, digestPattern, SQLiteReplicationSourceReader, SQLiteReplicationSource, SQLiteReplicationReplica;
587
+ var constants4, metadataTables, metadataColumns, guardPrefix, identifier, hash, digestPattern, SQLiteReplicationSourceReader, SQLiteReplicationSource, SQLiteReplicationReplica;
588
588
  var init_sqlite_replication = __esm({
589
589
  "src/continuity/sqlite-replication.ts"() {
590
590
  "use strict";
@@ -823,7 +823,8 @@ var init_sqlite_replication = __esm({
823
823
  this.derived = inspectLegacySQLiteIndexes(db);
824
824
  this.tables = inspectTables(db, this.derived?.excludedTables);
825
825
  if (sqliteReplicationSchemaHash(db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
826
- if (db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("REPLICATION_INVALID_BASELINE: foreign key");
826
+ 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());
827
+ if (!initialized && db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("REPLICATION_INVALID_BASELINE: foreign key");
827
828
  const allowed = new Set(options.suppressTriggers ?? []);
828
829
  if ([...allowed].some((name) => name.startsWith("writer_guard_"))) throw new Error("REPLICATION_WRITER_GUARD_MUST_REMAIN");
829
830
  this.triggers = schemaRows(db).filter((r) => r.type === "trigger" && !r.name.startsWith("writer_guard_"));
@@ -831,7 +832,6 @@ var init_sqlite_replication = __esm({
831
832
  throw new Error("REPLICATION_UNCLASSIFIED_TRIGGER");
832
833
  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));
833
834
  db.function("engine7_replication_capture_active", () => this.applying ? 1 : 0);
834
- 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());
835
835
  db.exec("BEGIN IMMEDIATE");
836
836
  try {
837
837
  if (!initialized) this.derived?.rebuild();
@@ -976,8 +976,8 @@ var init_sqlite_replication = __esm({
976
976
  });
977
977
 
978
978
  // src/continuity/runtime-replication.ts
979
- import { constants as constants6, lstatSync as lstatSync7, realpathSync as realpathSync2, mkdirSync as mkdirSync4, openSync as openSync6, closeSync as closeSync5, fstatSync as fstatSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5, fsyncSync as fsyncSync5 } from "node:fs";
980
- import { basename as basename2, dirname as dirname4, join as join6, resolve as resolve5 } from "node:path";
979
+ import { constants as constants7, lstatSync as lstatSync7, realpathSync as realpathSync2, mkdirSync as mkdirSync4, openSync as openSync6, closeSync as closeSync5, fstatSync as fstatSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync4, fsyncSync as fsyncSync5 } from "node:fs";
980
+ import { basename as basename2, dirname as dirname4, join as join7, resolve as resolve6 } from "node:path";
981
981
  function checkKey(component, key2) {
982
982
  if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
983
983
  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;
@@ -986,19 +986,19 @@ function checkKey(component, key2) {
986
986
  }
987
987
  function location2(stateDir, component, key2) {
988
988
  checkKey(component, key2);
989
- return join6(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
989
+ return join7(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
990
990
  }
991
991
  function runtimeReplicationFile(stateDir, component, key2) {
992
992
  checkKey(component, key2);
993
- if (component === "legacy-memory") return join6(stateDir, "agents", key2, "memory", "memory.db");
994
- if (component === "topics-vectors") return join6(stateDir, "topics-history", key2, "vectors.db");
995
- if (component === "session-events") return join6(stateDir, ".continuity", "session-events.db");
996
- return join6(stateDir, "." + component, component + ".db");
993
+ if (component === "legacy-memory") return join7(stateDir, "agents", key2, "memory", "memory.db");
994
+ if (component === "topics-vectors") return join7(stateDir, "topics-history", key2, "vectors.db");
995
+ if (component === "session-events") return join7(stateDir, ".continuity", "session-events.db");
996
+ return join7(stateDir, "." + component, component + ".db");
997
997
  }
998
998
  function runtimeReplicationLocation(stateDir, component, file) {
999
999
  const key2 = component === "legacy-memory" ? basename2(dirname4(dirname4(file))) : component === "topics-vectors" ? basename2(dirname4(file)) : void 0;
1000
1000
  try {
1001
- if (resolve5(file) !== resolve5(runtimeReplicationFile(stateDir, component, key2))) throw new Error();
1001
+ if (resolve6(file) !== resolve6(runtimeReplicationFile(stateDir, component, key2))) throw new Error();
1002
1002
  } catch (error) {
1003
1003
  throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED", { cause: error });
1004
1004
  }
@@ -1010,7 +1010,7 @@ function normalize2(input) {
1010
1010
  }
1011
1011
  function directory(path3) {
1012
1012
  const info = lstatSync7(path3);
1013
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path3) !== resolve5(path3) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1013
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path3) !== resolve6(path3) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1014
1014
  throw new Error("REPLICATION_REGISTRATION_INVALID");
1015
1015
  }
1016
1016
  function readRuntimeReplicationRegistration(stateDir, component, key2) {
@@ -1024,15 +1024,15 @@ function readRuntimeReplicationRegistration(stateDir, component, key2) {
1024
1024
  directory(dirname4(file));
1025
1025
  let fd;
1026
1026
  try {
1027
- fd = openSync6(file, constants6.O_RDONLY | (constants6.O_NOFOLLOW ?? 0));
1027
+ fd = openSync6(file, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
1028
1028
  } catch (error) {
1029
1029
  if (error.code === "ENOENT") return null;
1030
1030
  throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
1031
1031
  }
1032
1032
  try {
1033
1033
  const info = fstatSync4(fd);
1034
- if (!info.isFile() || info.size > 4096 || realpathSync2(file) !== resolve5(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
1035
- return normalize2(JSON.parse(readFileSync4(fd, "utf8")));
1034
+ if (!info.isFile() || info.size > 4096 || realpathSync2(file) !== resolve6(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
1035
+ return normalize2(JSON.parse(readFileSync3(fd, "utf8")));
1036
1036
  } catch (error) {
1037
1037
  throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
1038
1038
  } finally {
@@ -1047,7 +1047,7 @@ function checkRuntimeReplicationFile(file, registration, initial = false) {
1047
1047
  info = lstatSync7(file);
1048
1048
  } catch (error) {
1049
1049
  if (registration || !initial || error.code !== "ENOENT") throw error;
1050
- let parent = dirname4(resolve5(file));
1050
+ let parent = dirname4(resolve6(file));
1051
1051
  for (; ; ) {
1052
1052
  try {
1053
1053
  const existing = lstatSync7(parent);
@@ -1059,7 +1059,7 @@ function checkRuntimeReplicationFile(file, registration, initial = false) {
1059
1059
  }
1060
1060
  }
1061
1061
  }
1062
- if (!info.isFile() || info.isSymbolicLink() || realpathSync2(file) !== resolve5(file)) throw new Error();
1062
+ if (!info.isFile() || info.isSymbolicLink() || realpathSync2(file) !== resolve6(file)) throw new Error();
1063
1063
  } catch (error) {
1064
1064
  throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: error });
1065
1065
  }
@@ -1088,7 +1088,7 @@ function enrollRuntimeReplication(db, stateDir, component, binding, key2) {
1088
1088
  mkdirSync4(dirname4(file), { mode: 448, recursive: true });
1089
1089
  directory(dirname4(file));
1090
1090
  try {
1091
- writeFileSync5(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1091
+ writeFileSync4(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1092
1092
  } catch (error) {
1093
1093
  if (error.code !== "EEXIST") throw error;
1094
1094
  if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
@@ -1521,7 +1521,7 @@ var init_read_budget = __esm({
1521
1521
  // src/continuity/runtime-lock.ts
1522
1522
  import { randomUUID as randomUUID5 } from "node:crypto";
1523
1523
  import { AsyncLocalStorage } from "node:async_hooks";
1524
- import { closeSync as closeSync7, lstatSync as lstatSync9, mkdirSync as mkdirSync5, openSync as openSync8, readFileSync as readFileSync6, realpathSync as realpathSync4 } from "node:fs";
1524
+ import { closeSync as closeSync7, lstatSync as lstatSync9, mkdirSync as mkdirSync5, openSync as openSync8, readFileSync as readFileSync5, realpathSync as realpathSync4 } from "node:fs";
1525
1525
  import { join as join9 } from "node:path";
1526
1526
  import { createRequire as createRequire4 } from "node:module";
1527
1527
  function openSQLite(file, options = {}) {
@@ -1607,7 +1607,7 @@ function inspectRuntimeWriters(stateDir) {
1607
1607
  }
1608
1608
  for (const file2 of [".engine.pid", ".bg-worker.pid"]) {
1609
1609
  try {
1610
- const text2 = readFileSync6(join9(stateDir, file2), "utf8").trim(), pid = /^[1-9][0-9]*$/.test(text2) ? Number(text2) : NaN;
1610
+ const text2 = readFileSync5(join9(stateDir, file2), "utf8").trim(), pid = /^[1-9][0-9]*$/.test(text2) ? Number(text2) : NaN;
1611
1611
  legacy.push({ file: file2, ...Number.isSafeInteger(pid) ? { pid } : {}, state: stateOf(pid) });
1612
1612
  } catch (error) {
1613
1613
  if (error.code !== "ENOENT") throw error;
@@ -1686,7 +1686,7 @@ async function withCheckpointLock(stateDir, operation) {
1686
1686
  for (const name of [".engine.pid", ".bg-worker.pid"]) {
1687
1687
  let value2;
1688
1688
  try {
1689
- value2 = readFileSync6(join9(stateDir, name), "utf8").trim();
1689
+ value2 = readFileSync5(join9(stateDir, name), "utf8").trim();
1690
1690
  } catch (error) {
1691
1691
  if (error.code === "ENOENT") continue;
1692
1692
  throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
@@ -1963,7 +1963,7 @@ var init_topics_history = __esm({
1963
1963
  });
1964
1964
 
1965
1965
  // src/continuity/node-main.ts
1966
- import { readFileSync as readFileSync16, lstatSync as lstatSync27, realpathSync as realpathSync23 } from "node:fs";
1966
+ import { readFileSync as readFileSync15, lstatSync as lstatSync26, realpathSync as realpathSync23 } from "node:fs";
1967
1967
  import { DatabaseSync as DatabaseSync30 } from "node:sqlite";
1968
1968
  import { isAbsolute as isAbsolute10, resolve as resolve29 } from "node:path";
1969
1969
  import { fileURLToPath as fileURLToPath2 } from "node:url";
@@ -1971,7 +1971,7 @@ import { randomUUID as randomUUID16, createHash as createHash42 } from "node:cry
1971
1971
 
1972
1972
  // src/continuity/node-agent.ts
1973
1973
  import { DatabaseSync as DatabaseSync29 } from "node:sqlite";
1974
- import { existsSync as existsSync18, lstatSync as lstatSync26, mkdirSync as mkdirSync16, readFileSync as readFileSync15, realpathSync as realpathSync22, writeFileSync as writeFileSync26 } from "node:fs";
1974
+ import { existsSync as existsSync18, lstatSync as lstatSync25, mkdirSync as mkdirSync16, readFileSync as readFileSync14, realpathSync as realpathSync22, writeFileSync as writeFileSync25 } from "node:fs";
1975
1975
  import { isAbsolute as isAbsolute9, join as join38, resolve as resolve28 } from "node:path";
1976
1976
  import { createHash as createHash40, randomUUID as randomUUID15 } from "node:crypto";
1977
1977
  import { isIP } from "node:net";
@@ -1979,41 +1979,218 @@ import { isIP } from "node:net";
1979
1979
  // src/continuity/activation.ts
1980
1980
  init_runtime_authority();
1981
1981
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
1982
- import { cpSync, existsSync as existsSync10, lstatSync as lstatSync13, mkdirSync as mkdirSync9, readdirSync as readdirSync4, realpathSync as realpathSync10, unlinkSync as unlinkSync9, writeFileSync as writeFileSync12 } from "node:fs";
1982
+ import { constants as constants11, existsSync as existsSync10, mkdirSync as mkdirSync9, realpathSync as realpathSync10, unlinkSync as unlinkSync8, writeFileSync as writeFileSync11 } from "node:fs";
1983
+ import { copyFile, lstat as lstat3, mkdir, readdir as readdir2 } from "node:fs/promises";
1983
1984
  import { dirname as dirname11, isAbsolute as isAbsolute3, join as join19, resolve as resolve14 } from "node:path";
1984
1985
 
1985
1986
  // src/continuity/publication.ts
1986
1987
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
1987
1988
  import { createHash as createHash2 } from "node:crypto";
1988
1989
  import { lstatSync as lstatSync3 } from "node:fs";
1989
- import { join as join3, resolve as resolve3 } from "node:path";
1990
+ import { join as join4, resolve as resolve4 } from "node:path";
1991
+
1992
+ // src/continuity/inventory.ts
1993
+ import { constants as constants2 } from "node:fs";
1994
+ import { lstat, open, readdir, realpath } from "node:fs/promises";
1995
+ import { isAbsolute, join as join2, relative, resolve as resolve2, sep } from "node:path";
1996
+ 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(" "));
1997
+ var STATE_EXCLUDED = {
1998
+ ".continuity": "local runtime control; never business state",
1999
+ ".engine.pid": "local process identity",
2000
+ ".bg-worker.pid": "local process identity",
2001
+ ".travel-restored.json": "deployment activation gate; recreated on restore",
2002
+ ".travel-enrolled.json": "local runtime enrollment; recreated per node",
2003
+ ".travel-active.json": "local activation receipt; recreated per generation",
2004
+ ".git": "source control metadata",
2005
+ ".gitignore": "source control metadata",
2006
+ ".log-baseline.txt": "local diagnostics",
2007
+ logs: "local diagnostics; not authoritative history",
2008
+ diagnostics: "local diagnostics",
2009
+ backups: "historical recovery copies; not active state",
2010
+ "package.json": "installed application metadata",
2011
+ "start.sh": "local launcher; deployment must be reviewed separately",
2012
+ node_modules: "installed dependencies",
2013
+ install: "installed application",
2014
+ CogniFold: "installed optional runtime",
2015
+ "everos-venv": "installed Python runtime",
2016
+ "ollama-models": "installed model weights"
2017
+ };
2018
+ var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
2019
+ var WORKSPACE_DIAGNOSTICS = /* @__PURE__ */ new Set([".system-prompt.txt", ".context-debug.txt"]);
2020
+ var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
2021
+ 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(" "));
2022
+ 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(" "));
2023
+ function coreReason(path3) {
2024
+ const name = path3.split("/").at(-1);
2025
+ if (CORE_OMITTED.has(name) || /(?:\.lance$|(?:^|[-.])bak(?:[-.]|$))/i.test(name)) return "optional attachments, historical copies or rebuildable indexes; outside core travel";
2026
+ 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";
2027
+ }
2028
+ function stateReason(name, options) {
2029
+ if (options.selection === "core" && coreReason(name)) return coreReason(name);
2030
+ if (options.includeStateEntries?.includes(name)) return void 0;
2031
+ return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
2032
+ }
2033
+ function knownState(name) {
2034
+ return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
2035
+ }
2036
+ async function classifyState(options) {
2037
+ const result = { included: [], excluded: [], unclassified: [] };
2038
+ for (const name of (await readdir(options.stateDir)).sort()) {
2039
+ const reason = stateReason(name, options);
2040
+ if (reason) result.excluded.push({ path: name, reason });
2041
+ 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);
2042
+ else result.unclassified.push(name);
2043
+ }
2044
+ return result;
2045
+ }
2046
+ function validateRelativePath(path3) {
2047
+ if (typeof path3 !== "string" || !path3 || path3.length > 2048 || isAbsolute(path3)) throw new Error("INVALID_ARTIFACT_PATH");
2048
+ for (const part of path3.split("/")) {
2049
+ 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)))
2050
+ throw new Error("INVALID_ARTIFACT_PATH");
2051
+ }
2052
+ }
2053
+ function isWithin(root, candidate) {
2054
+ const rel = relative(resolve2(root), resolve2(candidate));
2055
+ return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2056
+ }
2057
+ async function collectInventory(options) {
2058
+ if (options.selection !== void 0 && options.selection !== "core") throw new Error("INVALID_INVENTORY_SELECTION");
2059
+ const state2 = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join2(state2, "workspace"));
2060
+ if (state2 === workspace || isWithin(workspace, state2)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
2061
+ const roots = { state: state2, workspace }, entries = [], exclusions = [], aliases = /* @__PURE__ */ new Set();
2062
+ const include = new Set(options.includeStateEntries ?? []);
2063
+ for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
2064
+ validateRelativePath(name);
2065
+ if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
2066
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2067
+ }
2068
+ for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
2069
+ for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
2070
+ validateRelativePath(name);
2071
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2072
+ if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
2073
+ }
2074
+ const classification = await classifyState(options);
2075
+ if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
2076
+ async function walk(root, directory2, prefix2 = "", ancestors = /* @__PURE__ */ new Set()) {
2077
+ const canonical3 = await realpath(directory2);
2078
+ if (ancestors.has(canonical3)) throw new Error(`SYMLINK_CYCLE: ${root}/${prefix2}`);
2079
+ const parents = new Set(ancestors);
2080
+ parents.add(canonical3);
2081
+ for (const name of (await readdir(directory2)).sort()) {
2082
+ const path3 = prefix2 ? prefix2 + "/" + name : name;
2083
+ let source = join2(directory2, name);
2084
+ if (root === "state" && source === workspace) continue;
2085
+ let reason = NESTED_EXCLUDED[name];
2086
+ if (root === "state" && prefix2) reason = options.excludeStateEntries?.[path3] ?? reason;
2087
+ if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path3] ?? reason;
2088
+ if (root === "workspace" && !prefix2 && WORKSPACE_DIAGNOSTICS.has(name)) reason = "generated runtime diagnostics; recreated on each node";
2089
+ if (!prefix2 && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
2090
+ if (root === "state" && !prefix2) {
2091
+ reason = stateReason(name, options);
2092
+ if (!reason && options.selection !== "core" && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
2093
+ }
2094
+ if (options.selection === "core") reason = coreReason(path3) ?? reason;
2095
+ if (reason) {
2096
+ exclusions.push({ root, path: path3, reason });
2097
+ continue;
2098
+ }
2099
+ validateRelativePath(path3);
2100
+ const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
2101
+ if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
2102
+ aliases.add(key2);
2103
+ let info = await lstat(source, { bigint: true }), linkSignature = "";
2104
+ if (options.selection === "core" && root === "workspace" && !prefix2 && !CORE_DIRECTORIES.has(name) && (info.isDirectory() || info.isSymbolicLink() && !/\.[a-z0-9]+$/i.test(name))) {
2105
+ exclusions.push({ root, path: path3, reason: "optional workspace material; outside core travel" });
2106
+ continue;
2107
+ }
2108
+ if (info.isSymbolicLink()) {
2109
+ linkSignature = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":") + ":";
2110
+ try {
2111
+ source = await realpath(source);
2112
+ } catch {
2113
+ throw new Error(`SYMLINK_REFUSED: ${root}/${path3}`);
2114
+ }
2115
+ info = await lstat(source, { bigint: true });
2116
+ linkSignature += source + ":";
2117
+ }
2118
+ if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
2119
+ if (options.selection === "core" && root === "workspace" && !prefix2 && info.isDirectory() && !CORE_DIRECTORIES.has(name)) {
2120
+ exclusions.push({ root, path: path3, reason: "optional workspace material; outside core travel" });
2121
+ continue;
2122
+ }
2123
+ if (info.isDirectory()) {
2124
+ try {
2125
+ const marker = await lstat(join2(source, "pyvenv.cfg"));
2126
+ if (marker.isFile() && !marker.isSymbolicLink()) {
2127
+ exclusions.push({ root, path: path3, reason: "installed Python virtual environment; rebuild for the target platform" });
2128
+ continue;
2129
+ }
2130
+ } catch (error) {
2131
+ if (error.code !== "ENOENT") throw error;
2132
+ }
2133
+ }
2134
+ const entry = {
2135
+ root,
2136
+ path: path3,
2137
+ source,
2138
+ kind: info.isDirectory() ? "directory" : "file",
2139
+ bytes: Number(info.size),
2140
+ mode: Number(info.mode) & 448,
2141
+ signature: linkSignature + [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
2142
+ };
2143
+ entries.push(entry);
2144
+ if (info.isDirectory()) await walk(root, source, path3, parents);
2145
+ else {
2146
+ const h = await open(source, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
2147
+ const header = Buffer.alloc(16);
2148
+ try {
2149
+ await h.read(header, 0, 16, 0);
2150
+ } finally {
2151
+ await h.close();
2152
+ }
2153
+ if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
2154
+ else if (info.size > 0n && /\.(db|sqlite|sqlite3)$/i.test(path3)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path3}`);
2155
+ }
2156
+ }
2157
+ }
2158
+ await walk("state", state2);
2159
+ await walk("workspace", workspace);
2160
+ const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
2161
+ for (const entry of entries) {
2162
+ if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
2163
+ if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
2164
+ entry.kind = "sidecar";
2165
+ }
2166
+ }
2167
+ return { entries, exclusions, roots };
2168
+ }
1990
2169
 
1991
2170
  // src/continuity/publication-objects.ts
1992
2171
  import { DatabaseSync } from "node:sqlite";
1993
2172
  import {
1994
- constants as constants2,
2173
+ constants as constants3,
1995
2174
  openSync as openSync2,
1996
2175
  closeSync as closeSync2,
1997
2176
  fstatSync as fstatSync2,
1998
2177
  fsyncSync as fsyncSync2,
1999
2178
  readSync,
2000
- writeSync,
2001
2179
  lstatSync as lstatSync2,
2002
2180
  realpathSync,
2003
- mkdirSync as mkdirSync2,
2004
- readFileSync as readFileSync2,
2005
- writeFileSync as writeFileSync2,
2006
- linkSync,
2007
- unlinkSync
2181
+ mkdirSync as mkdirSync2
2008
2182
  } from "node:fs";
2009
- import { join as join2, dirname as dirname2, resolve as resolve2 } from "node:path";
2183
+ import { open as open2, writeFile, link, unlink } from "node:fs/promises";
2184
+ import { join as join3, dirname as dirname2, resolve as resolve3 } from "node:path";
2010
2185
  import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID as randomUUID2 } from "node:crypto";
2186
+ import { setImmediate } from "node:timers/promises";
2011
2187
  var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
2012
2188
  var HASH = /^[a-f0-9]{64}$/;
2013
2189
  var OVERHEAD = 32;
2014
2190
  var MAGIC = Buffer.from("E7P1");
2191
+ var INLINE_BYTES = 64 * 1024;
2015
2192
  var sha = (body) => createHash("sha256").update(body).digest("hex");
2016
- var noFollow = constants2.O_NOFOLLOW ?? 0;
2193
+ var noFollow = constants3.O_NOFOLLOW ?? 0;
2017
2194
  function validateObjectRef(ref) {
2018
2195
  if (!ref || !HASH.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > PUBLICATION_CHUNK_BYTES)
2019
2196
  throw new Error("PUBLICATION_INVALID_OBJECT");
@@ -2029,12 +2206,12 @@ function validateFileContent(file) {
2029
2206
  }
2030
2207
  function assertPrivateDirectory2(path3) {
2031
2208
  const info = lstatSync2(path3);
2032
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path3) !== resolve2(path3) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
2209
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path3) !== resolve3(path3) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
2033
2210
  throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
2034
2211
  }
2035
2212
  function syncDir(path3) {
2036
2213
  if (process.platform === "win32") return;
2037
- const fd = openSync2(path3, constants2.O_RDONLY);
2214
+ const fd = openSync2(path3, constants3.O_RDONLY);
2038
2215
  try {
2039
2216
  fsyncSync2(fd);
2040
2217
  } finally {
@@ -2043,7 +2220,7 @@ function syncDir(path3) {
2043
2220
  }
2044
2221
  function preparePrivateDirectory(path3) {
2045
2222
  const missing = [];
2046
- let parent = resolve2(path3);
2223
+ let parent = resolve3(path3);
2047
2224
  for (; ; ) {
2048
2225
  try {
2049
2226
  lstatSync2(parent);
@@ -2087,15 +2264,24 @@ function preparePrivateDatabase(path3) {
2087
2264
  throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
2088
2265
  syncDir(dirname2(path3));
2089
2266
  }
2090
- function exclusivePublish(path3, body) {
2091
- const temp = join2(dirname2(path3), "." + randomUUID2() + ".partial");
2267
+ async function syncDirAsync(path3) {
2268
+ if (process.platform === "win32") return;
2269
+ const fd = await open2(path3, constants3.O_RDONLY);
2270
+ try {
2271
+ await fd.sync();
2272
+ } finally {
2273
+ await fd.close();
2274
+ }
2275
+ }
2276
+ async function exclusivePublish(path3, body, deferDirectorySync = false) {
2277
+ const temp = join3(dirname2(path3), "." + randomUUID2() + ".partial");
2092
2278
  try {
2093
- writeFileSync2(temp, body, { flag: "wx", mode: 384, flush: true });
2094
- linkSync(temp, path3);
2095
- syncDir(dirname2(path3));
2279
+ await writeFile(temp, body, { flag: "wx", mode: 384, flush: true });
2280
+ await link(temp, path3);
2281
+ if (!deferDirectorySync) await syncDirAsync(dirname2(path3));
2096
2282
  } finally {
2097
2283
  try {
2098
- unlinkSync(temp);
2284
+ await unlink(temp);
2099
2285
  } catch (error) {
2100
2286
  if (error.code !== "ENOENT") throw error;
2101
2287
  }
@@ -2108,25 +2294,26 @@ var PublicationObjects = class _PublicationObjects {
2108
2294
  key;
2109
2295
  maximumBytes;
2110
2296
  closed = false;
2297
+ inlineReads = 0;
2111
2298
  constructor(options) {
2112
2299
  if (!(options.key instanceof Uint8Array) || options.key.length !== 32) throw new Error("PUBLICATION_INVALID_KEY");
2113
2300
  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])))
2114
2301
  throw new Error("PUBLICATION_INVALID_IDENTITY");
2115
2302
  this.maximumBytes = options.maximumBytes ?? 10 * 1024 ** 3;
2116
2303
  if (!Number.isSafeInteger(this.maximumBytes) || this.maximumBytes < 1) throw new Error("PUBLICATION_INVALID_LIMIT");
2117
- this.directory = resolve2(options.directory);
2304
+ this.directory = resolve3(options.directory);
2118
2305
  this.key = Buffer.from(options.key);
2119
2306
  this.identity = Object.freeze({ tenantId: options.identity.tenantId, companionId: options.identity.companionId, seatId: options.identity.seatId });
2120
2307
  try {
2121
2308
  preparePrivateDirectory(this.directory);
2122
- const chunks = join2(this.directory, "chunks");
2309
+ const chunks = join3(this.directory, "chunks");
2123
2310
  preparePrivateDirectory(chunks);
2124
- const file = join2(this.directory, "catalog.sqlite");
2311
+ const file = join3(this.directory, "catalog.sqlite");
2125
2312
  preparePrivateDatabase(file);
2126
2313
  this.db = new DatabaseSync(file);
2127
2314
  this.db.exec(`PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
2128
2315
  CREATE TABLE IF NOT EXISTS identity (id INTEGER PRIMARY KEY CHECK(id=1), verifier BLOB NOT NULL);
2129
- CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0));`);
2316
+ CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0),ciphertext BLOB);`);
2130
2317
  this.db.exec("BEGIN IMMEDIATE");
2131
2318
  try {
2132
2319
  const row = this.db.prepare("SELECT verifier FROM identity WHERE id=1").get();
@@ -2137,6 +2324,13 @@ var PublicationObjects = class _PublicationObjects {
2137
2324
  throw new Error("PUBLICATION_KEY_OR_IDENTITY_MISMATCH");
2138
2325
  }
2139
2326
  } else this.db.prepare("INSERT INTO identity VALUES(1,?)").run(this.encrypt(Buffer.from("publication-object-key"), "identity"));
2327
+ if (!this.db.prepare("PRAGMA table_info(objects)").all().some((column) => column.name === "ciphertext"))
2328
+ this.db.exec("ALTER TABLE objects ADD COLUMN ciphertext BLOB");
2329
+ 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);
2330
+ INSERT OR IGNORE INTO object_usage SELECT 1,count(*),coalesce(sum(bytes+32),0) FROM objects;
2331
+ 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;
2332
+ 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;
2333
+ 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;`);
2140
2334
  this.db.exec("COMMIT");
2141
2335
  syncDir(this.directory);
2142
2336
  } catch (error) {
@@ -2176,54 +2370,135 @@ var PublicationObjects = class _PublicationObjects {
2176
2370
  }
2177
2371
  usage() {
2178
2372
  this.active();
2179
- return this.db.prepare("SELECT count(*) objects,COALESCE(sum(bytes+32),0) bytes FROM objects").get();
2373
+ return this.db.prepare("SELECT objects,bytes FROM object_usage WHERE id=1").get();
2180
2374
  }
2181
- async put(body) {
2182
- this.active();
2183
- assertPrivateDirectory2(this.directory);
2184
- assertPrivateDirectory2(join2(this.directory, "chunks"));
2185
- if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
2186
- throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
2187
- body = Buffer.from(body);
2188
- const ref = { sha256: sha(body), bytes: body.byteLength };
2375
+ reserve(refs2) {
2189
2376
  this.db.exec("BEGIN IMMEDIATE");
2190
2377
  try {
2191
- const row = this.db.prepare("SELECT bytes FROM objects WHERE hash=?").get(ref.sha256);
2192
- if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
2193
- if (!row) {
2194
- if (this.usage().bytes + ref.bytes + OVERHEAD > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
2195
- this.db.prepare("INSERT INTO objects VALUES(?,?)").run(ref.sha256, ref.bytes);
2378
+ let used = this.usage().bytes;
2379
+ const lookup = this.db.prepare("SELECT bytes FROM objects WHERE hash=?");
2380
+ const insert = this.db.prepare("INSERT INTO objects(hash,bytes) VALUES(?,?)");
2381
+ for (const ref of refs2) {
2382
+ const row = lookup.get(ref.sha256);
2383
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
2384
+ if (!row) {
2385
+ used += ref.bytes + OVERHEAD;
2386
+ if (used > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
2387
+ insert.run(ref.sha256, ref.bytes);
2388
+ }
2196
2389
  }
2197
2390
  this.db.exec("COMMIT");
2198
2391
  } catch (error) {
2199
2392
  this.db.exec("ROLLBACK");
2200
2393
  throw error;
2201
2394
  }
2202
- if (await this.has(ref)) return ref;
2395
+ }
2396
+ async put(body) {
2397
+ return this.putObject(body, false);
2398
+ }
2399
+ async putObject(body, deferDirectorySync) {
2400
+ this.active();
2401
+ assertPrivateDirectory2(this.directory);
2402
+ assertPrivateDirectory2(join3(this.directory, "chunks"));
2403
+ if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
2404
+ throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
2405
+ body = Buffer.from(body);
2406
+ const ref = { sha256: sha(body), bytes: body.byteLength };
2407
+ this.reserve([ref]);
2408
+ await this.writeObject(ref, Buffer.from(body), deferDirectorySync);
2409
+ return ref;
2410
+ }
2411
+ async writeObject(ref, body, deferDirectorySync) {
2412
+ if (await this.has(ref)) return;
2203
2413
  try {
2204
- exclusivePublish(join2(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256));
2414
+ await exclusivePublish(join3(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256), deferDirectorySync);
2205
2415
  } catch (error) {
2206
2416
  if (error.code !== "EEXIST") throw error;
2207
2417
  }
2208
2418
  await this.read(ref);
2209
- return ref;
2419
+ }
2420
+ /** Same immutable chunk format and row digests, with one durable reservation
2421
+ * and directory barrier for a bounded batch. All started writes settle even
2422
+ * when one fails, so callers can safely close or retry the store. */
2423
+ async putContents(bodies) {
2424
+ return this.putContentsWith(bodies, false);
2425
+ }
2426
+ async putContentsWith(bodies, deferDirectorySync) {
2427
+ this.active();
2428
+ assertPrivateDirectory2(this.directory);
2429
+ assertPrivateDirectory2(join3(this.directory, "chunks"));
2430
+ 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");
2431
+ const owned2 = bodies.map((body) => Buffer.from(body)), writes = /* @__PURE__ */ new Map();
2432
+ const files = owned2.map((body) => {
2433
+ const chunks = [];
2434
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
2435
+ const chunk = body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES), ref = { sha256: sha(chunk), bytes: chunk.length };
2436
+ chunks.push(ref);
2437
+ writes.set(ref.sha256, { ref, body: chunk });
2438
+ }
2439
+ return { sha256: sha(body), bytes: body.length, chunks };
2440
+ });
2441
+ const pending = [...writes.values()];
2442
+ if (!pending.length) return files;
2443
+ this.reserve(pending.map((item) => item.ref));
2444
+ const checked = await Promise.allSettled(pending.map(async (item) => ({ item, present: await this.has(item.ref) })));
2445
+ for (const result of checked) if (result.status === "rejected") throw result.reason;
2446
+ const missing = checked.flatMap((result) => result.status === "fulfilled" && !result.value.present ? [result.value.item] : []);
2447
+ const inline = missing.filter((item) => item.ref.bytes <= INLINE_BYTES), large = missing.filter((item) => item.ref.bytes > INLINE_BYTES);
2448
+ if (inline.length) {
2449
+ this.db.exec("BEGIN IMMEDIATE");
2450
+ try {
2451
+ const insert = this.db.prepare("UPDATE objects SET ciphertext=? WHERE hash=? AND ciphertext IS NULL");
2452
+ for (const item of inline) insert.run(this.encrypt(item.body, item.ref.sha256), item.ref.sha256);
2453
+ this.db.exec("COMMIT");
2454
+ } catch (error) {
2455
+ this.db.exec("ROLLBACK");
2456
+ throw error;
2457
+ }
2458
+ for (const item of inline) await this.read(item.ref);
2459
+ }
2460
+ try {
2461
+ for (let offset = 0; offset < large.length; offset += 8) {
2462
+ const results = await Promise.allSettled(large.slice(offset, offset + 8).map((item) => this.writeObject(item.ref, item.body, true)));
2463
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2464
+ }
2465
+ } finally {
2466
+ if (large.length && !deferDirectorySync) await syncDirAsync(join3(this.directory, "chunks"));
2467
+ }
2468
+ return files;
2210
2469
  }
2211
2470
  async read(ref) {
2212
2471
  this.active();
2213
2472
  validateObjectRef(ref);
2473
+ if (++this.inlineReads >= 32) {
2474
+ this.inlineReads = 0;
2475
+ await setImmediate();
2476
+ this.active();
2477
+ }
2214
2478
  assertPrivateDirectory2(this.directory);
2215
- assertPrivateDirectory2(join2(this.directory, "chunks"));
2216
- const path3 = join2(this.directory, "chunks", ref.sha256);
2217
- const fd = openSync2(path3, constants2.O_RDONLY | noFollow);
2479
+ assertPrivateDirectory2(join3(this.directory, "chunks"));
2480
+ const row = this.db.prepare("SELECT bytes,ciphertext FROM objects WHERE hash=?").get(ref.sha256);
2481
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
2482
+ if (row?.ciphertext !== void 0 && row.ciphertext !== null) {
2483
+ const cipher = Buffer.from(row.ciphertext);
2484
+ if (cipher.length !== ref.bytes + OVERHEAD) throw new Error("PUBLICATION_OBJECT_CORRUPT");
2485
+ const plain = this.decrypt(cipher, ref.sha256);
2486
+ if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
2487
+ return plain;
2488
+ }
2489
+ const path3 = join3(this.directory, "chunks", ref.sha256);
2490
+ const file = await open2(path3, constants3.O_RDONLY | noFollow);
2218
2491
  try {
2219
- const info = fstatSync2(fd);
2492
+ const info = await file.stat();
2220
2493
  if (!info.isFile() || info.size !== ref.bytes + OVERHEAD || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
2221
2494
  throw new Error("PUBLICATION_OBJECT_CORRUPT");
2222
- const plain = this.decrypt(readFileSync2(fd), ref.sha256);
2495
+ const cipher = await file.readFile();
2496
+ this.active();
2497
+ const plain = this.decrypt(cipher, ref.sha256);
2223
2498
  if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
2224
2499
  return plain;
2225
2500
  } finally {
2226
- closeSync2(fd);
2501
+ await file.close();
2227
2502
  }
2228
2503
  }
2229
2504
  async has(ref) {
@@ -2238,7 +2513,10 @@ var PublicationObjects = class _PublicationObjects {
2238
2513
  async putContent(body) {
2239
2514
  body = Buffer.from(body);
2240
2515
  const chunks = [];
2241
- for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
2516
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
2517
+ chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
2518
+ if (chunks.length % 32 === 0) await setImmediate();
2519
+ }
2242
2520
  return { bytes: body.length, sha256: sha(body), chunks };
2243
2521
  }
2244
2522
  async readContent(file, maximumBytes) {
@@ -2251,21 +2529,85 @@ var PublicationObjects = class _PublicationObjects {
2251
2529
  return body;
2252
2530
  }
2253
2531
  async captureFile(source) {
2532
+ return this.captureFileWith(source, (body) => this.put(body));
2533
+ }
2534
+ /** Every file is flushed before linking. One directory barrier makes the
2535
+ * whole batch durable before any references are returned to its caller.
2536
+ * Other puts on this handle retain their own immediate directory barrier. */
2537
+ async captureFiles(sources, onProgress, options = {}) {
2538
+ this.active();
2539
+ const chunkConcurrency = options.chunkConcurrency ?? 1;
2540
+ if (!Number.isSafeInteger(chunkConcurrency) || chunkConcurrency < 1 || chunkConcurrency > 8) throw new Error("PUBLICATION_BATCH_TOO_LARGE");
2541
+ const files = [];
2542
+ let completedBytes = 0, completedFiles = 0, wroteFiles = false;
2543
+ let pending = [];
2544
+ const put = (body) => new Promise((resolve30, reject) => {
2545
+ if (body.length > INLINE_BYTES) wroteFiles = true;
2546
+ pending.push({ body: Buffer.from(body), resolve: resolve30, reject });
2547
+ if (pending.length !== 1) return;
2548
+ queueMicrotask(() => {
2549
+ const batch = pending;
2550
+ pending = [];
2551
+ void (async () => {
2552
+ for (let offset = 0; offset < batch.length; ) {
2553
+ let end = offset, bytes = 0;
2554
+ while (end < batch.length && bytes + batch[end].body.length <= 8 * 1024 * 1024) bytes += batch[end++].body.length;
2555
+ const contents = await this.putContentsWith(batch.slice(offset, end).map((item) => item.body), true);
2556
+ for (let i = offset; i < end; i++) batch[i].resolve(contents[i - offset].chunks[0]);
2557
+ offset = end;
2558
+ }
2559
+ })().catch((error) => {
2560
+ for (const item of batch) item.reject(error);
2561
+ });
2562
+ });
2563
+ });
2564
+ try {
2565
+ for (let offset = 0; offset < sources.length; offset += 32) {
2566
+ const results = await Promise.allSettled(sources.slice(offset, offset + 32).map(async (source) => {
2567
+ let previousBytes = 0;
2568
+ const file = await this.captureFileWith(source, put, (bytes) => {
2569
+ completedBytes += bytes - previousBytes;
2570
+ previousBytes = bytes;
2571
+ onProgress?.({ completedFiles, completedBytes });
2572
+ }, chunkConcurrency);
2573
+ completedFiles++;
2574
+ if (completedFiles < sources.length) onProgress?.({ completedFiles, completedBytes });
2575
+ return file;
2576
+ }));
2577
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2578
+ for (const result of results) if (result.status === "fulfilled") files.push(result.value);
2579
+ }
2580
+ } finally {
2581
+ if (wroteFiles) await syncDirAsync(join3(this.directory, "chunks"));
2582
+ }
2583
+ onProgress?.({ completedFiles: files.length, completedBytes });
2584
+ return files;
2585
+ }
2586
+ async captureFileWith(source, put, onBytes, chunkConcurrency = 1) {
2254
2587
  this.active();
2255
- if (lstatSync2(source).isSymbolicLink() || realpathSync(dirname2(source)) !== resolve2(dirname2(source))) throw new Error("SYMLINK_REFUSED");
2256
- const fd = openSync2(source, constants2.O_RDONLY | noFollow);
2588
+ if (lstatSync2(source).isSymbolicLink() || realpathSync(dirname2(source)) !== resolve3(dirname2(source))) throw new Error("SYMLINK_REFUSED");
2589
+ const fd = openSync2(source, constants3.O_RDONLY | noFollow);
2257
2590
  try {
2258
2591
  const before = fstatSync2(fd, { bigint: true });
2259
2592
  if (!before.isFile()) throw new Error("PUBLICATION_NOT_REGULAR_FILE");
2260
- const chunks = [], digest7 = createHash("sha256"), buffer = Buffer.alloc(PUBLICATION_CHUNK_BYTES);
2593
+ const chunks = [], digest7 = createHash("sha256"), buffer = Buffer.alloc(Math.min(PUBLICATION_CHUNK_BYTES, Number(before.size) || 1));
2261
2594
  let bytes = 0;
2262
2595
  for (; ; ) {
2263
- const count = readSync(fd, buffer, 0, buffer.length, null);
2264
- if (!count) break;
2265
- const chunk = buffer.subarray(0, count);
2266
- digest7.update(chunk);
2267
- bytes += count;
2268
- chunks.push(await this.put(chunk));
2596
+ const batch = [];
2597
+ for (let i = 0; i < chunkConcurrency; i++) {
2598
+ const count = readSync(fd, buffer, 0, buffer.length, null);
2599
+ if (!count) break;
2600
+ const chunk = Buffer.from(buffer.subarray(0, count));
2601
+ digest7.update(chunk);
2602
+ bytes += count;
2603
+ batch.push(chunk);
2604
+ }
2605
+ if (!batch.length) break;
2606
+ const results = await Promise.allSettled(batch.map(put));
2607
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2608
+ for (const result of results) if (result.status === "fulfilled") chunks.push(result.value);
2609
+ onBytes?.(bytes);
2610
+ if (chunks.length % 32 === 0) await setImmediate();
2269
2611
  }
2270
2612
  const after = fstatSync2(fd, { bigint: true }), path3 = lstatSync2(source, { bigint: true });
2271
2613
  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");
@@ -2275,36 +2617,57 @@ var PublicationObjects = class _PublicationObjects {
2275
2617
  }
2276
2618
  }
2277
2619
  async restoreFile(file, destination) {
2620
+ return this.restoreFileWith(file, destination, false);
2621
+ }
2622
+ /** Private restore batches flush each file before linking it, then publish
2623
+ * the directory entries together. All started writers settle on failure. */
2624
+ async restoreFiles(files) {
2625
+ this.active();
2626
+ for (let offset = 0; offset < files.length; offset += 32) {
2627
+ const batch = files.slice(offset, offset + 32);
2628
+ const results = await Promise.allSettled(batch.map((file) => this.restoreFileWith(file.content, file.destination, true, file.mode)));
2629
+ const directories = [...new Set(batch.map((file) => dirname2(file.destination)))];
2630
+ for (let i = 0; i < directories.length; i += 8) {
2631
+ const synced = await Promise.allSettled(directories.slice(i, i + 8).map(syncDirAsync));
2632
+ for (const result of synced) if (result.status === "rejected") throw result.reason;
2633
+ }
2634
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2635
+ }
2636
+ }
2637
+ async restoreFileWith(file, destination, deferDirectorySync, mode = 384) {
2278
2638
  this.active();
2279
2639
  validateFileContent(file);
2280
- if (realpathSync(dirname2(destination)) !== resolve2(dirname2(destination))) throw new Error("SYMLINK_REFUSED");
2640
+ if (mode !== 384 && mode !== 448) throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
2641
+ file = { ...file, chunks: file.chunks.map((ref) => ({ ...ref })) };
2642
+ if (realpathSync(dirname2(destination)) !== resolve3(dirname2(destination))) throw new Error("SYMLINK_REFUSED");
2281
2643
  try {
2282
2644
  lstatSync2(destination);
2283
2645
  throw new Error("CONTINUITY_DESTINATION_EXISTS");
2284
2646
  } catch (error) {
2285
2647
  if (error.code !== "ENOENT") throw error;
2286
2648
  }
2287
- const temp = join2(dirname2(destination), "." + randomUUID2() + ".partial"), digest7 = createHash("sha256");
2288
- const fd = openSync2(temp, "wx", 384);
2649
+ const temp = join3(dirname2(destination), "." + randomUUID2() + ".partial"), digest7 = createHash("sha256");
2650
+ const fd = await open2(temp, "wx", 384);
2289
2651
  try {
2290
2652
  for (const ref of file.chunks) {
2291
2653
  const body = await this.read(ref);
2292
2654
  digest7.update(body);
2293
2655
  let offset = 0;
2294
- while (offset < body.length) offset += writeSync(fd, body, offset, body.length - offset);
2656
+ while (offset < body.length) offset += (await fd.write(body, offset, body.length - offset)).bytesWritten;
2295
2657
  }
2296
2658
  if (digest7.digest("hex") !== file.sha256) throw new Error("PUBLICATION_FILE_CORRUPT");
2297
- fsyncSync2(fd);
2659
+ if (mode !== 384) await fd.chmod(mode);
2660
+ await fd.sync();
2298
2661
  try {
2299
- linkSync(temp, destination);
2662
+ await link(temp, destination);
2300
2663
  } catch (error) {
2301
2664
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
2302
2665
  throw error;
2303
2666
  }
2304
- syncDir(dirname2(destination));
2667
+ if (!deferDirectorySync) await syncDirAsync(dirname2(destination));
2305
2668
  } finally {
2306
- closeSync2(fd);
2307
- unlinkSync(temp);
2669
+ await fd.close();
2670
+ await unlink(temp);
2308
2671
  }
2309
2672
  }
2310
2673
  close() {
@@ -2317,7 +2680,7 @@ var PublicationObjects = class _PublicationObjects {
2317
2680
  };
2318
2681
 
2319
2682
  // src/continuity/publication.ts
2320
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
2683
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
2321
2684
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
2322
2685
  var ZERO = "0".repeat(64);
2323
2686
  var HASH2 = /^[a-f0-9]{64}$/;
@@ -2358,8 +2721,12 @@ function normalizePublicationProfile(value2) {
2358
2721
  return Object.freeze(profile);
2359
2722
  }
2360
2723
  function validatePublicationPath(path3) {
2361
- 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)))
2724
+ if (typeof path3 !== "string" || path3.normalize("NFC") !== path3) throw new Error("PUBLICATION_INVALID_PATH");
2725
+ try {
2726
+ validateRelativePath(path3);
2727
+ } catch {
2362
2728
  throw new Error("PUBLICATION_INVALID_PATH");
2729
+ }
2363
2730
  }
2364
2731
  function normalizePublication(value2) {
2365
2732
  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");
@@ -2464,9 +2831,9 @@ var PublicationReplica = class _PublicationReplica {
2464
2831
  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)
2465
2832
  throw new Error("PUBLICATION_PROFILE_MISMATCH");
2466
2833
  }
2467
- const directory2 = resolve3(options.directory);
2834
+ const directory2 = resolve4(options.directory);
2468
2835
  preparePrivateDirectory(directory2);
2469
- const path3 = join3(directory2, "publications.sqlite");
2836
+ const path3 = join4(directory2, "publications.sqlite");
2470
2837
  preparePrivateDatabase(path3);
2471
2838
  this.journalFile = path3;
2472
2839
  const journalStat = lstatSync3(path3, { bigint: true });
@@ -2655,9 +3022,11 @@ var PublicationReplica = class _PublicationReplica {
2655
3022
  throw error;
2656
3023
  }
2657
3024
  }
2658
- async status() {
3025
+ // Paired control reads use the durable published cut. Original bytes are
3026
+ // verified when published and restored, rather than on every status poll.
3027
+ async status(verifyFiles = true) {
2659
3028
  const c = this.control(), manifest = c.head ? await this.manifest(c.head) : null;
2660
- const dataReady = manifest ? (await this.missing(manifest)).length === 0 : false;
3029
+ const dataReady = manifest ? (verifyFiles ? await this.missing(manifest) : this.databaseMissing(manifest)).length === 0 : false;
2661
3030
  const { applied } = await this.replicationStatus();
2662
3031
  const current2 = this.control();
2663
3032
  const stillReady = dataReady && manifest !== null && current2.head === c.head && current2.digest === c.digest && manifest.deletionWatermark >= current2.floor && this.databaseMissing(manifest).length === 0;
@@ -2702,13 +3071,13 @@ var PublicationReplica = class _PublicationReplica {
2702
3071
 
2703
3072
  // src/continuity/recovery-archive.ts
2704
3073
  import { DatabaseSync as DatabaseSync4, backup } from "node:sqlite";
2705
- import { existsSync as existsSync2, lstatSync as lstatSync5, mkdtempSync, rmSync, writeFileSync as writeFileSync3, chmodSync } from "node:fs";
2706
- import { join as join4, resolve as resolve4 } from "node:path";
3074
+ import { existsSync as existsSync2, lstatSync as lstatSync5, mkdtempSync, rmSync, writeFileSync as writeFileSync2, chmodSync } from "node:fs";
3075
+ import { join as join5, resolve as resolve5 } from "node:path";
2707
3076
  init_sqlite_replication();
2708
3077
 
2709
3078
  // src/continuity/key-service-store.ts
2710
3079
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
2711
- import { constants as constants4, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync3, closeSync as closeSync3, readFileSync as readFileSync3, writeSync as writeSync2, fstatSync as fstatSync3, fsyncSync as fsyncSync3, unlinkSync as unlinkSync2 } from "node:fs";
3080
+ import { constants as constants5, lstatSync as lstatSync4, mkdirSync as mkdirSync3, openSync as openSync3, closeSync as closeSync3, readFileSync as readFileSync2, writeSync, fstatSync as fstatSync3, fsyncSync as fsyncSync3, unlinkSync } from "node:fs";
2712
3081
  function validateKeyIdentity(value2) {
2713
3082
  if (!value2 || ["tenantId", "companionId", "seatId", "keyId"].some((k) => typeof value2[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2[k])) || !Number.isSafeInteger(value2.generation) || value2.generation < 1) throw new Error("KEY_SERVICE_INVALID_IDENTITY");
2714
3083
  }
@@ -2718,25 +3087,25 @@ function assertPrivateStat(stat, directory2) {
2718
3087
  }
2719
3088
  function readPrivateFile2(path3, maximumBytes = 65536) {
2720
3089
  assertPrivateStat(lstatSync4(path3), false);
2721
- const fd = openSync3(path3, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
3090
+ const fd = openSync3(path3, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0));
2722
3091
  try {
2723
3092
  const stat = fstatSync3(fd);
2724
3093
  assertPrivateStat(stat, false);
2725
3094
  if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
2726
- return readFileSync3(fd);
3095
+ return readFileSync2(fd);
2727
3096
  } finally {
2728
3097
  closeSync3(fd);
2729
3098
  }
2730
3099
  }
2731
3100
 
2732
3101
  // src/continuity/crypto.ts
2733
- import { constants as constants5, createWriteStream, openSync as openSync4 } from "node:fs";
2734
- import { open, lstat, link, unlink, writeFile, appendFile } from "node:fs/promises";
3102
+ import { constants as constants6, createWriteStream, openSync as openSync4 } from "node:fs";
3103
+ import { open as open3, lstat as lstat2, link as link2, unlink as unlink2, writeFile as writeFile2, appendFile } from "node:fs/promises";
2735
3104
  var MAGIC2 = Buffer.from("E7OBJ001");
2736
3105
  var HEADER_SIZE = MAGIC2.length + 12;
2737
3106
  async function syncDirectory(directory2) {
2738
3107
  if (process.platform === "win32") return;
2739
- const handle = await open(directory2, constants5.O_RDONLY);
3108
+ const handle = await open3(directory2, constants6.O_RDONLY);
2740
3109
  try {
2741
3110
  await handle.sync();
2742
3111
  } finally {
@@ -2781,7 +3150,8 @@ async function currentHDeletionCheckAsync(raw, control2, captured) {
2781
3150
  var schema = "CREATE TABLE archives(id TEXT PRIMARY KEY,kind TEXT NOT NULL,manifest_digest TEXT NOT NULL,content TEXT NOT NULL)";
2782
3151
  var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
2783
3152
  var FORMAT = "engine7-runtime-recovery-archive-v1";
2784
- var MAX_METADATA = 16 * 1024 * 1024;
3153
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
3154
+ var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
2785
3155
  var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
2786
3156
  var incarnation = (file) => {
2787
3157
  const s = lstatSync5(file, { bigint: true });
@@ -2825,14 +3195,17 @@ async function checkRecoveryDeletionAsync(manifest, current2, previous = 0) {
2825
3195
  const floor = await current2();
2826
3196
  return checkRecoveryDeletion(manifest, () => floor, previous);
2827
3197
  }
2828
- function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2) {
3198
+ function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2, scan = true) {
2829
3199
  const d = manifest.databases.find((d2) => d2.databaseId === databaseId), p = manifest.profile;
2830
3200
  const control2 = db.prepare("SELECT binding,head,digest,schema_hash FROM e7_replication_control WHERE role=?").get(role);
2831
3201
  const binding = JSON.stringify([p.identity.tenantId, p.identity.companionId, p.identity.seatId, databaseId, p.baselineId, p.epoch]);
2832
3202
  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");
2833
3203
  const actual = sqliteReplicationSchemaHash(db);
2834
- const checks = db.prepare("PRAGMA quick_check").all();
2835
- if (actual !== control2.schema_hash || checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
3204
+ if (actual !== control2.schema_hash) throw new Error("RECOVERY_DATABASE_CORRUPT");
3205
+ if (scan) {
3206
+ const checks = db.prepare("PRAGMA quick_check").all();
3207
+ if (checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
3208
+ }
2836
3209
  return actual;
2837
3210
  }
2838
3211
  var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
@@ -2844,10 +3217,10 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
2844
3217
  identity;
2845
3218
  closed = false;
2846
3219
  constructor(options) {
2847
- this.directory = resolve4(options.directory);
3220
+ this.directory = resolve5(options.directory);
2848
3221
  this.objects = options.objects;
2849
- this.file = join4(this.directory, "archives.sqlite");
2850
- this.marker = join4(this.directory, "archive.json");
3222
+ this.file = join5(this.directory, "archives.sqlite");
3223
+ this.marker = join5(this.directory, "archive.json");
2851
3224
  if (options.initialize) preparePrivateDirectory(this.directory);
2852
3225
  else {
2853
3226
  try {
@@ -2865,7 +3238,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
2865
3238
  this.db.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
2866
3239
  if (fresh) {
2867
3240
  this.db.exec(schema);
2868
- writeFileSync3(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
3241
+ writeFileSync2(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
2869
3242
  }
2870
3243
  if (!same(this.db.prepare("SELECT sql FROM sqlite_master WHERE type='table'").all().map((r) => String(r.sql)), [schema]) || this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("RECOVERY_ARCHIVE_REQUIRED");
2871
3244
  this.identity = incarnation(this.file);
@@ -2974,38 +3347,50 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
2974
3347
  if (old) {
2975
3348
  if (old.kind !== kind || old.manifest_digest !== digest7) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
2976
3349
  const entry = await this.read(id2);
2977
- for (const d of entry.databases) await verifyContent(this.objects, d.content);
2978
- for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
3350
+ if (options.verifyRetained !== false) {
3351
+ for (const d of entry.databases) await verifyContent(this.objects, d.content);
3352
+ for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
3353
+ }
2979
3354
  await verify3();
2980
3355
  return entry.receipt;
2981
3356
  }
2982
3357
  let publication;
2983
3358
  if (kind !== "LOCAL") {
2984
- const status = await options.receiver?.status();
3359
+ const status = await options.receiver?.status(options.verifyRetained !== false);
2985
3360
  if (!status || !currentHCheck && !status.dataReady || status.published?.digest !== digest7 || !same(status.profile, manifest.profile)) throw new Error("RECOVERY_COMMON_NOT_READY");
2986
3361
  publication = status.published;
2987
3362
  }
2988
3363
  if (!same(Object.keys(options.databases).sort(), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
2989
3364
  const role = kind === "LOCAL" ? "source" : "replica";
2990
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
2991
- const temporary = mkdtempSync(join4(this.directory, ".capture-"));
3365
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
3366
+ 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(digest7) : void 0;
3367
+ const retained = sibling ? await this.read(String(sibling.id)) : void 0;
3368
+ if (retained) {
3369
+ validateRecoveryArchiveEntry(retained, this.objects.identity);
3370
+ if (!same(retained.manifest, manifest) || !same(retained.publication, publication) || retained.databases.some((d) => d.role !== "replica")) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
3371
+ }
3372
+ const temporary = mkdtempSync(join5(this.directory, ".capture-"));
2992
3373
  try {
2993
- writeFileSync3(join4(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
3374
+ writeFileSync2(join5(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
2994
3375
  const databases = [];
2995
- for (let offset = 0; offset < manifest.databases.length; offset += 6) {
3376
+ if (retained) {
3377
+ if (options.verifyRetained !== false) for (const database of retained.databases) await verifyContent(this.objects, database.content);
3378
+ databases.push(...retained.databases);
3379
+ }
3380
+ for (let offset = 0; !retained && offset < manifest.databases.length; offset += 6) {
2996
3381
  const results = await Promise.allSettled(manifest.databases.slice(offset, offset + 6).map(async (d) => {
2997
3382
  floor = Math.max(floor, await verify3());
2998
- const file = join4(temporary, d.databaseId + ".sqlite");
3383
+ const file = join5(temporary, d.databaseId + ".sqlite");
2999
3384
  await backup(options.databases[d.databaseId], file);
3000
3385
  chmodSync(file, 384);
3001
3386
  const copy = new DatabaseSync4(file, { readOnly: true });
3002
3387
  let schemaHash2;
3003
3388
  try {
3004
- schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role);
3389
+ schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role, void 0, false);
3005
3390
  } finally {
3006
3391
  copy.close();
3007
3392
  }
3008
- const content = await this.objects.captureFile(file);
3393
+ const [content] = await this.objects.captureFiles([file], void 0, { chunkConcurrency: 8 });
3009
3394
  return { databaseId: d.databaseId, role, schemaHash: schemaHash2, content };
3010
3395
  }));
3011
3396
  for (const result of results) {
@@ -3014,7 +3399,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3014
3399
  }
3015
3400
  }
3016
3401
  for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
3017
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
3402
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
3018
3403
  if (kind !== "LOCAL") {
3019
3404
  const status = await options.receiver.status();
3020
3405
  if (!currentHCheck && !status.dataReady || status.published?.digest !== digest7) throw new Error("RECOVERY_COMMON_NOT_READY");
@@ -3044,19 +3429,18 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3044
3429
  if (currentHCheck) await verify3();
3045
3430
  }
3046
3431
  }
3047
- /** The caller has fetched only refs from this authenticated original seal.
3048
- * No receipt is installed until every chunk and real SQLite snapshot passes. */
3049
- async import(entry, deletionWatermark) {
3432
+ /** Paired transfer verifies original bytes here and opens the native stores
3433
+ * once at seed. Offline imports can also validate the full SQLite snapshots. */
3434
+ async import(entry, deletionWatermark, verifyDatabases = true) {
3050
3435
  this.active();
3051
3436
  const { value: value2, body, receipt: receipt2 } = validateRecoveryArchiveEntry(entry, this.objects.identity);
3052
- let floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark);
3437
+ const floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark);
3053
3438
  const prior = this.db.prepare("SELECT kind,manifest_digest,content FROM archives WHERE id=?").get(value2.id);
3054
3439
  if (prior && (prior.kind !== value2.kind || prior.manifest_digest !== receipt2.manifestDigest || JSON.parse(String(prior.content)).sha256 !== receipt2.digest)) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
3055
- const temporary = mkdtempSync(join4(this.directory, ".import-"));
3440
+ const temporary = verifyDatabases ? mkdtempSync(join5(this.directory, ".import-")) : void 0;
3056
3441
  try {
3057
- for (const db of value2.databases) {
3058
- floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
3059
- const file = join4(temporary, db.databaseId + ".sqlite");
3442
+ if (temporary) for (const db of value2.databases) {
3443
+ const file = join5(temporary, db.databaseId + ".sqlite");
3060
3444
  await this.objects.restoreFile(db.content, file);
3061
3445
  const probe = new DatabaseSync4(file, { readOnly: true });
3062
3446
  try {
@@ -3065,17 +3449,10 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3065
3449
  probe.close();
3066
3450
  }
3067
3451
  }
3068
- const files = value2.manifest.trees.flatMap((tree) => tree.files);
3069
- for (let offset = 0; offset < files.length; offset += 8) {
3070
- const results = await Promise.allSettled(files.slice(offset, offset + 8).map(async (file) => {
3071
- const current2 = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
3072
- await verifyContent(this.objects, file.content);
3073
- return current2;
3074
- }));
3075
- for (const result of results) {
3076
- if (result.status === "rejected") throw result.reason;
3077
- floor = Math.max(floor, result.value);
3078
- }
3452
+ const contents = [...temporary ? [] : value2.databases.map((db) => db.content), ...value2.manifest.trees.flatMap((tree) => tree.files.map((file) => file.content))];
3453
+ for (let offset = 0; offset < contents.length; offset += 8) {
3454
+ const results = await Promise.allSettled(contents.slice(offset, offset + 8).map((content) => verifyContent(this.objects, content)));
3455
+ for (const result of results) if (result.status === "rejected") throw result.reason;
3079
3456
  }
3080
3457
  const ref = await this.objects.putContent(body);
3081
3458
  await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
@@ -3092,7 +3469,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3092
3469
  }
3093
3470
  return (await this.read(value2.id)).receipt;
3094
3471
  } finally {
3095
- rmSync(temporary, { recursive: true, force: true });
3472
+ if (temporary) rmSync(temporary, { recursive: true, force: true });
3096
3473
  await syncDirectory(this.directory);
3097
3474
  }
3098
3475
  }
@@ -3110,13 +3487,13 @@ async function verifyContent(objects, content) {
3110
3487
  }
3111
3488
 
3112
3489
  // src/continuity/sqlite-store-location.ts
3113
- import { basename as basename3, dirname as dirname5, resolve as resolve6 } from "node:path";
3490
+ import { basename as basename3, dirname as dirname5, resolve as resolve7 } from "node:path";
3114
3491
 
3115
3492
  // src/continuity/mem7-replication.ts
3116
- import { closeSync as closeSync4, fsyncSync as fsyncSync4, lstatSync as lstatSync6, openSync as openSync5, writeFileSync as writeFileSync4 } from "node:fs";
3117
- import { dirname as dirname3, join as join5 } from "node:path";
3493
+ import { closeSync as closeSync4, fsyncSync as fsyncSync4, lstatSync as lstatSync6, openSync as openSync5, writeFileSync as writeFileSync3 } from "node:fs";
3494
+ import { dirname as dirname3, join as join6 } from "node:path";
3118
3495
  init_sqlite_replication();
3119
- var location = (stateDir) => join5(stateDir, ".continuity", "mem7-replication.json");
3496
+ var location = (stateDir) => join6(stateDir, ".continuity", "mem7-replication.json");
3120
3497
  function normalize(value2) {
3121
3498
  if (!value2 || !/^[a-f0-9]{64}$/.test(value2.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
3122
3499
  return Object.freeze({ binding: normalizeBinding(value2.binding), schemaHash: value2.schemaHash });
@@ -3148,7 +3525,7 @@ function ensureMem7ReplicationRegistration(stateDir, input) {
3148
3525
  const file = location(stateDir);
3149
3526
  preparePrivateDirectory(dirname3(file));
3150
3527
  try {
3151
- writeFileSync4(file, JSON.stringify(registration), { mode: 384, flag: "wx", flush: true });
3528
+ writeFileSync3(file, JSON.stringify(registration), { mode: 384, flag: "wx", flush: true });
3152
3529
  } catch (error) {
3153
3530
  if (error.code !== "EEXIST") throw error;
3154
3531
  if (JSON.stringify(readMem7ReplicationRegistration(stateDir)) !== JSON.stringify(registration)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
@@ -3166,7 +3543,7 @@ function ensureMem7ReplicationRegistration(stateDir, input) {
3166
3543
  // src/continuity/sqlite-store-location.ts
3167
3544
  init_runtime_replication();
3168
3545
  function sqliteStoreLocation(file) {
3169
- const absolute = resolve6(file), parent = dirname5(absolute), name = basename3(absolute);
3546
+ const absolute = resolve7(file), parent = dirname5(absolute), name = basename3(absolute);
3170
3547
  if (name === "mem7.db" && basename3(parent) === "index" && basename3(dirname5(parent)) === "mem7")
3171
3548
  return { stateDir: dirname5(dirname5(parent)), component: "mem7" };
3172
3549
  let stateDir, component;
@@ -3259,207 +3636,116 @@ CREATE TABLE IF NOT EXISTS e7_recovery_sources(
3259
3636
  CREATE TABLE IF NOT EXISTS e7_recovery_mappings(
3260
3637
  branch_digest TEXT NOT NULL,scope_id TEXT NOT NULL,kind TEXT NOT NULL,original_id TEXT NOT NULL,
3261
3638
  original_value TEXT NOT NULL,current_value TEXT NOT NULL,
3262
- PRIMARY KEY(branch_digest,scope_id,kind,original_id));
3263
- CREATE TABLE IF NOT EXISTS e7_recovery_resolutions(
3264
- resolution_id TEXT PRIMARY KEY,digest TEXT NOT NULL);`;
3265
- function initializeRecoveryAdmission(db) {
3266
- if (db.isTransaction || db.prepare("SELECT 1 FROM sqlite_master WHERE name='e7_replication_control'").get() && db.prepare("SELECT 1 FROM e7_replication_control LIMIT 1").get()) throw new Error("RECOVERY_NEW_BASELINE_REQUIRED");
3267
- db.exec(RECOVERY_ADMISSION_SCHEMA);
3268
- }
3269
-
3270
- // src/continuity/generation-integrity.ts
3271
- import { createHash as createHash5 } from "node:crypto";
3272
- import { constants as constants7, closeSync as closeSync6, fstatSync as fstatSync5, lstatSync as lstatSync8, openSync as openSync7, readSync as readSync2, readdirSync, realpathSync as realpathSync3 } from "node:fs";
3273
- import { join as join7, resolve as resolve7 } from "node:path";
3274
- function runtimeGenerationIntegrity(directory2) {
3275
- const root = resolve7(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
3276
- if (realpathSync3(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3277
- const visit = (path3) => {
3278
- if (path3 === ".runtime-publication-receipt.json") return;
3279
- const file = join7(root, path3), before = lstatSync8(file, { bigint: true });
3280
- if (before.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3281
- if (before.isDirectory()) {
3282
- for (const name of readdirSync(file).sort()) visit(path3 ? path3 + "/" + name : name);
3283
- return;
3284
- }
3285
- if (!before.isFile() || before.size > BigInt(Number.MAX_SAFE_INTEGER) || result.length >= 1e5) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3286
- const fd = openSync7(file, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0)), hash11 = createHash5("sha256");
3287
- let bytes = 0;
3288
- try {
3289
- while (true) {
3290
- const size = readSync2(fd, buffer);
3291
- if (!size) break;
3292
- hash11.update(buffer.subarray(0, size));
3293
- bytes += size;
3294
- }
3295
- const after = fstatSync5(fd, { bigint: true });
3296
- 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");
3297
- result.push({ path: path3, bytes, mode: Number(before.mode & 0o777n), sha256: hash11.digest("hex") });
3298
- } finally {
3299
- closeSync6(fd);
3300
- }
3301
- };
3302
- visit("");
3303
- return result.sort((a, b) => a.path.localeCompare(b.path, "en"));
3304
- }
3305
- function verifyRuntimeGenerationIntegrity(directory2, expected) {
3306
- if (!Array.isArray(expected) || JSON.stringify(runtimeGenerationIntegrity(directory2)) !== JSON.stringify(expected)) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3307
- }
3308
-
3309
- // src/continuity/inventory.ts
3310
- import { constants as constants8 } from "node:fs";
3311
- import { lstat as lstat2, open as open2, readdir, realpath } from "node:fs/promises";
3312
- import { isAbsolute, join as join8, relative, resolve as resolve8, sep } from "node:path";
3313
- 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(" "));
3314
- var STATE_EXCLUDED = {
3315
- ".continuity": "local runtime control; never business state",
3316
- ".engine.pid": "local process identity",
3317
- ".bg-worker.pid": "local process identity",
3318
- ".travel-restored.json": "deployment activation gate; recreated on restore",
3319
- ".travel-enrolled.json": "local runtime enrollment; recreated per node",
3320
- ".travel-active.json": "local activation receipt; recreated per generation",
3321
- ".git": "source control metadata",
3322
- ".gitignore": "source control metadata",
3323
- ".log-baseline.txt": "local diagnostics",
3324
- logs: "local diagnostics; not authoritative history",
3325
- diagnostics: "local diagnostics",
3326
- backups: "historical recovery copies; not active state",
3327
- "package.json": "installed application metadata",
3328
- "start.sh": "local launcher; deployment must be reviewed separately",
3329
- node_modules: "installed dependencies",
3330
- install: "installed application",
3331
- CogniFold: "installed optional runtime",
3332
- "everos-venv": "installed Python runtime",
3333
- "ollama-models": "installed model weights"
3334
- };
3335
- var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
3336
- var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
3337
- function stateReason(name, options) {
3338
- if (options.includeStateEntries?.includes(name)) return void 0;
3339
- return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
3340
- }
3341
- function knownState(name) {
3342
- return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
3343
- }
3344
- async function classifyState(options) {
3345
- const result = { included: [], excluded: [], unclassified: [] };
3346
- for (const name of (await readdir(options.stateDir)).sort()) {
3347
- const reason = stateReason(name, options);
3348
- if (reason) result.excluded.push({ path: name, reason });
3349
- else if (knownState(name) || options.includeStateEntries?.includes(name) || resolve8(options.stateDir, name) === resolve8(options.workspace ?? join8(options.stateDir, "workspace"))) result.included.push(name);
3350
- else result.unclassified.push(name);
3351
- }
3352
- return result;
3353
- }
3354
- function validateRelativePath(path3) {
3355
- if (typeof path3 !== "string" || !path3 || path3.length > 2048 || path3.includes("\\") || isAbsolute(path3)) throw new Error("INVALID_ARTIFACT_PATH");
3356
- for (const part of path3.split("/")) {
3357
- 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)
3358
- throw new Error("INVALID_ARTIFACT_PATH");
3359
- }
3360
- }
3361
- function isWithin(root, candidate) {
3362
- const rel = relative(resolve8(root), resolve8(candidate));
3363
- return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
3364
- }
3365
- async function collectInventory(options) {
3366
- const state2 = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join8(state2, "workspace"));
3367
- if (state2 === workspace || isWithin(workspace, state2)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
3368
- const roots = { state: state2, workspace }, entries = [], exclusions = [], aliases = /* @__PURE__ */ new Set();
3369
- const include = new Set(options.includeStateEntries ?? []);
3370
- for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
3371
- validateRelativePath(name);
3372
- if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
3373
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
3374
- }
3375
- for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
3376
- for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
3377
- validateRelativePath(name);
3378
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
3379
- if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
3380
- }
3381
- const classification = await classifyState(options);
3382
- if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
3383
- async function walk(root, directory2, prefix2 = "") {
3384
- for (const name of (await readdir(directory2)).sort()) {
3385
- const path3 = prefix2 ? prefix2 + "/" + name : name, source = join8(directory2, name);
3386
- if (root === "state" && source === workspace) continue;
3387
- let reason = NESTED_EXCLUDED[name];
3388
- if (root === "state" && prefix2) reason = options.excludeStateEntries?.[path3] ?? reason;
3389
- if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path3] ?? reason;
3390
- if (!prefix2 && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
3391
- if (root === "state" && !prefix2) {
3392
- reason = stateReason(name, options);
3393
- if (!reason && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
3394
- }
3395
- if (reason) {
3396
- exclusions.push({ root, path: path3, reason });
3397
- continue;
3398
- }
3399
- validateRelativePath(path3);
3400
- const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
3401
- if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
3402
- aliases.add(key2);
3403
- const info = await lstat2(source, { bigint: true });
3404
- if (info.isSymbolicLink()) throw new Error(`SYMLINK_REFUSED: ${root}/${path3}`);
3405
- if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
3406
- if (info.isDirectory()) {
3407
- try {
3408
- const marker = await lstat2(join8(source, "pyvenv.cfg"));
3409
- if (marker.isFile() && !marker.isSymbolicLink()) {
3410
- exclusions.push({ root, path: path3, reason: "installed Python virtual environment; rebuild for the target platform" });
3411
- continue;
3412
- }
3413
- } catch (error) {
3414
- if (error.code !== "ENOENT") throw error;
3415
- }
3416
- }
3417
- const entry = {
3418
- root,
3419
- path: path3,
3420
- source,
3421
- kind: info.isDirectory() ? "directory" : "file",
3422
- bytes: Number(info.size),
3423
- mode: Number(info.mode) & 448,
3424
- signature: [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
3425
- };
3426
- entries.push(entry);
3427
- if (info.isDirectory()) await walk(root, source, path3);
3428
- else {
3429
- const h = await open2(source, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
3430
- const header = Buffer.alloc(16);
3431
- try {
3432
- await h.read(header, 0, 16, 0);
3433
- } finally {
3434
- await h.close();
3435
- }
3436
- if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
3437
- else if (/\.(db|sqlite|sqlite3)$/i.test(path3)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path3}`);
3639
+ PRIMARY KEY(branch_digest,scope_id,kind,original_id));
3640
+ CREATE TABLE IF NOT EXISTS e7_recovery_resolutions(
3641
+ resolution_id TEXT PRIMARY KEY,digest TEXT NOT NULL);`;
3642
+ function initializeRecoveryAdmission(db) {
3643
+ if (db.isTransaction || db.prepare("SELECT 1 FROM sqlite_master WHERE name='e7_replication_control'").get() && db.prepare("SELECT 1 FROM e7_replication_control LIMIT 1").get()) throw new Error("RECOVERY_NEW_BASELINE_REQUIRED");
3644
+ db.exec(RECOVERY_ADMISSION_SCHEMA);
3645
+ }
3646
+
3647
+ // src/continuity/generation-integrity.ts
3648
+ import { createHash as createHash5 } from "node:crypto";
3649
+ import { constants as constants8, closeSync as closeSync6, fstatSync as fstatSync5, lstatSync as lstatSync8, openSync as openSync7, readSync as readSync2, readdirSync, realpathSync as realpathSync3 } from "node:fs";
3650
+ import { join as join8, resolve as resolve8 } from "node:path";
3651
+ import { open as open4 } from "node:fs/promises";
3652
+ var recentSeals = /* @__PURE__ */ new Map();
3653
+ function rememberSeal(root, integrity, files) {
3654
+ recentSeals.delete(root);
3655
+ recentSeals.set(root, { integrity: JSON.stringify(integrity), metadata: fileMetadata(files) });
3656
+ if (recentSeals.size > 4) recentSeals.delete(recentSeals.keys().next().value);
3657
+ }
3658
+ var metadata2 = (stat) => [stat.dev, stat.ino, stat.size, stat.mode, stat.mtimeNs, stat.ctimeNs].join(":");
3659
+ function generationFiles(root) {
3660
+ const files = [];
3661
+ if (realpathSync3(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3662
+ const visit = (path3) => {
3663
+ if (path3 === ".runtime-publication-receipt.json") return;
3664
+ const file = join8(root, path3), stat = lstatSync8(file, { bigint: true });
3665
+ if (stat.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3666
+ if (stat.isDirectory()) {
3667
+ for (const name of readdirSync(file).sort()) visit(path3 ? path3 + "/" + name : name);
3668
+ return;
3669
+ }
3670
+ if (!stat.isFile() || stat.size > BigInt(Number.MAX_SAFE_INTEGER) || files.length >= 1e5) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3671
+ files.push({ path: path3, stat });
3672
+ };
3673
+ visit("");
3674
+ return files.sort((a, b) => a.path.localeCompare(b.path, "en"));
3675
+ }
3676
+ var fileMetadata = (files) => JSON.stringify(files.map((file) => [file.path, metadata2(file.stat)]));
3677
+ function runtimeGenerationIntegrity(directory2) {
3678
+ const root = resolve8(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
3679
+ const files = generationFiles(root);
3680
+ for (const { path: path3, stat: before } of files) {
3681
+ const file = join8(root, path3);
3682
+ const fd = openSync7(file, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0)), hash11 = createHash5("sha256");
3683
+ let bytes = 0;
3684
+ try {
3685
+ while (true) {
3686
+ const size = readSync2(fd, buffer);
3687
+ if (!size) break;
3688
+ hash11.update(buffer.subarray(0, size));
3689
+ bytes += size;
3438
3690
  }
3691
+ const after = fstatSync5(fd, { bigint: true });
3692
+ if (metadata2(before) !== metadata2(after) || metadata2(before) !== metadata2(lstatSync8(file, { bigint: true })) || BigInt(bytes) !== before.size) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3693
+ result.push({ path: path3, bytes, mode: Number(before.mode & 0o777n), sha256: hash11.digest("hex") });
3694
+ } finally {
3695
+ closeSync6(fd);
3439
3696
  }
3440
3697
  }
3441
- await walk("state", state2);
3442
- await walk("workspace", workspace);
3443
- const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
3444
- for (const entry of entries) {
3445
- if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
3446
- if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
3447
- entry.kind = "sidecar";
3698
+ rememberSeal(root, result, files);
3699
+ return result;
3700
+ }
3701
+ async function runtimeGenerationIntegrityAsync(directory2) {
3702
+ const root = resolve8(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
3703
+ const files = generationFiles(root);
3704
+ for (const { path: path3, stat: before } of files) {
3705
+ const file = join8(root, path3), handle = await open4(file, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0)), hash11 = createHash5("sha256");
3706
+ let bytes = 0;
3707
+ try {
3708
+ while (true) {
3709
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
3710
+ if (!bytesRead) break;
3711
+ hash11.update(buffer.subarray(0, bytesRead));
3712
+ bytes += bytesRead;
3713
+ }
3714
+ const after = await handle.stat({ bigint: true });
3715
+ if (metadata2(before) !== metadata2(after) || metadata2(before) !== metadata2(lstatSync8(file, { bigint: true })) || BigInt(bytes) !== before.size) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3716
+ result.push({ path: path3, bytes, mode: Number(before.mode & 0o777n), sha256: hash11.digest("hex") });
3717
+ } finally {
3718
+ await handle.close();
3448
3719
  }
3449
3720
  }
3450
- return { entries, exclusions, roots };
3721
+ rememberSeal(root, result, files);
3722
+ return result;
3723
+ }
3724
+ function verifyRuntimeGenerationIntegrity(directory2, expected) {
3725
+ if (!Array.isArray(expected)) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3726
+ const root = resolve8(directory2), integrity = JSON.stringify(expected);
3727
+ const recentSeal = recentSeals.get(root);
3728
+ if (recentSeal?.integrity === integrity && recentSeal.metadata === fileMetadata(generationFiles(root))) return;
3729
+ if (JSON.stringify(runtimeGenerationIntegrity(root)) !== integrity) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3730
+ }
3731
+ async function verifyRuntimeGenerationIntegrityAsync(directory2, expected) {
3732
+ if (!Array.isArray(expected)) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3733
+ const root = resolve8(directory2), integrity = JSON.stringify(expected);
3734
+ const recentSeal = recentSeals.get(root);
3735
+ if (recentSeal?.integrity === integrity && recentSeal.metadata === fileMetadata(generationFiles(root))) return;
3736
+ if (JSON.stringify(await runtimeGenerationIntegrityAsync(root)) !== integrity) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3451
3737
  }
3452
3738
 
3453
3739
  // src/continuity/recovery-deletion-visibility.ts
3454
3740
  import { DatabaseSync as DatabaseSync11 } from "node:sqlite";
3455
3741
  import { createHash as createHash27, randomUUID as randomUUID11 } from "node:crypto";
3456
- import { existsSync as existsSync9, realpathSync as realpathSync9, renameSync as renameSync6, unlinkSync as unlinkSync8, writeFileSync as writeFileSync11 } from "node:fs";
3742
+ import { existsSync as existsSync9, realpathSync as realpathSync9, renameSync as renameSync6, unlinkSync as unlinkSync7, writeFileSync as writeFileSync10 } from "node:fs";
3457
3743
  import { join as join18, resolve as resolve13 } from "node:path";
3458
3744
 
3459
3745
  // src/continuity/recovery-deletion-overlay.ts
3460
3746
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
3461
3747
  import { createHash as createHash26, randomUUID as randomUUID10 } from "node:crypto";
3462
- import { existsSync as existsSync8, realpathSync as realpathSync8, renameSync as renameSync5, unlinkSync as unlinkSync7, writeFileSync as writeFileSync10 } from "node:fs";
3748
+ import { existsSync as existsSync8, realpathSync as realpathSync8, renameSync as renameSync5, unlinkSync as unlinkSync6, writeFileSync as writeFileSync9 } from "node:fs";
3463
3749
  import { dirname as dirname10, join as join17, resolve as resolve12 } from "node:path";
3464
3750
 
3465
3751
  // src/continuity/recovery-deletion-sources.ts
@@ -3715,7 +4001,7 @@ import { createHash as createHash11 } from "node:crypto";
3715
4001
 
3716
4002
  // src/mem7/core/change-feed.ts
3717
4003
  import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";
3718
- import { existsSync as existsSync3, readFileSync as readFileSync5, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync6 } from "node:fs";
4004
+ import { existsSync as existsSync3, readFileSync as readFileSync4, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync5 } from "node:fs";
3719
4005
 
3720
4006
  // src/mem7/core/state/temporal.ts
3721
4007
  function instant(value2) {
@@ -4684,7 +4970,7 @@ var ChangeFeed = class _ChangeFeed {
4684
4970
  let ledger = {};
4685
4971
  if (ledgerPath) {
4686
4972
  try {
4687
- ledger = JSON.parse(readFileSync5(ledgerPath, "utf8"))?.heals ?? {};
4973
+ ledger = JSON.parse(readFileSync4(ledgerPath, "utf8"))?.heals ?? {};
4688
4974
  } catch {
4689
4975
  }
4690
4976
  if (Number.isFinite(ledger[key2])) {
@@ -4709,11 +4995,11 @@ var ChangeFeed = class _ChangeFeed {
4709
4995
  retained[key2] = now2;
4710
4996
  const temp = `${ledgerPath}.${randomUUID3()}.tmp`;
4711
4997
  try {
4712
- writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
4998
+ writeFileSync5(temp, JSON.stringify({ version: 1, heals: retained }));
4713
4999
  renameSync2(temp, ledgerPath);
4714
5000
  } catch (error) {
4715
5001
  try {
4716
- if (existsSync3(temp)) unlinkSync3(temp);
5002
+ if (existsSync3(temp)) unlinkSync2(temp);
4717
5003
  } catch {
4718
5004
  }
4719
5005
  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}`);
@@ -5581,12 +5867,20 @@ var MemoryTombstones = class {
5581
5867
  has(scope, kind, id2) {
5582
5868
  return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeId(scope), kind, id2));
5583
5869
  }
5870
+ /** 1117:deep-recall 的引用只存 scopeId 字符串(无 scope 对象),同判定按 id 直查。 */
5871
+ hasByScopeId(scopeIdValue, kind, id2) {
5872
+ return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeIdValue, kind, id2));
5873
+ }
5584
5874
  any(scope) {
5585
5875
  return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? LIMIT 1").get(scopeId(scope)));
5586
5876
  }
5587
5877
  anyForOwner(ownerId) {
5588
5878
  return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones t JOIN memory_scopes s ON s.scope_id=t.scope_id WHERE s.owner_id=? LIMIT 1").get(ownerId));
5589
5879
  }
5880
+ /** 1117:撤回校验的快速门——墓碑可挂在任意 scope(如旧 default 池)下,不看 owner。 */
5881
+ exists() {
5882
+ return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones LIMIT 1").get());
5883
+ }
5590
5884
  deleteSource(scope, sourceId, expectedVersion, requestKey, reason) {
5591
5885
  if (!requestKey || !reason.trim()) throw new Error("INVALID_DELETE_REQUEST");
5592
5886
  this.transaction(() => {
@@ -6149,7 +6443,7 @@ var JobProvenanceStore = class {
6149
6443
 
6150
6444
  // src/mem7/core/legacy-recovery.ts
6151
6445
  import { createHash as createHash21 } from "node:crypto";
6152
- import { readFileSync as readFileSync9, realpathSync as realpathSync5, statSync } from "node:fs";
6446
+ import { readFileSync as readFileSync8, realpathSync as realpathSync5, statSync } from "node:fs";
6153
6447
  import { isAbsolute as isAbsolute2, join as join13, relative as relative3, resolve as resolve9, sep as sep2 } from "node:path";
6154
6448
 
6155
6449
  // src/mem7/core/store.ts
@@ -6159,7 +6453,7 @@ init_sqlite_replication();
6159
6453
  import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
6160
6454
  init_sqlite_autocommit();
6161
6455
  init_schema_migrations();
6162
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync7, renameSync as renameSync3, existsSync as existsSync5, readdirSync as readdirSync2, lstatSync as lstatSync10, unlinkSync as unlinkSync4 } from "node:fs";
6456
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync7, writeFileSync as writeFileSync6, renameSync as renameSync3, existsSync as existsSync5, readdirSync as readdirSync2, lstatSync as lstatSync10, unlinkSync as unlinkSync3 } from "node:fs";
6163
6457
  import { join as join12, relative as relative2 } from "node:path";
6164
6458
  import { createHash as createHash20, randomUUID as randomUUID8 } from "node:crypto";
6165
6459
 
@@ -6932,12 +7226,12 @@ var Mem7VectorStore = class {
6932
7226
  * public:get/ 分页列表也走这里收口) */
6933
7227
  toHit(kind, r) {
6934
7228
  const textCol = textColumnOf(kind);
6935
- const metadata3 = {};
7229
+ const metadata4 = {};
6936
7230
  const NOISE = /* @__PURE__ */ new Set(["vector", "_distance", "_score", "created_at", "updated_at", "id"]);
6937
7231
  for (const k of Object.keys(r)) {
6938
7232
  if (NOISE.has(k)) continue;
6939
7233
  const v = r[k];
6940
- metadata3[k] = typeof v?.toArray === "function" ? v.toArray() : v;
7234
+ metadata4[k] = typeof v?.toArray === "function" ? v.toArray() : v;
6941
7235
  }
6942
7236
  const ledger = this.publicationLedger();
6943
7237
  const dependencies2 = this.sharedDependencies();
@@ -6951,7 +7245,7 @@ var Mem7VectorStore = class {
6951
7245
  mdPath: r.md_path ? String(r.md_path) : void 0,
6952
7246
  distance: Number(r._distance ?? 0),
6953
7247
  score: 1 - Number(r._distance ?? 0),
6954
- metadata: metadata3,
7248
+ metadata: metadata4,
6955
7249
  ...ledger ? { assertCurrent: Object.assign(() => {
6956
7250
  const startedAt = performance.now();
6957
7251
  try {
@@ -8130,15 +8424,15 @@ var RecallSources = class {
8130
8424
  const id2 = scopeId(scope);
8131
8425
  if (!db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind='source' LIMIT 1").get(id2)) return;
8132
8426
  const dependents = /* @__PURE__ */ new Map();
8133
- const link2 = (parent, child) => {
8427
+ const link3 = (parent, child) => {
8134
8428
  const children = dependents.get(parent) ?? /* @__PURE__ */ new Set();
8135
8429
  children.add(child);
8136
8430
  dependents.set(parent, children);
8137
8431
  };
8138
8432
  const refs2 = (raw, child) => {
8139
8433
  for (const ref of JSON.parse(raw)) if (ref.scopeId === id2) {
8140
- link2(`s:${ref.sourceId}`, child);
8141
- if (ref.relationshipId) link2(`r:${ref.relationshipId}:${ref.semanticVersion}`, child);
8434
+ link3(`s:${ref.sourceId}`, child);
8435
+ if (ref.relationshipId) link3(`r:${ref.relationshipId}:${ref.semanticVersion}`, child);
8142
8436
  }
8143
8437
  };
8144
8438
  for (const row of db.prepare("SELECT source_id,context_refs,basis_refs FROM memory_social_sources WHERE scope_id=?").all(id2)) {
@@ -8153,7 +8447,7 @@ var RecallSources = class {
8153
8447
  const known = knownVersions ? knownVersions.get(JSON.stringify([row.relationship_id, row.semantic_version])) : row;
8154
8448
  if (!known) continue;
8155
8449
  const child = `r:${row.relationship_id}:${row.semantic_version}`;
8156
- if (row.source_id) link2(`s:${row.source_id}`, child);
8450
+ if (row.source_id) link3(`s:${row.source_id}`, child);
8157
8451
  refs2(known.basis_refs, child);
8158
8452
  }
8159
8453
  const queue = db.prepare("SELECT target_id FROM memory_tombstones WHERE scope_id=? AND target_kind='source'").all(id2).map((row) => `s:${row.target_id}`);
@@ -8190,8 +8484,8 @@ var RecallSources = class {
8190
8484
  return this.metadata.get(id2);
8191
8485
  }
8192
8486
  current(id2) {
8193
- const metadata3 = this.sourceMetadata(id2);
8194
- return Boolean(this.source(id2) && this.originals.isCurrent(this.scope, id2, this.cutoff) && !metadata3?.contextRefs.length && !metadata3?.basisRefs.length);
8487
+ const metadata4 = this.sourceMetadata(id2);
8488
+ return Boolean(this.source(id2) && this.originals.isCurrent(this.scope, id2, this.cutoff) && !metadata4?.contextRefs.length && !metadata4?.basisRefs.length);
8195
8489
  }
8196
8490
  referenceCurrent(ref) {
8197
8491
  return ref.scopeId === scopeId(this.scope) && this.source(ref.sourceId)?.sourceVersion === ref.sourceVersion && !ref.relationshipId && this.current(ref.sourceId);
@@ -8556,11 +8850,11 @@ var SocialSourceStore = class {
8556
8850
  return false;
8557
8851
  }
8558
8852
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
8559
- const metadata3 = snapshot.metadata.get(sourceId);
8853
+ const metadata4 = snapshot.metadata.get(sourceId);
8560
8854
  visited.add(sourceId);
8561
8855
  try {
8562
8856
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
8563
- const retained = !metadata3 || metadata3.contextRefs.every(check) && metadata3.basisRefs.every(check);
8857
+ const retained = !metadata4 || metadata4.contextRefs.every(check) && metadata4.basisRefs.every(check);
8564
8858
  memo.set(key2, retained);
8565
8859
  return retained;
8566
8860
  } finally {
@@ -8602,10 +8896,10 @@ var SocialSourceStore = class {
8602
8896
  return false;
8603
8897
  }
8604
8898
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
8605
- const metadata3 = snapshot.metadata.get(sourceId);
8899
+ const metadata4 = snapshot.metadata.get(sourceId);
8606
8900
  visited.add(sourceId);
8607
8901
  try {
8608
- const current2 = !metadata3 || metadata3.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
8902
+ const current2 = !metadata4 || metadata4.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
8609
8903
  snapshot.grounds.set(key2, current2);
8610
8904
  return current2;
8611
8905
  } finally {
@@ -9214,10 +9508,10 @@ init_read_guard();
9214
9508
  init_scope();
9215
9509
 
9216
9510
  // src/mem7/core/episode.ts
9217
- import { readFileSync as readFileSync7 } from "node:fs";
9511
+ import { readFileSync as readFileSync6 } from "node:fs";
9218
9512
  import { join as join11, dirname as dirname6 } from "node:path";
9219
9513
  import { fileURLToPath } from "node:url";
9220
- var PROMPT = readFileSync7(join11(dirname6(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
9514
+ var PROMPT = readFileSync6(join11(dirname6(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
9221
9515
 
9222
9516
  // src/mem7/core/source-material.ts
9223
9517
  function isAssistantDraft(source) {
@@ -10205,7 +10499,7 @@ var Mem7Store = class {
10205
10499
  let existingBlocks = "";
10206
10500
  let count;
10207
10501
  if (existsSync5(file)) {
10208
- const text2 = readFileSync8(file, "utf8");
10502
+ const text2 = readFileSync7(file, "utf8");
10209
10503
  const fmEnd = text2.indexOf("\n---", 3);
10210
10504
  const split = fmEnd >= 0 ? fmEnd + 4 : text2.length;
10211
10505
  head = text2.slice(0, split);
@@ -10262,7 +10556,7 @@ var Mem7Store = class {
10262
10556
  let existingBlocks = "";
10263
10557
  let count;
10264
10558
  if (existsSync5(file)) {
10265
- const text2 = readFileSync8(file, "utf8");
10559
+ const text2 = readFileSync7(file, "utf8");
10266
10560
  const fmEnd = text2.indexOf("\n---", 3);
10267
10561
  const split = fmEnd >= 0 ? fmEnd + 4 : text2.length;
10268
10562
  head = text2.slice(0, split);
@@ -10310,11 +10604,11 @@ var Mem7Store = class {
10310
10604
  assertRuntimeAuthority(this.stateDir, "WRITE");
10311
10605
  const temporary = `${file}.${randomUUID8()}.tmp`;
10312
10606
  try {
10313
- writeFileSync7(temporary, content, "utf8");
10607
+ writeFileSync6(temporary, content, "utf8");
10314
10608
  assertRuntimeAuthority(this.stateDir, "WRITE");
10315
10609
  renameSync3(temporary, file);
10316
10610
  } finally {
10317
- if (existsSync5(temporary)) unlinkSync4(temporary);
10611
+ if (existsSync5(temporary)) unlinkSync3(temporary);
10318
10612
  }
10319
10613
  }
10320
10614
  recordProjection(scope, kind, id2, file, content, body, expectedVersion) {
@@ -10357,7 +10651,7 @@ var Mem7Store = class {
10357
10651
  let max = 0;
10358
10652
  if (existsSync5(file)) {
10359
10653
  const re = new RegExp(`${prefix2}_${dateStr.replace(/-/g, "")}_(\\d+)`, "g");
10360
- for (const m of readFileSync8(file, "utf8").matchAll(re)) max = Math.max(max, Number(m[1]));
10654
+ for (const m of readFileSync7(file, "utf8").matchAll(re)) max = Math.max(max, Number(m[1]));
10361
10655
  }
10362
10656
  return max;
10363
10657
  }
@@ -10580,7 +10874,7 @@ ${e.outcome}
10580
10874
  for (const f of files) {
10581
10875
  let text2;
10582
10876
  try {
10583
- text2 = readFileSync8(join12(dir, f), "utf8");
10877
+ text2 = readFileSync7(join12(dir, f), "utf8");
10584
10878
  } catch {
10585
10879
  continue;
10586
10880
  }
@@ -10614,7 +10908,7 @@ ${e.outcome}
10614
10908
  for (const d of dirs) {
10615
10909
  let text2;
10616
10910
  try {
10617
- text2 = readFileSync8(join12(base, d, "SKILL.md"), "utf8");
10911
+ text2 = readFileSync7(join12(base, d, "SKILL.md"), "utf8");
10618
10912
  } catch {
10619
10913
  continue;
10620
10914
  }
@@ -10679,7 +10973,7 @@ ${e.outcome}
10679
10973
  let text2;
10680
10974
  const file = join12(this.root, this.ownerProjectionPath("users", ownerId, scope), "user.md");
10681
10975
  try {
10682
- text2 = readFileSync8(file, "utf8");
10976
+ text2 = readFileSync7(file, "utf8");
10683
10977
  } catch {
10684
10978
  return null;
10685
10979
  }
@@ -11251,7 +11545,7 @@ ${e.outcome}
11251
11545
  if (!/^foresight-\d{4}-\d{2}-\d{2}\.md$/.test(f)) continue;
11252
11546
  let content;
11253
11547
  try {
11254
- content = readFileSync8(join12(dir, f), "utf8");
11548
+ content = readFileSync7(join12(dir, f), "utf8");
11255
11549
  } catch {
11256
11550
  continue;
11257
11551
  }
@@ -11467,7 +11761,7 @@ function sessionCandidates(files, mapping) {
11467
11761
  rejected++;
11468
11762
  continue;
11469
11763
  }
11470
- const bytes = readFileSync9(file);
11764
+ const bytes = readFileSync8(file);
11471
11765
  const records = [];
11472
11766
  let header;
11473
11767
  let invalid = false;
@@ -11713,7 +12007,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
11713
12007
  gap("projection_kind_or_owner_unverified");
11714
12008
  continue;
11715
12009
  }
11716
- const bytes = readFileSync9(canonical3);
12010
+ const bytes = readFileSync8(canonical3);
11717
12011
  const text2 = bytes.toString("utf8").replace(/\r\n/g, "\n");
11718
12012
  const fileHash = hash6(bytes);
11719
12013
  const entries = [...text2.matchAll(/<!-- entry:([^\s<>]+) -->([\s\S]*?)<!-- \/entry:\1 -->/g)];
@@ -11783,7 +12077,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
11783
12077
  if (!apply || !candidates.length) return report;
11784
12078
  for (const file of new Set(candidates.map((candidate) => candidate.file))) {
11785
12079
  const candidate = candidates.find((candidate2) => candidate2.file === file);
11786
- if (hash6(readFileSync9(file)) !== candidate.fileHash) throw new Error("LEGACY_PROJECTION_CHANGED_DURING_RECOVERY");
12080
+ if (hash6(readFileSync8(file)) !== candidate.fileHash) throw new Error("LEGACY_PROJECTION_CHANGED_DURING_RECOVERY");
11787
12081
  if (realpathSync5(store.mem7RootPath()) !== root) throw new Error("LEGACY_PROJECTION_COPY_REQUIRED");
11788
12082
  }
11789
12083
  store.transaction(() => {
@@ -12259,7 +12553,7 @@ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
12259
12553
  import { createHash as createHash25 } from "node:crypto";
12260
12554
  import { gunzipSync as gunzipSync2 } from "node:zlib";
12261
12555
  import { isUtf8 } from "node:buffer";
12262
- import { rmSync as rmSync2, writeFileSync as writeFileSync9, existsSync as existsSync7, unlinkSync as unlinkSync6 } from "node:fs";
12556
+ import { rmSync as rmSync2, writeFileSync as writeFileSync8, existsSync as existsSync7, unlinkSync as unlinkSync5 } from "node:fs";
12263
12557
  import { join as join16, dirname as dirname9 } from "node:path";
12264
12558
 
12265
12559
  // src/continuity/session-events.ts
@@ -12267,9 +12561,10 @@ init_schema_migrations();
12267
12561
  init_sqlite_replication();
12268
12562
  init_runtime_replication();
12269
12563
  init_runtime_lock();
12564
+ init_runtime_authority();
12270
12565
  import { createRequire as createRequire5 } from "node:module";
12271
12566
  import { createHash as createHash23 } from "node:crypto";
12272
- import { constants as constants10, lstatSync as lstatSync12, readdirSync as readdirSync3, realpathSync as realpathSync7, readFileSync as readFileSync10, writeFileSync as writeFileSync8, openSync as openSync10, closeSync as closeSync9, readSync as readSync3, chmodSync as chmodSync2, existsSync as existsSync6 } from "node:fs";
12567
+ import { constants as constants10, lstatSync as lstatSync12, readdirSync as readdirSync3, realpathSync as realpathSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync7, openSync as openSync10, closeSync as closeSync9, readSync as readSync3, chmodSync as chmodSync2, existsSync as existsSync6 } from "node:fs";
12273
12568
  import { join as join15, resolve as resolve11, dirname as dirname8 } from "node:path";
12274
12569
 
12275
12570
  // src/continuity/session-event-projection.ts
@@ -12284,7 +12579,7 @@ import {
12284
12579
  fstatSync as fstatSync6,
12285
12580
  appendFileSync,
12286
12581
  renameSync as renameSync4,
12287
- unlinkSync as unlinkSync5
12582
+ unlinkSync as unlinkSync4
12288
12583
  } from "node:fs";
12289
12584
  import { basename as basename4, dirname as dirname7, join as join14, relative as relative4, resolve as resolve10 } from "node:path";
12290
12585
  import { createHash as createHash22, randomUUID as randomUUID9 } from "node:crypto";
@@ -12382,7 +12677,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
12382
12677
  prepareSessionDirectory(dirname7(file));
12383
12678
  if (record.state === "removed") {
12384
12679
  if (signature2 !== null) {
12385
- unlinkSync5(file);
12680
+ unlinkSync4(file);
12386
12681
  syncSessionDirectory(dirname7(file));
12387
12682
  }
12388
12683
  cursors.prepare("DELETE FROM cursors WHERE path=?").run(path3);
@@ -12426,7 +12721,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
12426
12721
  if (fd !== void 0) closeSync8(fd);
12427
12722
  if (!incremental && !complete) {
12428
12723
  try {
12429
- unlinkSync5(temp);
12724
+ unlinkSync4(temp);
12430
12725
  } catch (error) {
12431
12726
  if (error.code !== "ENOENT") throw error;
12432
12727
  }
@@ -12552,7 +12847,7 @@ var SessionEventStore = class {
12552
12847
  if (row && !approvedSourceRoot) {
12553
12848
  const file = join15(stateDir, ".travel-active.json"), stat = lstatSync12(file);
12554
12849
  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");
12555
- const activation = JSON.parse(readFileSync10(file, "utf8")), binding = registration.binding;
12850
+ const activation = JSON.parse(readFileSync9(file, "utf8")), binding = registration.binding;
12556
12851
  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;
12557
12852
  }
12558
12853
  if (!row || !approvedSourceRoot || !Number.isSafeInteger(row.revision) || Number(row.revision) < 0) throw new Error("REPLICATION_RECOVERY_REQUIRED");
@@ -12804,7 +13099,7 @@ async function restoreSessionEvents(options) {
12804
13099
  if (realpathSync7(dirname8(destination)) !== dirname8(destination)) throw new Error("SESSION_SYMLINK_REFUSED");
12805
13100
  if (existsSync6(destination)) throw new Error("CONTINUITY_DESTINATION_EXISTS");
12806
13101
  prepareSessionDirectory(destination);
12807
- writeFileSync8(join15(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-session-events-restore-v1", activationAllowed: false, binding }), { mode: 384, flag: "wx", flush: true });
13102
+ writeFileSync7(join15(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-session-events-restore-v1", activationAllowed: false, binding }), { mode: 384, flag: "wx", flush: true });
12808
13103
  syncSessionDirectory(destination);
12809
13104
  const directory2 = join15(destination, ".continuity");
12810
13105
  prepareSessionDirectory(directory2);
@@ -12819,7 +13114,7 @@ async function restoreSessionEvents(options) {
12819
13114
  cursors.exec("BEGIN IMMEDIATE");
12820
13115
  for (const row of copy.prepare("SELECT path FROM session_files ORDER BY path").all()) projectSessionFile(copy, cursors, destination, String(row.path), root);
12821
13116
  cursors.exec("COMMIT");
12822
- writeFileSync8(
13117
+ writeFileSync7(
12823
13118
  join15(destination, ".session-events-receipt.json"),
12824
13119
  JSON.stringify({ binding, head: { sequence: control2.head, digest: control2.digest }, activationAllowed: false }),
12825
13120
  { mode: 384, flag: "wx", flush: true }
@@ -13023,7 +13318,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13023
13318
  const path4 = join16(options.root, "trees", tree.id, file.path);
13024
13319
  if (existsSync7(path4)) {
13025
13320
  check();
13026
- unlinkSync6(path4);
13321
+ unlinkSync5(path4);
13027
13322
  await syncDirectory(dirname9(path4));
13028
13323
  check();
13029
13324
  debugCaches++;
@@ -13047,9 +13342,9 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13047
13342
  }).join("");
13048
13343
  if (!removed) continue;
13049
13344
  check();
13050
- writeFileSync9(path3, retained, { flush: true });
13345
+ writeFileSync8(path3, retained, { flush: true });
13051
13346
  const cursor = path3 + ".cursor";
13052
- if (file.path === "mem7/spool/intake.processing.jsonl" && existsSync7(cursor)) unlinkSync6(cursor);
13347
+ if (file.path === "mem7/spool/intake.processing.jsonl" && existsSync7(cursor)) unlinkSync5(cursor);
13053
13348
  await syncDirectory(dirname9(path3));
13054
13349
  check();
13055
13350
  intakeRecords += removed;
@@ -13062,9 +13357,9 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13062
13357
  const metadataDb = [...options.databases].filter(([, db2]) => readSchemaVersion(db2)?.component === "session-events");
13063
13358
  if (metadataDb.length !== 1) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
13064
13359
  const [databaseId, db] = metadataDb[0];
13065
- const metadata3 = parse(readPrivateFile2(join16(options.root, "trees", tree.id, "manifest.json"), 1024 * 1024).toString());
13360
+ const metadata4 = parse(readPrivateFile2(join16(options.root, "trees", tree.id, "manifest.json"), 1024 * 1024).toString());
13066
13361
  const binding = normalizeBinding({ ...options.manifest.profile.identity, baselineId: options.manifest.profile.baselineId, epoch: options.manifest.profile.epoch, databaseId });
13067
- if (metadata3.format !== "engine7-session-events-publication-v1" || metadata3.databaseId !== databaseId || JSON.stringify(metadata3.binding) !== JSON.stringify(binding) || JSON.stringify(metadata3.head) !== JSON.stringify(options.manifest.databases.find((d) => d.databaseId === databaseId)?.head)) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
13362
+ if (metadata4.format !== "engine7-session-events-publication-v1" || metadata4.databaseId !== databaseId || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(options.manifest.databases.find((d) => d.databaseId === databaseId)?.head)) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
13068
13363
  if (readSchemaVersion(db)?.version !== 1) throw new Error("RECOVERY_OVERLAY_SCHEMA");
13069
13364
  const legacyRecords = /* @__PURE__ */ new Map();
13070
13365
  for (const record of memory.prepare(`SELECT r.*,m.session_id FROM memory_legacy_source_records r
@@ -13356,8 +13651,8 @@ async function deletionOverlay(options, runtimeCopies) {
13356
13651
  text2 = text2.replace(/entry_count: \d+/, "entry_count: " + entries);
13357
13652
  const empty = text2.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "").trim() === "";
13358
13653
  await check();
13359
- if (empty) unlinkSync7(file);
13360
- else writeFileSync10(file, text2, { flush: true });
13654
+ if (empty) unlinkSync6(file);
13655
+ else writeFileSync9(file, text2, { flush: true });
13361
13656
  await syncDirectory(dirname10(file));
13362
13657
  await check();
13363
13658
  removedFiles.push("trees/" + matches[0].id + "/mem7/" + path3);
@@ -13417,13 +13712,13 @@ async function deletionOverlay(options, runtimeCopies) {
13417
13712
  const next = { ...original, originalIntegrity: original.originalIntegrity ?? original.integrity, deletionOverlay: proof, integrity: runtimeGenerationIntegrity(root) };
13418
13713
  const temporary = join17(root, ".runtime-publication-receipt-" + randomUUID10());
13419
13714
  try {
13420
- writeFileSync10(temporary, JSON.stringify(next), { mode: 384, flag: "wx", flush: true });
13715
+ writeFileSync9(temporary, JSON.stringify(next), { mode: 384, flag: "wx", flush: true });
13421
13716
  await check();
13422
13717
  renameSync5(temporary, receiptFile);
13423
13718
  await syncDirectory(root);
13424
13719
  await check();
13425
13720
  } finally {
13426
- if (existsSync8(temporary)) unlinkSync7(temporary);
13721
+ if (existsSync8(temporary)) unlinkSync6(temporary);
13427
13722
  }
13428
13723
  return proof;
13429
13724
  } finally {
@@ -13501,14 +13796,14 @@ async function completeCurrentHDeletionVisibility(options) {
13501
13796
  };
13502
13797
  const file = join18(options.snapshot, ".runtime-publication-receipt.json"), temporary = join18(options.snapshot, ".runtime-publication-receipt-" + randomUUID11());
13503
13798
  try {
13504
- writeFileSync11(temporary, JSON.stringify({ ...next, deletionVisibility: proof }), { mode: 384, flag: "wx", flush: true });
13799
+ writeFileSync10(temporary, JSON.stringify({ ...next, deletionVisibility: proof }), { mode: 384, flag: "wx", flush: true });
13505
13800
  await check();
13506
13801
  await effectsCheckAsync(options, floor);
13507
13802
  renameSync6(temporary, file);
13508
13803
  await syncDirectory(options.snapshot);
13509
13804
  await check();
13510
13805
  } finally {
13511
- if (existsSync9(temporary)) unlinkSync8(temporary);
13806
+ if (existsSync9(temporary)) unlinkSync7(temporary);
13512
13807
  }
13513
13808
  return proof;
13514
13809
  }
@@ -13539,7 +13834,9 @@ async function verifyRuntimeDirectory(directory2) {
13539
13834
  }
13540
13835
  }
13541
13836
  var same4 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
13837
+ var copyFlags = constants11.COPYFILE_EXCL | constants11.COPYFILE_FICLONE;
13542
13838
  function validateRuntimeActivationLayout(destination, raw, layout) {
13839
+ if (layout.inventorySelection !== void 0 && layout.inventorySelection !== "core") throw new Error("TRAVEL_ACTIVATION_LAYOUT");
13543
13840
  const manifest = normalizePublication(raw);
13544
13841
  if (!same4(Object.keys(layout.databases).sort(), manifest.profile.databaseIds) || !same4(Object.keys(layout.trees).sort(), manifest.profile.trees.map((t) => t.id).sort())) throw new Error("TRAVEL_ACTIVATION_LAYOUT");
13545
13842
  const locations = /* @__PURE__ */ new Map();
@@ -13593,7 +13890,7 @@ function validateRuntimeActivationSnapshot(snapshot, manifest, locations) {
13593
13890
  for (const d of manifest.databases) {
13594
13891
  const db = new DatabaseSync12(join19(snapshot, "databases", d.databaseId + ".sqlite"), { readOnly: true });
13595
13892
  try {
13596
- validateRecoveryDatabase(db, manifest, d.databaseId, "replica");
13893
+ validateRecoveryDatabase(db, manifest, d.databaseId, "replica", void 0, false);
13597
13894
  const place = locations.get(d.databaseId);
13598
13895
  if (readSchemaVersion(db)?.component !== place.component) throw new Error("TRAVEL_ACTIVATION_SCHEMA");
13599
13896
  if (place.component === "session-events") sourceRoots.push(String(db.prepare("SELECT source_root FROM session_control WHERE singleton=1").get().source_root));
@@ -13603,17 +13900,17 @@ function validateRuntimeActivationSnapshot(snapshot, manifest, locations) {
13603
13900
  }
13604
13901
  return sourceRoots;
13605
13902
  }
13606
- function copyTree(from, to, skipControl = false) {
13607
- const walk = (path3) => {
13608
- const stat = lstatSync13(path3);
13609
- if (stat.isSymbolicLink() || !stat.isDirectory() && !stat.isFile()) throw new Error("TRAVEL_ACTIVATION_UNSAFE_PATH");
13610
- if (stat.isDirectory()) for (const name of readdirSync4(path3)) walk(join19(path3, name));
13611
- };
13612
- walk(from);
13613
- mkdirSync9(to, { recursive: true, mode: 448 });
13614
- for (const name of readdirSync4(from)) {
13903
+ async function copyTree(from, to, skipControl = false) {
13904
+ const stat = await lstat3(from);
13905
+ if (stat.isSymbolicLink() || !stat.isDirectory() && !stat.isFile()) throw new Error("TRAVEL_ACTIVATION_UNSAFE_PATH");
13906
+ if (stat.isFile()) {
13907
+ await copyFile(from, to, copyFlags);
13908
+ return;
13909
+ }
13910
+ await mkdir(to, { recursive: true, mode: 448 });
13911
+ for (const name of await readdir2(from)) {
13615
13912
  if (skipControl && (name.startsWith(".") || name === "databases" || name === "trees" || name === "lance")) continue;
13616
- cpSync(join19(from, name), join19(to, name), { recursive: true, force: false, errorOnExist: true });
13913
+ await copyTree(join19(from, name), join19(to, name));
13617
13914
  }
13618
13915
  }
13619
13916
  async function activateRuntimeGeneration(options) {
@@ -13642,12 +13939,12 @@ async function activateRuntimeGeneration(options) {
13642
13939
  if (realpathSync10(snapshot) !== snapshot || realpathSync10(dirname11(destination)) !== dirname11(destination) || existsSync10(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
13643
13940
  const proof = JSON.parse(readPrivateFile2(join19(snapshot, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
13644
13941
  if (proof.format !== "engine7-runtime-publication-restore-v1" || !same4(proof.profile, manifest.profile) || proof.receipt?.digest !== digest7 || proof.receipt?.sequence !== manifest.sequence || proof.receipt?.state !== "PUBLISHED" || proof.activationAllowed !== false || !same4(proof.databases, manifest.databases)) throw new Error("TRAVEL_ACTIVATION_RECEIPT");
13645
- verifyRuntimeGenerationIntegrity(snapshot, proof.integrity);
13942
+ await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
13646
13943
  const locations = validateRuntimeActivationLayout(destination, manifest, options.layout);
13647
13944
  const sourceRoots = validateRuntimeActivationSnapshot(snapshot, manifest, locations);
13648
13945
  const profile = normalizePublicationProfile({ ...manifest.profile, baselineId: options.baselineId, epoch: options.permit.epoch });
13649
13946
  mkdirSync9(destination, { mode: 448 });
13650
- writeFileSync12(join19(destination, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
13947
+ writeFileSync11(join19(destination, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
13651
13948
  const runtime = new RuntimeAuthority({ stateDir: destination, identity, nodeId: options.permit.nodeId, bootId: options.permit.bootId, publicKey: options.authority.publicKey, allowedTools: options.allowedTools, initialize: true });
13652
13949
  runtime.acceptPermit(options.permit, options.requestStartedAt);
13653
13950
  runtime.advanceDeletionFloor(options.permit.deletionWatermark);
@@ -13657,14 +13954,14 @@ async function activateRuntimeGeneration(options) {
13657
13954
  await checkDeletion();
13658
13955
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13659
13956
  const source = tree.kind === "file" ? join19(snapshot, "trees", tree.id) : join19(snapshot, tree.kind === "vector" ? "lance" : "sessions", tree.id);
13660
- copyTree(source, join19(destination, options.layout.trees[tree.id]), tree.kind === "session");
13957
+ await copyTree(source, join19(destination, options.layout.trees[tree.id]), tree.kind === "session");
13661
13958
  }
13662
13959
  for (const d of manifest.databases) {
13663
13960
  await checkDeletion();
13664
13961
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13665
13962
  const path3 = join19(destination, options.layout.databases[d.databaseId]), place = locations.get(d.databaseId);
13666
13963
  mkdirSync9(dirname11(path3), { recursive: true, mode: 448 });
13667
- cpSync(join19(snapshot, "databases", d.databaseId + ".sqlite"), path3, { errorOnExist: true, force: false });
13964
+ await copyFile(join19(snapshot, "databases", d.databaseId + ".sqlite"), path3, copyFlags);
13668
13965
  const db = new DatabaseSync12(path3, { allowExtension: place.component === "legacy-memory" });
13669
13966
  try {
13670
13967
  if (place.component === "legacy-memory") loadLegacySQLiteVectorExtension(db);
@@ -13700,13 +13997,13 @@ async function activateRuntimeGeneration(options) {
13700
13997
  };
13701
13998
  await checkDeletion();
13702
13999
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13703
- verifyRuntimeGenerationIntegrity(snapshot, proof.integrity);
14000
+ await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
13704
14001
  runtime.advanceDeletionFloor(options.permit.deletionWatermark);
13705
- writeFileSync12(join19(destination, ".travel-active.json"), JSON.stringify(receipt2), { mode: 384, flag: "wx", flush: true });
14002
+ writeFileSync11(join19(destination, ".travel-active.json"), JSON.stringify(receipt2), { mode: 384, flag: "wx", flush: true });
13706
14003
  await syncDirectory(destination);
13707
14004
  await checkDeletion();
13708
14005
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13709
- unlinkSync9(join19(destination, ".travel-restored.json"));
14006
+ unlinkSync8(join19(destination, ".travel-restored.json"));
13710
14007
  await syncDirectory(destination);
13711
14008
  return { receipt: receipt2, profile, runtime };
13712
14009
  } catch (error) {
@@ -13722,7 +14019,7 @@ init_runtime_authority();
13722
14019
  // src/continuity/node-process.ts
13723
14020
  import { fork } from "node:child_process";
13724
14021
  import { DatabaseSync as DatabaseSync13 } from "node:sqlite";
13725
- import { closeSync as closeSync10, lstatSync as lstatSync14, openSync as openSync11, readFileSync as readFileSync13, realpathSync as realpathSync11 } from "node:fs";
14022
+ import { closeSync as closeSync10, lstatSync as lstatSync13, openSync as openSync11, readFileSync as readFileSync12, realpathSync as realpathSync11 } from "node:fs";
13726
14023
  import { isAbsolute as isAbsolute4, join as join20 } from "node:path";
13727
14024
  import { createHash as createHash28, randomUUID as randomUUID12 } from "node:crypto";
13728
14025
 
@@ -13837,8 +14134,8 @@ var SupervisedRuntimeProcess = class {
13837
14134
  const continuation = recovery ? this.db.prepare("SELECT * FROM recovery_continuations WHERE binding=?").get(JSON.stringify(binding)) : void 0;
13838
14135
  if (retired && (!recovery || continuation?.state !== "SUSPENDED" || continuation.entry_hash !== this.options.entrySha256 || continuation.authority_boot_id !== permit.authorityBootId)) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
13839
14136
  if (recovery && !retired) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
13840
- const info = lstatSync14(this.options.entry);
13841
- if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync11(this.options.entry) !== this.options.entry || createHash28("sha256").update(readFileSync13(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
14137
+ const info = lstatSync13(this.options.entry);
14138
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync11(this.options.entry) !== this.options.entry || createHash28("sha256").update(readFileSync12(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
13842
14139
  let environment;
13843
14140
  try {
13844
14141
  environment = supervisedRuntimeEnvironment(JSON.parse(readPrivateFile2(this.options.configFile, 1024 * 1024).toString()), process.env, this.options.environmentNames);
@@ -14022,15 +14319,15 @@ var SupervisedRuntimeProcess = class {
14022
14319
 
14023
14320
  // src/continuity/runtime-publication-restore.ts
14024
14321
  import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
14025
- import { mkdirSync as mkdirSync12, writeFileSync as writeFileSync15 } from "node:fs";
14322
+ import { mkdirSync as mkdirSync12, writeFileSync as writeFileSync14 } from "node:fs";
14026
14323
  import { join as join23, resolve as resolve17 } from "node:path";
14027
14324
 
14028
14325
  // src/continuity/publication-files.ts
14029
14326
  import { DatabaseSync as DatabaseSync14, backup as backup2 } from "node:sqlite";
14030
- import { lstatSync as lstatSync15, readdirSync as readdirSync5, realpathSync as realpathSync12, mkdirSync as mkdirSync10, writeFileSync as writeFileSync13, chmodSync as chmodSync3, openSync as openSync12, closeSync as closeSync11, fsyncSync as fsyncSync7 } from "node:fs";
14327
+ import { lstatSync as lstatSync14, readdirSync as readdirSync4, realpathSync as realpathSync12, mkdirSync as mkdirSync10, writeFileSync as writeFileSync12, chmodSync as chmodSync3, openSync as openSync12, closeSync as closeSync11, fsyncSync as fsyncSync7 } from "node:fs";
14031
14328
  import { join as join21, resolve as resolve15, dirname as dirname12 } from "node:path";
14032
14329
  async function restorePublication(options) {
14033
- const { receiver } = options, status = await receiver.status();
14330
+ const { receiver } = options, status = await receiver.status(false);
14034
14331
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
14035
14332
  const manifest = await receiver.manifest(status.published.sequence);
14036
14333
  if (JSON.stringify(Object.keys(options.databases).sort()) !== JSON.stringify(manifest.profile.databaseIds)) throw new Error("PUBLICATION_INCOMPLETE_DATABASES");
@@ -14044,7 +14341,7 @@ async function restorePublication(options) {
14044
14341
  throw error;
14045
14342
  }
14046
14343
  await syncDirectory(dirname12(destination));
14047
- writeFileSync13(join21(destination, ".travel-restored.json"), JSON.stringify({
14344
+ writeFileSync12(join21(destination, ".travel-restored.json"), JSON.stringify({
14048
14345
  format: "engine7-publication-restore-v1",
14049
14346
  activationAllowed: false,
14050
14347
  sequence: manifest.sequence,
@@ -14071,8 +14368,8 @@ async function restorePublication(options) {
14071
14368
  const row = copy.prepare("SELECT head,digest,binding FROM e7_replication_control WHERE role='replica'").get();
14072
14369
  const identity = manifest.profile.identity;
14073
14370
  const wanted = [identity.tenantId, identity.companionId, identity.seatId, item.databaseId, manifest.profile.baselineId, manifest.profile.epoch];
14074
- const check = copy.prepare("PRAGMA quick_check").all();
14075
- 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");
14371
+ if (!row || row.head !== item.head.sequence || row.digest !== item.head.digest || row.binding !== JSON.stringify(wanted))
14372
+ throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
14076
14373
  } finally {
14077
14374
  copy.close();
14078
14375
  }
@@ -14083,6 +14380,7 @@ async function restorePublication(options) {
14083
14380
  closeSync11(fd);
14084
14381
  }
14085
14382
  }
14383
+ const files = [];
14086
14384
  for (const tree of manifest.trees) {
14087
14385
  const root = join21(destination, "trees", tree.id);
14088
14386
  directory2(root);
@@ -14090,27 +14388,26 @@ async function restorePublication(options) {
14090
14388
  for (const file of tree.files) {
14091
14389
  const path3 = join21(root, file.path);
14092
14390
  directory2(dirname12(path3));
14093
- await receiver.objects.restoreFile(file.content, path3);
14094
- chmodSync3(path3, file.mode);
14095
- const fd = openSync12(path3, "r+");
14096
- try {
14097
- fsyncSync7(fd);
14098
- } finally {
14099
- closeSync11(fd);
14100
- }
14391
+ files.push({ content: file.content, destination: path3, mode: file.mode });
14101
14392
  }
14102
14393
  }
14103
- const after = await receiver.status();
14394
+ try {
14395
+ await receiver.objects.restoreFiles(files);
14396
+ } catch (error) {
14397
+ if (error.code === "ENOENT") throw new Error("PUBLICATION_NOT_READY");
14398
+ throw error;
14399
+ }
14400
+ const after = await receiver.status(false);
14104
14401
  if (!after.dataReady || after.published?.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
14105
14402
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
14106
- if (!options.deferReceipt) writeFileSync13(join21(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
14403
+ if (!options.deferReceipt) writeFileSync12(join21(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
14107
14404
  await syncDirectory(destination);
14108
14405
  return status.published;
14109
14406
  }
14110
14407
 
14111
14408
  // src/continuity/lance-publication.ts
14112
14409
  import { createHash as createHash29 } from "node:crypto";
14113
- import { lstatSync as lstatSync16, readdirSync as readdirSync6, realpathSync as realpathSync13, mkdirSync as mkdirSync11, writeFileSync as writeFileSync14, openSync as openSync13, closeSync as closeSync12, fsyncSync as fsyncSync8, chmodSync as chmodSync4 } from "node:fs";
14410
+ import { lstatSync as lstatSync15, readdirSync as readdirSync5, realpathSync as realpathSync13, mkdirSync as mkdirSync11, writeFileSync as writeFileSync13, openSync as openSync13, closeSync as closeSync12, fsyncSync as fsyncSync8, chmodSync as chmodSync4 } from "node:fs";
14114
14411
  import { join as join22, resolve as resolve16, dirname as dirname13, relative as relative5 } from "node:path";
14115
14412
  import { createRequire as createRequire6 } from "node:module";
14116
14413
  var kinds2 = ["agent_case", "agent_skill", "atomic_fact", "episode", "foresight"];
@@ -14126,16 +14423,16 @@ function rowPath(kind, id2) {
14126
14423
  return `${kind}/rows/${sha6(id2)}.arrow`;
14127
14424
  }
14128
14425
  function assertSource(directory2) {
14129
- if (realpathSync13(directory2) !== directory2 || !lstatSync16(directory2).isDirectory()) throw new Error("SYMLINK_REFUSED");
14426
+ if (realpathSync13(directory2) !== directory2 || !lstatSync15(directory2).isDirectory()) throw new Error("SYMLINK_REFUSED");
14130
14427
  let count = 0;
14131
14428
  const signatures2 = [];
14132
14429
  const visit = (path3, depth) => {
14133
14430
  if (++count > 1e5 || depth > 128) throw new Error("LANCE_PUBLICATION_SOURCE_TOO_LARGE");
14134
- const info = lstatSync16(path3, { bigint: true });
14431
+ const info = lstatSync15(path3, { bigint: true });
14135
14432
  if (info.isSymbolicLink()) throw new Error("SYMLINK_REFUSED");
14136
14433
  if (!info.isDirectory() && !info.isFile()) throw new Error("LANCE_PUBLICATION_SPECIAL_FILE");
14137
14434
  signatures2.push([relative5(directory2, path3), ...[info.dev, info.ino, info.size, info.mode, info.mtimeNs, info.ctimeNs].map(String)]);
14138
- if (info.isDirectory()) for (const name of readdirSync6(path3).sort()) visit(join22(path3, name), depth + 1);
14435
+ if (info.isDirectory()) for (const name of readdirSync5(path3).sort()) visit(join22(path3, name), depth + 1);
14139
14436
  };
14140
14437
  visit(directory2, 0);
14141
14438
  return sha6(JSON.stringify(signatures2));
@@ -14166,9 +14463,9 @@ async function inspectLancePublication(directory2) {
14166
14463
  }
14167
14464
  function durablePrivateTree(directory2) {
14168
14465
  const visit = (path3) => {
14169
- const info = lstatSync16(path3);
14466
+ const info = lstatSync15(path3);
14170
14467
  if (info.isSymbolicLink() || !info.isDirectory() && !info.isFile()) throw new Error("SYMLINK_REFUSED");
14171
- if (info.isDirectory()) for (const name of readdirSync6(path3)) visit(join22(path3, name));
14468
+ if (info.isDirectory()) for (const name of readdirSync5(path3)) visit(join22(path3, name));
14172
14469
  chmodSync4(path3, info.isDirectory() ? 448 : 384);
14173
14470
  if (process.platform !== "win32" || info.isFile()) {
14174
14471
  const fd = openSync13(path3, "r");
@@ -14215,14 +14512,28 @@ async function captureLancePublication(options) {
14215
14512
  const batchTable = new arrow.Table(batch);
14216
14513
  for (let start = 0; start < batchTable.numRows; start += batchRows) {
14217
14514
  const page = batchTable.slice(start, start + batchRows);
14515
+ let pending = [], pendingBytes = 0;
14516
+ const flush = async () => {
14517
+ if (!pending.length) return;
14518
+ const contents = await options.objects.putContents(pending.map((row) => row.bytes));
14519
+ for (let i = 0; i < pending.length; i++) tree.files.push({ path: pending[i].path, mode: 384, content: contents[i] });
14520
+ pending = [];
14521
+ pendingBytes = 0;
14522
+ };
14218
14523
  for (let index = 0; index < page.numRows; index++) {
14219
14524
  const one = page.slice(index, index + 1), path3 = rowPath(kind, one.getChild("id").get(0));
14220
14525
  if (seen.has(path3)) throw new Error("LANCE_PUBLICATION_DUPLICATE_ROW");
14221
14526
  seen.add(path3);
14222
14527
  const bytes = arrow.tableToIPC(one, "stream");
14223
- if (bytes.length > ROW_BYTES || tree.files.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
14224
- tree.files.push({ path: path3, mode: 384, content: await options.objects.putContent(bytes) });
14528
+ if (bytes.length > ROW_BYTES || tree.files.length + pending.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
14529
+ if (pending.length === 128 || pendingBytes + bytes.length > 8 * 1024 * 1024) await flush();
14530
+ if (bytes.length > 8 * 1024 * 1024) tree.files.push({ path: path3, mode: 384, content: await options.objects.putContent(bytes) });
14531
+ else {
14532
+ pending.push({ path: path3, bytes });
14533
+ pendingBytes += bytes.length;
14534
+ }
14225
14535
  }
14536
+ await flush();
14226
14537
  }
14227
14538
  }
14228
14539
  if (seen.size !== total) throw new Error("LANCE_PUBLICATION_ROW_COUNT_MISMATCH");
@@ -14278,7 +14589,7 @@ async function restoreLancePublication(options) {
14278
14589
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
14279
14590
  throw error;
14280
14591
  }
14281
- writeFileSync14(join22(destination, ".travel-restored.json"), JSON.stringify({
14592
+ writeFileSync13(join22(destination, ".travel-restored.json"), JSON.stringify({
14282
14593
  format: "engine7-lance-logical-restore-v1",
14283
14594
  activationAllowed: false,
14284
14595
  identity: options.objects.identity,
@@ -14318,7 +14629,7 @@ async function restoreLancePublication(options) {
14318
14629
  connection.close();
14319
14630
  }
14320
14631
  durablePrivateTree(destination);
14321
- writeFileSync14(
14632
+ writeFileSync13(
14322
14633
  join22(destination, ".lance-receipt.json"),
14323
14634
  JSON.stringify({ format: manifest.format, tables: manifest.tables, activationAllowed: false }),
14324
14635
  { flag: "wx", mode: 384, flush: true }
@@ -14360,7 +14671,7 @@ async function admitOriginalLanceRow(options) {
14360
14671
  // src/continuity/runtime-publication-restore.ts
14361
14672
  init_sqlite_replication();
14362
14673
  async function restoreRuntimePublication(options) {
14363
- const { receiver } = options, status = await receiver.status();
14674
+ const { receiver } = options, status = await receiver.status(false);
14364
14675
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
14365
14676
  if (options.sequence !== void 0 && options.sequence !== status.published.sequence) throw new Error("PUBLICATION_STALE_PUBLICATION");
14366
14677
  const manifest = await receiver.manifest(status.published.sequence), destination = resolve17(options.destination);
@@ -14368,15 +14679,15 @@ async function restoreRuntimePublication(options) {
14368
14679
  for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "session")) {
14369
14680
  const tree = manifest.trees.find((tree2) => tree2.id === kind.id);
14370
14681
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
14371
- const metadata3 = JSON.parse((await receiver.objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
14372
- const database = manifest.databases.find((d) => d.databaseId === metadata3.databaseId);
14682
+ const metadata4 = JSON.parse((await receiver.objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
14683
+ const database = manifest.databases.find((d) => d.databaseId === metadata4.databaseId);
14373
14684
  const binding = normalizeBinding({
14374
14685
  ...manifest.profile.identity,
14375
- databaseId: metadata3.databaseId,
14686
+ databaseId: metadata4.databaseId,
14376
14687
  baselineId: manifest.profile.baselineId,
14377
14688
  epoch: manifest.profile.epoch
14378
14689
  });
14379
- 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");
14690
+ 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");
14380
14691
  sessions.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
14381
14692
  }
14382
14693
  await restorePublication({ ...options, destination, deferReceipt: true });
@@ -14403,17 +14714,17 @@ async function restoreRuntimePublication(options) {
14403
14714
  await syncDirectory(join23(destination, "sessions"));
14404
14715
  sessionStates.push({ treeId: session.treeId, databaseId: session.databaseId, directory: `sessions/${session.treeId}` });
14405
14716
  }
14406
- const after = await receiver.status();
14717
+ const after = await receiver.status(false);
14407
14718
  if (!after.dataReady || after.published?.sequence !== manifest.sequence || after.published.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
14408
- writeFileSync15(join23(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
14409
- writeFileSync15(join23(destination, ".runtime-publication-receipt.json"), JSON.stringify({
14719
+ writeFileSync14(join23(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
14720
+ writeFileSync14(join23(destination, ".runtime-publication-receipt.json"), JSON.stringify({
14410
14721
  format: "engine7-runtime-publication-restore-v1",
14411
14722
  profile: manifest.profile,
14412
14723
  receipt: status.published,
14413
14724
  databases: manifest.databases,
14414
14725
  lance,
14415
14726
  sessions: sessionStates,
14416
- integrity: runtimeGenerationIntegrity(destination),
14727
+ integrity: await runtimeGenerationIntegrityAsync(destination),
14417
14728
  activationAllowed: false
14418
14729
  }), { flag: "wx", mode: 384, flush: true });
14419
14730
  await syncDirectory(destination);
@@ -14425,14 +14736,14 @@ import { join as join27 } from "node:path";
14425
14736
 
14426
14737
  // src/continuity/runtime-generation-source.ts
14427
14738
  import { DatabaseSync as DatabaseSync20 } from "node:sqlite";
14428
- import { existsSync as existsSync13, lstatSync as lstatSync20, realpathSync as realpathSync16 } from "node:fs";
14739
+ import { existsSync as existsSync13, lstatSync as lstatSync19, realpathSync as realpathSync16 } from "node:fs";
14429
14740
  import { createHash as createHash34 } from "node:crypto";
14430
14741
  import { isAbsolute as isAbsolute5, join as join26, resolve as resolve22 } from "node:path";
14431
14742
 
14432
14743
  // src/continuity/runtime-tree-source.ts
14433
14744
  import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
14434
14745
  import { createHash as createHash30 } from "node:crypto";
14435
- import { existsSync as existsSync11, writeFileSync as writeFileSync16, openSync as openSync14, closeSync as closeSync13, fsyncSync as fsyncSync9 } from "node:fs";
14746
+ import { existsSync as existsSync11, writeFileSync as writeFileSync15, openSync as openSync14, closeSync as closeSync13, fsyncSync as fsyncSync9 } from "node:fs";
14436
14747
  import { join as join24, resolve as resolve18 } from "node:path";
14437
14748
  var ZERO2 = "0".repeat(64);
14438
14749
  var HASH3 = /^[a-f0-9]{64}$/;
@@ -14496,7 +14807,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
14496
14807
  this.db.exec("ROLLBACK");
14497
14808
  throw error;
14498
14809
  }
14499
- writeFileSync16(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
14810
+ writeFileSync15(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
14500
14811
  if (process.platform !== "win32") {
14501
14812
  const fd = openSync14(directory2, "r");
14502
14813
  try {
@@ -14614,21 +14925,22 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
14614
14925
  // src/continuity/runtime-publication-source.ts
14615
14926
  import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
14616
14927
  import { createHash as createHash33 } from "node:crypto";
14617
- import { existsSync as existsSync12, lstatSync as lstatSync19, writeFileSync as writeFileSync17, openSync as openSync15, closeSync as closeSync14, fsyncSync as fsyncSync10 } from "node:fs";
14928
+ import { existsSync as existsSync12, lstatSync as lstatSync18, writeFileSync as writeFileSync16, openSync as openSync15, closeSync as closeSync14, fsyncSync as fsyncSync10 } from "node:fs";
14618
14929
  import { join as join25, resolve as resolve21 } from "node:path";
14619
14930
 
14620
14931
  // src/continuity/runtime-h-capture.ts
14621
14932
  import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
14622
14933
  import { createHash as createHash32 } from "node:crypto";
14623
- import { lstatSync as lstatSync18, realpathSync as realpathSync15 } from "node:fs";
14934
+ import { lstatSync as lstatSync17, realpathSync as realpathSync15 } from "node:fs";
14624
14935
  import { resolve as resolve20, relative as relative7 } from "node:path";
14625
14936
 
14626
14937
  // src/continuity/runtime-files.ts
14627
- import { lstatSync as lstatSync17, realpathSync as realpathSync14 } from "node:fs";
14938
+ import { lstatSync as lstatSync16, realpathSync as realpathSync14 } from "node:fs";
14628
14939
  import { relative as relative6, resolve as resolve19 } from "node:path";
14629
14940
  import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
14630
14941
  import { createHash as createHash31 } from "node:crypto";
14631
14942
  init_runtime_replication();
14943
+ import { setImmediate as setImmediate2 } from "node:timers/promises";
14632
14944
  async function runtimeFileEntries(options) {
14633
14945
  const state2 = resolve19(options.inventory.stateDir), workspace = resolve19(options.inventory.workspace ?? state2 + "/workspace");
14634
14946
  if (realpathSync14(state2) !== state2 || realpathSync14(workspace) !== workspace) throw new Error("SYMLINK_REFUSED");
@@ -14641,7 +14953,7 @@ async function runtimeFileEntries(options) {
14641
14953
  excludeWorkspaceEntries: { ...options.inventory.excludeWorkspaceEntries }
14642
14954
  };
14643
14955
  for (const directory2 of [...options.vectorDirectories, ...options.sessionDirectories].map(resolvePath)) {
14644
- const info = lstatSync17(directory2);
14956
+ const info = lstatSync16(directory2);
14645
14957
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync14(directory2) !== directory2) throw new Error("SYMLINK_REFUSED");
14646
14958
  const root = isWithin(workspace, directory2) ? "workspace" : isWithin(state2, directory2) ? "state" : void 0;
14647
14959
  if (!root || directory2 === state2 || directory2 === workspace) throw new Error("RUNTIME_FILE_PATH_OUTSIDE_ROOT");
@@ -14683,10 +14995,26 @@ async function captureRuntimeFiles(options) {
14683
14995
  { id: options.workspaceTreeId, files: [], directories: [] }
14684
14996
  ];
14685
14997
  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");
14686
- for (const entry of before) {
14998
+ const files = before.filter((entry) => entry.kind !== "directory");
14999
+ const progress = { completedFiles: 0, totalFiles: files.length, completedBytes: 0, totalBytes: files.reduce((n, e) => n + e.bytes, 0) };
15000
+ options.onProgress?.({ ...progress });
15001
+ for (const entry of before.filter((entry2) => entry2.kind === "directory")) {
14687
15002
  const tree = trees[entry.root === "state" ? 0 : 1];
14688
- if (entry.kind === "directory") tree.directories.push(entry.path);
14689
- else tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content: await options.objects.captureFile(entry.source) });
15003
+ tree.directories.push(entry.path);
15004
+ }
15005
+ for (let offset = 0; offset < files.length; offset += 32) {
15006
+ const batch = files.slice(offset, offset + 32);
15007
+ const bytesBefore = progress.completedBytes;
15008
+ const contents = await options.objects.captureFiles(batch.map((entry) => entry.source), (value2) => {
15009
+ progress.completedFiles = offset + value2.completedFiles;
15010
+ progress.completedBytes = bytesBefore + value2.completedBytes;
15011
+ options.onProgress?.({ ...progress });
15012
+ });
15013
+ for (const [index, entry] of batch.entries()) {
15014
+ const tree = trees[entry.root === "state" ? 0 : 1], content = contents[index];
15015
+ tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content });
15016
+ }
15017
+ await setImmediate2();
14690
15018
  }
14691
15019
  if (JSON.stringify(signatures(before)) !== JSON.stringify(signatures(await runtimeFileEntries(options)))) throw new Error("PUBLICATION_SOURCE_CHANGED");
14692
15020
  return trees;
@@ -14705,7 +15033,7 @@ async function captureRuntimeH(input) {
14705
15033
  }
14706
15034
  function assertStoppedSourceRoot(root) {
14707
15035
  try {
14708
- lstatSync18(resolve20(root, ".travel-restored.json"));
15036
+ lstatSync17(resolve20(root, ".travel-restored.json"));
14709
15037
  throw new Error("TRAVEL_ACTIVATION_REQUIRED");
14710
15038
  } catch (error) {
14711
15039
  if (error.code !== "ENOENT") throw error;
@@ -14767,7 +15095,7 @@ async function capture(input, assertRoot) {
14767
15095
  throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
14768
15096
  const observe = async () => {
14769
15097
  const heads = profile.databaseIds.map((databaseId) => {
14770
- const d = databases[databaseId], place = sqliteStoreLocation(d.file), info = lstatSync18(d.file);
15098
+ const d = databases[databaseId], place = sqliteStoreLocation(d.file), info = lstatSync17(d.file);
14771
15099
  if (!place || !isWithin(state2, place.stateDir) || !info.isFile() || info.isSymbolicLink() || realpathSync15(d.file) !== d.file)
14772
15100
  throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
14773
15101
  if (process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
@@ -14802,9 +15130,9 @@ async function capture(input, assertRoot) {
14802
15130
  }
14803
15131
  for (const s of sessionTrees) {
14804
15132
  const head = before.heads.find((d) => d.databaseId === s.databaseId).head;
14805
- const metadata3 = { format: "engine7-session-events-publication-v1", databaseId: s.databaseId, binding: databases[s.databaseId].source.binding, head };
14806
- trees.push({ id: s.treeId, directories: [], files: [{ path: "manifest.json", mode: 384, content: await objects.putContent(Buffer.from(JSON.stringify(metadata3))) }] });
14807
- origins[s.treeId] = metadata3;
15133
+ const metadata4 = { format: "engine7-session-events-publication-v1", databaseId: s.databaseId, binding: databases[s.databaseId].source.binding, head };
15134
+ trees.push({ id: s.treeId, directories: [], files: [{ path: "manifest.json", mode: 384, content: await objects.putContent(Buffer.from(JSON.stringify(metadata4))) }] });
15135
+ origins[s.treeId] = metadata4;
14808
15136
  }
14809
15137
  if (!same5(before, await observe())) throw new Error("PUBLICATION_SOURCE_CHANGED");
14810
15138
  return {
@@ -14834,7 +15162,7 @@ var same6 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
14834
15162
  var sha8 = (body) => createHash33("sha256").update(body).digest("hex");
14835
15163
  var stateHash = (m) => sha8(JSON.stringify([m.databases, m.trees, m.deletionWatermark]));
14836
15164
  var incarnation2 = (file) => {
14837
- const s = lstatSync19(file);
15165
+ const s = lstatSync18(file);
14838
15166
  if (s.isSymbolicLink() || !s.isFile()) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
14839
15167
  return `${s.dev}:${s.ino}`;
14840
15168
  };
@@ -14897,7 +15225,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14897
15225
  }
14898
15226
  sender.exec(senderSchema);
14899
15227
  sender.prepare("INSERT INTO sender VALUES(1,?,?)").run(JSON.stringify(this.profile), this.layoutDigest);
14900
- writeFileSync17(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
15228
+ writeFileSync16(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
14901
15229
  if (process.platform !== "win32") {
14902
15230
  const fd = openSync15(this.directory, "r");
14903
15231
  try {
@@ -14926,7 +15254,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14926
15254
  static async open(options) {
14927
15255
  const source = new _RuntimePublicationSource(options);
14928
15256
  try {
14929
- if (source.head().sequence) await source.read(source.head().sequence);
15257
+ if (source.head().sequence) await source.readManifest(source.head().sequence);
14930
15258
  return source;
14931
15259
  } catch (error) {
14932
15260
  source.close();
@@ -14977,6 +15305,15 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14977
15305
  };
14978
15306
  }
14979
15307
  async read(sequence) {
15308
+ return this.readPrepared(sequence, true);
15309
+ }
15310
+ /** Ancestry uses authenticated H metadata; payload availability is checked
15311
+ * when actual objects are transferred or restored, not for every old H. */
15312
+ async readManifest(sequence) {
15313
+ const { digest: digest7, manifest } = await this.readPrepared(sequence, false);
15314
+ return { digest: digest7, manifest };
15315
+ }
15316
+ async readPrepared(sequence, verifyDependencies) {
14980
15317
  const row = this.entry(sequence), ref = JSON.parse(row.content);
14981
15318
  validateFileContent(ref);
14982
15319
  const manifest = normalizePublication(JSON.parse((await this.objects.readContent(ref, PUBLICATION_MANIFEST_BYTES)).toString()));
@@ -14984,7 +15321,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14984
15321
  if (manifest.sequence !== sequence || !same6(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");
14985
15322
  const dependencies2 = JSON.parse(row.dependencies);
14986
15323
  if (!Array.isArray(dependencies2) || !same6(dependencies2.map((d) => d.treeId).sort(), this.profile.trees.map((t) => t.id))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
14987
- for (const d of dependencies2) {
15324
+ if (verifyDependencies) for (const d of dependencies2) {
14988
15325
  const tree = await this.trees.read(d.treeId, d.sequence);
14989
15326
  if (tree.digest !== d.digest || !same6(tree.tree, manifest.trees.find((t) => t.id === d.treeId))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
14990
15327
  }
@@ -14997,12 +15334,18 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14997
15334
  async prepare(options) {
14998
15335
  return this.prepareCapture(options, () => captureRuntimeH(options));
14999
15336
  }
15337
+ /** A first full baseline already lives in the bounded encrypted object store
15338
+ * and native SQLite snapshots. Only its envelope occupies the increment queue. */
15339
+ async prepareInitial(options) {
15340
+ if (this.control().head !== 0) throw new Error("RUNTIME_PUBLICATION_INITIAL_ALREADY_PREPARED");
15341
+ return this.prepareCapture(options, () => captureRuntimeH(options), true);
15342
+ }
15000
15343
  /** The source business stores stay read-only and writer exclusion remains
15001
15344
  * held until the caller durably seals its backup and archive receipt. */
15002
15345
  async withStoppedPreparation(options, operation) {
15003
15346
  return withStoppedRuntimeH(options, async (parts) => operation(await this.prepareCapture(options, async () => parts)));
15004
15347
  }
15005
- async prepareCapture(options, capture2) {
15348
+ async prepareCapture(options, capture2, initial = false) {
15006
15349
  const c = this.control(), pending = this.status();
15007
15350
  if (!same6(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
15008
15351
  if (pending.pendingCheckpoints >= this.maximumPendingCheckpoints || pending.pendingBytes >= this.maximumPendingBytes) throw new Error("RUNTIME_PUBLICATION_QUEUE_FULL");
@@ -15034,11 +15377,11 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
15034
15377
  for (const tree of prepared.manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) known.add(ref.sha256);
15035
15378
  }
15036
15379
  let bytes = encoded.length + Buffer.byteLength(JSON.stringify(dependencies2));
15037
- for (const tree of manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) if (!known.has(ref.sha256)) {
15380
+ 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)) {
15038
15381
  known.add(ref.sha256);
15039
15382
  bytes += ref.bytes;
15040
15383
  }
15041
- for (const d of manifest.databases) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
15384
+ for (const d of manifest.databases) if (!initial) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
15042
15385
  old?.manifest.databases.find((previous) => previous.databaseId === d.databaseId).head.sequence ?? 0,
15043
15386
  d.head.sequence
15044
15387
  );
@@ -15196,7 +15539,7 @@ async function openRuntimeGenerationSource(options) {
15196
15539
  for (const id2 of profile.databaseIds) {
15197
15540
  const path3 = layout.databases[id2];
15198
15541
  validatePublicationPath(path3);
15199
- const file = join26(stateDir, path3), place = sqliteStoreLocation(file), info = lstatSync20(file);
15542
+ const file = join26(stateDir, path3), place = sqliteStoreLocation(file), info = lstatSync19(file);
15200
15543
  if (!place || !isWithin(stateDir, place.stateDir) || !info.isFile() || info.isSymbolicLink() || realpathSync16(file) !== file || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("TRAVEL_SOURCE_LAYOUT");
15201
15544
  const db = new DatabaseSync20(file, { readOnly: options.mode === "SEALED", allowExtension: options.mode === "LIVE" && place.component === "legacy-memory" });
15202
15545
  handles[id2] = db;
@@ -15235,7 +15578,7 @@ async function openRuntimeGenerationSource(options) {
15235
15578
  lanceStores,
15236
15579
  deletionWatermark: runtime.deletionFloor(),
15237
15580
  files: {
15238
- inventory: { stateDir, workspace, includeStateEntries: layout.includedStateEntries },
15581
+ inventory: { stateDir, workspace, selection: layout.inventorySelection, includeStateEntries: layout.includedStateEntries },
15239
15582
  objects: options.objects,
15240
15583
  databaseFiles: Object.values(databases).map((db) => db.file),
15241
15584
  immutableDatabaseFiles: (layout.immutableDatabases ?? []).map((path3) => {
@@ -15302,14 +15645,14 @@ async function readStoppedRecoveryManifests(options) {
15302
15645
  await Promise.all([options.assertAvailable(), checkRecoveryDeletionAsync(local.manifest, options.deletionWatermark)]);
15303
15646
  };
15304
15647
  await check();
15305
- const common = await opened.source.read(options.common.sequence);
15648
+ const common = await opened.source.readManifest(options.common.sequence);
15306
15649
  await check();
15307
15650
  if (common.digest !== options.common.digest) throw new Error("RECOVERY_LOCAL_ANCESTRY_GAP");
15308
15651
  let parent = common.digest, bytes = 0;
15309
15652
  const manifests = [];
15310
15653
  const last = options.maximum === void 0 ? local.manifest.sequence : Math.min(local.manifest.sequence, options.common.sequence + options.maximum);
15311
15654
  for (let sequence = options.common.sequence + 1; sequence <= last; sequence++) {
15312
- const original = await opened.source.read(sequence);
15655
+ const original = await opened.source.readManifest(sequence);
15313
15656
  await check();
15314
15657
  if (original.manifest.parentDigest !== parent) throw new Error("RECOVERY_LOCAL_ANCESTRY_GAP");
15315
15658
  parent = original.digest;
@@ -15464,6 +15807,7 @@ function startTravelHeartbeatReporting(options) {
15464
15807
  })().catch((error) => {
15465
15808
  lastError = error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_REPORTING_UNAVAILABLE";
15466
15809
  if (lastError !== "TRAVEL_REPORTING_UNAVAILABLE" && lastError !== "TRAVEL_CONTROL_UNAVAILABLE" && lastError !== "TRAVEL_CONTROL_BUSY") {
15810
+ process.stderr.write("[travel-control] " + JSON.stringify({ nodeId: options.nodeId, phase: "revoke", error: lastError }) + "\n");
15467
15811
  try {
15468
15812
  options.runtime()?.revoke();
15469
15813
  } catch {
@@ -15543,7 +15887,7 @@ function startTravelHeartbeatReporting(options) {
15543
15887
 
15544
15888
  // src/continuity/recovery-archive-restore.ts
15545
15889
  import { DatabaseSync as DatabaseSync22 } from "node:sqlite";
15546
- import { mkdirSync as mkdirSync13, writeFileSync as writeFileSync18, chmodSync as chmodSync5, realpathSync as realpathSync17 } from "node:fs";
15890
+ import { mkdirSync as mkdirSync13, writeFileSync as writeFileSync17, realpathSync as realpathSync17 } from "node:fs";
15547
15891
  import { dirname as dirname14, join as join29, resolve as resolve23 } from "node:path";
15548
15892
  init_sqlite_replication();
15549
15893
  async function restoreRecoveryArchive(options) {
@@ -15569,7 +15913,7 @@ async function restoreOriginal(options, original, currentHCheck) {
15569
15913
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
15570
15914
  throw error;
15571
15915
  }
15572
- writeFileSync18(join29(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
15916
+ writeFileSync17(join29(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
15573
15917
  await syncDirectory(dirname14(destination));
15574
15918
  await syncDirectory(destination);
15575
15919
  const created = /* @__PURE__ */ new Set([destination]);
@@ -15583,29 +15927,28 @@ async function restoreOriginal(options, original, currentHCheck) {
15583
15927
  };
15584
15928
  directory2(join29(destination, "databases"));
15585
15929
  directory2(join29(destination, "trees"));
15930
+ await objects.restoreFiles(entry.databases.map((d) => ({ content: d.content, destination: join29(destination, "databases", d.databaseId + ".sqlite") })));
15586
15931
  for (const d of entry.databases) {
15587
- floor = await verify3();
15588
15932
  const path3 = join29(destination, "databases", d.databaseId + ".sqlite");
15589
- await objects.restoreFile(d.content, path3);
15590
15933
  const db = new DatabaseSync22(path3, { readOnly: true });
15591
15934
  try {
15592
- validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash);
15935
+ validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash, options.verifyDatabases !== false);
15593
15936
  } finally {
15594
15937
  db.close();
15595
15938
  }
15596
15939
  }
15940
+ const files = [];
15597
15941
  for (const tree of manifest.trees) {
15598
15942
  const root = join29(destination, "trees", tree.id);
15599
15943
  directory2(root);
15600
15944
  for (const path3 of tree.directories) directory2(join29(root, path3));
15601
15945
  for (const file of tree.files) {
15602
- floor = await verify3();
15603
15946
  const path3 = join29(root, file.path);
15604
15947
  directory2(dirname14(path3));
15605
- await objects.restoreFile(file.content, path3);
15606
- chmodSync5(path3, file.mode);
15948
+ files.push({ content: file.content, destination: path3, mode: file.mode });
15607
15949
  }
15608
15950
  }
15951
+ await objects.restoreFiles(files);
15609
15952
  directory2(join29(destination, "lance"));
15610
15953
  directory2(join29(destination, "sessions"));
15611
15954
  for (const kind of manifest.profile.trees) {
@@ -15613,10 +15956,10 @@ async function restoreOriginal(options, original, currentHCheck) {
15613
15956
  if (kind.kind === "vector") await restoreLancePublication({ tree, objects, destination: join29(destination, "lance", tree.id) });
15614
15957
  if (kind.kind === "session") {
15615
15958
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
15616
- const metadata3 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
15617
- const d = entry.databases.find((d2) => d2.databaseId === metadata3.databaseId);
15618
- const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata3.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
15619
- 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");
15959
+ const metadata4 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
15960
+ const d = entry.databases.find((d2) => d2.databaseId === metadata4.databaseId);
15961
+ const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata4.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
15962
+ 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");
15620
15963
  const db = new DatabaseSync22(join29(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
15621
15964
  try {
15622
15965
  await restoreSessionEvents({ db, binding, destination: join29(destination, "sessions", tree.id), replicationRole: d.role });
@@ -15624,11 +15967,10 @@ async function restoreOriginal(options, original, currentHCheck) {
15624
15967
  db.close();
15625
15968
  }
15626
15969
  }
15627
- floor = await verify3();
15628
15970
  }
15629
15971
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
15630
15972
  await verify3();
15631
- writeFileSync18(join29(destination, ".recovery-archive-receipt.json"), JSON.stringify(entry.receipt), { mode: 384, flag: "wx", flush: true });
15973
+ writeFileSync17(join29(destination, ".recovery-archive-receipt.json"), JSON.stringify(entry.receipt), { mode: 384, flag: "wx", flush: true });
15632
15974
  await syncDirectory(destination);
15633
15975
  await verify3();
15634
15976
  return entry.receipt;
@@ -15636,14 +15978,14 @@ async function restoreOriginal(options, original, currentHCheck) {
15636
15978
 
15637
15979
  // src/continuity/runtime-checkpoints.ts
15638
15980
  import { DatabaseSync as DatabaseSync23 } from "node:sqlite";
15639
- import { existsSync as existsSync14, lstatSync as lstatSync21, writeFileSync as writeFileSync19 } from "node:fs";
15981
+ import { existsSync as existsSync14, lstatSync as lstatSync20, writeFileSync as writeFileSync18 } from "node:fs";
15640
15982
  import { join as join30 } from "node:path";
15641
15983
  var zero = "0".repeat(64);
15642
15984
  var format3 = "engine7-runtime-checkpoint-control-v1";
15643
15985
  var hash7 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
15644
15986
  var natural3 = (value2) => typeof value2 === "number" && Number.isSafeInteger(value2) && value2 >= 0;
15645
15987
  var incarnation3 = (file) => {
15646
- const stat = lstatSync21(file, { bigint: true });
15988
+ const stat = lstatSync20(file, { bigint: true });
15647
15989
  return `${stat.dev}:${stat.ino}`;
15648
15990
  };
15649
15991
  var RuntimeCheckpointControl = class {
@@ -15656,7 +15998,7 @@ var RuntimeCheckpointControl = class {
15656
15998
  this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file) => join30(options.directory, file));
15657
15999
  const presence = this.files.map(existsSync14), fresh = presence.every((value2) => !value2);
15658
16000
  if (fresh && options.initialize !== true || !fresh && !presence.every(Boolean)) throw new Error("TRAVEL_CHECKPOINT_RECOVERY_REQUIRED");
15659
- if (fresh) writeFileSync19(this.files[0], JSON.stringify({ format: format3, binding: this.binding }), { mode: 384, flag: "wx", flush: true });
16001
+ if (fresh) writeFileSync18(this.files[0], JSON.stringify({ format: format3, binding: this.binding }), { mode: 384, flag: "wx", flush: true });
15660
16002
  const marker = JSON.parse(readPrivateFile2(this.files[0], 65536).toString());
15661
16003
  if (marker.format !== format3 || marker.binding !== this.binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
15662
16004
  preparePrivateDatabase(this.files[1]);
@@ -15713,7 +16055,6 @@ var RuntimeCheckpointControl = class {
15713
16055
  }
15714
16056
  async round(input) {
15715
16057
  const progress = this.status(), permit = this.permit();
15716
- await this.options.authority.assertPermit(permit, "PUBLISH");
15717
16058
  if (!input || JSON.stringify(normalizePublicationProfile(input.profile)) !== JSON.stringify(this.profile) || !input.acknowledged || !natural3(input.acknowledged.sequence) || !hash7(input.acknowledged.digest) || input.acknowledged.sequence < progress.sequence || !Array.isArray(input.checkpoints) || input.checkpoints.length > 64) throw new Error("TRAVEL_CHECKPOINT_CHAIN");
15718
16059
  let sequence = progress.sequence, digest7 = progress.digest;
15719
16060
  for (const checkpoint of input.checkpoints) {
@@ -15745,11 +16086,28 @@ var RuntimeCheckpointControl = class {
15745
16086
 
15746
16087
  // src/continuity/recovery-archive-transfer.ts
15747
16088
  import { Agent, createServer, request as request2 } from "node:https";
16089
+ import { gzipSync, gunzipSync as gunzipSync3, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants12 } from "node:zlib";
16090
+ import { pipeline } from "node:stream";
16091
+ import { pipeline as pipelineAsync } from "node:stream/promises";
15748
16092
  var endpoint = "/travel/archives/v1";
15749
- var metadataLimit = 16 * 1024 * 1024;
16093
+ var metadataLimit = RECOVERY_ARCHIVE_METADATA_BYTES;
15750
16094
  var requestLimit = 65536;
15751
16095
  var objectGroupLimit = 8;
15752
16096
  var partBodyLimit = 65536;
16097
+ var streamRefLimit = 512;
16098
+ var streamBatchBytes = 8 * 1024 * 1024;
16099
+ var streamBatchObjects = 128;
16100
+ var brotliOptions = { params: { [constants12.BROTLI_PARAM_QUALITY]: 4, [constants12.BROTLI_PARAM_LGWIN]: 22 } };
16101
+ function validateStreamRefs(value2) {
16102
+ if (!Array.isArray(value2) || value2.length < 1 || value2.length > streamRefLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
16103
+ const seen = /* @__PURE__ */ new Set();
16104
+ for (const ref of value2) {
16105
+ validateObjectRef(ref);
16106
+ if (Object.keys(ref).length !== 2 || seen.has(ref.sha256)) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
16107
+ seen.add(ref.sha256);
16108
+ }
16109
+ return value2;
16110
+ }
15753
16111
  var validId = (id2) => typeof id2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id2);
15754
16112
  function validateObjectParts(value2) {
15755
16113
  if (!Array.isArray(value2) || value2.length < 1 || value2.length > objectGroupLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
@@ -15824,7 +16182,7 @@ function refs(entry) {
15824
16182
  return result;
15825
16183
  }
15826
16184
  function createRecoveryArchiveServer(options) {
15827
- const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, ...tls2 } = options;
16185
+ const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, streaming = true, ...tls2 } = options;
15828
16186
  if (!identity || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
15829
16187
  if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
15830
16188
  const peers = new Map(Object.entries(allowedPeers).map(([fingerprint, credential]) => [fingerprint.replaceAll(":", "").toLowerCase(), credential]));
@@ -15833,6 +16191,7 @@ function createRecoveryArchiveServer(options) {
15833
16191
  const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
15834
16192
  const started = Date.now(), timings = {};
15835
16193
  let phase = "authenticate", action = "unknown", failure;
16194
+ let streamStats;
15836
16195
  const mark = (next) => {
15837
16196
  timings[phase] = Date.now() - started;
15838
16197
  phase = next;
@@ -15840,6 +16199,10 @@ function createRecoveryArchiveServer(options) {
15840
16199
  res.setHeader("Cache-Control", "no-store");
15841
16200
  const refuse = (status, error) => {
15842
16201
  if (!res.writableEnded && !res.destroyed) {
16202
+ if (res.headersSent) {
16203
+ res.destroy();
16204
+ return;
16205
+ }
15843
16206
  res.statusCode = status;
15844
16207
  res.setHeader("Content-Type", "application/json");
15845
16208
  res.end(JSON.stringify({ error }));
@@ -15877,6 +16240,11 @@ function createRecoveryArchiveServer(options) {
15877
16240
  const slot = { archiveDigest };
15878
16241
  slots.add(slot);
15879
16242
  busy.set(fingerprint, slots);
16243
+ const releaseSlot = () => {
16244
+ slots.delete(slot);
16245
+ if (!slots.size && busy.get(fingerprint) === slots) busy.delete(fingerprint);
16246
+ };
16247
+ res.once("close", releaseSlot);
15880
16248
  mark("body");
15881
16249
  const timer = setTimeout(() => {
15882
16250
  refuse(408, "RECOVERY_TRANSFER_REFUSED");
@@ -15892,8 +16260,8 @@ function createRecoveryArchiveServer(options) {
15892
16260
  }
15893
16261
  clearTimeout(timer);
15894
16262
  const input = JSON.parse(Buffer.concat(chunks).toString());
15895
- if (archiveDigest && input?.action !== "parts") throw new Error();
15896
- action = ["list", "read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
16263
+ if (archiveDigest && !["parts", "stream"].includes(input?.action)) throw new Error();
16264
+ action = ["list", "read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
15897
16265
  mark("resolve");
15898
16266
  if (input?.version === 1 && input.action === "list") {
15899
16267
  if (Object.keys(input).some((key2) => !["version", "action"].includes(key2))) throw new Error();
@@ -15908,8 +16276,8 @@ function createRecoveryArchiveServer(options) {
15908
16276
  return;
15909
16277
  }
15910
16278
  const ancestry = ["manifests", "manifest-page"].includes(input?.action), paged = input?.action === "manifest-page";
15911
- if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key2) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : input.action === "objects" ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key2))) throw new Error();
15912
- await Promise.all([assertAvailable(), authority.status(principal)]);
16279
+ if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key2) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : ["objects", "stream"].includes(input.action) ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key2))) throw new Error();
16280
+ await assertAvailable();
15913
16281
  if (ancestry && !validCommon(input.common)) throw new Error();
15914
16282
  const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
15915
16283
  const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
@@ -15925,6 +16293,111 @@ function createRecoveryArchiveServer(options) {
15925
16293
  const floor = (await authority.status(principal)).deletionWatermark;
15926
16294
  await checkRecoveryDeletionAsync(entry.manifest, () => floor);
15927
16295
  mark("content");
16296
+ if (input.action === "stream") {
16297
+ if (!streaming || !archiveDigest) throw new Error();
16298
+ const requested = validateStreamRefs(input.refs), allowed = refs(entry);
16299
+ if (requested.some((ref) => allowed.get(ref.sha256)?.bytes !== ref.bytes)) throw new Error();
16300
+ let currentFloor = floor;
16301
+ const check = async () => {
16302
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
16303
+ const [control3] = await Promise.all([authority.status(principal), assertAvailable()]);
16304
+ currentFloor = await checkRecoveryDeletionAsync(entry.manifest, () => control3.deletionWatermark, currentFloor);
16305
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
16306
+ };
16307
+ const accepted2 = String(req.headers["accept-encoding"] ?? "").split(",").map((value2) => value2.trim());
16308
+ const encoding2 = accepted2.includes("br") ? "br" : accepted2.includes("gzip") ? "gzip" : void 0;
16309
+ streamStats = { encoding: encoding2 ?? "identity", objects: requested.length, batches: 0, rawBytes: 0, wireBytes: 0, readMs: 0, controlMs: 0, encodeAndWriteMs: 0 };
16310
+ const encoder = encoding2 === "br" ? createBrotliCompress(brotliOptions) : void 0, output = encoder ?? res;
16311
+ encoder?.on("data", (body2) => {
16312
+ streamStats.wireBytes += body2.length;
16313
+ });
16314
+ const streamed = encoder ? pipelineAsync(encoder, res) : void 0;
16315
+ void streamed?.catch(() => {
16316
+ });
16317
+ const write = (body2) => new Promise((resolve30, reject) => {
16318
+ if (res.destroyed || output.destroyed) {
16319
+ reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
16320
+ return;
16321
+ }
16322
+ if (!encoder) streamStats.wireBytes += body2.length;
16323
+ if (output.write(body2)) {
16324
+ resolve30();
16325
+ return;
16326
+ }
16327
+ const cleanup = () => {
16328
+ output.off("drain", drain);
16329
+ output.off("close", closed);
16330
+ output.off("error", closed);
16331
+ };
16332
+ const drain = () => {
16333
+ cleanup();
16334
+ resolve30();
16335
+ }, closed = () => {
16336
+ cleanup();
16337
+ reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
16338
+ };
16339
+ output.once("drain", drain);
16340
+ output.once("close", closed);
16341
+ output.once("error", closed);
16342
+ });
16343
+ res.setHeader("Content-Type", "application/octet-stream");
16344
+ if (encoding2) {
16345
+ res.setHeader("Content-Encoding", encoding2);
16346
+ res.setHeader("Vary", "Accept-Encoding");
16347
+ }
16348
+ try {
16349
+ for (let offset = 0; offset < requested.length; ) {
16350
+ let end = offset, bytes2 = 0;
16351
+ while (end < requested.length && end - offset < streamBatchObjects && bytes2 + requested[end].bytes <= streamBatchBytes) {
16352
+ bytes2 += requested[end].bytes;
16353
+ end++;
16354
+ }
16355
+ if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
16356
+ let step = Date.now();
16357
+ const results = await Promise.allSettled(requested.slice(offset, end).map((ref) => archive.objects.read(ref)));
16358
+ for (const result of results) if (result.status === "rejected") throw result.reason;
16359
+ streamStats.readMs += Date.now() - step;
16360
+ step = Date.now();
16361
+ await check();
16362
+ streamStats.controlMs += Date.now() - step;
16363
+ step = Date.now();
16364
+ const bodies = results.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
16365
+ if (encoder) {
16366
+ await write(Buffer.concat(bodies));
16367
+ await new Promise((resolve30, reject) => {
16368
+ const cleanup = () => {
16369
+ encoder.off("error", failed);
16370
+ encoder.off("close", closed);
16371
+ };
16372
+ const failed = (error) => {
16373
+ cleanup();
16374
+ reject(error);
16375
+ }, closed = () => failed(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
16376
+ encoder.once("error", failed);
16377
+ encoder.once("close", closed);
16378
+ encoder.flush(constants12.BROTLI_OPERATION_FLUSH, () => {
16379
+ cleanup();
16380
+ resolve30();
16381
+ });
16382
+ });
16383
+ } else if (encoding2 === "gzip") await write(gzipSync(Buffer.concat(bodies), { level: 1 }));
16384
+ else for (const body2 of bodies) await write(body2);
16385
+ streamStats.encodeAndWriteMs += Date.now() - step;
16386
+ streamStats.rawBytes += bytes2;
16387
+ streamStats.batches++;
16388
+ offset = end;
16389
+ }
16390
+ await check();
16391
+ mark("reply");
16392
+ if (encoder) {
16393
+ encoder.end();
16394
+ await streamed;
16395
+ } else res.end();
16396
+ return;
16397
+ } finally {
16398
+ encoder?.destroy();
16399
+ }
16400
+ }
15928
16401
  let body;
15929
16402
  if (ancestry) {
15930
16403
  if (!evidence && !readManifests || entry.kind !== "LOCAL") throw new Error();
@@ -15945,6 +16418,7 @@ function createRecoveryArchiveServer(options) {
15945
16418
  body = Buffer.from(JSON.stringify(entry));
15946
16419
  if (body.length > metadataLimit) throw new Error();
15947
16420
  res.setHeader("Content-Type", "application/json");
16421
+ if (streaming) res.setHeader("X-Engine7-Recovery-Stream", "1");
15948
16422
  } else if (input.action === "parts") {
15949
16423
  const group = validateObjectParts(input.parts), allowed = refs(entry), parts = [];
15950
16424
  if (group.some((part) => allowed.get(part.ref.sha256)?.bytes !== part.ref.bytes)) throw new Error();
@@ -15971,6 +16445,16 @@ function createRecoveryArchiveServer(options) {
15971
16445
  const [control2] = await Promise.all([authority.status(principal), assertAvailable()]), latest = control2.deletionWatermark;
15972
16446
  await checkRecoveryDeletionAsync(entry.manifest, () => latest, floor);
15973
16447
  mark("reply");
16448
+ const accepted = String(req.headers["accept-encoding"] ?? "").split(",").map((value2) => value2.trim());
16449
+ const encoding = accepted.includes("br") ? "br" : accepted.includes("gzip") ? "gzip" : void 0;
16450
+ if (encoding) {
16451
+ const compressed = encoding === "br" ? brotliCompressSync(body, brotliOptions) : gzipSync(body, { level: 1 });
16452
+ if (res.getHeader("Content-Type") === "application/json" || compressed.length < body.length) {
16453
+ body = compressed;
16454
+ res.setHeader("Content-Encoding", encoding);
16455
+ res.setHeader("Vary", "Accept-Encoding");
16456
+ }
16457
+ }
15974
16458
  res.setHeader("Content-Length", body.length);
15975
16459
  res.end(body);
15976
16460
  } catch (error) {
@@ -15978,9 +16462,8 @@ function createRecoveryArchiveServer(options) {
15978
16462
  refuse(409, "RECOVERY_TRANSFER_REFUSED");
15979
16463
  } finally {
15980
16464
  clearTimeout(timer);
15981
- slots.delete(slot);
15982
- if (!slots.size) busy.delete(fingerprint);
15983
- if (failure || Date.now() - started >= 5e3) process.stderr.write("[travel-archive] " + JSON.stringify({ at: Date.now(), action, phase, elapsedMs: Date.now() - started, timings, failure }) + "\n");
16465
+ releaseSlot();
16466
+ if (failure || Date.now() - started >= 5e3) process.stderr.write("[travel-archive] " + JSON.stringify({ at: Date.now(), action, phase, elapsedMs: Date.now() - started, timings, stream: streamStats, failure }) + "\n");
15984
16467
  }
15985
16468
  });
15986
16469
  server.headersTimeout = 5e3;
@@ -15998,6 +16481,7 @@ var RecoveryArchiveClient = class {
15998
16481
  key;
15999
16482
  timeout;
16000
16483
  pending = /* @__PURE__ */ new Map();
16484
+ streamAvailable = false;
16001
16485
  closed = false;
16002
16486
  constructor(options) {
16003
16487
  try {
@@ -16045,6 +16529,7 @@ var RecoveryArchiveClient = class {
16045
16529
  const req = request2(this.url, { method: "POST", agent: this.agent, headers: {
16046
16530
  "Content-Type": "application/json",
16047
16531
  "Content-Length": body.length,
16532
+ "Accept-Encoding": "br, gzip",
16048
16533
  ...archiveDigest ? { "X-Engine7-Recovery-Archive": archiveDigest } : {}
16049
16534
  } }, (res) => {
16050
16535
  responseStarted = true;
@@ -16053,6 +16538,7 @@ var RecoveryArchiveClient = class {
16053
16538
  finish(new Error(res.statusCode === 503 ? "RECOVERY_TRANSFER_BUSY" : "RECOVERY_TRANSFER_REFUSED"));
16054
16539
  return;
16055
16540
  }
16541
+ if (input.action === "read") this.streamAvailable = res.headers["x-engine7-recovery-stream"] === "1";
16056
16542
  const chunks = [];
16057
16543
  let bytes = 0;
16058
16544
  res.on("data", (chunk) => {
@@ -16062,7 +16548,15 @@ var RecoveryArchiveClient = class {
16062
16548
  else chunks.push(chunk);
16063
16549
  });
16064
16550
  res.once("error", (error) => unavailable(error.code));
16065
- res.once("end", () => finish(void 0, Buffer.concat(chunks)));
16551
+ res.once("end", () => {
16552
+ try {
16553
+ const body2 = Buffer.concat(chunks), encoding = res.headers["content-encoding"];
16554
+ if (encoding !== void 0 && encoding !== "gzip" && encoding !== "br") throw new Error();
16555
+ finish(void 0, encoding === "br" ? brotliDecompressSync(body2, { maxOutputLength: maximum }) : encoding === "gzip" ? gunzipSync3(body2, { maxOutputLength: maximum }) : body2);
16556
+ } catch {
16557
+ finish(new Error("RECOVERY_TRANSFER_INVALID_RESPONSE"));
16558
+ }
16559
+ });
16066
16560
  });
16067
16561
  this.pending.set(req, archiveDigest);
16068
16562
  const timer = setTimeout(() => unavailable("TIMEOUT"), this.timeout);
@@ -16144,6 +16638,151 @@ var RecoveryArchiveClient = class {
16144
16638
  return result;
16145
16639
  });
16146
16640
  }
16641
+ canStreamObjects() {
16642
+ return this.streamAvailable;
16643
+ }
16644
+ async streamObjects(id2, refs2, archiveDigest, consume, signal, consumeBatch) {
16645
+ if (!this.streamAvailable) return false;
16646
+ if (this.closed) throw new Error("RECOVERY_TRANSFER_CLOSED");
16647
+ if (!validId(id2) || !/^[a-f0-9]{64}$/.test(archiveDigest) || typeof consume !== "function") throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
16648
+ const group = validateStreamRefs(refs2.map((ref) => ({ ...ref })));
16649
+ const body = Buffer.from(JSON.stringify({ version: 1, action: "stream", id: id2, refs: group }));
16650
+ if (body.length > requestLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
16651
+ if (this.pending.size) throw new Error("RECOVERY_TRANSFER_BUSY");
16652
+ if (signal?.aborted) throw new Error("RECOVERY_TRANSFER_CANCELLED");
16653
+ return new Promise((resolve30, reject) => {
16654
+ const started = performance.now();
16655
+ let phase = "request", failurePhase, failureCode, encodedBytes = 0, receivedBytes = 0, consumedBytes = 0, consumedObjects = 0, consumeMs = 0;
16656
+ let complete = false, consumption, failure, consumerFailure, timer;
16657
+ const finish = (error, code) => {
16658
+ if (complete) return;
16659
+ complete = true;
16660
+ clearTimeout(timer);
16661
+ this.pending.delete(req);
16662
+ signal?.removeEventListener("abort", abort);
16663
+ const reason = failureCode ?? code ?? error?.message;
16664
+ process.stderr.write("[travel-archive-client] " + JSON.stringify({
16665
+ at: Date.now(),
16666
+ action: "stream",
16667
+ phase: failurePhase ?? phase,
16668
+ result: error ? "failed" : "complete",
16669
+ elapsedMs: Math.round(performance.now() - started),
16670
+ receivedBytes,
16671
+ wireBytes: encodedBytes,
16672
+ consumedBytes,
16673
+ consumedObjects,
16674
+ consumeMs: Math.round(consumeMs),
16675
+ reusedSocket: req.reusedSocket,
16676
+ ...error ? { code: typeof reason === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(reason) ? reason : "OTHER" } : {}
16677
+ }) + "\n");
16678
+ if (error) {
16679
+ req.destroy();
16680
+ reject(error);
16681
+ } else resolve30(true);
16682
+ };
16683
+ const fail2 = (error, code) => {
16684
+ if (complete) return;
16685
+ if (!failure) {
16686
+ failurePhase = phase;
16687
+ failureCode = code ?? error.message;
16688
+ }
16689
+ failure ??= error;
16690
+ req.destroy();
16691
+ if (!consumption) finish(failure);
16692
+ };
16693
+ const progress = () => {
16694
+ clearTimeout(timer);
16695
+ timer = setTimeout(() => fail2(new Error("RECOVERY_TRANSFER_UNAVAILABLE"), "IDLE_TIMEOUT"), this.timeout);
16696
+ };
16697
+ const abort = () => fail2(new Error("RECOVERY_TRANSFER_CANCELLED"));
16698
+ const req = request2(this.url, { method: "POST", agent: this.agent, headers: {
16699
+ "Content-Type": "application/json",
16700
+ "Content-Length": body.length,
16701
+ "Accept-Encoding": "br, gzip",
16702
+ "X-Engine7-Recovery-Archive": archiveDigest
16703
+ } }, (res) => {
16704
+ if (res.statusCode !== 200) {
16705
+ res.resume();
16706
+ finish(new Error(res.statusCode === 503 ? "RECOVERY_TRANSFER_BUSY" : "RECOVERY_TRANSFER_REFUSED"));
16707
+ return;
16708
+ }
16709
+ phase = "receive";
16710
+ const encoding = res.headers["content-encoding"];
16711
+ if (encoding !== void 0 && encoding !== "gzip" && encoding !== "br") {
16712
+ res.resume();
16713
+ finish(new Error("RECOVERY_TRANSFER_INVALID_RESPONSE"));
16714
+ return;
16715
+ }
16716
+ const decoder = encoding === "br" ? createBrotliDecompress() : encoding === "gzip" ? createGunzip() : void 0, incoming = decoder ?? res;
16717
+ if (decoder) {
16718
+ res.on("data", (chunk) => {
16719
+ encodedBytes += chunk.length;
16720
+ });
16721
+ const invalid = (error) => /^(Z_|ERR_(?!STREAM_))/.test(error.code ?? "");
16722
+ decoder.once("error", (error) => {
16723
+ if (invalid(error)) fail2(new Error("RECOVERY_TRANSFER_INVALID_RESPONSE"), error.code);
16724
+ });
16725
+ pipeline(res, decoder, (error) => {
16726
+ if (error) fail2(new Error(invalid(error) ? "RECOVERY_TRANSFER_INVALID_RESPONSE" : "RECOVERY_TRANSFER_UNAVAILABLE"), error.code);
16727
+ });
16728
+ }
16729
+ consumption = (async () => {
16730
+ let index = 0, offset = 0, assembled = Buffer.alloc(group[0].bytes);
16731
+ let buffered = [];
16732
+ const consumeGroup = async () => {
16733
+ if (!buffered.length) return;
16734
+ if (this.closed || signal?.aborted || failure) throw failure ?? new Error(signal?.aborted ? "RECOVERY_TRANSFER_CANCELLED" : "RECOVERY_TRANSFER_CLOSED");
16735
+ const batch = buffered;
16736
+ buffered = [];
16737
+ clearTimeout(timer);
16738
+ phase = "persist";
16739
+ const consumeStarted = performance.now();
16740
+ const results = await Promise.allSettled(consumeBatch ? [consumeBatch(batch)] : batch.map(async (item) => consume(item.ref, item.body)));
16741
+ consumeMs += performance.now() - consumeStarted;
16742
+ for (const result of results) if (result.status === "rejected") {
16743
+ consumerFailure = result.reason instanceof Error ? result.reason : new Error("RECOVERY_CONTENT_CORRUPT");
16744
+ throw consumerFailure;
16745
+ }
16746
+ consumedBytes += batch.reduce((bytes, item) => bytes + item.body.length, 0);
16747
+ consumedObjects += batch.length;
16748
+ phase = "receive";
16749
+ if (!failure) progress();
16750
+ if (failure) throw failure;
16751
+ };
16752
+ for await (const chunk of incoming) {
16753
+ if (!decoder) encodedBytes += chunk.length;
16754
+ receivedBytes += chunk.length;
16755
+ progress();
16756
+ if (failure) throw failure;
16757
+ let position = 0;
16758
+ while (position < chunk.length) {
16759
+ if (index >= group.length) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
16760
+ const length = Math.min(chunk.length - position, assembled.length - offset);
16761
+ chunk.copy(assembled, offset, position, position + length);
16762
+ position += length;
16763
+ offset += length;
16764
+ if (offset === assembled.length) {
16765
+ buffered.push({ ref: group[index], body: assembled });
16766
+ if (buffered.length === objectGroupLimit) await consumeGroup();
16767
+ index++;
16768
+ offset = 0;
16769
+ if (index < group.length) assembled = Buffer.alloc(group[index].bytes);
16770
+ }
16771
+ }
16772
+ }
16773
+ if (failure) throw failure;
16774
+ if (index !== group.length || offset !== 0 || !res.complete || decoder && decoder.bytesWritten !== encodedBytes) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
16775
+ await consumeGroup();
16776
+ })();
16777
+ void consumption.then(() => finish(), (error) => finish(consumerFailure ?? failure ?? (error instanceof Error && /^RECOVERY_/.test(error.message) ? error : new Error(/^Z_/.test(error?.code ?? "") ? "RECOVERY_TRANSFER_INVALID_RESPONSE" : "RECOVERY_TRANSFER_UNAVAILABLE")), error?.code));
16778
+ });
16779
+ this.pending.set(req, archiveDigest);
16780
+ progress();
16781
+ signal?.addEventListener("abort", abort, { once: true });
16782
+ req.once("error", (error) => fail2(new Error(this.closed ? "RECOVERY_TRANSFER_CLOSED" : "RECOVERY_TRANSFER_UNAVAILABLE"), error.code));
16783
+ req.end(body);
16784
+ });
16785
+ }
16147
16786
  close() {
16148
16787
  if (this.closed) return;
16149
16788
  this.closed = true;
@@ -16155,8 +16794,9 @@ var RecoveryArchiveClient = class {
16155
16794
  async function transferRecoveryArchive(options) {
16156
16795
  const maximum = options.maximumBytes ?? 16 * 1024 * 1024 * 1024;
16157
16796
  if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 64 * 1024 * 1024 * 1024 || !/^[a-f0-9]{64}$/.test(options.expectedDigest)) throw new Error("RECOVERY_TRANSFER_CONFIG");
16797
+ const supplied = options.entry === void 0 ? void 0 : structuredClone(options.entry);
16158
16798
  await options.beforeStep?.();
16159
- const entry = await options.peer.read(options.id), validated = validateRecoveryArchiveEntry(entry, options.archive.objects.identity);
16799
+ const entry = supplied ?? await options.peer.read(options.id), validated = validateRecoveryArchiveEntry(entry, options.archive.objects.identity);
16160
16800
  await options.beforeStep?.();
16161
16801
  if (entry.id !== options.id || validated.receipt.digest !== options.expectedDigest) throw new Error("RECOVERY_ARCHIVE_DIGEST");
16162
16802
  let floor = await checkRecoveryDeletionAsync(entry.manifest, options.deletionWatermark);
@@ -16167,6 +16807,60 @@ async function transferRecoveryArchive(options) {
16167
16807
  const objects = refs(entry), bytes = validated.body.length + [...objects.values()].reduce((sum, ref) => sum + ref.bytes, 0);
16168
16808
  if (!Number.isSafeInteger(bytes) || bytes > maximum) throw new Error("RECOVERY_TRANSFER_BUDGET");
16169
16809
  const all = [...objects.values()];
16810
+ if (options.peer.canStreamObjects?.() && options.peer.streamObjects) {
16811
+ const localCheck = async () => {
16812
+ await options.beforeStep?.();
16813
+ if (options.signal?.aborted) throw new Error("RECOVERY_TRANSFER_CANCELLED");
16814
+ };
16815
+ const missing = [];
16816
+ for (let offset = 0; offset < all.length; offset += objectGroupLimit) {
16817
+ const results = await Promise.allSettled(all.slice(offset, offset + objectGroupLimit).map(async (ref) => {
16818
+ await localCheck();
16819
+ return await options.archive.objects.has(ref) ? void 0 : ref;
16820
+ }));
16821
+ for (const result of results) {
16822
+ if (result.status === "rejected") throw result.reason;
16823
+ if (result.value) missing.push(result.value);
16824
+ }
16825
+ }
16826
+ const consume = async (ref, body) => {
16827
+ await localCheck();
16828
+ if (!Buffer.isBuffer(body) || body.length !== ref.bytes) throw new Error("RECOVERY_CONTENT_CORRUPT");
16829
+ const stored = await options.archive.objects.put(body);
16830
+ if (stored.sha256 !== ref.sha256 || stored.bytes !== ref.bytes) throw new Error("RECOVERY_CONTENT_CORRUPT");
16831
+ await localCheck();
16832
+ };
16833
+ const consumeBatch = async (items) => {
16834
+ await localCheck();
16835
+ for (const { ref, body } of items) if (!Buffer.isBuffer(body) || body.length !== ref.bytes) throw new Error("RECOVERY_CONTENT_CORRUPT");
16836
+ const stored = await options.archive.objects.putContents(items.map((item) => item.body));
16837
+ for (let i = 0; i < items.length; i++) if (stored[i].sha256 !== items[i].ref.sha256 || stored[i].bytes !== items[i].ref.bytes) throw new Error("RECOVERY_CONTENT_CORRUPT");
16838
+ await localCheck();
16839
+ };
16840
+ for (let offset = 0; offset < missing.length; offset += streamRefLimit) {
16841
+ await options.beforeStep?.();
16842
+ await check();
16843
+ let completed;
16844
+ try {
16845
+ completed = await options.peer.streamObjects(options.id, missing.slice(offset, offset + streamRefLimit), entry.receipt.digest, consume, options.signal, consumeBatch);
16846
+ } catch (error) {
16847
+ await options.beforeStep?.();
16848
+ await check();
16849
+ throw error;
16850
+ }
16851
+ if (!completed) throw new Error("RECOVERY_TRANSFER_REFUSED");
16852
+ await options.beforeStep?.();
16853
+ await check();
16854
+ }
16855
+ await options.beforeStep?.();
16856
+ await check();
16857
+ return options.archive.import(entry, async () => {
16858
+ await localCheck();
16859
+ await check();
16860
+ await localCheck();
16861
+ return floor;
16862
+ }, false);
16863
+ }
16170
16864
  for (let offset = 0; offset < all.length; offset += objectGroupLimit) {
16171
16865
  const missing = [];
16172
16866
  const verified = await Promise.allSettled(all.slice(offset, offset + objectGroupLimit).map(async (ref) => {
@@ -16272,18 +16966,18 @@ async function transferRecoveryArchive(options) {
16272
16966
  return options.archive.import(entry, async () => {
16273
16967
  await check();
16274
16968
  return floor;
16275
- });
16969
+ }, false);
16276
16970
  }
16277
16971
 
16278
16972
  // src/continuity/runtime-replica-repository.ts
16279
16973
  import { DatabaseSync as DatabaseSync25 } from "node:sqlite";
16280
- import { existsSync as existsSync16, lstatSync as lstatSync23, realpathSync as realpathSync19, writeFileSync as writeFileSync21 } from "node:fs";
16974
+ import { existsSync as existsSync16, lstatSync as lstatSync22, realpathSync as realpathSync19, writeFileSync as writeFileSync20 } from "node:fs";
16281
16975
  import { isAbsolute as isAbsolute7, join as join32, resolve as resolve25 } from "node:path";
16282
16976
  import { randomUUID as randomUUID13 } from "node:crypto";
16283
16977
 
16284
16978
  // src/continuity/runtime-replica-seed.ts
16285
16979
  import { DatabaseSync as DatabaseSync24 } from "node:sqlite";
16286
- import { existsSync as existsSync15, writeFileSync as writeFileSync20, realpathSync as realpathSync18, lstatSync as lstatSync22 } from "node:fs";
16980
+ import { existsSync as existsSync15, writeFileSync as writeFileSync19, realpathSync as realpathSync18, lstatSync as lstatSync21 } from "node:fs";
16287
16981
  import { dirname as dirname15, isAbsolute as isAbsolute6, join as join31, resolve as resolve24 } from "node:path";
16288
16982
  init_sqlite_replication();
16289
16983
  init_schema_migrations();
@@ -16311,8 +17005,7 @@ async function seedRuntimeReplica(options) {
16311
17005
  const check = async () => {
16312
17006
  const permit = await (options.permitSupplier?.() ?? options.permit);
16313
17007
  if (!permit || ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== options.permit[key2])) throw new Error("TRAVEL_REPLICA_IDENTITY");
16314
- await options.authority.assertPermit(permit, "CONTROL");
16315
- const status = await options.authority.status(options.principal);
17008
+ const status = options.authority.assertPermitWithStatus ? await options.authority.assertPermitWithStatus(permit, "CONTROL") : (await options.authority.assertPermit(permit, "CONTROL"), await options.authority.status(options.principal));
16316
17009
  if (digest7 !== options.expectedDigest || manifest.sequence !== 1 || manifest.parentDigest !== "0".repeat(64)) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
16317
17010
  if (status.checkpointDigest !== controlCheckpoint) await options.authority.verifyAncestor(options.principal, controlCheckpoint, String(status.checkpointDigest));
16318
17011
  if (entry.kind !== "LOCAL" || manifest.profile.epoch !== permit.epoch || options.principal.nodeId !== permit.nodeId || ["tenantId", "companionId", "seatId"].some((field) => identity[field] !== options.principal[field] || identity[field] !== permit[field] || identity[field] !== options.objects.identity[field])) throw new Error("TRAVEL_REPLICA_IDENTITY");
@@ -16340,13 +17033,12 @@ async function seedRuntimeReplica(options) {
16340
17033
  };
16341
17034
  try {
16342
17035
  owner = acquireReplicaOwner(dataDirectory, true);
16343
- await restoreRecoveryArchive({ archive: options.archive, id: options.id, destination, deletionWatermark: options.deletionWatermark });
17036
+ await restoreRecoveryArchive({ archive: options.archive, id: options.id, destination, deletionWatermark: options.deletionWatermark, verifyDatabases: false });
16344
17037
  const refs2 = /* @__PURE__ */ new Map();
16345
17038
  for (const content of [...manifest.trees.flatMap((tree) => tree.files.map((file) => file.content)), ...entry.databases.map((db) => db.content)]) for (const ref of content.chunks) refs2.set(ref.sha256, ref);
16346
17039
  const independent = [...refs2.values()];
16347
- for (let offset = 0; offset < independent.length; offset += 8) {
17040
+ for (let offset = 0; options.objects !== options.archive.objects && offset < independent.length; offset += 8) {
16348
17041
  const results = await Promise.allSettled(independent.slice(offset, offset + 8).map(async (ref) => {
16349
- await check();
16350
17042
  if (!await options.objects.has(ref)) {
16351
17043
  const stored = await options.objects.put(await options.archive.objects.read(ref));
16352
17044
  if (stored.sha256 !== ref.sha256 || stored.bytes !== ref.bytes) throw new Error("TRAVEL_REPLICA_OBJECT");
@@ -16356,12 +17048,10 @@ async function seedRuntimeReplica(options) {
16356
17048
  if (failed) throw failed.reason;
16357
17049
  }
16358
17050
  for (const d of entry.databases) {
16359
- await check();
16360
17051
  const file = join31(destination, "databases", d.databaseId + ".sqlite");
16361
17052
  const probe = new DatabaseSync24(file, { readOnly: true });
16362
17053
  let component, version;
16363
17054
  try {
16364
- validateRecoveryDatabase(probe, manifest, d.databaseId, "source", d.schemaHash);
16365
17055
  const schema5 = readSchemaVersion(probe);
16366
17056
  component = schema5?.component;
16367
17057
  version = schema5?.version;
@@ -16378,7 +17068,7 @@ async function seedRuntimeReplica(options) {
16378
17068
  const suppressTriggers = db.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name NOT GLOB 'writer_guard_*' AND name NOT GLOB 'e7_replication_guard_*'").all().map((row) => String(row.name));
16379
17069
  const binding = normalizeBinding({ ...identity, databaseId: d.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
16380
17070
  replicas[d.databaseId] = new SQLiteReplicationReplica(db, binding, { schemaHash: d.schemaHash, baseline: manifest.databases.find((value2) => value2.databaseId === d.databaseId).head, suppressTriggers });
16381
- validateRecoveryDatabase(db, manifest, d.databaseId, "replica", d.schemaHash);
17071
+ validateRecoveryDatabase(db, manifest, d.databaseId, "replica", d.schemaHash, false);
16382
17072
  }
16383
17073
  await check();
16384
17074
  receiver = await PublicationReplica.open({ directory: join31(dataDirectory, "publications"), profile: manifest.profile, objects: options.objects, replicas, minimumDeletionWatermark: manifest.deletionWatermark });
@@ -16386,7 +17076,7 @@ async function seedRuntimeReplica(options) {
16386
17076
  const receipt2 = await receiver.publish(manifest.sequence);
16387
17077
  if (receipt2.state !== "PUBLISHED" || receipt2.digest !== digest7) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
16388
17078
  await check();
16389
- writeFileSync20(join31(dataDirectory, "replica-seed.json"), JSON.stringify({ format: "engine7-runtime-replica-seed-v1", profile: manifest.profile, sourceArchiveId: entry.id, sourceArchiveDigest: entry.receipt.digest, checkpointDigest: digest7, parentCheckpointDigest: controlCheckpoint, destination }), { mode: 384, flag: "wx", flush: true });
17079
+ writeFileSync19(join31(dataDirectory, "replica-seed.json"), JSON.stringify({ format: "engine7-runtime-replica-seed-v1", profile: manifest.profile, sourceArchiveId: entry.id, sourceArchiveDigest: entry.receipt.digest, checkpointDigest: digest7, parentCheckpointDigest: controlCheckpoint, destination }), { mode: 384, flag: "wx", flush: true });
16390
17080
  await syncDirectory(destination);
16391
17081
  await syncDirectory(dataDirectory);
16392
17082
  return { receiver, databases, replicas, profile: manifest.profile, receipt: receipt2, close };
@@ -16439,13 +17129,13 @@ async function openSeededRuntimeReplica(options) {
16439
17129
  floor();
16440
17130
  const file = join31(options.destination, "databases", d.databaseId + ".sqlite");
16441
17131
  if (!existsSync15(file)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
16442
- const stat = lstatSync22(file);
17132
+ const stat = lstatSync21(file);
16443
17133
  if (!stat.isFile() || stat.isSymbolicLink() || realpathSync18(file) !== file || process.platform !== "win32" && (stat.uid !== process.getuid() || stat.mode & 63)) throw new Error("TRAVEL_REPLICA_PATH");
16444
17134
  const probe = new DatabaseSync24(file, { readOnly: true }), binding = normalizeBinding({ ...profile.identity, databaseId: d.databaseId, baselineId: profile.baselineId, epoch: profile.epoch });
16445
17135
  let component, version;
16446
17136
  try {
16447
17137
  const control2 = probe.prepare("SELECT binding,schema_hash FROM e7_replication_control WHERE role='replica'").get(), schema5 = readSchemaVersion(probe);
16448
- if (!control2 || JSON.stringify(JSON.parse(String(control2.binding))) !== JSON.stringify([binding.tenantId, binding.companionId, binding.seatId, binding.databaseId, binding.baselineId, binding.epoch]) || control2.schema_hash !== d.schemaHash || sqliteReplicationSchemaHash(probe) !== d.schemaHash || probe.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
17138
+ if (!control2 || JSON.stringify(JSON.parse(String(control2.binding))) !== JSON.stringify([binding.tenantId, binding.companionId, binding.seatId, binding.databaseId, binding.baselineId, binding.epoch]) || control2.schema_hash !== d.schemaHash || sqliteReplicationSchemaHash(probe) !== d.schemaHash) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
16449
17139
  component = schema5?.component;
16450
17140
  version = schema5?.version;
16451
17141
  } finally {
@@ -16460,11 +17150,11 @@ async function openSeededRuntimeReplica(options) {
16460
17150
  replicas[d.databaseId] = new SQLiteReplicationReplica(db, binding, { schemaHash: d.schemaHash, baseline: manifest.databases.find((value2) => value2.databaseId === d.databaseId).head, suppressTriggers });
16461
17151
  }
16462
17152
  receiver = await PublicationReplica.open({ directory: dirname15(publicationFile), profile, objects: options.objects, replicas, minimumDeletionWatermark: floor() });
16463
- const status = await receiver.status();
17153
+ const status = await receiver.status(false);
16464
17154
  if (!status.published || status.published.sequence < manifest.sequence) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
16465
17155
  if (status.dataReady) {
16466
17156
  const current2 = await receiver.manifest(status.published.sequence);
16467
- for (const d of entry.databases) validateRecoveryDatabase(databases[d.databaseId], current2, d.databaseId, "replica", d.schemaHash);
17157
+ for (const d of entry.databases) validateRecoveryDatabase(databases[d.databaseId], current2, d.databaseId, "replica", d.schemaHash, false);
16468
17158
  }
16469
17159
  floor();
16470
17160
  return { receiver, databases, replicas, profile, receipt: status.published, close };
@@ -16477,7 +17167,7 @@ async function openSeededRuntimeReplica(options) {
16477
17167
  // src/continuity/runtime-replica-repository.ts
16478
17168
  var validId2 = (value2) => typeof value2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2);
16479
17169
  var incarnation4 = (file) => {
16480
- const stat = lstatSync23(file, { bigint: true });
17170
+ const stat = lstatSync22(file, { bigint: true });
16481
17171
  return `${stat.dev}:${stat.ino}`;
16482
17172
  };
16483
17173
  var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
@@ -16491,7 +17181,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
16491
17181
  const presence = this.files.map(existsSync16), fresh = presence.every((value2) => !value2);
16492
17182
  if (fresh && (options.initialize !== true || existsSync16(join32(options.directory, "receivers"))) || !fresh && !presence.every(Boolean)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
16493
17183
  const binding = JSON.stringify([options.objects.identity, options.nodeId, options.generationsDirectory]);
16494
- if (fresh) writeFileSync21(this.files[0], JSON.stringify({ format: "engine7-runtime-replica-repository-v1", binding }), { mode: 384, flag: "wx", flush: true });
17184
+ if (fresh) writeFileSync20(this.files[0], JSON.stringify({ format: "engine7-runtime-replica-repository-v1", binding }), { mode: 384, flag: "wx", flush: true });
16495
17185
  const marker = JSON.parse(readPrivateFile2(this.files[0], 65536).toString());
16496
17186
  if (marker.format !== "engine7-runtime-replica-repository-v1" || marker.binding !== binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_REPLICA_IDENTITY");
16497
17187
  preparePrivateDatabase(this.files[1]);
@@ -16586,9 +17276,8 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
16586
17276
  const check = async () => {
16587
17277
  this.assertOpen();
16588
17278
  const permit = await (request7.permitSupplier?.() ?? request7.permit);
16589
- await request7.authority.assertPermit(permit, "CONTROL");
17279
+ const status = request7.authority.assertPermitWithStatus ? await request7.authority.assertPermitWithStatus(permit, "CONTROL") : (await request7.authority.assertPermit(permit, "CONTROL"), await request7.authority.status(request7.principal));
16590
17280
  if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request7.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request7.principal[key2]) || JSON.stringify(entry.manifest.profile.identity) !== JSON.stringify(this.options.objects.identity) || entry.manifest.profile.epoch !== permit.epoch) throw new Error("TRAVEL_REPLICA_IDENTITY");
16591
- const status = await request7.authority.status(request7.principal);
16592
17281
  if (status.deletionWatermark !== entry.manifest.deletionWatermark || this.options.deletionWatermark() !== entry.manifest.deletionWatermark) throw new Error("TRAVEL_REPLICA_DELETION_BARRIER");
16593
17282
  if (status.buildManifestId !== entry.manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
16594
17283
  };
@@ -16791,7 +17480,7 @@ function createPublicationServer(options) {
16791
17480
  };
16792
17481
  switch (value2.operation) {
16793
17482
  case "status":
16794
- result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
17483
+ result = preservePublished ? await mutate(() => receiver.status(false)) : await receiver.status(false);
16795
17484
  break;
16796
17485
  case "replication-status":
16797
17486
  result = await receiver.replicationStatus();
@@ -16799,7 +17488,6 @@ function createPublicationServer(options) {
16799
17488
  case "missing": {
16800
17489
  if (!Array.isArray(value2.refs) || value2.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
16801
17490
  const missing = await Promise.all(value2.refs.map(async (ref) => {
16802
- await check();
16803
17491
  validateObjectRef(ref);
16804
17492
  return await receiver.objects.has(ref) ? null : ref.sha256;
16805
17493
  }));
@@ -16899,26 +17587,26 @@ async function createTravelNodeDataServer(options) {
16899
17587
 
16900
17588
  // src/continuity/recovery-runtime-adapter.ts
16901
17589
  import { DatabaseSync as DatabaseSync28 } from "node:sqlite";
16902
- import { lstatSync as lstatSync25, realpathSync as realpathSync21 } from "node:fs";
17590
+ import { lstatSync as lstatSync24, realpathSync as realpathSync21 } from "node:fs";
16903
17591
  import { isAbsolute as isAbsolute8, join as join36, resolve as resolve27 } from "node:path";
16904
17592
  init_schema_migrations();
16905
17593
 
16906
17594
  // src/continuity/recovery-admission.ts
16907
17595
  import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
16908
17596
  import { createHash as createHash37 } from "node:crypto";
16909
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync4, writeFileSync as writeFileSync23 } from "node:fs";
17597
+ import { mkdtempSync as mkdtempSync3, rmSync as rmSync4, writeFileSync as writeFileSync22 } from "node:fs";
16910
17598
  import { join as join34 } from "node:path";
16911
17599
 
16912
17600
  // src/continuity/recovery-diff.ts
16913
17601
  import { DatabaseSync as DatabaseSync26 } from "node:sqlite";
16914
17602
  import { createHash as createHash36 } from "node:crypto";
16915
- import { mkdtempSync as mkdtempSync2, rmSync as rmSync3, writeFileSync as writeFileSync22 } from "node:fs";
17603
+ import { mkdtempSync as mkdtempSync2, rmSync as rmSync3, writeFileSync as writeFileSync21 } from "node:fs";
16916
17604
  import { join as join33 } from "node:path";
16917
17605
  init_legacy_sqlite_indexes();
16918
17606
  init_schema_migrations();
16919
17607
  var same9 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
16920
17608
  var quote2 = (s) => '"' + s.replaceAll('"', '""') + '"';
16921
- var metadata2 = /* @__PURE__ */ new Set(["e7_replication_control", "e7_replication_outbox", "e7_replication_inbox"]);
17609
+ var metadata3 = /* @__PURE__ */ new Set(["e7_replication_control", "e7_replication_outbox", "e7_replication_inbox"]);
16922
17610
  function value(cell) {
16923
17611
  if (cell === null) return ["null"];
16924
17612
  if (typeof cell === "bigint") return ["integer", String(cell)];
@@ -16939,7 +17627,7 @@ function tables(db) {
16939
17627
  const result = [];
16940
17628
  for (const row of db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name").all()) {
16941
17629
  const name = String(row.name);
16942
- if (metadata2.has(name) || name.startsWith("e7_recovery_") || derived.has(name) || name.startsWith("sqlite_") && name !== "sqlite_sequence") continue;
17630
+ if (metadata3.has(name) || name.startsWith("e7_recovery_") || derived.has(name) || name.startsWith("sqlite_") && name !== "sqlite_sequence") continue;
16943
17631
  if (/CREATE\s+VIRTUAL\s+TABLE/i.test(String(row.sql))) throw new Error("RECOVERY_DIFF_UNSUPPORTED_TABLE");
16944
17632
  const info = db.prepare("PRAGMA table_info(" + quote2(name) + ")").all();
16945
17633
  const keys = name === "sqlite_sequence" ? ["name"] : info.filter((c) => Number(c.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk)).map((c) => String(c.name));
@@ -17007,7 +17695,7 @@ async function compareRecoveryArchives(options) {
17007
17695
  const entry = entries[index], ref = references[index], d = entry.databases.find((d2) => d2.databaseId === databaseId);
17008
17696
  const temporary = mkdtempSync2(join33(ref.archive.directory, ".compare-"));
17009
17697
  temporaries.push(temporary);
17010
- writeFileSync22(join33(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
17698
+ writeFileSync21(join33(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
17011
17699
  const file = join33(temporary, databaseId + ".sqlite");
17012
17700
  await ref.archive.objects.restoreFile(d.content, file);
17013
17701
  const db = new DatabaseSync26(file, { readOnly: true, allowExtension: true });
@@ -17217,10 +17905,10 @@ function socialReferences(db, table, row, archived) {
17217
17905
  statement.setReadBigInts(true);
17218
17906
  const current2 = statement.get(scope, id2), original = archived("memory_sources", { scope_id: row.scope_id, source_id: ["text", id2] });
17219
17907
  if (!current2 || !original || !sameSource(Object.fromEntries(Object.entries(current2).map(([k, v]) => [k, encode(v)])), original) || db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind='source' AND target_id=?").get(scope, id2) || !historical && db.prepare("SELECT 1 FROM memory_sources WHERE scope_id=? AND origin_key=? AND source_version>?").get(scope, current2.origin_key, current2.source_version)) return null;
17220
- const metadata3 = archived("memory_social_sources", { scope_id: row.scope_id, source_id: ["text", id2] });
17221
- if (metadata3 && id2 !== checkingMetadata) {
17908
+ const metadata4 = archived("memory_social_sources", { scope_id: row.scope_id, source_id: ["text", id2] });
17909
+ if (metadata4 && id2 !== checkingMetadata) {
17222
17910
  const live = db.prepare("SELECT * FROM memory_social_sources WHERE scope_id=? AND source_id=?").get(scope, id2);
17223
- if (!live || !same10(Object.fromEntries(Object.entries(live).map(([k, v]) => [k, encode(v)])), metadata3)) return null;
17911
+ if (!live || !same10(Object.fromEntries(Object.entries(live).map(([k, v]) => [k, encode(v)])), metadata4)) return null;
17224
17912
  sources.add(id2);
17225
17913
  try {
17226
17914
  if (!references(String(live.context_refs), true) || !references(String(live.basis_refs), historical)) return null;
@@ -17934,7 +18622,7 @@ async function admitRecoveryArchives(options) {
17934
18622
  }
17935
18623
  await active();
17936
18624
  const commonDirectory = mkdtempSync3(join34(options.common.archive.directory, ".admission-common-"));
17937
- writeFileSync23(join34(commonDirectory, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
18625
+ writeFileSync22(join34(commonDirectory, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
17938
18626
  const commonDatabases = /* @__PURE__ */ new Map();
17939
18627
  try {
17940
18628
  for (const d of common.databases) {
@@ -18074,6 +18762,10 @@ async function admitRecoveryArchives(options) {
18074
18762
  result.state = "HISTORY";
18075
18763
  result.reason = "node_local_auth_readiness_history";
18076
18764
  }
18765
+ if (item.treeId === "workspace" && [".system-prompt.txt", ".context-debug.txt"].includes(item.path ?? "") && local.manifest.profile.trees.some((tree) => tree.id === "workspace" && tree.kind === "file")) {
18766
+ result.state = "HISTORY";
18767
+ result.reason = "generated_runtime_diagnostic_history";
18768
+ }
18077
18769
  if (deletions.length && local.manifest.deletionWatermark < getPermit().deletionWatermark) {
18078
18770
  result.state = "DELETED_BLOCKED";
18079
18771
  result.reason = "unmapped_old_dependency";
@@ -18214,7 +18906,7 @@ async function admitRecoveryArchives(options) {
18214
18906
 
18215
18907
  // src/continuity/recovery-artifact-projection.ts
18216
18908
  import { createHash as createHash38, randomUUID as randomUUID14 } from "node:crypto";
18217
- import { existsSync as existsSync17, linkSync as linkSync2, lstatSync as lstatSync24, mkdirSync as mkdirSync14, readFileSync as readFileSync14, realpathSync as realpathSync20, unlinkSync as unlinkSync10, writeFileSync as writeFileSync24 } from "node:fs";
18909
+ import { existsSync as existsSync17, linkSync, lstatSync as lstatSync23, mkdirSync as mkdirSync14, readFileSync as readFileSync13, realpathSync as realpathSync20, unlinkSync as unlinkSync9, writeFileSync as writeFileSync23 } from "node:fs";
18218
18910
  import { dirname as dirname16, join as join35, resolve as resolve26 } from "node:path";
18219
18911
  import { createRequire as createRequire7 } from "node:module";
18220
18912
  init_runtime_authority();
@@ -18226,7 +18918,7 @@ function privateParents(root, path3) {
18226
18918
  if (!isWithin(root, directory2)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
18227
18919
  if (directory2 !== root) visit(dirname16(directory2));
18228
18920
  if (!existsSync17(directory2)) mkdirSync14(directory2, { mode: 448 });
18229
- const s = lstatSync24(directory2);
18921
+ const s = lstatSync23(directory2);
18230
18922
  if (!s.isDirectory() || s.isSymbolicLink() || process.platform !== "win32" && (s.uid !== process.getuid() || directory2 === root && s.mode & 63)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
18231
18923
  };
18232
18924
  visit(path3);
@@ -18329,27 +19021,27 @@ async function projectRecoveryArtifacts(options) {
18329
19021
  privateParents(root, dirname16(path3));
18330
19022
  active();
18331
19023
  if (existsSync17(path3)) {
18332
- const s = lstatSync24(path3);
18333
- if (!s.isFile() || s.isSymbolicLink() || (s.mode & 511) !== local.mode || !readFileSync14(path3).equals(Buffer.from(body))) continue;
19024
+ const s = lstatSync23(path3);
19025
+ if (!s.isFile() || s.isSymbolicLink() || (s.mode & 511) !== local.mode || !readFileSync13(path3).equals(Buffer.from(body))) continue;
18334
19026
  commit();
18335
19027
  continue;
18336
19028
  }
18337
19029
  const temporary = join35(dirname16(path3), ".recovery-" + randomUUID14()), original = Buffer.from(body);
18338
- writeFileSync24(temporary, original, { mode: local.mode, flag: "wx", flush: true });
19030
+ writeFileSync23(temporary, original, { mode: local.mode, flag: "wx", flush: true });
18339
19031
  let created = false;
18340
19032
  try {
18341
19033
  active();
18342
- linkSync2(temporary, path3);
19034
+ linkSync(temporary, path3);
18343
19035
  created = true;
18344
- unlinkSync10(temporary);
19036
+ unlinkSync9(temporary);
18345
19037
  await syncDirectory(dirname16(path3));
18346
19038
  await checkRemote();
18347
19039
  commit();
18348
19040
  } catch (error) {
18349
- if (created && existsSync17(path3) && lstatSync24(path3).isFile() && !lstatSync24(path3).isSymbolicLink() && readFileSync14(path3).equals(original)) unlinkSync10(path3);
19041
+ if (created && existsSync17(path3) && lstatSync23(path3).isFile() && !lstatSync23(path3).isSymbolicLink() && readFileSync13(path3).equals(original)) unlinkSync9(path3);
18350
19042
  if (!/RECOVERY_ARTIFACT_DEPENDENCY_PENDING/.test(String(error))) throw error;
18351
19043
  } finally {
18352
- if (existsSync17(temporary)) unlinkSync10(temporary);
19044
+ if (existsSync17(temporary)) unlinkSync9(temporary);
18353
19045
  }
18354
19046
  }
18355
19047
  } else if (kind === "session") {
@@ -18472,7 +19164,7 @@ async function admitNormalRecoveryArchives(options) {
18472
19164
  runtime.assert("WRITE");
18473
19165
  for (const id2 of profile.databaseIds) {
18474
19166
  validatePublicationPath(layout.databases[id2]);
18475
- const file = join36(stateDir, layout.databases[id2]), place = sqliteStoreLocation(file), stat = lstatSync25(file);
19167
+ const file = join36(stateDir, layout.databases[id2]), place = sqliteStoreLocation(file), stat = lstatSync24(file);
18476
19168
  if (!place || !stat.isFile() || stat.isSymbolicLink() || realpathSync21(file) !== file || process.platform !== "win32" && (stat.uid !== process.getuid() || stat.mode & 63)) throw new Error("RECOVERY_CURRENT_LAYOUT");
18477
19169
  if (place.component === "mem7") {
18478
19170
  if (id2 !== "memory" || memory || place.stateDir !== stateDir) throw new Error("RECOVERY_CURRENT_LAYOUT");
@@ -18550,7 +19242,7 @@ init_runtime_lock();
18550
19242
  // src/continuity/local-exit-proof.ts
18551
19243
  init_runtime_lock();
18552
19244
  import { createHash as createHash39, verify as verify2 } from "node:crypto";
18553
- import { createReadStream, mkdirSync as mkdirSync15, readdirSync as readdirSync7, writeFileSync as writeFileSync25 } from "node:fs";
19245
+ import { createReadStream, mkdirSync as mkdirSync15, readdirSync as readdirSync6, writeFileSync as writeFileSync24 } from "node:fs";
18554
19246
  import { join as join37, relative as relative8 } from "node:path";
18555
19247
  var hash9 = (value2) => createHash39("sha256").update(value2).digest("hex");
18556
19248
  var equal2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
@@ -18561,7 +19253,7 @@ function copyLocalExitPath(source, path3) {
18561
19253
  async function localExitFilesDigest(root, ordinary = false) {
18562
19254
  const files = [];
18563
19255
  const visit = async (directory2) => {
18564
- for (const entry of readdirSync7(directory2, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
19256
+ for (const entry of readdirSync6(directory2, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
18565
19257
  const file = join37(directory2, entry.name);
18566
19258
  if (ordinary ? relative8(root, file).replaceAll("\\", "/") === ".continuity/travel-exit-receipt.json" : !copyLocalExitPath(root, file)) continue;
18567
19259
  if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
@@ -18600,7 +19292,7 @@ async function writeStoppedLocalExitProof(options) {
18600
19292
  if (!equal2(binding, await currentBinding(options.stateDir, options.authority, options.principal))) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
18601
19293
  const body = { format: "engine7-stopped-local-exit-v1", ...binding, filesDigest };
18602
19294
  mkdirSync15(join37(options.stateDir, ".continuity"), { recursive: true, mode: 448 });
18603
- writeFileSync25(join37(options.stateDir, ".continuity/travel-exit-source.json"), JSON.stringify({ ...body, digest: hash9(JSON.stringify(body)) }), { mode: 384, flush: true });
19295
+ writeFileSync24(join37(options.stateDir, ".continuity/travel-exit-source.json"), JSON.stringify({ ...body, digest: hash9(JSON.stringify(body)) }), { mode: 384, flush: true });
18604
19296
  });
18605
19297
  }
18606
19298
 
@@ -18732,12 +19424,15 @@ var TravelNodeAgent = class _TravelNodeAgent {
18732
19424
  runtime: () => node.stopping ? null : node.runtime ?? node.activatingRuntime ?? null,
18733
19425
  intervalMs: options.heartbeatIntervalMs,
18734
19426
  client: { register: async (boot) => {
18735
- await node.assertDataAvailable();
19427
+ node.assertLocalDataAvailable();
18736
19428
  return options.report.register(boot);
18737
19429
  }, heartbeat: async (input) => {
18738
- await node.assertDataAvailable();
19430
+ await node.freshKeyWatermark();
19431
+ node.assertLocalDataAvailable();
18739
19432
  const response = await options.report.heartbeat(input);
18740
- await node.assertDataAvailable();
19433
+ await node.freshKeyWatermark();
19434
+ node.assertLocalDataAvailable();
19435
+ if (response?.deletionWatermark !== node.keyWatermark || response?.permit && response.permit.deletionWatermark !== node.keyWatermark) throw new Error("TRAVEL_NODE_KEY_UNAVAILABLE");
18741
19436
  return response;
18742
19437
  } }
18743
19438
  });
@@ -18760,23 +19455,31 @@ var TravelNodeAgent = class _TravelNodeAgent {
18760
19455
  }
18761
19456
  checkBuild() {
18762
19457
  for (const b of [this.options.build, this.options.dataBuild]) {
18763
- const info = lstatSync26(b.entry);
18764
- if (!/^[a-f0-9]{64}$/.test(b.sha256) || !info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync22(b.entry) !== b.entry || hash10(readFileSync15(b.entry)) !== b.sha256) throw new Error("TRAVEL_NODE_BUILD");
19458
+ const info = lstatSync25(b.entry);
19459
+ if (!/^[a-f0-9]{64}$/.test(b.sha256) || !info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync22(b.entry) !== b.entry || hash10(readFileSync14(b.entry)) !== b.sha256) throw new Error("TRAVEL_NODE_BUILD");
18765
19460
  }
18766
19461
  }
18767
19462
  assertKey() {
18768
19463
  if (this.closed || clock() - this.lastKeyCheck >= this.maxKeyAge) throw new Error("TRAVEL_NODE_KEY_UNAVAILABLE");
18769
19464
  }
18770
- async assertDataAvailable() {
19465
+ async freshKeyWatermark() {
19466
+ if (clock() - this.lastKeyCheck >= this.refreshInterval) await this.refreshKey();
18771
19467
  this.assertKey();
18772
- const status = await this.options.authority.status(this.principal);
19468
+ return this.keyWatermark;
19469
+ }
19470
+ assertLocalDataAvailable() {
18773
19471
  this.assertKey();
18774
- if (status.deletionWatermark !== this.keyWatermark) throw new Error("TRAVEL_NODE_KEY_UNAVAILABLE");
18775
19472
  if (this.sourceObjects) {
18776
- const stat = lstatSync26(join38(this.sourceObjects.directory, "catalog.sqlite"), { bigint: true });
19473
+ const stat = lstatSync25(join38(this.sourceObjects.directory, "catalog.sqlite"), { bigint: true });
18777
19474
  if (stat.isSymbolicLink() || !stat.isFile() || `${stat.dev}:${stat.ino}` !== this.sourceCatalogIdentity) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
18778
19475
  }
18779
19476
  }
19477
+ async assertDataAvailable() {
19478
+ this.assertLocalDataAvailable();
19479
+ const status = await this.options.authority.status(this.principal);
19480
+ this.assertLocalDataAvailable();
19481
+ if (status.deletionWatermark !== this.keyWatermark) throw new Error("TRAVEL_NODE_KEY_UNAVAILABLE");
19482
+ }
18780
19483
  async currentReceiver() {
18781
19484
  const [, status] = await Promise.all([this.assertDataAvailable(), Promise.resolve().then(() => this.options.authority.status(this.principal))]);
18782
19485
  if (this.runtime || this.process || this.dataProcess || !this.replica) return null;
@@ -18788,7 +19491,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
18788
19491
  try {
18789
19492
  const replica = this.replica;
18790
19493
  if (!replica || replica.receiver !== receiver || await this.currentReceiver() !== receiver) throw new Error("PUBLICATION_RECEIVER_CHANGED");
18791
- const status = await receiver.status();
19494
+ const status = await receiver.status(false);
18792
19495
  if (!status.published || !status.dataReady) return;
18793
19496
  const manifest = await receiver.manifest(status.published.sequence);
18794
19497
  const check = async () => {
@@ -18801,7 +19504,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
18801
19504
  manifest,
18802
19505
  databases: replica.databases,
18803
19506
  receiver,
18804
- deletionWatermark: check
19507
+ deletionWatermark: check,
19508
+ verifyRetained: false
18805
19509
  });
18806
19510
  await check();
18807
19511
  } finally {
@@ -18868,7 +19572,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
18868
19572
  if (this.stopping || token !== this.generationToken || archive !== this.archive) throw new Error("TRAVEL_NODE_CANCELLED");
18869
19573
  this.assertKey();
18870
19574
  };
18871
- await this.refreshKey();
19575
+ if (clock() - this.lastKeyCheck >= this.refreshInterval) await this.refreshKey();
18872
19576
  check();
18873
19577
  const entry = await archive.read(id2).catch((error) => {
18874
19578
  if (error instanceof Error && error.message === "RECOVERY_ARCHIVE_NOT_FOUND") return null;
@@ -18939,7 +19643,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
18939
19643
  assertPrivateDirectory2(directory2);
18940
19644
  assertPrivateDirectory2(join38(directory2, "chunks"));
18941
19645
  if (realpathSync22(directory2) !== directory2 || !existsSync18(file)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
18942
- const stat = lstatSync26(file, { bigint: true });
19646
+ const stat = lstatSync25(file, { bigint: true });
18943
19647
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
18944
19648
  const db = new DatabaseSync29(file, { readOnly: true });
18945
19649
  try {
@@ -18973,8 +19677,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
18973
19677
  async preserveReplicaRemote() {
18974
19678
  if (!this.replica || this.runtime || this.process || this.dataProcess) return;
18975
19679
  const replica = this.replica;
18976
- const [before, status] = await Promise.all([this.options.authority.status(this.principal), replica.receiver.status()]);
18977
- await this.assertDataAvailable();
19680
+ const [before, status] = await Promise.all([this.options.authority.status(this.principal), replica.receiver.status(false)]);
19681
+ this.assertLocalDataAvailable();
18978
19682
  if (!status.dataReady || !status.published || status.published.digest !== before.checkpointDigest) return;
18979
19683
  const digest7 = status.published.digest, manifest = await replica.receiver.manifest(status.published.sequence);
18980
19684
  const check = async () => {
@@ -18982,15 +19686,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
18982
19686
  if (this.replica !== replica || this.runtime || current2.authorityBootId !== before.authorityBootId || current2.epoch !== before.epoch || current2.checkpointDigest !== digest7 || current2.deletionWatermark !== before.deletionWatermark) throw new Error("TRAVEL_NODE_CHECKPOINT");
18983
19687
  return this.keyWatermark;
18984
19688
  };
18985
- await check();
18986
19689
  if (publicationDigest(manifest) !== digest7 || manifest.profile.buildManifestId !== this.options.build.manifestId) throw new Error("TRAVEL_NODE_CHECKPOINT");
18987
- await this.archive.preserve({ id: "remote-" + digest7, kind: "REMOTE", manifest, databases: replica.databases, receiver: replica.receiver, deletionWatermark: check });
18988
- await check();
19690
+ await this.archive.preserve({ id: "remote-" + digest7, kind: "REMOTE", manifest, databases: replica.databases, receiver: replica.receiver, deletionWatermark: check, verifyRetained: false });
18989
19691
  }
18990
19692
  listDataArchiveReceipts() {
18991
19693
  return this.exclusive(async () => {
18992
- await this.refreshKey();
18993
- this.assertKey();
19694
+ await this.freshKeyWatermark();
18994
19695
  if (!this.runtime && !this.process && !this.dataProcess) {
18995
19696
  const results = await Promise.allSettled([this.preserveBranches(), this.preserveReplicaRemote()]);
18996
19697
  for (const result of results) if (result.status === "rejected") throw result.reason;
@@ -19032,15 +19733,13 @@ var TravelNodeAgent = class _TravelNodeAgent {
19032
19733
  }
19033
19734
  readRecoveryManifests(common, localArchiveId) {
19034
19735
  return this.readRecoveryEvidence(localArchiveId, async () => {
19035
- await this.refreshKey();
19036
- this.assertKey();
19736
+ await this.freshKeyWatermark();
19037
19737
  return this.stoppedRecoveryManifests(common, localArchiveId);
19038
19738
  });
19039
19739
  }
19040
19740
  readRecoveryManifestEvidence(common, localArchiveId, maximum) {
19041
19741
  return this.readRecoveryEvidence(localArchiveId, async () => {
19042
- await this.refreshKey();
19043
- this.assertKey();
19742
+ await this.freshKeyWatermark();
19044
19743
  const archive = await this.dataArchive(localArchiveId), entry = await archive.read(localArchiveId);
19045
19744
  const manifests = await this.stoppedRecoveryManifests(common, localArchiveId, maximum);
19046
19745
  return { entry, manifests };
@@ -19078,21 +19777,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19078
19777
  if (!Array.isArray(binding) || binding.length !== 4 || binding[0] !== this.principal.nodeId || binding[3] !== profile.epoch || !isWithin(this.options.generationsDirectory, stateDir) || ["tenantId", "companionId", "seatId"].some((field) => profile.identity[field] !== this.principal[field])) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19079
19778
  const objects = await this.sourceObjectStore(profile), dataDirectory = join38(this.options.directory, "data", "source-" + hash10(String(row.binding)));
19080
19779
  const prior = this.db.prepare("SELECT archive_id,receipt FROM stopped_branches WHERE binding=?").get(String(row.binding));
19081
- if (prior) {
19082
- const archive = await RuntimeRecoveryArchive.open({ directory: join38(dataDirectory, "recovery"), objects });
19083
- try {
19084
- const entry = await archive.read(String(prior.archive_id));
19085
- if (entry.kind !== "LOCAL" || !same12(entry.manifest.profile, profile) || !same12(entry.receipt, JSON.parse(String(prior.receipt)))) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19086
- await checkRecoveryDeletionAsync(entry.manifest, async () => {
19087
- await this.assertDataAvailable();
19088
- return this.keyWatermark;
19089
- });
19090
- } finally {
19091
- archive.close();
19092
- }
19093
- continue;
19094
- }
19095
- const receipt2 = await preserveStoppedGeneration({
19780
+ const receipt2 = prior ? JSON.parse(String(prior.receipt)) : await preserveStoppedGeneration({
19096
19781
  stateDir,
19097
19782
  dataDirectory,
19098
19783
  objects,
@@ -19102,7 +19787,21 @@ var TravelNodeAgent = class _TravelNodeAgent {
19102
19787
  return this.keyWatermark;
19103
19788
  }
19104
19789
  });
19105
- this.db.prepare("INSERT INTO stopped_branches VALUES(?,?,?)").run(String(row.binding), receipt2.id, JSON.stringify(receipt2));
19790
+ const cached = this.sourceArchives.get(String(row.binding));
19791
+ const archive = cached ?? await RuntimeRecoveryArchive.open({ directory: join38(dataDirectory, "recovery"), objects });
19792
+ try {
19793
+ const entry = await archive.read(prior ? String(prior.archive_id) : receipt2.id);
19794
+ if (entry.kind !== "LOCAL" || !same12(entry.manifest.profile, profile) || !same12(entry.receipt, receipt2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19795
+ await checkRecoveryDeletionAsync(entry.manifest, async () => {
19796
+ await this.assertDataAvailable();
19797
+ return this.keyWatermark;
19798
+ });
19799
+ if (!prior) this.db.prepare("INSERT INTO stopped_branches VALUES(?,?,?)").run(String(row.binding), receipt2.id, JSON.stringify(receipt2));
19800
+ this.sourceArchives.set(String(row.binding), archive);
19801
+ } catch (error) {
19802
+ if (!cached) archive.close();
19803
+ throw error;
19804
+ }
19106
19805
  }
19107
19806
  }
19108
19807
  refreshKey() {
@@ -19144,7 +19843,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19144
19843
  if (!/^[a-f0-9]{64}$/.test(digest7)) throw new Error("TRAVEL_NODE_CHECKPOINT");
19145
19844
  if (this.db.prepare("SELECT 1 FROM common_preparations WHERE digest=?").get(digest7)) return this.preparedCommon(digest7);
19146
19845
  if (!replica) throw new Error("TRAVEL_NODE_REPLICA_NOT_READY");
19147
- const { receiver, databases } = replica, status = await receiver.status();
19846
+ const { receiver, databases } = replica, status = await receiver.status(false);
19148
19847
  if (status.published?.digest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
19149
19848
  const manifest = await receiver.manifest(status.published.sequence);
19150
19849
  if (publicationDigest(manifest) !== digest7 || ["tenantId", "companionId", "seatId"].some((field) => manifest.profile.identity[field] !== this.principal[field])) throw new Error("TRAVEL_NODE_CHECKPOINT");
@@ -19159,7 +19858,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19159
19858
  if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync22(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_PATH");
19160
19859
  const receipt2 = JSON.parse(readPrivateFile2(join38(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
19161
19860
  if (receipt2.receipt?.digest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
19162
- verifyRuntimeGenerationIntegrity(snapshot2, receipt2.integrity);
19861
+ await verifyRuntimeGenerationIntegrityAsync(snapshot2, receipt2.integrity);
19163
19862
  validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
19164
19863
  return { snapshot: snapshot2, manifest };
19165
19864
  }
@@ -19191,22 +19890,22 @@ var TravelNodeAgent = class _TravelNodeAgent {
19191
19890
  if (prior.archive_digest !== entry.receipt.digest || !isWithin(this.options.generationsDirectory, snapshot2) || realpathSync22(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19192
19891
  const proof = JSON.parse(readPrivateFile2(join38(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
19193
19892
  if (proof.recoveryArchive?.id !== entry.id || proof.recoveryArchive?.digest !== entry.receipt.digest || !same12(proof.receipt, entry.publication) || !same12(proof.profile, manifest.profile)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19194
- verifyRuntimeGenerationIntegrity(snapshot2, proof.integrity);
19893
+ await verifyRuntimeGenerationIntegrityAsync(snapshot2, proof.integrity);
19195
19894
  validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
19196
19895
  await check();
19197
19896
  return { snapshot: snapshot2, manifest };
19198
19897
  }
19199
19898
  const snapshot = join38(this.options.generationsDirectory, "snapshot-" + randomUUID15());
19200
- await restoreRecoveryArchive({ archive: this.archive, id: entry.id, destination: snapshot, deletionWatermark: check });
19899
+ await restoreRecoveryArchive({ archive: this.archive, id: entry.id, destination: snapshot, deletionWatermark: check, verifyDatabases: false });
19201
19900
  validateRuntimeActivationSnapshot(snapshot, manifest, locations);
19202
19901
  await check();
19203
- writeFileSync26(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19902
+ writeFileSync25(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19204
19903
  format: "engine7-runtime-publication-restore-v1",
19205
19904
  profile: manifest.profile,
19206
19905
  receipt: entry.publication,
19207
19906
  databases: manifest.databases,
19208
19907
  recoveryArchive: { id: entry.id, digest: entry.receipt.digest },
19209
- integrity: runtimeGenerationIntegrity(snapshot),
19908
+ integrity: await runtimeGenerationIntegrityAsync(snapshot),
19210
19909
  activationAllowed: false
19211
19910
  }), { mode: 384, flag: "wx", flush: true });
19212
19911
  await syncDirectory(snapshot);
@@ -19236,13 +19935,13 @@ var TravelNodeAgent = class _TravelNodeAgent {
19236
19935
  }
19237
19936
  const snapshot = join38(this.options.generationsDirectory, "snapshot-" + randomUUID15());
19238
19937
  await restoreCurrentHForDeletion({ archive: this.archive, id: id2, destination: snapshot, ...control2 });
19239
- writeFileSync26(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19938
+ writeFileSync25(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19240
19939
  format: "engine7-runtime-publication-restore-v1",
19241
19940
  profile: manifest.profile,
19242
19941
  receipt: entry.publication,
19243
19942
  databases: manifest.databases,
19244
19943
  recoveryArchive: { id: entry.id, digest: entry.receipt.digest },
19245
- integrity: runtimeGenerationIntegrity(snapshot),
19944
+ integrity: await runtimeGenerationIntegrityAsync(snapshot),
19246
19945
  activationAllowed: false
19247
19946
  }), { mode: 384, flag: "wx", flush: true });
19248
19947
  await syncDirectory(snapshot);
@@ -19272,12 +19971,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
19272
19971
  if (replica.receiver.objects !== this.archive.objects) throw new Error("TRAVEL_NODE_REPLICA_OBJECTS");
19273
19972
  if (!await (this.options.verifyDirectory ?? verifyRuntimeDirectory)(this.options.generationsDirectory)) throw new Error("TRAVEL_NODE_DIRECTORY");
19274
19973
  await check();
19275
- const status = await replica.receiver.status();
19974
+ const status = await replica.receiver.status(false);
19276
19975
  if (!status.dataReady || !status.published || status.profile.epoch !== (await this.options.authority.status(this.principal)).epoch) throw new Error("TRAVEL_NODE_CHECKPOINT");
19277
19976
  const prepared = await this.prepared(status.published.digest, replica);
19278
19977
  if (!same12(Object.keys(replica.databases).sort(), prepared.manifest.profile.databaseIds)) throw new Error("TRAVEL_NODE_CHECKPOINT");
19279
- for (const id2 of prepared.manifest.profile.databaseIds) validateRecoveryDatabase(replica.databases[id2], prepared.manifest, id2, "replica");
19280
- const after = await replica.receiver.status();
19978
+ for (const id2 of prepared.manifest.profile.databaseIds) validateRecoveryDatabase(replica.databases[id2], prepared.manifest, id2, "replica", void 0, false);
19979
+ const after = await replica.receiver.status(false);
19281
19980
  await check();
19282
19981
  if (!after.dataReady || after.published?.digest !== status.published.digest || prepared.manifest.profile.epoch !== (await this.options.authority.status(this.principal)).epoch) throw new Error("TRAVEL_NODE_CHECKPOINT");
19283
19982
  if ((prepared.deletionWatermark ?? prepared.manifest.deletionWatermark) !== this.keyWatermark) throw new Error("TRAVEL_NODE_DELETION_BARRIER");
@@ -19305,7 +20004,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19305
20004
  }
19306
20005
  replicaProfile() {
19307
20006
  return this.exclusive(async () => {
19308
- await this.refreshKey();
20007
+ await this.freshKeyWatermark();
19309
20008
  return (await this.currentReceiver())?.profile ?? null;
19310
20009
  });
19311
20010
  }
@@ -19353,14 +20052,20 @@ var TravelNodeAgent = class _TravelNodeAgent {
19353
20052
  trace("source-check");
19354
20053
  const token = this.generationToken;
19355
20054
  let currentPermit = request7.permit;
19356
- const boundedCheck = async () => {
20055
+ const localCheck = () => {
19357
20056
  if (this.closed || token !== this.generationToken) throw new Error("TRAVEL_NODE_CANCELLED");
19358
20057
  if (this.runtime || this.process || this.dataProcess) throw new Error("TRAVEL_NODE_GENERATION_COLLISION");
19359
- this.assertKey();
20058
+ this.assertLocalDataAvailable();
20059
+ };
20060
+ const boundedCheck = async () => {
20061
+ localCheck();
19360
20062
  const permit = currentPermit;
19361
- await this.options.authority.assertPermit(permit, "CONTROL");
19362
20063
  if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request7.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request7.principal[key2]) || request7.principal.nodeId === this.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key2) => request7.principal[key2] !== this.principal[key2])) throw new Error("TRAVEL_NODE_IDENTITY");
19363
- return (await this.options.authority.status(this.principal)).deletionWatermark;
20064
+ const authority = this.options.authority, status = authority.assertPermitWithStatus ? await authority.assertPermitWithStatus(permit, "CONTROL") : (await authority.assertPermit(permit, "CONTROL"), await authority.status(this.principal));
20065
+ localCheck();
20066
+ if (status.expired || status.authorityBootId !== permit.authorityBootId || status.epoch !== permit.epoch || status.activeNodeId !== permit.nodeId || status.activeBootId !== permit.bootId) throw new Error("TRAVEL_NODE_CHECKPOINT");
20067
+ if (status.deletionWatermark !== this.keyWatermark) throw new Error("TRAVEL_NODE_KEY_UNAVAILABLE");
20068
+ return status.deletionWatermark;
19364
20069
  };
19365
20070
  const check = async () => {
19366
20071
  currentPermit = await (request7.permitSupplier?.() ?? request7.permit);
@@ -19389,7 +20094,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19389
20094
  await check();
19390
20095
  if (entry.kind !== "LOCAL" || entry.receipt.digest !== request7.archiveDigest || publicationDigest(entry.manifest) !== request7.expectedDigest || entry.manifest.profile.epoch !== request7.permit.epoch || entry.manifest.profile.buildManifestId !== this.options.build.manifestId) throw new Error("TRAVEL_NODE_CHECKPOINT");
19391
20096
  trace("copy-source-archive");
19392
- await transferRecoveryArchive({ peer, archive: this.archive, id: request7.archiveId, expectedDigest: request7.archiveDigest, deletionWatermark: boundedCheck, beforeStep: boundedCheck });
20097
+ await transferRecoveryArchive({ peer, archive: this.archive, id: request7.archiveId, expectedDigest: request7.archiveDigest, entry, deletionWatermark: boundedCheck, beforeStep: async () => localCheck() });
19393
20098
  await check();
19394
20099
  if (!this.replicaRepository) {
19395
20100
  const initialize2 = this.db.prepare("SELECT replicas_ready FROM lifecycle WHERE id=1").get()?.replicas_ready === 0;
@@ -19398,8 +20103,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
19398
20103
  }
19399
20104
  await check();
19400
20105
  trace("seed-receiver");
19401
- const replica = await this.replicaRepository.bootstrap({ ...request7, authority: this.options.authority, permitSupplier: async () => {
19402
- await boundedCheck();
20106
+ const replica = await this.replicaRepository.bootstrap({ ...request7, authority: this.options.authority, permitSupplier: () => {
20107
+ localCheck();
19403
20108
  return currentPermit;
19404
20109
  } });
19405
20110
  await check();
@@ -19420,7 +20125,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19420
20125
  if (!this.runtime && !this.process && !this.dataProcess) await this.preserveBranches();
19421
20126
  if (!await (this.options.verifyDirectory ?? verifyRuntimeDirectory)(this.options.generationsDirectory)) throw new Error("TRAVEL_NODE_DIRECTORY");
19422
20127
  const prepared = await this.prepared(digest7), effects = await this.options.gateway.preparationEvidence(this.principal);
19423
- const replica = this.replica, status = await replica?.receiver.status();
20128
+ const replica = this.replica, status = await replica?.receiver.status(false);
19424
20129
  if (prepared.deletionWatermark === void 0 && replica && status?.dataReady && status.published?.digest === digest7) {
19425
20130
  await this.archive.preserve({
19426
20131
  id: "common-" + digest7,
@@ -19428,10 +20133,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
19428
20133
  manifest: prepared.manifest,
19429
20134
  databases: replica.databases,
19430
20135
  receiver: replica.receiver,
19431
- deletionWatermark: () => {
19432
- this.assertKey();
19433
- return this.keyWatermark;
19434
- }
20136
+ deletionWatermark: () => this.freshKeyWatermark(),
20137
+ verifyRetained: false
19435
20138
  });
19436
20139
  }
19437
20140
  const deletionWatermark = prepared.deletionWatermark ?? prepared.manifest.deletionWatermark;
@@ -19474,9 +20177,9 @@ var TravelNodeAgent = class _TravelNodeAgent {
19474
20177
  await this.refreshKey();
19475
20178
  this.assertKey();
19476
20179
  if (!/^[a-f0-9]{64}$/.test(digest7)) throw new Error("TRAVEL_NODE_CHECKPOINT");
19477
- const replica = this.replica, status = await replica?.receiver.status();
20180
+ const replica = this.replica, status = await replica?.receiver.status(false);
19478
20181
  const deletionWatermark = async () => {
19479
- this.assertKey();
20182
+ await this.freshKeyWatermark();
19480
20183
  return (await this.options.authority.status(this.principal)).deletionWatermark;
19481
20184
  };
19482
20185
  if (replica && status?.dataReady && status.published?.digest === digest7) {
@@ -19488,7 +20191,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
19488
20191
  manifest: prepared.manifest,
19489
20192
  databases: replica.databases,
19490
20193
  receiver: replica.receiver,
19491
- deletionWatermark
20194
+ deletionWatermark,
20195
+ verifyRetained: false
19492
20196
  });
19493
20197
  return;
19494
20198
  }
@@ -19517,7 +20221,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19517
20221
  await check();
19518
20222
  if (entry.kind !== "COMMON" || entry.id !== id2 || entry.publication?.digest !== digest7 || publicationDigest(entry.manifest) !== digest7 || !same12(entry.manifest.profile, profile2)) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
19519
20223
  trace("copy-common");
19520
- await transferRecoveryArchive({ peer: peer2, archive: this.archive, id: id2, expectedDigest: entry.receipt.digest, deletionWatermark: check });
20224
+ await transferRecoveryArchive({ peer: peer2, archive: this.archive, id: id2, expectedDigest: entry.receipt.digest, entry, deletionWatermark: check });
19521
20225
  await check();
19522
20226
  await this.preparedCommon(digest7);
19523
20227
  return;
@@ -19540,7 +20244,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19540
20244
  return current2.deletionWatermark;
19541
20245
  };
19542
20246
  trace("copy-common");
19543
- await transferRecoveryArchive({ peer, archive: this.archive, id: id2, expectedDigest: entry.receipt.digest, deletionWatermark: check });
20247
+ await transferRecoveryArchive({ peer, archive: this.archive, id: id2, expectedDigest: entry.receipt.digest, entry, deletionWatermark: check });
19544
20248
  await check();
19545
20249
  } finally {
19546
20250
  peer.close();
@@ -19598,7 +20302,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19598
20302
  assertActive();
19599
20303
  const prepared = await this.prepared(digest7), confirmed = await this.confirmPermit(permit);
19600
20304
  await assertGatewayResolved();
19601
- const replica = this.replica, replicaStatus = await replica?.receiver.status();
20305
+ const replica = this.replica, replicaStatus = await replica?.receiver.status(false);
19602
20306
  if (replica && replicaStatus?.dataReady && replicaStatus.published?.digest === digest7) {
19603
20307
  const common = await this.archive.read("common-" + digest7);
19604
20308
  if (common.kind !== "COMMON" || !same12(common.manifest, prepared.manifest)) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
@@ -19643,7 +20347,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19643
20347
  await assertGatewayResolved();
19644
20348
  const configFile = join38(destination, ".continuity", "engine-config.json"), config = { ...this.options.engineConfig, stateDir: destination, workspace: join38(destination, this.options.layout.trees.workspace) };
19645
20349
  validateTravelChannelConfiguration(config.channels);
19646
- writeFileSync26(configFile, JSON.stringify(config), { mode: 384, flush: true });
20350
+ writeFileSync25(configFile, JSON.stringify(config), { mode: 384, flush: true });
19647
20351
  const processDirectory = join38(this.options.directory, "processes");
19648
20352
  mkdirSync16(processDirectory, { recursive: true, mode: 448 });
19649
20353
  const dataRoot = join38(this.options.directory, "data");
@@ -19651,7 +20355,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19651
20355
  this.dataDirectory = join38(dataRoot, "source-" + hash10(binding));
19652
20356
  const encode2 = (value2) => value2.toString("base64"), keyService = this.options.keyService;
19653
20357
  const dataConfigFile = join38(destination, ".continuity", "data-config.json");
19654
- writeFileSync26(dataConfigFile, JSON.stringify({
20358
+ writeFileSync25(dataConfigFile, JSON.stringify({
19655
20359
  stateDir: destination,
19656
20360
  dataDirectory: this.dataDirectory,
19657
20361
  objectsDirectory: join38(dataRoot, "objects"),
@@ -19666,7 +20370,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19666
20370
  entry: this.options.dataBuild.entry,
19667
20371
  entrySha256: this.options.dataBuild.sha256,
19668
20372
  configFile: dataConfigFile,
19669
- timeoutMs: this.options.processTimeoutMs
20373
+ timeoutMs: this.options.dataProcessTimeoutMs ?? 3e5
19670
20374
  });
19671
20375
  await this.dataProcess.start();
19672
20376
  assertActive();
@@ -19808,7 +20512,20 @@ var TravelNodeAgent = class _TravelNodeAgent {
19808
20512
  const local = source ? await source.read(receipt2.id) : await peer.read(receipt2.id);
19809
20513
  await check();
19810
20514
  if (!same12(local.receipt, receipt2) || local.kind !== "LOCAL") throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19811
- if (local.manifest.profile.epoch < permit.epoch) missing.push({ receipt: receipt2, own, local, source });
20515
+ if (local.manifest.profile.epoch < permit.epoch) {
20516
+ validateRecoveryArchiveEntry(local, this.archive.objects.identity);
20517
+ const head = (await this.options.authority.status(this.principal)).checkpointDigest;
20518
+ await check();
20519
+ let committed = false;
20520
+ try {
20521
+ await this.options.authority.verifyAncestor(this.principal, receipt2.manifestDigest, head);
20522
+ committed = true;
20523
+ } catch (error) {
20524
+ if (!(error instanceof Error) || error.message !== "TRAVEL_ANCESTRY_GAP") throw error;
20525
+ }
20526
+ await check();
20527
+ if (!committed) missing.push({ receipt: receipt2, own, local, source });
20528
+ }
19812
20529
  }
19813
20530
  if (missing.length) {
19814
20531
  trace("capture-current-remote");
@@ -19997,15 +20714,21 @@ var TravelNodeAgent = class _TravelNodeAgent {
19997
20714
  const token = this.generationToken, runtime = this.runtime, child = this.dataProcess, control2 = this.checkpointControl;
19998
20715
  const operation = (async () => {
19999
20716
  if (!runtime || !child || !control2) throw new Error("TRAVEL_PERMIT_REQUIRED");
20000
- const check = async () => {
20717
+ const localCheck = () => {
20001
20718
  if (this.closed || this.stopping || this.generationToken !== token || this.runtime !== runtime) throw new Error("TRAVEL_NODE_CANCELLED");
20002
- await this.assertDataAvailable();
20719
+ this.assertLocalDataAvailable();
20003
20720
  runtime.assert("CONTROL");
20004
20721
  };
20722
+ const check = async () => {
20723
+ localCheck();
20724
+ await this.assertDataAvailable();
20725
+ localCheck();
20726
+ };
20005
20727
  for (let batch = 0; batch < 16; batch++) {
20006
- await check();
20728
+ localCheck();
20007
20729
  const proof = await child.publishedCheckpoints(control2.status().sequence);
20008
- await check();
20730
+ localCheck();
20731
+ if (proof.checkpoints?.length) await check();
20009
20732
  await control2.advance(proof);
20010
20733
  if (proof.checkpoints.length < 64) break;
20011
20734
  }
@@ -20250,9 +20973,12 @@ var RemoteTravelDataAuthority = class {
20250
20973
  this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
20251
20974
  }
20252
20975
  async authenticate(credential) {
20976
+ return Object.freeze({ ...(await this.readIdentity(credential)).principal });
20977
+ }
20978
+ readIdentity(credential) {
20253
20979
  const grant = this.grants.find((grant2) => grant2.credential === credential);
20254
20980
  if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
20255
- return Object.freeze({ ...(await this.read(grant)).principal });
20981
+ return this.read(grant);
20256
20982
  }
20257
20983
  grant(principal) {
20258
20984
  const grant = this.grants.find((grant2) => equal3(principal, grant2.principal));
@@ -20302,9 +21028,8 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
20302
21028
  }
20303
21029
  const remote = new _RemoteTravelNodeAuthority(options.publicKey, options.grants);
20304
21030
  for (const grant of options.grants) {
20305
- const identity = await grant.client.identity();
21031
+ const identity = await remote.readIdentity(grant.credential);
20306
21032
  if (identity.publicKey !== options.publicKey) throw new Error("TRAVEL_NODE_SIGNER_MISMATCH");
20307
- await remote.authenticate(grant.credential);
20308
21033
  }
20309
21034
  return remote;
20310
21035
  }
@@ -20391,9 +21116,12 @@ var TravelReportClient = class {
20391
21116
  this.timeout = options.timeoutMs ?? 8e3;
20392
21117
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
20393
21118
  this.key = options.key ? Buffer.from(options.key) : void 0;
20394
- this.agent = new Agent3({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
21119
+ const tls2 = { ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, maxSockets: 1 };
21120
+ this.agent = new Agent3({ ...tls2, keepAlive: true });
21121
+ this.mutationAgent = new Agent3({ ...tls2, keepAlive: false });
20395
21122
  }
20396
21123
  agent;
21124
+ mutationAgent;
20397
21125
  key;
20398
21126
  url;
20399
21127
  timeout;
@@ -20420,7 +21148,7 @@ var TravelReportClient = class {
20420
21148
  if (error) reject(error);
20421
21149
  else resolve30(value2);
20422
21150
  };
20423
- const req = request4(this.url, { method: "POST", agent: this.agent, headers: {
21151
+ const req = request4(this.url, { method: "POST", agent: readActions.has(input?.action) ? this.agent : this.mutationAgent, headers: {
20424
21152
  Authorization: "Bearer " + this.options.credential,
20425
21153
  "X-Engine7-Travel-Node": this.options.nodeId,
20426
21154
  "Content-Type": "application/json",
@@ -20495,6 +21223,7 @@ var TravelReportClient = class {
20495
21223
  this.closed = true;
20496
21224
  for (const req of this.pending) req.destroy();
20497
21225
  this.agent.destroy();
21226
+ this.mutationAgent.destroy();
20498
21227
  this.key?.fill(0);
20499
21228
  }
20500
21229
  };
@@ -20598,8 +21327,8 @@ var publicErrors2 = /* @__PURE__ */ new Set([
20598
21327
  "TRAVEL_GATEWAY_DELETION_BARRIER"
20599
21328
  ]);
20600
21329
  function encodeInput(input) {
20601
- const { body, ...metadata3 } = input;
20602
- return { ...metadata3, bodyBase64: body.toString("base64") };
21330
+ const { body, ...metadata4 } = input;
21331
+ return { ...metadata4, bodyBase64: body.toString("base64") };
20603
21332
  }
20604
21333
  function decodeBody(value2, maximum = 16 * 1024 * 1024) {
20605
21334
  if (typeof value2 !== "string" || value2.length > Math.ceil(maximum / 3) * 4) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
@@ -20689,8 +21418,8 @@ var TravelGatewayClient = class {
20689
21418
  if (!Array.isArray(result) || result.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_RESPONSE");
20690
21419
  return result.map((item) => {
20691
21420
  if (!item || typeof item.id !== "string" || !/^[a-f0-9]{64}$/.test(item.id) || !["EXECUTE", "RESUME_OUTPUT", "RECONCILE"].includes(item.mode) || item.nodeId !== permit.nodeId || item.bootId !== permit.bootId || item.epoch !== permit.epoch) throw new Error("TRAVEL_GATEWAY_INVALID_RESPONSE");
20692
- const { bodyBase64, ...metadata3 } = item;
20693
- return { ...metadata3, body: decodeBody(bodyBase64) };
21421
+ const { bodyBase64, ...metadata4 } = item;
21422
+ return { ...metadata4, body: decodeBody(bodyBase64) };
20694
21423
  });
20695
21424
  }
20696
21425
  async ack(permit, eventId2) {
@@ -20751,6 +21480,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
20751
21480
  "TRAVEL_NODE_CANCELLED",
20752
21481
  "TRAVEL_NODE_BOOT_MISMATCH",
20753
21482
  "TRAVEL_NODE_CHECKPOINT",
21483
+ "TRAVEL_NODE_COMMON_CHECKPOINT",
20754
21484
  "TRAVEL_NODE_GENERATION_COLLISION",
20755
21485
  "TRAVEL_NODE_KEY_UNAVAILABLE",
20756
21486
  "TRAVEL_NODE_KEY_BARRIER",
@@ -20842,13 +21572,16 @@ var RemoteTravelNodeSupervisor = class {
20842
21572
  observeQuery;
20843
21573
  permitQuery;
20844
21574
  closed = false;
20845
- call(action, args = {}, discover = false) {
21575
+ call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
20846
21576
  if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
20847
21577
  const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
20848
21578
  if ([...this.pending.values()].includes(slot)) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
20849
- const body = Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
21579
+ const body = wireBody ?? Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
20850
21580
  if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
20851
21581
  const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
21582
+ deadline ??= performance.now() + (slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
21583
+ const remaining = deadline - performance.now();
21584
+ if (remaining <= 0) return Promise.reject(unavailable());
20852
21585
  return new Promise((resolve30, reject) => {
20853
21586
  const started = performance.now();
20854
21587
  let responseStarted = false, receivedBytes = 0, reported = false;
@@ -20915,14 +21648,17 @@ var RemoteTravelNodeSupervisor = class {
20915
21648
  const timer = setTimeout(() => {
20916
21649
  lost("TIMEOUT");
20917
21650
  req.destroy();
20918
- }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
21651
+ }, remaining);
20919
21652
  const cleanup = () => {
20920
21653
  clearTimeout(timer);
20921
21654
  this.pending.delete(req);
20922
21655
  };
20923
21656
  req.once("error", (error) => {
20924
21657
  cleanup();
20925
- lost(error.code);
21658
+ if (!reported && retryStale && !this.closed && !responseStarted && (slot === "observe" || slot === "permit") && req.reusedSocket && error.code === "ECONNRESET") {
21659
+ reported = true;
21660
+ resolve30(this.call(action, args, discover, false, deadline, body));
21661
+ } else lost(error.code);
20926
21662
  });
20927
21663
  req.once("close", cleanup);
20928
21664
  req.end(body);
@@ -21157,7 +21893,7 @@ var path2 = (value2) => {
21157
21893
  if (typeof value2 !== "string" || !isAbsolute10(value2) || resolve29(value2) !== value2) throw new Error("TRAVEL_NODE_PATH");
21158
21894
  return value2;
21159
21895
  };
21160
- var tls = (value2) => ({ ca: readFileSync16(path2(value2?.caFile)), cert: readFileSync16(path2(value2?.certFile)), key: readPrivateFile2(path2(value2?.keyFile), 65536) });
21896
+ var tls = (value2) => ({ ca: readFileSync15(path2(value2?.caFile)), cert: readFileSync15(path2(value2?.certFile)), key: readPrivateFile2(path2(value2?.keyFile), 65536) });
21161
21897
  async function startTravelNodeService(input) {
21162
21898
  if (!nodeSupervisorRecord(input) || !nodeSupervisorRecord(input.principal) || !nodeSupervisorRecord(input.peer) || !nodeSupervisorRecord(input.control) || !nodeSupervisorRecord(input.management) || !nodeSupervisorRecord(input.data) || Object.hasOwn(input, "authorityDir")) throw new Error("TRAVEL_NODE_CONFIG");
21163
21899
  const config = input;
@@ -21248,6 +21984,7 @@ async function startTravelNodeService(input) {
21248
21984
  environmentNames: config.environmentNames,
21249
21985
  heartbeatIntervalMs: config.heartbeatIntervalMs,
21250
21986
  processTimeoutMs: config.processTimeoutMs,
21987
+ dataProcessTimeoutMs: config.dataProcessTimeoutMs,
21251
21988
  dataIntervalMs: config.dataIntervalMs,
21252
21989
  keyRefreshIntervalMs: config.keyRefreshIntervalMs,
21253
21990
  keyMaxAgeMs: config.keyMaxAgeMs,
@@ -21260,7 +21997,7 @@ async function startTravelNodeService(input) {
21260
21997
  const profile = normalizePublicationProfile(config.initialReplica.profile), databases = {}, replicas = {};
21261
21998
  if (JSON.stringify(Object.keys(config.initialReplica.databases).sort()) !== JSON.stringify(profile.databaseIds)) throw new Error("TRAVEL_NODE_REPLICA_NOT_READY");
21262
21999
  for (const id2 of profile.databaseIds) {
21263
- const file = path2(config.initialReplica.databases[id2]), stat = lstatSync27(file);
22000
+ const file = path2(config.initialReplica.databases[id2]), stat = lstatSync26(file);
21264
22001
  if (!stat.isFile() || stat.isSymbolicLink() || realpathSync23(file) !== file || process.platform !== "win32" && (stat.uid !== process.getuid() || stat.mode & 63)) throw new Error("TRAVEL_NODE_PATH");
21265
22002
  const db = new DatabaseSync30(file, { allowExtension: id2 === "legacy" });
21266
22003
  replicaHandles.push(db);