engine7 7.1.138 → 7.1.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -189,7 +189,7 @@ var init_legacy_sqlite_indexes = __esm({
189
189
 
190
190
  // src/continuity/runtime-authority.ts
191
191
  import { randomUUID as randomUUID2, verify } from "node:crypto";
192
- import { constants as constants5, closeSync as closeSync4, existsSync, fstatSync as fstatSync3, fsyncSync as fsyncSync4, lstatSync as lstatSync5, mkdirSync as mkdirSync4, openSync as openSync5, readFileSync as readFileSync3, renameSync, writeFileSync as writeFileSync3 } from "node:fs";
192
+ import { constants as constants5, closeSync as closeSync4, existsSync, fstatSync as fstatSync3, fsyncSync as fsyncSync4, lstatSync as lstatSync5, mkdirSync as mkdirSync4, openSync as openSync5, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
193
193
  import { basename, dirname as dirname3, join as join5, resolve as resolve5 } from "node:path";
194
194
  function assertPrivateDirectory2(path3) {
195
195
  const stat = lstatSync5(path3);
@@ -201,14 +201,14 @@ function readPrivateFile2(path3, maximum) {
201
201
  const fd = openSync5(path3, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0));
202
202
  try {
203
203
  if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
204
- return readFileSync3(fd);
204
+ return readFileSync2(fd);
205
205
  } finally {
206
206
  closeSync4(fd);
207
207
  }
208
208
  }
209
209
  function writeControl(path3, value2) {
210
210
  const temporary = path3 + "." + randomUUID2() + ".tmp";
211
- writeFileSync3(temporary, JSON.stringify(value2), { mode: 384, flag: "wx", flush: true });
211
+ writeFileSync2(temporary, JSON.stringify(value2), { mode: 384, flag: "wx", flush: true });
212
212
  renameSync(temporary, path3);
213
213
  if (process.platform !== "win32") {
214
214
  const fd = openSync5(dirname3(path3), "r");
@@ -279,9 +279,9 @@ var init_runtime_authority = __esm({
279
279
  mkdirSync4(this.directory, { mode: 448, recursive: true });
280
280
  assertPrivateDirectory2(this.directory);
281
281
  const file = join5(this.directory, "travel-runtime.json");
282
- if (!existsSync(file)) writeFileSync3(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
282
+ if (!existsSync(file)) writeFileSync2(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
283
283
  const marker = join5(this.stateDir, ".travel-enrolled.json");
284
- if (!existsSync(marker)) writeFileSync3(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
284
+ if (!existsSync(marker)) writeFileSync2(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
285
285
  }
286
286
  this.checkEnrollment();
287
287
  this.previous = runtimes.get(this.stateDir);
@@ -807,7 +807,8 @@ var init_sqlite_replication = __esm({
807
807
  this.derived = inspectLegacySQLiteIndexes(db);
808
808
  this.tables = inspectTables(db, this.derived?.excludedTables);
809
809
  if (sqliteReplicationSchemaHash(db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
810
- if (db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("REPLICATION_INVALID_BASELINE: foreign key");
810
+ const initialized = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get() && db.prepare("SELECT 1 FROM e7_replication_control WHERE role='replica'").get());
811
+ if (!initialized && db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("REPLICATION_INVALID_BASELINE: foreign key");
811
812
  const allowed = new Set(options.suppressTriggers ?? []);
812
813
  if ([...allowed].some((name) => name.startsWith("writer_guard_"))) throw new Error("REPLICATION_WRITER_GUARD_MUST_REMAIN");
813
814
  this.triggers = schemaRows(db).filter((r) => r.type === "trigger" && !r.name.startsWith("writer_guard_"));
@@ -815,7 +816,6 @@ var init_sqlite_replication = __esm({
815
816
  throw new Error("REPLICATION_UNCLASSIFIED_TRIGGER");
816
817
  this.automaticTables = new Set(schemaRows(db).filter((r) => this.tables.has(r.name) && r.type === "table" && /\bAUTOINCREMENT\b/i.test(r.sql)).map((r) => r.name));
817
818
  db.function("engine7_replication_capture_active", () => this.applying ? 1 : 0);
818
- const initialized = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get() && db.prepare("SELECT 1 FROM e7_replication_control WHERE role='replica'").get());
819
819
  db.exec("BEGIN IMMEDIATE");
820
820
  try {
821
821
  if (!initialized) this.derived?.rebuild();
@@ -960,7 +960,7 @@ var init_sqlite_replication = __esm({
960
960
  });
961
961
 
962
962
  // src/continuity/runtime-replication.ts
963
- import { constants as constants7, lstatSync as lstatSync7, realpathSync as realpathSync3, mkdirSync as mkdirSync5, openSync as openSync7, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5, fsyncSync as fsyncSync6 } from "node:fs";
963
+ import { constants as constants7, lstatSync as lstatSync7, realpathSync as realpathSync3, mkdirSync as mkdirSync5, openSync as openSync7, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync4, fsyncSync as fsyncSync6 } from "node:fs";
964
964
  import { basename as basename2, dirname as dirname5, join as join7, resolve as resolve6 } from "node:path";
965
965
  function checkKey(component, key2) {
966
966
  if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
@@ -1016,7 +1016,7 @@ function readRuntimeReplicationRegistration(stateDir, component, key2) {
1016
1016
  try {
1017
1017
  const info = fstatSync4(fd);
1018
1018
  if (!info.isFile() || info.size > 4096 || realpathSync3(file) !== resolve6(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
1019
- return normalize2(JSON.parse(readFileSync4(fd, "utf8")));
1019
+ return normalize2(JSON.parse(readFileSync3(fd, "utf8")));
1020
1020
  } catch (error) {
1021
1021
  throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
1022
1022
  } finally {
@@ -1072,7 +1072,7 @@ function enrollRuntimeReplication(db, stateDir, component, binding, key2) {
1072
1072
  mkdirSync5(dirname5(file), { mode: 448, recursive: true });
1073
1073
  directory(dirname5(file));
1074
1074
  try {
1075
- writeFileSync5(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1075
+ writeFileSync4(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1076
1076
  } catch (error) {
1077
1077
  if (error.code !== "EEXIST") throw error;
1078
1078
  if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
@@ -1099,7 +1099,7 @@ var init_runtime_replication = __esm({
1099
1099
  // src/continuity/runtime-lock.ts
1100
1100
  import { randomUUID as randomUUID3 } from "node:crypto";
1101
1101
  import { AsyncLocalStorage } from "node:async_hooks";
1102
- import { closeSync as closeSync7, lstatSync as lstatSync8, mkdirSync as mkdirSync6, openSync as openSync8, readFileSync as readFileSync5, realpathSync as realpathSync4 } from "node:fs";
1102
+ import { closeSync as closeSync7, lstatSync as lstatSync8, mkdirSync as mkdirSync6, openSync as openSync8, readFileSync as readFileSync4, realpathSync as realpathSync4 } from "node:fs";
1103
1103
  import { join as join8 } from "node:path";
1104
1104
  import { createRequire as createRequire4 } from "node:module";
1105
1105
  function openSQLite(file, options = {}) {
@@ -1230,7 +1230,7 @@ async function withCheckpointLock(stateDir, operation) {
1230
1230
  for (const name of [".engine.pid", ".bg-worker.pid"]) {
1231
1231
  let value2;
1232
1232
  try {
1233
- value2 = readFileSync5(join8(stateDir, name), "utf8").trim();
1233
+ value2 = readFileSync4(join8(stateDir, name), "utf8").trim();
1234
1234
  } catch (error) {
1235
1235
  if (error.code === "ENOENT") continue;
1236
1236
  throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
@@ -1629,7 +1629,7 @@ var init_timing = __esm({
1629
1629
 
1630
1630
  // src/continuity/publication-main.ts
1631
1631
  import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
1632
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync16, lstatSync as lstatSync19, realpathSync as realpathSync14 } from "node:fs";
1632
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync15, lstatSync as lstatSync19, realpathSync as realpathSync14 } from "node:fs";
1633
1633
  import { isAbsolute as isAbsolute5, resolve as resolve22, join as join23, dirname as dirname13 } from "node:path";
1634
1634
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1635
1635
  import { X509Certificate } from "node:crypto";
@@ -1663,21 +1663,19 @@ import {
1663
1663
  fstatSync as fstatSync2,
1664
1664
  fsyncSync as fsyncSync2,
1665
1665
  readSync,
1666
- writeSync as writeSync2,
1667
1666
  lstatSync as lstatSync2,
1668
1667
  realpathSync,
1669
- mkdirSync as mkdirSync2,
1670
- readFileSync as readFileSync2,
1671
- writeFileSync,
1672
- linkSync,
1673
- unlinkSync as unlinkSync2
1668
+ mkdirSync as mkdirSync2
1674
1669
  } from "node:fs";
1670
+ import { open, writeFile, link, unlink } from "node:fs/promises";
1675
1671
  import { join, dirname, resolve } from "node:path";
1676
1672
  import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
1673
+ import { setImmediate } from "node:timers/promises";
1677
1674
  var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
1678
1675
  var HASH = /^[a-f0-9]{64}$/;
1679
1676
  var OVERHEAD = 32;
1680
1677
  var MAGIC = Buffer.from("E7P1");
1678
+ var INLINE_BYTES = 64 * 1024;
1681
1679
  var sha = (body) => createHash("sha256").update(body).digest("hex");
1682
1680
  var noFollow = constants2.O_NOFOLLOW ?? 0;
1683
1681
  function validateObjectRef(ref) {
@@ -1753,15 +1751,24 @@ function preparePrivateDatabase(path3) {
1753
1751
  throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
1754
1752
  syncDir(dirname(path3));
1755
1753
  }
1756
- function exclusivePublish(path3, body) {
1754
+ async function syncDirAsync(path3) {
1755
+ if (process.platform === "win32") return;
1756
+ const fd = await open(path3, constants2.O_RDONLY);
1757
+ try {
1758
+ await fd.sync();
1759
+ } finally {
1760
+ await fd.close();
1761
+ }
1762
+ }
1763
+ async function exclusivePublish(path3, body, deferDirectorySync = false) {
1757
1764
  const temp = join(dirname(path3), "." + randomUUID() + ".partial");
1758
1765
  try {
1759
- writeFileSync(temp, body, { flag: "wx", mode: 384, flush: true });
1760
- linkSync(temp, path3);
1761
- syncDir(dirname(path3));
1766
+ await writeFile(temp, body, { flag: "wx", mode: 384, flush: true });
1767
+ await link(temp, path3);
1768
+ if (!deferDirectorySync) await syncDirAsync(dirname(path3));
1762
1769
  } finally {
1763
1770
  try {
1764
- unlinkSync2(temp);
1771
+ await unlink(temp);
1765
1772
  } catch (error) {
1766
1773
  if (error.code !== "ENOENT") throw error;
1767
1774
  }
@@ -1774,6 +1781,7 @@ var PublicationObjects = class _PublicationObjects {
1774
1781
  key;
1775
1782
  maximumBytes;
1776
1783
  closed = false;
1784
+ inlineReads = 0;
1777
1785
  constructor(options) {
1778
1786
  if (!(options.key instanceof Uint8Array) || options.key.length !== 32) throw new Error("PUBLICATION_INVALID_KEY");
1779
1787
  if (!options.identity || ["tenantId", "companionId", "seatId"].some((k) => typeof options.identity[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.identity[k])))
@@ -1792,7 +1800,7 @@ var PublicationObjects = class _PublicationObjects {
1792
1800
  this.db = new DatabaseSync2(file);
1793
1801
  this.db.exec(`PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
1794
1802
  CREATE TABLE IF NOT EXISTS identity (id INTEGER PRIMARY KEY CHECK(id=1), verifier BLOB NOT NULL);
1795
- CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0));`);
1803
+ CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0),ciphertext BLOB);`);
1796
1804
  this.db.exec("BEGIN IMMEDIATE");
1797
1805
  try {
1798
1806
  const row = this.db.prepare("SELECT verifier FROM identity WHERE id=1").get();
@@ -1803,6 +1811,13 @@ var PublicationObjects = class _PublicationObjects {
1803
1811
  throw new Error("PUBLICATION_KEY_OR_IDENTITY_MISMATCH");
1804
1812
  }
1805
1813
  } else this.db.prepare("INSERT INTO identity VALUES(1,?)").run(this.encrypt(Buffer.from("publication-object-key"), "identity"));
1814
+ if (!this.db.prepare("PRAGMA table_info(objects)").all().some((column) => column.name === "ciphertext"))
1815
+ this.db.exec("ALTER TABLE objects ADD COLUMN ciphertext BLOB");
1816
+ this.db.exec(`CREATE TABLE IF NOT EXISTS object_usage (id INTEGER PRIMARY KEY CHECK(id=1),objects INTEGER NOT NULL,bytes INTEGER NOT NULL);
1817
+ INSERT OR IGNORE INTO object_usage SELECT 1,count(*),coalesce(sum(bytes+32),0) FROM objects;
1818
+ CREATE TRIGGER IF NOT EXISTS objects_usage_insert AFTER INSERT ON objects BEGIN UPDATE object_usage SET objects=objects+1,bytes=bytes+NEW.bytes+32 WHERE id=1; END;
1819
+ CREATE TRIGGER IF NOT EXISTS objects_usage_delete AFTER DELETE ON objects BEGIN UPDATE object_usage SET objects=objects-1,bytes=bytes-OLD.bytes-32 WHERE id=1; END;
1820
+ CREATE TRIGGER IF NOT EXISTS objects_usage_resize AFTER UPDATE OF bytes ON objects BEGIN UPDATE object_usage SET bytes=bytes+NEW.bytes-OLD.bytes WHERE id=1; END;`);
1806
1821
  this.db.exec("COMMIT");
1807
1822
  syncDir(this.directory);
1808
1823
  } catch (error) {
@@ -1842,54 +1857,135 @@ var PublicationObjects = class _PublicationObjects {
1842
1857
  }
1843
1858
  usage() {
1844
1859
  this.active();
1845
- return this.db.prepare("SELECT count(*) objects,COALESCE(sum(bytes+32),0) bytes FROM objects").get();
1860
+ return this.db.prepare("SELECT objects,bytes FROM object_usage WHERE id=1").get();
1846
1861
  }
1847
- async put(body) {
1848
- this.active();
1849
- assertPrivateDirectory(this.directory);
1850
- assertPrivateDirectory(join(this.directory, "chunks"));
1851
- if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
1852
- throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
1853
- body = Buffer.from(body);
1854
- const ref = { sha256: sha(body), bytes: body.byteLength };
1862
+ reserve(refs) {
1855
1863
  this.db.exec("BEGIN IMMEDIATE");
1856
1864
  try {
1857
- const row = this.db.prepare("SELECT bytes FROM objects WHERE hash=?").get(ref.sha256);
1858
- if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1859
- if (!row) {
1860
- if (this.usage().bytes + ref.bytes + OVERHEAD > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
1861
- this.db.prepare("INSERT INTO objects VALUES(?,?)").run(ref.sha256, ref.bytes);
1865
+ let used = this.usage().bytes;
1866
+ const lookup = this.db.prepare("SELECT bytes FROM objects WHERE hash=?");
1867
+ const insert = this.db.prepare("INSERT INTO objects(hash,bytes) VALUES(?,?)");
1868
+ for (const ref of refs) {
1869
+ const row = lookup.get(ref.sha256);
1870
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1871
+ if (!row) {
1872
+ used += ref.bytes + OVERHEAD;
1873
+ if (used > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
1874
+ insert.run(ref.sha256, ref.bytes);
1875
+ }
1862
1876
  }
1863
1877
  this.db.exec("COMMIT");
1864
1878
  } catch (error) {
1865
1879
  this.db.exec("ROLLBACK");
1866
1880
  throw error;
1867
1881
  }
1868
- if (await this.has(ref)) return ref;
1882
+ }
1883
+ async put(body) {
1884
+ return this.putObject(body, false);
1885
+ }
1886
+ async putObject(body, deferDirectorySync) {
1887
+ this.active();
1888
+ assertPrivateDirectory(this.directory);
1889
+ assertPrivateDirectory(join(this.directory, "chunks"));
1890
+ if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
1891
+ throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
1892
+ body = Buffer.from(body);
1893
+ const ref = { sha256: sha(body), bytes: body.byteLength };
1894
+ this.reserve([ref]);
1895
+ await this.writeObject(ref, Buffer.from(body), deferDirectorySync);
1896
+ return ref;
1897
+ }
1898
+ async writeObject(ref, body, deferDirectorySync) {
1899
+ if (await this.has(ref)) return;
1869
1900
  try {
1870
- exclusivePublish(join(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256));
1901
+ await exclusivePublish(join(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256), deferDirectorySync);
1871
1902
  } catch (error) {
1872
1903
  if (error.code !== "EEXIST") throw error;
1873
1904
  }
1874
1905
  await this.read(ref);
1875
- return ref;
1906
+ }
1907
+ /** Same immutable chunk format and row digests, with one durable reservation
1908
+ * and directory barrier for a bounded batch. All started writes settle even
1909
+ * when one fails, so callers can safely close or retry the store. */
1910
+ async putContents(bodies) {
1911
+ return this.putContentsWith(bodies, false);
1912
+ }
1913
+ async putContentsWith(bodies, deferDirectorySync) {
1914
+ this.active();
1915
+ assertPrivateDirectory(this.directory);
1916
+ assertPrivateDirectory(join(this.directory, "chunks"));
1917
+ if (!Array.isArray(bodies) || bodies.length > 128 || bodies.some((body) => !(body instanceof Uint8Array)) || bodies.reduce((sum, body) => sum + body.byteLength, 0) > 8 * 1024 * 1024) throw new Error("PUBLICATION_BATCH_TOO_LARGE");
1918
+ const owned2 = bodies.map((body) => Buffer.from(body)), writes = /* @__PURE__ */ new Map();
1919
+ const files = owned2.map((body) => {
1920
+ const chunks = [];
1921
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
1922
+ const chunk = body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES), ref = { sha256: sha(chunk), bytes: chunk.length };
1923
+ chunks.push(ref);
1924
+ writes.set(ref.sha256, { ref, body: chunk });
1925
+ }
1926
+ return { sha256: sha(body), bytes: body.length, chunks };
1927
+ });
1928
+ const pending = [...writes.values()];
1929
+ if (!pending.length) return files;
1930
+ this.reserve(pending.map((item) => item.ref));
1931
+ const checked = await Promise.allSettled(pending.map(async (item) => ({ item, present: await this.has(item.ref) })));
1932
+ for (const result of checked) if (result.status === "rejected") throw result.reason;
1933
+ const missing = checked.flatMap((result) => result.status === "fulfilled" && !result.value.present ? [result.value.item] : []);
1934
+ const inline = missing.filter((item) => item.ref.bytes <= INLINE_BYTES), large = missing.filter((item) => item.ref.bytes > INLINE_BYTES);
1935
+ if (inline.length) {
1936
+ this.db.exec("BEGIN IMMEDIATE");
1937
+ try {
1938
+ const insert = this.db.prepare("UPDATE objects SET ciphertext=? WHERE hash=? AND ciphertext IS NULL");
1939
+ for (const item of inline) insert.run(this.encrypt(item.body, item.ref.sha256), item.ref.sha256);
1940
+ this.db.exec("COMMIT");
1941
+ } catch (error) {
1942
+ this.db.exec("ROLLBACK");
1943
+ throw error;
1944
+ }
1945
+ for (const item of inline) await this.read(item.ref);
1946
+ }
1947
+ try {
1948
+ for (let offset = 0; offset < large.length; offset += 8) {
1949
+ const results = await Promise.allSettled(large.slice(offset, offset + 8).map((item) => this.writeObject(item.ref, item.body, true)));
1950
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1951
+ }
1952
+ } finally {
1953
+ if (large.length && !deferDirectorySync) await syncDirAsync(join(this.directory, "chunks"));
1954
+ }
1955
+ return files;
1876
1956
  }
1877
1957
  async read(ref) {
1878
1958
  this.active();
1879
1959
  validateObjectRef(ref);
1960
+ if (++this.inlineReads >= 32) {
1961
+ this.inlineReads = 0;
1962
+ await setImmediate();
1963
+ this.active();
1964
+ }
1880
1965
  assertPrivateDirectory(this.directory);
1881
1966
  assertPrivateDirectory(join(this.directory, "chunks"));
1967
+ const row = this.db.prepare("SELECT bytes,ciphertext FROM objects WHERE hash=?").get(ref.sha256);
1968
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1969
+ if (row?.ciphertext !== void 0 && row.ciphertext !== null) {
1970
+ const cipher = Buffer.from(row.ciphertext);
1971
+ if (cipher.length !== ref.bytes + OVERHEAD) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1972
+ const plain = this.decrypt(cipher, ref.sha256);
1973
+ if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1974
+ return plain;
1975
+ }
1882
1976
  const path3 = join(this.directory, "chunks", ref.sha256);
1883
- const fd = openSync2(path3, constants2.O_RDONLY | noFollow);
1977
+ const file = await open(path3, constants2.O_RDONLY | noFollow);
1884
1978
  try {
1885
- const info = fstatSync2(fd);
1979
+ const info = await file.stat();
1886
1980
  if (!info.isFile() || info.size !== ref.bytes + OVERHEAD || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1887
1981
  throw new Error("PUBLICATION_OBJECT_CORRUPT");
1888
- const plain = this.decrypt(readFileSync2(fd), ref.sha256);
1982
+ const cipher = await file.readFile();
1983
+ this.active();
1984
+ const plain = this.decrypt(cipher, ref.sha256);
1889
1985
  if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1890
1986
  return plain;
1891
1987
  } finally {
1892
- closeSync2(fd);
1988
+ await file.close();
1893
1989
  }
1894
1990
  }
1895
1991
  async has(ref) {
@@ -1904,7 +2000,10 @@ var PublicationObjects = class _PublicationObjects {
1904
2000
  async putContent(body) {
1905
2001
  body = Buffer.from(body);
1906
2002
  const chunks = [];
1907
- for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
2003
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
2004
+ chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
2005
+ if (chunks.length % 32 === 0) await setImmediate();
2006
+ }
1908
2007
  return { bytes: body.length, sha256: sha(body), chunks };
1909
2008
  }
1910
2009
  async readContent(file, maximumBytes) {
@@ -1917,21 +2016,85 @@ var PublicationObjects = class _PublicationObjects {
1917
2016
  return body;
1918
2017
  }
1919
2018
  async captureFile(source) {
2019
+ return this.captureFileWith(source, (body) => this.put(body));
2020
+ }
2021
+ /** Every file is flushed before linking. One directory barrier makes the
2022
+ * whole batch durable before any references are returned to its caller.
2023
+ * Other puts on this handle retain their own immediate directory barrier. */
2024
+ async captureFiles(sources, onProgress, options = {}) {
2025
+ this.active();
2026
+ const chunkConcurrency = options.chunkConcurrency ?? 1;
2027
+ if (!Number.isSafeInteger(chunkConcurrency) || chunkConcurrency < 1 || chunkConcurrency > 8) throw new Error("PUBLICATION_BATCH_TOO_LARGE");
2028
+ const files = [];
2029
+ let completedBytes = 0, completedFiles = 0, wroteFiles = false;
2030
+ let pending = [];
2031
+ const put = (body) => new Promise((resolve23, reject) => {
2032
+ if (body.length > INLINE_BYTES) wroteFiles = true;
2033
+ pending.push({ body: Buffer.from(body), resolve: resolve23, reject });
2034
+ if (pending.length !== 1) return;
2035
+ queueMicrotask(() => {
2036
+ const batch = pending;
2037
+ pending = [];
2038
+ void (async () => {
2039
+ for (let offset = 0; offset < batch.length; ) {
2040
+ let end = offset, bytes = 0;
2041
+ while (end < batch.length && bytes + batch[end].body.length <= 8 * 1024 * 1024) bytes += batch[end++].body.length;
2042
+ const contents = await this.putContentsWith(batch.slice(offset, end).map((item) => item.body), true);
2043
+ for (let i = offset; i < end; i++) batch[i].resolve(contents[i - offset].chunks[0]);
2044
+ offset = end;
2045
+ }
2046
+ })().catch((error) => {
2047
+ for (const item of batch) item.reject(error);
2048
+ });
2049
+ });
2050
+ });
2051
+ try {
2052
+ for (let offset = 0; offset < sources.length; offset += 32) {
2053
+ const results = await Promise.allSettled(sources.slice(offset, offset + 32).map(async (source) => {
2054
+ let previousBytes = 0;
2055
+ const file = await this.captureFileWith(source, put, (bytes) => {
2056
+ completedBytes += bytes - previousBytes;
2057
+ previousBytes = bytes;
2058
+ onProgress?.({ completedFiles, completedBytes });
2059
+ }, chunkConcurrency);
2060
+ completedFiles++;
2061
+ if (completedFiles < sources.length) onProgress?.({ completedFiles, completedBytes });
2062
+ return file;
2063
+ }));
2064
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2065
+ for (const result of results) if (result.status === "fulfilled") files.push(result.value);
2066
+ }
2067
+ } finally {
2068
+ if (wroteFiles) await syncDirAsync(join(this.directory, "chunks"));
2069
+ }
2070
+ onProgress?.({ completedFiles: files.length, completedBytes });
2071
+ return files;
2072
+ }
2073
+ async captureFileWith(source, put, onBytes, chunkConcurrency = 1) {
1920
2074
  this.active();
1921
2075
  if (lstatSync2(source).isSymbolicLink() || realpathSync(dirname(source)) !== resolve(dirname(source))) throw new Error("SYMLINK_REFUSED");
1922
2076
  const fd = openSync2(source, constants2.O_RDONLY | noFollow);
1923
2077
  try {
1924
2078
  const before = fstatSync2(fd, { bigint: true });
1925
2079
  if (!before.isFile()) throw new Error("PUBLICATION_NOT_REGULAR_FILE");
1926
- const chunks = [], digest3 = createHash("sha256"), buffer = Buffer.alloc(PUBLICATION_CHUNK_BYTES);
2080
+ const chunks = [], digest3 = createHash("sha256"), buffer = Buffer.alloc(Math.min(PUBLICATION_CHUNK_BYTES, Number(before.size) || 1));
1927
2081
  let bytes = 0;
1928
2082
  for (; ; ) {
1929
- const count = readSync(fd, buffer, 0, buffer.length, null);
1930
- if (!count) break;
1931
- const chunk = buffer.subarray(0, count);
1932
- digest3.update(chunk);
1933
- bytes += count;
1934
- chunks.push(await this.put(chunk));
2083
+ const batch = [];
2084
+ for (let i = 0; i < chunkConcurrency; i++) {
2085
+ const count = readSync(fd, buffer, 0, buffer.length, null);
2086
+ if (!count) break;
2087
+ const chunk = Buffer.from(buffer.subarray(0, count));
2088
+ digest3.update(chunk);
2089
+ bytes += count;
2090
+ batch.push(chunk);
2091
+ }
2092
+ if (!batch.length) break;
2093
+ const results = await Promise.allSettled(batch.map(put));
2094
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2095
+ for (const result of results) if (result.status === "fulfilled") chunks.push(result.value);
2096
+ onBytes?.(bytes);
2097
+ if (chunks.length % 32 === 0) await setImmediate();
1935
2098
  }
1936
2099
  const after = fstatSync2(fd, { bigint: true }), path3 = lstatSync2(source, { bigint: true });
1937
2100
  if (path3.isSymbolicLink() || [after, path3].some((s) => ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((k) => s[k] !== before[k])) || BigInt(bytes) !== before.size) throw new Error("PUBLICATION_SOURCE_CHANGED");
@@ -1941,8 +2104,28 @@ var PublicationObjects = class _PublicationObjects {
1941
2104
  }
1942
2105
  }
1943
2106
  async restoreFile(file, destination) {
2107
+ return this.restoreFileWith(file, destination, false);
2108
+ }
2109
+ /** Private restore batches flush each file before linking it, then publish
2110
+ * the directory entries together. All started writers settle on failure. */
2111
+ async restoreFiles(files) {
2112
+ this.active();
2113
+ for (let offset = 0; offset < files.length; offset += 32) {
2114
+ const batch = files.slice(offset, offset + 32);
2115
+ const results = await Promise.allSettled(batch.map((file) => this.restoreFileWith(file.content, file.destination, true, file.mode)));
2116
+ const directories = [...new Set(batch.map((file) => dirname(file.destination)))];
2117
+ for (let i = 0; i < directories.length; i += 8) {
2118
+ const synced = await Promise.allSettled(directories.slice(i, i + 8).map(syncDirAsync));
2119
+ for (const result of synced) if (result.status === "rejected") throw result.reason;
2120
+ }
2121
+ for (const result of results) if (result.status === "rejected") throw result.reason;
2122
+ }
2123
+ }
2124
+ async restoreFileWith(file, destination, deferDirectorySync, mode = 384) {
1944
2125
  this.active();
1945
2126
  validateFileContent(file);
2127
+ if (mode !== 384 && mode !== 448) throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
2128
+ file = { ...file, chunks: file.chunks.map((ref) => ({ ...ref })) };
1946
2129
  if (realpathSync(dirname(destination)) !== resolve(dirname(destination))) throw new Error("SYMLINK_REFUSED");
1947
2130
  try {
1948
2131
  lstatSync2(destination);
@@ -1951,26 +2134,27 @@ var PublicationObjects = class _PublicationObjects {
1951
2134
  if (error.code !== "ENOENT") throw error;
1952
2135
  }
1953
2136
  const temp = join(dirname(destination), "." + randomUUID() + ".partial"), digest3 = createHash("sha256");
1954
- const fd = openSync2(temp, "wx", 384);
2137
+ const fd = await open(temp, "wx", 384);
1955
2138
  try {
1956
2139
  for (const ref of file.chunks) {
1957
2140
  const body = await this.read(ref);
1958
2141
  digest3.update(body);
1959
2142
  let offset = 0;
1960
- while (offset < body.length) offset += writeSync2(fd, body, offset, body.length - offset);
2143
+ while (offset < body.length) offset += (await fd.write(body, offset, body.length - offset)).bytesWritten;
1961
2144
  }
1962
2145
  if (digest3.digest("hex") !== file.sha256) throw new Error("PUBLICATION_FILE_CORRUPT");
1963
- fsyncSync2(fd);
2146
+ if (mode !== 384) await fd.chmod(mode);
2147
+ await fd.sync();
1964
2148
  try {
1965
- linkSync(temp, destination);
2149
+ await link(temp, destination);
1966
2150
  } catch (error) {
1967
2151
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
1968
2152
  throw error;
1969
2153
  }
1970
- syncDir(dirname(destination));
2154
+ if (!deferDirectorySync) await syncDirAsync(dirname(destination));
1971
2155
  } finally {
1972
- closeSync2(fd);
1973
- unlinkSync2(temp);
2156
+ await fd.close();
2157
+ await unlink(temp);
1974
2158
  }
1975
2159
  }
1976
2160
  close() {
@@ -1986,8 +2170,188 @@ var PublicationObjects = class _PublicationObjects {
1986
2170
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
1987
2171
  import { createHash as createHash2 } from "node:crypto";
1988
2172
  import { lstatSync as lstatSync3 } from "node:fs";
1989
- import { join as join2, resolve as resolve2 } from "node:path";
1990
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
2173
+ import { join as join3, resolve as resolve3 } from "node:path";
2174
+
2175
+ // src/continuity/inventory.ts
2176
+ import { constants as constants3 } from "node:fs";
2177
+ import { lstat, open as open2, readdir, realpath } from "node:fs/promises";
2178
+ import { isAbsolute, join as join2, relative, resolve as resolve2, sep } from "node:path";
2179
+ var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
2180
+ var STATE_EXCLUDED = {
2181
+ ".continuity": "local runtime control; never business state",
2182
+ ".engine.pid": "local process identity",
2183
+ ".bg-worker.pid": "local process identity",
2184
+ ".travel-restored.json": "deployment activation gate; recreated on restore",
2185
+ ".travel-enrolled.json": "local runtime enrollment; recreated per node",
2186
+ ".travel-active.json": "local activation receipt; recreated per generation",
2187
+ ".git": "source control metadata",
2188
+ ".gitignore": "source control metadata",
2189
+ ".log-baseline.txt": "local diagnostics",
2190
+ logs: "local diagnostics; not authoritative history",
2191
+ diagnostics: "local diagnostics",
2192
+ backups: "historical recovery copies; not active state",
2193
+ "package.json": "installed application metadata",
2194
+ "start.sh": "local launcher; deployment must be reviewed separately",
2195
+ node_modules: "installed dependencies",
2196
+ install: "installed application",
2197
+ CogniFold: "installed optional runtime",
2198
+ "everos-venv": "installed Python runtime",
2199
+ "ollama-models": "installed model weights"
2200
+ };
2201
+ var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
2202
+ var WORKSPACE_DIAGNOSTICS = /* @__PURE__ */ new Set([".system-prompt.txt", ".context-debug.txt"]);
2203
+ var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
2204
+ var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
2205
+ var CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
2206
+ function coreReason(path3) {
2207
+ const name = path3.split("/").at(-1);
2208
+ if (CORE_OMITTED.has(name) || /(?:\.lance$|(?:^|[-.])bak(?:[-.]|$))/i.test(name)) return "optional attachments, historical copies or rebuildable indexes; outside core travel";
2209
+ if (/\.(?:mp4|mov|mkv|webm|avi|m4v|mp3|wav|ogg|opus|m4a|aac|flac|png|jpe?g|gif|webp|heic|bmp|tiff?|ico|pdf|docx?|pptx?|xlsx?|zip|gz|tgz|tar|7z|rar|dmg|exe|dll|so|dylib|bin|onnx|safetensors|gguf|vrm|glb|gltf|fbx|ttf|otf|woff2?|pyc|log|out)$/i.test(name) || name === ".DS_Store" || name === "package-lock.json" || name === ".context-debug.txt" || path3 === "mem7/spool/intake.failed.jsonl") return "attachments, installed binaries or diagnostics; outside core travel";
2210
+ }
2211
+ function stateReason(name, options) {
2212
+ if (options.selection === "core" && coreReason(name)) return coreReason(name);
2213
+ if (options.includeStateEntries?.includes(name)) return void 0;
2214
+ return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
2215
+ }
2216
+ function knownState(name) {
2217
+ return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
2218
+ }
2219
+ async function classifyState(options) {
2220
+ const result = { included: [], excluded: [], unclassified: [] };
2221
+ for (const name of (await readdir(options.stateDir)).sort()) {
2222
+ const reason = stateReason(name, options);
2223
+ if (reason) result.excluded.push({ path: name, reason });
2224
+ else if (options.selection === "core" || knownState(name) || options.includeStateEntries?.includes(name) || resolve2(options.stateDir, name) === resolve2(options.workspace ?? join2(options.stateDir, "workspace"))) result.included.push(name);
2225
+ else result.unclassified.push(name);
2226
+ }
2227
+ return result;
2228
+ }
2229
+ function validateRelativePath(path3) {
2230
+ if (typeof path3 !== "string" || !path3 || path3.length > 2048 || isAbsolute(path3)) throw new Error("INVALID_ARTIFACT_PATH");
2231
+ for (const part of path3.split("/")) {
2232
+ if (!part || part === "." || part === ".." || /[\x00-\x1f]/.test(part) || Buffer.byteLength(part) > 255 || process.platform === "win32" && (/[<>:"|?*\\]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part)))
2233
+ throw new Error("INVALID_ARTIFACT_PATH");
2234
+ }
2235
+ }
2236
+ function isWithin(root, candidate) {
2237
+ const rel = relative(resolve2(root), resolve2(candidate));
2238
+ return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2239
+ }
2240
+ async function collectInventory(options) {
2241
+ if (options.selection !== void 0 && options.selection !== "core") throw new Error("INVALID_INVENTORY_SELECTION");
2242
+ const state2 = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join2(state2, "workspace"));
2243
+ if (state2 === workspace || isWithin(workspace, state2)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
2244
+ const roots = { state: state2, workspace }, entries = [], exclusions2 = [], aliases = /* @__PURE__ */ new Set();
2245
+ const include = new Set(options.includeStateEntries ?? []);
2246
+ for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
2247
+ validateRelativePath(name);
2248
+ if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
2249
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2250
+ }
2251
+ for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
2252
+ for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
2253
+ validateRelativePath(name);
2254
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2255
+ if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
2256
+ }
2257
+ const classification = await classifyState(options);
2258
+ if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
2259
+ async function walk(root, directory2, prefix = "", ancestors = /* @__PURE__ */ new Set()) {
2260
+ const canonical3 = await realpath(directory2);
2261
+ if (ancestors.has(canonical3)) throw new Error(`SYMLINK_CYCLE: ${root}/${prefix}`);
2262
+ const parents = new Set(ancestors);
2263
+ parents.add(canonical3);
2264
+ for (const name of (await readdir(directory2)).sort()) {
2265
+ const path3 = prefix ? prefix + "/" + name : name;
2266
+ let source = join2(directory2, name);
2267
+ if (root === "state" && source === workspace) continue;
2268
+ let reason = NESTED_EXCLUDED[name];
2269
+ if (root === "state" && prefix) reason = options.excludeStateEntries?.[path3] ?? reason;
2270
+ if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path3] ?? reason;
2271
+ if (root === "workspace" && !prefix && WORKSPACE_DIAGNOSTICS.has(name)) reason = "generated runtime diagnostics; recreated on each node";
2272
+ if (!prefix && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
2273
+ if (root === "state" && !prefix) {
2274
+ reason = stateReason(name, options);
2275
+ if (!reason && options.selection !== "core" && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
2276
+ }
2277
+ if (options.selection === "core") reason = coreReason(path3) ?? reason;
2278
+ if (reason) {
2279
+ exclusions2.push({ root, path: path3, reason });
2280
+ continue;
2281
+ }
2282
+ validateRelativePath(path3);
2283
+ const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
2284
+ if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
2285
+ aliases.add(key2);
2286
+ let info = await lstat(source, { bigint: true }), linkSignature = "";
2287
+ if (options.selection === "core" && root === "workspace" && !prefix && !CORE_DIRECTORIES.has(name) && (info.isDirectory() || info.isSymbolicLink() && !/\.[a-z0-9]+$/i.test(name))) {
2288
+ exclusions2.push({ root, path: path3, reason: "optional workspace material; outside core travel" });
2289
+ continue;
2290
+ }
2291
+ if (info.isSymbolicLink()) {
2292
+ linkSignature = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":") + ":";
2293
+ try {
2294
+ source = await realpath(source);
2295
+ } catch {
2296
+ throw new Error(`SYMLINK_REFUSED: ${root}/${path3}`);
2297
+ }
2298
+ info = await lstat(source, { bigint: true });
2299
+ linkSignature += source + ":";
2300
+ }
2301
+ if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
2302
+ if (options.selection === "core" && root === "workspace" && !prefix && info.isDirectory() && !CORE_DIRECTORIES.has(name)) {
2303
+ exclusions2.push({ root, path: path3, reason: "optional workspace material; outside core travel" });
2304
+ continue;
2305
+ }
2306
+ if (info.isDirectory()) {
2307
+ try {
2308
+ const marker = await lstat(join2(source, "pyvenv.cfg"));
2309
+ if (marker.isFile() && !marker.isSymbolicLink()) {
2310
+ exclusions2.push({ root, path: path3, reason: "installed Python virtual environment; rebuild for the target platform" });
2311
+ continue;
2312
+ }
2313
+ } catch (error) {
2314
+ if (error.code !== "ENOENT") throw error;
2315
+ }
2316
+ }
2317
+ const entry = {
2318
+ root,
2319
+ path: path3,
2320
+ source,
2321
+ kind: info.isDirectory() ? "directory" : "file",
2322
+ bytes: Number(info.size),
2323
+ mode: Number(info.mode) & 448,
2324
+ signature: linkSignature + [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
2325
+ };
2326
+ entries.push(entry);
2327
+ if (info.isDirectory()) await walk(root, source, path3, parents);
2328
+ else {
2329
+ const h = await open2(source, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
2330
+ const header = Buffer.alloc(16);
2331
+ try {
2332
+ await h.read(header, 0, 16, 0);
2333
+ } finally {
2334
+ await h.close();
2335
+ }
2336
+ if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
2337
+ else if (info.size > 0n && /\.(db|sqlite|sqlite3)$/i.test(path3)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path3}`);
2338
+ }
2339
+ }
2340
+ }
2341
+ await walk("state", state2);
2342
+ await walk("workspace", workspace);
2343
+ const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
2344
+ for (const entry of entries) {
2345
+ if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
2346
+ if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
2347
+ entry.kind = "sidecar";
2348
+ }
2349
+ }
2350
+ return { entries, exclusions: exclusions2, roots };
2351
+ }
2352
+
2353
+ // src/continuity/publication.ts
2354
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
1991
2355
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
1992
2356
  var ZERO = "0".repeat(64);
1993
2357
  var HASH2 = /^[a-f0-9]{64}$/;
@@ -2028,8 +2392,12 @@ function normalizePublicationProfile(value2) {
2028
2392
  return Object.freeze(profile);
2029
2393
  }
2030
2394
  function validatePublicationPath(path3) {
2031
- if (typeof path3 !== "string" || !path3 || path3.length > 2048 || path3.normalize("NFC") !== path3 || /[\x00-\x1f<>:"|?*\\]/.test(path3) || path3.split("/").some((p) => !p || p === "." || p === ".." || /[. ]$/.test(p) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)))
2395
+ if (typeof path3 !== "string" || path3.normalize("NFC") !== path3) throw new Error("PUBLICATION_INVALID_PATH");
2396
+ try {
2397
+ validateRelativePath(path3);
2398
+ } catch {
2032
2399
  throw new Error("PUBLICATION_INVALID_PATH");
2400
+ }
2033
2401
  }
2034
2402
  function normalizePublication(value2) {
2035
2403
  if (!value2 || value2.format !== "engine7-publication-v1" || !natural(value2.sequence) || !value2.sequence || !HASH2.test(value2.parentDigest) || !natural(value2.deletionWatermark) || !Array.isArray(value2.databases) || !Array.isArray(value2.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
@@ -2134,9 +2502,9 @@ var PublicationReplica = class _PublicationReplica {
2134
2502
  if (b.databaseId !== databaseId || b.baselineId !== this.profile.baselineId || b.epoch !== this.profile.epoch || b.tenantId !== identity.tenantId || b.companionId !== identity.companionId || b.seatId !== identity.seatId)
2135
2503
  throw new Error("PUBLICATION_PROFILE_MISMATCH");
2136
2504
  }
2137
- const directory2 = resolve2(options.directory);
2505
+ const directory2 = resolve3(options.directory);
2138
2506
  preparePrivateDirectory(directory2);
2139
- const path3 = join2(directory2, "publications.sqlite");
2507
+ const path3 = join3(directory2, "publications.sqlite");
2140
2508
  preparePrivateDatabase(path3);
2141
2509
  this.journalFile = path3;
2142
2510
  const journalStat = lstatSync3(path3, { bigint: true });
@@ -2325,9 +2693,11 @@ var PublicationReplica = class _PublicationReplica {
2325
2693
  throw error;
2326
2694
  }
2327
2695
  }
2328
- async status() {
2696
+ // Paired control reads use the durable published cut. Original bytes are
2697
+ // verified when published and restored, rather than on every status poll.
2698
+ async status(verifyFiles = true) {
2329
2699
  const c = this.control(), manifest = c.head ? await this.manifest(c.head) : null;
2330
- const dataReady = manifest ? (await this.missing(manifest)).length === 0 : false;
2700
+ const dataReady = manifest ? (verifyFiles ? await this.missing(manifest) : this.databaseMissing(manifest)).length === 0 : false;
2331
2701
  const { applied } = await this.replicationStatus();
2332
2702
  const current2 = this.control();
2333
2703
  const stillReady = dataReady && manifest !== null && current2.head === c.head && current2.digest === c.digest && manifest.deletionWatermark >= current2.floor && this.databaseMissing(manifest).length === 0;
@@ -2372,17 +2742,17 @@ var PublicationReplica = class _PublicationReplica {
2372
2742
 
2373
2743
  // src/continuity/publication-files.ts
2374
2744
  import { DatabaseSync as DatabaseSync4, backup } from "node:sqlite";
2375
- import { lstatSync as lstatSync4, readdirSync, realpathSync as realpathSync2, mkdirSync as mkdirSync3, writeFileSync as writeFileSync2, chmodSync, openSync as openSync4, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "node:fs";
2745
+ import { lstatSync as lstatSync4, readdirSync, realpathSync as realpathSync2, mkdirSync as mkdirSync3, writeFileSync, chmodSync, openSync as openSync4, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "node:fs";
2376
2746
  import { join as join4, resolve as resolve4, dirname as dirname2 } from "node:path";
2377
2747
 
2378
2748
  // src/continuity/crypto.ts
2379
- import { constants as constants3, createWriteStream, openSync as openSync3 } from "node:fs";
2380
- import { open, lstat, link, unlink, writeFile, appendFile } from "node:fs/promises";
2749
+ import { constants as constants4, createWriteStream, openSync as openSync3 } from "node:fs";
2750
+ import { open as open3, lstat as lstat2, link as link2, unlink as unlink2, writeFile as writeFile2, appendFile } from "node:fs/promises";
2381
2751
  var MAGIC2 = Buffer.from("E7OBJ001");
2382
2752
  var HEADER_SIZE = MAGIC2.length + 12;
2383
2753
  async function syncDirectory(directory2) {
2384
2754
  if (process.platform === "win32") return;
2385
- const handle = await open(directory2, constants3.O_RDONLY);
2755
+ const handle = await open3(directory2, constants4.O_RDONLY);
2386
2756
  try {
2387
2757
  await handle.sync();
2388
2758
  } finally {
@@ -2390,150 +2760,6 @@ async function syncDirectory(directory2) {
2390
2760
  }
2391
2761
  }
2392
2762
 
2393
- // src/continuity/inventory.ts
2394
- import { constants as constants4 } from "node:fs";
2395
- import { lstat as lstat2, open as open2, readdir, realpath } from "node:fs/promises";
2396
- import { isAbsolute, join as join3, relative, resolve as resolve3, sep } from "node:path";
2397
- var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
2398
- var STATE_EXCLUDED = {
2399
- ".continuity": "local runtime control; never business state",
2400
- ".engine.pid": "local process identity",
2401
- ".bg-worker.pid": "local process identity",
2402
- ".travel-restored.json": "deployment activation gate; recreated on restore",
2403
- ".travel-enrolled.json": "local runtime enrollment; recreated per node",
2404
- ".travel-active.json": "local activation receipt; recreated per generation",
2405
- ".git": "source control metadata",
2406
- ".gitignore": "source control metadata",
2407
- ".log-baseline.txt": "local diagnostics",
2408
- logs: "local diagnostics; not authoritative history",
2409
- diagnostics: "local diagnostics",
2410
- backups: "historical recovery copies; not active state",
2411
- "package.json": "installed application metadata",
2412
- "start.sh": "local launcher; deployment must be reviewed separately",
2413
- node_modules: "installed dependencies",
2414
- install: "installed application",
2415
- CogniFold: "installed optional runtime",
2416
- "everos-venv": "installed Python runtime",
2417
- "ollama-models": "installed model weights"
2418
- };
2419
- var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
2420
- var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
2421
- function stateReason(name, options) {
2422
- if (options.includeStateEntries?.includes(name)) return void 0;
2423
- return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
2424
- }
2425
- function knownState(name) {
2426
- return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
2427
- }
2428
- async function classifyState(options) {
2429
- const result = { included: [], excluded: [], unclassified: [] };
2430
- for (const name of (await readdir(options.stateDir)).sort()) {
2431
- const reason = stateReason(name, options);
2432
- if (reason) result.excluded.push({ path: name, reason });
2433
- else if (knownState(name) || options.includeStateEntries?.includes(name) || resolve3(options.stateDir, name) === resolve3(options.workspace ?? join3(options.stateDir, "workspace"))) result.included.push(name);
2434
- else result.unclassified.push(name);
2435
- }
2436
- return result;
2437
- }
2438
- function validateRelativePath(path3) {
2439
- if (typeof path3 !== "string" || !path3 || path3.length > 2048 || path3.includes("\\") || isAbsolute(path3)) throw new Error("INVALID_ARTIFACT_PATH");
2440
- for (const part of path3.split("/")) {
2441
- if (!part || part === "." || part === ".." || /[\x00-\x1f<>:"|?*]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part) || Buffer.byteLength(part) > 255)
2442
- throw new Error("INVALID_ARTIFACT_PATH");
2443
- }
2444
- }
2445
- function isWithin(root, candidate) {
2446
- const rel = relative(resolve3(root), resolve3(candidate));
2447
- return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2448
- }
2449
- async function collectInventory(options) {
2450
- const state2 = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join3(state2, "workspace"));
2451
- if (state2 === workspace || isWithin(workspace, state2)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
2452
- const roots = { state: state2, workspace }, entries = [], exclusions2 = [], aliases = /* @__PURE__ */ new Set();
2453
- const include = new Set(options.includeStateEntries ?? []);
2454
- for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
2455
- validateRelativePath(name);
2456
- if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
2457
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2458
- }
2459
- for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
2460
- for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
2461
- validateRelativePath(name);
2462
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2463
- if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
2464
- }
2465
- const classification = await classifyState(options);
2466
- if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
2467
- async function walk(root, directory2, prefix = "") {
2468
- for (const name of (await readdir(directory2)).sort()) {
2469
- const path3 = prefix ? prefix + "/" + name : name, source = join3(directory2, name);
2470
- if (root === "state" && source === workspace) continue;
2471
- let reason = NESTED_EXCLUDED[name];
2472
- if (root === "state" && prefix) reason = options.excludeStateEntries?.[path3] ?? reason;
2473
- if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path3] ?? reason;
2474
- if (!prefix && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
2475
- if (root === "state" && !prefix) {
2476
- reason = stateReason(name, options);
2477
- if (!reason && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
2478
- }
2479
- if (reason) {
2480
- exclusions2.push({ root, path: path3, reason });
2481
- continue;
2482
- }
2483
- validateRelativePath(path3);
2484
- const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
2485
- if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
2486
- aliases.add(key2);
2487
- const info = await lstat2(source, { bigint: true });
2488
- if (info.isSymbolicLink()) throw new Error(`SYMLINK_REFUSED: ${root}/${path3}`);
2489
- if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
2490
- if (info.isDirectory()) {
2491
- try {
2492
- const marker = await lstat2(join3(source, "pyvenv.cfg"));
2493
- if (marker.isFile() && !marker.isSymbolicLink()) {
2494
- exclusions2.push({ root, path: path3, reason: "installed Python virtual environment; rebuild for the target platform" });
2495
- continue;
2496
- }
2497
- } catch (error) {
2498
- if (error.code !== "ENOENT") throw error;
2499
- }
2500
- }
2501
- const entry = {
2502
- root,
2503
- path: path3,
2504
- source,
2505
- kind: info.isDirectory() ? "directory" : "file",
2506
- bytes: Number(info.size),
2507
- mode: Number(info.mode) & 448,
2508
- signature: [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
2509
- };
2510
- entries.push(entry);
2511
- if (info.isDirectory()) await walk(root, source, path3);
2512
- else {
2513
- const h = await open2(source, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
2514
- const header = Buffer.alloc(16);
2515
- try {
2516
- await h.read(header, 0, 16, 0);
2517
- } finally {
2518
- await h.close();
2519
- }
2520
- if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
2521
- else if (/\.(db|sqlite|sqlite3)$/i.test(path3)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path3}`);
2522
- }
2523
- }
2524
- }
2525
- await walk("state", state2);
2526
- await walk("workspace", workspace);
2527
- const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
2528
- for (const entry of entries) {
2529
- if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
2530
- if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
2531
- entry.kind = "sidecar";
2532
- }
2533
- }
2534
- return { entries, exclusions: exclusions2, roots };
2535
- }
2536
-
2537
2763
  // src/continuity/publication-files.ts
2538
2764
  function inventory(root) {
2539
2765
  if (realpathSync2(root) !== resolve4(root)) throw new Error("SYMLINK_REFUSED");
@@ -2587,7 +2813,7 @@ async function capturePublication(options) {
2587
2813
  });
2588
2814
  }
2589
2815
  async function restorePublication(options) {
2590
- const { receiver } = options, status = await receiver.status();
2816
+ const { receiver } = options, status = await receiver.status(false);
2591
2817
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
2592
2818
  const manifest = await receiver.manifest(status.published.sequence);
2593
2819
  if (JSON.stringify(Object.keys(options.databases).sort()) !== JSON.stringify(manifest.profile.databaseIds)) throw new Error("PUBLICATION_INCOMPLETE_DATABASES");
@@ -2601,7 +2827,7 @@ async function restorePublication(options) {
2601
2827
  throw error;
2602
2828
  }
2603
2829
  await syncDirectory(dirname2(destination));
2604
- writeFileSync2(join4(destination, ".travel-restored.json"), JSON.stringify({
2830
+ writeFileSync(join4(destination, ".travel-restored.json"), JSON.stringify({
2605
2831
  format: "engine7-publication-restore-v1",
2606
2832
  activationAllowed: false,
2607
2833
  sequence: manifest.sequence,
@@ -2628,8 +2854,8 @@ async function restorePublication(options) {
2628
2854
  const row = copy.prepare("SELECT head,digest,binding FROM e7_replication_control WHERE role='replica'").get();
2629
2855
  const identity = manifest.profile.identity;
2630
2856
  const wanted = [identity.tenantId, identity.companionId, identity.seatId, item.databaseId, manifest.profile.baselineId, manifest.profile.epoch];
2631
- const check = copy.prepare("PRAGMA quick_check").all();
2632
- if (!row || row.head !== item.head.sequence || row.digest !== item.head.digest || row.binding !== JSON.stringify(wanted) || check.length !== 1 || check[0].quick_check !== "ok") throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
2857
+ if (!row || row.head !== item.head.sequence || row.digest !== item.head.digest || row.binding !== JSON.stringify(wanted))
2858
+ throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
2633
2859
  } finally {
2634
2860
  copy.close();
2635
2861
  }
@@ -2640,6 +2866,7 @@ async function restorePublication(options) {
2640
2866
  closeSync3(fd);
2641
2867
  }
2642
2868
  }
2869
+ const files = [];
2643
2870
  for (const tree of manifest.trees) {
2644
2871
  const root = join4(destination, "trees", tree.id);
2645
2872
  directory2(root);
@@ -2647,20 +2874,19 @@ async function restorePublication(options) {
2647
2874
  for (const file of tree.files) {
2648
2875
  const path3 = join4(root, file.path);
2649
2876
  directory2(dirname2(path3));
2650
- await receiver.objects.restoreFile(file.content, path3);
2651
- chmodSync(path3, file.mode);
2652
- const fd = openSync4(path3, "r+");
2653
- try {
2654
- fsyncSync3(fd);
2655
- } finally {
2656
- closeSync3(fd);
2657
- }
2877
+ files.push({ content: file.content, destination: path3, mode: file.mode });
2658
2878
  }
2659
2879
  }
2660
- const after = await receiver.status();
2880
+ try {
2881
+ await receiver.objects.restoreFiles(files);
2882
+ } catch (error) {
2883
+ if (error.code === "ENOENT") throw new Error("PUBLICATION_NOT_READY");
2884
+ throw error;
2885
+ }
2886
+ const after = await receiver.status(false);
2661
2887
  if (!after.dataReady || after.published?.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
2662
2888
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
2663
- if (!options.deferReceipt) writeFileSync2(join4(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
2889
+ if (!options.deferReceipt) writeFileSync(join4(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
2664
2890
  await syncDirectory(destination);
2665
2891
  return status.published;
2666
2892
  }
@@ -2759,7 +2985,7 @@ function createPublicationServer(options) {
2759
2985
  };
2760
2986
  switch (value2.operation) {
2761
2987
  case "status":
2762
- result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
2988
+ result = preservePublished ? await mutate(() => receiver.status(false)) : await receiver.status(false);
2763
2989
  break;
2764
2990
  case "replication-status":
2765
2991
  result = await receiver.replicationStatus();
@@ -2767,7 +2993,6 @@ function createPublicationServer(options) {
2767
2993
  case "missing": {
2768
2994
  if (!Array.isArray(value2.refs) || value2.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
2769
2995
  const missing = await Promise.all(value2.refs.map(async (ref) => {
2770
- await check();
2771
2996
  validateObjectRef(ref);
2772
2997
  return await receiver.objects.has(ref) ? null : ref.sha256;
2773
2998
  }));
@@ -3059,7 +3284,7 @@ init_sqlite_replication();
3059
3284
  import { basename as basename3, dirname as dirname6, resolve as resolve7 } from "node:path";
3060
3285
 
3061
3286
  // src/continuity/mem7-replication.ts
3062
- import { closeSync as closeSync5, fsyncSync as fsyncSync5, lstatSync as lstatSync6, openSync as openSync6, writeFileSync as writeFileSync4 } from "node:fs";
3287
+ import { closeSync as closeSync5, fsyncSync as fsyncSync5, lstatSync as lstatSync6, openSync as openSync6, writeFileSync as writeFileSync3 } from "node:fs";
3063
3288
  import { dirname as dirname4, join as join6 } from "node:path";
3064
3289
  init_sqlite_replication();
3065
3290
  var location = (stateDir) => join6(stateDir, ".continuity", "mem7-replication.json");
@@ -3177,7 +3402,7 @@ import { lstatSync as lstatSync13, realpathSync as realpathSync9 } from "node:fs
3177
3402
  // src/continuity/runtime-tree-source.ts
3178
3403
  import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
3179
3404
  import { createHash as createHash5 } from "node:crypto";
3180
- import { existsSync as existsSync2, writeFileSync as writeFileSync6, openSync as openSync9, closeSync as closeSync8, fsyncSync as fsyncSync7 } from "node:fs";
3405
+ import { existsSync as existsSync2, writeFileSync as writeFileSync5, openSync as openSync9, closeSync as closeSync8, fsyncSync as fsyncSync7 } from "node:fs";
3181
3406
  import { join as join9, resolve as resolve8 } from "node:path";
3182
3407
  var ZERO2 = "0".repeat(64);
3183
3408
  var HASH3 = /^[a-f0-9]{64}$/;
@@ -3241,7 +3466,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
3241
3466
  this.db.exec("ROLLBACK");
3242
3467
  throw error;
3243
3468
  }
3244
- writeFileSync6(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
3469
+ writeFileSync5(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
3245
3470
  if (process.platform !== "win32") {
3246
3471
  const fd = openSync9(directory2, "r");
3247
3472
  try {
@@ -3362,6 +3587,7 @@ import { relative as relative2, resolve as resolve9 } from "node:path";
3362
3587
  import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
3363
3588
  import { createHash as createHash6 } from "node:crypto";
3364
3589
  init_runtime_replication();
3590
+ import { setImmediate as setImmediate2 } from "node:timers/promises";
3365
3591
  async function runtimeFileEntries(options) {
3366
3592
  const state2 = resolve9(options.inventory.stateDir), workspace = resolve9(options.inventory.workspace ?? state2 + "/workspace");
3367
3593
  if (realpathSync5(state2) !== state2 || realpathSync5(workspace) !== workspace) throw new Error("SYMLINK_REFUSED");
@@ -3416,10 +3642,26 @@ async function captureRuntimeFiles(options) {
3416
3642
  { id: options.workspaceTreeId, files: [], directories: [] }
3417
3643
  ];
3418
3644
  if (!trees.every((tree) => /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(tree.id)) || trees[0].id === trees[1].id) throw new Error("PUBLICATION_INVALID_ID");
3419
- for (const entry of before) {
3645
+ const files = before.filter((entry) => entry.kind !== "directory");
3646
+ const progress = { completedFiles: 0, totalFiles: files.length, completedBytes: 0, totalBytes: files.reduce((n, e) => n + e.bytes, 0) };
3647
+ options.onProgress?.({ ...progress });
3648
+ for (const entry of before.filter((entry2) => entry2.kind === "directory")) {
3420
3649
  const tree = trees[entry.root === "state" ? 0 : 1];
3421
- if (entry.kind === "directory") tree.directories.push(entry.path);
3422
- else tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content: await options.objects.captureFile(entry.source) });
3650
+ tree.directories.push(entry.path);
3651
+ }
3652
+ for (let offset = 0; offset < files.length; offset += 32) {
3653
+ const batch = files.slice(offset, offset + 32);
3654
+ const bytesBefore = progress.completedBytes;
3655
+ const contents = await options.objects.captureFiles(batch.map((entry) => entry.source), (value2) => {
3656
+ progress.completedFiles = offset + value2.completedFiles;
3657
+ progress.completedBytes = bytesBefore + value2.completedBytes;
3658
+ options.onProgress?.({ ...progress });
3659
+ });
3660
+ for (const [index, entry] of batch.entries()) {
3661
+ const tree = trees[entry.root === "state" ? 0 : 1], content = contents[index];
3662
+ tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content });
3663
+ }
3664
+ await setImmediate2();
3423
3665
  }
3424
3666
  if (JSON.stringify(signatures(before)) !== JSON.stringify(signatures(await runtimeFileEntries(options)))) throw new Error("PUBLICATION_SOURCE_CHANGED");
3425
3667
  return trees;
@@ -3430,7 +3672,7 @@ function resolvePath(path3) {
3430
3672
 
3431
3673
  // src/continuity/lance-publication.ts
3432
3674
  import { createHash as createHash11 } from "node:crypto";
3433
- import { lstatSync as lstatSync10, readdirSync as readdirSync2, realpathSync as realpathSync6, mkdirSync as mkdirSync7, writeFileSync as writeFileSync8, openSync as openSync10, closeSync as closeSync9, fsyncSync as fsyncSync8, chmodSync as chmodSync2 } from "node:fs";
3675
+ import { lstatSync as lstatSync10, readdirSync as readdirSync2, realpathSync as realpathSync6, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7, openSync as openSync10, closeSync as closeSync9, fsyncSync as fsyncSync8, chmodSync as chmodSync2 } from "node:fs";
3434
3676
  import { join as join11, resolve as resolve10, dirname as dirname8, relative as relative3 } from "node:path";
3435
3677
  import { createRequire as createRequire5 } from "node:module";
3436
3678
 
@@ -3459,7 +3701,7 @@ init_scope();
3459
3701
 
3460
3702
  // src/mem7/core/change-feed.ts
3461
3703
  import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
3462
- import { existsSync as existsSync3, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync7 } from "node:fs";
3704
+ import { existsSync as existsSync3, readFileSync as readFileSync5, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6 } from "node:fs";
3463
3705
 
3464
3706
  // src/mem7/core/state/temporal.ts
3465
3707
  function canonicalJson(value2) {
@@ -3666,7 +3908,7 @@ var ChangeFeed = class _ChangeFeed {
3666
3908
  let ledger = {};
3667
3909
  if (ledgerPath) {
3668
3910
  try {
3669
- ledger = JSON.parse(readFileSync6(ledgerPath, "utf8"))?.heals ?? {};
3911
+ ledger = JSON.parse(readFileSync5(ledgerPath, "utf8"))?.heals ?? {};
3670
3912
  } catch {
3671
3913
  }
3672
3914
  if (Number.isFinite(ledger[key2])) {
@@ -3691,11 +3933,11 @@ var ChangeFeed = class _ChangeFeed {
3691
3933
  retained[key2] = now2;
3692
3934
  const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
3693
3935
  try {
3694
- writeFileSync7(temp, JSON.stringify({ version: 1, heals: retained }));
3936
+ writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
3695
3937
  renameSync2(temp, ledgerPath);
3696
3938
  } catch (error) {
3697
3939
  try {
3698
- if (existsSync3(temp)) unlinkSync3(temp);
3940
+ if (existsSync3(temp)) unlinkSync2(temp);
3699
3941
  } catch {
3700
3942
  }
3701
3943
  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}`);
@@ -3970,10 +4212,10 @@ init_read_guard();
3970
4212
  init_scope();
3971
4213
 
3972
4214
  // src/mem7/core/episode.ts
3973
- import { readFileSync as readFileSync7 } from "node:fs";
4215
+ import { readFileSync as readFileSync6 } from "node:fs";
3974
4216
  import { join as join10, dirname as dirname7 } from "node:path";
3975
4217
  import { fileURLToPath } from "node:url";
3976
- var PROMPT = readFileSync7(join10(dirname7(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
4218
+ var PROMPT = readFileSync6(join10(dirname7(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
3977
4219
 
3978
4220
  // src/mem7/core/relationship-cognition.ts
3979
4221
  init_scope();
@@ -4281,14 +4523,28 @@ async function captureLancePublication(options) {
4281
4523
  const batchTable = new arrow.Table(batch);
4282
4524
  for (let start = 0; start < batchTable.numRows; start += batchRows) {
4283
4525
  const page = batchTable.slice(start, start + batchRows);
4526
+ let pending = [], pendingBytes = 0;
4527
+ const flush = async () => {
4528
+ if (!pending.length) return;
4529
+ const contents = await options.objects.putContents(pending.map((row) => row.bytes));
4530
+ for (let i = 0; i < pending.length; i++) tree.files.push({ path: pending[i].path, mode: 384, content: contents[i] });
4531
+ pending = [];
4532
+ pendingBytes = 0;
4533
+ };
4284
4534
  for (let index = 0; index < page.numRows; index++) {
4285
4535
  const one = page.slice(index, index + 1), path3 = rowPath(kind, one.getChild("id").get(0));
4286
4536
  if (seen.has(path3)) throw new Error("LANCE_PUBLICATION_DUPLICATE_ROW");
4287
4537
  seen.add(path3);
4288
4538
  const bytes = arrow.tableToIPC(one, "stream");
4289
- if (bytes.length > ROW_BYTES || tree.files.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
4290
- tree.files.push({ path: path3, mode: 384, content: await options.objects.putContent(bytes) });
4539
+ if (bytes.length > ROW_BYTES || tree.files.length + pending.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
4540
+ if (pending.length === 128 || pendingBytes + bytes.length > 8 * 1024 * 1024) await flush();
4541
+ if (bytes.length > 8 * 1024 * 1024) tree.files.push({ path: path3, mode: 384, content: await options.objects.putContent(bytes) });
4542
+ else {
4543
+ pending.push({ path: path3, bytes });
4544
+ pendingBytes += bytes.length;
4545
+ }
4291
4546
  }
4547
+ await flush();
4292
4548
  }
4293
4549
  }
4294
4550
  if (seen.size !== total) throw new Error("LANCE_PUBLICATION_ROW_COUNT_MISMATCH");
@@ -4344,7 +4600,7 @@ async function restoreLancePublication(options) {
4344
4600
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
4345
4601
  throw error;
4346
4602
  }
4347
- writeFileSync8(join11(destination, ".travel-restored.json"), JSON.stringify({
4603
+ writeFileSync7(join11(destination, ".travel-restored.json"), JSON.stringify({
4348
4604
  format: "engine7-lance-logical-restore-v1",
4349
4605
  activationAllowed: false,
4350
4606
  identity: options.objects.identity,
@@ -4384,7 +4640,7 @@ async function restoreLancePublication(options) {
4384
4640
  connection.close();
4385
4641
  }
4386
4642
  durablePrivateTree(destination);
4387
- writeFileSync8(
4643
+ writeFileSync7(
4388
4644
  join11(destination, ".lance-receipt.json"),
4389
4645
  JSON.stringify({ format: manifest.format, tables: manifest.tables, activationAllowed: false }),
4390
4646
  { flag: "wx", mode: 384, flush: true }
@@ -4397,9 +4653,10 @@ init_schema_migrations();
4397
4653
  init_sqlite_replication();
4398
4654
  init_runtime_replication();
4399
4655
  init_runtime_lock();
4656
+ init_runtime_authority();
4400
4657
  import { createRequire as createRequire6 } from "node:module";
4401
4658
  import { createHash as createHash13 } from "node:crypto";
4402
- import { constants as constants9, lstatSync as lstatSync12, readdirSync as readdirSync3, realpathSync as realpathSync8, readFileSync as readFileSync8, writeFileSync as writeFileSync9, openSync as openSync12, closeSync as closeSync11, readSync as readSync2, chmodSync as chmodSync3, existsSync as existsSync4 } from "node:fs";
4659
+ import { constants as constants9, lstatSync as lstatSync12, readdirSync as readdirSync3, realpathSync as realpathSync8, readFileSync as readFileSync7, writeFileSync as writeFileSync8, openSync as openSync12, closeSync as closeSync11, readSync as readSync2, chmodSync as chmodSync3, existsSync as existsSync4 } from "node:fs";
4403
4660
  import { join as join13, resolve as resolve12, dirname as dirname10 } from "node:path";
4404
4661
 
4405
4662
  // src/continuity/session-event-projection.ts
@@ -4414,7 +4671,7 @@ import {
4414
4671
  fstatSync as fstatSync5,
4415
4672
  appendFileSync,
4416
4673
  renameSync as renameSync3,
4417
- unlinkSync as unlinkSync4
4674
+ unlinkSync as unlinkSync3
4418
4675
  } from "node:fs";
4419
4676
  import { basename as basename4, dirname as dirname9, join as join12, relative as relative4, resolve as resolve11 } from "node:path";
4420
4677
  import { createHash as createHash12, randomUUID as randomUUID6 } from "node:crypto";
@@ -4512,7 +4769,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
4512
4769
  prepareSessionDirectory(dirname9(file));
4513
4770
  if (record.state === "removed") {
4514
4771
  if (signature !== null) {
4515
- unlinkSync4(file);
4772
+ unlinkSync3(file);
4516
4773
  syncSessionDirectory(dirname9(file));
4517
4774
  }
4518
4775
  cursors.prepare("DELETE FROM cursors WHERE path=?").run(path3);
@@ -4556,7 +4813,7 @@ function projectSessionFile(db, cursors, stateDir, path3, sourceRoot) {
4556
4813
  if (fd !== void 0) closeSync10(fd);
4557
4814
  if (!incremental && !complete) {
4558
4815
  try {
4559
- unlinkSync4(temp);
4816
+ unlinkSync3(temp);
4560
4817
  } catch (error) {
4561
4818
  if (error.code !== "ENOENT") throw error;
4562
4819
  }
@@ -4706,7 +4963,7 @@ function importFile(db, stateDir, file) {
4706
4963
  let ordinal = 0;
4707
4964
  const add = (body) => db.prepare("INSERT INTO session_file_events VALUES(?,?,?)").run(place.path, ++ordinal, rememberEvent(db, place.key, body, place.kind));
4708
4965
  if (place.kind !== "jsonl") {
4709
- add(readFileSync8(file));
4966
+ add(readFileSync7(file));
4710
4967
  return;
4711
4968
  }
4712
4969
  const fd = openSync12(file, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0)), chunk = Buffer.alloc(1024 * 1024);
@@ -4774,7 +5031,7 @@ var SessionEventStore = class {
4774
5031
  if (row && !approvedSourceRoot) {
4775
5032
  const file = join13(stateDir, ".travel-active.json"), stat = lstatSync12(file);
4776
5033
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4 * 1024 * 1024 || process.platform !== "win32" && (stat.mode & 63 || stat.uid !== process.getuid())) throw new Error("REPLICATION_RECOVERY_REQUIRED");
4777
- const activation = JSON.parse(readFileSync8(file, "utf8")), binding = registration.binding;
5034
+ const activation = JSON.parse(readFileSync7(file, "utf8")), binding = registration.binding;
4778
5035
  approvedSourceRoot = activation.format === "engine7-runtime-activation-v1" && activation.destination === stateDir && activation.originalSessionRoots?.includes(row.source_root) && activation.profile?.baselineId === binding.baselineId && activation.profile?.epoch === binding.epoch && activation.identity?.tenantId === binding.tenantId && activation.identity?.companionId === binding.companionId && activation.identity?.seatId === binding.seatId;
4779
5036
  }
4780
5037
  if (!row || !approvedSourceRoot || !Number.isSafeInteger(row.revision) || Number(row.revision) < 0) throw new Error("REPLICATION_RECOVERY_REQUIRED");
@@ -5026,7 +5283,7 @@ async function restoreSessionEvents(options) {
5026
5283
  if (realpathSync8(dirname10(destination)) !== dirname10(destination)) throw new Error("SESSION_SYMLINK_REFUSED");
5027
5284
  if (existsSync4(destination)) throw new Error("CONTINUITY_DESTINATION_EXISTS");
5028
5285
  prepareSessionDirectory(destination);
5029
- writeFileSync9(join13(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-session-events-restore-v1", activationAllowed: false, binding }), { mode: 384, flag: "wx", flush: true });
5286
+ writeFileSync8(join13(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-session-events-restore-v1", activationAllowed: false, binding }), { mode: 384, flag: "wx", flush: true });
5030
5287
  syncSessionDirectory(destination);
5031
5288
  const directory2 = join13(destination, ".continuity");
5032
5289
  prepareSessionDirectory(directory2);
@@ -5041,7 +5298,7 @@ async function restoreSessionEvents(options) {
5041
5298
  cursors.exec("BEGIN IMMEDIATE");
5042
5299
  for (const row of copy.prepare("SELECT path FROM session_files ORDER BY path").all()) projectSessionFile(copy, cursors, destination, String(row.path), root);
5043
5300
  cursors.exec("COMMIT");
5044
- writeFileSync9(
5301
+ writeFileSync8(
5045
5302
  join13(destination, ".session-events-receipt.json"),
5046
5303
  JSON.stringify({ binding, head: { sequence: control2.head, digest: control2.digest }, activationAllowed: false }),
5047
5304
  { mode: 384, flag: "wx", flush: true }
@@ -5215,13 +5472,13 @@ async function runRuntimeArtifactCli(command, config) {
5215
5472
  // src/continuity/runtime-sync-cli.ts
5216
5473
  import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
5217
5474
  import { createHash as createHash18 } from "node:crypto";
5218
- import { lstatSync as lstatSync17, realpathSync as realpathSync12, readFileSync as readFileSync9 } from "node:fs";
5475
+ import { lstatSync as lstatSync17, realpathSync as realpathSync12, readFileSync as readFileSync8 } from "node:fs";
5219
5476
  import { isAbsolute as isAbsolute4, resolve as resolve19, join as join20 } from "node:path";
5220
5477
 
5221
5478
  // src/continuity/runtime-publication-source.ts
5222
5479
  import { DatabaseSync as DatabaseSync13 } from "node:sqlite";
5223
5480
  import { createHash as createHash15 } from "node:crypto";
5224
- import { existsSync as existsSync5, lstatSync as lstatSync15, writeFileSync as writeFileSync10, openSync as openSync13, closeSync as closeSync12, fsyncSync as fsyncSync10 } from "node:fs";
5481
+ import { existsSync as existsSync5, lstatSync as lstatSync15, writeFileSync as writeFileSync9, openSync as openSync13, closeSync as closeSync12, fsyncSync as fsyncSync10 } from "node:fs";
5225
5482
  import { join as join15, resolve as resolve15 } from "node:path";
5226
5483
 
5227
5484
  // src/continuity/runtime-h-capture.ts
@@ -5335,9 +5592,9 @@ async function capture(input, assertRoot) {
5335
5592
  }
5336
5593
  for (const s of sessionTrees) {
5337
5594
  const head = before.heads.find((d) => d.databaseId === s.databaseId).head;
5338
- const metadata3 = { format: "engine7-session-events-publication-v1", databaseId: s.databaseId, binding: databases[s.databaseId].source.binding, head };
5339
- trees.push({ id: s.treeId, directories: [], files: [{ path: "manifest.json", mode: 384, content: await objects.putContent(Buffer.from(JSON.stringify(metadata3))) }] });
5340
- origins[s.treeId] = metadata3;
5595
+ const metadata4 = { format: "engine7-session-events-publication-v1", databaseId: s.databaseId, binding: databases[s.databaseId].source.binding, head };
5596
+ trees.push({ id: s.treeId, directories: [], files: [{ path: "manifest.json", mode: 384, content: await objects.putContent(Buffer.from(JSON.stringify(metadata4))) }] });
5597
+ origins[s.treeId] = metadata4;
5341
5598
  }
5342
5599
  if (!same2(before, await observe())) throw new Error("PUBLICATION_SOURCE_CHANGED");
5343
5600
  return {
@@ -5430,7 +5687,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5430
5687
  }
5431
5688
  sender.exec(senderSchema);
5432
5689
  sender.prepare("INSERT INTO sender VALUES(1,?,?)").run(JSON.stringify(this.profile), this.layoutDigest);
5433
- writeFileSync10(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
5690
+ writeFileSync9(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
5434
5691
  if (process.platform !== "win32") {
5435
5692
  const fd = openSync13(this.directory, "r");
5436
5693
  try {
@@ -5459,7 +5716,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5459
5716
  static async open(options) {
5460
5717
  const source = new _RuntimePublicationSource(options);
5461
5718
  try {
5462
- if (source.head().sequence) await source.read(source.head().sequence);
5719
+ if (source.head().sequence) await source.readManifest(source.head().sequence);
5463
5720
  return source;
5464
5721
  } catch (error) {
5465
5722
  source.close();
@@ -5510,6 +5767,15 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5510
5767
  };
5511
5768
  }
5512
5769
  async read(sequence) {
5770
+ return this.readPrepared(sequence, true);
5771
+ }
5772
+ /** Ancestry uses authenticated H metadata; payload availability is checked
5773
+ * when actual objects are transferred or restored, not for every old H. */
5774
+ async readManifest(sequence) {
5775
+ const { digest: digest3, manifest } = await this.readPrepared(sequence, false);
5776
+ return { digest: digest3, manifest };
5777
+ }
5778
+ async readPrepared(sequence, verifyDependencies) {
5513
5779
  const row = this.entry(sequence), ref = JSON.parse(row.content);
5514
5780
  validateFileContent(ref);
5515
5781
  const manifest = normalizePublication(JSON.parse((await this.objects.readContent(ref, PUBLICATION_MANIFEST_BYTES)).toString()));
@@ -5517,7 +5783,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5517
5783
  if (manifest.sequence !== sequence || !same3(manifest.profile, this.profile) || manifest.parentDigest !== parent || row.parent_digest !== parent || publicationDigest(manifest) !== row.digest || stateHash(manifest) !== row.state_hash) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
5518
5784
  const dependencies = JSON.parse(row.dependencies);
5519
5785
  if (!Array.isArray(dependencies) || !same3(dependencies.map((d) => d.treeId).sort(), this.profile.trees.map((t) => t.id))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
5520
- for (const d of dependencies) {
5786
+ if (verifyDependencies) for (const d of dependencies) {
5521
5787
  const tree = await this.trees.read(d.treeId, d.sequence);
5522
5788
  if (tree.digest !== d.digest || !same3(tree.tree, manifest.trees.find((t) => t.id === d.treeId))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
5523
5789
  }
@@ -5530,12 +5796,18 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5530
5796
  async prepare(options) {
5531
5797
  return this.prepareCapture(options, () => captureRuntimeH(options));
5532
5798
  }
5799
+ /** A first full baseline already lives in the bounded encrypted object store
5800
+ * and native SQLite snapshots. Only its envelope occupies the increment queue. */
5801
+ async prepareInitial(options) {
5802
+ if (this.control().head !== 0) throw new Error("RUNTIME_PUBLICATION_INITIAL_ALREADY_PREPARED");
5803
+ return this.prepareCapture(options, () => captureRuntimeH(options), true);
5804
+ }
5533
5805
  /** The source business stores stay read-only and writer exclusion remains
5534
5806
  * held until the caller durably seals its backup and archive receipt. */
5535
5807
  async withStoppedPreparation(options, operation) {
5536
5808
  return withStoppedRuntimeH(options, async (parts) => operation(await this.prepareCapture(options, async () => parts)));
5537
5809
  }
5538
- async prepareCapture(options, capture2) {
5810
+ async prepareCapture(options, capture2, initial = false) {
5539
5811
  const c = this.control(), pending = this.status();
5540
5812
  if (!same3(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
5541
5813
  if (pending.pendingCheckpoints >= this.maximumPendingCheckpoints || pending.pendingBytes >= this.maximumPendingBytes) throw new Error("RUNTIME_PUBLICATION_QUEUE_FULL");
@@ -5567,11 +5839,11 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
5567
5839
  for (const tree of prepared.manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) known.add(ref.sha256);
5568
5840
  }
5569
5841
  let bytes = encoded.length + Buffer.byteLength(JSON.stringify(dependencies));
5570
- for (const tree of manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) if (!known.has(ref.sha256)) {
5842
+ for (const tree of manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) if (!initial && !known.has(ref.sha256)) {
5571
5843
  known.add(ref.sha256);
5572
5844
  bytes += ref.bytes;
5573
5845
  }
5574
- for (const d of manifest.databases) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
5846
+ for (const d of manifest.databases) if (!initial) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
5575
5847
  old?.manifest.databases.find((previous) => previous.databaseId === d.databaseId).head.sequence ?? 0,
5576
5848
  d.head.sequence
5577
5849
  );
@@ -5887,7 +6159,7 @@ init_runtime_lock();
5887
6159
 
5888
6160
  // src/continuity/recovery-archive.ts
5889
6161
  import { DatabaseSync as DatabaseSync14, backup as backup2 } from "node:sqlite";
5890
- import { existsSync as existsSync6, lstatSync as lstatSync16, mkdtempSync, rmSync, writeFileSync as writeFileSync11, chmodSync as chmodSync4 } from "node:fs";
6162
+ import { existsSync as existsSync6, lstatSync as lstatSync16, mkdtempSync, rmSync, writeFileSync as writeFileSync10, chmodSync as chmodSync4 } from "node:fs";
5891
6163
  import { join as join16, resolve as resolve16 } from "node:path";
5892
6164
  init_sqlite_replication();
5893
6165
  import { createHash as createHash16 } from "node:crypto";
@@ -5926,7 +6198,8 @@ async function currentHDeletionCheckAsync(raw, control2, captured) {
5926
6198
  var schema4 = "CREATE TABLE archives(id TEXT PRIMARY KEY,kind TEXT NOT NULL,manifest_digest TEXT NOT NULL,content TEXT NOT NULL)";
5927
6199
  var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
5928
6200
  var FORMAT = "engine7-runtime-recovery-archive-v1";
5929
- var MAX_METADATA = 16 * 1024 * 1024;
6201
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
6202
+ var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
5930
6203
  var same5 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
5931
6204
  var incarnation2 = (file) => {
5932
6205
  const s = lstatSync16(file, { bigint: true });
@@ -5970,14 +6243,17 @@ async function checkRecoveryDeletionAsync(manifest, current2, previous = 0) {
5970
6243
  const floor = await current2();
5971
6244
  return checkRecoveryDeletion(manifest, () => floor, previous);
5972
6245
  }
5973
- function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2) {
6246
+ function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2, scan = true) {
5974
6247
  const d = manifest.databases.find((d2) => d2.databaseId === databaseId), p = manifest.profile;
5975
6248
  const control2 = db.prepare("SELECT binding,head,digest,schema_hash FROM e7_replication_control WHERE role=?").get(role);
5976
6249
  const binding = JSON.stringify([p.identity.tenantId, p.identity.companionId, p.identity.seatId, databaseId, p.baselineId, p.epoch]);
5977
6250
  if (!d || !control2 || control2.binding !== binding || control2.head !== d.head.sequence || control2.digest !== d.head.digest || schemaHash2 !== void 0 && control2.schema_hash !== schemaHash2) throw new Error("RECOVERY_DATABASE_SNAPSHOT_MISMATCH");
5978
6251
  const actual = sqliteReplicationSchemaHash(db);
5979
- const checks = db.prepare("PRAGMA quick_check").all();
5980
- if (actual !== control2.schema_hash || checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
6252
+ if (actual !== control2.schema_hash) throw new Error("RECOVERY_DATABASE_CORRUPT");
6253
+ if (scan) {
6254
+ const checks = db.prepare("PRAGMA quick_check").all();
6255
+ if (checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
6256
+ }
5981
6257
  return actual;
5982
6258
  }
5983
6259
  var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
@@ -6010,7 +6286,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6010
6286
  this.db.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
6011
6287
  if (fresh) {
6012
6288
  this.db.exec(schema4);
6013
- writeFileSync11(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
6289
+ writeFileSync10(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
6014
6290
  }
6015
6291
  if (!same5(this.db.prepare("SELECT sql FROM sqlite_master WHERE type='table'").all().map((r) => String(r.sql)), [schema4]) || this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("RECOVERY_ARCHIVE_REQUIRED");
6016
6292
  this.identity = incarnation2(this.file);
@@ -6119,25 +6395,37 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6119
6395
  if (old) {
6120
6396
  if (old.kind !== kind || old.manifest_digest !== digest3) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6121
6397
  const entry = await this.read(id2);
6122
- for (const d of entry.databases) await verifyContent(this.objects, d.content);
6123
- for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
6398
+ if (options.verifyRetained !== false) {
6399
+ for (const d of entry.databases) await verifyContent(this.objects, d.content);
6400
+ for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
6401
+ }
6124
6402
  await verify2();
6125
6403
  return entry.receipt;
6126
6404
  }
6127
6405
  let publication;
6128
6406
  if (kind !== "LOCAL") {
6129
- const status = await options.receiver?.status();
6407
+ const status = await options.receiver?.status(options.verifyRetained !== false);
6130
6408
  if (!status || !currentHCheck && !status.dataReady || status.published?.digest !== digest3 || !same5(status.profile, manifest.profile)) throw new Error("RECOVERY_COMMON_NOT_READY");
6131
6409
  publication = status.published;
6132
6410
  }
6133
6411
  if (!same5(Object.keys(options.databases).sort(), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
6134
6412
  const role = kind === "LOCAL" ? "source" : "replica";
6135
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
6413
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
6414
+ const sibling = kind !== "LOCAL" && !currentHCheck ? this.db.prepare("SELECT id FROM archives WHERE manifest_digest=? AND kind IN ('COMMON','REMOTE') ORDER BY id LIMIT 1").get(digest3) : void 0;
6415
+ const retained = sibling ? await this.read(String(sibling.id)) : void 0;
6416
+ if (retained) {
6417
+ validateRecoveryArchiveEntry(retained, this.objects.identity);
6418
+ if (!same5(retained.manifest, manifest) || !same5(retained.publication, publication) || retained.databases.some((d) => d.role !== "replica")) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6419
+ }
6136
6420
  const temporary = mkdtempSync(join16(this.directory, ".capture-"));
6137
6421
  try {
6138
- writeFileSync11(join16(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6422
+ writeFileSync10(join16(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6139
6423
  const databases = [];
6140
- for (let offset = 0; offset < manifest.databases.length; offset += 6) {
6424
+ if (retained) {
6425
+ if (options.verifyRetained !== false) for (const database of retained.databases) await verifyContent(this.objects, database.content);
6426
+ databases.push(...retained.databases);
6427
+ }
6428
+ for (let offset = 0; !retained && offset < manifest.databases.length; offset += 6) {
6141
6429
  const results = await Promise.allSettled(manifest.databases.slice(offset, offset + 6).map(async (d) => {
6142
6430
  floor = Math.max(floor, await verify2());
6143
6431
  const file = join16(temporary, d.databaseId + ".sqlite");
@@ -6146,11 +6434,11 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6146
6434
  const copy = new DatabaseSync14(file, { readOnly: true });
6147
6435
  let schemaHash2;
6148
6436
  try {
6149
- schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role);
6437
+ schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role, void 0, false);
6150
6438
  } finally {
6151
6439
  copy.close();
6152
6440
  }
6153
- const content = await this.objects.captureFile(file);
6441
+ const [content] = await this.objects.captureFiles([file], void 0, { chunkConcurrency: 8 });
6154
6442
  return { databaseId: d.databaseId, role, schemaHash: schemaHash2, content };
6155
6443
  }));
6156
6444
  for (const result of results) {
@@ -6159,7 +6447,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6159
6447
  }
6160
6448
  }
6161
6449
  for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
6162
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
6450
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
6163
6451
  if (kind !== "LOCAL") {
6164
6452
  const status = await options.receiver.status();
6165
6453
  if (!currentHCheck && !status.dataReady || status.published?.digest !== digest3) throw new Error("RECOVERY_COMMON_NOT_READY");
@@ -6189,18 +6477,17 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6189
6477
  if (currentHCheck) await verify2();
6190
6478
  }
6191
6479
  }
6192
- /** The caller has fetched only refs from this authenticated original seal.
6193
- * No receipt is installed until every chunk and real SQLite snapshot passes. */
6194
- async import(entry, deletionWatermark) {
6480
+ /** Paired transfer verifies original bytes here and opens the native stores
6481
+ * once at seed. Offline imports can also validate the full SQLite snapshots. */
6482
+ async import(entry, deletionWatermark, verifyDatabases = true) {
6195
6483
  this.active();
6196
6484
  const { value: value2, body, receipt } = validateRecoveryArchiveEntry(entry, this.objects.identity);
6197
- let floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark);
6485
+ const floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark);
6198
6486
  const prior = this.db.prepare("SELECT kind,manifest_digest,content FROM archives WHERE id=?").get(value2.id);
6199
6487
  if (prior && (prior.kind !== value2.kind || prior.manifest_digest !== receipt.manifestDigest || JSON.parse(String(prior.content)).sha256 !== receipt.digest)) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6200
- const temporary = mkdtempSync(join16(this.directory, ".import-"));
6488
+ const temporary = verifyDatabases ? mkdtempSync(join16(this.directory, ".import-")) : void 0;
6201
6489
  try {
6202
- for (const db of value2.databases) {
6203
- floor = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
6490
+ if (temporary) for (const db of value2.databases) {
6204
6491
  const file = join16(temporary, db.databaseId + ".sqlite");
6205
6492
  await this.objects.restoreFile(db.content, file);
6206
6493
  const probe = new DatabaseSync14(file, { readOnly: true });
@@ -6210,17 +6497,10 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6210
6497
  probe.close();
6211
6498
  }
6212
6499
  }
6213
- const files = value2.manifest.trees.flatMap((tree) => tree.files);
6214
- for (let offset = 0; offset < files.length; offset += 8) {
6215
- const results = await Promise.allSettled(files.slice(offset, offset + 8).map(async (file) => {
6216
- const current2 = await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
6217
- await verifyContent(this.objects, file.content);
6218
- return current2;
6219
- }));
6220
- for (const result of results) {
6221
- if (result.status === "rejected") throw result.reason;
6222
- floor = Math.max(floor, result.value);
6223
- }
6500
+ const contents = [...temporary ? [] : value2.databases.map((db) => db.content), ...value2.manifest.trees.flatMap((tree) => tree.files.map((file) => file.content))];
6501
+ for (let offset = 0; offset < contents.length; offset += 8) {
6502
+ const results = await Promise.allSettled(contents.slice(offset, offset + 8).map((content) => verifyContent(this.objects, content)));
6503
+ for (const result of results) if (result.status === "rejected") throw result.reason;
6224
6504
  }
6225
6505
  const ref = await this.objects.putContent(body);
6226
6506
  await checkRecoveryDeletionAsync(value2.manifest, deletionWatermark, floor);
@@ -6237,7 +6517,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
6237
6517
  }
6238
6518
  return (await this.read(value2.id)).receipt;
6239
6519
  } finally {
6240
- rmSync(temporary, { recursive: true, force: true });
6520
+ if (temporary) rmSync(temporary, { recursive: true, force: true });
6241
6521
  await syncDirectory(this.directory);
6242
6522
  }
6243
6523
  }
@@ -6255,12 +6535,12 @@ async function verifyContent(objects, content) {
6255
6535
  }
6256
6536
 
6257
6537
  // src/continuity/recovery-cli.ts
6258
- import { existsSync as existsSync7, writeFileSync as writeFileSync14 } from "node:fs";
6538
+ import { existsSync as existsSync7, writeFileSync as writeFileSync13 } from "node:fs";
6259
6539
  import { dirname as dirname12, isAbsolute as isAbsolute3, join as join19, resolve as resolve18 } from "node:path";
6260
6540
 
6261
6541
  // src/continuity/recovery-archive-restore.ts
6262
6542
  import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
6263
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync12, chmodSync as chmodSync5, realpathSync as realpathSync11 } from "node:fs";
6543
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync11, realpathSync as realpathSync11 } from "node:fs";
6264
6544
  import { dirname as dirname11, join as join17, resolve as resolve17 } from "node:path";
6265
6545
  init_sqlite_replication();
6266
6546
  async function restoreRecoveryArchive(options) {
@@ -6280,7 +6560,7 @@ async function restoreOriginal(options, original, currentHCheck) {
6280
6560
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
6281
6561
  throw error;
6282
6562
  }
6283
- writeFileSync12(join17(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
6563
+ writeFileSync11(join17(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
6284
6564
  await syncDirectory(dirname11(destination));
6285
6565
  await syncDirectory(destination);
6286
6566
  const created = /* @__PURE__ */ new Set([destination]);
@@ -6294,29 +6574,28 @@ async function restoreOriginal(options, original, currentHCheck) {
6294
6574
  };
6295
6575
  directory2(join17(destination, "databases"));
6296
6576
  directory2(join17(destination, "trees"));
6577
+ await objects.restoreFiles(entry.databases.map((d) => ({ content: d.content, destination: join17(destination, "databases", d.databaseId + ".sqlite") })));
6297
6578
  for (const d of entry.databases) {
6298
- floor = await verify2();
6299
6579
  const path3 = join17(destination, "databases", d.databaseId + ".sqlite");
6300
- await objects.restoreFile(d.content, path3);
6301
6580
  const db = new DatabaseSync15(path3, { readOnly: true });
6302
6581
  try {
6303
- validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash);
6582
+ validateRecoveryDatabase(db, manifest, d.databaseId, d.role, d.schemaHash, options.verifyDatabases !== false);
6304
6583
  } finally {
6305
6584
  db.close();
6306
6585
  }
6307
6586
  }
6587
+ const files = [];
6308
6588
  for (const tree of manifest.trees) {
6309
6589
  const root = join17(destination, "trees", tree.id);
6310
6590
  directory2(root);
6311
6591
  for (const path3 of tree.directories) directory2(join17(root, path3));
6312
6592
  for (const file of tree.files) {
6313
- floor = await verify2();
6314
6593
  const path3 = join17(root, file.path);
6315
6594
  directory2(dirname11(path3));
6316
- await objects.restoreFile(file.content, path3);
6317
- chmodSync5(path3, file.mode);
6595
+ files.push({ content: file.content, destination: path3, mode: file.mode });
6318
6596
  }
6319
6597
  }
6598
+ await objects.restoreFiles(files);
6320
6599
  directory2(join17(destination, "lance"));
6321
6600
  directory2(join17(destination, "sessions"));
6322
6601
  for (const kind of manifest.profile.trees) {
@@ -6324,10 +6603,10 @@ async function restoreOriginal(options, original, currentHCheck) {
6324
6603
  if (kind.kind === "vector") await restoreLancePublication({ tree, objects, destination: join17(destination, "lance", tree.id) });
6325
6604
  if (kind.kind === "session") {
6326
6605
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6327
- const metadata3 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
6328
- const d = entry.databases.find((d2) => d2.databaseId === metadata3.databaseId);
6329
- const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata3.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
6330
- if (metadata3.format !== "engine7-session-events-publication-v1" || !d || JSON.stringify(metadata3.binding) !== JSON.stringify(binding) || JSON.stringify(metadata3.head) !== JSON.stringify(manifest.databases.find((v) => v.databaseId === d.databaseId).head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6606
+ const metadata4 = JSON.parse((await objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
6607
+ const d = entry.databases.find((d2) => d2.databaseId === metadata4.databaseId);
6608
+ const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata4.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
6609
+ 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");
6331
6610
  const db = new DatabaseSync15(join17(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
6332
6611
  try {
6333
6612
  await restoreSessionEvents({ db, binding, destination: join17(destination, "sessions", tree.id), replicationRole: d.role });
@@ -6335,11 +6614,10 @@ async function restoreOriginal(options, original, currentHCheck) {
6335
6614
  db.close();
6336
6615
  }
6337
6616
  }
6338
- floor = await verify2();
6339
6617
  }
6340
6618
  for (const path3 of [...created].reverse()) await syncDirectory(path3);
6341
6619
  await verify2();
6342
- writeFileSync12(join17(destination, ".recovery-archive-receipt.json"), JSON.stringify(entry.receipt), { mode: 384, flag: "wx", flush: true });
6620
+ writeFileSync11(join17(destination, ".recovery-archive-receipt.json"), JSON.stringify(entry.receipt), { mode: 384, flag: "wx", flush: true });
6343
6621
  await syncDirectory(destination);
6344
6622
  await verify2();
6345
6623
  return entry.receipt;
@@ -6348,7 +6626,7 @@ async function restoreOriginal(options, original, currentHCheck) {
6348
6626
  // src/continuity/recovery-diff.ts
6349
6627
  import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
6350
6628
  import { createHash as createHash17 } from "node:crypto";
6351
- import { mkdtempSync as mkdtempSync2, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
6629
+ import { mkdtempSync as mkdtempSync2, rmSync as rmSync2, writeFileSync as writeFileSync12 } from "node:fs";
6352
6630
  import { join as join18 } from "node:path";
6353
6631
  init_legacy_sqlite_indexes();
6354
6632
  init_schema_migrations();
@@ -6443,7 +6721,7 @@ async function compareRecoveryArchives(options) {
6443
6721
  const entry = entries[index], ref = references[index], d = entry.databases.find((d2) => d2.databaseId === databaseId);
6444
6722
  const temporary = mkdtempSync2(join18(ref.archive.directory, ".compare-"));
6445
6723
  temporaries.push(temporary);
6446
- writeFileSync13(join18(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6724
+ writeFileSync12(join18(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
6447
6725
  const file = join18(temporary, databaseId + ".sqlite");
6448
6726
  await ref.archive.objects.restoreFile(d.content, file);
6449
6727
  const db = new DatabaseSync16(file, { readOnly: true, allowExtension: true });
@@ -6666,7 +6944,7 @@ async function runRecoveryCli(command, config) {
6666
6944
  const deletionWatermark = recoveryDeletionReader(config);
6667
6945
  deletionWatermark();
6668
6946
  const handles = [], keys = [];
6669
- const open3 = async (c) => {
6947
+ const open5 = async (c) => {
6670
6948
  const dataDir = absolute2(c.dataDir), keyFile = absolute2(c.dataKeyFile);
6671
6949
  if (isWithin(dataDir, keyFile)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
6672
6950
  assertPrivateDirectory(dataDir);
@@ -6682,14 +6960,14 @@ async function runRecoveryCli(command, config) {
6682
6960
  };
6683
6961
  try {
6684
6962
  if (command === "inspect-recovery") {
6685
- const ref = await open3(config);
6963
+ const ref = await open5(config);
6686
6964
  return await ref.archive.list();
6687
6965
  }
6688
6966
  if (command === "restore-recovery") {
6689
- const ref = await open3(config);
6967
+ const ref = await open5(config);
6690
6968
  return await restoreRecoveryArchive({ ...ref, destination: absolute2(config.destination), deletionWatermark });
6691
6969
  }
6692
- const common = await open3(config.common), local = await open3(config.local), remote = await open3(config.remote);
6970
+ const common = await open5(config.common), local = await open5(config.local), remote = await open5(config.remote);
6693
6971
  const report = await compareRecoveryArchives({ common, local, remote, deletionWatermark, maximumRows: config.maximumRows, maximumBytes: config.maximumBytes });
6694
6972
  const reportFile = absolute2(config.reportFile);
6695
6973
  assertPrivateDirectory(dirname12(reportFile));
@@ -6699,7 +6977,7 @@ async function runRecoveryCli(command, config) {
6699
6977
  const pointer = { format: "engine7-recovery-diff-reference-v1", identity: common.archive.objects.identity, digest: report.digest, content };
6700
6978
  if (existsSync7(reportFile)) {
6701
6979
  if (JSON.stringify(JSON.parse(readPrivateFile(reportFile, 1024 * 1024).toString())) !== JSON.stringify(pointer)) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
6702
- } else writeFileSync14(reportFile, JSON.stringify(pointer), { mode: 384, flag: "wx", flush: true });
6980
+ } else writeFileSync13(reportFile, JSON.stringify(pointer), { mode: 384, flag: "wx", flush: true });
6703
6981
  await syncDirectory(dirname12(reportFile));
6704
6982
  for (const ref of [common, local, remote]) checkRecoveryDeletion((await ref.archive.read(ref.id)).manifest, deletionWatermark);
6705
6983
  return { digest: report.digest, reportFile, counts: report.counts, scannedRecords: report.scannedRecords, admissionAllowed: false, activationAllowed: false };
@@ -6885,8 +7163,8 @@ async function runRuntimeSyncCli(command, config) {
6885
7163
  url: config.url,
6886
7164
  profile,
6887
7165
  timeoutMs: config.timeoutMs,
6888
- ca: readFileSync9(absolute3(config.caFile)),
6889
- cert: readFileSync9(absolute3(config.certificateFile)),
7166
+ ca: readFileSync8(absolute3(config.caFile)),
7167
+ cert: readFileSync8(absolute3(config.certificateFile)),
6890
7168
  key: readPrivateFile(absolute3(config.privateKeyFile))
6891
7169
  });
6892
7170
  const sync = { source, client, objects, databases: writableDatabases, maximumObjects: config.maximumObjects, maximumCommits: config.maximumCommits, maximumBytes: config.maximumDrainBytes };
@@ -6937,7 +7215,7 @@ async function runRuntimeSyncCli(command, config) {
6937
7215
 
6938
7216
  // src/continuity/runtime-publication-restore.ts
6939
7217
  import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
6940
- import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync15 } from "node:fs";
7218
+ import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync14 } from "node:fs";
6941
7219
  import { join as join22, resolve as resolve21 } from "node:path";
6942
7220
  init_sqlite_replication();
6943
7221
 
@@ -6945,41 +7223,59 @@ init_sqlite_replication();
6945
7223
  import { createHash as createHash19 } from "node:crypto";
6946
7224
  import { constants as constants10, closeSync as closeSync13, fstatSync as fstatSync6, lstatSync as lstatSync18, openSync as openSync14, readSync as readSync3, readdirSync as readdirSync4, realpathSync as realpathSync13 } from "node:fs";
6947
7225
  import { join as join21, resolve as resolve20 } from "node:path";
6948
- function runtimeGenerationIntegrity(directory2) {
6949
- const root = resolve20(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
7226
+ import { open as open4 } from "node:fs/promises";
7227
+ var recentSeals = /* @__PURE__ */ new Map();
7228
+ function rememberSeal(root, integrity, files) {
7229
+ recentSeals.delete(root);
7230
+ recentSeals.set(root, { integrity: JSON.stringify(integrity), metadata: fileMetadata(files) });
7231
+ if (recentSeals.size > 4) recentSeals.delete(recentSeals.keys().next().value);
7232
+ }
7233
+ var metadata3 = (stat) => [stat.dev, stat.ino, stat.size, stat.mode, stat.mtimeNs, stat.ctimeNs].join(":");
7234
+ function generationFiles(root) {
7235
+ const files = [];
6950
7236
  if (realpathSync13(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6951
7237
  const visit = (path3) => {
6952
7238
  if (path3 === ".runtime-publication-receipt.json") return;
6953
- const file = join21(root, path3), before = lstatSync18(file, { bigint: true });
6954
- if (before.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6955
- if (before.isDirectory()) {
7239
+ const file = join21(root, path3), stat = lstatSync18(file, { bigint: true });
7240
+ if (stat.isSymbolicLink()) throw new Error("TRAVEL_GENERATION_INTEGRITY");
7241
+ if (stat.isDirectory()) {
6956
7242
  for (const name of readdirSync4(file).sort()) visit(path3 ? path3 + "/" + name : name);
6957
7243
  return;
6958
7244
  }
6959
- if (!before.isFile() || before.size > BigInt(Number.MAX_SAFE_INTEGER) || result.length >= 1e5) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6960
- const fd = openSync14(file, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0)), hash2 = createHash19("sha256");
7245
+ if (!stat.isFile() || stat.size > BigInt(Number.MAX_SAFE_INTEGER) || files.length >= 1e5) throw new Error("TRAVEL_GENERATION_INTEGRITY");
7246
+ files.push({ path: path3, stat });
7247
+ };
7248
+ visit("");
7249
+ return files.sort((a, b) => a.path.localeCompare(b.path, "en"));
7250
+ }
7251
+ var fileMetadata = (files) => JSON.stringify(files.map((file) => [file.path, metadata3(file.stat)]));
7252
+ async function runtimeGenerationIntegrityAsync(directory2) {
7253
+ const root = resolve20(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
7254
+ const files = generationFiles(root);
7255
+ for (const { path: path3, stat: before } of files) {
7256
+ const file = join21(root, path3), handle = await open4(file, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0)), hash2 = createHash19("sha256");
6961
7257
  let bytes = 0;
6962
7258
  try {
6963
7259
  while (true) {
6964
- const size = readSync3(fd, buffer);
6965
- if (!size) break;
6966
- hash2.update(buffer.subarray(0, size));
6967
- bytes += size;
7260
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
7261
+ if (!bytesRead) break;
7262
+ hash2.update(buffer.subarray(0, bytesRead));
7263
+ bytes += bytesRead;
6968
7264
  }
6969
- const after = fstatSync6(fd, { bigint: true });
6970
- if ([before.dev, before.ino, before.size, before.mtimeNs, before.ctimeNs].join(":") !== [after.dev, after.ino, after.size, after.mtimeNs, after.ctimeNs].join(":") || BigInt(bytes) !== before.size) throw new Error("TRAVEL_GENERATION_INTEGRITY");
7265
+ const after = await handle.stat({ bigint: true });
7266
+ if (metadata3(before) !== metadata3(after) || metadata3(before) !== metadata3(lstatSync18(file, { bigint: true })) || BigInt(bytes) !== before.size) throw new Error("TRAVEL_GENERATION_INTEGRITY");
6971
7267
  result.push({ path: path3, bytes, mode: Number(before.mode & 0o777n), sha256: hash2.digest("hex") });
6972
7268
  } finally {
6973
- closeSync13(fd);
7269
+ await handle.close();
6974
7270
  }
6975
- };
6976
- visit("");
6977
- return result.sort((a, b) => a.path.localeCompare(b.path, "en"));
7271
+ }
7272
+ rememberSeal(root, result, files);
7273
+ return result;
6978
7274
  }
6979
7275
 
6980
7276
  // src/continuity/runtime-publication-restore.ts
6981
7277
  async function restoreRuntimePublication(options) {
6982
- const { receiver } = options, status = await receiver.status();
7278
+ const { receiver } = options, status = await receiver.status(false);
6983
7279
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
6984
7280
  if (options.sequence !== void 0 && options.sequence !== status.published.sequence) throw new Error("PUBLICATION_STALE_PUBLICATION");
6985
7281
  const manifest = await receiver.manifest(status.published.sequence), destination = resolve21(options.destination);
@@ -6987,15 +7283,15 @@ async function restoreRuntimePublication(options) {
6987
7283
  for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "session")) {
6988
7284
  const tree = manifest.trees.find((tree2) => tree2.id === kind.id);
6989
7285
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6990
- const metadata3 = JSON.parse((await receiver.objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
6991
- const database = manifest.databases.find((d) => d.databaseId === metadata3.databaseId);
7286
+ const metadata4 = JSON.parse((await receiver.objects.readContent(tree.files[0].content, 1024 * 1024)).toString());
7287
+ const database = manifest.databases.find((d) => d.databaseId === metadata4.databaseId);
6992
7288
  const binding = normalizeBinding({
6993
7289
  ...manifest.profile.identity,
6994
- databaseId: metadata3.databaseId,
7290
+ databaseId: metadata4.databaseId,
6995
7291
  baselineId: manifest.profile.baselineId,
6996
7292
  epoch: manifest.profile.epoch
6997
7293
  });
6998
- if (metadata3.format !== "engine7-session-events-publication-v1" || !database || JSON.stringify(metadata3.binding) !== JSON.stringify(binding) || JSON.stringify(metadata3.head) !== JSON.stringify(database.head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
7294
+ if (metadata4.format !== "engine7-session-events-publication-v1" || !database || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(database.head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
6999
7295
  sessions.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
7000
7296
  }
7001
7297
  await restorePublication({ ...options, destination, deferReceipt: true });
@@ -7022,17 +7318,17 @@ async function restoreRuntimePublication(options) {
7022
7318
  await syncDirectory(join22(destination, "sessions"));
7023
7319
  sessionStates.push({ treeId: session.treeId, databaseId: session.databaseId, directory: `sessions/${session.treeId}` });
7024
7320
  }
7025
- const after = await receiver.status();
7321
+ const after = await receiver.status(false);
7026
7322
  if (!after.dataReady || after.published?.sequence !== manifest.sequence || after.published.digest !== status.published.digest) throw new Error("PUBLICATION_CONCURRENT_CHANGE");
7027
- writeFileSync15(join22(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
7028
- writeFileSync15(join22(destination, ".runtime-publication-receipt.json"), JSON.stringify({
7323
+ writeFileSync14(join22(destination, ".publication-receipt.json"), JSON.stringify(status.published), { flag: "wx", mode: 384, flush: true });
7324
+ writeFileSync14(join22(destination, ".runtime-publication-receipt.json"), JSON.stringify({
7029
7325
  format: "engine7-runtime-publication-restore-v1",
7030
7326
  profile: manifest.profile,
7031
7327
  receipt: status.published,
7032
7328
  databases: manifest.databases,
7033
7329
  lance,
7034
7330
  sessions: sessionStates,
7035
- integrity: runtimeGenerationIntegrity(destination),
7331
+ integrity: await runtimeGenerationIntegrityAsync(destination),
7036
7332
  activationAllowed: false
7037
7333
  }), { flag: "wx", mode: 384, flush: true });
7038
7334
  await syncDirectory(destination);
@@ -7136,7 +7432,7 @@ async function runPublicationCli(args) {
7136
7432
  const roots = config.roots.map((r) => ({ id: r.id, path: path2(r.path) }));
7137
7433
  for (const r of roots) if (!isWithin(stateDir, r.path) || isWithin(r.path, manifestFile) || isWithin(r.path, keyFile)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
7138
7434
  const manifest = await capturePublication({ profile, roots, objects, sources, sequence: config.sequence, parentDigest: config.parentDigest, deletionWatermark: config.deletionWatermark });
7139
- writeFileSync16(manifestFile, JSON.stringify(manifest), { mode: 384, flag: "wx", flush: true });
7435
+ writeFileSync15(manifestFile, JSON.stringify(manifest), { mode: 384, flag: "wx", flush: true });
7140
7436
  await syncDirectory(dirname13(manifestFile));
7141
7437
  return { sequence: manifest.sequence, files: manifest.trees.reduce((n, t) => n + t.files.length, 0), activationAllowed: false };
7142
7438
  }
@@ -7145,8 +7441,8 @@ async function runPublicationCli(args) {
7145
7441
  url: config.url,
7146
7442
  profile,
7147
7443
  timeoutMs: config.timeoutMs,
7148
- ca: readFileSync10(path2(config.caFile)),
7149
- cert: readFileSync10(path2(config.certificateFile)),
7444
+ ca: readFileSync9(path2(config.caFile)),
7445
+ cert: readFileSync9(path2(config.certificateFile)),
7150
7446
  key: readPrivateFile(path2(config.privateKeyFile))
7151
7447
  });
7152
7448
  try {
@@ -7194,12 +7490,12 @@ async function runPublicationCli(args) {
7194
7490
  if (command === "restore") return await restorePublication({ receiver, databases, destination: path2(config.destination) });
7195
7491
  if (command === "restore-runtime") return await restoreRuntimePublication({ receiver, databases, destination: path2(config.destination), sequence: config.sequence });
7196
7492
  if (typeof config.host !== "string" || !Number.isInteger(config.port) || config.port < 0 || config.port > 65535) throw new Error("PUBLICATION_INVALID_LISTENER");
7197
- const certificate = new X509Certificate(readFileSync10(path2(config.allowedClientCertificateFile)));
7493
+ const certificate = new X509Certificate(readFileSync9(path2(config.allowedClientCertificateFile)));
7198
7494
  const server = createPublicationServer({
7199
7495
  receiver,
7200
7496
  allowedFingerprint: certificate.fingerprint256,
7201
- ca: readFileSync10(path2(config.clientCaFile)),
7202
- cert: readFileSync10(path2(config.certificateFile)),
7497
+ ca: readFileSync9(path2(config.clientCaFile)),
7498
+ cert: readFileSync9(path2(config.certificateFile)),
7203
7499
  key: readPrivateFile(path2(config.privateKeyFile))
7204
7500
  });
7205
7501
  try {