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.
@@ -135,7 +135,7 @@ var init_legacy_sqlite_indexes = __esm({
135
135
 
136
136
  // src/continuity/runtime-authority.ts
137
137
  import { randomUUID as randomUUID2, verify } from "node:crypto";
138
- import { constants as constants4, closeSync as closeSync4, existsSync as existsSync2, fstatSync as fstatSync3, fsyncSync as fsyncSync4, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync4, readFileSync as readFileSync3, renameSync, writeFileSync as writeFileSync3 } from "node:fs";
138
+ import { constants as constants4, closeSync as closeSync4, existsSync as existsSync2, fstatSync as fstatSync3, fsyncSync as fsyncSync4, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync4, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
139
139
  import { basename, dirname as dirname2, join as join4, resolve as resolve4 } from "node:path";
140
140
  function assertPrivateDirectory2(path2) {
141
141
  const stat = lstatSync3(path2);
@@ -147,14 +147,14 @@ function readPrivateFile2(path2, maximum) {
147
147
  const fd = openSync4(path2, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
148
148
  try {
149
149
  if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
150
- return readFileSync3(fd);
150
+ return readFileSync2(fd);
151
151
  } finally {
152
152
  closeSync4(fd);
153
153
  }
154
154
  }
155
155
  function writeControl(path2, value) {
156
156
  const temporary = path2 + "." + randomUUID2() + ".tmp";
157
- writeFileSync3(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
157
+ writeFileSync2(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
158
158
  renameSync(temporary, path2);
159
159
  if (process.platform !== "win32") {
160
160
  const fd = openSync4(dirname2(path2), "r");
@@ -225,9 +225,9 @@ var init_runtime_authority = __esm({
225
225
  mkdirSync3(this.directory, { mode: 448, recursive: true });
226
226
  assertPrivateDirectory2(this.directory);
227
227
  const file = join4(this.directory, "travel-runtime.json");
228
- if (!existsSync2(file)) writeFileSync3(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
228
+ if (!existsSync2(file)) writeFileSync2(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
229
229
  const marker = join4(this.stateDir, ".travel-enrolled.json");
230
- if (!existsSync2(marker)) writeFileSync3(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
230
+ if (!existsSync2(marker)) writeFileSync2(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
231
231
  }
232
232
  this.checkEnrollment();
233
233
  this.previous = runtimes.get(this.stateDir);
@@ -744,7 +744,7 @@ var init_sqlite_replication = __esm({
744
744
  });
745
745
 
746
746
  // src/continuity/runtime-replication.ts
747
- import { constants as constants6, lstatSync as lstatSync5, realpathSync as realpathSync2, mkdirSync as mkdirSync4, openSync as openSync6, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5, fsyncSync as fsyncSync6 } from "node:fs";
747
+ import { constants as constants6, lstatSync as lstatSync5, realpathSync as realpathSync2, mkdirSync as mkdirSync4, openSync as openSync6, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync4, fsyncSync as fsyncSync6 } from "node:fs";
748
748
  import { basename as basename2, dirname as dirname4, join as join6, resolve as resolve5 } from "node:path";
749
749
  function checkKey(component, key) {
750
750
  if (component === "topics-vectors" && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) return;
@@ -800,7 +800,7 @@ function readRuntimeReplicationRegistration(stateDir, component, key) {
800
800
  try {
801
801
  const info = fstatSync4(fd);
802
802
  if (!info.isFile() || info.size > 4096 || realpathSync2(file) !== resolve5(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
803
- return normalize2(JSON.parse(readFileSync4(fd, "utf8")));
803
+ return normalize2(JSON.parse(readFileSync3(fd, "utf8")));
804
804
  } catch (error) {
805
805
  throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
806
806
  } finally {
@@ -856,7 +856,7 @@ var init_runtime_replication = __esm({
856
856
  // src/continuity/runtime-lock.ts
857
857
  import { randomUUID as randomUUID3 } from "node:crypto";
858
858
  import { AsyncLocalStorage } from "node:async_hooks";
859
- import { closeSync as closeSync7, lstatSync as lstatSync7, mkdirSync as mkdirSync5, openSync as openSync7, readFileSync as readFileSync5, realpathSync as realpathSync4 } from "node:fs";
859
+ import { closeSync as closeSync7, lstatSync as lstatSync7, mkdirSync as mkdirSync5, openSync as openSync7, readFileSync as readFileSync4, realpathSync as realpathSync4 } from "node:fs";
860
860
  import { join as join7 } from "node:path";
861
861
  import { createRequire as createRequire2 } from "node:module";
862
862
  function openSQLite(file, options = {}) {
@@ -987,7 +987,7 @@ async function withCheckpointLock(stateDir, operation) {
987
987
  for (const name of [".engine.pid", ".bg-worker.pid"]) {
988
988
  let value;
989
989
  try {
990
- value = readFileSync5(join7(stateDir, name), "utf8").trim();
990
+ value = readFileSync4(join7(stateDir, name), "utf8").trim();
991
991
  } catch (error) {
992
992
  if (error.code === "ENOENT") continue;
993
993
  throw new Error("WRITER_STATE_UNKNOWN", { cause: error });
@@ -1493,21 +1493,19 @@ import {
1493
1493
  fstatSync as fstatSync2,
1494
1494
  fsyncSync as fsyncSync2,
1495
1495
  readSync,
1496
- writeSync as writeSync2,
1497
1496
  lstatSync as lstatSync2,
1498
1497
  realpathSync,
1499
- mkdirSync as mkdirSync2,
1500
- readFileSync as readFileSync2,
1501
- writeFileSync,
1502
- linkSync,
1503
- unlinkSync as unlinkSync2
1498
+ mkdirSync as mkdirSync2
1504
1499
  } from "node:fs";
1500
+ import { open, writeFile, link, unlink } from "node:fs/promises";
1505
1501
  import { join, dirname, resolve } from "node:path";
1506
1502
  import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
1503
+ import { setImmediate } from "node:timers/promises";
1507
1504
  var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
1508
1505
  var HASH = /^[a-f0-9]{64}$/;
1509
1506
  var OVERHEAD = 32;
1510
1507
  var MAGIC = Buffer.from("E7P1");
1508
+ var INLINE_BYTES = 64 * 1024;
1511
1509
  var sha = (body) => createHash("sha256").update(body).digest("hex");
1512
1510
  var noFollow = constants2.O_NOFOLLOW ?? 0;
1513
1511
  function validateObjectRef(ref) {
@@ -1583,15 +1581,24 @@ function preparePrivateDatabase(path2) {
1583
1581
  throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
1584
1582
  syncDir(dirname(path2));
1585
1583
  }
1586
- function exclusivePublish(path2, body) {
1584
+ async function syncDirAsync(path2) {
1585
+ if (process.platform === "win32") return;
1586
+ const fd = await open(path2, constants2.O_RDONLY);
1587
+ try {
1588
+ await fd.sync();
1589
+ } finally {
1590
+ await fd.close();
1591
+ }
1592
+ }
1593
+ async function exclusivePublish(path2, body, deferDirectorySync = false) {
1587
1594
  const temp = join(dirname(path2), "." + randomUUID() + ".partial");
1588
1595
  try {
1589
- writeFileSync(temp, body, { flag: "wx", mode: 384, flush: true });
1590
- linkSync(temp, path2);
1591
- syncDir(dirname(path2));
1596
+ await writeFile(temp, body, { flag: "wx", mode: 384, flush: true });
1597
+ await link(temp, path2);
1598
+ if (!deferDirectorySync) await syncDirAsync(dirname(path2));
1592
1599
  } finally {
1593
1600
  try {
1594
- unlinkSync2(temp);
1601
+ await unlink(temp);
1595
1602
  } catch (error) {
1596
1603
  if (error.code !== "ENOENT") throw error;
1597
1604
  }
@@ -1604,6 +1611,7 @@ var PublicationObjects = class _PublicationObjects {
1604
1611
  key;
1605
1612
  maximumBytes;
1606
1613
  closed = false;
1614
+ inlineReads = 0;
1607
1615
  constructor(options) {
1608
1616
  if (!(options.key instanceof Uint8Array) || options.key.length !== 32) throw new Error("PUBLICATION_INVALID_KEY");
1609
1617
  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])))
@@ -1622,7 +1630,7 @@ var PublicationObjects = class _PublicationObjects {
1622
1630
  this.db = new DatabaseSync2(file);
1623
1631
  this.db.exec(`PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
1624
1632
  CREATE TABLE IF NOT EXISTS identity (id INTEGER PRIMARY KEY CHECK(id=1), verifier BLOB NOT NULL);
1625
- CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0));`);
1633
+ CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY,bytes INTEGER NOT NULL CHECK(bytes>0),ciphertext BLOB);`);
1626
1634
  this.db.exec("BEGIN IMMEDIATE");
1627
1635
  try {
1628
1636
  const row = this.db.prepare("SELECT verifier FROM identity WHERE id=1").get();
@@ -1633,6 +1641,13 @@ var PublicationObjects = class _PublicationObjects {
1633
1641
  throw new Error("PUBLICATION_KEY_OR_IDENTITY_MISMATCH");
1634
1642
  }
1635
1643
  } else this.db.prepare("INSERT INTO identity VALUES(1,?)").run(this.encrypt(Buffer.from("publication-object-key"), "identity"));
1644
+ if (!this.db.prepare("PRAGMA table_info(objects)").all().some((column) => column.name === "ciphertext"))
1645
+ this.db.exec("ALTER TABLE objects ADD COLUMN ciphertext BLOB");
1646
+ 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);
1647
+ INSERT OR IGNORE INTO object_usage SELECT 1,count(*),coalesce(sum(bytes+32),0) FROM objects;
1648
+ 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;
1649
+ 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;
1650
+ 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;`);
1636
1651
  this.db.exec("COMMIT");
1637
1652
  syncDir(this.directory);
1638
1653
  } catch (error) {
@@ -1672,54 +1687,135 @@ var PublicationObjects = class _PublicationObjects {
1672
1687
  }
1673
1688
  usage() {
1674
1689
  this.active();
1675
- return this.db.prepare("SELECT count(*) objects,COALESCE(sum(bytes+32),0) bytes FROM objects").get();
1690
+ return this.db.prepare("SELECT objects,bytes FROM object_usage WHERE id=1").get();
1676
1691
  }
1677
- async put(body) {
1678
- this.active();
1679
- assertPrivateDirectory(this.directory);
1680
- assertPrivateDirectory(join(this.directory, "chunks"));
1681
- if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
1682
- throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
1683
- body = Buffer.from(body);
1684
- const ref = { sha256: sha(body), bytes: body.byteLength };
1692
+ reserve(refs) {
1685
1693
  this.db.exec("BEGIN IMMEDIATE");
1686
1694
  try {
1687
- const row = this.db.prepare("SELECT bytes FROM objects WHERE hash=?").get(ref.sha256);
1688
- if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1689
- if (!row) {
1690
- if (this.usage().bytes + ref.bytes + OVERHEAD > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
1691
- this.db.prepare("INSERT INTO objects VALUES(?,?)").run(ref.sha256, ref.bytes);
1695
+ let used = this.usage().bytes;
1696
+ const lookup = this.db.prepare("SELECT bytes FROM objects WHERE hash=?");
1697
+ const insert = this.db.prepare("INSERT INTO objects(hash,bytes) VALUES(?,?)");
1698
+ for (const ref of refs) {
1699
+ const row = lookup.get(ref.sha256);
1700
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1701
+ if (!row) {
1702
+ used += ref.bytes + OVERHEAD;
1703
+ if (used > this.maximumBytes) throw new Error("PUBLICATION_STORAGE_FULL");
1704
+ insert.run(ref.sha256, ref.bytes);
1705
+ }
1692
1706
  }
1693
1707
  this.db.exec("COMMIT");
1694
1708
  } catch (error) {
1695
1709
  this.db.exec("ROLLBACK");
1696
1710
  throw error;
1697
1711
  }
1698
- if (await this.has(ref)) return ref;
1712
+ }
1713
+ async put(body) {
1714
+ return this.putObject(body, false);
1715
+ }
1716
+ async putObject(body, deferDirectorySync) {
1717
+ this.active();
1718
+ assertPrivateDirectory(this.directory);
1719
+ assertPrivateDirectory(join(this.directory, "chunks"));
1720
+ if (!(body instanceof Uint8Array) || body.byteLength < 1 || body.byteLength > PUBLICATION_CHUNK_BYTES)
1721
+ throw new Error("PUBLICATION_OBJECT_TOO_LARGE");
1722
+ body = Buffer.from(body);
1723
+ const ref = { sha256: sha(body), bytes: body.byteLength };
1724
+ this.reserve([ref]);
1725
+ await this.writeObject(ref, Buffer.from(body), deferDirectorySync);
1726
+ return ref;
1727
+ }
1728
+ async writeObject(ref, body, deferDirectorySync) {
1729
+ if (await this.has(ref)) return;
1699
1730
  try {
1700
- exclusivePublish(join(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256));
1731
+ await exclusivePublish(join(this.directory, "chunks", ref.sha256), this.encrypt(Buffer.from(body), ref.sha256), deferDirectorySync);
1701
1732
  } catch (error) {
1702
1733
  if (error.code !== "EEXIST") throw error;
1703
1734
  }
1704
1735
  await this.read(ref);
1705
- return ref;
1736
+ }
1737
+ /** Same immutable chunk format and row digests, with one durable reservation
1738
+ * and directory barrier for a bounded batch. All started writes settle even
1739
+ * when one fails, so callers can safely close or retry the store. */
1740
+ async putContents(bodies) {
1741
+ return this.putContentsWith(bodies, false);
1742
+ }
1743
+ async putContentsWith(bodies, deferDirectorySync) {
1744
+ this.active();
1745
+ assertPrivateDirectory(this.directory);
1746
+ assertPrivateDirectory(join(this.directory, "chunks"));
1747
+ 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");
1748
+ const owned2 = bodies.map((body) => Buffer.from(body)), writes = /* @__PURE__ */ new Map();
1749
+ const files = owned2.map((body) => {
1750
+ const chunks = [];
1751
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
1752
+ const chunk = body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES), ref = { sha256: sha(chunk), bytes: chunk.length };
1753
+ chunks.push(ref);
1754
+ writes.set(ref.sha256, { ref, body: chunk });
1755
+ }
1756
+ return { sha256: sha(body), bytes: body.length, chunks };
1757
+ });
1758
+ const pending = [...writes.values()];
1759
+ if (!pending.length) return files;
1760
+ this.reserve(pending.map((item) => item.ref));
1761
+ const checked = await Promise.allSettled(pending.map(async (item) => ({ item, present: await this.has(item.ref) })));
1762
+ for (const result of checked) if (result.status === "rejected") throw result.reason;
1763
+ const missing = checked.flatMap((result) => result.status === "fulfilled" && !result.value.present ? [result.value.item] : []);
1764
+ const inline = missing.filter((item) => item.ref.bytes <= INLINE_BYTES), large = missing.filter((item) => item.ref.bytes > INLINE_BYTES);
1765
+ if (inline.length) {
1766
+ this.db.exec("BEGIN IMMEDIATE");
1767
+ try {
1768
+ const insert = this.db.prepare("UPDATE objects SET ciphertext=? WHERE hash=? AND ciphertext IS NULL");
1769
+ for (const item of inline) insert.run(this.encrypt(item.body, item.ref.sha256), item.ref.sha256);
1770
+ this.db.exec("COMMIT");
1771
+ } catch (error) {
1772
+ this.db.exec("ROLLBACK");
1773
+ throw error;
1774
+ }
1775
+ for (const item of inline) await this.read(item.ref);
1776
+ }
1777
+ try {
1778
+ for (let offset = 0; offset < large.length; offset += 8) {
1779
+ const results = await Promise.allSettled(large.slice(offset, offset + 8).map((item) => this.writeObject(item.ref, item.body, true)));
1780
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1781
+ }
1782
+ } finally {
1783
+ if (large.length && !deferDirectorySync) await syncDirAsync(join(this.directory, "chunks"));
1784
+ }
1785
+ return files;
1706
1786
  }
1707
1787
  async read(ref) {
1708
1788
  this.active();
1709
1789
  validateObjectRef(ref);
1790
+ if (++this.inlineReads >= 32) {
1791
+ this.inlineReads = 0;
1792
+ await setImmediate();
1793
+ this.active();
1794
+ }
1710
1795
  assertPrivateDirectory(this.directory);
1711
1796
  assertPrivateDirectory(join(this.directory, "chunks"));
1797
+ const row = this.db.prepare("SELECT bytes,ciphertext FROM objects WHERE hash=?").get(ref.sha256);
1798
+ if (row && row.bytes !== ref.bytes) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1799
+ if (row?.ciphertext !== void 0 && row.ciphertext !== null) {
1800
+ const cipher = Buffer.from(row.ciphertext);
1801
+ if (cipher.length !== ref.bytes + OVERHEAD) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1802
+ const plain = this.decrypt(cipher, ref.sha256);
1803
+ if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1804
+ return plain;
1805
+ }
1712
1806
  const path2 = join(this.directory, "chunks", ref.sha256);
1713
- const fd = openSync2(path2, constants2.O_RDONLY | noFollow);
1807
+ const file = await open(path2, constants2.O_RDONLY | noFollow);
1714
1808
  try {
1715
- const info = fstatSync2(fd);
1809
+ const info = await file.stat();
1716
1810
  if (!info.isFile() || info.size !== ref.bytes + OVERHEAD || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1717
1811
  throw new Error("PUBLICATION_OBJECT_CORRUPT");
1718
- const plain = this.decrypt(readFileSync2(fd), ref.sha256);
1812
+ const cipher = await file.readFile();
1813
+ this.active();
1814
+ const plain = this.decrypt(cipher, ref.sha256);
1719
1815
  if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
1720
1816
  return plain;
1721
1817
  } finally {
1722
- closeSync2(fd);
1818
+ await file.close();
1723
1819
  }
1724
1820
  }
1725
1821
  async has(ref) {
@@ -1734,7 +1830,10 @@ var PublicationObjects = class _PublicationObjects {
1734
1830
  async putContent(body) {
1735
1831
  body = Buffer.from(body);
1736
1832
  const chunks = [];
1737
- for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
1833
+ for (let offset = 0; offset < body.length; offset += PUBLICATION_CHUNK_BYTES) {
1834
+ chunks.push(await this.put(body.subarray(offset, offset + PUBLICATION_CHUNK_BYTES)));
1835
+ if (chunks.length % 32 === 0) await setImmediate();
1836
+ }
1738
1837
  return { bytes: body.length, sha256: sha(body), chunks };
1739
1838
  }
1740
1839
  async readContent(file, maximumBytes) {
@@ -1747,21 +1846,85 @@ var PublicationObjects = class _PublicationObjects {
1747
1846
  return body;
1748
1847
  }
1749
1848
  async captureFile(source) {
1849
+ return this.captureFileWith(source, (body) => this.put(body));
1850
+ }
1851
+ /** Every file is flushed before linking. One directory barrier makes the
1852
+ * whole batch durable before any references are returned to its caller.
1853
+ * Other puts on this handle retain their own immediate directory barrier. */
1854
+ async captureFiles(sources, onProgress, options = {}) {
1855
+ this.active();
1856
+ const chunkConcurrency = options.chunkConcurrency ?? 1;
1857
+ if (!Number.isSafeInteger(chunkConcurrency) || chunkConcurrency < 1 || chunkConcurrency > 8) throw new Error("PUBLICATION_BATCH_TOO_LARGE");
1858
+ const files = [];
1859
+ let completedBytes = 0, completedFiles = 0, wroteFiles = false;
1860
+ let pending = [];
1861
+ const put = (body) => new Promise((resolve15, reject) => {
1862
+ if (body.length > INLINE_BYTES) wroteFiles = true;
1863
+ pending.push({ body: Buffer.from(body), resolve: resolve15, reject });
1864
+ if (pending.length !== 1) return;
1865
+ queueMicrotask(() => {
1866
+ const batch = pending;
1867
+ pending = [];
1868
+ void (async () => {
1869
+ for (let offset = 0; offset < batch.length; ) {
1870
+ let end = offset, bytes = 0;
1871
+ while (end < batch.length && bytes + batch[end].body.length <= 8 * 1024 * 1024) bytes += batch[end++].body.length;
1872
+ const contents = await this.putContentsWith(batch.slice(offset, end).map((item) => item.body), true);
1873
+ for (let i = offset; i < end; i++) batch[i].resolve(contents[i - offset].chunks[0]);
1874
+ offset = end;
1875
+ }
1876
+ })().catch((error) => {
1877
+ for (const item of batch) item.reject(error);
1878
+ });
1879
+ });
1880
+ });
1881
+ try {
1882
+ for (let offset = 0; offset < sources.length; offset += 32) {
1883
+ const results = await Promise.allSettled(sources.slice(offset, offset + 32).map(async (source) => {
1884
+ let previousBytes = 0;
1885
+ const file = await this.captureFileWith(source, put, (bytes) => {
1886
+ completedBytes += bytes - previousBytes;
1887
+ previousBytes = bytes;
1888
+ onProgress?.({ completedFiles, completedBytes });
1889
+ }, chunkConcurrency);
1890
+ completedFiles++;
1891
+ if (completedFiles < sources.length) onProgress?.({ completedFiles, completedBytes });
1892
+ return file;
1893
+ }));
1894
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1895
+ for (const result of results) if (result.status === "fulfilled") files.push(result.value);
1896
+ }
1897
+ } finally {
1898
+ if (wroteFiles) await syncDirAsync(join(this.directory, "chunks"));
1899
+ }
1900
+ onProgress?.({ completedFiles: files.length, completedBytes });
1901
+ return files;
1902
+ }
1903
+ async captureFileWith(source, put, onBytes, chunkConcurrency = 1) {
1750
1904
  this.active();
1751
1905
  if (lstatSync2(source).isSymbolicLink() || realpathSync(dirname(source)) !== resolve(dirname(source))) throw new Error("SYMLINK_REFUSED");
1752
1906
  const fd = openSync2(source, constants2.O_RDONLY | noFollow);
1753
1907
  try {
1754
1908
  const before = fstatSync2(fd, { bigint: true });
1755
1909
  if (!before.isFile()) throw new Error("PUBLICATION_NOT_REGULAR_FILE");
1756
- const chunks = [], digest3 = createHash("sha256"), buffer = Buffer.alloc(PUBLICATION_CHUNK_BYTES);
1910
+ const chunks = [], digest3 = createHash("sha256"), buffer = Buffer.alloc(Math.min(PUBLICATION_CHUNK_BYTES, Number(before.size) || 1));
1757
1911
  let bytes = 0;
1758
1912
  for (; ; ) {
1759
- const count = readSync(fd, buffer, 0, buffer.length, null);
1760
- if (!count) break;
1761
- const chunk = buffer.subarray(0, count);
1762
- digest3.update(chunk);
1763
- bytes += count;
1764
- chunks.push(await this.put(chunk));
1913
+ const batch = [];
1914
+ for (let i = 0; i < chunkConcurrency; i++) {
1915
+ const count = readSync(fd, buffer, 0, buffer.length, null);
1916
+ if (!count) break;
1917
+ const chunk = Buffer.from(buffer.subarray(0, count));
1918
+ digest3.update(chunk);
1919
+ bytes += count;
1920
+ batch.push(chunk);
1921
+ }
1922
+ if (!batch.length) break;
1923
+ const results = await Promise.allSettled(batch.map(put));
1924
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1925
+ for (const result of results) if (result.status === "fulfilled") chunks.push(result.value);
1926
+ onBytes?.(bytes);
1927
+ if (chunks.length % 32 === 0) await setImmediate();
1765
1928
  }
1766
1929
  const after = fstatSync2(fd, { bigint: true }), path2 = lstatSync2(source, { bigint: true });
1767
1930
  if (path2.isSymbolicLink() || [after, path2].some((s) => ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((k) => s[k] !== before[k])) || BigInt(bytes) !== before.size) throw new Error("PUBLICATION_SOURCE_CHANGED");
@@ -1771,8 +1934,28 @@ var PublicationObjects = class _PublicationObjects {
1771
1934
  }
1772
1935
  }
1773
1936
  async restoreFile(file, destination) {
1937
+ return this.restoreFileWith(file, destination, false);
1938
+ }
1939
+ /** Private restore batches flush each file before linking it, then publish
1940
+ * the directory entries together. All started writers settle on failure. */
1941
+ async restoreFiles(files) {
1942
+ this.active();
1943
+ for (let offset = 0; offset < files.length; offset += 32) {
1944
+ const batch = files.slice(offset, offset + 32);
1945
+ const results = await Promise.allSettled(batch.map((file) => this.restoreFileWith(file.content, file.destination, true, file.mode)));
1946
+ const directories = [...new Set(batch.map((file) => dirname(file.destination)))];
1947
+ for (let i = 0; i < directories.length; i += 8) {
1948
+ const synced = await Promise.allSettled(directories.slice(i, i + 8).map(syncDirAsync));
1949
+ for (const result of synced) if (result.status === "rejected") throw result.reason;
1950
+ }
1951
+ for (const result of results) if (result.status === "rejected") throw result.reason;
1952
+ }
1953
+ }
1954
+ async restoreFileWith(file, destination, deferDirectorySync, mode = 384) {
1774
1955
  this.active();
1775
1956
  validateFileContent(file);
1957
+ if (mode !== 384 && mode !== 448) throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
1958
+ file = { ...file, chunks: file.chunks.map((ref) => ({ ...ref })) };
1776
1959
  if (realpathSync(dirname(destination)) !== resolve(dirname(destination))) throw new Error("SYMLINK_REFUSED");
1777
1960
  try {
1778
1961
  lstatSync2(destination);
@@ -1781,26 +1964,27 @@ var PublicationObjects = class _PublicationObjects {
1781
1964
  if (error.code !== "ENOENT") throw error;
1782
1965
  }
1783
1966
  const temp = join(dirname(destination), "." + randomUUID() + ".partial"), digest3 = createHash("sha256");
1784
- const fd = openSync2(temp, "wx", 384);
1967
+ const fd = await open(temp, "wx", 384);
1785
1968
  try {
1786
1969
  for (const ref of file.chunks) {
1787
1970
  const body = await this.read(ref);
1788
1971
  digest3.update(body);
1789
1972
  let offset = 0;
1790
- while (offset < body.length) offset += writeSync2(fd, body, offset, body.length - offset);
1973
+ while (offset < body.length) offset += (await fd.write(body, offset, body.length - offset)).bytesWritten;
1791
1974
  }
1792
1975
  if (digest3.digest("hex") !== file.sha256) throw new Error("PUBLICATION_FILE_CORRUPT");
1793
- fsyncSync2(fd);
1976
+ if (mode !== 384) await fd.chmod(mode);
1977
+ await fd.sync();
1794
1978
  try {
1795
- linkSync(temp, destination);
1979
+ await link(temp, destination);
1796
1980
  } catch (error) {
1797
1981
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
1798
1982
  throw error;
1799
1983
  }
1800
- syncDir(dirname(destination));
1984
+ if (!deferDirectorySync) await syncDirAsync(dirname(destination));
1801
1985
  } finally {
1802
- closeSync2(fd);
1803
- unlinkSync2(temp);
1986
+ await fd.close();
1987
+ await unlink(temp);
1804
1988
  }
1805
1989
  }
1806
1990
  close() {
@@ -1821,7 +2005,187 @@ import { isAbsolute as isAbsolute2, join as join12, resolve as resolve12 } from
1821
2005
  // src/continuity/publication.ts
1822
2006
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
1823
2007
  import { createHash as createHash2 } from "node:crypto";
1824
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
2008
+
2009
+ // src/continuity/inventory.ts
2010
+ import { constants as constants3 } from "node:fs";
2011
+ import { lstat, open as open2, readdir, realpath } from "node:fs/promises";
2012
+ import { isAbsolute, join as join2, relative, resolve as resolve2, sep } from "node:path";
2013
+ 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(" "));
2014
+ var STATE_EXCLUDED = {
2015
+ ".continuity": "local runtime control; never business state",
2016
+ ".engine.pid": "local process identity",
2017
+ ".bg-worker.pid": "local process identity",
2018
+ ".travel-restored.json": "deployment activation gate; recreated on restore",
2019
+ ".travel-enrolled.json": "local runtime enrollment; recreated per node",
2020
+ ".travel-active.json": "local activation receipt; recreated per generation",
2021
+ ".git": "source control metadata",
2022
+ ".gitignore": "source control metadata",
2023
+ ".log-baseline.txt": "local diagnostics",
2024
+ logs: "local diagnostics; not authoritative history",
2025
+ diagnostics: "local diagnostics",
2026
+ backups: "historical recovery copies; not active state",
2027
+ "package.json": "installed application metadata",
2028
+ "start.sh": "local launcher; deployment must be reviewed separately",
2029
+ node_modules: "installed dependencies",
2030
+ install: "installed application",
2031
+ CogniFold: "installed optional runtime",
2032
+ "everos-venv": "installed Python runtime",
2033
+ "ollama-models": "installed model weights"
2034
+ };
2035
+ var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
2036
+ var WORKSPACE_DIAGNOSTICS = /* @__PURE__ */ new Set([".system-prompt.txt", ".context-debug.txt"]);
2037
+ var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
2038
+ 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(" "));
2039
+ 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(" "));
2040
+ function coreReason(path2) {
2041
+ const name = path2.split("/").at(-1);
2042
+ if (CORE_OMITTED.has(name) || /(?:\.lance$|(?:^|[-.])bak(?:[-.]|$))/i.test(name)) return "optional attachments, historical copies or rebuildable indexes; outside core travel";
2043
+ 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" || path2 === "mem7/spool/intake.failed.jsonl") return "attachments, installed binaries or diagnostics; outside core travel";
2044
+ }
2045
+ function stateReason(name, options) {
2046
+ if (options.selection === "core" && coreReason(name)) return coreReason(name);
2047
+ if (options.includeStateEntries?.includes(name)) return void 0;
2048
+ return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
2049
+ }
2050
+ function knownState(name) {
2051
+ return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
2052
+ }
2053
+ async function classifyState(options) {
2054
+ const result = { included: [], excluded: [], unclassified: [] };
2055
+ for (const name of (await readdir(options.stateDir)).sort()) {
2056
+ const reason = stateReason(name, options);
2057
+ if (reason) result.excluded.push({ path: name, reason });
2058
+ 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);
2059
+ else result.unclassified.push(name);
2060
+ }
2061
+ return result;
2062
+ }
2063
+ function validateRelativePath(path2) {
2064
+ if (typeof path2 !== "string" || !path2 || path2.length > 2048 || isAbsolute(path2)) throw new Error("INVALID_ARTIFACT_PATH");
2065
+ for (const part of path2.split("/")) {
2066
+ 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)))
2067
+ throw new Error("INVALID_ARTIFACT_PATH");
2068
+ }
2069
+ }
2070
+ function isWithin(root, candidate) {
2071
+ const rel = relative(resolve2(root), resolve2(candidate));
2072
+ return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2073
+ }
2074
+ async function collectInventory(options) {
2075
+ if (options.selection !== void 0 && options.selection !== "core") throw new Error("INVALID_INVENTORY_SELECTION");
2076
+ const state = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join2(state, "workspace"));
2077
+ if (state === workspace || isWithin(workspace, state)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
2078
+ const roots = { state, workspace }, entries = [], exclusions = [], aliases = /* @__PURE__ */ new Set();
2079
+ const include = new Set(options.includeStateEntries ?? []);
2080
+ for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
2081
+ validateRelativePath(name);
2082
+ if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
2083
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2084
+ }
2085
+ for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
2086
+ for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
2087
+ validateRelativePath(name);
2088
+ if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2089
+ if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
2090
+ }
2091
+ const classification = await classifyState(options);
2092
+ if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
2093
+ async function walk(root, directory2, prefix = "", ancestors = /* @__PURE__ */ new Set()) {
2094
+ const canonical3 = await realpath(directory2);
2095
+ if (ancestors.has(canonical3)) throw new Error(`SYMLINK_CYCLE: ${root}/${prefix}`);
2096
+ const parents = new Set(ancestors);
2097
+ parents.add(canonical3);
2098
+ for (const name of (await readdir(directory2)).sort()) {
2099
+ const path2 = prefix ? prefix + "/" + name : name;
2100
+ let source = join2(directory2, name);
2101
+ if (root === "state" && source === workspace) continue;
2102
+ let reason = NESTED_EXCLUDED[name];
2103
+ if (root === "state" && prefix) reason = options.excludeStateEntries?.[path2] ?? reason;
2104
+ if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path2] ?? reason;
2105
+ if (root === "workspace" && !prefix && WORKSPACE_DIAGNOSTICS.has(name)) reason = "generated runtime diagnostics; recreated on each node";
2106
+ if (!prefix && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
2107
+ if (root === "state" && !prefix) {
2108
+ reason = stateReason(name, options);
2109
+ if (!reason && options.selection !== "core" && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
2110
+ }
2111
+ if (options.selection === "core") reason = coreReason(path2) ?? reason;
2112
+ if (reason) {
2113
+ exclusions.push({ root, path: path2, reason });
2114
+ continue;
2115
+ }
2116
+ validateRelativePath(path2);
2117
+ const key = root + "/" + path2.normalize("NFC").toLowerCase();
2118
+ if (aliases.has(key)) throw new Error("PORTABLE_PATH_COLLISION");
2119
+ aliases.add(key);
2120
+ let info = await lstat(source, { bigint: true }), linkSignature = "";
2121
+ if (options.selection === "core" && root === "workspace" && !prefix && !CORE_DIRECTORIES.has(name) && (info.isDirectory() || info.isSymbolicLink() && !/\.[a-z0-9]+$/i.test(name))) {
2122
+ exclusions.push({ root, path: path2, reason: "optional workspace material; outside core travel" });
2123
+ continue;
2124
+ }
2125
+ if (info.isSymbolicLink()) {
2126
+ linkSignature = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":") + ":";
2127
+ try {
2128
+ source = await realpath(source);
2129
+ } catch {
2130
+ throw new Error(`SYMLINK_REFUSED: ${root}/${path2}`);
2131
+ }
2132
+ info = await lstat(source, { bigint: true });
2133
+ linkSignature += source + ":";
2134
+ }
2135
+ if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
2136
+ if (options.selection === "core" && root === "workspace" && !prefix && info.isDirectory() && !CORE_DIRECTORIES.has(name)) {
2137
+ exclusions.push({ root, path: path2, reason: "optional workspace material; outside core travel" });
2138
+ continue;
2139
+ }
2140
+ if (info.isDirectory()) {
2141
+ try {
2142
+ const marker = await lstat(join2(source, "pyvenv.cfg"));
2143
+ if (marker.isFile() && !marker.isSymbolicLink()) {
2144
+ exclusions.push({ root, path: path2, reason: "installed Python virtual environment; rebuild for the target platform" });
2145
+ continue;
2146
+ }
2147
+ } catch (error) {
2148
+ if (error.code !== "ENOENT") throw error;
2149
+ }
2150
+ }
2151
+ const entry = {
2152
+ root,
2153
+ path: path2,
2154
+ source,
2155
+ kind: info.isDirectory() ? "directory" : "file",
2156
+ bytes: Number(info.size),
2157
+ mode: Number(info.mode) & 448,
2158
+ signature: linkSignature + [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
2159
+ };
2160
+ entries.push(entry);
2161
+ if (info.isDirectory()) await walk(root, source, path2, parents);
2162
+ else {
2163
+ const h = await open2(source, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
2164
+ const header = Buffer.alloc(16);
2165
+ try {
2166
+ await h.read(header, 0, 16, 0);
2167
+ } finally {
2168
+ await h.close();
2169
+ }
2170
+ if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
2171
+ else if (info.size > 0n && /\.(db|sqlite|sqlite3)$/i.test(path2)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path2}`);
2172
+ }
2173
+ }
2174
+ }
2175
+ await walk("state", state);
2176
+ await walk("workspace", workspace);
2177
+ const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
2178
+ for (const entry of entries) {
2179
+ if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
2180
+ if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
2181
+ entry.kind = "sidecar";
2182
+ }
2183
+ }
2184
+ return { entries, exclusions, roots };
2185
+ }
2186
+
2187
+ // src/continuity/publication.ts
2188
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
1825
2189
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
1826
2190
  var ZERO = "0".repeat(64);
1827
2191
  var HASH2 = /^[a-f0-9]{64}$/;
@@ -1862,8 +2226,12 @@ function normalizePublicationProfile(value) {
1862
2226
  return Object.freeze(profile);
1863
2227
  }
1864
2228
  function validatePublicationPath(path2) {
1865
- if (typeof path2 !== "string" || !path2 || path2.length > 2048 || path2.normalize("NFC") !== path2 || /[\x00-\x1f<>:"|?*\\]/.test(path2) || path2.split("/").some((p) => !p || p === "." || p === ".." || /[. ]$/.test(p) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)))
2229
+ if (typeof path2 !== "string" || path2.normalize("NFC") !== path2) throw new Error("PUBLICATION_INVALID_PATH");
2230
+ try {
2231
+ validateRelativePath(path2);
2232
+ } catch {
1866
2233
  throw new Error("PUBLICATION_INVALID_PATH");
2234
+ }
1867
2235
  }
1868
2236
  function normalizePublication(value) {
1869
2237
  if (!value || value.format !== "engine7-publication-v1" || !natural(value.sequence) || !value.sequence || !HASH2.test(value.parentDigest) || !natural(value.deletionWatermark) || !Array.isArray(value.databases) || !Array.isArray(value.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
@@ -1939,8 +2307,8 @@ function packReplicationCommit(commit) {
1939
2307
  // src/continuity/runtime-tree-source.ts
1940
2308
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
1941
2309
  import { createHash as createHash3 } from "node:crypto";
1942
- import { existsSync, writeFileSync as writeFileSync2, openSync as openSync3, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "node:fs";
1943
- import { join as join2, resolve as resolve2 } from "node:path";
2310
+ import { existsSync, writeFileSync, openSync as openSync3, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "node:fs";
2311
+ import { join as join3, resolve as resolve3 } from "node:path";
1944
2312
  var ZERO2 = "0".repeat(64);
1945
2313
  var HASH3 = /^[a-f0-9]{64}$/;
1946
2314
  var schema = [
@@ -1972,7 +2340,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
1972
2340
  if (JSON.stringify(this.profile.identity) !== JSON.stringify(this.objects.identity)) throw new Error("TREE_SOURCE_PROFILE_MISMATCH");
1973
2341
  this.maximumBytes = options.maximumBytes ?? 64 * 1024 * 1024;
1974
2342
  if (!Number.isSafeInteger(this.maximumBytes) || this.maximumBytes < 1) throw new Error("TREE_SOURCE_INVALID_LIMIT");
1975
- const directory2 = resolve2(options.directory), marker = join2(directory2, "source.json"), file = join2(directory2, "trees.sqlite");
2343
+ const directory2 = resolve3(options.directory), marker = join3(directory2, "source.json"), file = join3(directory2, "trees.sqlite");
1976
2344
  if (options.initialize) preparePrivateDirectory(directory2);
1977
2345
  else {
1978
2346
  try {
@@ -2003,7 +2371,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
2003
2371
  this.db.exec("ROLLBACK");
2004
2372
  throw error;
2005
2373
  }
2006
- writeFileSync2(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
2374
+ writeFileSync(marker, JSON.stringify({ format: "engine7-runtime-tree-source-v1", profile: this.profile }), { flag: "wx", mode: 384, flush: true });
2007
2375
  if (process.platform !== "win32") {
2008
2376
  const fd = openSync3(directory2, "r");
2009
2377
  try {
@@ -2121,7 +2489,7 @@ var RuntimeTreeSource = class _RuntimeTreeSource {
2121
2489
  // src/continuity/runtime-publication-source.ts
2122
2490
  import { DatabaseSync as DatabaseSync11 } from "node:sqlite";
2123
2491
  import { createHash as createHash10 } from "node:crypto";
2124
- import { existsSync as existsSync4, lstatSync as lstatSync10, writeFileSync as writeFileSync8, openSync as openSync9, closeSync as closeSync9, fsyncSync as fsyncSync8 } from "node:fs";
2492
+ import { existsSync as existsSync4, lstatSync as lstatSync10, writeFileSync as writeFileSync7, openSync as openSync9, closeSync as closeSync9, fsyncSync as fsyncSync8 } from "node:fs";
2125
2493
  import { join as join11, resolve as resolve11 } from "node:path";
2126
2494
 
2127
2495
  // src/continuity/runtime-h-capture.ts
@@ -2133,152 +2501,6 @@ import { resolve as resolve10, relative as relative5 } from "node:path";
2133
2501
  // src/continuity/runtime-files.ts
2134
2502
  import { lstatSync as lstatSync6, realpathSync as realpathSync3 } from "node:fs";
2135
2503
  import { relative as relative2, resolve as resolve7 } from "node:path";
2136
-
2137
- // src/continuity/inventory.ts
2138
- import { constants as constants3 } from "node:fs";
2139
- import { lstat, open, readdir, realpath } from "node:fs/promises";
2140
- import { isAbsolute, join as join3, relative, resolve as resolve3, sep } from "node:path";
2141
- 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(" "));
2142
- var STATE_EXCLUDED = {
2143
- ".continuity": "local runtime control; never business state",
2144
- ".engine.pid": "local process identity",
2145
- ".bg-worker.pid": "local process identity",
2146
- ".travel-restored.json": "deployment activation gate; recreated on restore",
2147
- ".travel-enrolled.json": "local runtime enrollment; recreated per node",
2148
- ".travel-active.json": "local activation receipt; recreated per generation",
2149
- ".git": "source control metadata",
2150
- ".gitignore": "source control metadata",
2151
- ".log-baseline.txt": "local diagnostics",
2152
- logs: "local diagnostics; not authoritative history",
2153
- diagnostics: "local diagnostics",
2154
- backups: "historical recovery copies; not active state",
2155
- "package.json": "installed application metadata",
2156
- "start.sh": "local launcher; deployment must be reviewed separately",
2157
- node_modules: "installed dependencies",
2158
- install: "installed application",
2159
- CogniFold: "installed optional runtime",
2160
- "everos-venv": "installed Python runtime",
2161
- "ollama-models": "installed model weights"
2162
- };
2163
- var NESTED_EXCLUDED = { ".git": "source control metadata", node_modules: "installed dependencies", __pycache__: "Python bytecode cache" };
2164
- var RUNTIME_CONTROL = /* @__PURE__ */ new Set([".continuity", ".engine.pid", ".bg-worker.pid", ".travel-restored.json", ".travel-enrolled.json", ".travel-active.json"]);
2165
- function stateReason(name, options) {
2166
- if (options.includeStateEntries?.includes(name)) return void 0;
2167
- return options.excludeStateEntries?.[name] ?? STATE_EXCLUDED[name] ?? (/^engines\.json\.bak(?:-|$)/.test(name) ? "historical host registry backup" : void 0);
2168
- }
2169
- function knownState(name) {
2170
- return STATE.has(name) || /^weixin-[^/]+\.json$/.test(name);
2171
- }
2172
- async function classifyState(options) {
2173
- const result = { included: [], excluded: [], unclassified: [] };
2174
- for (const name of (await readdir(options.stateDir)).sort()) {
2175
- const reason = stateReason(name, options);
2176
- if (reason) result.excluded.push({ path: name, reason });
2177
- else if (knownState(name) || options.includeStateEntries?.includes(name) || resolve3(options.stateDir, name) === resolve3(options.workspace ?? join3(options.stateDir, "workspace"))) result.included.push(name);
2178
- else result.unclassified.push(name);
2179
- }
2180
- return result;
2181
- }
2182
- function validateRelativePath(path2) {
2183
- if (typeof path2 !== "string" || !path2 || path2.length > 2048 || path2.includes("\\") || isAbsolute(path2)) throw new Error("INVALID_ARTIFACT_PATH");
2184
- for (const part of path2.split("/")) {
2185
- 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)
2186
- throw new Error("INVALID_ARTIFACT_PATH");
2187
- }
2188
- }
2189
- function isWithin(root, candidate) {
2190
- const rel = relative(resolve3(root), resolve3(candidate));
2191
- return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
2192
- }
2193
- async function collectInventory(options) {
2194
- const state = await realpath(options.stateDir), workspace = await realpath(options.workspace ?? join3(state, "workspace"));
2195
- if (state === workspace || isWithin(workspace, state)) throw new Error("OVERLAPPING_SOURCE_ROOTS");
2196
- const roots = { state, workspace }, entries = [], exclusions = [], aliases = /* @__PURE__ */ new Set();
2197
- const include = new Set(options.includeStateEntries ?? []);
2198
- for (const name of [...include, ...Object.keys(options.excludeStateEntries ?? {})]) {
2199
- validateRelativePath(name);
2200
- if (include.has(name) && name.includes("/")) throw new Error("TOP_LEVEL_CLASSIFICATION_REQUIRED");
2201
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2202
- }
2203
- for (const reason of Object.values(options.excludeStateEntries ?? {})) if (!reason.trim()) throw new Error("EXCLUSION_REASON_REQUIRED");
2204
- for (const [name, reason] of Object.entries(options.excludeWorkspaceEntries ?? {})) {
2205
- validateRelativePath(name);
2206
- if (RUNTIME_CONTROL.has(name.split("/")[0])) throw new Error("RESERVED_STATE_CLASSIFICATION");
2207
- if (!reason.trim()) throw new Error("WORKSPACE_EXCLUSION_REASON_REQUIRED");
2208
- }
2209
- const classification = await classifyState(options);
2210
- if (classification.unclassified.length) throw new Error(`UNCLASSIFIED_STATE: ${classification.unclassified.join(", ")}`);
2211
- async function walk(root, directory2, prefix = "") {
2212
- for (const name of (await readdir(directory2)).sort()) {
2213
- const path2 = prefix ? prefix + "/" + name : name, source = join3(directory2, name);
2214
- if (root === "state" && source === workspace) continue;
2215
- let reason = NESTED_EXCLUDED[name];
2216
- if (root === "state" && prefix) reason = options.excludeStateEntries?.[path2] ?? reason;
2217
- if (root === "workspace") reason = options.excludeWorkspaceEntries?.[path2] ?? reason;
2218
- if (!prefix && RUNTIME_CONTROL.has(name)) reason = STATE_EXCLUDED[name];
2219
- if (root === "state" && !prefix) {
2220
- reason = stateReason(name, options);
2221
- if (!reason && !knownState(name) && !include.has(name)) throw new Error(`UNCLASSIFIED_STATE: ${name}`);
2222
- }
2223
- if (reason) {
2224
- exclusions.push({ root, path: path2, reason });
2225
- continue;
2226
- }
2227
- validateRelativePath(path2);
2228
- const key = root + "/" + path2.normalize("NFC").toLowerCase();
2229
- if (aliases.has(key)) throw new Error("PORTABLE_PATH_COLLISION");
2230
- aliases.add(key);
2231
- const info = await lstat(source, { bigint: true });
2232
- if (info.isSymbolicLink()) throw new Error(`SYMLINK_REFUSED: ${root}/${path2}`);
2233
- if (!info.isDirectory() && !info.isFile()) throw new Error("SPECIAL_FILE_REFUSED");
2234
- if (info.isDirectory()) {
2235
- try {
2236
- const marker = await lstat(join3(source, "pyvenv.cfg"));
2237
- if (marker.isFile() && !marker.isSymbolicLink()) {
2238
- exclusions.push({ root, path: path2, reason: "installed Python virtual environment; rebuild for the target platform" });
2239
- continue;
2240
- }
2241
- } catch (error) {
2242
- if (error.code !== "ENOENT") throw error;
2243
- }
2244
- }
2245
- const entry = {
2246
- root,
2247
- path: path2,
2248
- source,
2249
- kind: info.isDirectory() ? "directory" : "file",
2250
- bytes: Number(info.size),
2251
- mode: Number(info.mode) & 448,
2252
- signature: [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":")
2253
- };
2254
- entries.push(entry);
2255
- if (info.isDirectory()) await walk(root, source, path2);
2256
- else {
2257
- const h = await open(source, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
2258
- const header = Buffer.alloc(16);
2259
- try {
2260
- await h.read(header, 0, 16, 0);
2261
- } finally {
2262
- await h.close();
2263
- }
2264
- if (header.equals(Buffer.from("SQLite format 3\0"))) entry.kind = "sqlite";
2265
- else if (/\.(db|sqlite|sqlite3)$/i.test(path2)) throw new Error(`INVALID_SQLITE_FILE: ${root}/${path2}`);
2266
- }
2267
- }
2268
- }
2269
- await walk("state", state);
2270
- await walk("workspace", workspace);
2271
- const sqlite2 = new Set(entries.filter((e) => e.kind === "sqlite").map((e) => e.source));
2272
- for (const entry of entries) {
2273
- if (entry.kind === "file" && /-(wal|shm|journal)$/.test(entry.source)) {
2274
- if (!sqlite2.has(entry.source.replace(/-(wal|shm|journal)$/, ""))) throw new Error(`UNOWNED_SQLITE_SIDECAR: ${entry.root}/${entry.path}`);
2275
- entry.kind = "sidecar";
2276
- }
2277
- }
2278
- return { entries, exclusions, roots };
2279
- }
2280
-
2281
- // src/continuity/runtime-files.ts
2282
2504
  import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
2283
2505
  import { createHash as createHash5 } from "node:crypto";
2284
2506
 
@@ -2286,7 +2508,7 @@ import { createHash as createHash5 } from "node:crypto";
2286
2508
  import { basename as basename3, dirname as dirname5, resolve as resolve6 } from "node:path";
2287
2509
 
2288
2510
  // src/continuity/mem7-replication.ts
2289
- import { closeSync as closeSync5, fsyncSync as fsyncSync5, lstatSync as lstatSync4, openSync as openSync5, writeFileSync as writeFileSync4 } from "node:fs";
2511
+ import { closeSync as closeSync5, fsyncSync as fsyncSync5, lstatSync as lstatSync4, openSync as openSync5, writeFileSync as writeFileSync3 } from "node:fs";
2290
2512
  import { dirname as dirname3, join as join5 } from "node:path";
2291
2513
  init_sqlite_replication();
2292
2514
  var location = (stateDir) => join5(stateDir, ".continuity", "mem7-replication.json");
@@ -2344,6 +2566,7 @@ function readSQLiteStoreRegistration(place) {
2344
2566
 
2345
2567
  // src/continuity/runtime-files.ts
2346
2568
  init_runtime_replication();
2569
+ import { setImmediate as setImmediate2 } from "node:timers/promises";
2347
2570
  async function runtimeFileEntries(options) {
2348
2571
  const state = resolve7(options.inventory.stateDir), workspace = resolve7(options.inventory.workspace ?? state + "/workspace");
2349
2572
  if (realpathSync3(state) !== state || realpathSync3(workspace) !== workspace) throw new Error("SYMLINK_REFUSED");
@@ -2398,10 +2621,26 @@ async function captureRuntimeFiles(options) {
2398
2621
  { id: options.workspaceTreeId, files: [], directories: [] }
2399
2622
  ];
2400
2623
  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");
2401
- for (const entry of before) {
2624
+ const files = before.filter((entry) => entry.kind !== "directory");
2625
+ const progress = { completedFiles: 0, totalFiles: files.length, completedBytes: 0, totalBytes: files.reduce((n, e) => n + e.bytes, 0) };
2626
+ options.onProgress?.({ ...progress });
2627
+ for (const entry of before.filter((entry2) => entry2.kind === "directory")) {
2402
2628
  const tree = trees[entry.root === "state" ? 0 : 1];
2403
- if (entry.kind === "directory") tree.directories.push(entry.path);
2404
- else tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content: await options.objects.captureFile(entry.source) });
2629
+ tree.directories.push(entry.path);
2630
+ }
2631
+ for (let offset = 0; offset < files.length; offset += 32) {
2632
+ const batch = files.slice(offset, offset + 32);
2633
+ const bytesBefore = progress.completedBytes;
2634
+ const contents = await options.objects.captureFiles(batch.map((entry) => entry.source), (value) => {
2635
+ progress.completedFiles = offset + value.completedFiles;
2636
+ progress.completedBytes = bytesBefore + value.completedBytes;
2637
+ options.onProgress?.({ ...progress });
2638
+ });
2639
+ for (const [index, entry] of batch.entries()) {
2640
+ const tree = trees[entry.root === "state" ? 0 : 1], content = contents[index];
2641
+ tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content });
2642
+ }
2643
+ await setImmediate2();
2405
2644
  }
2406
2645
  if (JSON.stringify(signatures(before)) !== JSON.stringify(signatures(await runtimeFileEntries(options)))) throw new Error("PUBLICATION_SOURCE_CHANGED");
2407
2646
  return trees;
@@ -2412,7 +2651,7 @@ function resolvePath(path2) {
2412
2651
 
2413
2652
  // src/continuity/lance-publication.ts
2414
2653
  import { createHash as createHash8 } from "node:crypto";
2415
- import { lstatSync as lstatSync8, readdirSync, realpathSync as realpathSync5, mkdirSync as mkdirSync6, writeFileSync as writeFileSync7, openSync as openSync8, closeSync as closeSync8, fsyncSync as fsyncSync7, chmodSync } from "node:fs";
2654
+ import { lstatSync as lstatSync8, readdirSync, realpathSync as realpathSync5, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6, openSync as openSync8, closeSync as closeSync8, fsyncSync as fsyncSync7, chmodSync } from "node:fs";
2416
2655
  import { join as join9, resolve as resolve8, dirname as dirname7, relative as relative3 } from "node:path";
2417
2656
  import { createRequire as createRequire3 } from "node:module";
2418
2657
 
@@ -2441,7 +2680,7 @@ init_scope();
2441
2680
 
2442
2681
  // src/mem7/core/change-feed.ts
2443
2682
  import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
2444
- import { existsSync as existsSync3, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync6 } from "node:fs";
2683
+ import { existsSync as existsSync3, readFileSync as readFileSync5, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync5 } from "node:fs";
2445
2684
 
2446
2685
  // src/mem7/core/state/temporal.ts
2447
2686
  function canonicalJson(value) {
@@ -2648,7 +2887,7 @@ var ChangeFeed = class _ChangeFeed {
2648
2887
  let ledger = {};
2649
2888
  if (ledgerPath) {
2650
2889
  try {
2651
- ledger = JSON.parse(readFileSync6(ledgerPath, "utf8"))?.heals ?? {};
2890
+ ledger = JSON.parse(readFileSync5(ledgerPath, "utf8"))?.heals ?? {};
2652
2891
  } catch {
2653
2892
  }
2654
2893
  if (Number.isFinite(ledger[key])) {
@@ -2673,11 +2912,11 @@ var ChangeFeed = class _ChangeFeed {
2673
2912
  retained[key] = now2;
2674
2913
  const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
2675
2914
  try {
2676
- writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
2915
+ writeFileSync5(temp, JSON.stringify({ version: 1, heals: retained }));
2677
2916
  renameSync2(temp, ledgerPath);
2678
2917
  } catch (error) {
2679
2918
  try {
2680
- if (existsSync3(temp)) unlinkSync3(temp);
2919
+ if (existsSync3(temp)) unlinkSync2(temp);
2681
2920
  } catch {
2682
2921
  }
2683
2922
  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}`);
@@ -2804,10 +3043,10 @@ init_read_guard();
2804
3043
  init_scope();
2805
3044
 
2806
3045
  // src/mem7/core/episode.ts
2807
- import { readFileSync as readFileSync7 } from "node:fs";
3046
+ import { readFileSync as readFileSync6 } from "node:fs";
2808
3047
  import { join as join8, dirname as dirname6 } from "node:path";
2809
3048
  import { fileURLToPath } from "node:url";
2810
- var PROMPT = readFileSync7(join8(dirname6(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
3049
+ var PROMPT = readFileSync6(join8(dirname6(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
2811
3050
 
2812
3051
  // src/mem7/core/relationship-cognition.ts
2813
3052
  init_scope();
@@ -3098,14 +3337,28 @@ async function captureLancePublication(options) {
3098
3337
  const batchTable = new arrow.Table(batch);
3099
3338
  for (let start = 0; start < batchTable.numRows; start += batchRows) {
3100
3339
  const page = batchTable.slice(start, start + batchRows);
3340
+ let pending = [], pendingBytes = 0;
3341
+ const flush = async () => {
3342
+ if (!pending.length) return;
3343
+ const contents = await options.objects.putContents(pending.map((row) => row.bytes));
3344
+ for (let i = 0; i < pending.length; i++) tree.files.push({ path: pending[i].path, mode: 384, content: contents[i] });
3345
+ pending = [];
3346
+ pendingBytes = 0;
3347
+ };
3101
3348
  for (let index = 0; index < page.numRows; index++) {
3102
3349
  const one = page.slice(index, index + 1), path2 = rowPath(kind, one.getChild("id").get(0));
3103
3350
  if (seen.has(path2)) throw new Error("LANCE_PUBLICATION_DUPLICATE_ROW");
3104
3351
  seen.add(path2);
3105
3352
  const bytes = arrow.tableToIPC(one, "stream");
3106
- if (bytes.length > ROW_BYTES || tree.files.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
3107
- tree.files.push({ path: path2, mode: 384, content: await options.objects.putContent(bytes) });
3353
+ if (bytes.length > ROW_BYTES || tree.files.length + pending.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
3354
+ if (pending.length === 128 || pendingBytes + bytes.length > 8 * 1024 * 1024) await flush();
3355
+ if (bytes.length > 8 * 1024 * 1024) tree.files.push({ path: path2, mode: 384, content: await options.objects.putContent(bytes) });
3356
+ else {
3357
+ pending.push({ path: path2, bytes });
3358
+ pendingBytes += bytes.length;
3359
+ }
3108
3360
  }
3361
+ await flush();
3109
3362
  }
3110
3363
  }
3111
3364
  if (seen.size !== total) throw new Error("LANCE_PUBLICATION_ROW_COUNT_MISMATCH");
@@ -3333,7 +3586,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
3333
3586
  }
3334
3587
  sender.exec(senderSchema);
3335
3588
  sender.prepare("INSERT INTO sender VALUES(1,?,?)").run(JSON.stringify(this.profile), this.layoutDigest);
3336
- writeFileSync8(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
3589
+ writeFileSync7(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
3337
3590
  if (process.platform !== "win32") {
3338
3591
  const fd = openSync9(this.directory, "r");
3339
3592
  try {
@@ -3362,7 +3615,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
3362
3615
  static async open(options) {
3363
3616
  const source = new _RuntimePublicationSource(options);
3364
3617
  try {
3365
- if (source.head().sequence) await source.read(source.head().sequence);
3618
+ if (source.head().sequence) await source.readManifest(source.head().sequence);
3366
3619
  return source;
3367
3620
  } catch (error) {
3368
3621
  source.close();
@@ -3413,6 +3666,15 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
3413
3666
  };
3414
3667
  }
3415
3668
  async read(sequence) {
3669
+ return this.readPrepared(sequence, true);
3670
+ }
3671
+ /** Ancestry uses authenticated H metadata; payload availability is checked
3672
+ * when actual objects are transferred or restored, not for every old H. */
3673
+ async readManifest(sequence) {
3674
+ const { digest: digest3, manifest } = await this.readPrepared(sequence, false);
3675
+ return { digest: digest3, manifest };
3676
+ }
3677
+ async readPrepared(sequence, verifyDependencies) {
3416
3678
  const row = this.entry(sequence), ref = JSON.parse(row.content);
3417
3679
  validateFileContent(ref);
3418
3680
  const manifest = normalizePublication(JSON.parse((await this.objects.readContent(ref, PUBLICATION_MANIFEST_BYTES)).toString()));
@@ -3420,7 +3682,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
3420
3682
  if (manifest.sequence !== sequence || !same2(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");
3421
3683
  const dependencies = JSON.parse(row.dependencies);
3422
3684
  if (!Array.isArray(dependencies) || !same2(dependencies.map((d) => d.treeId).sort(), this.profile.trees.map((t) => t.id))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
3423
- for (const d of dependencies) {
3685
+ if (verifyDependencies) for (const d of dependencies) {
3424
3686
  const tree = await this.trees.read(d.treeId, d.sequence);
3425
3687
  if (tree.digest !== d.digest || !same2(tree.tree, manifest.trees.find((t) => t.id === d.treeId))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
3426
3688
  }
@@ -3433,12 +3695,18 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
3433
3695
  async prepare(options) {
3434
3696
  return this.prepareCapture(options, () => captureRuntimeH(options));
3435
3697
  }
3698
+ /** A first full baseline already lives in the bounded encrypted object store
3699
+ * and native SQLite snapshots. Only its envelope occupies the increment queue. */
3700
+ async prepareInitial(options) {
3701
+ if (this.control().head !== 0) throw new Error("RUNTIME_PUBLICATION_INITIAL_ALREADY_PREPARED");
3702
+ return this.prepareCapture(options, () => captureRuntimeH(options), true);
3703
+ }
3436
3704
  /** The source business stores stay read-only and writer exclusion remains
3437
3705
  * held until the caller durably seals its backup and archive receipt. */
3438
3706
  async withStoppedPreparation(options, operation) {
3439
3707
  return withStoppedRuntimeH(options, async (parts) => operation(await this.prepareCapture(options, async () => parts)));
3440
3708
  }
3441
- async prepareCapture(options, capture2) {
3709
+ async prepareCapture(options, capture2, initial = false) {
3442
3710
  const c = this.control(), pending = this.status();
3443
3711
  if (!same2(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
3444
3712
  if (pending.pendingCheckpoints >= this.maximumPendingCheckpoints || pending.pendingBytes >= this.maximumPendingBytes) throw new Error("RUNTIME_PUBLICATION_QUEUE_FULL");
@@ -3470,11 +3738,11 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
3470
3738
  for (const tree of prepared.manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) known.add(ref.sha256);
3471
3739
  }
3472
3740
  let bytes = encoded.length + Buffer.byteLength(JSON.stringify(dependencies));
3473
- for (const tree of manifest.trees) for (const file of tree.files) for (const ref of file.content.chunks) if (!known.has(ref.sha256)) {
3741
+ 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)) {
3474
3742
  known.add(ref.sha256);
3475
3743
  bytes += ref.bytes;
3476
3744
  }
3477
- for (const d of manifest.databases) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
3745
+ for (const d of manifest.databases) if (!initial) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
3478
3746
  old?.manifest.databases.find((previous) => previous.databaseId === d.databaseId).head.sequence ?? 0,
3479
3747
  d.head.sequence
3480
3748
  );
@@ -3723,7 +3991,7 @@ async function openRuntimeGenerationSource(options) {
3723
3991
  lanceStores,
3724
3992
  deletionWatermark: runtime.deletionFloor(),
3725
3993
  files: {
3726
- inventory: { stateDir, workspace, includeStateEntries: layout.includedStateEntries },
3994
+ inventory: { stateDir, workspace, selection: layout.inventorySelection, includeStateEntries: layout.includedStateEntries },
3727
3995
  objects: options.objects,
3728
3996
  databaseFiles: Object.values(databases).map((db) => db.file),
3729
3997
  immutableDatabaseFiles: (layout.immutableDatabases ?? []).map((path2) => {
@@ -3746,18 +4014,18 @@ async function openRuntimeGenerationSource(options) {
3746
4014
 
3747
4015
  // src/continuity/recovery-archive.ts
3748
4016
  import { DatabaseSync as DatabaseSync13, backup } from "node:sqlite";
3749
- import { existsSync as existsSync6, lstatSync as lstatSync12, mkdtempSync, rmSync, writeFileSync as writeFileSync9, chmodSync as chmodSync2 } from "node:fs";
4017
+ import { existsSync as existsSync6, lstatSync as lstatSync12, mkdtempSync, rmSync, writeFileSync as writeFileSync8, chmodSync as chmodSync2 } from "node:fs";
3750
4018
  import { join as join13, resolve as resolve13 } from "node:path";
3751
4019
  init_sqlite_replication();
3752
4020
 
3753
4021
  // src/continuity/crypto.ts
3754
4022
  import { constants as constants7, createWriteStream, openSync as openSync10 } from "node:fs";
3755
- import { open as open2, lstat as lstat2, link, unlink, writeFile, appendFile } from "node:fs/promises";
4023
+ import { open as open3, lstat as lstat2, link as link2, unlink as unlink2, writeFile as writeFile2, appendFile } from "node:fs/promises";
3756
4024
  var MAGIC2 = Buffer.from("E7OBJ001");
3757
4025
  var HEADER_SIZE = MAGIC2.length + 12;
3758
4026
  async function syncDirectory(directory2) {
3759
4027
  if (process.platform === "win32") return;
3760
- const handle = await open2(directory2, constants7.O_RDONLY);
4028
+ const handle = await open3(directory2, constants7.O_RDONLY);
3761
4029
  try {
3762
4030
  await handle.sync();
3763
4031
  } finally {
@@ -3802,7 +4070,8 @@ async function currentHDeletionCheckAsync(raw, control2, captured) {
3802
4070
  var schema3 = "CREATE TABLE archives(id TEXT PRIMARY KEY,kind TEXT NOT NULL,manifest_digest TEXT NOT NULL,content TEXT NOT NULL)";
3803
4071
  var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
3804
4072
  var FORMAT = "engine7-runtime-recovery-archive-v1";
3805
- var MAX_METADATA = 16 * 1024 * 1024;
4073
+ var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
4074
+ var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
3806
4075
  var same4 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
3807
4076
  var incarnation2 = (file) => {
3808
4077
  const s = lstatSync12(file, { bigint: true });
@@ -3846,14 +4115,17 @@ async function checkRecoveryDeletionAsync(manifest, current2, previous = 0) {
3846
4115
  const floor = await current2();
3847
4116
  return checkRecoveryDeletion(manifest, () => floor, previous);
3848
4117
  }
3849
- function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2) {
4118
+ function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2, scan = true) {
3850
4119
  const d = manifest.databases.find((d2) => d2.databaseId === databaseId), p = manifest.profile;
3851
4120
  const control2 = db.prepare("SELECT binding,head,digest,schema_hash FROM e7_replication_control WHERE role=?").get(role);
3852
4121
  const binding = JSON.stringify([p.identity.tenantId, p.identity.companionId, p.identity.seatId, databaseId, p.baselineId, p.epoch]);
3853
4122
  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");
3854
4123
  const actual = sqliteReplicationSchemaHash(db);
3855
- const checks = db.prepare("PRAGMA quick_check").all();
3856
- if (actual !== control2.schema_hash || checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
4124
+ if (actual !== control2.schema_hash) throw new Error("RECOVERY_DATABASE_CORRUPT");
4125
+ if (scan) {
4126
+ const checks = db.prepare("PRAGMA quick_check").all();
4127
+ if (checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
4128
+ }
3857
4129
  return actual;
3858
4130
  }
3859
4131
  var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
@@ -3886,7 +4158,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3886
4158
  this.db.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
3887
4159
  if (fresh) {
3888
4160
  this.db.exec(schema3);
3889
- writeFileSync9(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
4161
+ writeFileSync8(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
3890
4162
  }
3891
4163
  if (!same4(this.db.prepare("SELECT sql FROM sqlite_master WHERE type='table'").all().map((r) => String(r.sql)), [schema3]) || this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("RECOVERY_ARCHIVE_REQUIRED");
3892
4164
  this.identity = incarnation2(this.file);
@@ -3995,25 +4267,37 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
3995
4267
  if (old) {
3996
4268
  if (old.kind !== kind || old.manifest_digest !== digest3) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
3997
4269
  const entry = await this.read(id2);
3998
- for (const d of entry.databases) await verifyContent(this.objects, d.content);
3999
- for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
4270
+ if (options.verifyRetained !== false) {
4271
+ for (const d of entry.databases) await verifyContent(this.objects, d.content);
4272
+ for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
4273
+ }
4000
4274
  await verify2();
4001
4275
  return entry.receipt;
4002
4276
  }
4003
4277
  let publication;
4004
4278
  if (kind !== "LOCAL") {
4005
- const status = await options.receiver?.status();
4279
+ const status = await options.receiver?.status(options.verifyRetained !== false);
4006
4280
  if (!status || !currentHCheck && !status.dataReady || status.published?.digest !== digest3 || !same4(status.profile, manifest.profile)) throw new Error("RECOVERY_COMMON_NOT_READY");
4007
4281
  publication = status.published;
4008
4282
  }
4009
4283
  if (!same4(Object.keys(options.databases).sort(), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
4010
4284
  const role = kind === "LOCAL" ? "source" : "replica";
4011
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
4285
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
4286
+ 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;
4287
+ const retained = sibling ? await this.read(String(sibling.id)) : void 0;
4288
+ if (retained) {
4289
+ validateRecoveryArchiveEntry(retained, this.objects.identity);
4290
+ if (!same4(retained.manifest, manifest) || !same4(retained.publication, publication) || retained.databases.some((d) => d.role !== "replica")) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
4291
+ }
4012
4292
  const temporary = mkdtempSync(join13(this.directory, ".capture-"));
4013
4293
  try {
4014
- writeFileSync9(join13(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
4294
+ writeFileSync8(join13(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
4015
4295
  const databases = [];
4016
- for (let offset = 0; offset < manifest.databases.length; offset += 6) {
4296
+ if (retained) {
4297
+ if (options.verifyRetained !== false) for (const database of retained.databases) await verifyContent(this.objects, database.content);
4298
+ databases.push(...retained.databases);
4299
+ }
4300
+ for (let offset = 0; !retained && offset < manifest.databases.length; offset += 6) {
4017
4301
  const results = await Promise.allSettled(manifest.databases.slice(offset, offset + 6).map(async (d) => {
4018
4302
  floor = Math.max(floor, await verify2());
4019
4303
  const file = join13(temporary, d.databaseId + ".sqlite");
@@ -4022,11 +4306,11 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
4022
4306
  const copy = new DatabaseSync13(file, { readOnly: true });
4023
4307
  let schemaHash2;
4024
4308
  try {
4025
- schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role);
4309
+ schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role, void 0, false);
4026
4310
  } finally {
4027
4311
  copy.close();
4028
4312
  }
4029
- const content = await this.objects.captureFile(file);
4313
+ const [content] = await this.objects.captureFiles([file], void 0, { chunkConcurrency: 8 });
4030
4314
  return { databaseId: d.databaseId, role, schemaHash: schemaHash2, content };
4031
4315
  }));
4032
4316
  for (const result of results) {
@@ -4035,7 +4319,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
4035
4319
  }
4036
4320
  }
4037
4321
  for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
4038
- for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
4322
+ for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
4039
4323
  if (kind !== "LOCAL") {
4040
4324
  const status = await options.receiver.status();
4041
4325
  if (!currentHCheck && !status.dataReady || status.published?.digest !== digest3) throw new Error("RECOVERY_COMMON_NOT_READY");
@@ -4065,18 +4349,17 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
4065
4349
  if (currentHCheck) await verify2();
4066
4350
  }
4067
4351
  }
4068
- /** The caller has fetched only refs from this authenticated original seal.
4069
- * No receipt is installed until every chunk and real SQLite snapshot passes. */
4070
- async import(entry, deletionWatermark) {
4352
+ /** Paired transfer verifies original bytes here and opens the native stores
4353
+ * once at seed. Offline imports can also validate the full SQLite snapshots. */
4354
+ async import(entry, deletionWatermark, verifyDatabases = true) {
4071
4355
  this.active();
4072
4356
  const { value, body, receipt } = validateRecoveryArchiveEntry(entry, this.objects.identity);
4073
- let floor = await checkRecoveryDeletionAsync(value.manifest, deletionWatermark);
4357
+ const floor = await checkRecoveryDeletionAsync(value.manifest, deletionWatermark);
4074
4358
  const prior = this.db.prepare("SELECT kind,manifest_digest,content FROM archives WHERE id=?").get(value.id);
4075
4359
  if (prior && (prior.kind !== value.kind || prior.manifest_digest !== receipt.manifestDigest || JSON.parse(String(prior.content)).sha256 !== receipt.digest)) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
4076
- const temporary = mkdtempSync(join13(this.directory, ".import-"));
4360
+ const temporary = verifyDatabases ? mkdtempSync(join13(this.directory, ".import-")) : void 0;
4077
4361
  try {
4078
- for (const db of value.databases) {
4079
- floor = await checkRecoveryDeletionAsync(value.manifest, deletionWatermark, floor);
4362
+ if (temporary) for (const db of value.databases) {
4080
4363
  const file = join13(temporary, db.databaseId + ".sqlite");
4081
4364
  await this.objects.restoreFile(db.content, file);
4082
4365
  const probe = new DatabaseSync13(file, { readOnly: true });
@@ -4086,17 +4369,10 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
4086
4369
  probe.close();
4087
4370
  }
4088
4371
  }
4089
- const files = value.manifest.trees.flatMap((tree) => tree.files);
4090
- for (let offset = 0; offset < files.length; offset += 8) {
4091
- const results = await Promise.allSettled(files.slice(offset, offset + 8).map(async (file) => {
4092
- const current2 = await checkRecoveryDeletionAsync(value.manifest, deletionWatermark, floor);
4093
- await verifyContent(this.objects, file.content);
4094
- return current2;
4095
- }));
4096
- for (const result of results) {
4097
- if (result.status === "rejected") throw result.reason;
4098
- floor = Math.max(floor, result.value);
4099
- }
4372
+ const contents = [...temporary ? [] : value.databases.map((db) => db.content), ...value.manifest.trees.flatMap((tree) => tree.files.map((file) => file.content))];
4373
+ for (let offset = 0; offset < contents.length; offset += 8) {
4374
+ const results = await Promise.allSettled(contents.slice(offset, offset + 8).map((content) => verifyContent(this.objects, content)));
4375
+ for (const result of results) if (result.status === "rejected") throw result.reason;
4100
4376
  }
4101
4377
  const ref = await this.objects.putContent(body);
4102
4378
  await checkRecoveryDeletionAsync(value.manifest, deletionWatermark, floor);
@@ -4113,7 +4389,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
4113
4389
  }
4114
4390
  return (await this.read(value.id)).receipt;
4115
4391
  } finally {
4116
- rmSync(temporary, { recursive: true, force: true });
4392
+ if (temporary) rmSync(temporary, { recursive: true, force: true });
4117
4393
  await syncDirectory(this.directory);
4118
4394
  }
4119
4395
  }
@@ -4136,6 +4412,37 @@ init_runtime_authority();
4136
4412
  // src/continuity/engine-control.ts
4137
4413
  init_runtime_authority();
4138
4414
  var format = "engine7-travel-process-v1";
4415
+ var diagnosticActions = /* @__PURE__ */ new Set(["status", "drain", "capture", "connect-peer", "synchronize", "checkpoints", "seal"]);
4416
+ var diagnosticCodes = /* @__PURE__ */ new Set([
4417
+ "PUBLICATION_SOURCE_CHANGED",
4418
+ "PUBLICATION_NOT_READY",
4419
+ "PUBLICATION_CONCURRENT_CHANGE",
4420
+ "PUBLICATION_CONNECTION_FAILED",
4421
+ "PUBLICATION_TIMEOUT",
4422
+ "PUBLICATION_INVALID_RESPONSE",
4423
+ "PUBLICATION_DELETION_REGRESSION",
4424
+ "PUBLICATION_REMOVAL_REQUIRES_DELETION",
4425
+ "PUBLICATION_INCOMPLETE_DATABASES",
4426
+ "RUNTIME_PUBLICATION_CLOSED",
4427
+ "RUNTIME_PUBLICATION_CONCURRENT_CHANGE",
4428
+ "RUNTIME_PUBLICATION_PROFILE_MISMATCH",
4429
+ "RUNTIME_PUBLICATION_RECOVERY_REQUIRED",
4430
+ "RUNTIME_PUBLICATION_SEND_BUSY",
4431
+ "RUNTIME_SYNC_INVALID_STATE",
4432
+ "TRAVEL_LEASE_EXPIRED",
4433
+ "TRAVEL_PERMIT_REQUIRED",
4434
+ "TRAVEL_INVALID_PERMIT",
4435
+ "TRAVEL_INPUT_PAUSED",
4436
+ "TRAVEL_HANDOFF_FROZEN",
4437
+ "TRAVEL_DELETION_BARRIER",
4438
+ "TRAVEL_DELETION_ROLLBACK",
4439
+ "TRAVEL_STALE_WRITER_EPOCH",
4440
+ "TRAVEL_RUNTIME_RECOVERY_REQUIRED",
4441
+ "TRAVEL_CONTROL_UNAVAILABLE",
4442
+ "TRAVEL_CONTROL_REFUSED",
4443
+ "RECOVERY_DELETION_BARRIER",
4444
+ "KEY_SERVICE_DENIED"
4445
+ ]);
4139
4446
  function travelProcessBinding(stateDir) {
4140
4447
  const runtime = runtimeAuthorityFor(stateDir);
4141
4448
  if (!runtime) throw new Error("TRAVEL_PROCESS_ENROLLMENT_REQUIRED");
@@ -4155,10 +4462,13 @@ function installTravelEngineControl(options) {
4155
4462
  };
4156
4463
  const handler = async (message) => {
4157
4464
  if (message?.format !== format || message.type !== "request" || typeof message.nonce !== "string" || !/^[a-f0-9-]{36}$/.test(message.nonce)) return;
4465
+ let phase = "binding";
4158
4466
  try {
4159
4467
  if (JSON.stringify(message.binding) !== JSON.stringify(binding) || JSON.stringify(travelProcessBinding(options.stateDir)) !== JSON.stringify(binding)) throw new Error();
4468
+ phase = "dispatch";
4160
4469
  if (message.action === "status") send({ format, type: "response", nonce: message.nonce, binding, ok: true, result: { busy: options.isBusy(), draining: !!draining } });
4161
4470
  else if (message.action === "drain") {
4471
+ phase = "operation";
4162
4472
  draining ??= (async () => {
4163
4473
  runtime.pauseInput(true);
4164
4474
  while (options.isBusy()) {
@@ -4171,27 +4481,42 @@ function installTravelEngineControl(options) {
4171
4481
  await draining;
4172
4482
  send({ format, type: "response", nonce: message.nonce, binding, ok: true, result: { drained: true } });
4173
4483
  } else if (message.action === "capture" && options.capture && !draining) {
4484
+ phase = "operation";
4174
4485
  const result = await options.capture();
4486
+ phase = "control-check";
4175
4487
  runtime.assert("CONTROL");
4176
4488
  send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
4177
4489
  } else if (message.action === "connect-peer" && options.connectPeer && !draining) {
4490
+ phase = "operation";
4178
4491
  const result = await options.connectPeer(message.peer);
4492
+ phase = "control-check";
4179
4493
  runtime.assert("CONTROL");
4180
4494
  send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
4181
4495
  } else if (message.action === "synchronize" && options.synchronize && !draining) {
4496
+ phase = "operation";
4182
4497
  const result = await options.synchronize();
4498
+ phase = "control-check";
4183
4499
  runtime.assert("CONTROL");
4184
4500
  send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
4185
4501
  } else if (message.action === "checkpoints" && options.checkpoints && !draining) {
4502
+ phase = "operation";
4186
4503
  const result = await options.checkpoints(message.afterSequence);
4504
+ phase = "control-check";
4187
4505
  runtime.assert("CONTROL");
4188
4506
  send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
4189
4507
  } else if (message.action === "seal" && options.seal && !draining) {
4508
+ phase = "operation";
4190
4509
  const result = await options.seal();
4510
+ phase = "control-check";
4191
4511
  runtime.assert("CONTROL");
4192
4512
  send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
4193
4513
  } else throw new Error();
4194
4514
  } catch (error) {
4515
+ console.error("[travel-engine-control]", JSON.stringify({
4516
+ action: diagnosticActions.has(message.action) ? message.action : "unknown",
4517
+ phase,
4518
+ code: error instanceof Error && diagnosticCodes.has(error.message) ? error.message : "OTHER"
4519
+ }));
4195
4520
  const code = error instanceof Error && error.message === "PUBLICATION_SOURCE_CHANGED" ? "PUBLICATION_SOURCE_CHANGED" : "TRAVEL_PROCESS_REFUSED";
4196
4521
  send({ format, type: "response", nonce: message.nonce, binding, ok: false, error: code });
4197
4522
  }
@@ -4683,11 +5008,14 @@ async function openGenerationData(options) {
4683
5008
  })().finally(() => {
4684
5009
  keyCheck = void 0;
4685
5010
  });
4686
- let keyTimer, captureTimer;
5011
+ const availableAfterWork = async () => {
5012
+ if (clock() - checkedAt >= 1e4) await refresh();
5013
+ assertAvailable();
5014
+ };
5015
+ let keyTimer;
4687
5016
  const close = () => closing ??= (async () => {
4688
5017
  closed = true;
4689
5018
  if (keyTimer) clearInterval(keyTimer);
4690
- if (captureTimer) clearInterval(captureTimer);
4691
5019
  client?.close();
4692
5020
  await scheduler?.stop();
4693
5021
  await active?.catch(() => {
@@ -4708,9 +5036,9 @@ async function openGenerationData(options) {
4708
5036
  const restart = !!scheduler?.status().running;
4709
5037
  await scheduler?.stop();
4710
5038
  try {
4711
- assertAvailable();
5039
+ await availableAfterWork();
4712
5040
  const h = await opened.source.prepare(opened.capture());
4713
- assertAvailable();
5041
+ await availableAfterWork();
4714
5042
  if (!baseline) {
4715
5043
  if (h.sequence !== 1) throw new Error("TRAVEL_DATA_BASELINE_REQUIRED");
4716
5044
  baseline = await archive.preserve({
@@ -4718,13 +5046,13 @@ async function openGenerationData(options) {
4718
5046
  kind: "LOCAL",
4719
5047
  manifest: h.manifest,
4720
5048
  databases: opened.databases,
4721
- deletionWatermark: () => {
4722
- assertAvailable();
5049
+ deletionWatermark: async () => {
5050
+ await availableAfterWork();
4723
5051
  return runtime.deletionFloor();
4724
5052
  }
4725
5053
  });
4726
5054
  }
4727
- assertAvailable();
5055
+ await availableAfterWork();
4728
5056
  return {
4729
5057
  sequence: h.sequence,
4730
5058
  digest: h.digest,
@@ -4755,10 +5083,6 @@ async function openGenerationData(options) {
4755
5083
  assertAvailable();
4756
5084
  if (!target.dataReady || !target.published || target.published.digest !== (await opened.source.read(target.published.sequence)).digest) throw new Error("TRAVEL_DATA_PEER_BASELINE");
4757
5085
  assertAvailable();
4758
- if (captureTimer) {
4759
- clearInterval(captureTimer);
4760
- captureTimer = void 0;
4761
- }
4762
5086
  client = candidate;
4763
5087
  candidate = void 0;
4764
5088
  peerBinding = binding;
@@ -4810,19 +5134,19 @@ async function openGenerationData(options) {
4810
5134
  const restart = !!scheduler?.status().running;
4811
5135
  await scheduler?.stop();
4812
5136
  try {
4813
- assertAvailable();
5137
+ await availableAfterWork();
4814
5138
  const h = await opened.source.prepare(opened.capture());
4815
5139
  const receipt = await archive.preserve({
4816
5140
  id: "local-" + h.digest,
4817
5141
  kind: "LOCAL",
4818
5142
  manifest: h.manifest,
4819
5143
  databases: opened.databases,
4820
- deletionWatermark: () => {
4821
- assertAvailable();
5144
+ deletionWatermark: async () => {
5145
+ await availableAfterWork();
4822
5146
  return runtime.deletionFloor();
4823
5147
  }
4824
5148
  });
4825
- assertAvailable();
5149
+ await availableAfterWork();
4826
5150
  return { sequence: h.sequence, digest: h.digest, archive: receipt };
4827
5151
  } finally {
4828
5152
  if (restart && !closed) scheduler.start();
@@ -4835,6 +5159,10 @@ async function openGenerationData(options) {
4835
5159
  };
4836
5160
  try {
4837
5161
  await refresh();
5162
+ keyTimer = setInterval(() => {
5163
+ void refresh().catch(() => {
5164
+ });
5165
+ }, 1e4);
4838
5166
  opened = await openRuntimeGenerationSource({ stateDir: options.stateDir, dataDirectory: options.dataDirectory, objects, initialize: options.initialize, mode: "LIVE" });
4839
5167
  archive = await RuntimeRecoveryArchive.open({ directory: join14(options.dataDirectory, "recovery"), objects, initialize: options.initialize });
4840
5168
  const id2 = "baseline-" + hash2(JSON.stringify(opened.profile));
@@ -4846,14 +5174,6 @@ async function openGenerationData(options) {
4846
5174
  if (baseline && (baseline.kind !== "LOCAL" || baseline.manifestDigest !== (await opened.source.read(1)).digest)) throw new Error("TRAVEL_DATA_BASELINE_REQUIRED");
4847
5175
  await capture2();
4848
5176
  if (options.peer) await connectPeer(options.peer);
4849
- else captureTimer = setInterval(() => {
4850
- void capture2().catch(() => {
4851
- });
4852
- }, interval);
4853
- keyTimer = setInterval(() => {
4854
- void refresh().catch(() => {
4855
- });
4856
- }, 1e4);
4857
5177
  return {
4858
5178
  capture: capture2,
4859
5179
  connectPeer,