engine7 7.1.140 → 7.1.142
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/dist/bg-worker.mjs +16 -4
- package/dist/cli.mjs +4003 -1168
- package/dist/engine-startup.mjs +3136 -2143
- package/dist/main.mjs +3142 -2149
- package/dist/recall-worker.mjs +14 -2
- package/dist/sqlite-maintenance-worker.mjs +1 -1
- package/dist/topics-worker.mjs +56 -10
- package/dist/travel-activation-database.mjs +1077 -0
- package/dist/travel-authority.mjs +9 -3
- package/dist/travel-console.mjs +29 -17
- package/dist/travel-controller.mjs +16 -4
- package/dist/travel-data.mjs +364 -266
- package/dist/travel-gateway.mjs +559 -147
- package/dist/travel-host.mjs +1779 -1643
- package/dist/travel-initial-baseline.mjs +5961 -0
- package/dist/travel-node-data.mjs +149 -46
- package/dist/travel-node.mjs +1471 -1246
- package/dist/travel-pairing.mjs +562 -149
- package/dist/web-console.mjs +1065 -1449
- package/dlls/win32/msvcp140.dll +0 -0
- package/dlls/win32/vcruntime140.dll +0 -0
- package/dlls/win32/vcruntime140_1.dll +0 -0
- package/package.json +5 -3
|
@@ -0,0 +1,1077 @@
|
|
|
1
|
+
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
|
+
|
|
3
|
+
// src/continuity/key-service-store.ts
|
|
4
|
+
import { DatabaseSync } from "node:sqlite";
|
|
5
|
+
import { constants, lstatSync, mkdirSync, openSync, closeSync, readFileSync, writeSync, fstatSync, fsyncSync, unlinkSync } from "node:fs";
|
|
6
|
+
function assertPrivateStat(stat, directory2) {
|
|
7
|
+
if ((directory2 ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
8
|
+
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
9
|
+
}
|
|
10
|
+
function readPrivateFile(path, maximumBytes = 65536) {
|
|
11
|
+
assertPrivateStat(lstatSync(path), false);
|
|
12
|
+
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
13
|
+
try {
|
|
14
|
+
const stat = fstatSync(fd);
|
|
15
|
+
assertPrivateStat(stat, false);
|
|
16
|
+
if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
17
|
+
return readFileSync(fd);
|
|
18
|
+
} finally {
|
|
19
|
+
closeSync(fd);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/continuity/activation-database-main.ts
|
|
24
|
+
import { realpathSync as realpathSync3 } from "node:fs";
|
|
25
|
+
import { resolve as resolve6, join as join6 } from "node:path";
|
|
26
|
+
|
|
27
|
+
// src/continuity/inventory.ts
|
|
28
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
29
|
+
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(" "));
|
|
30
|
+
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 topics .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
|
|
31
|
+
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(" "));
|
|
32
|
+
function isWithin(root, candidate) {
|
|
33
|
+
const rel = relative(resolve(root), resolve(candidate));
|
|
34
|
+
return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/continuity/activation-database.ts
|
|
38
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
39
|
+
|
|
40
|
+
// src/continuity/sqlite-store-location.ts
|
|
41
|
+
import { basename as basename3, dirname as dirname5, resolve as resolve5 } from "node:path";
|
|
42
|
+
|
|
43
|
+
// src/continuity/mem7-replication.ts
|
|
44
|
+
import { closeSync as closeSync4, fsyncSync as fsyncSync4, lstatSync as lstatSync4, openSync as openSync4, writeFileSync as writeFileSync2 } from "node:fs";
|
|
45
|
+
import { dirname as dirname3, join as join4 } from "node:path";
|
|
46
|
+
|
|
47
|
+
// src/continuity/publication-objects.ts
|
|
48
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
49
|
+
import {
|
|
50
|
+
constants as constants2,
|
|
51
|
+
openSync as openSync2,
|
|
52
|
+
closeSync as closeSync2,
|
|
53
|
+
fstatSync as fstatSync2,
|
|
54
|
+
fsyncSync as fsyncSync2,
|
|
55
|
+
readSync,
|
|
56
|
+
lstatSync as lstatSync2,
|
|
57
|
+
realpathSync,
|
|
58
|
+
mkdirSync as mkdirSync2
|
|
59
|
+
} from "node:fs";
|
|
60
|
+
import { join as join2, dirname, resolve as resolve2 } from "node:path";
|
|
61
|
+
var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
|
|
62
|
+
var MAGIC = Buffer.from("E7P1");
|
|
63
|
+
var INLINE_BYTES = 64 * 1024;
|
|
64
|
+
var noFollow = constants2.O_NOFOLLOW ?? 0;
|
|
65
|
+
function assertPrivateDirectory(path) {
|
|
66
|
+
const info = lstatSync2(path);
|
|
67
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path) !== resolve2(path) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
68
|
+
throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
69
|
+
}
|
|
70
|
+
function syncDir(path) {
|
|
71
|
+
if (process.platform === "win32") return;
|
|
72
|
+
const fd = openSync2(path, constants2.O_RDONLY);
|
|
73
|
+
try {
|
|
74
|
+
fsyncSync2(fd);
|
|
75
|
+
} finally {
|
|
76
|
+
closeSync2(fd);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function preparePrivateDirectory(path) {
|
|
80
|
+
const missing = [];
|
|
81
|
+
let parent = resolve2(path);
|
|
82
|
+
for (; ; ) {
|
|
83
|
+
try {
|
|
84
|
+
lstatSync2(parent);
|
|
85
|
+
break;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error.code !== "ENOENT") throw error;
|
|
88
|
+
}
|
|
89
|
+
missing.push(parent);
|
|
90
|
+
parent = dirname(parent);
|
|
91
|
+
}
|
|
92
|
+
if (realpathSync(parent) !== parent) throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
93
|
+
for (const directory2 of missing.reverse()) {
|
|
94
|
+
try {
|
|
95
|
+
mkdirSync2(directory2, { mode: 448 });
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error.code !== "EEXIST") throw error;
|
|
98
|
+
}
|
|
99
|
+
assertPrivateDirectory(directory2);
|
|
100
|
+
syncDir(dirname(directory2));
|
|
101
|
+
}
|
|
102
|
+
assertPrivateDirectory(path);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/continuity/sqlite-replication.ts
|
|
106
|
+
import { createHash } from "node:crypto";
|
|
107
|
+
import { createRequire } from "node:module";
|
|
108
|
+
|
|
109
|
+
// src/memory/schema-migrations.ts
|
|
110
|
+
function authorizeMemoryWriter(db, supportedVersion) {
|
|
111
|
+
db.function("engine_memory_writer_version", () => supportedVersion);
|
|
112
|
+
}
|
|
113
|
+
function installWriterGuards(db) {
|
|
114
|
+
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();
|
|
115
|
+
for (const { name } of tables) {
|
|
116
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) throw new Error("INVALID_MEMORY_TABLE_NAME");
|
|
117
|
+
for (const operation of ["INSERT", "UPDATE", "DELETE"]) {
|
|
118
|
+
db.exec(`CREATE TRIGGER IF NOT EXISTS writer_guard_${name}_${operation.toLowerCase()} BEFORE ${operation} ON ${name}
|
|
119
|
+
BEGIN SELECT CASE WHEN engine_memory_writer_version() < (SELECT version FROM engine_schema_version WHERE singleton=1)
|
|
120
|
+
THEN RAISE(ABORT,'MEMORY_WRITER_VERSION_UNSUPPORTED') END; END`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function readSchemaVersion(db) {
|
|
125
|
+
const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='engine_schema_version'").get();
|
|
126
|
+
if (!table) return null;
|
|
127
|
+
const row = db.prepare("SELECT component, version FROM engine_schema_version WHERE singleton=1").get();
|
|
128
|
+
if (!row || !Number.isSafeInteger(row.version) || row.version < 1) {
|
|
129
|
+
throw new Error("Invalid engine schema version metadata");
|
|
130
|
+
}
|
|
131
|
+
return row;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/continuity/legacy-sqlite-indexes.ts
|
|
135
|
+
var ftsColumns = ["text", "id", "path", "source", "model", "start_line", "end_line"];
|
|
136
|
+
var chunkColumns = ["id", "path", "source", "start_line", "end_line", "hash", "model", "text", "embedding", "updated_at"];
|
|
137
|
+
var quote = (name) => '"' + name.replaceAll('"', '""') + '"';
|
|
138
|
+
var unsupported = (name) => {
|
|
139
|
+
throw new Error("REPLICATION_UNSUPPORTED_SCHEMA: " + name);
|
|
140
|
+
};
|
|
141
|
+
var columns = (db, name) => db.prepare("PRAGMA table_info(" + quote(name) + ")").all().map((r) => [String(r.name), String(r.type).toUpperCase(), Number(r.notnull), Number(r.pk)]);
|
|
142
|
+
function inspectLegacySQLiteIndexes(db) {
|
|
143
|
+
const version = readSchemaVersion(db);
|
|
144
|
+
if (version?.component !== "legacy-memory") return null;
|
|
145
|
+
if (version.version !== 1) unsupported("legacy-memory version");
|
|
146
|
+
for (const [name, names] of [
|
|
147
|
+
["meta", ["key", "value"]],
|
|
148
|
+
["files", ["path", "source", "hash", "mtime", "size"]],
|
|
149
|
+
["chunks", chunkColumns]
|
|
150
|
+
]) if (JSON.stringify(columns(db, name).map((c) => c[0])) !== JSON.stringify(names)) unsupported(name);
|
|
151
|
+
const rows = db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table'").all();
|
|
152
|
+
const types = new Map(db.prepare("PRAGMA table_list").all().filter((r) => r.schema === "main").map((r) => [String(r.name), String(r.type)]));
|
|
153
|
+
const excludedTables = /* @__PURE__ */ new Set();
|
|
154
|
+
const storage = (name, shape, type) => {
|
|
155
|
+
if (types.get(name) !== type || JSON.stringify(columns(db, name)) !== JSON.stringify(shape)) unsupported(name);
|
|
156
|
+
excludedTables.add(name);
|
|
157
|
+
};
|
|
158
|
+
const fts = rows.find((r) => r.name === "chunks_fts");
|
|
159
|
+
if (fts) {
|
|
160
|
+
if (!/^CREATE\s+VIRTUAL\s+TABLE\s+chunks_fts\s+USING\s+fts5\s*\(/i.test(fts.sql) || JSON.stringify(columns(db, "chunks_fts").map((c) => c[0])) !== JSON.stringify(ftsColumns)) unsupported("chunks_fts");
|
|
161
|
+
excludedTables.add("chunks_fts");
|
|
162
|
+
storage("chunks_fts_data", [["id", "INTEGER", 0, 1], ["block", "BLOB", 0, 0]], "shadow");
|
|
163
|
+
storage("chunks_fts_idx", [["segid", "", 1, 1], ["term", "", 1, 2], ["pgno", "", 0, 0]], "shadow");
|
|
164
|
+
storage("chunks_fts_content", [["id", "INTEGER", 0, 1], ...ftsColumns.map((_, i) => ["c" + i, "", 0, 0])], "shadow");
|
|
165
|
+
storage("chunks_fts_docsize", [["id", "INTEGER", 0, 1], ["sz", "BLOB", 0, 0]], "shadow");
|
|
166
|
+
storage("chunks_fts_config", [["k", "", 1, 1], ["v", "", 0, 0]], "shadow");
|
|
167
|
+
}
|
|
168
|
+
const vec = rows.find((r) => r.name === "chunks_vec");
|
|
169
|
+
let dimensions;
|
|
170
|
+
if (vec) {
|
|
171
|
+
const match = /^CREATE\s+VIRTUAL\s+TABLE\s+chunks_vec\s+USING\s+vec0\s*\(\s*id\s+TEXT\s+PRIMARY\s+KEY\s*,\s*embedding\s+FLOAT\[(\d+)\]\s*\)$/i.exec(vec.sql);
|
|
172
|
+
if (!match) return unsupported("chunks_vec");
|
|
173
|
+
if (Number(match[1]) < 1 || Number(match[1]) > 8192) unsupported("chunks_vec");
|
|
174
|
+
dimensions = Number(match[1]);
|
|
175
|
+
storage("chunks_vec", [["id", "", 1, 1], ["embedding", "", 0, 0]], "virtual");
|
|
176
|
+
storage("chunks_vec_info", [["key", "TEXT", 0, 1], ["value", "ANY", 0, 0]], "shadow");
|
|
177
|
+
storage("chunks_vec_chunks", [["chunk_id", "INTEGER", 0, 1], ["size", "INTEGER", 1, 0], ["validity", "BLOB", 1, 0], ["rowids", "BLOB", 1, 0]], "shadow");
|
|
178
|
+
storage("chunks_vec_rowids", [["rowid", "INTEGER", 0, 1], ["id", "TEXT", 1, 0], ["chunk_id", "INTEGER", 0, 0], ["chunk_offset", "INTEGER", 0, 0]], "shadow");
|
|
179
|
+
storage("chunks_vec_vector_chunks00", [["rowid", "", 0, 1], ["vectors", "BLOB", 1, 0]], "table");
|
|
180
|
+
}
|
|
181
|
+
for (const row of rows) {
|
|
182
|
+
if (/^chunks_vec_(?:vector_chunks|metadata|auxiliary)/.test(row.name) && !excludedTables.has(row.name)) unsupported(row.name);
|
|
183
|
+
if (types.get(row.name) === "shadow" && /^(?:chunks_fts|chunks_vec)_/.test(row.name) && !excludedTables.has(row.name)) unsupported(row.name);
|
|
184
|
+
}
|
|
185
|
+
const vector = (value) => {
|
|
186
|
+
let parsed;
|
|
187
|
+
try {
|
|
188
|
+
parsed = JSON.parse(String(value));
|
|
189
|
+
} catch {
|
|
190
|
+
throw new Error("REPLICATION_LEGACY_VECTOR_INVALID");
|
|
191
|
+
}
|
|
192
|
+
if (!Array.isArray(parsed) || parsed.some((v) => typeof v !== "number" || !Number.isFinite(v))) throw new Error("REPLICATION_LEGACY_VECTOR_INVALID");
|
|
193
|
+
return parsed.length === dimensions ? Buffer.from(Float32Array.from(parsed).buffer) : null;
|
|
194
|
+
};
|
|
195
|
+
const installFunction = () => {
|
|
196
|
+
if (vec) db.function("engine7_replication_legacy_vector", { deterministic: true }, vector);
|
|
197
|
+
};
|
|
198
|
+
const remove = (row) => (fts ? "DELETE FROM chunks_fts WHERE id=" + row + ".id;" : "") + (vec ? "DELETE FROM chunks_vec WHERE id=" + row + ".id;" : "");
|
|
199
|
+
const write = (row) => remove(row) + (fts ? "INSERT INTO chunks_fts(" + ftsColumns.join(",") + ") VALUES(" + ftsColumns.map((c) => row + "." + c).join(",") + ");" : "") + (vec ? `INSERT INTO chunks_vec(id,embedding) SELECT ${row}.id,engine7_replication_legacy_vector(${row}.embedding)
|
|
200
|
+
WHERE engine7_replication_legacy_vector(${row}.embedding) IS NOT NULL;` : "");
|
|
201
|
+
return {
|
|
202
|
+
excludedTables,
|
|
203
|
+
rebuild() {
|
|
204
|
+
installFunction();
|
|
205
|
+
if (fts) db.exec("DELETE FROM chunks_fts; INSERT INTO chunks_fts(" + ftsColumns.join(",") + ") SELECT " + ftsColumns.join(",") + " FROM chunks");
|
|
206
|
+
if (vec) {
|
|
207
|
+
db.exec("DELETE FROM chunks_vec");
|
|
208
|
+
const insert = db.prepare("INSERT INTO chunks_vec(id,embedding) VALUES(?,?)");
|
|
209
|
+
for (const row of db.prepare("SELECT id,embedding FROM chunks").iterate()) {
|
|
210
|
+
const blob = vector(row.embedding);
|
|
211
|
+
if (blob) insert.run(row.id, blob);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
beforeApply() {
|
|
216
|
+
if (!excludedTables.size) return () => {
|
|
217
|
+
};
|
|
218
|
+
installFunction();
|
|
219
|
+
const names = ["insert", "update", "delete"].map((op) => "e7_legacy_replica_" + op);
|
|
220
|
+
const cleanup = () => {
|
|
221
|
+
for (const name of names) db.exec("DROP TRIGGER IF EXISTS temp." + quote(name));
|
|
222
|
+
};
|
|
223
|
+
if (db.prepare("SELECT 1 FROM sqlite_temp_master WHERE type='trigger' AND name IN (?,?,?)").get(...names)) throw new Error("REPLICATION_LEGACY_TRIGGER_COLLISION");
|
|
224
|
+
try {
|
|
225
|
+
db.exec(`CREATE TEMP TRIGGER ${names[0]} AFTER INSERT ON main.chunks BEGIN ${write("NEW")} END;
|
|
226
|
+
CREATE TEMP TRIGGER ${names[1]} AFTER UPDATE ON main.chunks BEGIN ${remove("OLD") + write("NEW")} END;
|
|
227
|
+
CREATE TEMP TRIGGER ${names[2]} AFTER DELETE ON main.chunks BEGIN ${remove("OLD")} END;`);
|
|
228
|
+
return cleanup;
|
|
229
|
+
} catch (error) {
|
|
230
|
+
cleanup();
|
|
231
|
+
throw error;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// src/continuity/runtime-authority.ts
|
|
238
|
+
import { randomUUID, verify } from "node:crypto";
|
|
239
|
+
import { constants as constants3, closeSync as closeSync3, existsSync, fstatSync as fstatSync3, fsyncSync as fsyncSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
|
|
240
|
+
import { basename, dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
|
|
241
|
+
var runtimes = /* @__PURE__ */ new Map();
|
|
242
|
+
var now = () => Number(process.hrtime.bigint() / 1000000n);
|
|
243
|
+
var equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
244
|
+
function assertPrivateDirectory2(path) {
|
|
245
|
+
const stat = lstatSync3(path);
|
|
246
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || process.platform !== "win32" && (stat.uid !== process.getuid() || stat.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
|
|
247
|
+
}
|
|
248
|
+
function readPrivateFile2(path, maximum) {
|
|
249
|
+
const before = lstatSync3(path);
|
|
250
|
+
if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
|
|
251
|
+
const fd = openSync3(path, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
|
|
252
|
+
try {
|
|
253
|
+
if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
|
|
254
|
+
return readFileSync2(fd);
|
|
255
|
+
} finally {
|
|
256
|
+
closeSync3(fd);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function writeControl(path, value) {
|
|
260
|
+
const temporary = path + "." + randomUUID() + ".tmp";
|
|
261
|
+
writeFileSync(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
|
|
262
|
+
renameSync(temporary, path);
|
|
263
|
+
if (process.platform !== "win32") {
|
|
264
|
+
const fd = openSync3(dirname2(path), "r");
|
|
265
|
+
try {
|
|
266
|
+
fsyncSync3(fd);
|
|
267
|
+
} finally {
|
|
268
|
+
closeSync3(fd);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
var RuntimeAuthority = class {
|
|
273
|
+
stateDir;
|
|
274
|
+
enrollment;
|
|
275
|
+
directory;
|
|
276
|
+
clock;
|
|
277
|
+
previous;
|
|
278
|
+
cachedGrant = null;
|
|
279
|
+
cachedFloor = 0;
|
|
280
|
+
constructor(options) {
|
|
281
|
+
this.stateDir = resolve3(options.stateDir);
|
|
282
|
+
this.directory = join3(this.stateDir, ".continuity");
|
|
283
|
+
this.clock = options.monotonicNow ?? now;
|
|
284
|
+
const tools = options.allowedTools ?? [];
|
|
285
|
+
if (!Array.isArray(tools) || tools.length > 1024 || tools.some((t) => typeof t !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(t))) throw new Error("TRAVEL_INVALID_CAPABILITIES");
|
|
286
|
+
this.enrollment = { format: "engine7-travel-runtime-v1", identity: options.identity, nodeId: options.nodeId, bootId: options.bootId, publicKey: options.publicKey, allowedTools: [...new Set(tools)].sort() };
|
|
287
|
+
if (options.initialize) {
|
|
288
|
+
mkdirSync3(this.directory, { mode: 448, recursive: true });
|
|
289
|
+
assertPrivateDirectory2(this.directory);
|
|
290
|
+
const file = join3(this.directory, "travel-runtime.json");
|
|
291
|
+
if (!existsSync(file)) writeFileSync(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
|
|
292
|
+
const marker = join3(this.stateDir, ".travel-enrolled.json");
|
|
293
|
+
if (!existsSync(marker)) writeFileSync(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
|
|
294
|
+
}
|
|
295
|
+
this.checkEnrollment();
|
|
296
|
+
this.previous = runtimes.get(this.stateDir);
|
|
297
|
+
runtimes.set(this.stateDir, this);
|
|
298
|
+
}
|
|
299
|
+
checkEnrollment() {
|
|
300
|
+
try {
|
|
301
|
+
assertPrivateDirectory2(this.directory);
|
|
302
|
+
const existing = JSON.parse(readPrivateFile2(join3(this.directory, "travel-runtime.json"), 16384).toString());
|
|
303
|
+
if (!equal(existing, this.enrollment)) throw new Error("TRAVEL_RUNTIME_IDENTITY_MISMATCH");
|
|
304
|
+
} catch (error) {
|
|
305
|
+
throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED", { cause: error });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
grant() {
|
|
309
|
+
this.checkEnrollment();
|
|
310
|
+
const file = join3(this.directory, "travel-permit.json");
|
|
311
|
+
if (!existsSync(file)) return null;
|
|
312
|
+
try {
|
|
313
|
+
const grant = JSON.parse(readPrivateFile2(file, 16384).toString());
|
|
314
|
+
if (typeof grant.frozen !== "boolean" || grant.inputPaused !== void 0 && typeof grant.inputPaused !== "boolean" || !Number.isSafeInteger(grant.epoch) || grant.epoch < 1 || !Number.isSafeInteger(grant.leaseSequence) || grant.leaseSequence < 1 || !Number.isFinite(grant.requestStartedAt)) throw new Error();
|
|
315
|
+
return grant;
|
|
316
|
+
} catch (error) {
|
|
317
|
+
throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED", { cause: error });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
writeGrant(grant) {
|
|
321
|
+
this.checkEnrollment();
|
|
322
|
+
writeControl(join3(this.directory, "travel-permit.json"), grant);
|
|
323
|
+
this.cachedGrant = grant;
|
|
324
|
+
}
|
|
325
|
+
validatePermit(permit) {
|
|
326
|
+
try {
|
|
327
|
+
const { signature, ...body } = permit;
|
|
328
|
+
if (!verify(null, Buffer.from(JSON.stringify(body)), this.enrollment.publicKey, Buffer.from(signature, "base64"))) throw new Error();
|
|
329
|
+
} catch {
|
|
330
|
+
throw new Error("TRAVEL_INVALID_PERMIT");
|
|
331
|
+
}
|
|
332
|
+
const { identity, nodeId, bootId } = this.enrollment;
|
|
333
|
+
if (permit.nodeId !== nodeId || permit.bootId !== bootId || permit.tenantId !== identity.tenantId || permit.companionId !== identity.companionId || permit.seatId !== identity.seatId) throw new Error("TRAVEL_PERMIT_IDENTITY_MISMATCH");
|
|
334
|
+
if (!Number.isSafeInteger(permit.validForMs) || permit.validForMs < 1 || permit.validForMs > 3e5 || !Number.isSafeInteger(permit.epoch) || permit.epoch < 1 || !Number.isSafeInteger(permit.deletionWatermark) || permit.deletionWatermark < 0 || !Number.isSafeInteger(permit.leaseSequence) || permit.leaseSequence < 1) throw new Error("TRAVEL_INVALID_PERMIT");
|
|
335
|
+
}
|
|
336
|
+
acceptPermit(permit, requestStartedAt) {
|
|
337
|
+
this.validatePermit(permit);
|
|
338
|
+
const current = this.grant();
|
|
339
|
+
if (current && (permit.epoch < current.epoch || permit.authorityBootId === current.authorityBootId && permit.leaseSequence <= current.leaseSequence)) throw new Error("TRAVEL_PERMIT_REPLAY");
|
|
340
|
+
const receivedAt = this.clock();
|
|
341
|
+
if (!Number.isFinite(requestStartedAt) || requestStartedAt > receivedAt || receivedAt >= requestStartedAt + permit.validForMs) throw new Error("TRAVEL_LEASE_EXPIRED");
|
|
342
|
+
this.writeGrant({ permit, requestStartedAt, frozen: current?.frozen ?? false, inputPaused: current?.inputPaused ?? false, epoch: permit.epoch, authorityBootId: permit.authorityBootId, leaseSequence: permit.leaseSequence });
|
|
343
|
+
}
|
|
344
|
+
assert(operation, binding) {
|
|
345
|
+
const grant = this.grant();
|
|
346
|
+
if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
347
|
+
this.validatePermit(grant.permit);
|
|
348
|
+
this.cachedFloor = this.deletionFloor();
|
|
349
|
+
this.cachedGrant = grant;
|
|
350
|
+
return this.assertFast(operation, binding);
|
|
351
|
+
}
|
|
352
|
+
/** Only for a synchronous SQLite capture whose BEGIN and COMMIT re-read the
|
|
353
|
+
* control files. In-transaction rows never publish past a changed barrier. */
|
|
354
|
+
assertFast(operation, binding) {
|
|
355
|
+
const grant = this.cachedGrant;
|
|
356
|
+
if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
357
|
+
const current = this.clock(), deadline = grant.requestStartedAt + grant.permit.validForMs;
|
|
358
|
+
if (current < grant.requestStartedAt || current >= deadline) throw new Error("TRAVEL_LEASE_EXPIRED");
|
|
359
|
+
if (operation !== "CONTROL" && grant.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
|
|
360
|
+
if (operation === "INPUT" && grant.inputPaused) throw new Error("TRAVEL_INPUT_PAUSED");
|
|
361
|
+
if (operation !== "CONTROL" && grant.permit.deletionWatermark !== this.cachedFloor) throw new Error("TRAVEL_DELETION_BARRIER");
|
|
362
|
+
if (binding && (binding.tenantId !== grant.permit.tenantId || binding.companionId !== grant.permit.companionId || binding.seatId !== grant.permit.seatId || binding.epoch !== grant.permit.epoch)) throw new Error("TRAVEL_STALE_WRITER_EPOCH");
|
|
363
|
+
return grant.permit;
|
|
364
|
+
}
|
|
365
|
+
deletionFloor() {
|
|
366
|
+
const file = join3(this.directory, "travel-deletion-floor.json");
|
|
367
|
+
if (!existsSync(file)) return 0;
|
|
368
|
+
const value = JSON.parse(readPrivateFile2(file, 128).toString());
|
|
369
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
|
|
370
|
+
return value;
|
|
371
|
+
}
|
|
372
|
+
advanceDeletionFloor(floor) {
|
|
373
|
+
if (!Number.isSafeInteger(floor) || floor < this.deletionFloor()) throw new Error("TRAVEL_DELETION_ROLLBACK");
|
|
374
|
+
writeControl(join3(this.directory, "travel-deletion-floor.json"), floor);
|
|
375
|
+
this.cachedFloor = floor;
|
|
376
|
+
}
|
|
377
|
+
freeze(frozen) {
|
|
378
|
+
const grant = this.grant();
|
|
379
|
+
if (!grant) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
380
|
+
if (grant.permit) this.validatePermit(grant.permit);
|
|
381
|
+
this.writeGrant({ ...grant, frozen });
|
|
382
|
+
}
|
|
383
|
+
pauseInput(paused) {
|
|
384
|
+
if (typeof paused !== "boolean") throw new Error("TRAVEL_INVALID_CONTROL");
|
|
385
|
+
const grant = this.grant();
|
|
386
|
+
if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
387
|
+
this.validatePermit(grant.permit);
|
|
388
|
+
this.writeGrant({ ...grant, inputPaused: paused });
|
|
389
|
+
}
|
|
390
|
+
revoke() {
|
|
391
|
+
const grant = this.grant();
|
|
392
|
+
if (grant) this.writeGrant({ ...grant, permit: null });
|
|
393
|
+
}
|
|
394
|
+
close() {
|
|
395
|
+
if (runtimes.get(this.stateDir) === this) {
|
|
396
|
+
if (this.previous) runtimes.set(this.stateDir, this.previous);
|
|
397
|
+
else runtimes.delete(this.stateDir);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
function runtimeAuthorityFor(stateDir) {
|
|
402
|
+
for (let root = resolve3(stateDir); ; ) {
|
|
403
|
+
const existing = runtimes.get(root);
|
|
404
|
+
if (existing) return existing;
|
|
405
|
+
const file = join3(root, ".continuity", "travel-runtime.json");
|
|
406
|
+
if (existsSync(file)) {
|
|
407
|
+
const enrollment = JSON.parse(readPrivateFile2(file, 16384).toString());
|
|
408
|
+
if (enrollment.format !== "engine7-travel-runtime-v1") throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
|
|
409
|
+
return new RuntimeAuthority({ stateDir: root, ...enrollment });
|
|
410
|
+
}
|
|
411
|
+
if (existsSync(join3(root, ".travel-active.json")) || existsSync(join3(root, ".travel-enrolled.json"))) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
|
|
412
|
+
const parent = dirname2(root);
|
|
413
|
+
if (parent === root) return null;
|
|
414
|
+
root = parent;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
function databaseRuntimeAuthorityFor(db) {
|
|
418
|
+
const file = String(db.prepare("PRAGMA database_list").all().find((r) => r.name === "main")?.file ?? "");
|
|
419
|
+
if (!file) return null;
|
|
420
|
+
const parent = dirname2(file), name = basename(file);
|
|
421
|
+
let root;
|
|
422
|
+
if (name === "mem7.db" && basename(parent) === "index" && basename(dirname2(parent)) === "mem7") root = dirname2(dirname2(parent));
|
|
423
|
+
else if (name === "calendar.db" && basename(parent) === ".calendar" || name === "proactive.db" && basename(parent) === ".proactive" || name === "session-events.db" && basename(parent) === ".continuity") root = dirname2(parent);
|
|
424
|
+
else if (name === "memory.db" && basename(parent) === "memory" && basename(dirname2(dirname2(parent))) === "agents") root = dirname2(dirname2(dirname2(parent)));
|
|
425
|
+
else if (name === "vectors.db" && basename(dirname2(parent)) === "topics-history") root = dirname2(dirname2(parent));
|
|
426
|
+
return root ? runtimeAuthorityFor(root) : null;
|
|
427
|
+
}
|
|
428
|
+
function assertDatabaseRuntimeAuthority(db, binding) {
|
|
429
|
+
databaseRuntimeAuthorityFor(db)?.assert("WRITE", binding);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// src/continuity/sqlite-replication.ts
|
|
433
|
+
var constants4;
|
|
434
|
+
function sqliteConstants() {
|
|
435
|
+
return constants4 ??= createRequire(import.meta.url)("node:sqlite").constants;
|
|
436
|
+
}
|
|
437
|
+
var metadataTables = /* @__PURE__ */ new Set(["e7_replication_control", "e7_replication_outbox", "e7_replication_inbox"]);
|
|
438
|
+
var metadataColumns = {
|
|
439
|
+
e7_replication_control: [
|
|
440
|
+
["role", "TEXT", 0, 1],
|
|
441
|
+
["binding", "TEXT", 1, 0],
|
|
442
|
+
["schema_hash", "TEXT", 1, 0],
|
|
443
|
+
["head", "INTEGER", 1, 0],
|
|
444
|
+
["digest", "TEXT", 1, 0],
|
|
445
|
+
["ack_seq", "INTEGER", 1, 0],
|
|
446
|
+
["ack_digest", "TEXT", 1, 0],
|
|
447
|
+
["pending_bytes", "INTEGER", 1, 0]
|
|
448
|
+
],
|
|
449
|
+
e7_replication_outbox: [
|
|
450
|
+
["sequence", "INTEGER", 0, 1],
|
|
451
|
+
["parent_digest", "TEXT", 1, 0],
|
|
452
|
+
["changeset", "BLOB", 1, 0],
|
|
453
|
+
["sequences", "TEXT", 1, 0],
|
|
454
|
+
["digest", "TEXT", 1, 0]
|
|
455
|
+
],
|
|
456
|
+
e7_replication_inbox: [
|
|
457
|
+
["sequence", "INTEGER", 0, 1],
|
|
458
|
+
["parent_digest", "TEXT", 1, 0],
|
|
459
|
+
["changeset", "BLOB", 0, 0],
|
|
460
|
+
["sequences", "TEXT", 1, 0],
|
|
461
|
+
["digest", "TEXT", 1, 0],
|
|
462
|
+
["state", "TEXT", 1, 0]
|
|
463
|
+
]
|
|
464
|
+
};
|
|
465
|
+
var guardPrefix = "writer_guard_replication_";
|
|
466
|
+
var identifier = (s) => '"' + s.replaceAll('"', '""') + '"';
|
|
467
|
+
var hash = (s) => createHash("sha256").update(s).digest("hex");
|
|
468
|
+
var digestPattern = /^[a-f0-9]{64}$/;
|
|
469
|
+
function bindingText(binding) {
|
|
470
|
+
if (!binding || ["tenantId", "companionId", "seatId", "databaseId", "baselineId"].some((k) => typeof binding[k] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(String(binding[k]))) || !Number.isSafeInteger(binding.epoch) || binding.epoch < 1) throw new Error("REPLICATION_INVALID_BINDING");
|
|
471
|
+
return JSON.stringify([binding.tenantId, binding.companionId, binding.seatId, binding.databaseId, binding.baselineId, binding.epoch]);
|
|
472
|
+
}
|
|
473
|
+
function normalizeBinding(binding) {
|
|
474
|
+
const [tenantId, companionId, seatId, databaseId, baselineId, epoch] = JSON.parse(bindingText(binding));
|
|
475
|
+
return Object.freeze({ tenantId, companionId, seatId, databaseId, baselineId, epoch });
|
|
476
|
+
}
|
|
477
|
+
function readSQLiteReplicationSource(db) {
|
|
478
|
+
if (!validateMetadata(db)) return null;
|
|
479
|
+
const rows = db.prepare("SELECT role,binding,schema_hash FROM e7_replication_control").all();
|
|
480
|
+
if (rows.length !== 1 || rows[0].role !== "source") throw new Error("REPLICATION_SOURCE_REQUIRED");
|
|
481
|
+
const row = rows[0];
|
|
482
|
+
try {
|
|
483
|
+
const fields = JSON.parse(String(row.binding));
|
|
484
|
+
if (!Array.isArray(fields) || fields.length !== 6 || !digestPattern.test(String(row.schema_hash))) throw new Error();
|
|
485
|
+
const [tenantId, companionId, seatId, databaseId, baselineId, epoch] = fields;
|
|
486
|
+
return { binding: normalizeBinding({ tenantId, companionId, seatId, databaseId, baselineId, epoch }), schemaHash: String(row.schema_hash) };
|
|
487
|
+
} catch {
|
|
488
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
function limits(options) {
|
|
492
|
+
const maximumPendingBytes = options.maximumPendingBytes ?? 64 * 1024 * 1024;
|
|
493
|
+
const maximumCommitBytes = options.maximumCommitBytes ?? 16 * 1024 * 1024;
|
|
494
|
+
if ([maximumPendingBytes, maximumCommitBytes].some((n) => !Number.isSafeInteger(n) || n < 1 || n > 256 * 1024 * 1024))
|
|
495
|
+
throw new Error("REPLICATION_INVALID_LIMIT");
|
|
496
|
+
return { maximumPendingBytes, maximumCommitBytes };
|
|
497
|
+
}
|
|
498
|
+
function schemaRows(db) {
|
|
499
|
+
return db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_master WHERE sql IS NOT NULL AND name NOT GLOB 'sqlite_*' ORDER BY type,name").all().filter((r) => !metadataTables.has(r.tbl_name) && !r.name.startsWith(guardPrefix));
|
|
500
|
+
}
|
|
501
|
+
function sqliteReplicationSchemaHash(db) {
|
|
502
|
+
return hash(JSON.stringify(schemaRows(db)));
|
|
503
|
+
}
|
|
504
|
+
function inspectTables(db, excluded = /* @__PURE__ */ new Set()) {
|
|
505
|
+
const tables = /* @__PURE__ */ new Map();
|
|
506
|
+
for (const row of schemaRows(db).filter((r) => r.type === "table")) {
|
|
507
|
+
if (excluded.has(row.name)) continue;
|
|
508
|
+
const columns2 = db.prepare(`PRAGMA table_info(${identifier(row.name)})`).all();
|
|
509
|
+
const keys = columns2.filter((c) => Number(c.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk)).map((c) => c.name);
|
|
510
|
+
if (!keys.length || /CREATE\s+VIRTUAL\s+TABLE/i.test(row.sql) || row.name.startsWith("e7_replication_"))
|
|
511
|
+
throw new Error("REPLICATION_UNSUPPORTED_SCHEMA: " + row.name);
|
|
512
|
+
if (db.prepare(`SELECT 1 FROM ${identifier(row.name)} WHERE ${keys.map((k) => `${identifier(k)} IS NULL`).join(" OR ")} LIMIT 1`).get())
|
|
513
|
+
throw new Error("REPLICATION_NULL_PRIMARY_KEY: " + row.name);
|
|
514
|
+
tables.set(row.name, keys);
|
|
515
|
+
}
|
|
516
|
+
if (!tables.size) throw new Error("REPLICATION_UNSUPPORTED_SCHEMA: no business tables");
|
|
517
|
+
return tables;
|
|
518
|
+
}
|
|
519
|
+
function validateMetadata(db) {
|
|
520
|
+
const rows = db.prepare("SELECT name,type FROM sqlite_master WHERE name IN (?,?,?)").all(...metadataTables);
|
|
521
|
+
if (!rows.length) return false;
|
|
522
|
+
if (rows.length !== metadataTables.size || rows.some((row) => row.type !== "table"))
|
|
523
|
+
throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: new Error("incomplete replication metadata") });
|
|
524
|
+
for (const [table, expected] of Object.entries(metadataColumns)) {
|
|
525
|
+
const columns2 = db.prepare(`PRAGMA table_xinfo(${identifier(table)})`).all();
|
|
526
|
+
if (columns2.length !== expected.length || columns2.some((column, index) => {
|
|
527
|
+
const [name, type, notnull, pk] = expected[index];
|
|
528
|
+
return column.name !== name || String(column.type).toUpperCase() !== type || Number(column.notnull) !== notnull || Number(column.pk) !== pk || Number(column.hidden) !== 0 || column.dflt_value !== null;
|
|
529
|
+
})) throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: new Error("invalid replication metadata " + table) });
|
|
530
|
+
}
|
|
531
|
+
return true;
|
|
532
|
+
}
|
|
533
|
+
function metadata(db) {
|
|
534
|
+
validateMetadata(db);
|
|
535
|
+
db.exec(`CREATE TABLE IF NOT EXISTS e7_replication_control(
|
|
536
|
+
role TEXT PRIMARY KEY, binding TEXT NOT NULL, schema_hash TEXT NOT NULL,
|
|
537
|
+
head INTEGER NOT NULL, digest TEXT NOT NULL, ack_seq INTEGER NOT NULL, ack_digest TEXT NOT NULL,
|
|
538
|
+
pending_bytes INTEGER NOT NULL CHECK(pending_bytes>=0));
|
|
539
|
+
CREATE TABLE IF NOT EXISTS e7_replication_outbox(
|
|
540
|
+
sequence INTEGER PRIMARY KEY,parent_digest TEXT NOT NULL,changeset BLOB NOT NULL,sequences TEXT NOT NULL,digest TEXT NOT NULL);
|
|
541
|
+
CREATE TABLE IF NOT EXISTS e7_replication_inbox(
|
|
542
|
+
sequence INTEGER PRIMARY KEY,parent_digest TEXT NOT NULL,changeset BLOB,sequences TEXT NOT NULL,digest TEXT NOT NULL,
|
|
543
|
+
state TEXT NOT NULL CHECK(state IN ('RECEIVED','APPLIED')));`);
|
|
544
|
+
}
|
|
545
|
+
function captureGuardHash(db) {
|
|
546
|
+
const rows = db.prepare("SELECT name,sql FROM sqlite_master WHERE type='trigger' ORDER BY name").all().filter((r) => String(r.name).startsWith(guardPrefix));
|
|
547
|
+
return hash(JSON.stringify(rows));
|
|
548
|
+
}
|
|
549
|
+
function installCaptureGuards(db, tables) {
|
|
550
|
+
const enrolled = Boolean(db.prepare("SELECT 1 FROM e7_replication_control LIMIT 1").get());
|
|
551
|
+
for (const [table, keys] of tables) for (const operation of ["INSERT", "UPDATE", "DELETE"]) {
|
|
552
|
+
const name = guardPrefix + hash(table).slice(0, 20) + "_" + operation.toLowerCase();
|
|
553
|
+
const nullCheck = operation === "DELETE" ? "" : `SELECT CASE WHEN ${keys.map((k) => `NEW.${identifier(k)} IS NULL`).join(" OR ")}
|
|
554
|
+
THEN RAISE(ABORT,'REPLICATION_NULL_PRIMARY_KEY') END;`;
|
|
555
|
+
const sql = `CREATE TRIGGER ${identifier(name)} BEFORE ${operation} ON ${identifier(table)} BEGIN
|
|
556
|
+
SELECT CASE WHEN engine7_replication_capture_active()!=1 THEN RAISE(ABORT,'REPLICATION_CAPTURE_REQUIRED') END;
|
|
557
|
+
${nullCheck} END`;
|
|
558
|
+
const existing = db.prepare("SELECT sql FROM sqlite_master WHERE type='trigger' AND name=?").get(name);
|
|
559
|
+
if (!existing && enrolled || existing && existing.sql !== sql) throw new Error("REPLICATION_GUARD_MISMATCH");
|
|
560
|
+
if (!existing) db.exec(sql);
|
|
561
|
+
}
|
|
562
|
+
return captureGuardHash(db);
|
|
563
|
+
}
|
|
564
|
+
function configure(db) {
|
|
565
|
+
if (typeof db.createSession !== "function" || typeof db.applyChangeset !== "function" || typeof db.isTransaction !== "boolean" || typeof sqliteConstants()?.SQLITE_CHANGESET_ABORT !== "number") throw new Error("REPLICATION_UNSUPPORTED_SQLITE_RUNTIME");
|
|
566
|
+
if (db.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
|
|
567
|
+
if (db.prepare("PRAGMA database_list").all().some((r) => r.name !== "main" && r.name !== "temp"))
|
|
568
|
+
throw new Error("REPLICATION_UNSUPPORTED_ATTACHED_DATABASE");
|
|
569
|
+
db.exec("PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000");
|
|
570
|
+
}
|
|
571
|
+
function requireForeignKeys(db) {
|
|
572
|
+
if (Number(db.prepare("PRAGMA foreign_keys").get().foreign_keys) !== 1) throw new Error("REPLICATION_FOREIGN_KEYS_REQUIRED");
|
|
573
|
+
}
|
|
574
|
+
function rootDigest(binding, schemaHash) {
|
|
575
|
+
return hash(JSON.stringify(["engine7-sqlite-replication-baseline-v1", bindingText(binding), schemaHash]));
|
|
576
|
+
}
|
|
577
|
+
function initialize(db, role, binding, schemaHash, baseline) {
|
|
578
|
+
const existing = db.prepare("SELECT binding,schema_hash,ack_seq,ack_digest FROM e7_replication_control WHERE role=?").get(role);
|
|
579
|
+
if (existing) {
|
|
580
|
+
if (existing.binding !== bindingText(binding) || existing.schema_hash !== schemaHash) throw new Error("REPLICATION_BINDING_OR_SCHEMA_MISMATCH");
|
|
581
|
+
if (role === "replica" && (existing.ack_seq !== baseline.sequence || existing.ack_digest !== baseline.digest))
|
|
582
|
+
throw new Error("REPLICATION_BASELINE_MISMATCH");
|
|
583
|
+
} else db.prepare(`INSERT INTO e7_replication_control VALUES(?,?,?,?,?,?,?,0)`).run(role, bindingText(binding), schemaHash, baseline.sequence, baseline.digest, baseline.sequence, baseline.digest);
|
|
584
|
+
}
|
|
585
|
+
function control(db, role) {
|
|
586
|
+
const row = db.prepare("SELECT head,digest,ack_seq,ack_digest,pending_bytes FROM e7_replication_control WHERE role=?").get(role);
|
|
587
|
+
if (!row || [row.head, row.ack_seq, row.pending_bytes].some((n) => !Number.isSafeInteger(n) || n < 0) || row.ack_seq > row.head || !digestPattern.test(row.digest) || !digestPattern.test(row.ack_digest))
|
|
588
|
+
throw new Error("REPLICATION_CORRUPT_CONTROL");
|
|
589
|
+
return row;
|
|
590
|
+
}
|
|
591
|
+
function sequences(db, excluded = /* @__PURE__ */ new Set()) {
|
|
592
|
+
if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='sqlite_sequence'").get()) return /* @__PURE__ */ new Map();
|
|
593
|
+
const statement = db.prepare("SELECT name,seq FROM sqlite_sequence ORDER BY name");
|
|
594
|
+
statement.setReadBigInts(true);
|
|
595
|
+
const rows = statement.all();
|
|
596
|
+
if (rows.some((r) => typeof r.seq !== "bigint" || r.seq < 0n)) throw new Error("REPLICATION_CORRUPT_SEQUENCE");
|
|
597
|
+
return new Map(rows.filter((r) => !excluded.has(r.name)).map((r) => [r.name, String(r.seq)]));
|
|
598
|
+
}
|
|
599
|
+
function commitDigest(commit) {
|
|
600
|
+
const header = JSON.stringify([
|
|
601
|
+
"engine7-sqlite-replication-commit-v1",
|
|
602
|
+
bindingText(commit.binding),
|
|
603
|
+
commit.sequence,
|
|
604
|
+
commit.parentDigest,
|
|
605
|
+
commit.schemaHash,
|
|
606
|
+
commit.sequences
|
|
607
|
+
]);
|
|
608
|
+
return createHash("sha256").update(header).update(commit.changeset).digest("hex");
|
|
609
|
+
}
|
|
610
|
+
function logCommit(row, binding, schemaHash) {
|
|
611
|
+
return {
|
|
612
|
+
version: 1,
|
|
613
|
+
binding,
|
|
614
|
+
schemaHash,
|
|
615
|
+
sequence: row.sequence,
|
|
616
|
+
parentDigest: row.parent_digest,
|
|
617
|
+
changeset: Buffer.from(row.changeset),
|
|
618
|
+
sequences: JSON.parse(row.sequences),
|
|
619
|
+
digest: row.digest
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
function sourceHeadEvidence(db, sequence) {
|
|
623
|
+
const c = control(db, "source");
|
|
624
|
+
if (!Number.isSafeInteger(sequence) || sequence < 0 || sequence > c.head) throw new Error("REPLICATION_INVALID_SEQUENCE");
|
|
625
|
+
if (sequence === c.head) return { sequence, digest: c.digest };
|
|
626
|
+
if (sequence === c.ack_seq) return { sequence, digest: c.ack_digest };
|
|
627
|
+
if (sequence < c.ack_seq) throw new Error("REPLICATION_LOG_GAP");
|
|
628
|
+
const row = db.prepare("SELECT digest FROM e7_replication_outbox WHERE sequence=?").get(sequence);
|
|
629
|
+
if (!row || !digestPattern.test(String(row.digest))) throw new Error("REPLICATION_LOG_GAP");
|
|
630
|
+
return { sequence, digest: String(row.digest) };
|
|
631
|
+
}
|
|
632
|
+
function sourcePendingBytes(db, after, through) {
|
|
633
|
+
if (!Number.isSafeInteger(after) || after < 0 || after > through) throw new Error("REPLICATION_INVALID_SEQUENCE");
|
|
634
|
+
sourceHeadEvidence(db, through);
|
|
635
|
+
const bytes = Number(db.prepare("SELECT COALESCE(SUM(length(changeset)+length(CAST(sequences AS BLOB))),0) bytes FROM e7_replication_outbox WHERE sequence>? AND sequence<=?").get(after, through).bytes);
|
|
636
|
+
if (!Number.isSafeInteger(bytes) || bytes < 0) throw new Error("REPLICATION_CORRUPT_CONTROL");
|
|
637
|
+
return bytes;
|
|
638
|
+
}
|
|
639
|
+
var SQLiteReplicationSource = class {
|
|
640
|
+
constructor(db, binding, options = {}) {
|
|
641
|
+
this.db = db;
|
|
642
|
+
this.execute = db.exec.bind(db);
|
|
643
|
+
this.binding = normalizeBinding(binding);
|
|
644
|
+
this.budget = limits(options);
|
|
645
|
+
configure(db);
|
|
646
|
+
const derived = inspectLegacySQLiteIndexes(db);
|
|
647
|
+
this.excludedTables = derived?.excludedTables ?? /* @__PURE__ */ new Set();
|
|
648
|
+
const tables = inspectTables(db, this.excludedTables);
|
|
649
|
+
if (this.excludedTables.size) this.sessionTables = [...tables.keys()];
|
|
650
|
+
this.schemaHash = sqliteReplicationSchemaHash(db);
|
|
651
|
+
db.function("engine7_replication_capture_active", () => {
|
|
652
|
+
if (this.active) this.runtimeAuthority?.assertFast("WRITE", this.binding);
|
|
653
|
+
return this.active ? 1 : 0;
|
|
654
|
+
});
|
|
655
|
+
db.exec("BEGIN IMMEDIATE");
|
|
656
|
+
try {
|
|
657
|
+
metadata(db);
|
|
658
|
+
this.guardHash = installCaptureGuards(db, tables);
|
|
659
|
+
initialize(db, "source", this.binding, this.schemaHash, { sequence: 0, digest: rootDigest(this.binding, this.schemaHash) });
|
|
660
|
+
control(db, "source");
|
|
661
|
+
db.exec("COMMIT");
|
|
662
|
+
} catch (error) {
|
|
663
|
+
db.exec("ROLLBACK");
|
|
664
|
+
throw error;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
binding;
|
|
668
|
+
excludedTables;
|
|
669
|
+
sessionTables;
|
|
670
|
+
schemaHash;
|
|
671
|
+
active = null;
|
|
672
|
+
runtimeAuthority = null;
|
|
673
|
+
budget;
|
|
674
|
+
guardHash;
|
|
675
|
+
execute;
|
|
676
|
+
head() {
|
|
677
|
+
const c = control(this.db, "source");
|
|
678
|
+
return { sequence: c.head, digest: c.digest };
|
|
679
|
+
}
|
|
680
|
+
/** Proof for a saved target. An older, already pruned head cannot be guessed. */
|
|
681
|
+
headEvidence(sequence) {
|
|
682
|
+
return sourceHeadEvidence(this.db, sequence);
|
|
683
|
+
}
|
|
684
|
+
/** Durable outbox payload still required for this new cut. Already APPLIED
|
|
685
|
+
* transactions have separate receiver evidence and are not queued again. */
|
|
686
|
+
pendingStoredBytesAfter(after, through) {
|
|
687
|
+
return sourcePendingBytes(this.db, after, through);
|
|
688
|
+
}
|
|
689
|
+
beginCapture() {
|
|
690
|
+
this.runtimeAuthority = databaseRuntimeAuthorityFor(this.db);
|
|
691
|
+
this.runtimeAuthority?.assert("WRITE", this.binding);
|
|
692
|
+
if (!this.db.isTransaction || this.active) throw new Error("REPLICATION_CAPTURE_BOUNDARY");
|
|
693
|
+
requireForeignKeys(this.db);
|
|
694
|
+
if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
|
|
695
|
+
if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
|
|
696
|
+
const before = sequences(this.db, this.excludedTables), sessions = [];
|
|
697
|
+
try {
|
|
698
|
+
if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
|
|
699
|
+
else sessions.push(this.db.createSession());
|
|
700
|
+
} catch (error) {
|
|
701
|
+
for (const session of sessions) session.close();
|
|
702
|
+
throw error;
|
|
703
|
+
}
|
|
704
|
+
this.active = { sessions, sequences: before, closed: false };
|
|
705
|
+
return this.active;
|
|
706
|
+
}
|
|
707
|
+
appendCapture(capture) {
|
|
708
|
+
assertDatabaseRuntimeAuthority(this.db, this.binding);
|
|
709
|
+
if (capture !== this.active || capture.closed || !this.db.isTransaction) throw new Error("REPLICATION_CAPTURE_BOUNDARY");
|
|
710
|
+
if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
|
|
711
|
+
if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
|
|
712
|
+
const changeset = Buffer.concat(capture.sessions.map((session) => Buffer.from(session.changeset())));
|
|
713
|
+
for (const session of capture.sessions) session.close();
|
|
714
|
+
capture.closed = true;
|
|
715
|
+
const afterSequences = sequences(this.db, this.excludedTables);
|
|
716
|
+
for (const [table, before] of capture.sequences) {
|
|
717
|
+
const after = afterSequences.get(table);
|
|
718
|
+
if (after === void 0 || BigInt(after) < BigInt(before)) throw new Error("REPLICATION_SEQUENCE_REGRESSION");
|
|
719
|
+
}
|
|
720
|
+
const sequenceChanges = [...afterSequences].filter(([table, value]) => capture.sequences.get(table) !== value).map(([table, value]) => ({ table, value }));
|
|
721
|
+
if (!changeset.length && !sequenceChanges.length) return;
|
|
722
|
+
const bytes = changeset.length + Buffer.byteLength(JSON.stringify(sequenceChanges));
|
|
723
|
+
const state = control(this.db, "source");
|
|
724
|
+
if (bytes > this.budget.maximumCommitBytes) throw new Error("REPLICATION_COMMIT_TOO_LARGE");
|
|
725
|
+
if (state.pending_bytes + bytes > this.budget.maximumPendingBytes) throw new Error("REPLICATION_QUEUE_FULL");
|
|
726
|
+
if (state.head >= Number.MAX_SAFE_INTEGER) throw new Error("REPLICATION_SEQUENCE_EXHAUSTED");
|
|
727
|
+
const commit = {
|
|
728
|
+
version: 1,
|
|
729
|
+
binding: this.binding,
|
|
730
|
+
schemaHash: this.schemaHash,
|
|
731
|
+
sequence: state.head + 1,
|
|
732
|
+
parentDigest: state.digest,
|
|
733
|
+
changeset,
|
|
734
|
+
sequences: sequenceChanges
|
|
735
|
+
};
|
|
736
|
+
const digest = commitDigest(commit);
|
|
737
|
+
this.db.prepare("INSERT INTO e7_replication_outbox VALUES(?,?,?,?,?)").run(commit.sequence, commit.parentDigest, changeset, JSON.stringify(sequenceChanges), digest);
|
|
738
|
+
this.db.prepare("UPDATE e7_replication_control SET head=?,digest=?,pending_bytes=pending_bytes+? WHERE role='source'").run(commit.sequence, digest, bytes);
|
|
739
|
+
assertDatabaseRuntimeAuthority(this.db, this.binding);
|
|
740
|
+
}
|
|
741
|
+
endCapture(capture) {
|
|
742
|
+
if (capture !== this.active) throw new Error("REPLICATION_CAPTURE_BOUNDARY");
|
|
743
|
+
if (!capture.closed) for (const session of capture.sessions) session.close();
|
|
744
|
+
this.active = null;
|
|
745
|
+
}
|
|
746
|
+
transaction(operation) {
|
|
747
|
+
assertDatabaseRuntimeAuthority(this.db, this.binding);
|
|
748
|
+
if (this.db.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
|
|
749
|
+
this.execute("BEGIN IMMEDIATE");
|
|
750
|
+
let capture;
|
|
751
|
+
try {
|
|
752
|
+
capture = this.beginCapture();
|
|
753
|
+
const result = operation();
|
|
754
|
+
if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
|
|
755
|
+
assertDatabaseRuntimeAuthority(this.db, this.binding);
|
|
756
|
+
this.appendCapture(capture);
|
|
757
|
+
assertDatabaseRuntimeAuthority(this.db, this.binding);
|
|
758
|
+
this.execute("COMMIT");
|
|
759
|
+
return result;
|
|
760
|
+
} catch (error) {
|
|
761
|
+
this.execute("ROLLBACK");
|
|
762
|
+
throw error;
|
|
763
|
+
} finally {
|
|
764
|
+
if (capture) this.endCapture(capture);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
readAfter(sequence, limit = 64) {
|
|
768
|
+
const c = control(this.db, "source");
|
|
769
|
+
if (!Number.isSafeInteger(sequence) || sequence < 0 || sequence > c.head || !Number.isSafeInteger(limit) || limit < 1 || limit > 1024)
|
|
770
|
+
throw new Error("REPLICATION_INVALID_SEQUENCE");
|
|
771
|
+
if (sequence < c.ack_seq) throw new Error("REPLICATION_LOG_GAP");
|
|
772
|
+
return this.db.prepare("SELECT * FROM e7_replication_outbox WHERE sequence>? ORDER BY sequence LIMIT ?").all(sequence, limit).map((row) => logCommit(row, this.binding, this.schemaHash));
|
|
773
|
+
}
|
|
774
|
+
acknowledgeApplied(receipt) {
|
|
775
|
+
if (receipt?.state !== "APPLIED") throw new Error("REPLICATION_APPLIED_RECEIPT_REQUIRED");
|
|
776
|
+
if (bindingText(receipt.binding) !== bindingText(this.binding)) throw new Error("REPLICATION_BINDING_MISMATCH");
|
|
777
|
+
if (!Number.isSafeInteger(receipt.sequence) || receipt.sequence < 0 || !digestPattern.test(receipt.digest))
|
|
778
|
+
throw new Error("REPLICATION_INVALID_RECEIPT");
|
|
779
|
+
if (this.db.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
|
|
780
|
+
this.execute("BEGIN IMMEDIATE");
|
|
781
|
+
try {
|
|
782
|
+
const c = control(this.db, "source");
|
|
783
|
+
if (receipt.sequence < c.ack_seq) {
|
|
784
|
+
this.execute("COMMIT");
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
if (receipt.sequence === c.ack_seq) {
|
|
788
|
+
if (receipt.digest !== c.ack_digest) throw new Error("REPLICATION_RECEIPT_MISMATCH");
|
|
789
|
+
} else {
|
|
790
|
+
const row = this.db.prepare("SELECT digest FROM e7_replication_outbox WHERE sequence=?").get(receipt.sequence);
|
|
791
|
+
if (!row || row.digest !== receipt.digest) throw new Error("REPLICATION_RECEIPT_MISMATCH");
|
|
792
|
+
const bytes = Number(this.db.prepare("SELECT COALESCE(SUM(length(changeset)+length(CAST(sequences AS BLOB))),0) bytes FROM e7_replication_outbox WHERE sequence<=?").get(receipt.sequence).bytes);
|
|
793
|
+
this.db.prepare("DELETE FROM e7_replication_outbox WHERE sequence<=?").run(receipt.sequence);
|
|
794
|
+
this.db.prepare("UPDATE e7_replication_control SET ack_seq=?,ack_digest=?,pending_bytes=pending_bytes-? WHERE role='source'").run(receipt.sequence, receipt.digest, bytes);
|
|
795
|
+
}
|
|
796
|
+
this.execute("COMMIT");
|
|
797
|
+
} catch (error) {
|
|
798
|
+
this.execute("ROLLBACK");
|
|
799
|
+
throw error;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
|
|
804
|
+
// src/continuity/mem7-replication.ts
|
|
805
|
+
var location = (stateDir) => join4(stateDir, ".continuity", "mem7-replication.json");
|
|
806
|
+
function normalize(value) {
|
|
807
|
+
if (!value || !/^[a-f0-9]{64}$/.test(value.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
808
|
+
return Object.freeze({ binding: normalizeBinding(value.binding), schemaHash: value.schemaHash });
|
|
809
|
+
}
|
|
810
|
+
function hasMem7ReplicationRegistration(stateDir) {
|
|
811
|
+
try {
|
|
812
|
+
lstatSync4(location(stateDir));
|
|
813
|
+
return true;
|
|
814
|
+
} catch (error) {
|
|
815
|
+
if (error.code === "ENOENT") return false;
|
|
816
|
+
throw error;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
function readMem7ReplicationRegistration(stateDir) {
|
|
820
|
+
if (!hasMem7ReplicationRegistration(stateDir)) return null;
|
|
821
|
+
try {
|
|
822
|
+
assertPrivateDirectory(dirname3(location(stateDir)));
|
|
823
|
+
return normalize(JSON.parse(readPrivateFile(location(stateDir), 4096).toString()));
|
|
824
|
+
} catch {
|
|
825
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
function ensureMem7ReplicationRegistration(stateDir, input) {
|
|
829
|
+
const registration = normalize(input), existing = readMem7ReplicationRegistration(stateDir);
|
|
830
|
+
if (existing) {
|
|
831
|
+
if (JSON.stringify(existing) !== JSON.stringify(registration)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
const file = location(stateDir);
|
|
835
|
+
preparePrivateDirectory(dirname3(file));
|
|
836
|
+
try {
|
|
837
|
+
writeFileSync2(file, JSON.stringify(registration), { mode: 384, flag: "wx", flush: true });
|
|
838
|
+
} catch (error) {
|
|
839
|
+
if (error.code !== "EEXIST") throw error;
|
|
840
|
+
if (JSON.stringify(readMem7ReplicationRegistration(stateDir)) !== JSON.stringify(registration)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
|
|
841
|
+
}
|
|
842
|
+
if (process.platform !== "win32") {
|
|
843
|
+
const fd = openSync4(dirname3(file), "r");
|
|
844
|
+
try {
|
|
845
|
+
fsyncSync4(fd);
|
|
846
|
+
} finally {
|
|
847
|
+
closeSync4(fd);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// src/continuity/runtime-replication.ts
|
|
853
|
+
import { constants as constants5, lstatSync as lstatSync5, realpathSync as realpathSync2, mkdirSync as mkdirSync4, openSync as openSync5, closeSync as closeSync5, fstatSync as fstatSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync3, fsyncSync as fsyncSync5 } from "node:fs";
|
|
854
|
+
import { basename as basename2, dirname as dirname4, join as join5, resolve as resolve4 } from "node:path";
|
|
855
|
+
function checkKey(component, key) {
|
|
856
|
+
if (component === "topics-vectors" && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) return;
|
|
857
|
+
if (component === "legacy-memory" && typeof key === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key) && !/[. ]$/.test(key) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key)) return;
|
|
858
|
+
if (["calendar", "proactive", "session-events"].includes(component) && key === void 0) return;
|
|
859
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
860
|
+
}
|
|
861
|
+
function location2(stateDir, component, key) {
|
|
862
|
+
checkKey(component, key);
|
|
863
|
+
return join5(stateDir, ".continuity", component + (key === void 0 ? "" : "-" + key) + "-replication.json");
|
|
864
|
+
}
|
|
865
|
+
function runtimeReplicationFile(stateDir, component, key) {
|
|
866
|
+
checkKey(component, key);
|
|
867
|
+
if (component === "legacy-memory") return join5(stateDir, "agents", key, "memory", "memory.db");
|
|
868
|
+
if (component === "topics-vectors") return join5(stateDir, "topics-history", key, "vectors.db");
|
|
869
|
+
if (component === "session-events") return join5(stateDir, ".continuity", "session-events.db");
|
|
870
|
+
return join5(stateDir, "." + component, component + ".db");
|
|
871
|
+
}
|
|
872
|
+
function runtimeReplicationLocation(stateDir, component, file) {
|
|
873
|
+
const key = component === "legacy-memory" ? basename2(dirname4(dirname4(file))) : component === "topics-vectors" ? basename2(dirname4(file)) : void 0;
|
|
874
|
+
try {
|
|
875
|
+
if (resolve4(file) !== resolve4(runtimeReplicationFile(stateDir, component, key))) throw new Error();
|
|
876
|
+
} catch (error) {
|
|
877
|
+
throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED", { cause: error });
|
|
878
|
+
}
|
|
879
|
+
return { component, ...key === void 0 ? {} : { key } };
|
|
880
|
+
}
|
|
881
|
+
function normalize2(input) {
|
|
882
|
+
if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
883
|
+
return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
|
|
884
|
+
}
|
|
885
|
+
function directory(path) {
|
|
886
|
+
const info = lstatSync5(path);
|
|
887
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path) !== resolve4(path) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
888
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
889
|
+
}
|
|
890
|
+
function readRuntimeReplicationRegistration(stateDir, component, key) {
|
|
891
|
+
const file = location2(stateDir, component, key);
|
|
892
|
+
try {
|
|
893
|
+
lstatSync5(dirname4(file));
|
|
894
|
+
} catch (error) {
|
|
895
|
+
if (error.code === "ENOENT") return null;
|
|
896
|
+
throw error;
|
|
897
|
+
}
|
|
898
|
+
directory(dirname4(file));
|
|
899
|
+
let fd;
|
|
900
|
+
try {
|
|
901
|
+
fd = openSync5(file, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0));
|
|
902
|
+
} catch (error) {
|
|
903
|
+
if (error.code === "ENOENT") return null;
|
|
904
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
|
|
905
|
+
}
|
|
906
|
+
try {
|
|
907
|
+
const info = fstatSync4(fd);
|
|
908
|
+
if (!info.isFile() || info.size > 4096 || realpathSync2(file) !== resolve4(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
|
|
909
|
+
return normalize2(JSON.parse(readFileSync3(fd, "utf8")));
|
|
910
|
+
} catch (error) {
|
|
911
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
|
|
912
|
+
} finally {
|
|
913
|
+
closeSync5(fd);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
function checkRuntimeReplicationDatabase(db, registration, component, version, requested) {
|
|
917
|
+
const enrolled = readSQLiteReplicationSource(db);
|
|
918
|
+
if (enrolled && !registration && !requested) throw new Error("REPLICATION_REGISTRATION_REQUIRED");
|
|
919
|
+
const expected = registration ?? enrolled;
|
|
920
|
+
if (expected) {
|
|
921
|
+
if (!enrolled || JSON.stringify(enrolled) !== JSON.stringify(expected)) throw new Error("REPLICATION_RECOVERY_REQUIRED");
|
|
922
|
+
const actual = readSchemaVersion(db);
|
|
923
|
+
if (actual?.component !== component || actual.version !== version || sqliteReplicationSchemaHash(db) !== expected.schemaHash)
|
|
924
|
+
throw new Error("REPLICATION_SCHEMA_MISMATCH");
|
|
925
|
+
if (requested && JSON.stringify(normalizeBinding(requested)) !== JSON.stringify(expected.binding)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
|
|
926
|
+
}
|
|
927
|
+
return requested ?? registration?.binding;
|
|
928
|
+
}
|
|
929
|
+
function enrollRuntimeReplication(db, stateDir, component, binding, key) {
|
|
930
|
+
const file = location2(stateDir, component, key), old = readRuntimeReplicationRegistration(stateDir, component, key);
|
|
931
|
+
const version = readSchemaVersion(db);
|
|
932
|
+
if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
|
|
933
|
+
checkRuntimeReplicationDatabase(db, old, component, version.version, binding);
|
|
934
|
+
const input = normalize2({ binding, schemaHash: sqliteReplicationSchemaHash(db) });
|
|
935
|
+
if (old && JSON.stringify(old) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
|
|
936
|
+
if (!old) {
|
|
937
|
+
mkdirSync4(dirname4(file), { mode: 448, recursive: true });
|
|
938
|
+
directory(dirname4(file));
|
|
939
|
+
try {
|
|
940
|
+
writeFileSync3(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
|
|
941
|
+
} catch (error) {
|
|
942
|
+
if (error.code !== "EEXIST") throw error;
|
|
943
|
+
if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
|
|
944
|
+
}
|
|
945
|
+
if (process.platform !== "win32") {
|
|
946
|
+
const fd = openSync5(dirname4(file), "r");
|
|
947
|
+
try {
|
|
948
|
+
fsyncSync5(fd);
|
|
949
|
+
} finally {
|
|
950
|
+
closeSync5(fd);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
return new SQLiteReplicationSource(db, binding);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// src/continuity/sqlite-store-location.ts
|
|
958
|
+
function sqliteStoreLocation(file) {
|
|
959
|
+
const absolute = resolve5(file), parent = dirname5(absolute), name = basename3(absolute);
|
|
960
|
+
if (name === "mem7.db" && basename3(parent) === "index" && basename3(dirname5(parent)) === "mem7")
|
|
961
|
+
return { stateDir: dirname5(dirname5(parent)), component: "mem7" };
|
|
962
|
+
let stateDir, component;
|
|
963
|
+
if (name === "calendar.db" && basename3(parent) === ".calendar") {
|
|
964
|
+
stateDir = dirname5(parent);
|
|
965
|
+
component = "calendar";
|
|
966
|
+
} else if (name === "proactive.db" && basename3(parent) === ".proactive") {
|
|
967
|
+
stateDir = dirname5(parent);
|
|
968
|
+
component = "proactive";
|
|
969
|
+
} else if (name === "session-events.db" && basename3(parent) === ".continuity") {
|
|
970
|
+
stateDir = dirname5(parent);
|
|
971
|
+
component = "session-events";
|
|
972
|
+
} else if (name === "memory.db" && basename3(parent) === "memory" && basename3(dirname5(dirname5(parent))) === "agents") {
|
|
973
|
+
stateDir = dirname5(dirname5(dirname5(parent)));
|
|
974
|
+
component = "legacy-memory";
|
|
975
|
+
} else if (name === "vectors.db" && basename3(dirname5(parent)) === "topics-history") {
|
|
976
|
+
stateDir = dirname5(dirname5(parent));
|
|
977
|
+
component = "topics-vectors";
|
|
978
|
+
} else return null;
|
|
979
|
+
return { stateDir, ...runtimeReplicationLocation(stateDir, component, absolute) };
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// src/continuity/legacy-memory-replication.ts
|
|
983
|
+
import { createRequire as createRequire3 } from "node:module";
|
|
984
|
+
|
|
985
|
+
// src/memory/host/sqlite-vec-platform-variant.ts
|
|
986
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
987
|
+
var PLATFORM_VARIANTS = {
|
|
988
|
+
"linux-x64": { pkg: "sqlite-vec-linux-x64", file: "vec0.so" },
|
|
989
|
+
"linux-arm64": { pkg: "sqlite-vec-linux-arm64", file: "vec0.so" },
|
|
990
|
+
"darwin-x64": { pkg: "sqlite-vec-darwin-x64", file: "vec0.dylib" },
|
|
991
|
+
"darwin-arm64": { pkg: "sqlite-vec-darwin-arm64", file: "vec0.dylib" },
|
|
992
|
+
"win32-x64": { pkg: "sqlite-vec-windows-x64", file: "vec0.dll" }
|
|
993
|
+
};
|
|
994
|
+
function resolveSqliteVecPlatformVariant() {
|
|
995
|
+
const entry = PLATFORM_VARIANTS[`${process.platform}-${process.arch}`];
|
|
996
|
+
if (!entry) {
|
|
997
|
+
return void 0;
|
|
998
|
+
}
|
|
999
|
+
try {
|
|
1000
|
+
const require_ = createRequire2(import.meta.url);
|
|
1001
|
+
const extensionPath = require_.resolve(`${entry.pkg}/${entry.file}`);
|
|
1002
|
+
return { pkg: entry.pkg, extensionPath };
|
|
1003
|
+
} catch {
|
|
1004
|
+
return void 0;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// src/continuity/legacy-memory-replication.ts
|
|
1009
|
+
var require2 = createRequire3(import.meta.url);
|
|
1010
|
+
function loadLegacySQLiteVectorExtension(db, extensionPath) {
|
|
1011
|
+
db.enableLoadExtension(true);
|
|
1012
|
+
if (extensionPath) {
|
|
1013
|
+
db.loadExtension(extensionPath);
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
let module;
|
|
1017
|
+
try {
|
|
1018
|
+
module = require2("sqlite-vec");
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
if (error.code !== "MODULE_NOT_FOUND") throw error;
|
|
1021
|
+
const variant = resolveSqliteVecPlatformVariant();
|
|
1022
|
+
if (!variant) throw new Error("REPLICATION_LEGACY_VECTOR_MODULE_REQUIRED", { cause: error });
|
|
1023
|
+
db.loadExtension(variant.extensionPath);
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
module.load(db);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// src/continuity/recovery-admission-schema.ts
|
|
1030
|
+
var RECOVERY_ADMISSION_SCHEMA = `CREATE TABLE IF NOT EXISTS e7_recovery_batches(
|
|
1031
|
+
batch_id TEXT PRIMARY KEY,digest TEXT NOT NULL);
|
|
1032
|
+
CREATE TABLE IF NOT EXISTS e7_recovery_items(
|
|
1033
|
+
item_id TEXT PRIMARY KEY,original_hash TEXT NOT NULL,batch_id TEXT NOT NULL,result TEXT NOT NULL);
|
|
1034
|
+
CREATE TABLE IF NOT EXISTS e7_recovery_objects(
|
|
1035
|
+
sha256 TEXT PRIMARY KEY,body BLOB NOT NULL);
|
|
1036
|
+
CREATE TABLE IF NOT EXISTS e7_recovery_sources(
|
|
1037
|
+
scope_id TEXT NOT NULL,source_id TEXT NOT NULL,PRIMARY KEY(scope_id,source_id));
|
|
1038
|
+
CREATE TABLE IF NOT EXISTS e7_recovery_mappings(
|
|
1039
|
+
branch_digest TEXT NOT NULL,scope_id TEXT NOT NULL,kind TEXT NOT NULL,original_id TEXT NOT NULL,
|
|
1040
|
+
original_value TEXT NOT NULL,current_value TEXT NOT NULL,
|
|
1041
|
+
PRIMARY KEY(branch_digest,scope_id,kind,original_id));
|
|
1042
|
+
CREATE TABLE IF NOT EXISTS e7_recovery_resolutions(
|
|
1043
|
+
resolution_id TEXT PRIMARY KEY,digest TEXT NOT NULL);`;
|
|
1044
|
+
function initializeRecoveryAdmission(db) {
|
|
1045
|
+
if (db.isTransaction || db.prepare("SELECT 1 FROM sqlite_master WHERE name='e7_replication_control'").get() && db.prepare("SELECT 1 FROM e7_replication_control LIMIT 1").get()) throw new Error("RECOVERY_NEW_BASELINE_REQUIRED");
|
|
1046
|
+
db.exec(RECOVERY_ADMISSION_SCHEMA);
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// src/continuity/activation-database.ts
|
|
1050
|
+
function initializeActivationDatabase(file, raw) {
|
|
1051
|
+
const binding = normalizeBinding(raw), place = sqliteStoreLocation(file);
|
|
1052
|
+
if (!place) throw Error("TRAVEL_ACTIVATION_SCHEMA");
|
|
1053
|
+
const db = new DatabaseSync3(file, { allowExtension: place.component === "legacy-memory" });
|
|
1054
|
+
try {
|
|
1055
|
+
if (place.component === "legacy-memory") loadLegacySQLiteVectorExtension(db);
|
|
1056
|
+
const version = readSchemaVersion(db);
|
|
1057
|
+
if (!version || version.component !== place.component) throw Error("TRAVEL_ACTIVATION_SCHEMA");
|
|
1058
|
+
authorizeMemoryWriter(db, version.version);
|
|
1059
|
+
db.exec("BEGIN IMMEDIATE; DELETE FROM e7_replication_control; DELETE FROM e7_replication_outbox; DELETE FROM e7_replication_inbox; COMMIT");
|
|
1060
|
+
initializeRecoveryAdmission(db);
|
|
1061
|
+
if (place.component === "calendar" || place.component === "proactive") installWriterGuards(db);
|
|
1062
|
+
const source = new SQLiteReplicationSource(db, binding);
|
|
1063
|
+
if (place.component === "mem7") ensureMem7ReplicationRegistration(place.stateDir, { binding, schemaHash: source.schemaHash });
|
|
1064
|
+
else enrollRuntimeReplication(db, place.stateDir, place.component, binding, place.key);
|
|
1065
|
+
if (sqliteReplicationSchemaHash(db) !== db.prepare("SELECT schema_hash FROM e7_replication_control WHERE role='source'").get().schema_hash) throw Error("TRAVEL_ACTIVATION_SCHEMA");
|
|
1066
|
+
} finally {
|
|
1067
|
+
db.close();
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// src/continuity/activation-database-main.ts
|
|
1072
|
+
var args = process.argv.slice(2);
|
|
1073
|
+
if (args.length !== 2 || args[0] !== "--config") throw Error("TRAVEL_ACTIVATION_DATABASE_CONFIG");
|
|
1074
|
+
var config = JSON.parse(readPrivateFile(resolve6(args[1]), 65536).toString());
|
|
1075
|
+
if (realpathSync3(config.root) !== config.root || realpathSync3(config.file) !== config.file || !isWithin(config.root, config.file) || JSON.parse(readPrivateFile(join6(config.root, ".travel-restored.json"), 65536).toString()).activationAllowed !== false) throw Error("TRAVEL_ACTIVATION_DATABASE_CONFIG");
|
|
1076
|
+
initializeActivationDatabase(config.file, config.binding);
|
|
1077
|
+
process.stdout.write('{"ready":true}\n');
|