engine7 7.1.133 → 7.1.137
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 +1 -0
- package/dist/auth-server.mjs +632 -0
- package/dist/bg-worker.mjs +31663 -28486
- package/dist/cc-desktop.mjs +951 -0
- package/dist/cli.mjs +41495 -30171
- package/dist/engine-startup.mjs +54213 -40973
- package/dist/main.mjs +50129 -36887
- package/dist/recall-worker.mjs +20446 -0
- package/dist/sqlite-maintenance-worker.mjs +1166 -124
- package/dist/stop-history-worker.mjs +180 -0
- package/dist/topics-worker.mjs +3353 -1078
- package/dist/travel-authority.mjs +1068 -0
- package/dist/travel-console.mjs +2206 -0
- package/dist/travel-controller.mjs +1883 -0
- package/dist/travel-data.mjs +7253 -0
- package/dist/travel-gateway.mjs +3259 -0
- package/dist/travel-key-service.mjs +483 -0
- package/dist/travel-node-data.mjs +4936 -0
- package/dist/travel-node.mjs +21258 -0
- package/dist/travel-retire.mjs +1095 -0
- package/dist/web-console.mjs +3355 -0
- package/package.json +32 -17
- package/templates/config.template.json +45 -0
- package/templates/skills/auth-connect/SKILL.md +22 -0
- package/templates/skills/email/SKILL.md +119 -115
- package/templates/skills/email/scripts/email-config-path.test.js +52 -0
- package/templates/skills/email/scripts/email-config.d.ts +4 -0
- package/templates/skills/email/scripts/email-config.js +6 -3
- package/templates/skills/pptx/SKILL.md +5 -0
- package/templates/skills/pptx/assets/engine7-aurora/field.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/hero.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/wordmark.png +0 -0
- package/templates/skills/pptx/examples/engine7-aurora.cjs +190 -0
- package/templates/skills/pptx/package-lock.json +171 -0
- package/templates/skills/pptx/package.json +12 -0
- package/templates/skills/pptx/scripts/engine7-aurora.cjs +132 -0
- package/templates/skills/pptx/styles/engine7-aurora.md +136 -0
- package/templates/skills/pptx/tests/engine7-aurora.test.cjs +116 -0
- package/templates/workspace/AGENTS.md +2 -9
- package/templates/workspace/RULES.md +22 -0
- package/templates/workspace/hooks/loop-detector.mjs +37 -0
- package/templates/workspace/souls/unnamed.md +10 -0
|
@@ -9,6 +9,384 @@ var __export = (target, all) => {
|
|
|
9
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
10
|
};
|
|
11
11
|
|
|
12
|
+
// src/continuity/runtime-authority.ts
|
|
13
|
+
import { randomUUID, verify } from "node:crypto";
|
|
14
|
+
import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
16
|
+
function assertPrivateDirectory(path2) {
|
|
17
|
+
const stat = lstatSync(path2);
|
|
18
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || process.platform !== "win32" && (stat.uid !== process.getuid() || stat.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
|
|
19
|
+
}
|
|
20
|
+
function readPrivateFile(path2, maximum) {
|
|
21
|
+
const before = lstatSync(path2);
|
|
22
|
+
if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
|
|
23
|
+
const fd = openSync(path2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
24
|
+
try {
|
|
25
|
+
if (fstatSync(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
|
|
26
|
+
return readFileSync(fd);
|
|
27
|
+
} finally {
|
|
28
|
+
closeSync(fd);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function writeControl(path2, value) {
|
|
32
|
+
const temporary = path2 + "." + randomUUID() + ".tmp";
|
|
33
|
+
writeFileSync(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
|
|
34
|
+
renameSync(temporary, path2);
|
|
35
|
+
if (process.platform !== "win32") {
|
|
36
|
+
const fd = openSync(dirname(path2), "r");
|
|
37
|
+
try {
|
|
38
|
+
fsyncSync(fd);
|
|
39
|
+
} finally {
|
|
40
|
+
closeSync(fd);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function runtimeAuthorityFor(stateDir) {
|
|
45
|
+
for (let root = resolve(stateDir); ; ) {
|
|
46
|
+
const existing = runtimes.get(root);
|
|
47
|
+
if (existing) return existing;
|
|
48
|
+
const file = join(root, ".continuity", "travel-runtime.json");
|
|
49
|
+
if (existsSync(file)) {
|
|
50
|
+
const enrollment = JSON.parse(readPrivateFile(file, 16384).toString());
|
|
51
|
+
if (enrollment.format !== "engine7-travel-runtime-v1") throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
|
|
52
|
+
return new RuntimeAuthority({ stateDir: root, ...enrollment });
|
|
53
|
+
}
|
|
54
|
+
if (existsSync(join(root, ".travel-active.json")) || existsSync(join(root, ".travel-enrolled.json"))) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
|
|
55
|
+
const parent = dirname(root);
|
|
56
|
+
if (parent === root) return null;
|
|
57
|
+
root = parent;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function assertRuntimeAuthority(stateDir, operation) {
|
|
61
|
+
const root = stateDir || process.env.ENGINE7_TRAVEL_STATE_DIR || process.env.ENGINE_STATE_DIR;
|
|
62
|
+
if (root) runtimeAuthorityFor(root)?.assert(operation);
|
|
63
|
+
}
|
|
64
|
+
var runtimes, now, equal, RuntimeAuthority;
|
|
65
|
+
var init_runtime_authority = __esm({
|
|
66
|
+
"src/continuity/runtime-authority.ts"() {
|
|
67
|
+
"use strict";
|
|
68
|
+
runtimes = /* @__PURE__ */ new Map();
|
|
69
|
+
now = () => Number(process.hrtime.bigint() / 1000000n);
|
|
70
|
+
equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
71
|
+
RuntimeAuthority = class {
|
|
72
|
+
stateDir;
|
|
73
|
+
enrollment;
|
|
74
|
+
directory;
|
|
75
|
+
clock;
|
|
76
|
+
previous;
|
|
77
|
+
cachedGrant = null;
|
|
78
|
+
cachedFloor = 0;
|
|
79
|
+
constructor(options) {
|
|
80
|
+
this.stateDir = resolve(options.stateDir);
|
|
81
|
+
this.directory = join(this.stateDir, ".continuity");
|
|
82
|
+
this.clock = options.monotonicNow ?? now;
|
|
83
|
+
const tools = options.allowedTools ?? [];
|
|
84
|
+
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");
|
|
85
|
+
this.enrollment = { format: "engine7-travel-runtime-v1", identity: options.identity, nodeId: options.nodeId, bootId: options.bootId, publicKey: options.publicKey, allowedTools: [...new Set(tools)].sort() };
|
|
86
|
+
if (options.initialize) {
|
|
87
|
+
mkdirSync(this.directory, { mode: 448, recursive: true });
|
|
88
|
+
assertPrivateDirectory(this.directory);
|
|
89
|
+
const file = join(this.directory, "travel-runtime.json");
|
|
90
|
+
if (!existsSync(file)) writeFileSync(file, JSON.stringify(this.enrollment), { mode: 384, flag: "wx", flush: true });
|
|
91
|
+
const marker = join(this.stateDir, ".travel-enrolled.json");
|
|
92
|
+
if (!existsSync(marker)) writeFileSync(marker, JSON.stringify({ format: this.enrollment.format, identity: options.identity }), { mode: 384, flag: "wx", flush: true });
|
|
93
|
+
}
|
|
94
|
+
this.checkEnrollment();
|
|
95
|
+
this.previous = runtimes.get(this.stateDir);
|
|
96
|
+
runtimes.set(this.stateDir, this);
|
|
97
|
+
}
|
|
98
|
+
checkEnrollment() {
|
|
99
|
+
try {
|
|
100
|
+
assertPrivateDirectory(this.directory);
|
|
101
|
+
const existing = JSON.parse(readPrivateFile(join(this.directory, "travel-runtime.json"), 16384).toString());
|
|
102
|
+
if (!equal(existing, this.enrollment)) throw new Error("TRAVEL_RUNTIME_IDENTITY_MISMATCH");
|
|
103
|
+
} catch (error) {
|
|
104
|
+
throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED", { cause: error });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
grant() {
|
|
108
|
+
this.checkEnrollment();
|
|
109
|
+
const file = join(this.directory, "travel-permit.json");
|
|
110
|
+
if (!existsSync(file)) return null;
|
|
111
|
+
try {
|
|
112
|
+
const grant = JSON.parse(readPrivateFile(file, 16384).toString());
|
|
113
|
+
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();
|
|
114
|
+
return grant;
|
|
115
|
+
} catch (error) {
|
|
116
|
+
throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED", { cause: error });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
writeGrant(grant) {
|
|
120
|
+
this.checkEnrollment();
|
|
121
|
+
writeControl(join(this.directory, "travel-permit.json"), grant);
|
|
122
|
+
this.cachedGrant = grant;
|
|
123
|
+
}
|
|
124
|
+
validatePermit(permit) {
|
|
125
|
+
try {
|
|
126
|
+
const { signature, ...body } = permit;
|
|
127
|
+
if (!verify(null, Buffer.from(JSON.stringify(body)), this.enrollment.publicKey, Buffer.from(signature, "base64"))) throw new Error();
|
|
128
|
+
} catch {
|
|
129
|
+
throw new Error("TRAVEL_INVALID_PERMIT");
|
|
130
|
+
}
|
|
131
|
+
const { identity, nodeId, bootId: bootId2 } = this.enrollment;
|
|
132
|
+
if (permit.nodeId !== nodeId || permit.bootId !== bootId2 || permit.tenantId !== identity.tenantId || permit.companionId !== identity.companionId || permit.seatId !== identity.seatId) throw new Error("TRAVEL_PERMIT_IDENTITY_MISMATCH");
|
|
133
|
+
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");
|
|
134
|
+
}
|
|
135
|
+
acceptPermit(permit, requestStartedAt) {
|
|
136
|
+
this.validatePermit(permit);
|
|
137
|
+
const current2 = this.grant();
|
|
138
|
+
if (current2 && (permit.epoch < current2.epoch || permit.authorityBootId === current2.authorityBootId && permit.leaseSequence <= current2.leaseSequence)) throw new Error("TRAVEL_PERMIT_REPLAY");
|
|
139
|
+
const receivedAt = this.clock();
|
|
140
|
+
if (!Number.isFinite(requestStartedAt) || requestStartedAt > receivedAt || receivedAt >= requestStartedAt + permit.validForMs) throw new Error("TRAVEL_LEASE_EXPIRED");
|
|
141
|
+
this.writeGrant({ permit, requestStartedAt, frozen: current2?.frozen ?? false, inputPaused: current2?.inputPaused ?? false, epoch: permit.epoch, authorityBootId: permit.authorityBootId, leaseSequence: permit.leaseSequence });
|
|
142
|
+
}
|
|
143
|
+
assert(operation, binding) {
|
|
144
|
+
const grant = this.grant();
|
|
145
|
+
if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
146
|
+
this.validatePermit(grant.permit);
|
|
147
|
+
this.cachedFloor = this.deletionFloor();
|
|
148
|
+
this.cachedGrant = grant;
|
|
149
|
+
return this.assertFast(operation, binding);
|
|
150
|
+
}
|
|
151
|
+
/** Only for a synchronous SQLite capture whose BEGIN and COMMIT re-read the
|
|
152
|
+
* control files. In-transaction rows never publish past a changed barrier. */
|
|
153
|
+
assertFast(operation, binding) {
|
|
154
|
+
const grant = this.cachedGrant;
|
|
155
|
+
if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
156
|
+
const current2 = this.clock(), deadline = grant.requestStartedAt + grant.permit.validForMs;
|
|
157
|
+
if (current2 < grant.requestStartedAt || current2 >= deadline) throw new Error("TRAVEL_LEASE_EXPIRED");
|
|
158
|
+
if (operation !== "CONTROL" && grant.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
|
|
159
|
+
if (operation === "INPUT" && grant.inputPaused) throw new Error("TRAVEL_INPUT_PAUSED");
|
|
160
|
+
if (operation !== "CONTROL" && grant.permit.deletionWatermark !== this.cachedFloor) throw new Error("TRAVEL_DELETION_BARRIER");
|
|
161
|
+
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");
|
|
162
|
+
return grant.permit;
|
|
163
|
+
}
|
|
164
|
+
deletionFloor() {
|
|
165
|
+
const file = join(this.directory, "travel-deletion-floor.json");
|
|
166
|
+
if (!existsSync(file)) return 0;
|
|
167
|
+
const value = JSON.parse(readPrivateFile(file, 128).toString());
|
|
168
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error("TRAVEL_RUNTIME_RECOVERY_REQUIRED");
|
|
169
|
+
return value;
|
|
170
|
+
}
|
|
171
|
+
advanceDeletionFloor(floor) {
|
|
172
|
+
if (!Number.isSafeInteger(floor) || floor < this.deletionFloor()) throw new Error("TRAVEL_DELETION_ROLLBACK");
|
|
173
|
+
writeControl(join(this.directory, "travel-deletion-floor.json"), floor);
|
|
174
|
+
this.cachedFloor = floor;
|
|
175
|
+
}
|
|
176
|
+
freeze(frozen) {
|
|
177
|
+
const grant = this.grant();
|
|
178
|
+
if (!grant) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
179
|
+
if (grant.permit) this.validatePermit(grant.permit);
|
|
180
|
+
this.writeGrant({ ...grant, frozen });
|
|
181
|
+
}
|
|
182
|
+
pauseInput(paused) {
|
|
183
|
+
if (typeof paused !== "boolean") throw new Error("TRAVEL_INVALID_CONTROL");
|
|
184
|
+
const grant = this.grant();
|
|
185
|
+
if (!grant?.permit) throw new Error("TRAVEL_PERMIT_REQUIRED");
|
|
186
|
+
this.validatePermit(grant.permit);
|
|
187
|
+
this.writeGrant({ ...grant, inputPaused: paused });
|
|
188
|
+
}
|
|
189
|
+
revoke() {
|
|
190
|
+
const grant = this.grant();
|
|
191
|
+
if (grant) this.writeGrant({ ...grant, permit: null });
|
|
192
|
+
}
|
|
193
|
+
close() {
|
|
194
|
+
if (runtimes.get(this.stateDir) === this) {
|
|
195
|
+
if (this.previous) runtimes.set(this.stateDir, this.previous);
|
|
196
|
+
else runtimes.delete(this.stateDir);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
// src/continuity/runtime-lock.ts
|
|
204
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
205
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
206
|
+
import { closeSync as closeSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, realpathSync } from "node:fs";
|
|
207
|
+
import { join as join2 } from "node:path";
|
|
208
|
+
import { createRequire } from "node:module";
|
|
209
|
+
function openSQLite(file, options = {}) {
|
|
210
|
+
return new (sqlite ??= createRequire(import.meta.url)("node:sqlite")).DatabaseSync(file, options);
|
|
211
|
+
}
|
|
212
|
+
function openControl(stateDir, create = true, busyTimeoutMs = 0) {
|
|
213
|
+
if (create) mkdirSync2(stateDir, { recursive: true });
|
|
214
|
+
const state = realpathSync(stateDir);
|
|
215
|
+
if (process.platform !== "win32" && lstatSync2(state).uid !== process.getuid()) throw new Error("CONTROL_OWNER_MISMATCH: run travel as the engine data owner, without sudo");
|
|
216
|
+
const directory2 = join2(state, ".continuity");
|
|
217
|
+
if (create) mkdirSync2(directory2, { recursive: true, mode: 448 });
|
|
218
|
+
if (lstatSync2(directory2).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_DIRECTORY");
|
|
219
|
+
assertControlPermissions(directory2);
|
|
220
|
+
const file = join2(directory2, "runtime.sqlite");
|
|
221
|
+
if (create) {
|
|
222
|
+
try {
|
|
223
|
+
closeSync2(openSync2(file, "wx", 384));
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (error.code !== "EEXIST") throw error;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
assertControlPermissions(file);
|
|
229
|
+
for (const name of [file, file + "-journal", file + "-wal", file + "-shm"]) {
|
|
230
|
+
try {
|
|
231
|
+
if (!lstatSync2(name).isFile() || lstatSync2(name).isSymbolicLink()) throw new Error("UNSAFE_CONTROL_FILE");
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (error.code !== "ENOENT") throw error;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const db = openSQLite(file);
|
|
237
|
+
try {
|
|
238
|
+
db.exec(`PRAGMA busy_timeout=${busyTimeoutMs}; PRAGMA synchronous=FULL;
|
|
239
|
+
CREATE TABLE IF NOT EXISTS writers (
|
|
240
|
+
id TEXT PRIMARY KEY, pid INTEGER NOT NULL, boot_id TEXT NOT NULL,
|
|
241
|
+
kind TEXT NOT NULL, registered_at TEXT NOT NULL
|
|
242
|
+
)`);
|
|
243
|
+
return db;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
db.close();
|
|
246
|
+
throw normalize(error);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function assertControlPermissions(file) {
|
|
250
|
+
const info = lstatSync2(file);
|
|
251
|
+
if (process.platform !== "win32" && (info.uid !== process.getuid() || info.mode & 63))
|
|
252
|
+
throw new Error("CONTROL_PERMISSIONS: use the engine data owner; repair .continuity ownership and private permissions while stopped");
|
|
253
|
+
}
|
|
254
|
+
function assertStateDirUsable(stateDir) {
|
|
255
|
+
if (typeof stateDir !== "string" || !stateDir.trim()) throw new Error("RUNTIME_STATE_DIR_REQUIRED");
|
|
256
|
+
const initial = initialBaselineAdmission.getStore();
|
|
257
|
+
if (initial?.active && initial.roots.has(realpathSync(stateDir))) return;
|
|
258
|
+
try {
|
|
259
|
+
lstatSync2(join2(stateDir, ".travel-restored.json"));
|
|
260
|
+
throw new Error("TRAVEL_ACTIVATION_REQUIRED");
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (error.code !== "ENOENT") throw error;
|
|
263
|
+
}
|
|
264
|
+
assertRuntimeAuthority(stateDir, "WRITE");
|
|
265
|
+
}
|
|
266
|
+
function normalize(error) {
|
|
267
|
+
return /database is locked|database table is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error)) ? new Error("CHECKPOINT_BUSY", { cause: error }) : error;
|
|
268
|
+
}
|
|
269
|
+
function registerRuntimeWriter(stateDir, kind) {
|
|
270
|
+
assertStateDirUsable(stateDir);
|
|
271
|
+
const recovery = recoveryWriterLocks.getStore();
|
|
272
|
+
if (recovery?.active && recovery.roots.has(realpathSync(stateDir))) return () => {
|
|
273
|
+
};
|
|
274
|
+
const db = openControl(stateDir, true, 1e3), id = randomUUID2();
|
|
275
|
+
try {
|
|
276
|
+
db.exec("BEGIN IMMEDIATE");
|
|
277
|
+
db.prepare("INSERT INTO writers VALUES (?, ?, ?, ?, ?)").run(id, process.pid, bootId, kind, (/* @__PURE__ */ new Date()).toISOString());
|
|
278
|
+
db.exec("COMMIT");
|
|
279
|
+
} catch (error) {
|
|
280
|
+
throw normalize(error);
|
|
281
|
+
} finally {
|
|
282
|
+
db.close();
|
|
283
|
+
}
|
|
284
|
+
let released = false;
|
|
285
|
+
const release = () => {
|
|
286
|
+
if (released) return;
|
|
287
|
+
let control;
|
|
288
|
+
try {
|
|
289
|
+
control = openControl(stateDir, false, 1e3);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error.code !== "ENOENT") throw error;
|
|
292
|
+
released = true;
|
|
293
|
+
releases.delete(release);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
control.prepare("DELETE FROM writers WHERE id=? AND boot_id=?").run(id, bootId);
|
|
298
|
+
} finally {
|
|
299
|
+
control.close();
|
|
300
|
+
}
|
|
301
|
+
released = true;
|
|
302
|
+
releases.delete(release);
|
|
303
|
+
};
|
|
304
|
+
releases.add(release);
|
|
305
|
+
if (!exitHookInstalled) {
|
|
306
|
+
exitHookInstalled = true;
|
|
307
|
+
process.once("exit", () => {
|
|
308
|
+
for (const stop of releases) {
|
|
309
|
+
try {
|
|
310
|
+
stop();
|
|
311
|
+
} catch {
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
return release;
|
|
317
|
+
}
|
|
318
|
+
var sqlite, bootId, releases, exitHookInstalled, recoveryWriterLocks, initialBaselineAdmission;
|
|
319
|
+
var init_runtime_lock = __esm({
|
|
320
|
+
"src/continuity/runtime-lock.ts"() {
|
|
321
|
+
"use strict";
|
|
322
|
+
init_runtime_authority();
|
|
323
|
+
bootId = randomUUID2();
|
|
324
|
+
releases = /* @__PURE__ */ new Set();
|
|
325
|
+
exitHookInstalled = false;
|
|
326
|
+
recoveryWriterLocks = new AsyncLocalStorage();
|
|
327
|
+
initialBaselineAdmission = new AsyncLocalStorage();
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
// src/continuity/key-service-store.ts
|
|
332
|
+
import { DatabaseSync } from "node:sqlite";
|
|
333
|
+
import { constants as constants2, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync3, closeSync as closeSync3, readFileSync as readFileSync3, writeSync, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync } from "node:fs";
|
|
334
|
+
function assertPrivateStat(stat, directory2) {
|
|
335
|
+
if ((directory2 ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
336
|
+
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
337
|
+
}
|
|
338
|
+
function readPrivateFile2(path2, maximumBytes = 65536) {
|
|
339
|
+
assertPrivateStat(lstatSync3(path2), false);
|
|
340
|
+
const fd = openSync3(path2, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
341
|
+
try {
|
|
342
|
+
const stat = fstatSync2(fd);
|
|
343
|
+
assertPrivateStat(stat, false);
|
|
344
|
+
if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
345
|
+
return readFileSync3(fd);
|
|
346
|
+
} finally {
|
|
347
|
+
closeSync3(fd);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
var init_key_service_store = __esm({
|
|
351
|
+
"src/continuity/key-service-store.ts"() {
|
|
352
|
+
"use strict";
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
// src/continuity/publication-objects.ts
|
|
357
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
358
|
+
import {
|
|
359
|
+
constants as constants3,
|
|
360
|
+
openSync as openSync4,
|
|
361
|
+
closeSync as closeSync4,
|
|
362
|
+
fstatSync as fstatSync3,
|
|
363
|
+
fsyncSync as fsyncSync3,
|
|
364
|
+
readSync,
|
|
365
|
+
writeSync as writeSync2,
|
|
366
|
+
lstatSync as lstatSync4,
|
|
367
|
+
realpathSync as realpathSync2,
|
|
368
|
+
mkdirSync as mkdirSync4,
|
|
369
|
+
readFileSync as readFileSync4,
|
|
370
|
+
writeFileSync as writeFileSync2,
|
|
371
|
+
linkSync,
|
|
372
|
+
unlinkSync as unlinkSync2
|
|
373
|
+
} from "node:fs";
|
|
374
|
+
import { join as join3, dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
375
|
+
function assertPrivateDirectory2(path2) {
|
|
376
|
+
const info = lstatSync4(path2);
|
|
377
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path2) !== resolve2(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
378
|
+
throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
|
|
379
|
+
}
|
|
380
|
+
var PUBLICATION_CHUNK_BYTES, MAGIC, noFollow;
|
|
381
|
+
var init_publication_objects = __esm({
|
|
382
|
+
"src/continuity/publication-objects.ts"() {
|
|
383
|
+
"use strict";
|
|
384
|
+
PUBLICATION_CHUNK_BYTES = 1024 * 1024;
|
|
385
|
+
MAGIC = Buffer.from("E7P1");
|
|
386
|
+
noFollow = constants3.O_NOFOLLOW ?? 0;
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
|
|
12
390
|
// src/memory/schema-migrations.ts
|
|
13
391
|
function authorizeMemoryWriter(db, supportedVersion) {
|
|
14
392
|
db.function("engine_memory_writer_version", () => supportedVersion);
|
|
@@ -28,39 +406,410 @@ var init_schema_migrations = __esm({
|
|
|
28
406
|
}
|
|
29
407
|
});
|
|
30
408
|
|
|
409
|
+
// src/continuity/legacy-sqlite-indexes.ts
|
|
410
|
+
var init_legacy_sqlite_indexes = __esm({
|
|
411
|
+
"src/continuity/legacy-sqlite-indexes.ts"() {
|
|
412
|
+
"use strict";
|
|
413
|
+
init_schema_migrations();
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
// src/continuity/sqlite-replication.ts
|
|
418
|
+
import { createHash } from "node:crypto";
|
|
419
|
+
function bindingText(binding) {
|
|
420
|
+
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");
|
|
421
|
+
return JSON.stringify([binding.tenantId, binding.companionId, binding.seatId, binding.databaseId, binding.baselineId, binding.epoch]);
|
|
422
|
+
}
|
|
423
|
+
function normalizeBinding(binding) {
|
|
424
|
+
const [tenantId, companionId, seatId, databaseId, baselineId, epoch] = JSON.parse(bindingText(binding));
|
|
425
|
+
return Object.freeze({ tenantId, companionId, seatId, databaseId, baselineId, epoch });
|
|
426
|
+
}
|
|
427
|
+
function readSQLiteReplicationSource(db) {
|
|
428
|
+
if (!validateMetadata(db)) return null;
|
|
429
|
+
const rows = db.prepare("SELECT role,binding,schema_hash FROM e7_replication_control").all();
|
|
430
|
+
if (rows.length !== 1 || rows[0].role !== "source") throw new Error("REPLICATION_SOURCE_REQUIRED");
|
|
431
|
+
const row = rows[0];
|
|
432
|
+
try {
|
|
433
|
+
const fields = JSON.parse(String(row.binding));
|
|
434
|
+
if (!Array.isArray(fields) || fields.length !== 6 || !digestPattern.test(String(row.schema_hash))) throw new Error();
|
|
435
|
+
const [tenantId, companionId, seatId, databaseId, baselineId, epoch] = fields;
|
|
436
|
+
return { binding: normalizeBinding({ tenantId, companionId, seatId, databaseId, baselineId, epoch }), schemaHash: String(row.schema_hash) };
|
|
437
|
+
} catch {
|
|
438
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
function schemaRows(db) {
|
|
442
|
+
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));
|
|
443
|
+
}
|
|
444
|
+
function sqliteReplicationSchemaHash(db) {
|
|
445
|
+
return hash(JSON.stringify(schemaRows(db)));
|
|
446
|
+
}
|
|
447
|
+
function validateMetadata(db) {
|
|
448
|
+
const rows = db.prepare("SELECT name,type FROM sqlite_master WHERE name IN (?,?,?)").all(...metadataTables);
|
|
449
|
+
if (!rows.length) return false;
|
|
450
|
+
if (rows.length !== metadataTables.size || rows.some((row) => row.type !== "table"))
|
|
451
|
+
throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: new Error("incomplete replication metadata") });
|
|
452
|
+
for (const [table, expected] of Object.entries(metadataColumns)) {
|
|
453
|
+
const columns = db.prepare(`PRAGMA table_xinfo(${identifier(table)})`).all();
|
|
454
|
+
if (columns.length !== expected.length || columns.some((column, index) => {
|
|
455
|
+
const [name, type, notnull, pk] = expected[index];
|
|
456
|
+
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;
|
|
457
|
+
})) throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: new Error("invalid replication metadata " + table) });
|
|
458
|
+
}
|
|
459
|
+
return true;
|
|
460
|
+
}
|
|
461
|
+
var metadataTables, metadataColumns, guardPrefix, identifier, hash, digestPattern;
|
|
462
|
+
var init_sqlite_replication = __esm({
|
|
463
|
+
"src/continuity/sqlite-replication.ts"() {
|
|
464
|
+
"use strict";
|
|
465
|
+
init_legacy_sqlite_indexes();
|
|
466
|
+
init_runtime_authority();
|
|
467
|
+
metadataTables = /* @__PURE__ */ new Set(["e7_replication_control", "e7_replication_outbox", "e7_replication_inbox"]);
|
|
468
|
+
metadataColumns = {
|
|
469
|
+
e7_replication_control: [
|
|
470
|
+
["role", "TEXT", 0, 1],
|
|
471
|
+
["binding", "TEXT", 1, 0],
|
|
472
|
+
["schema_hash", "TEXT", 1, 0],
|
|
473
|
+
["head", "INTEGER", 1, 0],
|
|
474
|
+
["digest", "TEXT", 1, 0],
|
|
475
|
+
["ack_seq", "INTEGER", 1, 0],
|
|
476
|
+
["ack_digest", "TEXT", 1, 0],
|
|
477
|
+
["pending_bytes", "INTEGER", 1, 0]
|
|
478
|
+
],
|
|
479
|
+
e7_replication_outbox: [
|
|
480
|
+
["sequence", "INTEGER", 0, 1],
|
|
481
|
+
["parent_digest", "TEXT", 1, 0],
|
|
482
|
+
["changeset", "BLOB", 1, 0],
|
|
483
|
+
["sequences", "TEXT", 1, 0],
|
|
484
|
+
["digest", "TEXT", 1, 0]
|
|
485
|
+
],
|
|
486
|
+
e7_replication_inbox: [
|
|
487
|
+
["sequence", "INTEGER", 0, 1],
|
|
488
|
+
["parent_digest", "TEXT", 1, 0],
|
|
489
|
+
["changeset", "BLOB", 0, 0],
|
|
490
|
+
["sequences", "TEXT", 1, 0],
|
|
491
|
+
["digest", "TEXT", 1, 0],
|
|
492
|
+
["state", "TEXT", 1, 0]
|
|
493
|
+
]
|
|
494
|
+
};
|
|
495
|
+
guardPrefix = "writer_guard_replication_";
|
|
496
|
+
identifier = (s) => '"' + s.replaceAll('"', '""') + '"';
|
|
497
|
+
hash = (s) => createHash("sha256").update(s).digest("hex");
|
|
498
|
+
digestPattern = /^[a-f0-9]{64}$/;
|
|
499
|
+
}
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
// src/continuity/mem7-replication.ts
|
|
503
|
+
import { closeSync as closeSync5, fsyncSync as fsyncSync4, lstatSync as lstatSync5, openSync as openSync5, writeFileSync as writeFileSync3 } from "node:fs";
|
|
504
|
+
import { dirname as dirname3, join as join4 } from "node:path";
|
|
505
|
+
function normalize2(value) {
|
|
506
|
+
if (!value || !/^[a-f0-9]{64}$/.test(value.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
507
|
+
return Object.freeze({ binding: normalizeBinding(value.binding), schemaHash: value.schemaHash });
|
|
508
|
+
}
|
|
509
|
+
function hasMem7ReplicationRegistration(stateDir) {
|
|
510
|
+
try {
|
|
511
|
+
lstatSync5(location(stateDir));
|
|
512
|
+
return true;
|
|
513
|
+
} catch (error) {
|
|
514
|
+
if (error.code === "ENOENT") return false;
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
function readMem7ReplicationRegistration(stateDir) {
|
|
519
|
+
if (!hasMem7ReplicationRegistration(stateDir)) return null;
|
|
520
|
+
try {
|
|
521
|
+
assertPrivateDirectory2(dirname3(location(stateDir)));
|
|
522
|
+
return normalize2(JSON.parse(readPrivateFile2(location(stateDir), 4096).toString()));
|
|
523
|
+
} catch {
|
|
524
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
var location;
|
|
528
|
+
var init_mem7_replication = __esm({
|
|
529
|
+
"src/continuity/mem7-replication.ts"() {
|
|
530
|
+
"use strict";
|
|
531
|
+
init_key_service_store();
|
|
532
|
+
init_publication_objects();
|
|
533
|
+
init_sqlite_replication();
|
|
534
|
+
location = (stateDir) => join4(stateDir, ".continuity", "mem7-replication.json");
|
|
535
|
+
}
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
// src/continuity/runtime-replication.ts
|
|
539
|
+
import { constants as constants4, lstatSync as lstatSync6, realpathSync as realpathSync3, mkdirSync as mkdirSync5, openSync as openSync6, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4, fsyncSync as fsyncSync5 } from "node:fs";
|
|
540
|
+
import { basename as basename2, dirname as dirname4, join as join5, resolve as resolve3 } from "node:path";
|
|
541
|
+
function checkKey(component, key) {
|
|
542
|
+
if (component === "topics-vectors" && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) return;
|
|
543
|
+
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;
|
|
544
|
+
if (["calendar", "proactive", "session-events"].includes(component) && key === void 0) return;
|
|
545
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
546
|
+
}
|
|
547
|
+
function location2(stateDir, component, key) {
|
|
548
|
+
checkKey(component, key);
|
|
549
|
+
return join5(stateDir, ".continuity", component + (key === void 0 ? "" : "-" + key) + "-replication.json");
|
|
550
|
+
}
|
|
551
|
+
function runtimeReplicationFile(stateDir, component, key) {
|
|
552
|
+
checkKey(component, key);
|
|
553
|
+
if (component === "legacy-memory") return join5(stateDir, "agents", key, "memory", "memory.db");
|
|
554
|
+
if (component === "topics-vectors") return join5(stateDir, "topics-history", key, "vectors.db");
|
|
555
|
+
if (component === "session-events") return join5(stateDir, ".continuity", "session-events.db");
|
|
556
|
+
return join5(stateDir, "." + component, component + ".db");
|
|
557
|
+
}
|
|
558
|
+
function runtimeReplicationLocation(stateDir, component, file) {
|
|
559
|
+
const key = component === "legacy-memory" ? basename2(dirname4(dirname4(file))) : component === "topics-vectors" ? basename2(dirname4(file)) : void 0;
|
|
560
|
+
try {
|
|
561
|
+
if (resolve3(file) !== resolve3(runtimeReplicationFile(stateDir, component, key))) throw new Error();
|
|
562
|
+
} catch (error) {
|
|
563
|
+
throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED", { cause: error });
|
|
564
|
+
}
|
|
565
|
+
return { component, ...key === void 0 ? {} : { key } };
|
|
566
|
+
}
|
|
567
|
+
function normalize3(input) {
|
|
568
|
+
if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
569
|
+
return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
|
|
570
|
+
}
|
|
571
|
+
function directory(path2) {
|
|
572
|
+
const info = lstatSync6(path2);
|
|
573
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync3(path2) !== resolve3(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
574
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
575
|
+
}
|
|
576
|
+
function readRuntimeReplicationRegistration(stateDir, component, key) {
|
|
577
|
+
const file = location2(stateDir, component, key);
|
|
578
|
+
try {
|
|
579
|
+
lstatSync6(dirname4(file));
|
|
580
|
+
} catch (error) {
|
|
581
|
+
if (error.code === "ENOENT") return null;
|
|
582
|
+
throw error;
|
|
583
|
+
}
|
|
584
|
+
directory(dirname4(file));
|
|
585
|
+
let fd;
|
|
586
|
+
try {
|
|
587
|
+
fd = openSync6(file, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
|
|
588
|
+
} catch (error) {
|
|
589
|
+
if (error.code === "ENOENT") return null;
|
|
590
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
|
|
591
|
+
}
|
|
592
|
+
try {
|
|
593
|
+
const info = fstatSync4(fd);
|
|
594
|
+
if (!info.isFile() || info.size > 4096 || realpathSync3(file) !== resolve3(file) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error();
|
|
595
|
+
return normalize3(JSON.parse(readFileSync5(fd, "utf8")));
|
|
596
|
+
} catch (error) {
|
|
597
|
+
throw new Error("REPLICATION_REGISTRATION_INVALID", { cause: error });
|
|
598
|
+
} finally {
|
|
599
|
+
closeSync6(fd);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
function checkRuntimeReplicationFile(file, registration, initial = false) {
|
|
603
|
+
if (!registration && !initial) return;
|
|
604
|
+
try {
|
|
605
|
+
let info;
|
|
606
|
+
try {
|
|
607
|
+
info = lstatSync6(file);
|
|
608
|
+
} catch (error) {
|
|
609
|
+
if (registration || !initial || error.code !== "ENOENT") throw error;
|
|
610
|
+
let parent = dirname4(resolve3(file));
|
|
611
|
+
for (; ; ) {
|
|
612
|
+
try {
|
|
613
|
+
const existing = lstatSync6(parent);
|
|
614
|
+
if (!existing.isDirectory() || existing.isSymbolicLink() || realpathSync3(parent) !== parent) throw new Error();
|
|
615
|
+
return;
|
|
616
|
+
} catch (error2) {
|
|
617
|
+
if (error2.code !== "ENOENT") throw error2;
|
|
618
|
+
parent = dirname4(parent);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
if (!info.isFile() || info.isSymbolicLink() || realpathSync3(file) !== resolve3(file)) throw new Error();
|
|
623
|
+
} catch (error) {
|
|
624
|
+
throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: error });
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
var init_runtime_replication = __esm({
|
|
628
|
+
"src/continuity/runtime-replication.ts"() {
|
|
629
|
+
"use strict";
|
|
630
|
+
init_schema_migrations();
|
|
631
|
+
init_sqlite_replication();
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
|
|
31
635
|
// src/memory/topics-cleaning/materials.ts
|
|
32
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
33
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
34
|
-
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
636
|
+
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
637
|
+
import { existsSync as existsSync2, lstatSync as lstatSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync5 } from "node:fs";
|
|
638
|
+
import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute2, join as join7, relative as relative2, resolve as resolve7, sep as sep2 } from "node:path";
|
|
35
639
|
function canonical(value) {
|
|
36
640
|
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
37
641
|
if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
38
642
|
return JSON.stringify(value);
|
|
39
643
|
}
|
|
40
|
-
function safeRelative(
|
|
41
|
-
return typeof
|
|
644
|
+
function safeRelative(path2) {
|
|
645
|
+
return typeof path2 === "string" && !!path2 && !isAbsolute2(path2) && !/[:\\\x00-\x1f]/.test(path2) && path2.split("/").every((p) => p && p !== "." && p !== "..");
|
|
42
646
|
}
|
|
43
|
-
function unlinked(
|
|
44
|
-
let cursor =
|
|
647
|
+
function unlinked(path2) {
|
|
648
|
+
let cursor = resolve7(path2);
|
|
45
649
|
for (; ; ) {
|
|
46
650
|
try {
|
|
47
|
-
if (
|
|
651
|
+
if (lstatSync8(cursor).isSymbolicLink()) throw new Error("SYMLINK_PATH");
|
|
48
652
|
} catch (e) {
|
|
49
653
|
if (e.code !== "ENOENT") throw e;
|
|
50
654
|
}
|
|
51
|
-
const parent =
|
|
52
|
-
if (parent === cursor) return
|
|
655
|
+
const parent = dirname6(cursor);
|
|
656
|
+
if (parent === cursor) return resolve7(path2);
|
|
53
657
|
cursor = parent;
|
|
54
658
|
}
|
|
55
659
|
}
|
|
56
|
-
function readJson(
|
|
57
|
-
return JSON.parse(
|
|
660
|
+
function readJson(path2) {
|
|
661
|
+
return JSON.parse(readFileSync6(unlinked(path2), "utf8").replace(/^\uFEFF/, ""));
|
|
58
662
|
}
|
|
59
663
|
var digest;
|
|
60
664
|
var init_materials = __esm({
|
|
61
665
|
"src/memory/topics-cleaning/materials.ts"() {
|
|
62
666
|
"use strict";
|
|
63
|
-
digest = (value) =>
|
|
667
|
+
digest = (value) => createHash2("sha256").update(value).digest("hex");
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
// src/continuity/sqlite-autocommit.ts
|
|
672
|
+
var init_sqlite_autocommit = __esm({
|
|
673
|
+
"src/continuity/sqlite-autocommit.ts"() {
|
|
674
|
+
"use strict";
|
|
675
|
+
}
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
// src/config/writer.ts
|
|
679
|
+
import fs from "node:fs";
|
|
680
|
+
import path from "node:path";
|
|
681
|
+
function isNormalized(text) {
|
|
682
|
+
if (text === "") return true;
|
|
683
|
+
if (text.includes("\r")) return false;
|
|
684
|
+
let minIndent = Infinity;
|
|
685
|
+
for (const line of text.split("\n")) {
|
|
686
|
+
const m = /^( +)\S/.exec(line);
|
|
687
|
+
if (!m) continue;
|
|
688
|
+
const width = m[1].length;
|
|
689
|
+
if (width % 2 !== 0) return false;
|
|
690
|
+
if (width < minIndent) minIndent = width;
|
|
691
|
+
}
|
|
692
|
+
return minIndent === 2 || minIndent === Infinity;
|
|
693
|
+
}
|
|
694
|
+
function rotateBaks(filePath) {
|
|
695
|
+
const dir = path.dirname(filePath);
|
|
696
|
+
const base = path.basename(filePath);
|
|
697
|
+
const baks = fs.readdirSync(dir).filter((n) => n.startsWith(base + ".bak-")).sort();
|
|
698
|
+
while (baks.length >= KEEP_BAKS) {
|
|
699
|
+
const victim = baks.shift();
|
|
700
|
+
try {
|
|
701
|
+
fs.unlinkSync(path.join(dir, victim));
|
|
702
|
+
} catch {
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
function sleepSync(ms) {
|
|
707
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
708
|
+
}
|
|
709
|
+
function errCode(err) {
|
|
710
|
+
return err?.code ?? "";
|
|
711
|
+
}
|
|
712
|
+
function writeFailure(filePath, primary, extra) {
|
|
713
|
+
const code = errCode(primary);
|
|
714
|
+
const reason = RETRYABLE_CODES.has(code) ? `\u76EE\u6807\u6587\u4EF6\u88AB\u5360\u7528\u6216\u4E0D\u53EF\u5199\uFF08${code}\uFF09\u2014\u2014\u8BF7\u5173\u95ED\u6B63\u5728\u4F7F\u7528\u5B83\u7684\u7A0B\u5E8F\uFF08\u7F16\u8F91\u5668\u3001\u6740\u6BD2\u3001\u540C\u6B65\u76D8\u7B49\uFF09\u540E\u91CD\u8BD5` : `\u5199\u5165\u5931\u8D25${code ? `\uFF08${code}\uFF09` : ""}\uFF1A${primary?.message ?? String(primary)}`;
|
|
715
|
+
return new ConfigWriteError(`\u65E0\u6CD5\u5199\u5165 ${filePath}\uFF1A${reason}${extra ? `\uFF1B${extra}` : ""}`, code, primary);
|
|
716
|
+
}
|
|
717
|
+
function renameWithRetry(from, to) {
|
|
718
|
+
for (let attempt = 1; ; attempt++) {
|
|
719
|
+
try {
|
|
720
|
+
fs.renameSync(from, to);
|
|
721
|
+
return;
|
|
722
|
+
} catch (err) {
|
|
723
|
+
if (attempt >= RENAME_ATTEMPTS || !RETRYABLE_CODES.has(errCode(err))) throw err;
|
|
724
|
+
sleepSync(RENAME_RETRY_MS);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
function commitFile(tmp, filePath) {
|
|
729
|
+
try {
|
|
730
|
+
renameWithRetry(tmp, filePath);
|
|
731
|
+
return;
|
|
732
|
+
} catch (primaryErr) {
|
|
733
|
+
const old = `${filePath}.old`;
|
|
734
|
+
try {
|
|
735
|
+
fs.renameSync(filePath, old);
|
|
736
|
+
} catch (err) {
|
|
737
|
+
throw writeFailure(filePath, primaryErr, `\u6539\u540D .old \u5907\u4EFD\u4E5F\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
|
|
738
|
+
}
|
|
739
|
+
try {
|
|
740
|
+
fs.renameSync(tmp, filePath);
|
|
741
|
+
} catch (err) {
|
|
742
|
+
try {
|
|
743
|
+
fs.renameSync(old, filePath);
|
|
744
|
+
} catch {
|
|
745
|
+
throw writeFailure(filePath, primaryErr, `\u65B0\u5185\u5BB9\u843D\u76D8\u4E0E\u56DE\u6EDA\u90FD\u5931\u8D25\uFF0C\u65E7\u5185\u5BB9\u7559\u5728 ${old}`);
|
|
746
|
+
}
|
|
747
|
+
throw writeFailure(filePath, primaryErr, `\u6362\u540D\u843D\u76D8\u5931\u8D25\uFF08${errCode(err) || "\u672A\u77E5"}\uFF09`);
|
|
748
|
+
}
|
|
749
|
+
try {
|
|
750
|
+
fs.unlinkSync(old);
|
|
751
|
+
} catch {
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
function writeConfigAtomic(filePath, obj) {
|
|
756
|
+
const existed = fs.existsSync(filePath);
|
|
757
|
+
let prevText = "";
|
|
758
|
+
let fileMode;
|
|
759
|
+
if (existed) {
|
|
760
|
+
try {
|
|
761
|
+
prevText = fs.readFileSync(filePath, "utf-8");
|
|
762
|
+
fileMode = fs.statSync(filePath).mode & 511;
|
|
763
|
+
} catch (err) {
|
|
764
|
+
throw writeFailure(filePath, err);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
const normalized = !existed || !isNormalized(prevText);
|
|
768
|
+
if (prevText) {
|
|
769
|
+
try {
|
|
770
|
+
fs.copyFileSync(filePath, `${filePath}.bak-${Date.now()}`);
|
|
771
|
+
} catch {
|
|
772
|
+
}
|
|
773
|
+
rotateBaks(filePath);
|
|
774
|
+
}
|
|
775
|
+
const content = JSON.stringify(obj, null, 2) + "\n";
|
|
776
|
+
const tmp = path.join(path.dirname(filePath), `.${path.basename(filePath)}.tmp-${process.pid}`);
|
|
777
|
+
try {
|
|
778
|
+
const fd = fs.openSync(tmp, "w", fileMode);
|
|
779
|
+
try {
|
|
780
|
+
if (fileMode !== void 0) fs.fchmodSync(fd, fileMode);
|
|
781
|
+
fs.writeFileSync(fd, content, "utf-8");
|
|
782
|
+
fs.fsyncSync(fd);
|
|
783
|
+
} finally {
|
|
784
|
+
fs.closeSync(fd);
|
|
785
|
+
}
|
|
786
|
+
commitFile(tmp, filePath);
|
|
787
|
+
} catch (err) {
|
|
788
|
+
throw err instanceof ConfigWriteError ? err : writeFailure(filePath, err);
|
|
789
|
+
} finally {
|
|
790
|
+
try {
|
|
791
|
+
fs.unlinkSync(tmp);
|
|
792
|
+
} catch {
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
return { normalized };
|
|
796
|
+
}
|
|
797
|
+
var KEEP_BAKS, RENAME_ATTEMPTS, RENAME_RETRY_MS, RETRYABLE_CODES, ConfigWriteError;
|
|
798
|
+
var init_writer = __esm({
|
|
799
|
+
"src/config/writer.ts"() {
|
|
800
|
+
"use strict";
|
|
801
|
+
KEEP_BAKS = 3;
|
|
802
|
+
RENAME_ATTEMPTS = 5;
|
|
803
|
+
RENAME_RETRY_MS = 50;
|
|
804
|
+
RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
|
|
805
|
+
ConfigWriteError = class extends Error {
|
|
806
|
+
code;
|
|
807
|
+
constructor(message, code, cause) {
|
|
808
|
+
super(message, { cause });
|
|
809
|
+
this.name = "ConfigWriteError";
|
|
810
|
+
this.code = code;
|
|
811
|
+
}
|
|
812
|
+
};
|
|
64
813
|
}
|
|
65
814
|
});
|
|
66
815
|
|
|
@@ -72,6 +821,7 @@ var LiveConfigClass, liveConfig, selfWrite;
|
|
|
72
821
|
var init_live = __esm({
|
|
73
822
|
"src/config/live.ts"() {
|
|
74
823
|
"use strict";
|
|
824
|
+
init_writer();
|
|
75
825
|
LiveConfigClass = class {
|
|
76
826
|
current = null;
|
|
77
827
|
/** 启动时注入(替代 registry.config = config) */
|
|
@@ -120,7 +870,7 @@ var init_live = __esm({
|
|
|
120
870
|
* "免费档补齐 xxx" 的成功日志 ⇒ 配置**没写进文件**却被读成"写好了":进程内生效、托盘
|
|
121
871
|
* 读文件还是旧值、下次启动重放同一句——正是本仓最恨的假信号。
|
|
122
872
|
*/
|
|
123
|
-
async set(dotPath, val) {
|
|
873
|
+
async set(dotPath, val, options) {
|
|
124
874
|
if (!this.current) throw new Error("[liveConfig] not initialized \u2014 call liveConfig.init() first");
|
|
125
875
|
const keys = dotPath.split(".");
|
|
126
876
|
const dangerous = keys.find((k) => k === "__proto__" || k === "constructor" || k === "prototype");
|
|
@@ -131,18 +881,18 @@ var init_live = __esm({
|
|
|
131
881
|
obj = obj[keys[i]];
|
|
132
882
|
}
|
|
133
883
|
obj[keys[keys.length - 1]] = val;
|
|
134
|
-
return this.persistToFile(dotPath, val);
|
|
884
|
+
return this.persistToFile(dotPath, val, options?.atomic === true);
|
|
135
885
|
}
|
|
136
886
|
/** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
|
|
137
|
-
async persistToFile(dotPath, val) {
|
|
138
|
-
const
|
|
887
|
+
async persistToFile(dotPath, val, atomic = false) {
|
|
888
|
+
const fs2 = await import("node:fs");
|
|
139
889
|
const cfgPath = this.current?._configFilePath;
|
|
140
|
-
if (!cfgPath || !
|
|
890
|
+
if (!cfgPath || !fs2.existsSync(cfgPath)) {
|
|
141
891
|
console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
|
|
142
892
|
return false;
|
|
143
893
|
}
|
|
144
894
|
try {
|
|
145
|
-
const raw = JSON.parse(
|
|
895
|
+
const raw = JSON.parse(fs2.readFileSync(cfgPath, "utf-8"));
|
|
146
896
|
const keys = dotPath.split(".");
|
|
147
897
|
let o = raw;
|
|
148
898
|
for (let i = 0; i < keys.length - 1; i++) {
|
|
@@ -150,7 +900,9 @@ var init_live = __esm({
|
|
|
150
900
|
o = o[keys[i]];
|
|
151
901
|
}
|
|
152
902
|
o[keys[keys.length - 1]] = val;
|
|
153
|
-
|
|
903
|
+
if (atomic) {
|
|
904
|
+
writeConfigAtomic(cfgPath, raw);
|
|
905
|
+
} else fs2.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
|
|
154
906
|
const lastKey = keys[keys.length - 1].toLowerCase();
|
|
155
907
|
const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
|
|
156
908
|
const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
|
|
@@ -172,11 +924,19 @@ var init_live = __esm({
|
|
|
172
924
|
}
|
|
173
925
|
});
|
|
174
926
|
|
|
927
|
+
// src/time/wall-parts.ts
|
|
928
|
+
var init_wall_parts = __esm({
|
|
929
|
+
"src/time/wall-parts.ts"() {
|
|
930
|
+
"use strict";
|
|
931
|
+
}
|
|
932
|
+
});
|
|
933
|
+
|
|
175
934
|
// src/time/clock.ts
|
|
176
935
|
var init_clock = __esm({
|
|
177
936
|
"src/time/clock.ts"() {
|
|
178
937
|
"use strict";
|
|
179
938
|
init_live();
|
|
939
|
+
init_wall_parts();
|
|
180
940
|
}
|
|
181
941
|
});
|
|
182
942
|
|
|
@@ -197,12 +957,12 @@ var init_scope = __esm({
|
|
|
197
957
|
|
|
198
958
|
// src/mem7/core/state/temporal.ts
|
|
199
959
|
function canonicalJson(value) {
|
|
200
|
-
const
|
|
201
|
-
if (Array.isArray(input)) return input.map(
|
|
202
|
-
if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key,
|
|
960
|
+
const normalize4 = (input) => {
|
|
961
|
+
if (Array.isArray(input)) return input.map(normalize4);
|
|
962
|
+
if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, normalize4(entry)]));
|
|
203
963
|
return input;
|
|
204
964
|
};
|
|
205
|
-
const json = JSON.stringify(
|
|
965
|
+
const json = JSON.stringify(normalize4(value));
|
|
206
966
|
if (json === void 0) throw new Error("INVALID_JSON_VALUE");
|
|
207
967
|
return json;
|
|
208
968
|
}
|
|
@@ -301,8 +1061,8 @@ var init_dependencies = __esm({
|
|
|
301
1061
|
});
|
|
302
1062
|
|
|
303
1063
|
// src/mem7/core/change-feed.ts
|
|
304
|
-
import { createHash as
|
|
305
|
-
import { existsSync as
|
|
1064
|
+
import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
|
|
1065
|
+
import { existsSync as existsSync3, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync6 } from "node:fs";
|
|
306
1066
|
function isBusyError(error) {
|
|
307
1067
|
if (!error || typeof error !== "object") return false;
|
|
308
1068
|
if (error.errcode === 5) return true;
|
|
@@ -326,7 +1086,7 @@ function appendMemoryChange(db, input, requestKey) {
|
|
|
326
1086
|
sourceIds: [...new Set(input.sourceIds)].sort(),
|
|
327
1087
|
...input.changedEntityIds ? { changedEntityIds: [...new Set(input.changedEntityIds)].sort() } : {}
|
|
328
1088
|
};
|
|
329
|
-
const eventId = `evt_${
|
|
1089
|
+
const eventId = `evt_${createHash3("sha256").update(canonicalJson([input.scopeId, input.kind, requestKey])).digest("hex")}`;
|
|
330
1090
|
const previous = db.prepare("SELECT payload_json FROM memory_state_outbox WHERE event_id=?").get(eventId);
|
|
331
1091
|
if (previous) {
|
|
332
1092
|
const event2 = JSON.parse(previous.payload_json);
|
|
@@ -387,7 +1147,7 @@ var init_change_feed = __esm({
|
|
|
387
1147
|
SELECT ?,event_id,scope_id FROM memory_state_outbox WHERE rowid>? AND rowid<=?`).run(sinkId, watermark.seq, max);
|
|
388
1148
|
this.db.prepare("UPDATE memory_projection_sink_watermarks SET seq=? WHERE sink_id=?").run(max, sinkId);
|
|
389
1149
|
}
|
|
390
|
-
pending(sinkId, limit = 50,
|
|
1150
|
+
pending(sinkId, limit = 50, now2 = Date.now()) {
|
|
391
1151
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) throw new Error("INVALID_DELIVERY_LIMIT");
|
|
392
1152
|
this.register(sinkId);
|
|
393
1153
|
const rows = this.db.prepare(`WITH heads AS (
|
|
@@ -398,7 +1158,7 @@ var init_change_feed = __esm({
|
|
|
398
1158
|
JOIN memory_state_outbox event ON event.scope_id=heads.scope_id AND event.event_seq=heads.event_seq
|
|
399
1159
|
JOIN memory_projection_deliveries delivery ON delivery.event_id=event.event_id AND delivery.sink_id=?
|
|
400
1160
|
WHERE delivery.next_run_at<=?
|
|
401
|
-
ORDER BY event.created_at,event.scope_id,event.event_seq LIMIT ?`).all(sinkId, sinkId,
|
|
1161
|
+
ORDER BY event.created_at,event.scope_id,event.event_seq LIMIT ?`).all(sinkId, sinkId, now2, limit);
|
|
402
1162
|
return rows.map((row) => JSON.parse(row.payload_json));
|
|
403
1163
|
}
|
|
404
1164
|
pendingWindow(sinkId, head, limit) {
|
|
@@ -423,9 +1183,9 @@ var init_change_feed = __esm({
|
|
|
423
1183
|
return true;
|
|
424
1184
|
});
|
|
425
1185
|
}
|
|
426
|
-
retry(sinkId, eventId, reason,
|
|
1186
|
+
retry(sinkId, eventId, reason, now2 = Date.now()) {
|
|
427
1187
|
this.db.prepare(`UPDATE memory_projection_deliveries SET attempts=attempts+1,last_error=?,
|
|
428
|
-
next_run_at=?+MIN(300000,1000*(1 << MIN(attempts,8))) WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(reason.slice(0, 300),
|
|
1188
|
+
next_run_at=?+MIN(300000,1000*(1 << MIN(attempts,8))) WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(reason.slice(0, 300), now2, sinkId, eventId);
|
|
429
1189
|
}
|
|
430
1190
|
/** 1027 小柯事故自愈:迁移/换新图(图 inbox 全新、position=0)撞上生产端带 ack 前缀 →
|
|
431
1191
|
* 队头永久 PROJECTION_SEQUENCE_GAP,投递与死信 skip 同检连坐、零进展直到人工介入。
|
|
@@ -435,14 +1195,14 @@ var init_change_feed = __esm({
|
|
|
435
1195
|
* 回滚后的生产端,只能人工重放。死信行复活时保留 attempts(妹妹 review P2-5:已知毒
|
|
436
1196
|
* 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
|
|
437
1197
|
* 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
|
|
438
|
-
reenqueueGapPrefix(sinkId, head,
|
|
1198
|
+
reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
|
|
439
1199
|
const key = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
|
|
440
1200
|
if (this.healedGaps.has(key)) return;
|
|
441
1201
|
const ledgerPath = this.gapHealLedgerPath;
|
|
442
1202
|
let ledger = {};
|
|
443
1203
|
if (ledgerPath) {
|
|
444
1204
|
try {
|
|
445
|
-
ledger = JSON.parse(
|
|
1205
|
+
ledger = JSON.parse(readFileSync7(ledgerPath, "utf8"))?.heals ?? {};
|
|
446
1206
|
} catch {
|
|
447
1207
|
}
|
|
448
1208
|
if (Number.isFinite(ledger[key])) {
|
|
@@ -462,25 +1222,25 @@ var init_change_feed = __esm({
|
|
|
462
1222
|
});
|
|
463
1223
|
this.healedGaps.add(key);
|
|
464
1224
|
if (!ledgerPath) return;
|
|
465
|
-
const cutoff =
|
|
1225
|
+
const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
|
|
466
1226
|
for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
|
|
467
|
-
retained[key] =
|
|
468
|
-
const temp = `${ledgerPath}.${
|
|
1227
|
+
retained[key] = now2;
|
|
1228
|
+
const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
|
|
469
1229
|
try {
|
|
470
|
-
|
|
471
|
-
|
|
1230
|
+
writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
|
|
1231
|
+
renameSync3(temp, ledgerPath);
|
|
472
1232
|
} catch (error) {
|
|
473
1233
|
try {
|
|
474
|
-
if (
|
|
1234
|
+
if (existsSync3(temp)) unlinkSync3(temp);
|
|
475
1235
|
} catch {
|
|
476
1236
|
}
|
|
477
1237
|
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}`);
|
|
478
1238
|
}
|
|
479
1239
|
}
|
|
480
1240
|
/** busy:只推后下次到期,attempts 不动(死信预算只留给真失败)。 */
|
|
481
|
-
retryTransient(sinkId, eventId,
|
|
1241
|
+
retryTransient(sinkId, eventId, now2) {
|
|
482
1242
|
this.db.prepare(`UPDATE memory_projection_deliveries SET last_error='SQLITE_BUSY',next_run_at=?
|
|
483
|
-
WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(
|
|
1243
|
+
WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(now2 + _ChangeFeed.BUSY_RETRY_MS, sinkId, eventId);
|
|
484
1244
|
}
|
|
485
1245
|
/** 满次数转死信终态(置 acked_at 解除队头阻塞),返回是否已转。must be head-of-line:
|
|
486
1246
|
* pending() 只出同 scope 队头,走到这里的失败事件前面不存在未 ack 事件,直接置终态
|
|
@@ -488,7 +1248,7 @@ var init_change_feed = __esm({
|
|
|
488
1248
|
* 1020 astra review P1:生产端终态 ≠ 消费者序号已前进——onDead(消费者 skip 协议)
|
|
489
1249
|
* 必须先落库再置终态,否则同 scope 后续正常事件全部 PROJECTION_SEQUENCE_GAP 连坐。
|
|
490
1250
|
* skip 失败 = 不死信、下轮重试(此时 attempts 已超帽,每轮退避重试 skip,响亮留痕)。 */
|
|
491
|
-
async deadLetter(sinkId, event, reason,
|
|
1251
|
+
async deadLetter(sinkId, event, reason, now2, onDead) {
|
|
492
1252
|
const row = this.db.prepare("SELECT attempts FROM memory_projection_deliveries WHERE sink_id=? AND event_id=?").get(sinkId, event.eventId);
|
|
493
1253
|
if (!row || Number(row.attempts) + 1 < _ChangeFeed.DEAD_LETTER_ATTEMPTS) return false;
|
|
494
1254
|
if (onDead) {
|
|
@@ -504,7 +1264,7 @@ var init_change_feed = __esm({
|
|
|
504
1264
|
}
|
|
505
1265
|
this.transaction(() => {
|
|
506
1266
|
this.db.prepare(`UPDATE memory_projection_deliveries SET attempts=attempts+1,last_error=?,acked_at=?,next_run_at=?
|
|
507
|
-
WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(`dead:${reason.slice(0, 290)}`, new Date(
|
|
1267
|
+
WHERE sink_id=? AND event_id=? AND acked_at IS NULL`).run(`dead:${reason.slice(0, 290)}`, new Date(now2).toISOString(), now2, sinkId, event.eventId);
|
|
508
1268
|
});
|
|
509
1269
|
console.warn(`[mem7] delivery dead-lettered ${event.kind} ${event.eventId.slice(0, 24)} after ${_ChangeFeed.DEAD_LETTER_ATTEMPTS} attempts: ${reason}\uFF08\u91CD\u653E\uFF1A\u6682\u505C\u6295\u9012\u5E76\u4FEE\u597D\u6839\u56E0\uFF0C\u91CD\u7F6E\u540C sink/scope \u4ECE seq=${event.eventSeq} \u8D77\u7684\u5168\u90E8\u6295\u9012\u884C\uFF0C\u5220\u540C scope \u8BE5\u6BB5 inbox \u6536\u636E\uFF0Cposition \u56DE\u9000\u81F3 ${event.eventSeq - 1}\uFF1B\u4FDD\u7559 heads \u5E76\u6309\u5E8F\u6062\u590D\uFF09`);
|
|
510
1270
|
return true;
|
|
@@ -518,21 +1278,21 @@ var init_change_feed = __esm({
|
|
|
518
1278
|
return { pending: Number(row.pending ?? 0), delivered: Number(row.delivered ?? 0), failed: Number(row.failed ?? 0) };
|
|
519
1279
|
}
|
|
520
1280
|
async deliver(sinkId, receive, options = {}) {
|
|
521
|
-
const
|
|
1281
|
+
const now2 = options.now ?? Date.now();
|
|
522
1282
|
const limit = options.limit ?? 100;
|
|
523
1283
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) throw new Error("INVALID_DELIVERY_LIMIT");
|
|
524
1284
|
let delivered = 0;
|
|
525
1285
|
let attempted = 0;
|
|
526
1286
|
const blockedScopes = /* @__PURE__ */ new Set();
|
|
527
1287
|
while (attempted < limit) {
|
|
528
|
-
const pending = this.pending(sinkId, limit,
|
|
1288
|
+
const pending = this.pending(sinkId, limit, now2).filter((event) => !blockedScopes.has(event.scopeId));
|
|
529
1289
|
if (!pending.length) break;
|
|
530
1290
|
const perScope = Math.max(1, Math.floor((limit - attempted) / pending.length));
|
|
531
1291
|
const windows = pending.map((head) => this.pendingWindow(sinkId, head, perScope));
|
|
532
1292
|
const batch = Array.from({ length: perScope }, (_, index) => windows.flatMap((window) => window[index] ? [window[index]] : [])).flat();
|
|
533
1293
|
for (const { event, dueAt } of batch) {
|
|
534
1294
|
if (blockedScopes.has(event.scopeId)) continue;
|
|
535
|
-
if (dueAt >
|
|
1295
|
+
if (dueAt > now2) {
|
|
536
1296
|
blockedScopes.add(event.scopeId);
|
|
537
1297
|
continue;
|
|
538
1298
|
}
|
|
@@ -543,11 +1303,11 @@ var init_change_feed = __esm({
|
|
|
543
1303
|
} catch (error) {
|
|
544
1304
|
const reason = deliveryReasonCode(error);
|
|
545
1305
|
if (isBusyError(error)) {
|
|
546
|
-
this.retryTransient(sinkId, event.eventId,
|
|
1306
|
+
this.retryTransient(sinkId, event.eventId, now2);
|
|
547
1307
|
} else {
|
|
548
1308
|
console.warn(`[mem7] delivery failed ${event.kind} ${event.eventId.slice(0, 24)}: ${reason} ${(error instanceof Error ? error.message : String(error)).slice(0, 300)}`);
|
|
549
1309
|
if (reason === "PROJECTION_SEQUENCE_GAP") this.reenqueueGapPrefix(sinkId, event);
|
|
550
|
-
if (!await this.deadLetter(sinkId, event, reason,
|
|
1310
|
+
if (!await this.deadLetter(sinkId, event, reason, now2, options.onDead)) this.retry(sinkId, event.eventId, reason, now2);
|
|
551
1311
|
}
|
|
552
1312
|
blockedScopes.add(event.scopeId);
|
|
553
1313
|
}
|
|
@@ -575,6 +1335,13 @@ var init_interpretation_impact = __esm({
|
|
|
575
1335
|
}
|
|
576
1336
|
});
|
|
577
1337
|
|
|
1338
|
+
// src/mem7/core/conversation-text.ts
|
|
1339
|
+
var init_conversation_text = __esm({
|
|
1340
|
+
"src/mem7/core/conversation-text.ts"() {
|
|
1341
|
+
"use strict";
|
|
1342
|
+
}
|
|
1343
|
+
});
|
|
1344
|
+
|
|
578
1345
|
// src/mem7/core/source-store.ts
|
|
579
1346
|
var init_source_store = __esm({
|
|
580
1347
|
"src/mem7/core/source-store.ts"() {
|
|
@@ -585,6 +1352,7 @@ var init_source_store = __esm({
|
|
|
585
1352
|
init_knowledge_history();
|
|
586
1353
|
init_read_budget();
|
|
587
1354
|
init_interpretation_impact();
|
|
1355
|
+
init_conversation_text();
|
|
588
1356
|
}
|
|
589
1357
|
});
|
|
590
1358
|
|
|
@@ -595,23 +1363,39 @@ var init_schema = __esm({
|
|
|
595
1363
|
}
|
|
596
1364
|
});
|
|
597
1365
|
|
|
1366
|
+
// src/continuity/recovery-deletion-sources.ts
|
|
1367
|
+
var init_recovery_deletion_sources = __esm({
|
|
1368
|
+
"src/continuity/recovery-deletion-sources.ts"() {
|
|
1369
|
+
"use strict";
|
|
1370
|
+
}
|
|
1371
|
+
});
|
|
1372
|
+
|
|
1373
|
+
// src/continuity/recovery-deletion.ts
|
|
1374
|
+
var init_recovery_deletion = __esm({
|
|
1375
|
+
"src/continuity/recovery-deletion.ts"() {
|
|
1376
|
+
"use strict";
|
|
1377
|
+
init_recovery_deletion_sources();
|
|
1378
|
+
}
|
|
1379
|
+
});
|
|
1380
|
+
|
|
598
1381
|
// src/mem7/core/state/tombstones.ts
|
|
599
1382
|
var init_tombstones = __esm({
|
|
600
1383
|
"src/mem7/core/state/tombstones.ts"() {
|
|
601
1384
|
"use strict";
|
|
602
1385
|
init_scope();
|
|
603
1386
|
init_change_feed();
|
|
1387
|
+
init_recovery_deletion();
|
|
604
1388
|
}
|
|
605
1389
|
});
|
|
606
1390
|
|
|
607
1391
|
// src/mem7/core/host-turns.ts
|
|
608
|
-
import { randomUUID as
|
|
1392
|
+
import { randomUUID as randomUUID5, createHash as createHash4 } from "node:crypto";
|
|
609
1393
|
var processOwnerId, currentSource, owned;
|
|
610
1394
|
var init_host_turns = __esm({
|
|
611
1395
|
"src/mem7/core/host-turns.ts"() {
|
|
612
1396
|
"use strict";
|
|
613
1397
|
init_scope();
|
|
614
|
-
processOwnerId =
|
|
1398
|
+
processOwnerId = randomUUID5();
|
|
615
1399
|
currentSource = `EXISTS (SELECT 1 FROM memory_sources s WHERE s.scope_id=memory_host_turns.scope_id
|
|
616
1400
|
AND s.source_id=memory_host_turns.source_id AND s.role='user' AND s.origin_class='host_user' AND s.interpretation_status<>'deleted'
|
|
617
1401
|
AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id AND newer.origin_key=s.origin_key
|
|
@@ -725,8 +1509,8 @@ var init_job_runner = __esm({
|
|
|
725
1509
|
});
|
|
726
1510
|
|
|
727
1511
|
// src/mem7/core/episode.ts
|
|
728
|
-
import { readFileSync as
|
|
729
|
-
import { join as
|
|
1512
|
+
import { readFileSync as readFileSync8 } from "node:fs";
|
|
1513
|
+
import { join as join8, dirname as dirname7 } from "node:path";
|
|
730
1514
|
import { fileURLToPath } from "node:url";
|
|
731
1515
|
var PROMPT;
|
|
732
1516
|
var init_episode = __esm({
|
|
@@ -734,7 +1518,7 @@ var init_episode = __esm({
|
|
|
734
1518
|
"use strict";
|
|
735
1519
|
init_prompt_render();
|
|
736
1520
|
init_job_runner();
|
|
737
|
-
PROMPT =
|
|
1521
|
+
PROMPT = readFileSync8(join8(dirname7(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
|
|
738
1522
|
}
|
|
739
1523
|
});
|
|
740
1524
|
|
|
@@ -767,11 +1551,82 @@ var init_types = __esm({
|
|
|
767
1551
|
}
|
|
768
1552
|
});
|
|
769
1553
|
|
|
1554
|
+
// src/memory/topics-history/dates.ts
|
|
1555
|
+
var init_dates = __esm({
|
|
1556
|
+
"src/memory/topics-history/dates.ts"() {
|
|
1557
|
+
"use strict";
|
|
1558
|
+
init_clock();
|
|
1559
|
+
}
|
|
1560
|
+
});
|
|
1561
|
+
|
|
1562
|
+
// src/mem7/core/tokenizer.ts
|
|
1563
|
+
import { Jieba } from "@node-rs/jieba";
|
|
1564
|
+
import { dict } from "@node-rs/jieba/dict.js";
|
|
1565
|
+
var init_tokenizer = __esm({
|
|
1566
|
+
"src/mem7/core/tokenizer.ts"() {
|
|
1567
|
+
"use strict";
|
|
1568
|
+
}
|
|
1569
|
+
});
|
|
1570
|
+
|
|
1571
|
+
// src/mem7/core/historical-recall.ts
|
|
1572
|
+
var init_historical_recall = __esm({
|
|
1573
|
+
"src/mem7/core/historical-recall.ts"() {
|
|
1574
|
+
"use strict";
|
|
1575
|
+
init_scope();
|
|
1576
|
+
init_read_guard();
|
|
1577
|
+
init_read_budget();
|
|
1578
|
+
}
|
|
1579
|
+
});
|
|
1580
|
+
|
|
1581
|
+
// src/memory/topics-history/cutoff.ts
|
|
1582
|
+
import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
|
|
1583
|
+
var init_cutoff = __esm({
|
|
1584
|
+
"src/memory/topics-history/cutoff.ts"() {
|
|
1585
|
+
"use strict";
|
|
1586
|
+
init_historical_recall();
|
|
1587
|
+
init_scope();
|
|
1588
|
+
init_clock();
|
|
1589
|
+
init_materials();
|
|
1590
|
+
init_dates();
|
|
1591
|
+
}
|
|
1592
|
+
});
|
|
1593
|
+
|
|
1594
|
+
// src/memory/topics-history/index.ts
|
|
1595
|
+
import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
|
|
1596
|
+
var init_topics_history = __esm({
|
|
1597
|
+
"src/memory/topics-history/index.ts"() {
|
|
1598
|
+
"use strict";
|
|
1599
|
+
init_materials();
|
|
1600
|
+
init_dates();
|
|
1601
|
+
init_tokenizer();
|
|
1602
|
+
init_cutoff();
|
|
1603
|
+
init_clock();
|
|
1604
|
+
init_runtime_replication();
|
|
1605
|
+
}
|
|
1606
|
+
});
|
|
1607
|
+
|
|
1608
|
+
// src/memory/memdir/memoryAge.ts
|
|
1609
|
+
var init_memoryAge = __esm({
|
|
1610
|
+
"src/memory/memdir/memoryAge.ts"() {
|
|
1611
|
+
"use strict";
|
|
1612
|
+
}
|
|
1613
|
+
});
|
|
1614
|
+
|
|
1615
|
+
// src/messages/attachments.ts
|
|
1616
|
+
var init_attachments = __esm({
|
|
1617
|
+
"src/messages/attachments.ts"() {
|
|
1618
|
+
"use strict";
|
|
1619
|
+
init_topics_history();
|
|
1620
|
+
init_memoryAge();
|
|
1621
|
+
}
|
|
1622
|
+
});
|
|
1623
|
+
|
|
770
1624
|
// src/compact/tokenEstimate.ts
|
|
771
1625
|
var init_tokenEstimate = __esm({
|
|
772
1626
|
"src/compact/tokenEstimate.ts"() {
|
|
773
1627
|
"use strict";
|
|
774
1628
|
init_types();
|
|
1629
|
+
init_attachments();
|
|
775
1630
|
}
|
|
776
1631
|
});
|
|
777
1632
|
|
|
@@ -900,6 +1755,13 @@ var init_migrations = __esm({
|
|
|
900
1755
|
}
|
|
901
1756
|
});
|
|
902
1757
|
|
|
1758
|
+
// src/mem7/core/snapshot-reads.ts
|
|
1759
|
+
var init_snapshot_reads = __esm({
|
|
1760
|
+
"src/mem7/core/snapshot-reads.ts"() {
|
|
1761
|
+
"use strict";
|
|
1762
|
+
}
|
|
1763
|
+
});
|
|
1764
|
+
|
|
903
1765
|
// src/mem7/core/state/basis-check.ts
|
|
904
1766
|
var init_basis_check = __esm({
|
|
905
1767
|
"src/mem7/core/state/basis-check.ts"() {
|
|
@@ -963,16 +1825,23 @@ var init_retire_graph_audits = __esm({
|
|
|
963
1825
|
});
|
|
964
1826
|
|
|
965
1827
|
// src/mem7/core/store.ts
|
|
966
|
-
import { DatabaseSync } from "node:sqlite";
|
|
1828
|
+
import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
|
|
967
1829
|
var STALE_ARTIFACT_FORCE_MS;
|
|
968
1830
|
var init_store = __esm({
|
|
969
1831
|
"src/mem7/core/store.ts"() {
|
|
970
1832
|
"use strict";
|
|
1833
|
+
init_runtime_lock();
|
|
1834
|
+
init_runtime_authority();
|
|
1835
|
+
init_sqlite_replication();
|
|
1836
|
+
init_mem7_replication();
|
|
1837
|
+
init_sqlite_autocommit();
|
|
1838
|
+
init_schema_migrations();
|
|
971
1839
|
init_vector_store();
|
|
972
1840
|
init_prompt_render();
|
|
973
1841
|
init_clock();
|
|
974
1842
|
init_migrations();
|
|
975
1843
|
init_source_store();
|
|
1844
|
+
init_snapshot_reads();
|
|
976
1845
|
init_entities();
|
|
977
1846
|
init_facts();
|
|
978
1847
|
init_change_feed();
|
|
@@ -997,15 +1866,6 @@ var init_store = __esm({
|
|
|
997
1866
|
}
|
|
998
1867
|
});
|
|
999
1868
|
|
|
1000
|
-
// src/mem7/core/tokenizer.ts
|
|
1001
|
-
import { Jieba } from "@node-rs/jieba";
|
|
1002
|
-
import { dict } from "@node-rs/jieba/dict.js";
|
|
1003
|
-
var init_tokenizer = __esm({
|
|
1004
|
-
"src/mem7/core/tokenizer.ts"() {
|
|
1005
|
-
"use strict";
|
|
1006
|
-
}
|
|
1007
|
-
});
|
|
1008
|
-
|
|
1009
1869
|
// src/mem7/core/filters.ts
|
|
1010
1870
|
var init_filters = __esm({
|
|
1011
1871
|
"src/mem7/core/filters.ts"() {
|
|
@@ -1015,17 +1875,17 @@ var init_filters = __esm({
|
|
|
1015
1875
|
});
|
|
1016
1876
|
|
|
1017
1877
|
// src/mem7/core/search/timing.ts
|
|
1018
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1878
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
1019
1879
|
var current;
|
|
1020
1880
|
var init_timing = __esm({
|
|
1021
1881
|
"src/mem7/core/search/timing.ts"() {
|
|
1022
1882
|
"use strict";
|
|
1023
|
-
current = new
|
|
1883
|
+
current = new AsyncLocalStorage2();
|
|
1024
1884
|
}
|
|
1025
1885
|
});
|
|
1026
1886
|
|
|
1027
1887
|
// src/mem7/core/vector-store.ts
|
|
1028
|
-
import { DatabaseSync as
|
|
1888
|
+
import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
|
|
1029
1889
|
function lanceSpecifierFor(platform, arch) {
|
|
1030
1890
|
return platform === "darwin" && arch === "x64" ? "@engine7/lancedb-intel" : "@lancedb/lancedb";
|
|
1031
1891
|
}
|
|
@@ -1040,6 +1900,7 @@ var init_vector_store = __esm({
|
|
|
1040
1900
|
init_dependencies();
|
|
1041
1901
|
init_read_guard();
|
|
1042
1902
|
init_timing();
|
|
1903
|
+
init_runtime_authority();
|
|
1043
1904
|
isIntelMac = process.platform === "darwin" && process.arch === "x64";
|
|
1044
1905
|
bootAt = Date.now();
|
|
1045
1906
|
}
|
|
@@ -1050,15 +1911,15 @@ var validate_legacy_backup_exports = {};
|
|
|
1050
1911
|
__export(validate_legacy_backup_exports, {
|
|
1051
1912
|
validateLegacyTopicsBackup: () => validateLegacyTopicsBackup
|
|
1052
1913
|
});
|
|
1053
|
-
import { DatabaseSync as
|
|
1914
|
+
import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
|
|
1054
1915
|
import { open, readdir } from "node:fs/promises";
|
|
1055
|
-
import { basename as
|
|
1056
|
-
async function validateLegacyTopicsBackup(state,
|
|
1916
|
+
import { basename as basename5, join as join9 } from "node:path";
|
|
1917
|
+
async function validateLegacyTopicsBackup(state, directory2, history) {
|
|
1057
1918
|
unlinked(state);
|
|
1058
|
-
unlinked(
|
|
1919
|
+
unlinked(directory2);
|
|
1059
1920
|
unlinked(history);
|
|
1060
|
-
const snapshot = new
|
|
1061
|
-
const live = new
|
|
1921
|
+
const snapshot = new DatabaseSync8(unlinked(join9(directory2, "mem7.db")), { readOnly: true });
|
|
1922
|
+
const live = new DatabaseSync8(unlinked(join9(state, "mem7", "index", "mem7.db")), { readOnly: true });
|
|
1062
1923
|
try {
|
|
1063
1924
|
snapshot.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=0");
|
|
1064
1925
|
const schema = readSchemaVersion(snapshot);
|
|
@@ -1067,14 +1928,14 @@ async function validateLegacyTopicsBackup(state, directory, history) {
|
|
|
1067
1928
|
let bound = false;
|
|
1068
1929
|
for (const scope of scopes) {
|
|
1069
1930
|
if (!live.prepare("SELECT 1 FROM memory_scopes WHERE scope_id=? AND owner_id=? AND app_id=? AND project_id=?").get(scope.scope_id, scope.owner_id, scope.app_id, scope.project_id)) throw new Error("LEGACY_BACKUP_SCOPE_MISMATCH");
|
|
1070
|
-
if (
|
|
1931
|
+
if (basename5(history) === digest(canonical({ ownerId: scope.owner_id, appId: scope.app_id, projectId: scope.project_id }))) bound = true;
|
|
1071
1932
|
}
|
|
1072
1933
|
if (!bound) throw new Error("LEGACY_BACKUP_HISTORY_MISMATCH");
|
|
1073
1934
|
for (const row of snapshot.prepare("SELECT DISTINCT path FROM memory_artifact_publications WHERE medium='markdown' AND path IS NOT NULL").all()) {
|
|
1074
1935
|
const rel = String(row.path);
|
|
1075
1936
|
if (!safeRelative(rel)) throw new Error("LEGACY_BACKUP_PUBLICATION_PATH_INVALID");
|
|
1076
1937
|
if (!rel.startsWith("users/")) continue;
|
|
1077
|
-
const file = await open(unlinked(
|
|
1938
|
+
const file = await open(unlinked(join9(directory2, rel)), "r");
|
|
1078
1939
|
await file.close();
|
|
1079
1940
|
}
|
|
1080
1941
|
} finally {
|
|
@@ -1083,10 +1944,10 @@ async function validateLegacyTopicsBackup(state, directory, history) {
|
|
|
1083
1944
|
}
|
|
1084
1945
|
const readTree = async (root) => {
|
|
1085
1946
|
for (const entry of await readdir(unlinked(root), { withFileTypes: true })) {
|
|
1086
|
-
const
|
|
1087
|
-
if (entry.isDirectory()) await readTree(
|
|
1947
|
+
const path2 = unlinked(join9(root, entry.name));
|
|
1948
|
+
if (entry.isDirectory()) await readTree(path2);
|
|
1088
1949
|
else if (entry.isFile()) {
|
|
1089
|
-
const file = await open(
|
|
1950
|
+
const file = await open(path2, "r");
|
|
1090
1951
|
try {
|
|
1091
1952
|
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
1092
1953
|
while ((await file.read(buffer)).bytesRead > 0) {
|
|
@@ -1097,10 +1958,10 @@ async function validateLegacyTopicsBackup(state, directory, history) {
|
|
|
1097
1958
|
} else throw new Error("LEGACY_BACKUP_UNSUPPORTED_FILE");
|
|
1098
1959
|
}
|
|
1099
1960
|
};
|
|
1100
|
-
await readTree(
|
|
1101
|
-
await readTree(
|
|
1961
|
+
await readTree(join9(directory2, "users"));
|
|
1962
|
+
await readTree(join9(directory2, "lancedb"));
|
|
1102
1963
|
const loaded = await import(lanceSpecifierFor(process.platform, process.arch)), lance = loaded.connect ? loaded : loaded.default;
|
|
1103
|
-
const connection = await lance.connect(
|
|
1964
|
+
const connection = await lance.connect(join9(directory2, "lancedb"));
|
|
1104
1965
|
try {
|
|
1105
1966
|
for (const name of await connection.tableNames()) {
|
|
1106
1967
|
const table = await connection.openTable(name);
|
|
@@ -1129,35 +1990,35 @@ var validate_import_live_exports = {};
|
|
|
1129
1990
|
__export(validate_import_live_exports, {
|
|
1130
1991
|
validateCompletedTopicsImport: () => validateCompletedTopicsImport
|
|
1131
1992
|
});
|
|
1132
|
-
import { DatabaseSync as
|
|
1133
|
-
import { existsSync as
|
|
1993
|
+
import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
|
|
1994
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
1134
1995
|
import { open as open2, readFile, readdir as readdir2 } from "node:fs/promises";
|
|
1135
|
-
import { basename as
|
|
1996
|
+
import { basename as basename6, join as join10 } from "node:path";
|
|
1136
1997
|
async function validateCompletedTopicsImport(state, history) {
|
|
1137
|
-
const root = unlinked(
|
|
1138
|
-
if (marker.report?.failed !== 0 || !Number.isFinite(Date.parse(marker.completedAt)) || !Array.isArray(marker.hashes) || marker.hashes.some((
|
|
1998
|
+
const root = unlinked(join10(state, "mem7")), marker = readJson(join10(history, "topics-import.json"));
|
|
1999
|
+
if (marker.report?.failed !== 0 || !Number.isFinite(Date.parse(marker.completedAt)) || !Array.isArray(marker.hashes) || marker.hashes.some((hash2) => typeof hash2 !== "string" || !/^[a-f0-9]{64}$/.test(hash2)))
|
|
1139
2000
|
throw new Error("TOPICS_IMPORT_COMPLETION_INVALID");
|
|
1140
2001
|
if (!marker.hashes.length && (marker.report.imported > 0 || marker.report.skipped > 0)) throw new Error("TOPICS_IMPORT_COMPLETION_INVALID");
|
|
1141
|
-
const db = new
|
|
2002
|
+
const db = new DatabaseSync9(unlinked(join10(root, "index", "mem7.db")), { readOnly: true });
|
|
1142
2003
|
let owner;
|
|
1143
2004
|
try {
|
|
1144
2005
|
db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=0");
|
|
1145
2006
|
if (readSchemaVersion(db)?.component !== "mem7" || db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || db.prepare("PRAGMA foreign_key_check").all().length) throw new Error("TOPICS_IMPORT_LIVE_DATABASE_INVALID");
|
|
1146
|
-
const scope = db.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes").all().find((row) =>
|
|
2007
|
+
const scope = db.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes").all().find((row) => basename6(history) === digest(canonical({ ownerId: row.owner_id, appId: row.app_id, projectId: row.project_id })));
|
|
1147
2008
|
if (!scope) throw new Error("TOPICS_IMPORT_LIVE_SCOPE_MISMATCH");
|
|
1148
2009
|
owner = String(scope.owner_id);
|
|
1149
2010
|
for (const row of db.prepare("SELECT DISTINCT path FROM memory_artifact_publications WHERE medium='markdown' AND path IS NOT NULL").all()) {
|
|
1150
2011
|
if (!safeRelative(row.path)) throw new Error("TOPICS_IMPORT_LIVE_PUBLICATION_PATH_INVALID");
|
|
1151
|
-
const file = await open2(unlinked(
|
|
2012
|
+
const file = await open2(unlinked(join10(root, row.path)), "r");
|
|
1152
2013
|
await file.close();
|
|
1153
2014
|
}
|
|
1154
2015
|
} finally {
|
|
1155
2016
|
db.close();
|
|
1156
2017
|
}
|
|
1157
2018
|
const prose = /* @__PURE__ */ new Map(), idsByHash = /* @__PURE__ */ new Map();
|
|
1158
|
-
const scan = async (
|
|
1159
|
-
for (const entry of await readdir2(unlinked(
|
|
1160
|
-
const file = unlinked(
|
|
2019
|
+
const scan = async (path3) => {
|
|
2020
|
+
for (const entry of await readdir2(unlinked(path3), { withFileTypes: true })) {
|
|
2021
|
+
const file = unlinked(join10(path3, entry.name));
|
|
1161
2022
|
if (entry.isDirectory()) await scan(file);
|
|
1162
2023
|
else if (entry.isFile() && entry.name.endsWith(".md")) {
|
|
1163
2024
|
const text = await readFile(file, "utf8");
|
|
@@ -1169,19 +2030,19 @@ async function validateCompletedTopicsImport(state, history) {
|
|
|
1169
2030
|
const content = match[2].slice(start + "\n### Content\n".length).replace(/\r?\n$/, "");
|
|
1170
2031
|
prose.set(match[1], content);
|
|
1171
2032
|
const body = content.startsWith("[\u65E7 topics\uFF5C") ? content.slice(content.indexOf("\n\n") + 2) : content;
|
|
1172
|
-
for (const
|
|
1173
|
-
const ids = idsByHash.get(
|
|
2033
|
+
for (const hash2 of [digest(body), digest(body.trim())]) {
|
|
2034
|
+
const ids = idsByHash.get(hash2) ?? /* @__PURE__ */ new Set();
|
|
1174
2035
|
ids.add(match[1]);
|
|
1175
|
-
idsByHash.set(
|
|
2036
|
+
idsByHash.set(hash2, ids);
|
|
1176
2037
|
}
|
|
1177
2038
|
}
|
|
1178
2039
|
}
|
|
1179
2040
|
}
|
|
1180
2041
|
};
|
|
1181
|
-
if (
|
|
1182
|
-
const cachePath =
|
|
1183
|
-
if (
|
|
1184
|
-
const cache = new
|
|
2042
|
+
if (existsSync4(join10(root, "users"))) await scan(join10(root, "users"));
|
|
2043
|
+
const cachePath = join10(history, "vectors.db");
|
|
2044
|
+
if (existsSync4(cachePath)) {
|
|
2045
|
+
const cache = new DatabaseSync9(unlinked(cachePath), { readOnly: true });
|
|
1185
2046
|
try {
|
|
1186
2047
|
if (cache.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='hash_aliases'").get())
|
|
1187
2048
|
for (const row of cache.prepare("SELECT old_hash,hash FROM hash_aliases").all()) {
|
|
@@ -1193,9 +2054,9 @@ async function validateCompletedTopicsImport(state, history) {
|
|
|
1193
2054
|
}
|
|
1194
2055
|
}
|
|
1195
2056
|
const loaded = await import(lanceSpecifierFor(process.platform, process.arch)), lance = loaded.connect ? loaded : loaded.default;
|
|
1196
|
-
const
|
|
1197
|
-
if (!
|
|
1198
|
-
const connection = await lance.connect(
|
|
2057
|
+
const path2 = unlinked(join10(root, "index", "lancedb"));
|
|
2058
|
+
if (!existsSync4(path2)) throw new Error("TOPICS_IMPORT_LIVE_VECTORS_MISSING");
|
|
2059
|
+
const connection = await lance.connect(path2), vectorIds = /* @__PURE__ */ new Set();
|
|
1199
2060
|
try {
|
|
1200
2061
|
for (const name of await connection.tableNames()) {
|
|
1201
2062
|
const table = await connection.openTable(name);
|
|
@@ -1212,8 +2073,8 @@ async function validateCompletedTopicsImport(state, history) {
|
|
|
1212
2073
|
table.close();
|
|
1213
2074
|
}
|
|
1214
2075
|
}
|
|
1215
|
-
for (const
|
|
1216
|
-
if (![...idsByHash.get(
|
|
2076
|
+
for (const hash2 of marker.hashes)
|
|
2077
|
+
if (![...idsByHash.get(hash2) ?? []].some((id) => vectorIds.has(id))) throw new Error("TOPICS_IMPORT_LIVE_HISTORY_MISSING");
|
|
1217
2078
|
} finally {
|
|
1218
2079
|
connection.close();
|
|
1219
2080
|
}
|
|
@@ -1228,43 +2089,207 @@ var init_validate_import_live = __esm({
|
|
|
1228
2089
|
});
|
|
1229
2090
|
|
|
1230
2091
|
// src/mem7/sqlite-maintenance-worker.ts
|
|
1231
|
-
|
|
1232
|
-
import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
|
|
2092
|
+
init_runtime_lock();
|
|
1233
2093
|
import { statSync, statfsSync } from "node:fs";
|
|
1234
|
-
import { dirname as
|
|
2094
|
+
import { dirname as dirname8, join as join11, resolve as resolve8 } from "node:path";
|
|
1235
2095
|
import { setImmediate as yieldToIntake } from "node:timers/promises";
|
|
1236
2096
|
import { Worker } from "node:worker_threads";
|
|
1237
|
-
|
|
1238
|
-
|
|
2097
|
+
|
|
2098
|
+
// src/continuity/sqlite-physical-maintenance.ts
|
|
2099
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
2100
|
+
import { lstatSync as lstatSync7 } from "node:fs";
|
|
2101
|
+
import { resolve as resolve6 } from "node:path";
|
|
2102
|
+
|
|
2103
|
+
// src/continuity/sqlite-store-location.ts
|
|
2104
|
+
init_mem7_replication();
|
|
2105
|
+
init_runtime_replication();
|
|
2106
|
+
import { basename as basename3, dirname as dirname5, resolve as resolve4 } from "node:path";
|
|
2107
|
+
function sqliteStoreLocation(file) {
|
|
2108
|
+
const absolute = resolve4(file), parent = dirname5(absolute), name = basename3(absolute);
|
|
2109
|
+
if (name === "mem7.db" && basename3(parent) === "index" && basename3(dirname5(parent)) === "mem7")
|
|
2110
|
+
return { stateDir: dirname5(dirname5(parent)), component: "mem7" };
|
|
2111
|
+
let stateDir, component;
|
|
2112
|
+
if (name === "calendar.db" && basename3(parent) === ".calendar") {
|
|
2113
|
+
stateDir = dirname5(parent);
|
|
2114
|
+
component = "calendar";
|
|
2115
|
+
} else if (name === "proactive.db" && basename3(parent) === ".proactive") {
|
|
2116
|
+
stateDir = dirname5(parent);
|
|
2117
|
+
component = "proactive";
|
|
2118
|
+
} else if (name === "session-events.db" && basename3(parent) === ".continuity") {
|
|
2119
|
+
stateDir = dirname5(parent);
|
|
2120
|
+
component = "session-events";
|
|
2121
|
+
} else if (name === "memory.db" && basename3(parent) === "memory" && basename3(dirname5(dirname5(parent))) === "agents") {
|
|
2122
|
+
stateDir = dirname5(dirname5(dirname5(parent)));
|
|
2123
|
+
component = "legacy-memory";
|
|
2124
|
+
} else if (name === "vectors.db" && basename3(dirname5(parent)) === "topics-history") {
|
|
2125
|
+
stateDir = dirname5(dirname5(parent));
|
|
2126
|
+
component = "topics-vectors";
|
|
2127
|
+
} else return null;
|
|
2128
|
+
return { stateDir, ...runtimeReplicationLocation(stateDir, component, absolute) };
|
|
2129
|
+
}
|
|
2130
|
+
function readSQLiteStoreRegistration(place) {
|
|
2131
|
+
return place.component === "mem7" ? readMem7ReplicationRegistration(place.stateDir) : readRuntimeReplicationRegistration(place.stateDir, place.component, place.key);
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
// src/continuity/sqlite-physical-maintenance.ts
|
|
2135
|
+
init_runtime_replication();
|
|
2136
|
+
init_sqlite_replication();
|
|
2137
|
+
|
|
2138
|
+
// src/continuity/legacy-memory-replication.ts
|
|
2139
|
+
import { createRequire as createRequire3 } from "node:module";
|
|
2140
|
+
init_schema_migrations();
|
|
2141
|
+
|
|
2142
|
+
// src/memory/host/sqlite-vec-platform-variant.ts
|
|
2143
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
2144
|
+
var PLATFORM_VARIANTS = {
|
|
2145
|
+
"linux-x64": { pkg: "sqlite-vec-linux-x64", file: "vec0.so" },
|
|
2146
|
+
"linux-arm64": { pkg: "sqlite-vec-linux-arm64", file: "vec0.so" },
|
|
2147
|
+
"darwin-x64": { pkg: "sqlite-vec-darwin-x64", file: "vec0.dylib" },
|
|
2148
|
+
"darwin-arm64": { pkg: "sqlite-vec-darwin-arm64", file: "vec0.dylib" },
|
|
2149
|
+
"win32-x64": { pkg: "sqlite-vec-windows-x64", file: "vec0.dll" }
|
|
2150
|
+
};
|
|
2151
|
+
function resolveSqliteVecPlatformVariant() {
|
|
2152
|
+
const entry = PLATFORM_VARIANTS[`${process.platform}-${process.arch}`];
|
|
2153
|
+
if (!entry) {
|
|
2154
|
+
return void 0;
|
|
2155
|
+
}
|
|
2156
|
+
try {
|
|
2157
|
+
const require_ = createRequire2(import.meta.url);
|
|
2158
|
+
const extensionPath = require_.resolve(`${entry.pkg}/${entry.file}`);
|
|
2159
|
+
return { pkg: entry.pkg, extensionPath };
|
|
2160
|
+
} catch {
|
|
2161
|
+
return void 0;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
// src/continuity/legacy-memory-replication.ts
|
|
2166
|
+
init_runtime_replication();
|
|
2167
|
+
init_sqlite_replication();
|
|
2168
|
+
var require2 = createRequire3(import.meta.url);
|
|
2169
|
+
function loadLegacySQLiteVectorExtension(db, extensionPath) {
|
|
2170
|
+
db.enableLoadExtension(true);
|
|
2171
|
+
if (extensionPath) {
|
|
2172
|
+
db.loadExtension(extensionPath);
|
|
2173
|
+
return;
|
|
2174
|
+
}
|
|
2175
|
+
let module;
|
|
2176
|
+
try {
|
|
2177
|
+
module = require2("sqlite-vec");
|
|
2178
|
+
} catch (error) {
|
|
2179
|
+
if (error.code !== "MODULE_NOT_FOUND") throw error;
|
|
2180
|
+
const variant = resolveSqliteVecPlatformVariant();
|
|
2181
|
+
if (!variant) throw new Error("REPLICATION_LEGACY_VECTOR_MODULE_REQUIRED", { cause: error });
|
|
2182
|
+
db.loadExtension(variant.extensionPath);
|
|
2183
|
+
return;
|
|
2184
|
+
}
|
|
2185
|
+
module.load(db);
|
|
2186
|
+
}
|
|
2187
|
+
|
|
2188
|
+
// src/continuity/sqlite-physical-maintenance.ts
|
|
2189
|
+
init_runtime_lock();
|
|
2190
|
+
init_schema_migrations();
|
|
2191
|
+
|
|
2192
|
+
// src/continuity/inventory.ts
|
|
2193
|
+
import { isAbsolute, join as join6, relative, resolve as resolve5, sep } from "node:path";
|
|
2194
|
+
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(" "));
|
|
2195
|
+
function isWithin(root, candidate) {
|
|
2196
|
+
const rel = relative(resolve5(root), resolve5(candidate));
|
|
2197
|
+
return !rel || !rel.startsWith(".." + sep) && rel !== ".." && !isAbsolute(rel);
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
// src/continuity/sqlite-physical-maintenance.ts
|
|
2201
|
+
function openPhysicalMaintenanceDatabase(file, stateDir) {
|
|
2202
|
+
const absolute = resolve6(file), place = sqliteStoreLocation(absolute);
|
|
2203
|
+
const registration = place ? readSQLiteStoreRegistration(place) : null;
|
|
2204
|
+
if (stateDir && !isWithin(stateDir, absolute)) throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED");
|
|
2205
|
+
const runtimeRoots = [.../* @__PURE__ */ new Set([...stateDir ? [resolve6(stateDir)] : [], ...place ? [place.stateDir] : []])].sort();
|
|
2206
|
+
for (const root of runtimeRoots) assertStateDirUsable(root);
|
|
2207
|
+
try {
|
|
2208
|
+
const info = lstatSync7(absolute);
|
|
2209
|
+
if (!info.isFile() || info.isSymbolicLink()) throw new Error();
|
|
2210
|
+
} catch (error) {
|
|
2211
|
+
throw new Error("REPLICATION_RECOVERY_REQUIRED", { cause: error });
|
|
2212
|
+
}
|
|
2213
|
+
checkRuntimeReplicationFile(absolute, registration);
|
|
2214
|
+
const releases2 = [];
|
|
2215
|
+
const release = () => {
|
|
2216
|
+
while (releases2.length) releases2.pop()();
|
|
2217
|
+
};
|
|
2218
|
+
let db;
|
|
2219
|
+
try {
|
|
2220
|
+
for (const root of runtimeRoots) releases2.push(registerRuntimeWriter(root, "sqlite-physical-maintenance"));
|
|
2221
|
+
db = new DatabaseSync3(absolute, { allowExtension: place?.component === "legacy-memory" });
|
|
2222
|
+
} catch (error) {
|
|
2223
|
+
release();
|
|
2224
|
+
throw error;
|
|
2225
|
+
}
|
|
2226
|
+
try {
|
|
2227
|
+
if (place?.component === "legacy-memory") loadLegacySQLiteVectorExtension(db);
|
|
2228
|
+
const enrolled = readSQLiteReplicationSource(db), schema = readSchemaVersion(db);
|
|
2229
|
+
if (registration && (!enrolled || JSON.stringify(enrolled) !== JSON.stringify(registration))) throw new Error("REPLICATION_RECOVERY_REQUIRED");
|
|
2230
|
+
if (enrolled && !registration) throw new Error("REPLICATION_REGISTRATION_REQUIRED");
|
|
2231
|
+
if (registration && (schema?.component !== place.component || sqliteReplicationSchemaHash(db) !== registration.schemaHash)) throw new Error("REPLICATION_SCHEMA_MISMATCH");
|
|
2232
|
+
if (schema) authorizeMemoryWriter(db, schema.version);
|
|
2233
|
+
if (enrolled) db.function("engine7_replication_capture_active", () => 0);
|
|
2234
|
+
const execute = db.exec.bind(db), prepare = db.prepare.bind(db), close = db.close.bind(db);
|
|
2235
|
+
db.exec = (sql) => {
|
|
2236
|
+
const text = sql.trim().replace(/;$/, "").trim();
|
|
2237
|
+
if (!/^PRAGMA busy_timeout\s*=\s*\d+$/i.test(text) && !/^PRAGMA optimize$/i.test(text) && !/^PRAGMA auto_vacuum\s*=\s*INCREMENTAL\s*;\s*VACUUM$/i.test(text)) throw new Error("REPLICATION_PHYSICAL_SQL_REQUIRED");
|
|
2238
|
+
execute(sql);
|
|
2239
|
+
};
|
|
2240
|
+
db.prepare = (sql) => {
|
|
2241
|
+
if (!/^\s*(?:SELECT\b|PRAGMA\s+(?:auto_vacuum|wal_checkpoint|page_size|page_count|freelist_count|incremental_vacuum)\b)/i.test(sql))
|
|
2242
|
+
throw new Error("REPLICATION_PHYSICAL_SQL_REQUIRED");
|
|
2243
|
+
return prepare(sql);
|
|
2244
|
+
};
|
|
2245
|
+
db.close = () => {
|
|
2246
|
+
try {
|
|
2247
|
+
close();
|
|
2248
|
+
} finally {
|
|
2249
|
+
release();
|
|
2250
|
+
}
|
|
2251
|
+
};
|
|
2252
|
+
return db;
|
|
2253
|
+
} catch (error) {
|
|
2254
|
+
try {
|
|
2255
|
+
db.close();
|
|
2256
|
+
} finally {
|
|
2257
|
+
release();
|
|
2258
|
+
}
|
|
2259
|
+
throw error;
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
// src/mem7/sqlite-maintenance-worker.ts
|
|
2264
|
+
function intakePendingForDatabase(path2) {
|
|
2265
|
+
const spool = join11(dirname8(dirname8(path2)), "spool");
|
|
1239
2266
|
return ["intake.jsonl", "intake.processing.jsonl"].some((name) => {
|
|
1240
2267
|
try {
|
|
1241
|
-
return statSync(
|
|
2268
|
+
return statSync(join11(spool, name)).size > 0;
|
|
1242
2269
|
} catch (e) {
|
|
1243
2270
|
if (e.code !== "ENOENT") throw e;
|
|
1244
2271
|
return false;
|
|
1245
2272
|
}
|
|
1246
2273
|
});
|
|
1247
2274
|
}
|
|
1248
|
-
var bytes = (
|
|
2275
|
+
var bytes = (path2) => {
|
|
1249
2276
|
try {
|
|
1250
|
-
return statSync(
|
|
2277
|
+
return statSync(path2).size;
|
|
1251
2278
|
} catch (e) {
|
|
1252
2279
|
if (e.code !== "ENOENT") throw e;
|
|
1253
2280
|
return 0;
|
|
1254
2281
|
}
|
|
1255
2282
|
};
|
|
1256
|
-
async function runSqlitePhysicalMaintenance(
|
|
2283
|
+
async function runSqlitePhysicalMaintenance(path2, options = {}) {
|
|
1257
2284
|
const minimum = options.minFreeBytes ?? 32 * 1024 * 1024, ratio = options.minFreeRatio ?? 0.05;
|
|
1258
2285
|
if (!Number.isFinite(minimum) || minimum < 0 || !Number.isFinite(ratio) || ratio < 0 || ratio > 1) throw new Error("INVALID_SQLITE_RETENTION_THRESHOLD");
|
|
1259
|
-
const before = bytes(
|
|
1260
|
-
const allowed = () => options.shouldRun?.() !== false && !intakePendingForDatabase(
|
|
1261
|
-
const db =
|
|
2286
|
+
const before = bytes(path2) + bytes(path2 + "-wal"), started = performance.now();
|
|
2287
|
+
const allowed = () => options.shouldRun?.() !== false && !intakePendingForDatabase(path2);
|
|
2288
|
+
const db = openPhysicalMaintenanceDatabase(path2, options.stateDir);
|
|
1262
2289
|
let mode = "bootstrap";
|
|
1263
|
-
const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(
|
|
2290
|
+
const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(path2) - bytes(path2 + "-wal")) });
|
|
1264
2291
|
try {
|
|
1265
2292
|
db.exec("PRAGMA busy_timeout=0");
|
|
1266
|
-
const schema = readSchemaVersion(db);
|
|
1267
|
-
if (schema) authorizeMemoryWriter(db, schema.version);
|
|
1268
2293
|
mode = Number(db.prepare("PRAGMA auto_vacuum").get().auto_vacuum) === 2 ? "incremental" : "bootstrap";
|
|
1269
2294
|
if (!allowed()) return report("deferred");
|
|
1270
2295
|
const checkpoint = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
|
|
@@ -1272,10 +2297,10 @@ async function runSqlitePhysicalMaintenance(path, options = {}) {
|
|
|
1272
2297
|
const pageSize = Number(db.prepare("PRAGMA page_size").get().page_size);
|
|
1273
2298
|
const pages = Number(db.prepare("PRAGMA page_count").get().page_count);
|
|
1274
2299
|
const free = Number(db.prepare("PRAGMA freelist_count").get().freelist_count);
|
|
1275
|
-
const oversized = bytes(
|
|
2300
|
+
const oversized = bytes(path2) > pages * pageSize + 1024 * 1024;
|
|
1276
2301
|
if (!oversized && (free * pageSize < minimum || free / Math.max(1, pages) < ratio)) return report("idle");
|
|
1277
2302
|
if (mode === "bootstrap" || oversized) {
|
|
1278
|
-
const disk = statfsSync(
|
|
2303
|
+
const disk = statfsSync(dirname8(path2));
|
|
1279
2304
|
if (disk.bavail * disk.bsize < (pages - free) * pageSize * 2 + 64 * 1024 * 1024) return report("deferred");
|
|
1280
2305
|
if (!allowed()) return report("deferred");
|
|
1281
2306
|
options.onPhase?.("vacuum");
|
|
@@ -1294,7 +2319,7 @@ async function runSqlitePhysicalMaintenance(path, options = {}) {
|
|
|
1294
2319
|
}
|
|
1295
2320
|
const finalCheckpoint = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
|
|
1296
2321
|
const finalPages = Number(db.prepare("PRAGMA page_count").get().page_count);
|
|
1297
|
-
if (finalCheckpoint.busy || bytes(
|
|
2322
|
+
if (finalCheckpoint.busy || bytes(path2) > finalPages * pageSize + 1024 * 1024) return report("deferred");
|
|
1298
2323
|
return report("complete");
|
|
1299
2324
|
} catch (error) {
|
|
1300
2325
|
if (/database is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error))) return report("deferred");
|
|
@@ -1303,10 +2328,27 @@ async function runSqlitePhysicalMaintenance(path, options = {}) {
|
|
|
1303
2328
|
db.close();
|
|
1304
2329
|
}
|
|
1305
2330
|
}
|
|
2331
|
+
if (process.argv.includes("--sqlite-checkpoint")) {
|
|
2332
|
+
const flag = process.argv.indexOf("--sqlite-checkpoint");
|
|
2333
|
+
const path2 = process.argv[flag + 1], stateDir = process.argv[flag + 2];
|
|
2334
|
+
registerRuntimeWriter(stateDir, "sqlite-checkpoint");
|
|
2335
|
+
const db = openPhysicalMaintenanceDatabase(path2, stateDir);
|
|
2336
|
+
try {
|
|
2337
|
+
db.exec("PRAGMA busy_timeout=15000");
|
|
2338
|
+
console.log("wal checkpoint " + JSON.stringify(db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()));
|
|
2339
|
+
const started = Date.now();
|
|
2340
|
+
db.exec("PRAGMA optimize");
|
|
2341
|
+
console.log("pragma optimize " + (Date.now() - started) + "ms");
|
|
2342
|
+
} finally {
|
|
2343
|
+
db.close();
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
1306
2346
|
if (process.argv.includes("--sqlite-maintenance")) {
|
|
1307
|
-
const flag = process.argv.indexOf("--sqlite-maintenance"),
|
|
2347
|
+
const flag = process.argv.indexOf("--sqlite-maintenance"), path2 = resolve8(process.argv[flag + 1] ?? "");
|
|
1308
2348
|
if (!process.argv[flag + 1]) throw new Error("SQLITE_MAINTENANCE_PATH_REQUIRED");
|
|
1309
2349
|
const config = process.argv[flag + 2] ? JSON.parse(process.argv[flag + 2]) : {};
|
|
2350
|
+
if (!config.stateDir) throw new Error("SQLITE_MAINTENANCE_STATE_DIR_REQUIRED");
|
|
2351
|
+
registerRuntimeWriter(config.stateDir, "sqlite-maintenance");
|
|
1310
2352
|
const watchdog = new Worker(`
|
|
1311
2353
|
const { workerData } = require('node:worker_threads')
|
|
1312
2354
|
const { statSync } = require('node:fs')
|
|
@@ -1322,9 +2364,9 @@ if (process.argv.includes("--sqlite-maintenance")) {
|
|
|
1322
2364
|
}
|
|
1323
2365
|
if (cancel) process.kill(process.pid, 'SIGTERM')
|
|
1324
2366
|
}, 100)
|
|
1325
|
-
`, { eval: true, workerData: { path, ownerPid: process.connected ? process.ppid : null } });
|
|
2367
|
+
`, { eval: true, workerData: { path: path2, ownerPid: process.connected ? process.ppid : null } });
|
|
1326
2368
|
try {
|
|
1327
|
-
console.log(JSON.stringify(await runSqlitePhysicalMaintenance(
|
|
2369
|
+
console.log(JSON.stringify(await runSqlitePhysicalMaintenance(path2, {
|
|
1328
2370
|
...config,
|
|
1329
2371
|
onPhase: (phase) => {
|
|
1330
2372
|
if (process.connected) process.send?.({ type: "sqliteMaintenancePhase", phase });
|