engine7 7.1.138 → 7.1.141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/bg-worker.mjs +134 -128
- package/dist/cli.mjs +4908 -3448
- package/dist/cpu-router-worker.mjs +604 -8
- package/dist/device-connectors/reader +0 -0
- package/dist/engine-startup.mjs +9105 -6642
- package/dist/main.mjs +9082 -6618
- package/dist/optional-deps.json +78 -0
- package/dist/recall-worker.mjs +57 -53
- package/dist/sqlite-maintenance-worker.mjs +16 -18
- package/dist/topics-worker.mjs +56 -52
- package/dist/travel-activation-database.mjs +1077 -0
- package/dist/travel-authority.mjs +46 -25
- package/dist/travel-console.mjs +150 -83
- package/dist/travel-controller.mjs +244 -51
- package/dist/travel-data.mjs +972 -578
- package/dist/travel-gateway.mjs +1529 -745
- package/dist/travel-host.mjs +3970 -3068
- package/dist/travel-initial-baseline.mjs +5959 -0
- package/dist/travel-node-data.mjs +751 -324
- package/dist/travel-node.mjs +2489 -1541
- package/dist/travel-pairing.mjs +1570 -779
- package/dist/travel-resource.mjs +23 -16
- package/dist/travel-retire.mjs +52 -37
- package/dist/web-console.mjs +1972 -320
- package/package.json +13 -8
- package/scripts/verify-cpu-router-package.mjs +14 -1
- package/templates/config.template.json +14 -0
|
@@ -135,11 +135,11 @@ 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
|
|
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
|
-
const
|
|
142
|
-
if (!
|
|
141
|
+
const stat2 = lstatSync3(path2);
|
|
142
|
+
if (!stat2.isDirectory() || stat2.isSymbolicLink() || process.platform !== "win32" && (stat2.uid !== process.getuid() || stat2.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
|
|
143
143
|
}
|
|
144
144
|
function readPrivateFile2(path2, maximum) {
|
|
145
145
|
const before = 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
|
|
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
|
-
|
|
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))
|
|
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))
|
|
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
|
|
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(
|
|
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
|
|
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 =
|
|
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 });
|
|
@@ -1386,7 +1386,7 @@ var init_timing = __esm({
|
|
|
1386
1386
|
|
|
1387
1387
|
// src/continuity/runtime-generation-data.ts
|
|
1388
1388
|
import { createHash as createHash13 } from "node:crypto";
|
|
1389
|
-
import { join as
|
|
1389
|
+
import { join as join15, resolve as resolve14 } from "node:path";
|
|
1390
1390
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
1391
1391
|
import { existsSync as existsSync7 } from "node:fs";
|
|
1392
1392
|
|
|
@@ -1396,17 +1396,17 @@ import { constants, lstatSync, mkdirSync, openSync, closeSync, readFileSync, wri
|
|
|
1396
1396
|
function validateKeyIdentity(value) {
|
|
1397
1397
|
if (!value || ["tenantId", "companionId", "seatId", "keyId"].some((k) => typeof value[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value[k])) || !Number.isSafeInteger(value.generation) || value.generation < 1) throw new Error("KEY_SERVICE_INVALID_IDENTITY");
|
|
1398
1398
|
}
|
|
1399
|
-
function assertPrivateStat(
|
|
1400
|
-
if ((directory2 ? !
|
|
1399
|
+
function assertPrivateStat(stat2, directory2) {
|
|
1400
|
+
if ((directory2 ? !stat2.isDirectory() : !stat2.isFile()) || process.platform !== "win32" && ((stat2.mode & 63) !== 0 || stat2.uid !== process.getuid?.()))
|
|
1401
1401
|
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
1402
1402
|
}
|
|
1403
1403
|
function readPrivateFile(path2, maximumBytes = 65536) {
|
|
1404
1404
|
assertPrivateStat(lstatSync(path2), false);
|
|
1405
1405
|
const fd = openSync(path2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
1406
1406
|
try {
|
|
1407
|
-
const
|
|
1408
|
-
assertPrivateStat(
|
|
1409
|
-
if (
|
|
1407
|
+
const stat2 = fstatSync(fd);
|
|
1408
|
+
assertPrivateStat(stat2, false);
|
|
1409
|
+
if (stat2.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
1410
1410
|
return readFileSync(fd);
|
|
1411
1411
|
} finally {
|
|
1412
1412
|
closeSync(fd);
|
|
@@ -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
|
|
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
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
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
|
-
|
|
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
|
|
1690
|
+
return this.db.prepare("SELECT objects,bytes FROM object_usage WHERE id=1").get();
|
|
1676
1691
|
}
|
|
1677
|
-
|
|
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
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
1807
|
+
const file = await open(path2, constants2.O_RDONLY | noFollow);
|
|
1714
1808
|
try {
|
|
1715
|
-
const info =
|
|
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
|
|
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
|
-
|
|
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)
|
|
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
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
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 =
|
|
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 +=
|
|
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
|
-
|
|
1976
|
+
if (mode !== 384) await fd.chmod(mode);
|
|
1977
|
+
await fd.sync();
|
|
1794
1978
|
try {
|
|
1795
|
-
|
|
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
|
-
|
|
1984
|
+
if (!deferDirectorySync) await syncDirAsync(dirname(destination));
|
|
1801
1985
|
} finally {
|
|
1802
|
-
|
|
1803
|
-
|
|
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
|
-
|
|
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" ||
|
|
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
|
|
1943
|
-
import { join as
|
|
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 =
|
|
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
|
-
|
|
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
|
|
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
|
|
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");
|
|
@@ -2355,6 +2578,8 @@ async function runtimeFileEntries(options) {
|
|
|
2355
2578
|
excludeStateEntries: { ...options.inventory.excludeStateEntries },
|
|
2356
2579
|
excludeWorkspaceEntries: { ...options.inventory.excludeWorkspaceEntries }
|
|
2357
2580
|
};
|
|
2581
|
+
for (const path2 of ["mem7/spool/intake.write.lock", "mem7/spool/intake.write.lock.reap"])
|
|
2582
|
+
inventoryOptions.excludeStateEntries[path2] = "local queue writer ownership; recreated per process";
|
|
2358
2583
|
for (const directory2 of [...options.vectorDirectories, ...options.sessionDirectories].map(resolvePath)) {
|
|
2359
2584
|
const info = lstatSync6(directory2);
|
|
2360
2585
|
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync3(directory2) !== directory2) throw new Error("SYMLINK_REFUSED");
|
|
@@ -2388,7 +2613,13 @@ async function runtimeFileEntries(options) {
|
|
|
2388
2613
|
};
|
|
2389
2614
|
return await classify();
|
|
2390
2615
|
}
|
|
2391
|
-
var signatures = (entries) => entries.map((entry) => [
|
|
2616
|
+
var signatures = (entries) => entries.map((entry) => [
|
|
2617
|
+
entry.root,
|
|
2618
|
+
entry.path,
|
|
2619
|
+
entry.kind,
|
|
2620
|
+
entry.mode,
|
|
2621
|
+
entry.kind === "directory" ? entry.signature.split(":").slice(0, -3).join(":") : entry.signature
|
|
2622
|
+
]);
|
|
2392
2623
|
async function runtimeFileFingerprint(options) {
|
|
2393
2624
|
return createHash5("sha256").update(JSON.stringify(signatures(await runtimeFileEntries(options)))).digest("hex");
|
|
2394
2625
|
}
|
|
@@ -2398,10 +2629,26 @@ async function captureRuntimeFiles(options) {
|
|
|
2398
2629
|
{ id: options.workspaceTreeId, files: [], directories: [] }
|
|
2399
2630
|
];
|
|
2400
2631
|
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
|
-
|
|
2632
|
+
const files = before.filter((entry) => entry.kind !== "directory");
|
|
2633
|
+
const progress = { completedFiles: 0, totalFiles: files.length, completedBytes: 0, totalBytes: files.reduce((n, e) => n + e.bytes, 0) };
|
|
2634
|
+
options.onProgress?.({ ...progress });
|
|
2635
|
+
for (const entry of before.filter((entry2) => entry2.kind === "directory")) {
|
|
2402
2636
|
const tree = trees[entry.root === "state" ? 0 : 1];
|
|
2403
|
-
|
|
2404
|
-
|
|
2637
|
+
tree.directories.push(entry.path);
|
|
2638
|
+
}
|
|
2639
|
+
for (let offset = 0; offset < files.length; offset += 32) {
|
|
2640
|
+
const batch = files.slice(offset, offset + 32);
|
|
2641
|
+
const bytesBefore = progress.completedBytes;
|
|
2642
|
+
const contents = await options.objects.captureFiles(batch.map((entry) => entry.source), (value) => {
|
|
2643
|
+
progress.completedFiles = offset + value.completedFiles;
|
|
2644
|
+
progress.completedBytes = bytesBefore + value.completedBytes;
|
|
2645
|
+
options.onProgress?.({ ...progress });
|
|
2646
|
+
});
|
|
2647
|
+
for (const [index, entry] of batch.entries()) {
|
|
2648
|
+
const tree = trees[entry.root === "state" ? 0 : 1], content = contents[index];
|
|
2649
|
+
tree.files.push({ path: entry.path, mode: entry.mode & 64 ? 448 : 384, content });
|
|
2650
|
+
}
|
|
2651
|
+
await setImmediate2();
|
|
2405
2652
|
}
|
|
2406
2653
|
if (JSON.stringify(signatures(before)) !== JSON.stringify(signatures(await runtimeFileEntries(options)))) throw new Error("PUBLICATION_SOURCE_CHANGED");
|
|
2407
2654
|
return trees;
|
|
@@ -2412,7 +2659,7 @@ function resolvePath(path2) {
|
|
|
2412
2659
|
|
|
2413
2660
|
// src/continuity/lance-publication.ts
|
|
2414
2661
|
import { createHash as createHash8 } from "node:crypto";
|
|
2415
|
-
import { lstatSync as lstatSync8, readdirSync, realpathSync as realpathSync5, mkdirSync as mkdirSync6, writeFileSync as
|
|
2662
|
+
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
2663
|
import { join as join9, resolve as resolve8, dirname as dirname7, relative as relative3 } from "node:path";
|
|
2417
2664
|
import { createRequire as createRequire3 } from "node:module";
|
|
2418
2665
|
|
|
@@ -2441,7 +2688,7 @@ init_scope();
|
|
|
2441
2688
|
|
|
2442
2689
|
// src/mem7/core/change-feed.ts
|
|
2443
2690
|
import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
|
|
2444
|
-
import { existsSync as existsSync3, readFileSync as
|
|
2691
|
+
import { existsSync as existsSync3, readFileSync as readFileSync5, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync5 } from "node:fs";
|
|
2445
2692
|
|
|
2446
2693
|
// src/mem7/core/state/temporal.ts
|
|
2447
2694
|
function canonicalJson(value) {
|
|
@@ -2648,7 +2895,7 @@ var ChangeFeed = class _ChangeFeed {
|
|
|
2648
2895
|
let ledger = {};
|
|
2649
2896
|
if (ledgerPath) {
|
|
2650
2897
|
try {
|
|
2651
|
-
ledger = JSON.parse(
|
|
2898
|
+
ledger = JSON.parse(readFileSync5(ledgerPath, "utf8"))?.heals ?? {};
|
|
2652
2899
|
} catch {
|
|
2653
2900
|
}
|
|
2654
2901
|
if (Number.isFinite(ledger[key])) {
|
|
@@ -2673,11 +2920,11 @@ var ChangeFeed = class _ChangeFeed {
|
|
|
2673
2920
|
retained[key] = now2;
|
|
2674
2921
|
const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
|
|
2675
2922
|
try {
|
|
2676
|
-
|
|
2923
|
+
writeFileSync5(temp, JSON.stringify({ version: 1, heals: retained }));
|
|
2677
2924
|
renameSync2(temp, ledgerPath);
|
|
2678
2925
|
} catch (error) {
|
|
2679
2926
|
try {
|
|
2680
|
-
if (existsSync3(temp))
|
|
2927
|
+
if (existsSync3(temp)) unlinkSync2(temp);
|
|
2681
2928
|
} catch {
|
|
2682
2929
|
}
|
|
2683
2930
|
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 +3051,10 @@ init_read_guard();
|
|
|
2804
3051
|
init_scope();
|
|
2805
3052
|
|
|
2806
3053
|
// src/mem7/core/episode.ts
|
|
2807
|
-
import { readFileSync as
|
|
3054
|
+
import { readFileSync as readFileSync6 } from "node:fs";
|
|
2808
3055
|
import { join as join8, dirname as dirname6 } from "node:path";
|
|
2809
3056
|
import { fileURLToPath } from "node:url";
|
|
2810
|
-
var PROMPT =
|
|
3057
|
+
var PROMPT = readFileSync6(join8(dirname6(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
|
|
2811
3058
|
|
|
2812
3059
|
// src/mem7/core/relationship-cognition.ts
|
|
2813
3060
|
init_scope();
|
|
@@ -3098,14 +3345,28 @@ async function captureLancePublication(options) {
|
|
|
3098
3345
|
const batchTable = new arrow.Table(batch);
|
|
3099
3346
|
for (let start = 0; start < batchTable.numRows; start += batchRows) {
|
|
3100
3347
|
const page = batchTable.slice(start, start + batchRows);
|
|
3348
|
+
let pending = [], pendingBytes = 0;
|
|
3349
|
+
const flush = async () => {
|
|
3350
|
+
if (!pending.length) return;
|
|
3351
|
+
const contents = await options.objects.putContents(pending.map((row) => row.bytes));
|
|
3352
|
+
for (let i = 0; i < pending.length; i++) tree.files.push({ path: pending[i].path, mode: 384, content: contents[i] });
|
|
3353
|
+
pending = [];
|
|
3354
|
+
pendingBytes = 0;
|
|
3355
|
+
};
|
|
3101
3356
|
for (let index = 0; index < page.numRows; index++) {
|
|
3102
3357
|
const one = page.slice(index, index + 1), path2 = rowPath(kind, one.getChild("id").get(0));
|
|
3103
3358
|
if (seen.has(path2)) throw new Error("LANCE_PUBLICATION_DUPLICATE_ROW");
|
|
3104
3359
|
seen.add(path2);
|
|
3105
3360
|
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
|
-
|
|
3361
|
+
if (bytes.length > ROW_BYTES || tree.files.length + pending.length >= 99999) throw new Error("LANCE_PUBLICATION_ROW_TOO_LARGE");
|
|
3362
|
+
if (pending.length === 128 || pendingBytes + bytes.length > 8 * 1024 * 1024) await flush();
|
|
3363
|
+
if (bytes.length > 8 * 1024 * 1024) tree.files.push({ path: path2, mode: 384, content: await options.objects.putContent(bytes) });
|
|
3364
|
+
else {
|
|
3365
|
+
pending.push({ path: path2, bytes });
|
|
3366
|
+
pendingBytes += bytes.length;
|
|
3367
|
+
}
|
|
3108
3368
|
}
|
|
3369
|
+
await flush();
|
|
3109
3370
|
}
|
|
3110
3371
|
}
|
|
3111
3372
|
if (seen.size !== total) throw new Error("LANCE_PUBLICATION_ROW_COUNT_MISMATCH");
|
|
@@ -3333,7 +3594,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
|
|
|
3333
3594
|
}
|
|
3334
3595
|
sender.exec(senderSchema);
|
|
3335
3596
|
sender.prepare("INSERT INTO sender VALUES(1,?,?)").run(JSON.stringify(this.profile), this.layoutDigest);
|
|
3336
|
-
|
|
3597
|
+
writeFileSync7(this.marker, JSON.stringify({ format: "engine7-runtime-publication-source-v1", profile: this.profile, layoutDigest: this.layoutDigest }), { flag: "wx", mode: 384, flush: true });
|
|
3337
3598
|
if (process.platform !== "win32") {
|
|
3338
3599
|
const fd = openSync9(this.directory, "r");
|
|
3339
3600
|
try {
|
|
@@ -3362,7 +3623,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
|
|
|
3362
3623
|
static async open(options) {
|
|
3363
3624
|
const source = new _RuntimePublicationSource(options);
|
|
3364
3625
|
try {
|
|
3365
|
-
if (source.head().sequence) await source.
|
|
3626
|
+
if (source.head().sequence) await source.readManifest(source.head().sequence);
|
|
3366
3627
|
return source;
|
|
3367
3628
|
} catch (error) {
|
|
3368
3629
|
source.close();
|
|
@@ -3413,6 +3674,15 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
|
|
|
3413
3674
|
};
|
|
3414
3675
|
}
|
|
3415
3676
|
async read(sequence) {
|
|
3677
|
+
return this.readPrepared(sequence, true);
|
|
3678
|
+
}
|
|
3679
|
+
/** Ancestry uses authenticated H metadata; payload availability is checked
|
|
3680
|
+
* when actual objects are transferred or restored, not for every old H. */
|
|
3681
|
+
async readManifest(sequence) {
|
|
3682
|
+
const { digest: digest3, manifest } = await this.readPrepared(sequence, false);
|
|
3683
|
+
return { digest: digest3, manifest };
|
|
3684
|
+
}
|
|
3685
|
+
async readPrepared(sequence, verifyDependencies) {
|
|
3416
3686
|
const row = this.entry(sequence), ref = JSON.parse(row.content);
|
|
3417
3687
|
validateFileContent(ref);
|
|
3418
3688
|
const manifest = normalizePublication(JSON.parse((await this.objects.readContent(ref, PUBLICATION_MANIFEST_BYTES)).toString()));
|
|
@@ -3420,7 +3690,7 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
|
|
|
3420
3690
|
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
3691
|
const dependencies = JSON.parse(row.dependencies);
|
|
3422
3692
|
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) {
|
|
3693
|
+
if (verifyDependencies) for (const d of dependencies) {
|
|
3424
3694
|
const tree = await this.trees.read(d.treeId, d.sequence);
|
|
3425
3695
|
if (tree.digest !== d.digest || !same2(tree.tree, manifest.trees.find((t) => t.id === d.treeId))) throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
|
|
3426
3696
|
}
|
|
@@ -3433,12 +3703,41 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
|
|
|
3433
3703
|
async prepare(options) {
|
|
3434
3704
|
return this.prepareCapture(options, () => captureRuntimeH(options));
|
|
3435
3705
|
}
|
|
3436
|
-
/**
|
|
3437
|
-
*
|
|
3706
|
+
/** A first full baseline already lives in the bounded encrypted object store
|
|
3707
|
+
* and native SQLite snapshots. Only its envelope occupies the increment queue. */
|
|
3708
|
+
async prepareInitial(options) {
|
|
3709
|
+
if (this.control().head !== 0) throw new Error("RUNTIME_PUBLICATION_INITIAL_ALREADY_PREPARED");
|
|
3710
|
+
return this.prepareCapture(options, () => captureRuntimeH(options), true);
|
|
3711
|
+
}
|
|
3712
|
+
/** The final LOCAL original is archived independently of the transport queue.
|
|
3713
|
+
* Read-only stores and writer exclusion remain held through its durable seal. */
|
|
3438
3714
|
async withStoppedPreparation(options, operation) {
|
|
3439
|
-
|
|
3715
|
+
const before = this.control();
|
|
3716
|
+
if (!same2(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
|
|
3717
|
+
if (options.deletionWatermark < before.watermark) throw new Error("PUBLICATION_DELETION_REGRESSION");
|
|
3718
|
+
return withStoppedRuntimeH(options, async (parts) => {
|
|
3719
|
+
const manifest = normalizePublication({
|
|
3720
|
+
format: "engine7-publication-v1",
|
|
3721
|
+
profile: this.profile,
|
|
3722
|
+
sequence: before.head + 1,
|
|
3723
|
+
parentDigest: before.digest,
|
|
3724
|
+
databases: parts.databases,
|
|
3725
|
+
trees: parts.trees,
|
|
3726
|
+
deletionWatermark: parts.deletionWatermark
|
|
3727
|
+
});
|
|
3728
|
+
const old = before.head ? await this.readManifest(before.head) : null;
|
|
3729
|
+
if (old && manifest.deletionWatermark === old.manifest.deletionWatermark) {
|
|
3730
|
+
const present = new Set(manifest.trees.flatMap((tree) => tree.files.map((file) => tree.id + "/" + file.path)));
|
|
3731
|
+
if (old.manifest.trees.some((tree) => tree.files.some((file) => !present.has(tree.id + "/" + file.path)))) throw new Error("PUBLICATION_REMOVAL_REQUIRES_DELETION");
|
|
3732
|
+
}
|
|
3733
|
+
const current2 = this.control();
|
|
3734
|
+
if (current2.head !== before.head || current2.digest !== before.digest) throw new Error("RUNTIME_PUBLICATION_CONCURRENT_CHANGE");
|
|
3735
|
+
if (manifest.deletionWatermark < current2.watermark) throw new Error("PUBLICATION_DELETION_REGRESSION");
|
|
3736
|
+
if (old && stateHash(old.manifest) === stateHash(manifest)) return operation({ ...old, sequence: before.head, activationAllowed: false });
|
|
3737
|
+
return operation({ sequence: manifest.sequence, digest: publicationDigest(manifest), manifest, activationAllowed: false });
|
|
3738
|
+
});
|
|
3440
3739
|
}
|
|
3441
|
-
async prepareCapture(options, capture2) {
|
|
3740
|
+
async prepareCapture(options, capture2, initial = false) {
|
|
3442
3741
|
const c = this.control(), pending = this.status();
|
|
3443
3742
|
if (!same2(options.profile, this.profile) || options.objects !== this.objects) throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
|
|
3444
3743
|
if (pending.pendingCheckpoints >= this.maximumPendingCheckpoints || pending.pendingBytes >= this.maximumPendingBytes) throw new Error("RUNTIME_PUBLICATION_QUEUE_FULL");
|
|
@@ -3470,11 +3769,11 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
|
|
|
3470
3769
|
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
3770
|
}
|
|
3472
3771
|
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)) {
|
|
3772
|
+
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
3773
|
known.add(ref.sha256);
|
|
3475
3774
|
bytes += ref.bytes;
|
|
3476
3775
|
}
|
|
3477
|
-
for (const d of manifest.databases) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
|
|
3776
|
+
for (const d of manifest.databases) if (!initial) bytes += options.databases[d.databaseId].source.pendingStoredBytesAfter(
|
|
3478
3777
|
old?.manifest.databases.find((previous) => previous.databaseId === d.databaseId).head.sequence ?? 0,
|
|
3479
3778
|
d.head.sequence
|
|
3480
3779
|
);
|
|
@@ -3723,7 +4022,7 @@ async function openRuntimeGenerationSource(options) {
|
|
|
3723
4022
|
lanceStores,
|
|
3724
4023
|
deletionWatermark: runtime.deletionFloor(),
|
|
3725
4024
|
files: {
|
|
3726
|
-
inventory: { stateDir, workspace, includeStateEntries: layout.includedStateEntries },
|
|
4025
|
+
inventory: { stateDir, workspace, selection: layout.inventorySelection, includeStateEntries: layout.includedStateEntries },
|
|
3727
4026
|
objects: options.objects,
|
|
3728
4027
|
databaseFiles: Object.values(databases).map((db) => db.file),
|
|
3729
4028
|
immutableDatabaseFiles: (layout.immutableDatabases ?? []).map((path2) => {
|
|
@@ -3744,20 +4043,85 @@ async function openRuntimeGenerationSource(options) {
|
|
|
3744
4043
|
}
|
|
3745
4044
|
}
|
|
3746
4045
|
|
|
3747
|
-
// src/continuity/
|
|
4046
|
+
// src/continuity/native-database-snapshot.ts
|
|
3748
4047
|
import { DatabaseSync as DatabaseSync13, backup } from "node:sqlite";
|
|
3749
|
-
import {
|
|
3750
|
-
|
|
4048
|
+
import { lstat as lstat2 } from "node:fs/promises";
|
|
4049
|
+
|
|
4050
|
+
// src/continuity/native-file-copy.ts
|
|
4051
|
+
import { constants as constants7 } from "node:fs";
|
|
4052
|
+
import { copyFile, link as link2, rename, rm, stat } from "node:fs/promises";
|
|
4053
|
+
import { execFile } from "node:child_process";
|
|
4054
|
+
import { promisify as promisify2 } from "node:util";
|
|
4055
|
+
import { dirname as dirname9, join as join13 } from "node:path";
|
|
4056
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
4057
|
+
var exec = promisify2(execFile);
|
|
4058
|
+
async function copyNativeFile(source, destination, flags = constants7.COPYFILE_EXCL | constants7.COPYFILE_FICLONE, bytes) {
|
|
4059
|
+
if (process.platform !== "darwin") {
|
|
4060
|
+
await copyFile(source, destination, flags);
|
|
4061
|
+
return;
|
|
4062
|
+
}
|
|
4063
|
+
if ((bytes ?? (await stat(source)).size) < 1024 * 1024) {
|
|
4064
|
+
await copyFile(source, destination, flags);
|
|
4065
|
+
return;
|
|
4066
|
+
}
|
|
4067
|
+
const temporary = join13(dirname9(destination), ".e7-native-copy-" + randomUUID6());
|
|
4068
|
+
try {
|
|
4069
|
+
await exec("/bin/cp", ["-c", "-p", source, temporary], { maxBuffer: 8192 });
|
|
4070
|
+
if (flags & constants7.COPYFILE_EXCL) await link2(temporary, destination);
|
|
4071
|
+
else await rename(temporary, destination);
|
|
4072
|
+
} finally {
|
|
4073
|
+
await rm(temporary, { force: true });
|
|
4074
|
+
}
|
|
4075
|
+
}
|
|
4076
|
+
|
|
4077
|
+
// src/continuity/native-database-snapshot.ts
|
|
4078
|
+
async function snapshotNativeDatabase(db, destination) {
|
|
4079
|
+
if (process.platform !== "darwin") {
|
|
4080
|
+
await backup(db, destination);
|
|
4081
|
+
return;
|
|
4082
|
+
}
|
|
4083
|
+
const file = String(db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? "");
|
|
4084
|
+
if (!file) {
|
|
4085
|
+
await backup(db, destination);
|
|
4086
|
+
return;
|
|
4087
|
+
}
|
|
4088
|
+
const reader = new DatabaseSync13(file, { readOnly: true, allowExtension: true });
|
|
4089
|
+
try {
|
|
4090
|
+
reader.exec("BEGIN");
|
|
4091
|
+
reader.prepare("SELECT count(*) FROM sqlite_master").get();
|
|
4092
|
+
await copyNativeFile(file, destination);
|
|
4093
|
+
try {
|
|
4094
|
+
await lstat2(file + "-wal");
|
|
4095
|
+
await copyNativeFile(file + "-wal", destination + "-wal");
|
|
4096
|
+
} catch (error) {
|
|
4097
|
+
if (error.code !== "ENOENT") throw error;
|
|
4098
|
+
}
|
|
4099
|
+
reader.exec("ROLLBACK");
|
|
4100
|
+
} finally {
|
|
4101
|
+
reader.close();
|
|
4102
|
+
}
|
|
4103
|
+
const target = new DatabaseSync13(destination);
|
|
4104
|
+
try {
|
|
4105
|
+
if (Number(target.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()?.busy) !== 0) throw Error("DATABASE_SNAPSHOT_BUSY");
|
|
4106
|
+
} finally {
|
|
4107
|
+
target.close();
|
|
4108
|
+
}
|
|
4109
|
+
}
|
|
4110
|
+
|
|
4111
|
+
// src/continuity/recovery-archive.ts
|
|
4112
|
+
import { DatabaseSync as DatabaseSync14 } from "node:sqlite";
|
|
4113
|
+
import { existsSync as existsSync6, lstatSync as lstatSync12, mkdtempSync, rmSync, writeFileSync as writeFileSync8, chmodSync as chmodSync2 } from "node:fs";
|
|
4114
|
+
import { join as join14, resolve as resolve13 } from "node:path";
|
|
3751
4115
|
init_sqlite_replication();
|
|
3752
4116
|
|
|
3753
4117
|
// src/continuity/crypto.ts
|
|
3754
|
-
import { constants as
|
|
3755
|
-
import { open as
|
|
4118
|
+
import { constants as constants8, createWriteStream, openSync as openSync10 } from "node:fs";
|
|
4119
|
+
import { open as open3, lstat as lstat3, link as link3, unlink as unlink2, writeFile as writeFile2, appendFile } from "node:fs/promises";
|
|
3756
4120
|
var MAGIC2 = Buffer.from("E7OBJ001");
|
|
3757
4121
|
var HEADER_SIZE = MAGIC2.length + 12;
|
|
3758
4122
|
async function syncDirectory(directory2) {
|
|
3759
4123
|
if (process.platform === "win32") return;
|
|
3760
|
-
const handle = await
|
|
4124
|
+
const handle = await open3(directory2, constants8.O_RDONLY);
|
|
3761
4125
|
try {
|
|
3762
4126
|
await handle.sync();
|
|
3763
4127
|
} finally {
|
|
@@ -3802,7 +4166,8 @@ async function currentHDeletionCheckAsync(raw, control2, captured) {
|
|
|
3802
4166
|
var schema3 = "CREATE TABLE archives(id TEXT PRIMARY KEY,kind TEXT NOT NULL,manifest_digest TEXT NOT NULL,content TEXT NOT NULL)";
|
|
3803
4167
|
var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
3804
4168
|
var FORMAT = "engine7-runtime-recovery-archive-v1";
|
|
3805
|
-
var
|
|
4169
|
+
var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
|
|
4170
|
+
var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
|
|
3806
4171
|
var same4 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
3807
4172
|
var incarnation2 = (file) => {
|
|
3808
4173
|
const s = lstatSync12(file, { bigint: true });
|
|
@@ -3846,14 +4211,17 @@ async function checkRecoveryDeletionAsync(manifest, current2, previous = 0) {
|
|
|
3846
4211
|
const floor = await current2();
|
|
3847
4212
|
return checkRecoveryDeletion(manifest, () => floor, previous);
|
|
3848
4213
|
}
|
|
3849
|
-
function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2) {
|
|
4214
|
+
function validateRecoveryDatabase(db, manifest, databaseId, role, schemaHash2, scan = true) {
|
|
3850
4215
|
const d = manifest.databases.find((d2) => d2.databaseId === databaseId), p = manifest.profile;
|
|
3851
4216
|
const control2 = db.prepare("SELECT binding,head,digest,schema_hash FROM e7_replication_control WHERE role=?").get(role);
|
|
3852
4217
|
const binding = JSON.stringify([p.identity.tenantId, p.identity.companionId, p.identity.seatId, databaseId, p.baselineId, p.epoch]);
|
|
3853
4218
|
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
4219
|
const actual = sqliteReplicationSchemaHash(db);
|
|
3855
|
-
|
|
3856
|
-
if (
|
|
4220
|
+
if (actual !== control2.schema_hash) throw new Error("RECOVERY_DATABASE_CORRUPT");
|
|
4221
|
+
if (scan) {
|
|
4222
|
+
const checks = db.prepare("PRAGMA quick_check").all();
|
|
4223
|
+
if (checks.length !== 1 || checks[0].quick_check !== "ok") throw new Error("RECOVERY_DATABASE_CORRUPT");
|
|
4224
|
+
}
|
|
3857
4225
|
return actual;
|
|
3858
4226
|
}
|
|
3859
4227
|
var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
@@ -3867,8 +4235,8 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
|
3867
4235
|
constructor(options) {
|
|
3868
4236
|
this.directory = resolve13(options.directory);
|
|
3869
4237
|
this.objects = options.objects;
|
|
3870
|
-
this.file =
|
|
3871
|
-
this.marker =
|
|
4238
|
+
this.file = join14(this.directory, "archives.sqlite");
|
|
4239
|
+
this.marker = join14(this.directory, "archive.json");
|
|
3872
4240
|
if (options.initialize) preparePrivateDirectory(this.directory);
|
|
3873
4241
|
else {
|
|
3874
4242
|
try {
|
|
@@ -3882,11 +4250,11 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
|
3882
4250
|
if (!fresh) this.checkMarker();
|
|
3883
4251
|
preparePrivateDatabase(this.file);
|
|
3884
4252
|
try {
|
|
3885
|
-
this.db = new
|
|
4253
|
+
this.db = new DatabaseSync14(this.file);
|
|
3886
4254
|
this.db.exec("PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
|
|
3887
4255
|
if (fresh) {
|
|
3888
4256
|
this.db.exec(schema3);
|
|
3889
|
-
|
|
4257
|
+
writeFileSync8(this.marker, JSON.stringify({ format: FORMAT, identity: this.objects.identity }), { mode: 384, flag: "wx", flush: true });
|
|
3890
4258
|
}
|
|
3891
4259
|
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
4260
|
this.identity = incarnation2(this.file);
|
|
@@ -3976,6 +4344,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
|
3976
4344
|
this.active();
|
|
3977
4345
|
const { id: id2, kind } = options, manifest = normalizePublication(options.manifest), digest3 = publicationDigest(manifest);
|
|
3978
4346
|
if (typeof id2 !== "string" || !ID2.test(id2) || !["COMMON", "LOCAL", "REMOTE"].includes(kind)) throw new Error("RECOVERY_INVALID_ID");
|
|
4347
|
+
if (options.snapshotDatabase && (kind !== "LOCAL" || id2 !== "first-baseline" || manifest.sequence !== 1 || manifest.parentDigest !== "0".repeat(64))) throw new Error("RECOVERY_INVALID_SNAPSHOT");
|
|
3979
4348
|
if (!same4(manifest.profile.identity, this.objects.identity)) throw new Error("RECOVERY_IDENTITY_MISMATCH");
|
|
3980
4349
|
const deletion = async () => {
|
|
3981
4350
|
const value = await options.deletionWatermark();
|
|
@@ -3995,38 +4364,51 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
|
3995
4364
|
if (old) {
|
|
3996
4365
|
if (old.kind !== kind || old.manifest_digest !== digest3) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
|
|
3997
4366
|
const entry = await this.read(id2);
|
|
3998
|
-
|
|
3999
|
-
|
|
4367
|
+
if (options.verifyRetained !== false) {
|
|
4368
|
+
for (const d of entry.databases) await verifyContent(this.objects, d.content);
|
|
4369
|
+
for (const tree of manifest.trees) for (const file of tree.files) await verifyContent(this.objects, file.content);
|
|
4370
|
+
}
|
|
4000
4371
|
await verify2();
|
|
4001
4372
|
return entry.receipt;
|
|
4002
4373
|
}
|
|
4003
4374
|
let publication;
|
|
4004
4375
|
if (kind !== "LOCAL") {
|
|
4005
|
-
const status = await options.receiver?.status();
|
|
4376
|
+
const status = await options.receiver?.status(options.verifyRetained !== false);
|
|
4006
4377
|
if (!status || !currentHCheck && !status.dataReady || status.published?.digest !== digest3 || !same4(status.profile, manifest.profile)) throw new Error("RECOVERY_COMMON_NOT_READY");
|
|
4007
4378
|
publication = status.published;
|
|
4008
4379
|
}
|
|
4009
4380
|
if (!same4(Object.keys(options.databases).sort(), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
|
|
4010
4381
|
const role = kind === "LOCAL" ? "source" : "replica";
|
|
4011
|
-
for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role);
|
|
4012
|
-
const
|
|
4382
|
+
for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
|
|
4383
|
+
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;
|
|
4384
|
+
const retained = sibling ? await this.read(String(sibling.id)) : void 0;
|
|
4385
|
+
if (retained) {
|
|
4386
|
+
validateRecoveryArchiveEntry(retained, this.objects.identity);
|
|
4387
|
+
if (!same4(retained.manifest, manifest) || !same4(retained.publication, publication) || retained.databases.some((d) => d.role !== "replica")) throw new Error("RECOVERY_IDEMPOTENCY_CONFLICT");
|
|
4388
|
+
}
|
|
4389
|
+
const temporary = mkdtempSync(join14(this.directory, ".capture-"));
|
|
4013
4390
|
try {
|
|
4014
|
-
|
|
4391
|
+
writeFileSync8(join14(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
|
|
4015
4392
|
const databases = [];
|
|
4016
|
-
|
|
4393
|
+
if (retained) {
|
|
4394
|
+
if (options.verifyRetained !== false) for (const database of retained.databases) await verifyContent(this.objects, database.content);
|
|
4395
|
+
databases.push(...retained.databases);
|
|
4396
|
+
}
|
|
4397
|
+
for (let offset = 0; !retained && offset < manifest.databases.length; offset += 6) {
|
|
4017
4398
|
const results = await Promise.allSettled(manifest.databases.slice(offset, offset + 6).map(async (d) => {
|
|
4018
4399
|
floor = Math.max(floor, await verify2());
|
|
4019
|
-
const file =
|
|
4020
|
-
await
|
|
4400
|
+
const file = join14(temporary, d.databaseId + ".sqlite");
|
|
4401
|
+
if (options.snapshotDatabase) await options.snapshotDatabase(options.databases[d.databaseId], file, d.databaseId);
|
|
4402
|
+
else await snapshotNativeDatabase(options.databases[d.databaseId], file);
|
|
4021
4403
|
chmodSync2(file, 384);
|
|
4022
|
-
const copy = new
|
|
4404
|
+
const copy = new DatabaseSync14(file, { readOnly: true });
|
|
4023
4405
|
let schemaHash2;
|
|
4024
4406
|
try {
|
|
4025
|
-
schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role);
|
|
4407
|
+
schemaHash2 = validateRecoveryDatabase(copy, manifest, d.databaseId, role, void 0, false);
|
|
4026
4408
|
} finally {
|
|
4027
4409
|
copy.close();
|
|
4028
4410
|
}
|
|
4029
|
-
const content = await this.objects.
|
|
4411
|
+
const [content] = await this.objects.captureFiles([file], void 0, { chunkConcurrency: 8 });
|
|
4030
4412
|
return { databaseId: d.databaseId, role, schemaHash: schemaHash2, content };
|
|
4031
4413
|
}));
|
|
4032
4414
|
for (const result of results) {
|
|
@@ -4035,7 +4417,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
|
4035
4417
|
}
|
|
4036
4418
|
}
|
|
4037
4419
|
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);
|
|
4420
|
+
for (const d of manifest.databases) validateRecoveryDatabase(options.databases[d.databaseId], manifest, d.databaseId, role, void 0, false);
|
|
4039
4421
|
if (kind !== "LOCAL") {
|
|
4040
4422
|
const status = await options.receiver.status();
|
|
4041
4423
|
if (!currentHCheck && !status.dataReady || status.published?.digest !== digest3) throw new Error("RECOVERY_COMMON_NOT_READY");
|
|
@@ -4065,38 +4447,30 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
|
4065
4447
|
if (currentHCheck) await verify2();
|
|
4066
4448
|
}
|
|
4067
4449
|
}
|
|
4068
|
-
/**
|
|
4069
|
-
*
|
|
4070
|
-
async import(entry, deletionWatermark) {
|
|
4450
|
+
/** Paired transfer verifies original bytes here and opens the native stores
|
|
4451
|
+
* once at seed. Offline imports can also validate the full SQLite snapshots. */
|
|
4452
|
+
async import(entry, deletionWatermark, verifyDatabases = true) {
|
|
4071
4453
|
this.active();
|
|
4072
4454
|
const { value, body, receipt } = validateRecoveryArchiveEntry(entry, this.objects.identity);
|
|
4073
|
-
|
|
4455
|
+
const floor = await checkRecoveryDeletionAsync(value.manifest, deletionWatermark);
|
|
4074
4456
|
const prior = this.db.prepare("SELECT kind,manifest_digest,content FROM archives WHERE id=?").get(value.id);
|
|
4075
4457
|
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(
|
|
4458
|
+
const temporary = verifyDatabases ? mkdtempSync(join14(this.directory, ".import-")) : void 0;
|
|
4077
4459
|
try {
|
|
4078
|
-
for (const db of value.databases) {
|
|
4079
|
-
|
|
4080
|
-
const file = join13(temporary, db.databaseId + ".sqlite");
|
|
4460
|
+
if (temporary) for (const db of value.databases) {
|
|
4461
|
+
const file = join14(temporary, db.databaseId + ".sqlite");
|
|
4081
4462
|
await this.objects.restoreFile(db.content, file);
|
|
4082
|
-
const probe = new
|
|
4463
|
+
const probe = new DatabaseSync14(file, { readOnly: true });
|
|
4083
4464
|
try {
|
|
4084
4465
|
validateRecoveryDatabase(probe, value.manifest, db.databaseId, db.role, db.schemaHash);
|
|
4085
4466
|
} finally {
|
|
4086
4467
|
probe.close();
|
|
4087
4468
|
}
|
|
4088
4469
|
}
|
|
4089
|
-
const
|
|
4090
|
-
for (let offset = 0; offset <
|
|
4091
|
-
const results = await Promise.allSettled(
|
|
4092
|
-
|
|
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
|
-
}
|
|
4470
|
+
const contents = [...temporary ? [] : value.databases.map((db) => db.content), ...value.manifest.trees.flatMap((tree) => tree.files.map((file) => file.content))];
|
|
4471
|
+
for (let offset = 0; offset < contents.length; offset += 8) {
|
|
4472
|
+
const results = await Promise.allSettled(contents.slice(offset, offset + 8).map((content) => verifyContent(this.objects, content)));
|
|
4473
|
+
for (const result of results) if (result.status === "rejected") throw result.reason;
|
|
4100
4474
|
}
|
|
4101
4475
|
const ref = await this.objects.putContent(body);
|
|
4102
4476
|
await checkRecoveryDeletionAsync(value.manifest, deletionWatermark, floor);
|
|
@@ -4113,7 +4487,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
|
|
|
4113
4487
|
}
|
|
4114
4488
|
return (await this.read(value.id)).receipt;
|
|
4115
4489
|
} finally {
|
|
4116
|
-
rmSync(temporary, { recursive: true, force: true });
|
|
4490
|
+
if (temporary) rmSync(temporary, { recursive: true, force: true });
|
|
4117
4491
|
await syncDirectory(this.directory);
|
|
4118
4492
|
}
|
|
4119
4493
|
}
|
|
@@ -4136,6 +4510,37 @@ init_runtime_authority();
|
|
|
4136
4510
|
// src/continuity/engine-control.ts
|
|
4137
4511
|
init_runtime_authority();
|
|
4138
4512
|
var format = "engine7-travel-process-v1";
|
|
4513
|
+
var diagnosticActions = /* @__PURE__ */ new Set(["status", "drain", "capture", "connect-peer", "synchronize", "checkpoints", "seal"]);
|
|
4514
|
+
var diagnosticCodes = /* @__PURE__ */ new Set([
|
|
4515
|
+
"PUBLICATION_SOURCE_CHANGED",
|
|
4516
|
+
"PUBLICATION_NOT_READY",
|
|
4517
|
+
"PUBLICATION_CONCURRENT_CHANGE",
|
|
4518
|
+
"PUBLICATION_CONNECTION_FAILED",
|
|
4519
|
+
"PUBLICATION_TIMEOUT",
|
|
4520
|
+
"PUBLICATION_INVALID_RESPONSE",
|
|
4521
|
+
"PUBLICATION_DELETION_REGRESSION",
|
|
4522
|
+
"PUBLICATION_REMOVAL_REQUIRES_DELETION",
|
|
4523
|
+
"PUBLICATION_INCOMPLETE_DATABASES",
|
|
4524
|
+
"RUNTIME_PUBLICATION_CLOSED",
|
|
4525
|
+
"RUNTIME_PUBLICATION_CONCURRENT_CHANGE",
|
|
4526
|
+
"RUNTIME_PUBLICATION_PROFILE_MISMATCH",
|
|
4527
|
+
"RUNTIME_PUBLICATION_RECOVERY_REQUIRED",
|
|
4528
|
+
"RUNTIME_PUBLICATION_SEND_BUSY",
|
|
4529
|
+
"RUNTIME_SYNC_INVALID_STATE",
|
|
4530
|
+
"TRAVEL_LEASE_EXPIRED",
|
|
4531
|
+
"TRAVEL_PERMIT_REQUIRED",
|
|
4532
|
+
"TRAVEL_INVALID_PERMIT",
|
|
4533
|
+
"TRAVEL_INPUT_PAUSED",
|
|
4534
|
+
"TRAVEL_HANDOFF_FROZEN",
|
|
4535
|
+
"TRAVEL_DELETION_BARRIER",
|
|
4536
|
+
"TRAVEL_DELETION_ROLLBACK",
|
|
4537
|
+
"TRAVEL_STALE_WRITER_EPOCH",
|
|
4538
|
+
"TRAVEL_RUNTIME_RECOVERY_REQUIRED",
|
|
4539
|
+
"TRAVEL_CONTROL_UNAVAILABLE",
|
|
4540
|
+
"TRAVEL_CONTROL_REFUSED",
|
|
4541
|
+
"RECOVERY_DELETION_BARRIER",
|
|
4542
|
+
"KEY_SERVICE_DENIED"
|
|
4543
|
+
]);
|
|
4139
4544
|
function travelProcessBinding(stateDir) {
|
|
4140
4545
|
const runtime = runtimeAuthorityFor(stateDir);
|
|
4141
4546
|
if (!runtime) throw new Error("TRAVEL_PROCESS_ENROLLMENT_REQUIRED");
|
|
@@ -4155,10 +4560,13 @@ function installTravelEngineControl(options) {
|
|
|
4155
4560
|
};
|
|
4156
4561
|
const handler = async (message) => {
|
|
4157
4562
|
if (message?.format !== format || message.type !== "request" || typeof message.nonce !== "string" || !/^[a-f0-9-]{36}$/.test(message.nonce)) return;
|
|
4563
|
+
let phase = "binding";
|
|
4158
4564
|
try {
|
|
4159
4565
|
if (JSON.stringify(message.binding) !== JSON.stringify(binding) || JSON.stringify(travelProcessBinding(options.stateDir)) !== JSON.stringify(binding)) throw new Error();
|
|
4566
|
+
phase = "dispatch";
|
|
4160
4567
|
if (message.action === "status") send({ format, type: "response", nonce: message.nonce, binding, ok: true, result: { busy: options.isBusy(), draining: !!draining } });
|
|
4161
4568
|
else if (message.action === "drain") {
|
|
4569
|
+
phase = "operation";
|
|
4162
4570
|
draining ??= (async () => {
|
|
4163
4571
|
runtime.pauseInput(true);
|
|
4164
4572
|
while (options.isBusy()) {
|
|
@@ -4171,27 +4579,42 @@ function installTravelEngineControl(options) {
|
|
|
4171
4579
|
await draining;
|
|
4172
4580
|
send({ format, type: "response", nonce: message.nonce, binding, ok: true, result: { drained: true } });
|
|
4173
4581
|
} else if (message.action === "capture" && options.capture && !draining) {
|
|
4582
|
+
phase = "operation";
|
|
4174
4583
|
const result = await options.capture();
|
|
4584
|
+
phase = "control-check";
|
|
4175
4585
|
runtime.assert("CONTROL");
|
|
4176
4586
|
send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
|
|
4177
4587
|
} else if (message.action === "connect-peer" && options.connectPeer && !draining) {
|
|
4588
|
+
phase = "operation";
|
|
4178
4589
|
const result = await options.connectPeer(message.peer);
|
|
4590
|
+
phase = "control-check";
|
|
4179
4591
|
runtime.assert("CONTROL");
|
|
4180
4592
|
send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
|
|
4181
4593
|
} else if (message.action === "synchronize" && options.synchronize && !draining) {
|
|
4594
|
+
phase = "operation";
|
|
4182
4595
|
const result = await options.synchronize();
|
|
4596
|
+
phase = "control-check";
|
|
4183
4597
|
runtime.assert("CONTROL");
|
|
4184
4598
|
send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
|
|
4185
4599
|
} else if (message.action === "checkpoints" && options.checkpoints && !draining) {
|
|
4600
|
+
phase = "operation";
|
|
4186
4601
|
const result = await options.checkpoints(message.afterSequence);
|
|
4602
|
+
phase = "control-check";
|
|
4187
4603
|
runtime.assert("CONTROL");
|
|
4188
4604
|
send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
|
|
4189
4605
|
} else if (message.action === "seal" && options.seal && !draining) {
|
|
4606
|
+
phase = "operation";
|
|
4190
4607
|
const result = await options.seal();
|
|
4608
|
+
phase = "control-check";
|
|
4191
4609
|
runtime.assert("CONTROL");
|
|
4192
4610
|
send({ format, type: "response", nonce: message.nonce, binding, ok: true, result });
|
|
4193
4611
|
} else throw new Error();
|
|
4194
4612
|
} catch (error) {
|
|
4613
|
+
console.error("[travel-engine-control]", JSON.stringify({
|
|
4614
|
+
action: diagnosticActions.has(message.action) ? message.action : "unknown",
|
|
4615
|
+
phase,
|
|
4616
|
+
code: error instanceof Error && diagnosticCodes.has(error.message) ? error.message : "OTHER"
|
|
4617
|
+
}));
|
|
4195
4618
|
const code = error instanceof Error && error.message === "PUBLICATION_SOURCE_CHANGED" ? "PUBLICATION_SOURCE_CHANGED" : "TRAVEL_PROCESS_REFUSED";
|
|
4196
4619
|
send({ format, type: "response", nonce: message.nonce, binding, ok: false, error: code });
|
|
4197
4620
|
}
|
|
@@ -4625,7 +5048,7 @@ var RuntimeSyncScheduler = class {
|
|
|
4625
5048
|
};
|
|
4626
5049
|
|
|
4627
5050
|
// src/continuity/runtime-checkpoints.ts
|
|
4628
|
-
import { DatabaseSync as
|
|
5051
|
+
import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
|
|
4629
5052
|
var zero = "0".repeat(64);
|
|
4630
5053
|
var natural3 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
4631
5054
|
async function readPublishedRuntimeCheckpoints(options) {
|
|
@@ -4656,8 +5079,8 @@ async function openGenerationData(options) {
|
|
|
4656
5079
|
if (!runtime || !/^[a-f0-9]{64}$/.test(options.keySha256) || typeof options.initialize !== "boolean") throw new Error("TRAVEL_DATA_CONFIG");
|
|
4657
5080
|
const interval = options.intervalMs ?? 5e3;
|
|
4658
5081
|
if (!Number.isSafeInteger(interval) || interval < 250 || interval > 6e4) throw new Error("TRAVEL_DATA_CONFIG");
|
|
4659
|
-
const sourcePresent = ["source.json", "source.sqlite", "sender.sqlite"].some((file) => existsSync7(
|
|
4660
|
-
const archivePresent = ["archive.json", "archives.sqlite"].map((file) => existsSync7(
|
|
5082
|
+
const sourcePresent = ["source.json", "source.sqlite", "sender.sqlite"].some((file) => existsSync7(join15(options.dataDirectory, "runtime-publications", file)));
|
|
5083
|
+
const archivePresent = ["archive.json", "archives.sqlite"].map((file) => existsSync7(join15(options.dataDirectory, "recovery", file)));
|
|
4661
5084
|
if (sourcePresent && !archivePresent.every(Boolean) || !sourcePresent && archivePresent.some(Boolean)) throw new Error("RECOVERY_ARCHIVE_REQUIRED");
|
|
4662
5085
|
let checkedAt = -Infinity, checkedFloor = -1, closed = false, keyCheck;
|
|
4663
5086
|
let objects, opened, archive;
|
|
@@ -4683,11 +5106,15 @@ async function openGenerationData(options) {
|
|
|
4683
5106
|
})().finally(() => {
|
|
4684
5107
|
keyCheck = void 0;
|
|
4685
5108
|
});
|
|
4686
|
-
|
|
5109
|
+
const availableAfterWork = async () => {
|
|
5110
|
+
runtime.assert("CONTROL");
|
|
5111
|
+
if (clock() - checkedAt >= 1e4) await refresh();
|
|
5112
|
+
assertAvailable();
|
|
5113
|
+
};
|
|
5114
|
+
let keyTimer;
|
|
4687
5115
|
const close = () => closing ??= (async () => {
|
|
4688
5116
|
closed = true;
|
|
4689
5117
|
if (keyTimer) clearInterval(keyTimer);
|
|
4690
|
-
if (captureTimer) clearInterval(captureTimer);
|
|
4691
5118
|
client?.close();
|
|
4692
5119
|
await scheduler?.stop();
|
|
4693
5120
|
await active?.catch(() => {
|
|
@@ -4708,9 +5135,9 @@ async function openGenerationData(options) {
|
|
|
4708
5135
|
const restart = !!scheduler?.status().running;
|
|
4709
5136
|
await scheduler?.stop();
|
|
4710
5137
|
try {
|
|
4711
|
-
|
|
5138
|
+
await availableAfterWork();
|
|
4712
5139
|
const h = await opened.source.prepare(opened.capture());
|
|
4713
|
-
|
|
5140
|
+
await availableAfterWork();
|
|
4714
5141
|
if (!baseline) {
|
|
4715
5142
|
if (h.sequence !== 1) throw new Error("TRAVEL_DATA_BASELINE_REQUIRED");
|
|
4716
5143
|
baseline = await archive.preserve({
|
|
@@ -4718,13 +5145,13 @@ async function openGenerationData(options) {
|
|
|
4718
5145
|
kind: "LOCAL",
|
|
4719
5146
|
manifest: h.manifest,
|
|
4720
5147
|
databases: opened.databases,
|
|
4721
|
-
deletionWatermark: () => {
|
|
4722
|
-
|
|
5148
|
+
deletionWatermark: async () => {
|
|
5149
|
+
await availableAfterWork();
|
|
4723
5150
|
return runtime.deletionFloor();
|
|
4724
5151
|
}
|
|
4725
5152
|
});
|
|
4726
5153
|
}
|
|
4727
|
-
|
|
5154
|
+
await availableAfterWork();
|
|
4728
5155
|
return {
|
|
4729
5156
|
sequence: h.sequence,
|
|
4730
5157
|
digest: h.digest,
|
|
@@ -4755,10 +5182,6 @@ async function openGenerationData(options) {
|
|
|
4755
5182
|
assertAvailable();
|
|
4756
5183
|
if (!target.dataReady || !target.published || target.published.digest !== (await opened.source.read(target.published.sequence)).digest) throw new Error("TRAVEL_DATA_PEER_BASELINE");
|
|
4757
5184
|
assertAvailable();
|
|
4758
|
-
if (captureTimer) {
|
|
4759
|
-
clearInterval(captureTimer);
|
|
4760
|
-
captureTimer = void 0;
|
|
4761
|
-
}
|
|
4762
5185
|
client = candidate;
|
|
4763
5186
|
candidate = void 0;
|
|
4764
5187
|
peerBinding = binding;
|
|
@@ -4810,19 +5233,19 @@ async function openGenerationData(options) {
|
|
|
4810
5233
|
const restart = !!scheduler?.status().running;
|
|
4811
5234
|
await scheduler?.stop();
|
|
4812
5235
|
try {
|
|
4813
|
-
|
|
5236
|
+
await availableAfterWork();
|
|
4814
5237
|
const h = await opened.source.prepare(opened.capture());
|
|
4815
5238
|
const receipt = await archive.preserve({
|
|
4816
5239
|
id: "local-" + h.digest,
|
|
4817
5240
|
kind: "LOCAL",
|
|
4818
5241
|
manifest: h.manifest,
|
|
4819
5242
|
databases: opened.databases,
|
|
4820
|
-
deletionWatermark: () => {
|
|
4821
|
-
|
|
5243
|
+
deletionWatermark: async () => {
|
|
5244
|
+
await availableAfterWork();
|
|
4822
5245
|
return runtime.deletionFloor();
|
|
4823
5246
|
}
|
|
4824
5247
|
});
|
|
4825
|
-
|
|
5248
|
+
await availableAfterWork();
|
|
4826
5249
|
return { sequence: h.sequence, digest: h.digest, archive: receipt };
|
|
4827
5250
|
} finally {
|
|
4828
5251
|
if (restart && !closed) scheduler.start();
|
|
@@ -4835,8 +5258,12 @@ async function openGenerationData(options) {
|
|
|
4835
5258
|
};
|
|
4836
5259
|
try {
|
|
4837
5260
|
await refresh();
|
|
5261
|
+
keyTimer = setInterval(() => {
|
|
5262
|
+
void refresh().catch(() => {
|
|
5263
|
+
});
|
|
5264
|
+
}, 1e4);
|
|
4838
5265
|
opened = await openRuntimeGenerationSource({ stateDir: options.stateDir, dataDirectory: options.dataDirectory, objects, initialize: options.initialize, mode: "LIVE" });
|
|
4839
|
-
archive = await RuntimeRecoveryArchive.open({ directory:
|
|
5266
|
+
archive = await RuntimeRecoveryArchive.open({ directory: join15(options.dataDirectory, "recovery"), objects, initialize: options.initialize });
|
|
4840
5267
|
const id2 = "baseline-" + hash2(JSON.stringify(opened.profile));
|
|
4841
5268
|
try {
|
|
4842
5269
|
baseline = (await archive.read(id2)).receipt;
|
|
@@ -4844,16 +5271,9 @@ async function openGenerationData(options) {
|
|
|
4844
5271
|
if (!(error instanceof Error) || error.message !== "RECOVERY_ARCHIVE_NOT_FOUND") throw error;
|
|
4845
5272
|
}
|
|
4846
5273
|
if (baseline && (baseline.kind !== "LOCAL" || baseline.manifestDigest !== (await opened.source.read(1)).digest)) throw new Error("TRAVEL_DATA_BASELINE_REQUIRED");
|
|
4847
|
-
await
|
|
5274
|
+
if (baseline) await availableAfterWork();
|
|
5275
|
+
else await capture2();
|
|
4848
5276
|
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
5277
|
return {
|
|
4858
5278
|
capture: capture2,
|
|
4859
5279
|
connectPeer,
|
|
@@ -4862,6 +5282,7 @@ async function openGenerationData(options) {
|
|
|
4862
5282
|
close,
|
|
4863
5283
|
isBusy: () => !!active || !!scheduler?.status().inFlight,
|
|
4864
5284
|
assertAvailable,
|
|
5285
|
+
refreshAvailability: availableAfterWork,
|
|
4865
5286
|
checkpoints: (afterSequence) => readPublishedRuntimeCheckpoints({ source: opened.source, afterSequence, assertAvailable }),
|
|
4866
5287
|
status: () => ({ head: opened.source.head(), baseline, sync: scheduler?.status() ?? null })
|
|
4867
5288
|
};
|
|
@@ -4909,15 +5330,21 @@ async function runGenerationDataCli(args) {
|
|
|
4909
5330
|
process.off("disconnect", stop);
|
|
4910
5331
|
void data.close().then(resolveStop, rejectStop);
|
|
4911
5332
|
};
|
|
5333
|
+
let checking, lastFailure;
|
|
4912
5334
|
const guard = setInterval(() => {
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
|
|
4917
|
-
|
|
5335
|
+
if (stopping || checking) return;
|
|
5336
|
+
checking = data.refreshAvailability().then(() => {
|
|
5337
|
+
lastFailure = void 0;
|
|
5338
|
+
}).catch((error) => {
|
|
5339
|
+
const code = error instanceof Error && /^(?:TRAVEL|KEY_SERVICE)_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_DATA_UNAVAILABLE";
|
|
5340
|
+
if (code !== lastFailure) process.stderr.write("[travel-data] " + code + "\n");
|
|
5341
|
+
lastFailure = code;
|
|
5342
|
+
if (["TRAVEL_NODE_KEY_UNAVAILABLE", "KEY_SERVICE_TIMEOUT", "KEY_SERVICE_CONNECTION_FAILED"].includes(code)) return;
|
|
4918
5343
|
process.exitCode = 1;
|
|
4919
5344
|
stop();
|
|
4920
|
-
}
|
|
5345
|
+
}).finally(() => {
|
|
5346
|
+
checking = void 0;
|
|
5347
|
+
});
|
|
4921
5348
|
}, 1e3);
|
|
4922
5349
|
process.once("SIGTERM", stop);
|
|
4923
5350
|
process.once("SIGINT", stop);
|