engine7 7.1.137 → 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,11 +58,11 @@ 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;
62
- if (name !== "feishu") throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
61
+ if (name === "emotion" || value2?.enabled !== true) continue;
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
- const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key2, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken"].includes(key2) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
65
- if (hasPlatformSecret(value2) || ["FEISHU_APP_SECRET", "LARK_APP_SECRET", "FEISHU_ACCESS_TOKEN"].some((k) => !!process.env[k])) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
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));
65
+ if (hasPlatformSecret(value2) || ["FEISHU_APP_SECRET", "LARK_APP_SECRET", "FEISHU_ACCESS_TOKEN", "DISCORD_TOKEN", "WECHAT_TOKEN"].some((k) => !!process.env[k])) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
66
66
  let url;
67
67
  try {
68
68
  url = new URL(value2.gatewayUrl);
@@ -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,9 +3449,10 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3065
3449
  probe.close();
3066
3450
  }
3067
3451
  }
3068
- for (const tree of value2.manifest.trees) for (const file of tree.files) {
3069
- floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
3070
- await verifyContent(this.objects, file.content);
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;
3071
3456
  }
3072
3457
  const ref = await this.objects.putContent(body);
3073
3458
  await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
@@ -3084,7 +3469,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3084
3469
  }
3085
3470
  return (await this.read(value2.id)).receipt;
3086
3471
  } finally {
3087
- rmSync(temporary, { recursive: true, force: true });
3472
+ if (temporary) rmSync(temporary, { recursive: true, force: true });
3088
3473
  await syncDirectory(this.directory);
3089
3474
  }
3090
3475
  }
@@ -3102,13 +3487,13 @@ async function verifyContent(objects, content) {
3102
3487
  }
3103
3488
 
3104
3489
  // src/continuity/sqlite-store-location.ts
3105
- 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";
3106
3491
 
3107
3492
  // src/continuity/mem7-replication.ts
3108
- import { closeSync as closeSync4, fsyncSync as fsyncSync4, lstatSync as lstatSync6, openSync as openSync5, writeFileSync as writeFileSync4 } from "node:fs";
3109
- 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";
3110
3495
  init_sqlite_replication();
3111
- var location = (stateDir) => join5(stateDir, ".continuity", "mem7-replication.json");
3496
+ var location = (stateDir) => join6(stateDir, ".continuity", "mem7-replication.json");
3112
3497
  function normalize(value2) {
3113
3498
  if (!value2 || !/^[a-f0-9]{64}$/.test(value2.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
3114
3499
  return Object.freeze({ binding: normalizeBinding(value2.binding), schemaHash: value2.schemaHash });
@@ -3140,7 +3525,7 @@ function ensureMem7ReplicationRegistration(stateDir, input) {
3140
3525
  const file = location(stateDir);
3141
3526
  preparePrivateDirectory(dirname3(file));
3142
3527
  try {
3143
- writeFileSync4(file, JSON.stringify(registration), { mode: 384, flag: "wx", flush: true });
3528
+ writeFileSync3(file, JSON.stringify(registration), { mode: 384, flag: "wx", flush: true });
3144
3529
  } catch (error) {
3145
3530
  if (error.code !== "EEXIST") throw error;
3146
3531
  if (JSON.stringify(readMem7ReplicationRegistration(stateDir)) !== JSON.stringify(registration)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
@@ -3158,7 +3543,7 @@ function ensureMem7ReplicationRegistration(stateDir, input) {
3158
3543
  // src/continuity/sqlite-store-location.ts
3159
3544
  init_runtime_replication();
3160
3545
  function sqliteStoreLocation(file) {
3161
- const absolute = resolve6(file), parent = dirname5(absolute), name = basename3(absolute);
3546
+ const absolute = resolve7(file), parent = dirname5(absolute), name = basename3(absolute);
3162
3547
  if (name === "mem7.db" && basename3(parent) === "index" && basename3(dirname5(parent)) === "mem7")
3163
3548
  return { stateDir: dirname5(dirname5(parent)), component: "mem7" };
3164
3549
  let stateDir, component;
@@ -3261,21 +3646,40 @@ function initializeRecoveryAdmission(db) {
3261
3646
 
3262
3647
  // src/continuity/generation-integrity.ts
3263
3648
  import { createHash as createHash5 } from "node:crypto";
3264
- 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";
3265
- import { join as join7, resolve as resolve7 } from "node:path";
3266
- function runtimeGenerationIntegrity(directory2) {
3267
- const root = resolve7(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
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 = [];
3268
3661
  if (realpathSync3(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3269
3662
  const visit = (path3) => {
3270
3663
  if (path3 === ".runtime-publication-receipt.json") return;
3271
- const file = join7(root, path3), before = lstatSync8(file, { bigint: true });
3272
- if (before.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3273
- if (before.isDirectory()) {
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()) {
3274
3667
  for (const name of readdirSync(file).sort()) visit(path3 ? path3 + "/" + name : name);
3275
3668
  return;
3276
3669
  }
3277
- if (!before.isFile() || before.size > BigInt(Number.MAX_SAFE_INTEGER) || result.length >= 1e5) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3278
- const fd = openSync7(file, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0)), hash11 = createHash5("sha256");
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");
3279
3683
  let bytes = 0;
3280
3684
  try {
3281
3685
  while (true) {
@@ -3285,173 +3689,63 @@ function runtimeGenerationIntegrity(directory2) {
3285
3689
  bytes += size;
3286
3690
  }
3287
3691
  const after = fstatSync5(fd, { bigint: true });
3288
- 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");
3692
+ if (metadata2(before) !== metadata2(after) || metadata2(before) !== metadata2(lstatSync8(file, { bigint: true })) || BigInt(bytes) !== before.size) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3289
3693
  result.push({ path: path3, bytes, mode: Number(before.mode & 0o777n), sha256: hash11.digest("hex") });
3290
- } finally {
3291
- closeSync6(fd);
3292
- }
3293
- };
3294
- visit("");
3295
- return result.sort((a, b) => a.path.localeCompare(b.path, "en"));
3296
- }
3297
- function verifyRuntimeGenerationIntegrity(directory2, expected) {
3298
- if (!Array.isArray(expected) || JSON.stringify(runtimeGenerationIntegrity(directory2)) !== JSON.stringify(expected)) throw new Error("TRAVEL_GENERATION_INTEGRITY");
3299
- }
3300
-
3301
- // src/continuity/inventory.ts
3302
- import { constants as constants8 } from "node:fs";
3303
- import { lstat as lstat2, open as open2, readdir, realpath } from "node:fs/promises";
3304
- import { isAbsolute, join as join8, relative, resolve as resolve8, sep } from "node:path";
3305
- 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(" "));
3306
- var STATE_EXCLUDED = {
3307
- ".continuity": "local runtime control; never business state",
3308
- ".engine.pid": "local process identity",
3309
- ".bg-worker.pid": "local process identity",
3310
- ".travel-restored.json": "deployment activation gate; recreated on restore",
3311
- ".travel-enrolled.json": "local runtime enrollment; recreated per node",
3312
- ".travel-active.json": "local activation receipt; recreated per generation",
3313
- ".git": "source control metadata",
3314
- ".gitignore": "source control metadata",
3315
- ".log-baseline.txt": "local diagnostics",
3316
- logs: "local diagnostics; not authoritative history",
3317
- diagnostics: "local diagnostics",
3318
- backups: "historical recovery copies; not active state",
3319
- "package.json": "installed application metadata",
3320
- "start.sh": "local launcher; deployment must be reviewed separately",
3321
- node_modules: "installed dependencies",
3322
- install: "installed application",
3323
- CogniFold: "installed optional runtime",
3324
- "everos-venv": "installed Python runtime",
3325
- "ollama-models": "installed model weights"
3326
- };
3327
- var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
3328
- var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
3329
- function stateReason(name, options) {
3330
- if (options.includeStateEntries?.includes(name)) return void 0;
3331
- return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
3332
- }
3333
- function knownState(name) {
3334
- return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
3335
- }
3336
- async function classifyState(options) {
3337
- const result = { included: [], excluded: [], unclassified: [] };
3338
- for (const name of (await readdir(options.stateDir)).sort()) {
3339
- const reason = stateReason(name, options);
3340
- if (reason) result.excluded.push({ path: name, reason });
3341
- else if (knownState(name) || options.includeStateEntries?.includes(name) || resolve8(options.stateDir, name) === resolve8(options.workspace ?? join8(options.stateDir, "workspace"))) result.included.push(name);
3342
- else result.unclassified.push(name);
3343
- }
3344
- return result;
3345
- }
3346
- function validateRelativePath(path3) {
3347
- if (typeof path3 !== "string" || !path3 || path3.length > 2048 || path3.includes("\\") || isAbsolute(path3)) throw new Error("INVALID_ARTIFACT_PATH");
3348
- for (const part of path3.split("/")) {
3349
- 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)
3350
- throw new Error("INVALID_ARTIFACT_PATH");
3351
- }
3352
- }
3353
- function isWithin(root, candidate) {
3354
- const rel = relative(resolve8(root), resolve8(candidate));
3355
- return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
3356
- }
3357
- async function collectInventory(options) {
3358
- const state2 = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join8(state2, "workspace"));
3359
- if (state2 === workspace || isWithin(workspace, state2)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
3360
- const roots = { state: state2, workspace }, entries = [], exclusions = [], aliases = /* @__PURE__ */ new Set();
3361
- const include = new Set(options.includeStateEntries ?? []);
3362
- for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
3363
- validateRelativePath(name);
3364
- if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
3365
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
3366
- }
3367
- for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
3368
- for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
3369
- validateRelativePath(name);
3370
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
3371
- if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
3372
- }
3373
- const classification = await classifyState(options);
3374
- if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
3375
- async function walk(root, directory2, prefix2 = "") {
3376
- for (const name of (await readdir(directory2)).sort()) {
3377
- const path3 = prefix2 ? prefix2 + "/" + name : name, source = join8(directory2, name);
3378
- if (root === "state" && source === workspace) continue;
3379
- let reason = NESTED_EXCLUDED[name];
3380
- if (root === "state" && prefix2) reason = options.excludeStateEntries?.[path3] ?? reason;
3381
- if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path3] ?? reason;
3382
- if (!prefix2 && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
3383
- if (root === "state" && !prefix2) {
3384
- reason = stateReason(name, options);
3385
- if (!reason && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
3386
- }
3387
- if (reason) {
3388
- exclusions.push({ root, path: path3, reason });
3389
- continue;
3390
- }
3391
- validateRelativePath(path3);
3392
- const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
3393
- if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
3394
- aliases.add(key2);
3395
- const info = await lstat2(source, { bigint: true });
3396
- if (info.isSymbolicLink()) throw new Error(`SYMLINK_REFUSED: ${root}/${path3}`);
3397
- if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
3398
- if (info.isDirectory()) {
3399
- try {
3400
- const marker = await lstat2(join8(source, "pyvenv.cfg"));
3401
- if (marker.isFile() && !marker.isSymbolicLink()) {
3402
- exclusions.push({ root, path: path3, reason: "installed Python virtual environment; rebuild for the target platform" });
3403
- continue;
3404
- }
3405
- } catch (error) {
3406
- if (error.code !== "ENOENT") throw error;
3407
- }
3408
- }
3409
- const entry = {
3410
- root,
3411
- path: path3,
3412
- source,
3413
- kind: info.isDirectory() ? "directory" : "file",
3414
- bytes: Number(info.size),
3415
- mode: Number(info.mode) & 448,
3416
- signature: [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
3417
- };
3418
- entries.push(entry);
3419
- if (info.isDirectory()) await walk(root, source, path3);
3420
- else {
3421
- const h = await open2(source, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
3422
- const header = Buffer.alloc(16);
3423
- try {
3424
- await h.read(header, 0, 16, 0);
3425
- } finally {
3426
- await h.close();
3427
- }
3428
- if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
3429
- else if (/\.(db|sqlite|sqlite3)$/i.test(path3)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path3}`);
3430
- }
3694
+ } finally {
3695
+ closeSync6(fd);
3431
3696
  }
3432
3697
  }
3433
- await walk("state", state2);
3434
- await walk("workspace", workspace);
3435
- const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
3436
- for (const entry of entries) {
3437
- if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
3438
- if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
3439
- 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();
3440
3719
  }
3441
3720
  }
3442
- 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");
3443
3737
  }
3444
3738
 
3445
3739
  // src/continuity/recovery-deletion-visibility.ts
3446
3740
  import { DatabaseSync as DatabaseSync11 } from "node:sqlite";
3447
3741
  import { createHash as createHash27, randomUUID as randomUUID11 } from "node:crypto";
3448
- 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";
3449
3743
  import { join as join18, resolve as resolve13 } from "node:path";
3450
3744
 
3451
3745
  // src/continuity/recovery-deletion-overlay.ts
3452
3746
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
3453
3747
  import { createHash as createHash26, randomUUID as randomUUID10 } from "node:crypto";
3454
- 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";
3455
3749
  import { dirname as dirname10, join as join17, resolve as resolve12 } from "node:path";
3456
3750
 
3457
3751
  // src/continuity/recovery-deletion-sources.ts
@@ -3707,7 +4001,7 @@ import { createHash as createHash11 } from "node:crypto";
3707
4001
 
3708
4002
  // src/mem7/core/change-feed.ts
3709
4003
  import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";
3710
- 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";
3711
4005
 
3712
4006
  // src/mem7/core/state/temporal.ts
3713
4007
  function instant(value2) {
@@ -4676,7 +4970,7 @@ var ChangeFeed = class _ChangeFeed {
4676
4970
  let ledger = {};
4677
4971
  if (ledgerPath) {
4678
4972
  try {
4679
- ledger = JSON.parse(readFileSync5(ledgerPath, "utf8"))?.heals ?? {};
4973
+ ledger = JSON.parse(readFileSync4(ledgerPath, "utf8"))?.heals ?? {};
4680
4974
  } catch {
4681
4975
  }
4682
4976
  if (Number.isFinite(ledger[key2])) {
@@ -4701,11 +4995,11 @@ var ChangeFeed = class _ChangeFeed {
4701
4995
  retained[key2] = now2;
4702
4996
  const temp = `${ledgerPath}.${randomUUID3()}.tmp`;
4703
4997
  try {
4704
- writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
4998
+ writeFileSync5(temp, JSON.stringify({ version: 1, heals: retained }));
4705
4999
  renameSync2(temp, ledgerPath);
4706
5000
  } catch (error) {
4707
5001
  try {
4708
- if (existsSync3(temp)) unlinkSync3(temp);
5002
+ if (existsSync3(temp)) unlinkSync2(temp);
4709
5003
  } catch {
4710
5004
  }
4711
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}`);
@@ -5573,12 +5867,20 @@ var MemoryTombstones = class {
5573
5867
  has(scope, kind, id2) {
5574
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));
5575
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
+ }
5576
5874
  any(scope) {
5577
5875
  return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? LIMIT 1").get(scopeId(scope)));
5578
5876
  }
5579
5877
  anyForOwner(ownerId) {
5580
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));
5581
5879
  }
5880
+ /** 1117:撤回校验的快速门——墓碑可挂在任意 scope(如旧 default 池)下,不看 owner。 */
5881
+ exists() {
5882
+ return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones LIMIT 1").get());
5883
+ }
5582
5884
  deleteSource(scope, sourceId, expectedVersion, requestKey, reason) {
5583
5885
  if (!requestKey || !reason.trim()) throw new Error("INVALID_DELETE_REQUEST");
5584
5886
  this.transaction(() => {
@@ -6141,7 +6443,7 @@ var JobProvenanceStore = class {
6141
6443
 
6142
6444
  // src/mem7/core/legacy-recovery.ts
6143
6445
  import { createHash as createHash21 } from "node:crypto";
6144
- import { readFileSync as readFileSync9, realpathSync as realpathSync5, statSync } from "node:fs";
6446
+ import { readFileSync as readFileSync8, realpathSync as realpathSync5, statSync } from "node:fs";
6145
6447
  import { isAbsolute as isAbsolute2, join as join13, relative as relative3, resolve as resolve9, sep as sep2 } from "node:path";
6146
6448
 
6147
6449
  // src/mem7/core/store.ts
@@ -6151,7 +6453,7 @@ init_sqlite_replication();
6151
6453
  import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
6152
6454
  init_sqlite_autocommit();
6153
6455
  init_schema_migrations();
6154
- 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";
6155
6457
  import { join as join12, relative as relative2 } from "node:path";
6156
6458
  import { createHash as createHash20, randomUUID as randomUUID8 } from "node:crypto";
6157
6459
 
@@ -6924,12 +7226,12 @@ var Mem7VectorStore = class {
6924
7226
  * public:get/ 分页列表也走这里收口) */
6925
7227
  toHit(kind, r) {
6926
7228
  const textCol = textColumnOf(kind);
6927
- const metadata3 = {};
7229
+ const metadata4 = {};
6928
7230
  const NOISE = /* @__PURE__ */ new Set(["vector", "_distance", "_score", "created_at", "updated_at", "id"]);
6929
7231
  for (const k of Object.keys(r)) {
6930
7232
  if (NOISE.has(k)) continue;
6931
7233
  const v = r[k];
6932
- metadata3[k] = typeof v?.toArray === "function" ? v.toArray() : v;
7234
+ metadata4[k] = typeof v?.toArray === "function" ? v.toArray() : v;
6933
7235
  }
6934
7236
  const ledger = this.publicationLedger();
6935
7237
  const dependencies2 = this.sharedDependencies();
@@ -6943,7 +7245,7 @@ var Mem7VectorStore = class {
6943
7245
  mdPath: r.md_path ? String(r.md_path) : void 0,
6944
7246
  distance: Number(r._distance ?? 0),
6945
7247
  score: 1 - Number(r._distance ?? 0),
6946
- metadata: metadata3,
7248
+ metadata: metadata4,
6947
7249
  ...ledger ? { assertCurrent: Object.assign(() => {
6948
7250
  const startedAt = performance.now();
6949
7251
  try {
@@ -8122,15 +8424,15 @@ var RecallSources = class {
8122
8424
  const id2 = scopeId(scope);
8123
8425
  if (!db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind='source' LIMIT 1").get(id2)) return;
8124
8426
  const dependents = /* @__PURE__ */ new Map();
8125
- const link2 = (parent, child) => {
8427
+ const link3 = (parent, child) => {
8126
8428
  const children = dependents.get(parent) ?? /* @__PURE__ */ new Set();
8127
8429
  children.add(child);
8128
8430
  dependents.set(parent, children);
8129
8431
  };
8130
8432
  const refs2 = (raw, child) => {
8131
8433
  for (const ref of JSON.parse(raw)) if (ref.scopeId === id2) {
8132
- link2(`s:${ref.sourceId}`, child);
8133
- 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);
8134
8436
  }
8135
8437
  };
8136
8438
  for (const row of db.prepare("SELECT source_id,context_refs,basis_refs FROM memory_social_sources WHERE scope_id=?").all(id2)) {
@@ -8145,7 +8447,7 @@ var RecallSources = class {
8145
8447
  const known = knownVersions ? knownVersions.get(JSON.stringify([row.relationship_id, row.semantic_version])) : row;
8146
8448
  if (!known) continue;
8147
8449
  const child = `r:${row.relationship_id}:${row.semantic_version}`;
8148
- if (row.source_id) link2(`s:${row.source_id}`, child);
8450
+ if (row.source_id) link3(`s:${row.source_id}`, child);
8149
8451
  refs2(known.basis_refs, child);
8150
8452
  }
8151
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}`);
@@ -8182,8 +8484,8 @@ var RecallSources = class {
8182
8484
  return this.metadata.get(id2);
8183
8485
  }
8184
8486
  current(id2) {
8185
- const metadata3 = this.sourceMetadata(id2);
8186
- 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);
8187
8489
  }
8188
8490
  referenceCurrent(ref) {
8189
8491
  return ref.scopeId === scopeId(this.scope) && this.source(ref.sourceId)?.sourceVersion === ref.sourceVersion && !ref.relationshipId && this.current(ref.sourceId);
@@ -8548,11 +8850,11 @@ var SocialSourceStore = class {
8548
8850
  return false;
8549
8851
  }
8550
8852
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
8551
- const metadata3 = snapshot.metadata.get(sourceId);
8853
+ const metadata4 = snapshot.metadata.get(sourceId);
8552
8854
  visited.add(sourceId);
8553
8855
  try {
8554
8856
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
8555
- const retained = !metadata3 || metadata3.contextRefs.every(check) && metadata3.basisRefs.every(check);
8857
+ const retained = !metadata4 || metadata4.contextRefs.every(check) && metadata4.basisRefs.every(check);
8556
8858
  memo.set(key2, retained);
8557
8859
  return retained;
8558
8860
  } finally {
@@ -8594,10 +8896,10 @@ var SocialSourceStore = class {
8594
8896
  return false;
8595
8897
  }
8596
8898
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
8597
- const metadata3 = snapshot.metadata.get(sourceId);
8899
+ const metadata4 = snapshot.metadata.get(sourceId);
8598
8900
  visited.add(sourceId);
8599
8901
  try {
8600
- 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));
8601
8903
  snapshot.grounds.set(key2, current2);
8602
8904
  return current2;
8603
8905
  } finally {
@@ -9206,10 +9508,10 @@ init_read_guard();
9206
9508
  init_scope();
9207
9509
 
9208
9510
  // src/mem7/core/episode.ts
9209
- import { readFileSync as readFileSync7 } from "node:fs";
9511
+ import { readFileSync as readFileSync6 } from "node:fs";
9210
9512
  import { join as join11, dirname as dirname6 } from "node:path";
9211
9513
  import { fileURLToPath } from "node:url";
9212
- 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");
9213
9515
 
9214
9516
  // src/mem7/core/source-material.ts
9215
9517
  function isAssistantDraft(source) {
@@ -10197,7 +10499,7 @@ var Mem7Store = class {
10197
10499
  let existingBlocks = "";
10198
10500
  let count;
10199
10501
  if (existsSync5(file)) {
10200
- const text2 = readFileSync8(file, "utf8");
10502
+ const text2 = readFileSync7(file, "utf8");
10201
10503
  const fmEnd = text2.indexOf("\n---", 3);
10202
10504
  const split = fmEnd >= 0 ? fmEnd + 4 : text2.length;
10203
10505
  head = text2.slice(0, split);
@@ -10254,7 +10556,7 @@ var Mem7Store = class {
10254
10556
  let existingBlocks = "";
10255
10557
  let count;
10256
10558
  if (existsSync5(file)) {
10257
- const text2 = readFileSync8(file, "utf8");
10559
+ const text2 = readFileSync7(file, "utf8");
10258
10560
  const fmEnd = text2.indexOf("\n---", 3);
10259
10561
  const split = fmEnd >= 0 ? fmEnd + 4 : text2.length;
10260
10562
  head = text2.slice(0, split);
@@ -10302,11 +10604,11 @@ var Mem7Store = class {
10302
10604
  assertRuntimeAuthority(this.stateDir, "WRITE");
10303
10605
  const temporary = `${file}.${randomUUID8()}.tmp`;
10304
10606
  try {
10305
- writeFileSync7(temporary, content, "utf8");
10607
+ writeFileSync6(temporary, content, "utf8");
10306
10608
  assertRuntimeAuthority(this.stateDir, "WRITE");
10307
10609
  renameSync3(temporary, file);
10308
10610
  } finally {
10309
- if (existsSync5(temporary)) unlinkSync4(temporary);
10611
+ if (existsSync5(temporary)) unlinkSync3(temporary);
10310
10612
  }
10311
10613
  }
10312
10614
  recordProjection(scope, kind, id2, file, content, body, expectedVersion) {
@@ -10349,7 +10651,7 @@ var Mem7Store = class {
10349
10651
  let max = 0;
10350
10652
  if (existsSync5(file)) {
10351
10653
  const re = new RegExp(`${prefix2}_${dateStr.replace(/-/g, "")}_(\\d+)`, "g");
10352
- 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]));
10353
10655
  }
10354
10656
  return max;
10355
10657
  }
@@ -10572,7 +10874,7 @@ ${e.outcome}
10572
10874
  for (const f of files) {
10573
10875
  let text2;
10574
10876
  try {
10575
- text2 = readFileSync8(join12(dir, f), "utf8");
10877
+ text2 = readFileSync7(join12(dir, f), "utf8");
10576
10878
  } catch {
10577
10879
  continue;
10578
10880
  }
@@ -10606,7 +10908,7 @@ ${e.outcome}
10606
10908
  for (const d of dirs) {
10607
10909
  let text2;
10608
10910
  try {
10609
- text2 = readFileSync8(join12(base, d, "SKILL.md"), "utf8");
10911
+ text2 = readFileSync7(join12(base, d, "SKILL.md"), "utf8");
10610
10912
  } catch {
10611
10913
  continue;
10612
10914
  }
@@ -10671,7 +10973,7 @@ ${e.outcome}
10671
10973
  let text2;
10672
10974
  const file = join12(this.root, this.ownerProjectionPath("users", ownerId, scope), "user.md");
10673
10975
  try {
10674
- text2 = readFileSync8(file, "utf8");
10976
+ text2 = readFileSync7(file, "utf8");
10675
10977
  } catch {
10676
10978
  return null;
10677
10979
  }
@@ -11243,7 +11545,7 @@ ${e.outcome}
11243
11545
  if (!/^foresight-\d{4}-\d{2}-\d{2}\.md$/.test(f)) continue;
11244
11546
  let content;
11245
11547
  try {
11246
- content = readFileSync8(join12(dir, f), "utf8");
11548
+ content = readFileSync7(join12(dir, f), "utf8");
11247
11549
  } catch {
11248
11550
  continue;
11249
11551
  }
@@ -11459,7 +11761,7 @@ function sessionCandidates(files, mapping) {
11459
11761
  rejected++;
11460
11762
  continue;
11461
11763
  }
11462
- const bytes = readFileSync9(file);
11764
+ const bytes = readFileSync8(file);
11463
11765
  const records = [];
11464
11766
  let header;
11465
11767
  let invalid = false;
@@ -11705,7 +12007,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
11705
12007
  gap("projection_kind_or_owner_unverified");
11706
12008
  continue;
11707
12009
  }
11708
- const bytes = readFileSync9(canonical3);
12010
+ const bytes = readFileSync8(canonical3);
11709
12011
  const text2 = bytes.toString("utf8").replace(/\r\n/g, "\n");
11710
12012
  const fileHash = hash6(bytes);
11711
12013
  const entries = [...text2.matchAll(/<!-- entry:([^\s<>]+) -->([\s\S]*?)<!-- \/entry:\1 -->/g)];
@@ -11775,7 +12077,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
11775
12077
  if (!apply || !candidates.length) return report;
11776
12078
  for (const file of new Set(candidates.map((candidate) => candidate.file))) {
11777
12079
  const candidate = candidates.find((candidate2) => candidate2.file === file);
11778
- 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");
11779
12081
  if (realpathSync5(store.mem7RootPath()) !== root) throw new Error("LEGACY_PROJECTION_COPY_REQUIRED");
11780
12082
  }
11781
12083
  store.transaction(() => {
@@ -12251,7 +12553,7 @@ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
12251
12553
  import { createHash as createHash25 } from "node:crypto";
12252
12554
  import { gunzipSync as gunzipSync2 } from "node:zlib";
12253
12555
  import { isUtf8 } from "node:buffer";
12254
- 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";
12255
12557
  import { join as join16, dirname as dirname9 } from "node:path";
12256
12558
 
12257
12559
  // src/continuity/session-events.ts
@@ -12259,9 +12561,10 @@ init_schema_migrations();
12259
12561
  init_sqlite_replication();
12260
12562
  init_runtime_replication();
12261
12563
  init_runtime_lock();
12564
+ init_runtime_authority();
12262
12565
  import { createRequire as createRequire5 } from "node:module";
12263
12566
  import { createHash as createHash23 } from "node:crypto";
12264
- 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";
12265
12568
  import { join as join15, resolve as resolve11, dirname as dirname8 } from "node:path";
12266
12569
 
12267
12570
  // src/continuity/session-event-projection.ts
@@ -12276,7 +12579,7 @@ import {
12276
12579
  fstatSync as fstatSync6,
12277
12580
  appendFileSync,
12278
12581
  renameSync as renameSync4,
12279
- unlinkSync as unlinkSync5
12582
+ unlinkSync as unlinkSync4
12280
12583
  } from "node:fs";
12281
12584
  import { basename as basename4, dirname as dirname7, join as join14, relative as relative4, resolve as resolve10 } from "node:path";
12282
12585
  import { createHash as createHash22, randomUUID as randomUUID9 } from "node:crypto";
@@ -12374,7 +12677,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
12374
12677
  prepareSessionDirectory(dirname7(file));
12375
12678
  if (record.state === "removed") {
12376
12679
  if (signature2 !== null) {
12377
- unlinkSync5(file);
12680
+ unlinkSync4(file);
12378
12681
  syncSessionDirectory(dirname7(file));
12379
12682
  }
12380
12683
  cursors.prepare("DELETE FROM cursors WHERE path=?").run(path3);
@@ -12418,7 +12721,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
12418
12721
  if (fd !== void 0) closeSync8(fd);
12419
12722
  if (!incremental && !complete) {
12420
12723
  try {
12421
- unlinkSync5(temp);
12724
+ unlinkSync4(temp);
12422
12725
  } catch (error) {
12423
12726
  if (error.code !== "ENOENT") throw error;
12424
12727
  }
@@ -12544,7 +12847,7 @@ var SessionEventStore = class {
12544
12847
  if (row && !approvedSourceRoot) {
12545
12848
  const file = join15(stateDir, ".travel-active.json"), stat = lstatSync12(file);
12546
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");
12547
- const activation = JSON.parse(readFileSync10(file, "utf8")), binding = registration.binding;
12850
+ const activation = JSON.parse(readFileSync9(file, "utf8")), binding = registration.binding;
12548
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;
12549
12852
  }
12550
12853
  if (!row || !approvedSourceRoot || !Number.isSafeInteger(row.revision) || Number(row.revision) < 0) throw new Error("REPLICATION_RECOVERY_REQUIRED");
@@ -12796,7 +13099,7 @@ async function restoreSessionEvents(options) {
12796
13099
  if (realpathSync7(dirname8(destination)) !== dirname8(destination)) throw new Error("SESSION_SYMLINK_REFUSED");
12797
13100
  if (existsSync6(destination)) throw new Error("CONTINUITY_DESTINATION_EXISTS");
12798
13101
  prepareSessionDirectory(destination);
12799
- 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 });
12800
13103
  syncSessionDirectory(destination);
12801
13104
  const directory2 = join15(destination, ".continuity");
12802
13105
  prepareSessionDirectory(directory2);
@@ -12811,7 +13114,7 @@ async function restoreSessionEvents(options) {
12811
13114
  cursors.exec("BEGIN IMMEDIATE");
12812
13115
  for (const row of copy.prepare("SELECT path FROM session_files ORDER BY path").all()) projectSessionFile(copy, cursors, destination, String(row.path), root);
12813
13116
  cursors.exec("COMMIT");
12814
- writeFileSync8(
13117
+ writeFileSync7(
12815
13118
  join15(destination, ".session-events-receipt.json"),
12816
13119
  JSON.stringify({ binding, head: { sequence: control2.head, digest: control2.digest }, activationAllowed: false }),
12817
13120
  { mode: 384, flag: "wx", flush: true }
@@ -13015,7 +13318,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13015
13318
  const path4 = join16(options.root, "trees", tree.id, file.path);
13016
13319
  if (existsSync7(path4)) {
13017
13320
  check();
13018
- unlinkSync6(path4);
13321
+ unlinkSync5(path4);
13019
13322
  await syncDirectory(dirname9(path4));
13020
13323
  check();
13021
13324
  debugCaches++;
@@ -13039,9 +13342,9 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13039
13342
  }).join("");
13040
13343
  if (!removed) continue;
13041
13344
  check();
13042
- writeFileSync9(path3, retained, { flush: true });
13345
+ writeFileSync8(path3, retained, { flush: true });
13043
13346
  const cursor = path3 + ".cursor";
13044
- 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);
13045
13348
  await syncDirectory(dirname9(path3));
13046
13349
  check();
13047
13350
  intakeRecords += removed;
@@ -13054,9 +13357,9 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13054
13357
  const metadataDb = [...options.databases].filter(([, db2]) => readSchemaVersion(db2)?.component === "session-events");
13055
13358
  if (metadataDb.length !== 1) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
13056
13359
  const [databaseId, db] = metadataDb[0];
13057
- 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());
13058
13361
  const binding = normalizeBinding({ ...options.manifest.profile.identity, baselineId: options.manifest.profile.baselineId, epoch: options.manifest.profile.epoch, databaseId });
13059
- 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");
13060
13363
  if (readSchemaVersion(db)?.version !== 1) throw new Error("RECOVERY_OVERLAY_SCHEMA");
13061
13364
  const legacyRecords = /* @__PURE__ */ new Map();
13062
13365
  for (const record of memory.prepare(`SELECT r.*,m.session_id FROM memory_legacy_source_records r
@@ -13348,8 +13651,8 @@ async function deletionOverlay(options, runtimeCopies) {
13348
13651
  text2 = text2.replace(/entry_count: \d+/, "entry_count: " + entries);
13349
13652
  const empty = text2.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "").trim() === "";
13350
13653
  await check();
13351
- if (empty) unlinkSync7(file);
13352
- else writeFileSync10(file, text2, { flush: true });
13654
+ if (empty) unlinkSync6(file);
13655
+ else writeFileSync9(file, text2, { flush: true });
13353
13656
  await syncDirectory(dirname10(file));
13354
13657
  await check();
13355
13658
  removedFiles.push("trees/" + matches[0].id + "/mem7/" + path3);
@@ -13409,13 +13712,13 @@ async function deletionOverlay(options, runtimeCopies) {
13409
13712
  const next = { ...original, originalIntegrity: original.originalIntegrity ?? original.integrity, deletionOverlay: proof, integrity: runtimeGenerationIntegrity(root) };
13410
13713
  const temporary = join17(root, ".runtime-publication-receipt-" + randomUUID10());
13411
13714
  try {
13412
- writeFileSync10(temporary, JSON.stringify(next), { mode: 384, flag: "wx", flush: true });
13715
+ writeFileSync9(temporary, JSON.stringify(next), { mode: 384, flag: "wx", flush: true });
13413
13716
  await check();
13414
13717
  renameSync5(temporary, receiptFile);
13415
13718
  await syncDirectory(root);
13416
13719
  await check();
13417
13720
  } finally {
13418
- if (existsSync8(temporary)) unlinkSync7(temporary);
13721
+ if (existsSync8(temporary)) unlinkSync6(temporary);
13419
13722
  }
13420
13723
  return proof;
13421
13724
  } finally {
@@ -13493,14 +13796,14 @@ async function completeCurrentHDeletionVisibility(options) {
13493
13796
  };
13494
13797
  const file = join18(options.snapshot, ".runtime-publication-receipt.json"), temporary = join18(options.snapshot, ".runtime-publication-receipt-" + randomUUID11());
13495
13798
  try {
13496
- 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 });
13497
13800
  await check();
13498
13801
  await effectsCheckAsync(options, floor);
13499
13802
  renameSync6(temporary, file);
13500
13803
  await syncDirectory(options.snapshot);
13501
13804
  await check();
13502
13805
  } finally {
13503
- if (existsSync9(temporary)) unlinkSync8(temporary);
13806
+ if (existsSync9(temporary)) unlinkSync7(temporary);
13504
13807
  }
13505
13808
  return proof;
13506
13809
  }
@@ -13531,7 +13834,9 @@ async function verifyRuntimeDirectory(directory2) {
13531
13834
  }
13532
13835
  }
13533
13836
  var same4 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
13837
+ var copyFlags = constants11.COPYFILE_EXCL | constants11.COPYFILE_FICLONE;
13534
13838
  function validateRuntimeActivationLayout(destination, raw, layout) {
13839
+ if (layout.inventorySelection !== void 0 && layout.inventorySelection !== "core") throw new Error("TRAVEL_ACTIVATION_LAYOUT");
13535
13840
  const manifest = normalizePublication(raw);
13536
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");
13537
13842
  const locations = /* @__PURE__ */ new Map();
@@ -13585,7 +13890,7 @@ function validateRuntimeActivationSnapshot(snapshot, manifest, locations) {
13585
13890
  for (const d of manifest.databases) {
13586
13891
  const db = new DatabaseSync12(join19(snapshot, "databases", d.databaseId + ".sqlite"), { readOnly: true });
13587
13892
  try {
13588
- validateRecoveryDatabase(db, manifest, d.databaseId, "replica");
13893
+ validateRecoveryDatabase(db, manifest, d.databaseId, "replica", void 0, false);
13589
13894
  const place = locations.get(d.databaseId);
13590
13895
  if (readSchemaVersion(db)?.component !== place.component) throw new Error("TRAVEL_ACTIVATION_SCHEMA");
13591
13896
  if (place.component === "session-events") sourceRoots.push(String(db.prepare("SELECT source_root FROM session_control WHERE singleton=1").get().source_root));
@@ -13595,17 +13900,17 @@ function validateRuntimeActivationSnapshot(snapshot, manifest, locations) {
13595
13900
  }
13596
13901
  return sourceRoots;
13597
13902
  }
13598
- function copyTree(from, to, skipControl = false) {
13599
- const walk = (path3) => {
13600
- const stat = lstatSync13(path3);
13601
- if (stat.isSymbolicLink() || !stat.isDirectory() && !stat.isFile()) throw new Error("TRAVEL_ACTIVATION_UNSAFE_PATH");
13602
- if (stat.isDirectory()) for (const name of readdirSync4(path3)) walk(join19(path3, name));
13603
- };
13604
- walk(from);
13605
- mkdirSync9(to, { recursive: true, mode: 448 });
13606
- 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)) {
13607
13912
  if (skipControl && (name.startsWith(".") || name === "databases" || name === "trees" || name === "lance")) continue;
13608
- cpSync(join19(from, name), join19(to, name), { recursive: true, force: false, errorOnExist: true });
13913
+ await copyTree(join19(from, name), join19(to, name));
13609
13914
  }
13610
13915
  }
13611
13916
  async function activateRuntimeGeneration(options) {
@@ -13634,12 +13939,12 @@ async function activateRuntimeGeneration(options) {
13634
13939
  if (realpathSync10(snapshot) !== snapshot || realpathSync10(dirname11(destination)) !== dirname11(destination) || existsSync10(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
13635
13940
  const proof = JSON.parse(readPrivateFile2(join19(snapshot, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
13636
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");
13637
- verifyRuntimeGenerationIntegrity(snapshot, proof.integrity);
13942
+ await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
13638
13943
  const locations = validateRuntimeActivationLayout(destination, manifest, options.layout);
13639
13944
  const sourceRoots = validateRuntimeActivationSnapshot(snapshot, manifest, locations);
13640
13945
  const profile = normalizePublicationProfile({ ...manifest.profile, baselineId: options.baselineId, epoch: options.permit.epoch });
13641
13946
  mkdirSync9(destination, { mode: 448 });
13642
- 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 });
13643
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 });
13644
13949
  runtime.acceptPermit(options.permit, options.requestStartedAt);
13645
13950
  runtime.advanceDeletionFloor(options.permit.deletionWatermark);
@@ -13649,14 +13954,14 @@ async function activateRuntimeGeneration(options) {
13649
13954
  await checkDeletion();
13650
13955
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13651
13956
  const source = tree.kind === "file" ? join19(snapshot, "trees", tree.id) : join19(snapshot, tree.kind === "vector" ? "lance" : "sessions", tree.id);
13652
- 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");
13653
13958
  }
13654
13959
  for (const d of manifest.databases) {
13655
13960
  await checkDeletion();
13656
13961
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13657
13962
  const path3 = join19(destination, options.layout.databases[d.databaseId]), place = locations.get(d.databaseId);
13658
13963
  mkdirSync9(dirname11(path3), { recursive: true, mode: 448 });
13659
- cpSync(join19(snapshot, "databases", d.databaseId + ".sqlite"), path3, { errorOnExist: true, force: false });
13964
+ await copyFile(join19(snapshot, "databases", d.databaseId + ".sqlite"), path3, copyFlags);
13660
13965
  const db = new DatabaseSync12(path3, { allowExtension: place.component === "legacy-memory" });
13661
13966
  try {
13662
13967
  if (place.component === "legacy-memory") loadLegacySQLiteVectorExtension(db);
@@ -13692,13 +13997,13 @@ async function activateRuntimeGeneration(options) {
13692
13997
  };
13693
13998
  await checkDeletion();
13694
13999
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13695
- verifyRuntimeGenerationIntegrity(snapshot, proof.integrity);
14000
+ await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
13696
14001
  runtime.advanceDeletionFloor(options.permit.deletionWatermark);
13697
- 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 });
13698
14003
  await syncDirectory(destination);
13699
14004
  await checkDeletion();
13700
14005
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
13701
- unlinkSync9(join19(destination, ".travel-restored.json"));
14006
+ unlinkSync8(join19(destination, ".travel-restored.json"));
13702
14007
  await syncDirectory(destination);
13703
14008
  return { receipt: receipt2, profile, runtime };
13704
14009
  } catch (error) {
@@ -13714,7 +14019,7 @@ init_runtime_authority();
13714
14019
  // src/continuity/node-process.ts
13715
14020
  import { fork } from "node:child_process";
13716
14021
  import { DatabaseSync as DatabaseSync13 } from "node:sqlite";
13717
- 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";
13718
14023
  import { isAbsolute as isAbsolute4, join as join20 } from "node:path";
13719
14024
  import { createHash as createHash28, randomUUID as randomUUID12 } from "node:crypto";
13720
14025
 
@@ -13829,8 +14134,8 @@ var SupervisedRuntimeProcess = class {
13829
14134
  const continuation = recovery ? this.db.prepare("SELECT * FROM recovery_continuations WHERE binding=?").get(JSON.stringify(binding)) : void 0;
13830
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");
13831
14136
  if (recovery && !retired) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
13832
- const info = lstatSync14(this.options.entry);
13833
- 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");
13834
14139
  let environment;
13835
14140
  try {
13836
14141
  environment = supervisedRuntimeEnvironment(JSON.parse(readPrivateFile2(this.options.configFile, 1024 * 1024).toString()), process.env, this.options.environmentNames);
@@ -14014,15 +14319,15 @@ var SupervisedRuntimeProcess = class {
14014
14319
 
14015
14320
  // src/continuity/runtime-publication-restore.ts
14016
14321
  import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
14017
- import { mkdirSync as mkdirSync12, writeFileSync as writeFileSync15 } from "node:fs";
14322
+ import { mkdirSync as mkdirSync12, writeFileSync as writeFileSync14 } from "node:fs";
14018
14323
  import { join as join23, resolve as resolve17 } from "node:path";
14019
14324
 
14020
14325
  // src/continuity/publication-files.ts
14021
14326
  import { DatabaseSync as DatabaseSync14, backup as backup2 } from "node:sqlite";
14022
- 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";
14023
14328
  import { join as join21, resolve as resolve15, dirname as dirname12 } from "node:path";
14024
14329
  async function restorePublication(options) {
14025
- const { receiver } = options, status = await receiver.status();
14330
+ const { receiver } = options, status = await receiver.status(false);
14026
14331
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
14027
14332
  const manifest = await receiver.manifest(status.published.sequence);
14028
14333
  if (JSON.stringify(Object.keys(options.databases).sort()) !== JSON.stringify(manifest.profile.databaseIds)) throw new Error("PUBLICATION_INCOMPLETE_DATABASES");
@@ -14036,7 +14341,7 @@ async function restorePublication(options) {
14036
14341
  throw error;
14037
14342
  }
14038
14343
  await syncDirectory(dirname12(destination));
14039
- writeFileSync13(join21(destination, ".travel-restored.json"), JSON.stringify({
14344
+ writeFileSync12(join21(destination, ".travel-restored.json"), JSON.stringify({
14040
14345
  format: "engine7-publication-restore-v1",
14041
14346
  activationAllowed: false,
14042
14347
  sequence: manifest.sequence,
@@ -14063,8 +14368,8 @@ async function restorePublication(options) {
14063
14368
  const row = copy.prepare("SELECT head,digest,binding FROM e7_replication_control WHERE role='replica'").get();
14064
14369
  const identity = manifest.profile.identity;
14065
14370
  const wanted = [identity.tenantId, identity.companionId, identity.seatId, item.databaseId, manifest.profile.baselineId, manifest.profile.epoch];
14066
- const check = copy.prepare("PRAGMA quick_check").all();
14067
- 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");
14068
14373
  } finally {
14069
14374
  copy.close();
14070
14375
  }
@@ -14075,6 +14380,7 @@ async function restorePublication(options) {
14075
14380
  closeSync11(fd);
14076
14381
  }
14077
14382
  }
14383
+ const files = [];
14078
14384
  for (const tree of manifest.trees) {
14079
14385
  const root = join21(destination, "trees", tree.id);
14080
14386
  directory2(root);
@@ -14082,27 +14388,26 @@ async function restorePublication(options) {
14082
14388
  for (const file of tree.files) {
14083
14389
  const path3 = join21(root, file.path);
14084
14390
  directory2(dirname12(path3));
14085
- await receiver.objects.restoreFile(file.content, path3);
14086
- chmodSync3(path3, file.mode);
14087
- const fd = openSync12(path3, "r+");
14088
- try {
14089
- fsyncSync7(fd);
14090
- } finally {
14091
- closeSync11(fd);
14092
- }
14391
+ files.push({ content: file.content, destination: path3, mode: file.mode });
14093
14392
  }
14094
14393
  }
14095
- 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);
14096
14401
  if (!after.dataReady || after.published?.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
14097
14402
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
14098
- 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 });
14099
14404
  await syncDirectory(destination);
14100
14405
  return status.published;
14101
14406
  }
14102
14407
 
14103
14408
  // src/continuity/lance-publication.ts
14104
14409
  import { createHash as createHash29 } from "node:crypto";
14105
- 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";
14106
14411
  import { join as join22, resolve as resolve16, dirname as dirname13, relative as relative5 } from "node:path";
14107
14412
  import { createRequire as createRequire6 } from "node:module";
14108
14413
  var kinds2 = ["agent_case", "agent_skill", "atomic_fact", "episode", "foresight"];
@@ -14118,16 +14423,16 @@ function rowPath(kind, id2) {
14118
14423
  return `${kind}/rows/${sha6(id2)}.arrow`;
14119
14424
  }
14120
14425
  function assertSource(directory2) {
14121
- 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");
14122
14427
  let count = 0;
14123
14428
  const signatures2 = [];
14124
14429
  const visit = (path3, depth) => {
14125
14430
  if (++count > 1e5 || depth > 128) throw new Error("LANCE_PUBLICATION_SOURCE_TOO_LARGE");
14126
- const info = lstatSync16(path3, { bigint: true });
14431
+ const info = lstatSync15(path3, { bigint: true });
14127
14432
  if (info.isSymbolicLink()) throw new Error("SYMLINK_REFUSED");
14128
14433
  if (!info.isDirectory() && !info.isFile()) throw new Error("LANCE_PUBLICATION_SPECIAL_FILE");
14129
14434
  signatures2.push([relative5(directory2, path3), ...[info.dev, info.ino, info.size, info.mode, info.mtimeNs, info.ctimeNs].map(String)]);
14130
- 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);
14131
14436
  };
14132
14437
  visit(directory2, 0);
14133
14438
  return sha6(JSON.stringify(signatures2));
@@ -14158,9 +14463,9 @@ async function inspectLancePublication(directory2) {
14158
14463
  }
14159
14464
  function durablePrivateTree(directory2) {
14160
14465
  const visit = (path3) => {
14161
- const info = lstatSync16(path3);
14466
+ const info = lstatSync15(path3);
14162
14467
  if (info.isSymbolicLink() || !info.isDirectory() && !info.isFile()) throw new Error("SYMLINK_REFUSED");
14163
- 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));
14164
14469
  chmodSync4(path3, info.isDirectory() ? 448 : 384);
14165
14470
  if (process.platform !== "win32" || info.isFile()) {
14166
14471
  const fd = openSync13(path3, "r");
@@ -14207,14 +14512,28 @@ async function captureLancePublication(options) {
14207
14512
  const batchTable = new arrow.Table(batch);
14208
14513
  for (let start = 0; start < batchTable.numRows; start += batchRows) {
14209
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
+ };
14210
14523
  for (let index = 0; index < page.numRows; index++) {
14211
14524
  const one = page.slice(index, index + 1), path3 = rowPath(kind, one.getChild("id").get(0));
14212
14525
  if (seen.has(path3)) throw new Error("LANCE_PUBLICATION_DUPLICATE_ROW");
14213
14526
  seen.add(path3);
14214
14527
  const bytes = arrow.tableToIPC(one, "stream");
14215
- if (bytes.length > ROW_BYTES || tree.files.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
14216
- 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
+ }
14217
14535
  }
14536
+ await flush();
14218
14537
  }
14219
14538
  }
14220
14539
  if (seen.size !== total) throw new Error("LANCE_PUBLICATION_ROW_COUNT_MISMATCH");
@@ -14270,7 +14589,7 @@ async function restoreLancePublication(options) {
14270
14589
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
14271
14590
  throw error;
14272
14591
  }
14273
- writeFileSync14(join22(destination, ".travel-restored.json"), JSON.stringify({
14592
+ writeFileSync13(join22(destination, ".travel-restored.json"), JSON.stringify({
14274
14593
  format: "engine7-lance-logical-restore-v1",
14275
14594
  activationAllowed: false,
14276
14595
  identity: options.objects.identity,
@@ -14310,7 +14629,7 @@ async function restoreLancePublication(options) {
14310
14629
  connection.close();
14311
14630
  }
14312
14631
  durablePrivateTree(destination);
14313
- writeFileSync14(
14632
+ writeFileSync13(
14314
14633
  join22(destination, ".lance-receipt.json"),
14315
14634
  JSON.stringify({ format: manifest.format, tables: manifest.tables, activationAllowed: false }),
14316
14635
  { flag: "wx", mode: 384, flush: true }
@@ -14352,7 +14671,7 @@ async function admitOriginalLanceRow(options) {
14352
14671
  // src/continuity/runtime-publication-restore.ts
14353
14672
  init_sqlite_replication();
14354
14673
  async function restoreRuntimePublication(options) {
14355
- const { receiver } = options, status = await receiver.status();
14674
+ const { receiver } = options, status = await receiver.status(false);
14356
14675
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
14357
14676
  if (options.sequence !== void 0 && options.sequence !== status.published.sequence) throw new Error("PUBLICATION_STALE_PUBLICATION");
14358
14677
  const manifest = await receiver.manifest(status.published.sequence), destination = resolve17(options.destination);
@@ -14360,15 +14679,15 @@ async function restoreRuntimePublication(options) {
14360
14679
  for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "session")) {
14361
14680
  const tree = manifest.trees.find((tree2) => tree2.id === kind.id);
14362
14681
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
14363
- const metadata3 = JSON.parse((await receiver.objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
14364
- 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);
14365
14684
  const binding = normalizeBinding({
14366
14685
  ...manifest.profile.identity,
14367
- databaseId: metadata3.databaseId,
14686
+ databaseId: metadata4.databaseId,
14368
14687
  baselineId: manifest.profile.baselineId,
14369
14688
  epoch: manifest.profile.epoch
14370
14689
  });
14371
- 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");
14372
14691
  sessions.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
14373
14692
  }
14374
14693
  await restorePublication({ ...options, destination, deferReceipt: true });
@@ -14395,17 +14714,17 @@ async function restoreRuntimePublication(options) {
14395
14714
  await syncDirectory(join23(destination, "sessions"));
14396
14715
  sessionStates.push({ treeId: session.treeId, databaseId: session.databaseId, directory: `sessions/${session.treeId}` });
14397
14716
  }
14398
- const after = await receiver.status();
14717
+ const after = await receiver.status(false);
14399
14718
  if (!after.dataReady || after.published?.sequence !== manifest.sequence || after.published.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
14400
- writeFileSync15(join23(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
14401
- 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({
14402
14721
  format: "engine7-runtime-publication-restore-v1",
14403
14722
  profile: manifest.profile,
14404
14723
  receipt: status.published,
14405
14724
  databases: manifest.databases,
14406
14725
  lance,
14407
14726
  sessions: sessionStates,
14408
- integrity: runtimeGenerationIntegrity(destination),
14727
+ integrity: await runtimeGenerationIntegrityAsync(destination),
14409
14728
  activationAllowed: false
14410
14729
  }), { flag: "wx", mode: 384, flush: true });
14411
14730
  await syncDirectory(destination);
@@ -14417,14 +14736,14 @@ import { join as join27 } from "node:path";
14417
14736
 
14418
14737
  // src/continuity/runtime-generation-source.ts
14419
14738
  import { DatabaseSync as DatabaseSync20 } from "node:sqlite";
14420
- 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";
14421
14740
  import { createHash as createHash34 } from "node:crypto";
14422
14741
  import { isAbsolute as isAbsolute5, join as join26, resolve as resolve22 } from "node:path";
14423
14742
 
14424
14743
  // src/continuity/runtime-tree-source.ts
14425
14744
  import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
14426
14745
  import { createHash as createHash30 } from "node:crypto";
14427
- 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";
14428
14747
  import { join as join24, resolve as resolve18 } from "node:path";
14429
14748
  var ZERO2 = "0".repeat(64);
14430
14749
  var HASH3 = /^[a-f0-9]{64}$/;
@@ -14488,7 +14807,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
14488
14807
  this.db.exec("ROLLBACK");
14489
14808
  throw error;
14490
14809
  }
14491
- 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 });
14492
14811
  if (process.platform !== "win32") {
14493
14812
  const fd = openSync14(directory2, "r");
14494
14813
  try {
@@ -14606,21 +14925,22 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
14606
14925
  // src/continuity/runtime-publication-source.ts
14607
14926
  import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
14608
14927
  import { createHash as createHash33 } from "node:crypto";
14609
- 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";
14610
14929
  import { join as join25, resolve as resolve21 } from "node:path";
14611
14930
 
14612
14931
  // src/continuity/runtime-h-capture.ts
14613
14932
  import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
14614
14933
  import { createHash as createHash32 } from "node:crypto";
14615
- import { lstatSync as lstatSync18, realpathSync as realpathSync15 } from "node:fs";
14934
+ import { lstatSync as lstatSync17, realpathSync as realpathSync15 } from "node:fs";
14616
14935
  import { resolve as resolve20, relative as relative7 } from "node:path";
14617
14936
 
14618
14937
  // src/continuity/runtime-files.ts
14619
- import { lstatSync as lstatSync17, realpathSync as realpathSync14 } from "node:fs";
14938
+ import { lstatSync as lstatSync16, realpathSync as realpathSync14 } from "node:fs";
14620
14939
  import { relative as relative6, resolve as resolve19 } from "node:path";
14621
14940
  import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
14622
14941
  import { createHash as createHash31 } from "node:crypto";
14623
14942
  init_runtime_replication();
14943
+ import { setImmediate as setImmediate2 } from "node:timers/promises";
14624
14944
  async function runtimeFileEntries(options) {
14625
14945
  const state2 = resolve19(options.inventory.stateDir), workspace = resolve19(options.inventory.workspace ?? state2 + "/workspace");
14626
14946
  if (realpathSync14(state2) !== state2 || realpathSync14(workspace) !== workspace) throw new Error("SYMLINK_REFUSED");
@@ -14633,7 +14953,7 @@ async function runtimeFileEntries(options) {
14633
14953
  excludeWorkspaceEntries: { ...options.inventory.excludeWorkspaceEntries }
14634
14954
  };
14635
14955
  for (const directory2 of [...options.vectorDirectories, ...options.sessionDirectories].map(resolvePath)) {
14636
- const info = lstatSync17(directory2);
14956
+ const info = lstatSync16(directory2);
14637
14957
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync14(directory2) !== directory2) throw new Error("SYMLINK_REFUSED");
14638
14958
  const root = isWithin(workspace, directory2) ? "workspace" : isWithin(state2, directory2) ? "state" : void 0;
14639
14959
  if (!root || directory2 === state2 || directory2 === workspace) throw new Error("RUNTIME_FILE_PATH_OUTSIDE_ROOT");
@@ -14675,10 +14995,26 @@ async function captureRuntimeFiles(options) {
14675
14995
  { id: options.workspaceTreeId, files: [], directories: [] }
14676
14996
  ];
14677
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");
14678
- 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")) {
14679
15002
  const tree = trees[entry.root === "state" ? 0 : 1];
14680
- if (entry.kind === "directory") tree.directories.push(entry.path);
14681
- 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();
14682
15018
  }
14683
15019
  if (JSON.stringify(signatures(before)) !== JSON.stringify(signatures(await runtimeFileEntries(options)))) throw new Error("PUBLICATION_SOURCE_CHANGED");
14684
15020
  return trees;
@@ -14697,7 +15033,7 @@ async function captureRuntimeH(input) {
14697
15033
  }
14698
15034
  function assertStoppedSourceRoot(root) {
14699
15035
  try {
14700
- lstatSync18(resolve20(root, ".travel-restored.json"));
15036
+ lstatSync17(resolve20(root, ".travel-restored.json"));
14701
15037
  throw new Error("TRAVEL_ACTIVATION_REQUIRED");
14702
15038
  } catch (error) {
14703
15039
  if (error.code !== "ENOENT") throw error;
@@ -14759,7 +15095,7 @@ async function capture(input, assertRoot) {
14759
15095
  throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
14760
15096
  const observe = async () => {
14761
15097
  const heads = profile.databaseIds.map((databaseId) => {
14762
- 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);
14763
15099
  if (!place || !isWithin(state2, place.stateDir) || !info.isFile() || info.isSymbolicLink() || realpathSync15(d.file) !== d.file)
14764
15100
  throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
14765
15101
  if (process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
@@ -14794,9 +15130,9 @@ async function capture(input, assertRoot) {
14794
15130
  }
14795
15131
  for (const s of sessionTrees) {
14796
15132
  const head = before.heads.find((d) => d.databaseId === s.databaseId).head;
14797
- const metadata3 = { format: "engine7-session-events-publication-v1", databaseId: s.databaseId, binding: databases[s.databaseId].source.binding, head };
14798
- trees.push({ id: s.treeId, directories: [], files: [{ path: "manifest.json", mode: 384, content: await objects.putContent(Buffer.from(JSON.stringify(metadata3))) }] });
14799
- 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;
14800
15136
  }
14801
15137
  if (!same5(before, await observe())) throw new Error("PUBLICATION_SOURCE_CHANGED");
14802
15138
  return {
@@ -14826,7 +15162,7 @@ var same6 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
14826
15162
  var sha8 = (body) => createHash33("sha256").update(body).digest("hex");
14827
15163
  var stateHash = (m) => sha8(JSON.stringify([m.databases, m.trees, m.deletionWatermark]));
14828
15164
  var incarnation2 = (file) => {
14829
- const s = lstatSync19(file);
15165
+ const s = lstatSync18(file);
14830
15166
  if (s.isSymbolicLink() || !s.isFile()) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
14831
15167
  return `${s.dev}:${s.ino}`;
14832
15168
  };
@@ -14889,7 +15225,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14889
15225
  }
14890
15226
  sender.exec(senderSchema);
14891
15227
  sender.prepare("INSERT INTO sender VALUES(1,?,?)").run(JSON.stringify(this.profile), this.layoutDigest);
14892
- 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 });
14893
15229
  if (process.platform !== "win32") {
14894
15230
  const fd = openSync15(this.directory, "r");
14895
15231
  try {
@@ -14918,7 +15254,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14918
15254
  static async open(options) {
14919
15255
  const source = new _RuntimePublicationSource(options);
14920
15256
  try {
14921
- if (source.head().sequence) await source.read(source.head().sequence);
15257
+ if (source.head().sequence) await source.readManifest(source.head().sequence);
14922
15258
  return source;
14923
15259
  } catch (error) {
14924
15260
  source.close();
@@ -14969,6 +15305,15 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14969
15305
  };
14970
15306
  }
14971
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) {
14972
15317
  const row = this.entry(sequence), ref = JSON.parse(row.content);
14973
15318
  validateFileContent(ref);
14974
15319
  const manifest = normalizePublication(JSON.parse((await this.objects.readContent(ref, PUBLICATION_MANIFEST_BYTES)).toString()));
@@ -14976,7 +15321,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14976
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");
14977
15322
  const dependencies2 = JSON.parse(row.dependencies);
14978
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");
14979
- for (const d of dependencies2) {
15324
+ if (verifyDependencies) for (const d of dependencies2) {
14980
15325
  const tree = await this.trees.read(d.treeId, d.sequence);
14981
15326
  if (tree.digest !== d.digest || !same6(tree.tree, manifest.trees.find((t) => t.id === d.treeId))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
14982
15327
  }
@@ -14989,12 +15334,18 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
14989
15334
  async prepare(options) {
14990
15335
  return this.prepareCapture(options, () => captureRuntimeH(options));
14991
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
+ }
14992
15343
  /** The source business stores stay read-only and writer exclusion remains
14993
15344
  * held until the caller durably seals its backup and archive receipt. */
14994
15345
  async withStoppedPreparation(options, operation) {
14995
15346
  return withStoppedRuntimeH(options, async (parts) => operation(await this.prepareCapture(options, async () => parts)));
14996
15347
  }
14997
- async prepareCapture(options, capture2) {
15348
+ async prepareCapture(options, capture2, initial = false) {
14998
15349
  const c = this.control(), pending = this.status();
14999
15350
  if (!same6(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
15000
15351
  if (pending.pendingCheckpoints >= this.maximumPendingCheckpoints || pending.pendingBytes >= this.maximumPendingBytes) throw new Error("RUNTIME_PUBLICATION_QUEUE_FULL");
@@ -15026,11 +15377,11 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
15026
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);
15027
15378
  }
15028
15379
  let bytes = encoded.length + Buffer.byteLength(JSON.stringify(dependencies2));
15029
- 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)) {
15030
15381
  known.add(ref.sha256);
15031
15382
  bytes += ref.bytes;
15032
15383
  }
15033
- 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(
15034
15385
  old?.manifest.databases.find((previous) => previous.databaseId === d.databaseId).head.sequence ?? 0,
15035
15386
  d.head.sequence
15036
15387
  );
@@ -15188,7 +15539,7 @@ async function openRuntimeGenerationSource(options) {
15188
15539
  for (const id2 of profile.databaseIds) {
15189
15540
  const path3 = layout.databases[id2];
15190
15541
  validatePublicationPath(path3);
15191
- const file = join26(stateDir, path3), place = sqliteStoreLocation(file), info = lstatSync20(file);
15542
+ const file = join26(stateDir, path3), place = sqliteStoreLocation(file), info = lstatSync19(file);
15192
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");
15193
15544
  const db = new DatabaseSync20(file, { readOnly: options.mode === "SEALED", allowExtension: options.mode === "LIVE" && place.component === "legacy-memory" });
15194
15545
  handles[id2] = db;
@@ -15227,7 +15578,7 @@ async function openRuntimeGenerationSource(options) {
15227
15578
  lanceStores,
15228
15579
  deletionWatermark: runtime.deletionFloor(),
15229
15580
  files: {
15230
- inventory: { stateDir, workspace, includeStateEntries: layout.includedStateEntries },
15581
+ inventory: { stateDir, workspace, selection: layout.inventorySelection, includeStateEntries: layout.includedStateEntries },
15231
15582
  objects: options.objects,
15232
15583
  databaseFiles: Object.values(databases).map((db) => db.file),
15233
15584
  immutableDatabaseFiles: (layout.immutableDatabases ?? []).map((path3) => {
@@ -15294,14 +15645,14 @@ async function readStoppedRecoveryManifests(options) {
15294
15645
  await Promise.all([options.assertAvailable(), checkRecoveryDeletionAsync(local.manifest, options.deletionWatermark)]);
15295
15646
  };
15296
15647
  await check();
15297
- const common = await opened.source.read(options.common.sequence);
15648
+ const common = await opened.source.readManifest(options.common.sequence);
15298
15649
  await check();
15299
15650
  if (common.digest !== options.common.digest) throw new Error("RECOVERY_LOCAL_ANCESTRY_GAP");
15300
15651
  let parent = common.digest, bytes = 0;
15301
15652
  const manifests = [];
15302
15653
  const last = options.maximum === void 0 ? local.manifest.sequence : Math.min(local.manifest.sequence, options.common.sequence + options.maximum);
15303
15654
  for (let sequence = options.common.sequence + 1; sequence <= last; sequence++) {
15304
- const original = await opened.source.read(sequence);
15655
+ const original = await opened.source.readManifest(sequence);
15305
15656
  await check();
15306
15657
  if (original.manifest.parentDigest !== parent) throw new Error("RECOVERY_LOCAL_ANCESTRY_GAP");
15307
15658
  parent = original.digest;
@@ -15456,6 +15807,7 @@ function startTravelHeartbeatReporting(options) {
15456
15807
  })().catch((error) => {
15457
15808
  lastError = error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_REPORTING_UNAVAILABLE";
15458
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");
15459
15811
  try {
15460
15812
  options.runtime()?.revoke();
15461
15813
  } catch {
@@ -15535,7 +15887,7 @@ function startTravelHeartbeatReporting(options) {
15535
15887
 
15536
15888
  // src/continuity/recovery-archive-restore.ts
15537
15889
  import { DatabaseSync as DatabaseSync22 } from "node:sqlite";
15538
- 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";
15539
15891
  import { dirname as dirname14, join as join29, resolve as resolve23 } from "node:path";
15540
15892
  init_sqlite_replication();
15541
15893
  async function restoreRecoveryArchive(options) {
@@ -15561,7 +15913,7 @@ async function restoreOriginal(options, original, currentHCheck) {
15561
15913
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
15562
15914
  throw error;
15563
15915
  }
15564
- 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 });
15565
15917
  await syncDirectory(dirname14(destination));
15566
15918
  await syncDirectory(destination);
15567
15919
  const created = /* @__PURE__ */ new Set([destination]);
@@ -15575,29 +15927,28 @@ async function restoreOriginal(options, original, currentHCheck) {
15575
15927
  };
15576
15928
  directory2(join29(destination, "databases"));
15577
15929
  directory2(join29(destination, "trees"));
15930
+ await objects.restoreFiles(entry.databases.map((d) => ({ content: d.content, destination: join29(destination, "databases", d.databaseId + ".sqlite") })));
15578
15931
  for (const d of entry.databases) {
15579
- floor = await verify3();
15580
15932
  const path3 = join29(destination, "databases", d.databaseId + ".sqlite");
15581
- await objects.restoreFile(d.content, path3);
15582
15933
  const db = new DatabaseSync22(path3, { readOnly: true });
15583
15934
  try {
15584
- validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash);
15935
+ validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash, options.verifyDatabases !== false);
15585
15936
  } finally {
15586
15937
  db.close();
15587
15938
  }
15588
15939
  }
15940
+ const files = [];
15589
15941
  for (const tree of manifest.trees) {
15590
15942
  const root = join29(destination, "trees", tree.id);
15591
15943
  directory2(root);
15592
15944
  for (const path3 of tree.directories) directory2(join29(root, path3));
15593
15945
  for (const file of tree.files) {
15594
- floor = await verify3();
15595
15946
  const path3 = join29(root, file.path);
15596
15947
  directory2(dirname14(path3));
15597
- await objects.restoreFile(file.content, path3);
15598
- chmodSync5(path3, file.mode);
15948
+ files.push({ content: file.content, destination: path3, mode: file.mode });
15599
15949
  }
15600
15950
  }
15951
+ await objects.restoreFiles(files);
15601
15952
  directory2(join29(destination, "lance"));
15602
15953
  directory2(join29(destination, "sessions"));
15603
15954
  for (const kind of manifest.profile.trees) {
@@ -15605,10 +15956,10 @@ async function restoreOriginal(options, original, currentHCheck) {
15605
15956
  if (kind.kind === "vector") await restoreLancePublication({ tree, objects, destination: join29(destination, "lance", tree.id) });
15606
15957
  if (kind.kind === "session") {
15607
15958
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
15608
- const metadata3 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
15609
- const d = entry.databases.find((d2) => d2.databaseId === metadata3.databaseId);
15610
- const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata3.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
15611
- 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");
15612
15963
  const db = new DatabaseSync22(join29(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
15613
15964
  try {
15614
15965
  await restoreSessionEvents({ db, binding, destination: join29(destination, "sessions", tree.id), replicationRole: d.role });
@@ -15616,11 +15967,10 @@ async function restoreOriginal(options, original, currentHCheck) {
15616
15967
  db.close();
15617
15968
  }
15618
15969
  }
15619
- floor = await verify3();
15620
15970
  }
15621
15971
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
15622
15972
  await verify3();
15623
- 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 });
15624
15974
  await syncDirectory(destination);
15625
15975
  await verify3();
15626
15976
  return entry.receipt;
@@ -15628,14 +15978,14 @@ async function restoreOriginal(options, original, currentHCheck) {
15628
15978
 
15629
15979
  // src/continuity/runtime-checkpoints.ts
15630
15980
  import { DatabaseSync as DatabaseSync23 } from "node:sqlite";
15631
- 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";
15632
15982
  import { join as join30 } from "node:path";
15633
15983
  var zero = "0".repeat(64);
15634
15984
  var format3 = "engine7-runtime-checkpoint-control-v1";
15635
15985
  var hash7 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
15636
15986
  var natural3 = (value2) => typeof value2 === "number" && Number.isSafeInteger(value2) && value2 >= 0;
15637
15987
  var incarnation3 = (file) => {
15638
- const stat = lstatSync21(file, { bigint: true });
15988
+ const stat = lstatSync20(file, { bigint: true });
15639
15989
  return `${stat.dev}:${stat.ino}`;
15640
15990
  };
15641
15991
  var RuntimeCheckpointControl = class {
@@ -15648,7 +15998,7 @@ var RuntimeCheckpointControl = class {
15648
15998
  this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file) => join30(options.directory, file));
15649
15999
  const presence = this.files.map(existsSync14), fresh = presence.every((value2) => !value2);
15650
16000
  if (fresh && options.initialize !== true || !fresh && !presence.every(Boolean)) throw new Error("TRAVEL_CHECKPOINT_RECOVERY_REQUIRED");
15651
- 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 });
15652
16002
  const marker = JSON.parse(readPrivateFile2(this.files[0], 65536).toString());
15653
16003
  if (marker.format !== format3 || marker.binding !== this.binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
15654
16004
  preparePrivateDatabase(this.files[1]);
@@ -15705,7 +16055,6 @@ var RuntimeCheckpointControl = class {
15705
16055
  }
15706
16056
  async round(input) {
15707
16057
  const progress = this.status(), permit = this.permit();
15708
- await this.options.authority.assertPermit(permit, "PUBLISH");
15709
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");
15710
16059
  let sequence = progress.sequence, digest7 = progress.digest;
15711
16060
  for (const checkpoint of input.checkpoints) {
@@ -15737,11 +16086,28 @@ var RuntimeCheckpointControl = class {
15737
16086
 
15738
16087
  // src/continuity/recovery-archive-transfer.ts
15739
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";
15740
16092
  var endpoint = "/travel/archives/v1";
15741
- var metadataLimit = 16 * 1024 * 1024;
16093
+ var metadataLimit = RECOVERY_ARCHIVE_METADATA_BYTES;
15742
16094
  var requestLimit = 65536;
15743
16095
  var objectGroupLimit = 8;
15744
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
+ }
15745
16111
  var validId = (id2) => typeof id2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id2);
15746
16112
  function validateObjectParts(value2) {
15747
16113
  if (!Array.isArray(value2) || value2.length < 1 || value2.length > objectGroupLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
@@ -15816,7 +16182,7 @@ function refs(entry) {
15816
16182
  return result;
15817
16183
  }
15818
16184
  function createRecoveryArchiveServer(options) {
15819
- 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;
15820
16186
  if (!identity || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
15821
16187
  if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
15822
16188
  const peers = new Map(Object.entries(allowedPeers).map(([fingerprint, credential]) => [fingerprint.replaceAll(":", "").toLowerCase(), credential]));
@@ -15825,6 +16191,7 @@ function createRecoveryArchiveServer(options) {
15825
16191
  const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
15826
16192
  const started = Date.now(), timings = {};
15827
16193
  let phase = "authenticate", action = "unknown", failure;
16194
+ let streamStats;
15828
16195
  const mark = (next) => {
15829
16196
  timings[phase] = Date.now() - started;
15830
16197
  phase = next;
@@ -15832,6 +16199,10 @@ function createRecoveryArchiveServer(options) {
15832
16199
  res.setHeader("Cache-Control", "no-store");
15833
16200
  const refuse = (status, error) => {
15834
16201
  if (!res.writableEnded && !res.destroyed) {
16202
+ if (res.headersSent) {
16203
+ res.destroy();
16204
+ return;
16205
+ }
15835
16206
  res.statusCode = status;
15836
16207
  res.setHeader("Content-Type", "application/json");
15837
16208
  res.end(JSON.stringify({ error }));
@@ -15869,6 +16240,11 @@ function createRecoveryArchiveServer(options) {
15869
16240
  const slot = { archiveDigest };
15870
16241
  slots.add(slot);
15871
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);
15872
16248
  mark("body");
15873
16249
  const timer = setTimeout(() => {
15874
16250
  refuse(408, "RECOVERY_TRANSFER_REFUSED");
@@ -15884,8 +16260,8 @@ function createRecoveryArchiveServer(options) {
15884
16260
  }
15885
16261
  clearTimeout(timer);
15886
16262
  const input = JSON.parse(Buffer.concat(chunks).toString());
15887
- if (archiveDigest && input?.action !== "parts") throw new Error();
15888
- 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";
15889
16265
  mark("resolve");
15890
16266
  if (input?.version === 1 && input.action === "list") {
15891
16267
  if (Object.keys(input).some((key2) => !["version", "action"].includes(key2))) throw new Error();
@@ -15900,8 +16276,8 @@ function createRecoveryArchiveServer(options) {
15900
16276
  return;
15901
16277
  }
15902
16278
  const ancestry = ["manifests", "manifest-page"].includes(input?.action), paged = input?.action === "manifest-page";
15903
- 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();
15904
- 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();
15905
16281
  if (ancestry && !validCommon(input.common)) throw new Error();
15906
16282
  const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
15907
16283
  const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
@@ -15917,6 +16293,111 @@ function createRecoveryArchiveServer(options) {
15917
16293
  const floor = (await authority.status(principal)).deletionWatermark;
15918
16294
  await checkRecoveryDeletionAsync(entry.manifest, () => floor);
15919
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
+ }
15920
16401
  let body;
15921
16402
  if (ancestry) {
15922
16403
  if (!evidence && !readManifests || entry.kind !== "LOCAL") throw new Error();
@@ -15937,6 +16418,7 @@ function createRecoveryArchiveServer(options) {
15937
16418
  body = Buffer.from(JSON.stringify(entry));
15938
16419
  if (body.length > metadataLimit) throw new Error();
15939
16420
  res.setHeader("Content-Type", "application/json");
16421
+ if (streaming) res.setHeader("X-Engine7-Recovery-Stream", "1");
15940
16422
  } else if (input.action === "parts") {
15941
16423
  const group = validateObjectParts(input.parts), allowed = refs(entry), parts = [];
15942
16424
  if (group.some((part) => allowed.get(part.ref.sha256)?.bytes !== part.ref.bytes)) throw new Error();
@@ -15963,6 +16445,16 @@ function createRecoveryArchiveServer(options) {
15963
16445
  const [control2] = await Promise.all([authority.status(principal), assertAvailable()]), latest = control2.deletionWatermark;
15964
16446
  await checkRecoveryDeletionAsync(entry.manifest, () => latest, floor);
15965
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
+ }
15966
16458
  res.setHeader("Content-Length", body.length);
15967
16459
  res.end(body);
15968
16460
  } catch (error) {
@@ -15970,9 +16462,8 @@ function createRecoveryArchiveServer(options) {
15970
16462
  refuse(409, "RECOVERY_TRANSFER_REFUSED");
15971
16463
  } finally {
15972
16464
  clearTimeout(timer);
15973
- slots.delete(slot);
15974
- if (!slots.size) busy.delete(fingerprint);
15975
- 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");
15976
16467
  }
15977
16468
  });
15978
16469
  server.headersTimeout = 5e3;
@@ -15990,6 +16481,7 @@ var RecoveryArchiveClient = class {
15990
16481
  key;
15991
16482
  timeout;
15992
16483
  pending = /* @__PURE__ */ new Map();
16484
+ streamAvailable = false;
15993
16485
  closed = false;
15994
16486
  constructor(options) {
15995
16487
  try {
@@ -16037,6 +16529,7 @@ var RecoveryArchiveClient = class {
16037
16529
  const req = request2(this.url, { method: "POST", agent: this.agent, headers: {
16038
16530
  "Content-Type": "application/json",
16039
16531
  "Content-Length": body.length,
16532
+ "Accept-Encoding": "br, gzip",
16040
16533
  ...archiveDigest ? { "X-Engine7-Recovery-Archive": archiveDigest } : {}
16041
16534
  } }, (res) => {
16042
16535
  responseStarted = true;
@@ -16045,6 +16538,7 @@ var RecoveryArchiveClient = class {
16045
16538
  finish(new Error(res.statusCode === 503 ? "RECOVERY_TRANSFER_BUSY" : "RECOVERY_TRANSFER_REFUSED"));
16046
16539
  return;
16047
16540
  }
16541
+ if (input.action === "read") this.streamAvailable = res.headers["x-engine7-recovery-stream"] === "1";
16048
16542
  const chunks = [];
16049
16543
  let bytes = 0;
16050
16544
  res.on("data", (chunk) => {
@@ -16054,7 +16548,15 @@ var RecoveryArchiveClient = class {
16054
16548
  else chunks.push(chunk);
16055
16549
  });
16056
16550
  res.once("error", (error) => unavailable(error.code));
16057
- 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
+ });
16058
16560
  });
16059
16561
  this.pending.set(req, archiveDigest);
16060
16562
  const timer = setTimeout(() => unavailable("TIMEOUT"), this.timeout);
@@ -16136,6 +16638,151 @@ var RecoveryArchiveClient = class {
16136
16638
  return result;
16137
16639
  });
16138
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
+ }
16139
16786
  close() {
16140
16787
  if (this.closed) return;
16141
16788
  this.closed = true;
@@ -16147,8 +16794,9 @@ var RecoveryArchiveClient = class {
16147
16794
  async function transferRecoveryArchive(options) {
16148
16795
  const maximum = options.maximumBytes ?? 16 * 1024 * 1024 * 1024;
16149
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);
16150
16798
  await options.beforeStep?.();
16151
- 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);
16152
16800
  await options.beforeStep?.();
16153
16801
  if (entry.id !== options.id || validated.receipt.digest !== options.expectedDigest) throw new Error("RECOVERY_ARCHIVE_DIGEST");
16154
16802
  let floor = await checkRecoveryDeletionAsync(entry.manifest, options.deletionWatermark);
@@ -16159,12 +16807,70 @@ async function transferRecoveryArchive(options) {
16159
16807
  const objects = refs(entry), bytes = validated.body.length + [...objects.values()].reduce((sum, ref) => sum + ref.bytes, 0);
16160
16808
  if (!Number.isSafeInteger(bytes) || bytes > maximum) throw new Error("RECOVERY_TRANSFER_BUDGET");
16161
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
+ }
16162
16864
  for (let offset = 0; offset < all.length; offset += objectGroupLimit) {
16163
16865
  const missing = [];
16164
- for (const ref of all.slice(offset, offset + objectGroupLimit)) {
16866
+ const verified = await Promise.allSettled(all.slice(offset, offset + objectGroupLimit).map(async (ref) => {
16165
16867
  await options.beforeStep?.();
16166
16868
  await check();
16167
- if (!await options.archive.objects.has(ref)) missing.push(ref);
16869
+ return await options.archive.objects.has(ref) ? void 0 : ref;
16870
+ }));
16871
+ for (const result of verified) {
16872
+ if (result.status === "rejected") throw result.reason;
16873
+ if (result.value) missing.push(result.value);
16168
16874
  }
16169
16875
  if (!missing.length) continue;
16170
16876
  if (options.peer.parts && missing.reduce((bytes2, ref) => bytes2 + ref.bytes, 0) > partBodyLimit) {
@@ -16260,18 +16966,18 @@ async function transferRecoveryArchive(options) {
16260
16966
  return options.archive.import(entry, async () => {
16261
16967
  await check();
16262
16968
  return floor;
16263
- });
16969
+ }, false);
16264
16970
  }
16265
16971
 
16266
16972
  // src/continuity/runtime-replica-repository.ts
16267
16973
  import { DatabaseSync as DatabaseSync25 } from "node:sqlite";
16268
- 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";
16269
16975
  import { isAbsolute as isAbsolute7, join as join32, resolve as resolve25 } from "node:path";
16270
16976
  import { randomUUID as randomUUID13 } from "node:crypto";
16271
16977
 
16272
16978
  // src/continuity/runtime-replica-seed.ts
16273
16979
  import { DatabaseSync as DatabaseSync24 } from "node:sqlite";
16274
- 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";
16275
16981
  import { dirname as dirname15, isAbsolute as isAbsolute6, join as join31, resolve as resolve24 } from "node:path";
16276
16982
  init_sqlite_replication();
16277
16983
  init_schema_migrations();
@@ -16299,8 +17005,7 @@ async function seedRuntimeReplica(options) {
16299
17005
  const check = async () => {
16300
17006
  const permit = await (options.permitSupplier?.() ?? options.permit);
16301
17007
  if (!permit || ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== options.permit[key2])) throw new Error("TRAVEL_REPLICA_IDENTITY");
16302
- await options.authority.assertPermit(permit, "CONTROL");
16303
- 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));
16304
17009
  if (digest7 !== options.expectedDigest || manifest.sequence !== 1 || manifest.parentDigest !== "0".repeat(64)) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
16305
17010
  if (status.checkpointDigest !== controlCheckpoint) await options.authority.verifyAncestor(options.principal, controlCheckpoint, String(status.checkpointDigest));
16306
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");
@@ -16328,23 +17033,25 @@ async function seedRuntimeReplica(options) {
16328
17033
  };
16329
17034
  try {
16330
17035
  owner = acquireReplicaOwner(dataDirectory, true);
16331
- 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 });
16332
17037
  const refs2 = /* @__PURE__ */ new Map();
16333
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);
16334
- for (const ref of refs2.values()) {
16335
- await check();
16336
- if (!await options.objects.has(ref)) {
16337
- const stored = await options.objects.put(await options.archive.objects.read(ref));
16338
- if (stored.sha256 !== ref.sha256 || stored.bytes !== ref.bytes) throw new Error("TRAVEL_REPLICA_OBJECT");
16339
- }
17039
+ const independent = [...refs2.values()];
17040
+ for (let offset = 0; options.objects !== options.archive.objects && offset < independent.length; offset += 8) {
17041
+ const results = await Promise.allSettled(independent.slice(offset, offset + 8).map(async (ref) => {
17042
+ if (!await options.objects.has(ref)) {
17043
+ const stored = await options.objects.put(await options.archive.objects.read(ref));
17044
+ if (stored.sha256 !== ref.sha256 || stored.bytes !== ref.bytes) throw new Error("TRAVEL_REPLICA_OBJECT");
17045
+ }
17046
+ }));
17047
+ const failed = results.find((result) => result.status === "rejected");
17048
+ if (failed) throw failed.reason;
16340
17049
  }
16341
17050
  for (const d of entry.databases) {
16342
- await check();
16343
17051
  const file = join31(destination, "databases", d.databaseId + ".sqlite");
16344
17052
  const probe = new DatabaseSync24(file, { readOnly: true });
16345
17053
  let component, version;
16346
17054
  try {
16347
- validateRecoveryDatabase(probe, manifest, d.databaseId, "source", d.schemaHash);
16348
17055
  const schema5 = readSchemaVersion(probe);
16349
17056
  component = schema5?.component;
16350
17057
  version = schema5?.version;
@@ -16361,7 +17068,7 @@ async function seedRuntimeReplica(options) {
16361
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));
16362
17069
  const binding = normalizeBinding({ ...identity, databaseId: d.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
16363
17070
  replicas[d.databaseId] = new SQLiteReplicationReplica(db, binding, { schemaHash: d.schemaHash, baseline: manifest.databases.find((value2) => value2.databaseId === d.databaseId).head, suppressTriggers });
16364
- validateRecoveryDatabase(db, manifest, d.databaseId, "replica", d.schemaHash);
17071
+ validateRecoveryDatabase(db, manifest, d.databaseId, "replica", d.schemaHash, false);
16365
17072
  }
16366
17073
  await check();
16367
17074
  receiver = await PublicationReplica.open({ directory: join31(dataDirectory, "publications"), profile: manifest.profile, objects: options.objects, replicas, minimumDeletionWatermark: manifest.deletionWatermark });
@@ -16369,7 +17076,7 @@ async function seedRuntimeReplica(options) {
16369
17076
  const receipt2 = await receiver.publish(manifest.sequence);
16370
17077
  if (receipt2.state !== "PUBLISHED" || receipt2.digest !== digest7) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
16371
17078
  await check();
16372
- 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 });
16373
17080
  await syncDirectory(destination);
16374
17081
  await syncDirectory(dataDirectory);
16375
17082
  return { receiver, databases, replicas, profile: manifest.profile, receipt: receipt2, close };
@@ -16422,13 +17129,13 @@ async function openSeededRuntimeReplica(options) {
16422
17129
  floor();
16423
17130
  const file = join31(options.destination, "databases", d.databaseId + ".sqlite");
16424
17131
  if (!existsSync15(file)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
16425
- const stat = lstatSync22(file);
17132
+ const stat = lstatSync21(file);
16426
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");
16427
17134
  const probe = new DatabaseSync24(file, { readOnly: true }), binding = normalizeBinding({ ...profile.identity, databaseId: d.databaseId, baselineId: profile.baselineId, epoch: profile.epoch });
16428
17135
  let component, version;
16429
17136
  try {
16430
17137
  const control2 = probe.prepare("SELECT binding,schema_hash FROM e7_replication_control WHERE role='replica'").get(), schema5 = readSchemaVersion(probe);
16431
- 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");
16432
17139
  component = schema5?.component;
16433
17140
  version = schema5?.version;
16434
17141
  } finally {
@@ -16443,11 +17150,11 @@ async function openSeededRuntimeReplica(options) {
16443
17150
  replicas[d.databaseId] = new SQLiteReplicationReplica(db, binding, { schemaHash: d.schemaHash, baseline: manifest.databases.find((value2) => value2.databaseId === d.databaseId).head, suppressTriggers });
16444
17151
  }
16445
17152
  receiver = await PublicationReplica.open({ directory: dirname15(publicationFile), profile, objects: options.objects, replicas, minimumDeletionWatermark: floor() });
16446
- const status = await receiver.status();
17153
+ const status = await receiver.status(false);
16447
17154
  if (!status.published || status.published.sequence < manifest.sequence) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
16448
17155
  if (status.dataReady) {
16449
17156
  const current2 = await receiver.manifest(status.published.sequence);
16450
- 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);
16451
17158
  }
16452
17159
  floor();
16453
17160
  return { receiver, databases, replicas, profile, receipt: status.published, close };
@@ -16460,7 +17167,7 @@ async function openSeededRuntimeReplica(options) {
16460
17167
  // src/continuity/runtime-replica-repository.ts
16461
17168
  var validId2 = (value2) => typeof value2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2);
16462
17169
  var incarnation4 = (file) => {
16463
- const stat = lstatSync23(file, { bigint: true });
17170
+ const stat = lstatSync22(file, { bigint: true });
16464
17171
  return `${stat.dev}:${stat.ino}`;
16465
17172
  };
16466
17173
  var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
@@ -16474,7 +17181,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
16474
17181
  const presence = this.files.map(existsSync16), fresh = presence.every((value2) => !value2);
16475
17182
  if (fresh && (options.initialize !== true || existsSync16(join32(options.directory, "receivers"))) || !fresh && !presence.every(Boolean)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
16476
17183
  const binding = JSON.stringify([options.objects.identity, options.nodeId, options.generationsDirectory]);
16477
- 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 });
16478
17185
  const marker = JSON.parse(readPrivateFile2(this.files[0], 65536).toString());
16479
17186
  if (marker.format !== "engine7-runtime-replica-repository-v1" || marker.binding !== binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_REPLICA_IDENTITY");
16480
17187
  preparePrivateDatabase(this.files[1]);
@@ -16569,9 +17276,8 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
16569
17276
  const check = async () => {
16570
17277
  this.assertOpen();
16571
17278
  const permit = await (request7.permitSupplier?.() ?? request7.permit);
16572
- 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));
16573
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");
16574
- const status = await request7.authority.status(request7.principal);
16575
17281
  if (status.deletionWatermark !== entry.manifest.deletionWatermark || this.options.deletionWatermark() !== entry.manifest.deletionWatermark) throw new Error("TRAVEL_REPLICA_DELETION_BARRIER");
16576
17282
  if (status.buildManifestId !== entry.manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
16577
17283
  };
@@ -16774,7 +17480,7 @@ function createPublicationServer(options) {
16774
17480
  };
16775
17481
  switch (value2.operation) {
16776
17482
  case "status":
16777
- result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
17483
+ result = preservePublished ? await mutate(() => receiver.status(false)) : await receiver.status(false);
16778
17484
  break;
16779
17485
  case "replication-status":
16780
17486
  result = await receiver.replicationStatus();
@@ -16782,7 +17488,6 @@ function createPublicationServer(options) {
16782
17488
  case "missing": {
16783
17489
  if (!Array.isArray(value2.refs) || value2.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
16784
17490
  const missing = await Promise.all(value2.refs.map(async (ref) => {
16785
- await check();
16786
17491
  validateObjectRef(ref);
16787
17492
  return await receiver.objects.has(ref) ? null : ref.sha256;
16788
17493
  }));
@@ -16882,26 +17587,26 @@ async function createTravelNodeDataServer(options) {
16882
17587
 
16883
17588
  // src/continuity/recovery-runtime-adapter.ts
16884
17589
  import { DatabaseSync as DatabaseSync28 } from "node:sqlite";
16885
- import { lstatSync as lstatSync25, realpathSync as realpathSync21 } from "node:fs";
17590
+ import { lstatSync as lstatSync24, realpathSync as realpathSync21 } from "node:fs";
16886
17591
  import { isAbsolute as isAbsolute8, join as join36, resolve as resolve27 } from "node:path";
16887
17592
  init_schema_migrations();
16888
17593
 
16889
17594
  // src/continuity/recovery-admission.ts
16890
17595
  import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
16891
17596
  import { createHash as createHash37 } from "node:crypto";
16892
- 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";
16893
17598
  import { join as join34 } from "node:path";
16894
17599
 
16895
17600
  // src/continuity/recovery-diff.ts
16896
17601
  import { DatabaseSync as DatabaseSync26 } from "node:sqlite";
16897
17602
  import { createHash as createHash36 } from "node:crypto";
16898
- 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";
16899
17604
  import { join as join33 } from "node:path";
16900
17605
  init_legacy_sqlite_indexes();
16901
17606
  init_schema_migrations();
16902
17607
  var same9 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
16903
17608
  var quote2 = (s) => '"' + s.replaceAll('"', '""') + '"';
16904
- 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"]);
16905
17610
  function value(cell) {
16906
17611
  if (cell === null) return ["null"];
16907
17612
  if (typeof cell === "bigint") return ["integer", String(cell)];
@@ -16922,7 +17627,7 @@ function tables(db) {
16922
17627
  const result = [];
16923
17628
  for (const row of db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name").all()) {
16924
17629
  const name = String(row.name);
16925
- 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;
16926
17631
  if (/CREATE\s+VIRTUAL\s+TABLE/i.test(String(row.sql))) throw new Error("RECOVERY_DIFF_UNSUPPORTED_TABLE");
16927
17632
  const info = db.prepare("PRAGMA table_info(" + quote2(name) + ")").all();
16928
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));
@@ -16990,7 +17695,7 @@ async function compareRecoveryArchives(options) {
16990
17695
  const entry = entries[index], ref = references[index], d = entry.databases.find((d2) => d2.databaseId === databaseId);
16991
17696
  const temporary = mkdtempSync2(join33(ref.archive.directory, ".compare-"));
16992
17697
  temporaries.push(temporary);
16993
- 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 });
16994
17699
  const file = join33(temporary, databaseId + ".sqlite");
16995
17700
  await ref.archive.objects.restoreFile(d.content, file);
16996
17701
  const db = new DatabaseSync26(file, { readOnly: true, allowExtension: true });
@@ -17200,10 +17905,10 @@ function socialReferences(db, table, row, archived) {
17200
17905
  statement.setReadBigInts(true);
17201
17906
  const current2 = statement.get(scope, id2), original = archived("memory_sources", { scope_id: row.scope_id, source_id: ["text", id2] });
17202
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;
17203
- const metadata3 = archived("memory_social_sources", { scope_id: row.scope_id, source_id: ["text", id2] });
17204
- 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) {
17205
17910
  const live = db.prepare("SELECT * FROM memory_social_sources WHERE scope_id=? AND source_id=?").get(scope, id2);
17206
- 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;
17207
17912
  sources.add(id2);
17208
17913
  try {
17209
17914
  if (!references(String(live.context_refs), true) || !references(String(live.basis_refs), historical)) return null;
@@ -17917,7 +18622,7 @@ async function admitRecoveryArchives(options) {
17917
18622
  }
17918
18623
  await active();
17919
18624
  const commonDirectory = mkdtempSync3(join34(options.common.archive.directory, ".admission-common-"));
17920
- 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 });
17921
18626
  const commonDatabases = /* @__PURE__ */ new Map();
17922
18627
  try {
17923
18628
  for (const d of common.databases) {
@@ -18057,6 +18762,10 @@ async function admitRecoveryArchives(options) {
18057
18762
  result.state = "HISTORY";
18058
18763
  result.reason = "node_local_auth_readiness_history";
18059
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
+ }
18060
18769
  if (deletions.length && local.manifest.deletionWatermark < getPermit().deletionWatermark) {
18061
18770
  result.state = "DELETED_BLOCKED";
18062
18771
  result.reason = "unmapped_old_dependency";
@@ -18197,7 +18906,7 @@ async function admitRecoveryArchives(options) {
18197
18906
 
18198
18907
  // src/continuity/recovery-artifact-projection.ts
18199
18908
  import { createHash as createHash38, randomUUID as randomUUID14 } from "node:crypto";
18200
- 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";
18201
18910
  import { dirname as dirname16, join as join35, resolve as resolve26 } from "node:path";
18202
18911
  import { createRequire as createRequire7 } from "node:module";
18203
18912
  init_runtime_authority();
@@ -18209,7 +18918,7 @@ function privateParents(root, path3) {
18209
18918
  if (!isWithin(root, directory2)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
18210
18919
  if (directory2 !== root) visit(dirname16(directory2));
18211
18920
  if (!existsSync17(directory2)) mkdirSync14(directory2, { mode: 448 });
18212
- const s = lstatSync24(directory2);
18921
+ const s = lstatSync23(directory2);
18213
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");
18214
18923
  };
18215
18924
  visit(path3);
@@ -18312,27 +19021,27 @@ async function projectRecoveryArtifacts(options) {
18312
19021
  privateParents(root, dirname16(path3));
18313
19022
  active();
18314
19023
  if (existsSync17(path3)) {
18315
- const s = lstatSync24(path3);
18316
- 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;
18317
19026
  commit();
18318
19027
  continue;
18319
19028
  }
18320
19029
  const temporary = join35(dirname16(path3), ".recovery-" + randomUUID14()), original = Buffer.from(body);
18321
- writeFileSync24(temporary, original, { mode: local.mode, flag: "wx", flush: true });
19030
+ writeFileSync23(temporary, original, { mode: local.mode, flag: "wx", flush: true });
18322
19031
  let created = false;
18323
19032
  try {
18324
19033
  active();
18325
- linkSync2(temporary, path3);
19034
+ linkSync(temporary, path3);
18326
19035
  created = true;
18327
- unlinkSync10(temporary);
19036
+ unlinkSync9(temporary);
18328
19037
  await syncDirectory(dirname16(path3));
18329
19038
  await checkRemote();
18330
19039
  commit();
18331
19040
  } catch (error) {
18332
- 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);
18333
19042
  if (!/RECOVERY_ARTIFACT_DEPENDENCY_PENDING/.test(String(error))) throw error;
18334
19043
  } finally {
18335
- if (existsSync17(temporary)) unlinkSync10(temporary);
19044
+ if (existsSync17(temporary)) unlinkSync9(temporary);
18336
19045
  }
18337
19046
  }
18338
19047
  } else if (kind === "session") {
@@ -18455,7 +19164,7 @@ async function admitNormalRecoveryArchives(options) {
18455
19164
  runtime.assert("WRITE");
18456
19165
  for (const id2 of profile.databaseIds) {
18457
19166
  validatePublicationPath(layout.databases[id2]);
18458
- 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);
18459
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");
18460
19169
  if (place.component === "mem7") {
18461
19170
  if (id2 !== "memory" || memory || place.stateDir !== stateDir) throw new Error("RECOVERY_CURRENT_LAYOUT");
@@ -18533,7 +19242,7 @@ init_runtime_lock();
18533
19242
  // src/continuity/local-exit-proof.ts
18534
19243
  init_runtime_lock();
18535
19244
  import { createHash as createHash39, verify as verify2 } from "node:crypto";
18536
- 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";
18537
19246
  import { join as join37, relative as relative8 } from "node:path";
18538
19247
  var hash9 = (value2) => createHash39("sha256").update(value2).digest("hex");
18539
19248
  var equal2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
@@ -18544,7 +19253,7 @@ function copyLocalExitPath(source, path3) {
18544
19253
  async function localExitFilesDigest(root, ordinary = false) {
18545
19254
  const files = [];
18546
19255
  const visit = async (directory2) => {
18547
- 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))) {
18548
19257
  const file = join37(directory2, entry.name);
18549
19258
  if (ordinary ? relative8(root, file).replaceAll("\\", "/") === ".continuity/travel-exit-receipt.json" : !copyLocalExitPath(root, file)) continue;
18550
19259
  if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
@@ -18583,7 +19292,7 @@ async function writeStoppedLocalExitProof(options) {
18583
19292
  if (!equal2(binding, await currentBinding(options.stateDir, options.authority, options.principal))) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
18584
19293
  const body = { format: "engine7-stopped-local-exit-v1", ...binding, filesDigest };
18585
19294
  mkdirSync15(join37(options.stateDir, ".continuity"), { recursive: true, mode: 448 });
18586
- 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 });
18587
19296
  });
18588
19297
  }
18589
19298
 
@@ -18715,12 +19424,15 @@ var TravelNodeAgent = class _TravelNodeAgent {
18715
19424
  runtime: () => node.stopping ? null : node.runtime ?? node.activatingRuntime ?? null,
18716
19425
  intervalMs: options.heartbeatIntervalMs,
18717
19426
  client: { register: async (boot) => {
18718
- await node.assertDataAvailable();
19427
+ node.assertLocalDataAvailable();
18719
19428
  return options.report.register(boot);
18720
19429
  }, heartbeat: async (input) => {
18721
- await node.assertDataAvailable();
19430
+ await node.freshKeyWatermark();
19431
+ node.assertLocalDataAvailable();
18722
19432
  const response = await options.report.heartbeat(input);
18723
- 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");
18724
19436
  return response;
18725
19437
  } }
18726
19438
  });
@@ -18743,23 +19455,31 @@ var TravelNodeAgent = class _TravelNodeAgent {
18743
19455
  }
18744
19456
  checkBuild() {
18745
19457
  for (const b of [this.options.build, this.options.dataBuild]) {
18746
- const info = lstatSync26(b.entry);
18747
- 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");
18748
19460
  }
18749
19461
  }
18750
19462
  assertKey() {
18751
19463
  if (this.closed || clock() - this.lastKeyCheck >= this.maxKeyAge) throw new Error("TRAVEL_NODE_KEY_UNAVAILABLE");
18752
19464
  }
18753
- async assertDataAvailable() {
19465
+ async freshKeyWatermark() {
19466
+ if (clock() - this.lastKeyCheck >= this.refreshInterval) await this.refreshKey();
18754
19467
  this.assertKey();
18755
- const status = await this.options.authority.status(this.principal);
19468
+ return this.keyWatermark;
19469
+ }
19470
+ assertLocalDataAvailable() {
18756
19471
  this.assertKey();
18757
- if (status.deletionWatermark !== this.keyWatermark) throw new Error("TRAVEL_NODE_KEY_UNAVAILABLE");
18758
19472
  if (this.sourceObjects) {
18759
- const stat = lstatSync26(join38(this.sourceObjects.directory, "catalog.sqlite"), { bigint: true });
19473
+ const stat = lstatSync25(join38(this.sourceObjects.directory, "catalog.sqlite"), { bigint: true });
18760
19474
  if (stat.isSymbolicLink() || !stat.isFile() || `${stat.dev}:${stat.ino}` !== this.sourceCatalogIdentity) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
18761
19475
  }
18762
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
+ }
18763
19483
  async currentReceiver() {
18764
19484
  const [, status] = await Promise.all([this.assertDataAvailable(), Promise.resolve().then(() => this.options.authority.status(this.principal))]);
18765
19485
  if (this.runtime || this.process || this.dataProcess || !this.replica) return null;
@@ -18771,7 +19491,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
18771
19491
  try {
18772
19492
  const replica = this.replica;
18773
19493
  if (!replica || replica.receiver !== receiver || await this.currentReceiver() !== receiver) throw new Error("PUBLICATION_RECEIVER_CHANGED");
18774
- const status = await receiver.status();
19494
+ const status = await receiver.status(false);
18775
19495
  if (!status.published || !status.dataReady) return;
18776
19496
  const manifest = await receiver.manifest(status.published.sequence);
18777
19497
  const check = async () => {
@@ -18784,7 +19504,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
18784
19504
  manifest,
18785
19505
  databases: replica.databases,
18786
19506
  receiver,
18787
- deletionWatermark: check
19507
+ deletionWatermark: check,
19508
+ verifyRetained: false
18788
19509
  });
18789
19510
  await check();
18790
19511
  } finally {
@@ -18851,7 +19572,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
18851
19572
  if (this.stopping || token !== this.generationToken || archive !== this.archive) throw new Error("TRAVEL_NODE_CANCELLED");
18852
19573
  this.assertKey();
18853
19574
  };
18854
- await this.refreshKey();
19575
+ if (clock() - this.lastKeyCheck >= this.refreshInterval) await this.refreshKey();
18855
19576
  check();
18856
19577
  const entry = await archive.read(id2).catch((error) => {
18857
19578
  if (error instanceof Error && error.message === "RECOVERY_ARCHIVE_NOT_FOUND") return null;
@@ -18922,7 +19643,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
18922
19643
  assertPrivateDirectory2(directory2);
18923
19644
  assertPrivateDirectory2(join38(directory2, "chunks"));
18924
19645
  if (realpathSync22(directory2) !== directory2 || !existsSync18(file)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
18925
- const stat = lstatSync26(file, { bigint: true });
19646
+ const stat = lstatSync25(file, { bigint: true });
18926
19647
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
18927
19648
  const db = new DatabaseSync29(file, { readOnly: true });
18928
19649
  try {
@@ -18956,8 +19677,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
18956
19677
  async preserveReplicaRemote() {
18957
19678
  if (!this.replica || this.runtime || this.process || this.dataProcess) return;
18958
19679
  const replica = this.replica;
18959
- const [before, status] = await Promise.all([this.options.authority.status(this.principal), replica.receiver.status()]);
18960
- await this.assertDataAvailable();
19680
+ const [before, status] = await Promise.all([this.options.authority.status(this.principal), replica.receiver.status(false)]);
19681
+ this.assertLocalDataAvailable();
18961
19682
  if (!status.dataReady || !status.published || status.published.digest !== before.checkpointDigest) return;
18962
19683
  const digest7 = status.published.digest, manifest = await replica.receiver.manifest(status.published.sequence);
18963
19684
  const check = async () => {
@@ -18965,15 +19686,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
18965
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");
18966
19687
  return this.keyWatermark;
18967
19688
  };
18968
- await check();
18969
19689
  if (publicationDigest(manifest) !== digest7 || manifest.profile.buildManifestId !== this.options.build.manifestId) throw new Error("TRAVEL_NODE_CHECKPOINT");
18970
- await this.archive.preserve({ id: "remote-" + digest7, kind: "REMOTE", manifest, databases: replica.databases, receiver: replica.receiver, deletionWatermark: check });
18971
- await check();
19690
+ await this.archive.preserve({ id: "remote-" + digest7, kind: "REMOTE", manifest, databases: replica.databases, receiver: replica.receiver, deletionWatermark: check, verifyRetained: false });
18972
19691
  }
18973
19692
  listDataArchiveReceipts() {
18974
19693
  return this.exclusive(async () => {
18975
- await this.refreshKey();
18976
- this.assertKey();
19694
+ await this.freshKeyWatermark();
18977
19695
  if (!this.runtime && !this.process && !this.dataProcess) {
18978
19696
  const results = await Promise.allSettled([this.preserveBranches(), this.preserveReplicaRemote()]);
18979
19697
  for (const result of results) if (result.status === "rejected") throw result.reason;
@@ -19015,15 +19733,13 @@ var TravelNodeAgent = class _TravelNodeAgent {
19015
19733
  }
19016
19734
  readRecoveryManifests(common, localArchiveId) {
19017
19735
  return this.readRecoveryEvidence(localArchiveId, async () => {
19018
- await this.refreshKey();
19019
- this.assertKey();
19736
+ await this.freshKeyWatermark();
19020
19737
  return this.stoppedRecoveryManifests(common, localArchiveId);
19021
19738
  });
19022
19739
  }
19023
19740
  readRecoveryManifestEvidence(common, localArchiveId, maximum) {
19024
19741
  return this.readRecoveryEvidence(localArchiveId, async () => {
19025
- await this.refreshKey();
19026
- this.assertKey();
19742
+ await this.freshKeyWatermark();
19027
19743
  const archive = await this.dataArchive(localArchiveId), entry = await archive.read(localArchiveId);
19028
19744
  const manifests = await this.stoppedRecoveryManifests(common, localArchiveId, maximum);
19029
19745
  return { entry, manifests };
@@ -19061,21 +19777,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19061
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");
19062
19778
  const objects = await this.sourceObjectStore(profile), dataDirectory = join38(this.options.directory, "data", "source-" + hash10(String(row.binding)));
19063
19779
  const prior = this.db.prepare("SELECT archive_id,receipt FROM stopped_branches WHERE binding=?").get(String(row.binding));
19064
- if (prior) {
19065
- const archive = await RuntimeRecoveryArchive.open({ directory: join38(dataDirectory, "recovery"), objects });
19066
- try {
19067
- const entry = await archive.read(String(prior.archive_id));
19068
- if (entry.kind !== "LOCAL" || !same12(entry.manifest.profile, profile) || !same12(entry.receipt, JSON.parse(String(prior.receipt)))) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19069
- await checkRecoveryDeletionAsync(entry.manifest, async () => {
19070
- await this.assertDataAvailable();
19071
- return this.keyWatermark;
19072
- });
19073
- } finally {
19074
- archive.close();
19075
- }
19076
- continue;
19077
- }
19078
- const receipt2 = await preserveStoppedGeneration({
19780
+ const receipt2 = prior ? JSON.parse(String(prior.receipt)) : await preserveStoppedGeneration({
19079
19781
  stateDir,
19080
19782
  dataDirectory,
19081
19783
  objects,
@@ -19085,7 +19787,21 @@ var TravelNodeAgent = class _TravelNodeAgent {
19085
19787
  return this.keyWatermark;
19086
19788
  }
19087
19789
  });
19088
- 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
+ }
19089
19805
  }
19090
19806
  }
19091
19807
  refreshKey() {
@@ -19127,7 +19843,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19127
19843
  if (!/^[a-f0-9]{64}$/.test(digest7)) throw new Error("TRAVEL_NODE_CHECKPOINT");
19128
19844
  if (this.db.prepare("SELECT 1 FROM common_preparations WHERE digest=?").get(digest7)) return this.preparedCommon(digest7);
19129
19845
  if (!replica) throw new Error("TRAVEL_NODE_REPLICA_NOT_READY");
19130
- const { receiver, databases } = replica, status = await receiver.status();
19846
+ const { receiver, databases } = replica, status = await receiver.status(false);
19131
19847
  if (status.published?.digest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
19132
19848
  const manifest = await receiver.manifest(status.published.sequence);
19133
19849
  if (publicationDigest(manifest) !== digest7 || ["tenantId", "companionId", "seatId"].some((field) => manifest.profile.identity[field] !== this.principal[field])) throw new Error("TRAVEL_NODE_CHECKPOINT");
@@ -19142,7 +19858,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19142
19858
  if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync22(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_PATH");
19143
19859
  const receipt2 = JSON.parse(readPrivateFile2(join38(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
19144
19860
  if (receipt2.receipt?.digest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
19145
- verifyRuntimeGenerationIntegrity(snapshot2, receipt2.integrity);
19861
+ await verifyRuntimeGenerationIntegrityAsync(snapshot2, receipt2.integrity);
19146
19862
  validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
19147
19863
  return { snapshot: snapshot2, manifest };
19148
19864
  }
@@ -19174,22 +19890,22 @@ var TravelNodeAgent = class _TravelNodeAgent {
19174
19890
  if (prior.archive_digest !== entry.receipt.digest || !isWithin(this.options.generationsDirectory, snapshot2) || realpathSync22(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19175
19891
  const proof = JSON.parse(readPrivateFile2(join38(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
19176
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");
19177
- verifyRuntimeGenerationIntegrity(snapshot2, proof.integrity);
19893
+ await verifyRuntimeGenerationIntegrityAsync(snapshot2, proof.integrity);
19178
19894
  validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
19179
19895
  await check();
19180
19896
  return { snapshot: snapshot2, manifest };
19181
19897
  }
19182
19898
  const snapshot = join38(this.options.generationsDirectory, "snapshot-" + randomUUID15());
19183
- 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 });
19184
19900
  validateRuntimeActivationSnapshot(snapshot, manifest, locations);
19185
19901
  await check();
19186
- writeFileSync26(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19902
+ writeFileSync25(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19187
19903
  format: "engine7-runtime-publication-restore-v1",
19188
19904
  profile: manifest.profile,
19189
19905
  receipt: entry.publication,
19190
19906
  databases: manifest.databases,
19191
19907
  recoveryArchive: { id: entry.id, digest: entry.receipt.digest },
19192
- integrity: runtimeGenerationIntegrity(snapshot),
19908
+ integrity: await runtimeGenerationIntegrityAsync(snapshot),
19193
19909
  activationAllowed: false
19194
19910
  }), { mode: 384, flag: "wx", flush: true });
19195
19911
  await syncDirectory(snapshot);
@@ -19219,13 +19935,13 @@ var TravelNodeAgent = class _TravelNodeAgent {
19219
19935
  }
19220
19936
  const snapshot = join38(this.options.generationsDirectory, "snapshot-" + randomUUID15());
19221
19937
  await restoreCurrentHForDeletion({ archive: this.archive, id: id2, destination: snapshot, ...control2 });
19222
- writeFileSync26(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19938
+ writeFileSync25(join38(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
19223
19939
  format: "engine7-runtime-publication-restore-v1",
19224
19940
  profile: manifest.profile,
19225
19941
  receipt: entry.publication,
19226
19942
  databases: manifest.databases,
19227
19943
  recoveryArchive: { id: entry.id, digest: entry.receipt.digest },
19228
- integrity: runtimeGenerationIntegrity(snapshot),
19944
+ integrity: await runtimeGenerationIntegrityAsync(snapshot),
19229
19945
  activationAllowed: false
19230
19946
  }), { mode: 384, flag: "wx", flush: true });
19231
19947
  await syncDirectory(snapshot);
@@ -19255,12 +19971,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
19255
19971
  if (replica.receiver.objects !== this.archive.objects) throw new Error("TRAVEL_NODE_REPLICA_OBJECTS");
19256
19972
  if (!await (this.options.verifyDirectory ?? verifyRuntimeDirectory)(this.options.generationsDirectory)) throw new Error("TRAVEL_NODE_DIRECTORY");
19257
19973
  await check();
19258
- const status = await replica.receiver.status();
19974
+ const status = await replica.receiver.status(false);
19259
19975
  if (!status.dataReady || !status.published || status.profile.epoch !== (await this.options.authority.status(this.principal)).epoch) throw new Error("TRAVEL_NODE_CHECKPOINT");
19260
19976
  const prepared = await this.prepared(status.published.digest, replica);
19261
19977
  if (!same12(Object.keys(replica.databases).sort(), prepared.manifest.profile.databaseIds)) throw new Error("TRAVEL_NODE_CHECKPOINT");
19262
- for (const id2 of prepared.manifest.profile.databaseIds) validateRecoveryDatabase(replica.databases[id2], prepared.manifest, id2, "replica");
19263
- 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);
19264
19980
  await check();
19265
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");
19266
19982
  if ((prepared.deletionWatermark ?? prepared.manifest.deletionWatermark) !== this.keyWatermark) throw new Error("TRAVEL_NODE_DELETION_BARRIER");
@@ -19288,7 +20004,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19288
20004
  }
19289
20005
  replicaProfile() {
19290
20006
  return this.exclusive(async () => {
19291
- await this.refreshKey();
20007
+ await this.freshKeyWatermark();
19292
20008
  return (await this.currentReceiver())?.profile ?? null;
19293
20009
  });
19294
20010
  }
@@ -19336,14 +20052,20 @@ var TravelNodeAgent = class _TravelNodeAgent {
19336
20052
  trace("source-check");
19337
20053
  const token = this.generationToken;
19338
20054
  let currentPermit = request7.permit;
19339
- const boundedCheck = async () => {
20055
+ const localCheck = () => {
19340
20056
  if (this.closed || token !== this.generationToken) throw new Error("TRAVEL_NODE_CANCELLED");
19341
20057
  if (this.runtime || this.process || this.dataProcess) throw new Error("TRAVEL_NODE_GENERATION_COLLISION");
19342
- this.assertKey();
20058
+ this.assertLocalDataAvailable();
20059
+ };
20060
+ const boundedCheck = async () => {
20061
+ localCheck();
19343
20062
  const permit = currentPermit;
19344
- await this.options.authority.assertPermit(permit, "CONTROL");
19345
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");
19346
- 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;
19347
20069
  };
19348
20070
  const check = async () => {
19349
20071
  currentPermit = await (request7.permitSupplier?.() ?? request7.permit);
@@ -19372,7 +20094,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19372
20094
  await check();
19373
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");
19374
20096
  trace("copy-source-archive");
19375
- await transferRecoveryArchive({ peer, archive: this.archive, id: request7.archiveId, expectedDigest: request7.archiveDigest, deletionWatermark: boundedCheck, beforeStep: check });
20097
+ await transferRecoveryArchive({ peer, archive: this.archive, id: request7.archiveId, expectedDigest: request7.archiveDigest, entry, deletionWatermark: boundedCheck, beforeStep: async () => localCheck() });
19376
20098
  await check();
19377
20099
  if (!this.replicaRepository) {
19378
20100
  const initialize2 = this.db.prepare("SELECT replicas_ready FROM lifecycle WHERE id=1").get()?.replicas_ready === 0;
@@ -19381,8 +20103,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
19381
20103
  }
19382
20104
  await check();
19383
20105
  trace("seed-receiver");
19384
- const replica = await this.replicaRepository.bootstrap({ ...request7, authority: this.options.authority, permitSupplier: async () => {
19385
- await check();
20106
+ const replica = await this.replicaRepository.bootstrap({ ...request7, authority: this.options.authority, permitSupplier: () => {
20107
+ localCheck();
19386
20108
  return currentPermit;
19387
20109
  } });
19388
20110
  await check();
@@ -19403,7 +20125,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19403
20125
  if (!this.runtime && !this.process && !this.dataProcess) await this.preserveBranches();
19404
20126
  if (!await (this.options.verifyDirectory ?? verifyRuntimeDirectory)(this.options.generationsDirectory)) throw new Error("TRAVEL_NODE_DIRECTORY");
19405
20127
  const prepared = await this.prepared(digest7), effects = await this.options.gateway.preparationEvidence(this.principal);
19406
- const replica = this.replica, status = await replica?.receiver.status();
20128
+ const replica = this.replica, status = await replica?.receiver.status(false);
19407
20129
  if (prepared.deletionWatermark === void 0 && replica && status?.dataReady && status.published?.digest === digest7) {
19408
20130
  await this.archive.preserve({
19409
20131
  id: "common-" + digest7,
@@ -19411,10 +20133,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
19411
20133
  manifest: prepared.manifest,
19412
20134
  databases: replica.databases,
19413
20135
  receiver: replica.receiver,
19414
- deletionWatermark: () => {
19415
- this.assertKey();
19416
- return this.keyWatermark;
19417
- }
20136
+ deletionWatermark: () => this.freshKeyWatermark(),
20137
+ verifyRetained: false
19418
20138
  });
19419
20139
  }
19420
20140
  const deletionWatermark = prepared.deletionWatermark ?? prepared.manifest.deletionWatermark;
@@ -19457,9 +20177,9 @@ var TravelNodeAgent = class _TravelNodeAgent {
19457
20177
  await this.refreshKey();
19458
20178
  this.assertKey();
19459
20179
  if (!/^[a-f0-9]{64}$/.test(digest7)) throw new Error("TRAVEL_NODE_CHECKPOINT");
19460
- const replica = this.replica, status = await replica?.receiver.status();
20180
+ const replica = this.replica, status = await replica?.receiver.status(false);
19461
20181
  const deletionWatermark = async () => {
19462
- this.assertKey();
20182
+ await this.freshKeyWatermark();
19463
20183
  return (await this.options.authority.status(this.principal)).deletionWatermark;
19464
20184
  };
19465
20185
  if (replica && status?.dataReady && status.published?.digest === digest7) {
@@ -19471,7 +20191,8 @@ var TravelNodeAgent = class _TravelNodeAgent {
19471
20191
  manifest: prepared.manifest,
19472
20192
  databases: replica.databases,
19473
20193
  receiver: replica.receiver,
19474
- deletionWatermark
20194
+ deletionWatermark,
20195
+ verifyRetained: false
19475
20196
  });
19476
20197
  return;
19477
20198
  }
@@ -19500,7 +20221,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19500
20221
  await check();
19501
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");
19502
20223
  trace("copy-common");
19503
- 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 });
19504
20225
  await check();
19505
20226
  await this.preparedCommon(digest7);
19506
20227
  return;
@@ -19517,12 +20238,13 @@ var TravelNodeAgent = class _TravelNodeAgent {
19517
20238
  if (entry.kind !== "COMMON" || entry.receipt?.kind !== "COMMON" || entry.id !== id2 || publicationDigest(entry.manifest) !== digest7 || !same12(normalizePublicationProfile(entry.manifest.profile), profile)) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
19518
20239
  const check = async () => {
19519
20240
  this.assertKey();
19520
- await this.options.authority.assertPermit(this.runtime.assert("CONTROL"), "CONTROL");
19521
- if (this.runtime.assert("CONTROL").epoch !== permit.epoch || (await this.options.authority.status(this.principal)).checkpointDigest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
19522
- return deletionWatermark();
20241
+ const currentPermit = this.runtime.assert("CONTROL"), authority = this.options.authority;
20242
+ const current2 = authority.assertPermitWithStatus ? await authority.assertPermitWithStatus(currentPermit, "CONTROL") : (await authority.assertPermit(currentPermit, "CONTROL"), await authority.status(this.principal));
20243
+ if (this.runtime.assert("CONTROL").epoch !== permit.epoch || current2.checkpointDigest !== digest7 || current2.expired || current2.authorityBootId !== permit.authorityBootId || current2.epoch !== permit.epoch || current2.activeNodeId !== permit.nodeId || current2.activeBootId !== permit.bootId) throw new Error("TRAVEL_NODE_CHECKPOINT");
20244
+ return current2.deletionWatermark;
19523
20245
  };
19524
20246
  trace("copy-common");
19525
- 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 });
19526
20248
  await check();
19527
20249
  } finally {
19528
20250
  peer.close();
@@ -19580,7 +20302,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19580
20302
  assertActive();
19581
20303
  const prepared = await this.prepared(digest7), confirmed = await this.confirmPermit(permit);
19582
20304
  await assertGatewayResolved();
19583
- const replica = this.replica, replicaStatus = await replica?.receiver.status();
20305
+ const replica = this.replica, replicaStatus = await replica?.receiver.status(false);
19584
20306
  if (replica && replicaStatus?.dataReady && replicaStatus.published?.digest === digest7) {
19585
20307
  const common = await this.archive.read("common-" + digest7);
19586
20308
  if (common.kind !== "COMMON" || !same12(common.manifest, prepared.manifest)) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
@@ -19625,7 +20347,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19625
20347
  await assertGatewayResolved();
19626
20348
  const configFile = join38(destination, ".continuity", "engine-config.json"), config = { ...this.options.engineConfig, stateDir: destination, workspace: join38(destination, this.options.layout.trees.workspace) };
19627
20349
  validateTravelChannelConfiguration(config.channels);
19628
- writeFileSync26(configFile, JSON.stringify(config), { mode: 384, flush: true });
20350
+ writeFileSync25(configFile, JSON.stringify(config), { mode: 384, flush: true });
19629
20351
  const processDirectory = join38(this.options.directory, "processes");
19630
20352
  mkdirSync16(processDirectory, { recursive: true, mode: 448 });
19631
20353
  const dataRoot = join38(this.options.directory, "data");
@@ -19633,7 +20355,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19633
20355
  this.dataDirectory = join38(dataRoot, "source-" + hash10(binding));
19634
20356
  const encode2 = (value2) => value2.toString("base64"), keyService = this.options.keyService;
19635
20357
  const dataConfigFile = join38(destination, ".continuity", "data-config.json");
19636
- writeFileSync26(dataConfigFile, JSON.stringify({
20358
+ writeFileSync25(dataConfigFile, JSON.stringify({
19637
20359
  stateDir: destination,
19638
20360
  dataDirectory: this.dataDirectory,
19639
20361
  objectsDirectory: join38(dataRoot, "objects"),
@@ -19648,7 +20370,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19648
20370
  entry: this.options.dataBuild.entry,
19649
20371
  entrySha256: this.options.dataBuild.sha256,
19650
20372
  configFile: dataConfigFile,
19651
- timeoutMs: this.options.processTimeoutMs
20373
+ timeoutMs: this.options.dataProcessTimeoutMs ?? 3e5
19652
20374
  });
19653
20375
  await this.dataProcess.start();
19654
20376
  assertActive();
@@ -19790,7 +20512,20 @@ var TravelNodeAgent = class _TravelNodeAgent {
19790
20512
  const local = source ? await source.read(receipt2.id) : await peer.read(receipt2.id);
19791
20513
  await check();
19792
20514
  if (!same12(local.receipt, receipt2) || local.kind !== "LOCAL") throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
19793
- 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
+ }
19794
20529
  }
19795
20530
  if (missing.length) {
19796
20531
  trace("capture-current-remote");
@@ -19979,15 +20714,21 @@ var TravelNodeAgent = class _TravelNodeAgent {
19979
20714
  const token = this.generationToken, runtime = this.runtime, child = this.dataProcess, control2 = this.checkpointControl;
19980
20715
  const operation = (async () => {
19981
20716
  if (!runtime || !child || !control2) throw new Error("TRAVEL_PERMIT_REQUIRED");
19982
- const check = async () => {
20717
+ const localCheck = () => {
19983
20718
  if (this.closed || this.stopping || this.generationToken !== token || this.runtime !== runtime) throw new Error("TRAVEL_NODE_CANCELLED");
19984
- await this.assertDataAvailable();
20719
+ this.assertLocalDataAvailable();
19985
20720
  runtime.assert("CONTROL");
19986
20721
  };
20722
+ const check = async () => {
20723
+ localCheck();
20724
+ await this.assertDataAvailable();
20725
+ localCheck();
20726
+ };
19987
20727
  for (let batch = 0; batch < 16; batch++) {
19988
- await check();
20728
+ localCheck();
19989
20729
  const proof = await child.publishedCheckpoints(control2.status().sequence);
19990
- await check();
20730
+ localCheck();
20731
+ if (proof.checkpoints?.length) await check();
19991
20732
  await control2.advance(proof);
19992
20733
  if (proof.checkpoints.length < 64) break;
19993
20734
  }
@@ -20232,9 +20973,12 @@ var RemoteTravelDataAuthority = class {
20232
20973
  this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
20233
20974
  }
20234
20975
  async authenticate(credential) {
20976
+ return Object.freeze({ ...(await this.readIdentity(credential)).principal });
20977
+ }
20978
+ readIdentity(credential) {
20235
20979
  const grant = this.grants.find((grant2) => grant2.credential === credential);
20236
20980
  if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
20237
- return Object.freeze({ ...(await this.read(grant)).principal });
20981
+ return this.read(grant);
20238
20982
  }
20239
20983
  grant(principal) {
20240
20984
  const grant = this.grants.find((grant2) => equal3(principal, grant2.principal));
@@ -20275,6 +21019,7 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
20275
21019
  this.publicKey = publicKey;
20276
21020
  this.nodeGrants = nodeGrants;
20277
21021
  }
21022
+ permitReads = /* @__PURE__ */ new Map();
20278
21023
  static async open(options) {
20279
21024
  try {
20280
21025
  if (createPublicKey(options.publicKey).asymmetricKeyType !== "ed25519") throw new Error();
@@ -20283,9 +21028,8 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
20283
21028
  }
20284
21029
  const remote = new _RemoteTravelNodeAuthority(options.publicKey, options.grants);
20285
21030
  for (const grant of options.grants) {
20286
- const identity = await grant.client.identity();
21031
+ const identity = await remote.readIdentity(grant.credential);
20287
21032
  if (identity.publicKey !== options.publicKey) throw new Error("TRAVEL_NODE_SIGNER_MISMATCH");
20288
- await remote.authenticate(grant.credential);
20289
21033
  }
20290
21034
  return remote;
20291
21035
  }
@@ -20294,6 +21038,20 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
20294
21038
  if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
20295
21039
  return grant.client;
20296
21040
  }
21041
+ async assertPermit(...args) {
21042
+ await this.assertPermitWithStatus(...args);
21043
+ }
21044
+ assertPermitWithStatus(...[permit, operation]) {
21045
+ const grant = this.nodeGrants.find((value2) => ["tenantId", "companionId", "seatId", "nodeId"].every((field) => permit[field] === value2.principal[field]));
21046
+ if (!grant) return Promise.reject(new Error("TRAVEL_AUTH_DENIED"));
21047
+ const key2 = JSON.stringify([permit, operation]), pending = this.permitReads.get(key2);
21048
+ if (pending) return pending;
21049
+ const read2 = grant.client.assertPermitWithStatus(permit, operation).then((current2) => current2 === void 0 ? this.status(grant.principal) : current2).finally(() => {
21050
+ this.permitReads.delete(key2);
21051
+ });
21052
+ this.permitReads.set(key2, read2);
21053
+ return read2;
21054
+ }
20297
21055
  async handoffStatus(principal, id2) {
20298
21056
  return this.client(principal).handoffStatus(id2);
20299
21057
  }
@@ -20358,9 +21116,12 @@ var TravelReportClient = class {
20358
21116
  this.timeout = options.timeoutMs ?? 8e3;
20359
21117
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
20360
21118
  this.key = options.key ? Buffer.from(options.key) : void 0;
20361
- 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 });
20362
21122
  }
20363
21123
  agent;
21124
+ mutationAgent;
20364
21125
  key;
20365
21126
  url;
20366
21127
  timeout;
@@ -20387,7 +21148,7 @@ var TravelReportClient = class {
20387
21148
  if (error) reject(error);
20388
21149
  else resolve30(value2);
20389
21150
  };
20390
- 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: {
20391
21152
  Authorization: "Bearer " + this.options.credential,
20392
21153
  "X-Engine7-Travel-Node": this.options.nodeId,
20393
21154
  "Content-Type": "application/json",
@@ -20462,6 +21223,7 @@ var TravelReportClient = class {
20462
21223
  this.closed = true;
20463
21224
  for (const req of this.pending) req.destroy();
20464
21225
  this.agent.destroy();
21226
+ this.mutationAgent.destroy();
20465
21227
  this.key?.fill(0);
20466
21228
  }
20467
21229
  };
@@ -20488,6 +21250,9 @@ var TravelManagementClient = class extends TravelReportClient {
20488
21250
  if (url.pathname !== "/travel/manage/v1") throw new Error("TRAVEL_MANAGEMENT_ENDPOINT_REQUIRED");
20489
21251
  super(options);
20490
21252
  }
21253
+ async bindInitialCheckpoint(digest7, buildManifestId) {
21254
+ await this.call({ action: "bindInitialCheckpoint", digest: digest7, buildManifestId });
21255
+ }
20491
21256
  async verifyAncestor(ancestor, descendant) {
20492
21257
  await this.call({ action: "verifyAncestor", ancestor, descendant });
20493
21258
  }
@@ -20509,6 +21274,9 @@ var TravelManagementClient = class extends TravelReportClient {
20509
21274
  async assertPermit(permit, operation) {
20510
21275
  await this.call({ action: "assertPermit", permit, operation });
20511
21276
  }
21277
+ async assertPermitWithStatus(permit, operation) {
21278
+ return (await this.call({ action: "assertPermit", permit, operation })).status;
21279
+ }
20512
21280
  async acquire(ready) {
20513
21281
  return (await this.call({ action: "acquire", ready })).permit;
20514
21282
  }
@@ -20559,8 +21327,8 @@ var publicErrors2 = /* @__PURE__ */ new Set([
20559
21327
  "TRAVEL_GATEWAY_DELETION_BARRIER"
20560
21328
  ]);
20561
21329
  function encodeInput(input) {
20562
- const { body, ...metadata3 } = input;
20563
- return { ...metadata3, bodyBase64: body.toString("base64") };
21330
+ const { body, ...metadata4 } = input;
21331
+ return { ...metadata4, bodyBase64: body.toString("base64") };
20564
21332
  }
20565
21333
  function decodeBody(value2, maximum = 16 * 1024 * 1024) {
20566
21334
  if (typeof value2 !== "string" || value2.length > Math.ceil(maximum / 3) * 4) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
@@ -20650,8 +21418,8 @@ var TravelGatewayClient = class {
20650
21418
  if (!Array.isArray(result) || result.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_RESPONSE");
20651
21419
  return result.map((item) => {
20652
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");
20653
- const { bodyBase64, ...metadata3 } = item;
20654
- return { ...metadata3, body: decodeBody(bodyBase64) };
21421
+ const { bodyBase64, ...metadata4 } = item;
21422
+ return { ...metadata4, body: decodeBody(bodyBase64) };
20655
21423
  });
20656
21424
  }
20657
21425
  async ack(permit, eventId2) {
@@ -20712,6 +21480,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
20712
21480
  "TRAVEL_NODE_CANCELLED",
20713
21481
  "TRAVEL_NODE_BOOT_MISMATCH",
20714
21482
  "TRAVEL_NODE_CHECKPOINT",
21483
+ "TRAVEL_NODE_COMMON_CHECKPOINT",
20715
21484
  "TRAVEL_NODE_GENERATION_COLLISION",
20716
21485
  "TRAVEL_NODE_KEY_UNAVAILABLE",
20717
21486
  "TRAVEL_NODE_KEY_BARRIER",
@@ -20745,7 +21514,8 @@ var fields2 = {
20745
21514
  replicaProfile: [],
20746
21515
  bootstrapReplica: ["request"],
20747
21516
  connectReplica: ["profile"],
20748
- recoverBranches: []
21517
+ recoverBranches: [],
21518
+ synchronize: []
20749
21519
  };
20750
21520
  function exact(value2, allowed, required = allowed) {
20751
21521
  return Object.keys(value2).every((key2) => allowed.includes(key2)) && required.every((key2) => Object.hasOwn(value2, key2));
@@ -20802,31 +21572,53 @@ var RemoteTravelNodeSupervisor = class {
20802
21572
  observeQuery;
20803
21573
  permitQuery;
20804
21574
  closed = false;
20805
- call(action, args = {}, discover = false) {
21575
+ call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
20806
21576
  if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
20807
21577
  const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
20808
21578
  if ([...this.pending.values()].includes(slot)) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
20809
- 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 } }));
20810
21580
  if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
20811
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());
20812
21585
  return new Promise((resolve30, reject) => {
21586
+ const started = performance.now();
21587
+ let responseStarted = false, receivedBytes = 0, reported = false;
21588
+ const lost = (code) => {
21589
+ if (!reported && slot !== "observe") process.stderr.write("[travel-node-client] " + JSON.stringify({
21590
+ at: Date.now(),
21591
+ action,
21592
+ nodeId: this.principal.nodeId,
21593
+ phase: responseStarted ? "response" : "request",
21594
+ elapsedMs: Math.round(performance.now() - started),
21595
+ receivedBytes,
21596
+ reusedSocket: req.reusedSocket,
21597
+ code: typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : "OTHER"
21598
+ }) + "\n");
21599
+ reported = true;
21600
+ reject(unavailable());
21601
+ };
20813
21602
  const req = request6(this.url, { method: "POST", agent: this.agents[slot], headers: {
20814
21603
  Authorization: "Bearer " + this.options.credential,
20815
21604
  "X-Engine7-Travel-Node": this.principal.nodeId,
20816
21605
  "Content-Type": "application/json",
20817
21606
  "Content-Length": body.length
20818
21607
  } }, (res) => {
21608
+ responseStarted = true;
20819
21609
  const parts = [];
20820
21610
  let bytes = 0;
20821
21611
  res.on("data", (part) => {
20822
21612
  bytes += part.length;
21613
+ receivedBytes = bytes;
20823
21614
  if (bytes > nodeSupervisorLimit) {
20824
21615
  req.destroy();
20825
21616
  reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
20826
21617
  } else parts.push(part);
20827
21618
  });
20828
- res.once("error", () => reject(unavailable()));
21619
+ res.once("error", (error) => lost(error.code));
20829
21620
  res.once("end", () => {
21621
+ reported = true;
20830
21622
  cleanup();
20831
21623
  if (this.closed) {
20832
21624
  reject(unavailable());
@@ -20854,16 +21646,19 @@ var RemoteTravelNodeSupervisor = class {
20854
21646
  });
20855
21647
  this.pending.set(req, slot);
20856
21648
  const timer = setTimeout(() => {
21649
+ lost("TIMEOUT");
20857
21650
  req.destroy();
20858
- reject(unavailable());
20859
- }, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
21651
+ }, remaining);
20860
21652
  const cleanup = () => {
20861
21653
  clearTimeout(timer);
20862
21654
  this.pending.delete(req);
20863
21655
  };
20864
- req.once("error", () => {
21656
+ req.once("error", (error) => {
20865
21657
  cleanup();
20866
- reject(unavailable());
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);
20867
21662
  });
20868
21663
  req.once("close", cleanup);
20869
21664
  req.end(body);
@@ -20933,6 +21728,9 @@ var RemoteTravelNodeSupervisor = class {
20933
21728
  recoverBranches() {
20934
21729
  return this.invoke("recoverBranches");
20935
21730
  }
21731
+ synchronize() {
21732
+ return this.invoke("synchronize");
21733
+ }
20936
21734
  close() {
20937
21735
  if (this.closed) return;
20938
21736
  this.closed = true;
@@ -21057,6 +21855,10 @@ function createTravelNodeSupervisorServer(options) {
21057
21855
  if (!node.recoverBranches) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
21058
21856
  result = await node.recoverBranches();
21059
21857
  break;
21858
+ case "synchronize":
21859
+ if (!node.synchronize) throw new Error("TRAVEL_NODE_REPLICATION_PEER");
21860
+ result = await node.synchronize();
21861
+ break;
21060
21862
  }
21061
21863
  const body = JSON.stringify({ node: { version: 1, nodeId: node.principal.nodeId, bootId: bootId2, result: result ?? null } });
21062
21864
  if (Buffer.byteLength(body) > nodeSupervisorLimit) throw new Error("TRAVEL_NODE_RESPONSE_LIMIT");
@@ -21091,7 +21893,7 @@ var path2 = (value2) => {
21091
21893
  if (typeof value2 !== "string" || !isAbsolute10(value2) || resolve29(value2) !== value2) throw new Error("TRAVEL_NODE_PATH");
21092
21894
  return value2;
21093
21895
  };
21094
- 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) });
21095
21897
  async function startTravelNodeService(input) {
21096
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");
21097
21899
  const config = input;
@@ -21182,6 +21984,7 @@ async function startTravelNodeService(input) {
21182
21984
  environmentNames: config.environmentNames,
21183
21985
  heartbeatIntervalMs: config.heartbeatIntervalMs,
21184
21986
  processTimeoutMs: config.processTimeoutMs,
21987
+ dataProcessTimeoutMs: config.dataProcessTimeoutMs,
21185
21988
  dataIntervalMs: config.dataIntervalMs,
21186
21989
  keyRefreshIntervalMs: config.keyRefreshIntervalMs,
21187
21990
  keyMaxAgeMs: config.keyMaxAgeMs,
@@ -21194,7 +21997,7 @@ async function startTravelNodeService(input) {
21194
21997
  const profile = normalizePublicationProfile(config.initialReplica.profile), databases = {}, replicas = {};
21195
21998
  if (JSON.stringify(Object.keys(config.initialReplica.databases).sort()) !== JSON.stringify(profile.databaseIds)) throw new Error("TRAVEL_NODE_REPLICA_NOT_READY");
21196
21999
  for (const id2 of profile.databaseIds) {
21197
- const file = path2(config.initialReplica.databases[id2]), stat = lstatSync27(file);
22000
+ const file = path2(config.initialReplica.databases[id2]), stat = lstatSync26(file);
21198
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");
21199
22002
  const db = new DatabaseSync30(file, { allowExtension: id2 === "legacy" });
21200
22003
  replicaHandles.push(db);
@@ -21243,7 +22046,7 @@ async function runTravelNodeCli(args) {
21243
22046
  process.once("SIGINT", stop);
21244
22047
  return service.status();
21245
22048
  }
21246
- if (process.argv[1] && resolve29(process.argv[1]) === fileURLToPath2(import.meta.url)) {
22049
+ if (process.argv[1] && /[\\/](node-main\.ts|travel-node\.mjs)$/.test(process.argv[1]) && resolve29(process.argv[1]) === fileURLToPath2(import.meta.url)) {
21247
22050
  runTravelNodeCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch((error) => {
21248
22051
  const reason = error instanceof Error ? /^(?:TRAVEL|RECOVERY|RUNTIME|PUBLICATION|REPLICATION|KEY_SERVICE)_[A-Z_]+/.exec(error.message)?.[0] : void 0;
21249
22052
  process.stderr.write((reason ?? "TRAVEL_NODE_REFUSED") + "\n");