@verax-ai/body 0.6.1 → 0.8.0

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.
@@ -0,0 +1,917 @@
1
+ import { createHash, createPrivateKey, createPublicKey, randomBytes, sign, verify } from "node:crypto";
2
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readSync, readdirSync, readFileSync, renameSync, statSync, writeSync, } from "node:fs";
3
+ import { chmod, mkdir, open, rename, stat, unlink } from "node:fs/promises";
4
+ import { dirname, join, resolve, sep } from "node:path";
5
+ import { canonical } from "@cedulon/core";
6
+ import { canonicalizeDirPath, resolveHeadDir } from "./keys.js";
7
+ class UncertainAppendError extends Error {
8
+ constructor() {
9
+ super("memory-append-uncertain");
10
+ this.name = "UncertainAppendError";
11
+ }
12
+ }
13
+ export const MEMORY_COMMITS_FILE = "memory-commits.jsonl";
14
+ export const MEMORY_PURPOSE = "verax.memory.v2";
15
+ export const MEMORY_HASH_SCHEMA = 2;
16
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
17
+ const OBJECT_KEYS = new Set([
18
+ "id",
19
+ "revision",
20
+ "tenantKey",
21
+ "body",
22
+ "source",
23
+ "validFromMs",
24
+ "validUntilMs",
25
+ "versionHash",
26
+ ]);
27
+ const COMMIT_PAYLOAD_KEYS = new Set([
28
+ "v",
29
+ "seq",
30
+ "tenantKey",
31
+ "id",
32
+ "revision",
33
+ "versionHash",
34
+ "objectPath",
35
+ "putRef",
36
+ "prevCommitHash",
37
+ "ts",
38
+ ]);
39
+ const LINE_KEYS = new Set(["payload", "sig"]);
40
+ const HEAD_PAYLOAD_KEYS = new Set(["v", "stateDirHash", "seq", "lastHash", "ts"]);
41
+ const stores = new Map();
42
+ const lockChains = new Map();
43
+ function withLock(key, fn) {
44
+ const previous = lockChains.get(key) ?? Promise.resolve();
45
+ const run = previous.then(fn, fn);
46
+ const settled = run.then(() => undefined, () => undefined);
47
+ lockChains.set(key, settled);
48
+ void settled.then(() => {
49
+ if (lockChains.get(key) === settled)
50
+ lockChains.delete(key);
51
+ });
52
+ return run;
53
+ }
54
+ function tenantMemoryLockKey(stateDir, tenantKey) {
55
+ return `memory-quota:${resolve(stateDir, "tenants", tenantKey, "memory")}`;
56
+ }
57
+ function sha256Canonical(value) {
58
+ return createHash("sha256").update(canonical(value), "utf8").digest("hex");
59
+ }
60
+ function storeKey(stateDir) {
61
+ return resolve(stateDir);
62
+ }
63
+ export function memoryVersionHash(fields) {
64
+ return sha256Canonical({
65
+ purpose: MEMORY_PURPOSE,
66
+ hashSchema: MEMORY_HASH_SCHEMA,
67
+ tenantKey: fields.tenantKey,
68
+ id: fields.id,
69
+ revision: fields.revision,
70
+ body: fields.body,
71
+ source: fields.source,
72
+ validFromMs: fields.validFromMs,
73
+ validUntilMs: fields.validUntilMs,
74
+ });
75
+ }
76
+ export function memoryStateDirHash(stateDir) {
77
+ return createHash("sha256").update(canonicalizeDirPath(stateDir), "utf8").digest("hex");
78
+ }
79
+ export function memoryHeadPath(stateDir, headDir) {
80
+ return join(headDir, `memory-head-${memoryStateDirHash(stateDir).slice(0, 16)}.json`);
81
+ }
82
+ function signPayload(payload, privateKeyPem) {
83
+ const key = createPrivateKey(privateKeyPem);
84
+ return sign(null, Buffer.from(canonical(payload), "utf8"), key).toString("base64");
85
+ }
86
+ function verifyPayload(payload, sig, publicKeyPem) {
87
+ try {
88
+ return verify(null, Buffer.from(canonical(payload), "utf8"), createPublicKey(publicKeyPem), Buffer.from(sig, "base64"));
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ function closedKeys(value, allowed) {
95
+ return Object.keys(value).every((key) => allowed.has(key));
96
+ }
97
+ function isCommitPayload(value) {
98
+ if (value === null || typeof value !== "object" || Array.isArray(value))
99
+ return false;
100
+ if (!closedKeys(value, COMMIT_PAYLOAD_KEYS))
101
+ return false;
102
+ const row = value;
103
+ return (row.v === 1 &&
104
+ typeof row.seq === "number" &&
105
+ Number.isInteger(row.seq) &&
106
+ row.seq >= 1 &&
107
+ typeof row.tenantKey === "string" &&
108
+ typeof row.id === "string" &&
109
+ ID_RE.test(row.id) &&
110
+ typeof row.revision === "number" &&
111
+ Number.isInteger(row.revision) &&
112
+ row.revision >= 1 &&
113
+ typeof row.versionHash === "string" &&
114
+ /^[0-9a-f]{64}$/.test(row.versionHash) &&
115
+ typeof row.objectPath === "string" &&
116
+ typeof row.putRef === "string" &&
117
+ (row.prevCommitHash === null || (typeof row.prevCommitHash === "string" && /^[0-9a-f]{64}$/.test(row.prevCommitHash))) &&
118
+ typeof row.ts === "number");
119
+ }
120
+ function isHeadPayload(value) {
121
+ if (value === null || typeof value !== "object" || Array.isArray(value))
122
+ return false;
123
+ if (!closedKeys(value, HEAD_PAYLOAD_KEYS))
124
+ return false;
125
+ const row = value;
126
+ const lastHashOk = row.lastHash === null || (typeof row.lastHash === "string" && /^[0-9a-f]{64}$/.test(row.lastHash));
127
+ if (row.v !== 1 ||
128
+ typeof row.stateDirHash !== "string" ||
129
+ !/^[0-9a-f]{64}$/.test(row.stateDirHash) ||
130
+ typeof row.seq !== "number" ||
131
+ !Number.isInteger(row.seq) ||
132
+ row.seq < 0 ||
133
+ !lastHashOk ||
134
+ typeof row.ts !== "number") {
135
+ return false;
136
+ }
137
+ if (row.seq === 0)
138
+ return row.lastHash === null;
139
+ return typeof row.lastHash === "string";
140
+ }
141
+ function guardedJoin(root, ...parts) {
142
+ const base = resolve(root);
143
+ const path = resolve(base, ...parts);
144
+ const prefix = base.endsWith(sep) ? base : `${base}${sep}`;
145
+ if (path !== base && !path.startsWith(prefix))
146
+ return null;
147
+ return path;
148
+ }
149
+ export function relativeObjectPath(tenantKey, id, revision) {
150
+ return `tenants/${tenantKey}/memory/${id}/${revision}.json`;
151
+ }
152
+ function resolveObjectPath(stateDir, objectPath) {
153
+ if (objectPath.includes("\0"))
154
+ return null;
155
+ const parts = objectPath.split("/").filter((part) => part !== "");
156
+ if (parts.some((part) => part === ".." || part === "."))
157
+ return null;
158
+ if (parts.length !== 5 || parts[0] !== "tenants" || parts[2] !== "memory")
159
+ return null;
160
+ if (!parts[4].endsWith(".json"))
161
+ return null;
162
+ return guardedJoin(stateDir, ...parts);
163
+ }
164
+ function parseMemoryObject(raw) {
165
+ let parsed;
166
+ try {
167
+ parsed = JSON.parse(raw);
168
+ }
169
+ catch {
170
+ return null;
171
+ }
172
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
173
+ return null;
174
+ if (!closedKeys(parsed, OBJECT_KEYS))
175
+ return null;
176
+ const item = parsed;
177
+ if (typeof item.id !== "string" || !ID_RE.test(item.id))
178
+ return null;
179
+ if (typeof item.revision !== "number" || !Number.isInteger(item.revision) || item.revision < 1)
180
+ return null;
181
+ if (typeof item.tenantKey !== "string")
182
+ return null;
183
+ if (item.source === null || typeof item.source !== "object" || Array.isArray(item.source))
184
+ return null;
185
+ if (typeof item.validFromMs !== "number" || typeof item.validUntilMs !== "number")
186
+ return null;
187
+ if (typeof item.versionHash !== "string")
188
+ return null;
189
+ return {
190
+ id: item.id,
191
+ revision: item.revision,
192
+ tenantKey: item.tenantKey,
193
+ body: item.body,
194
+ source: item.source,
195
+ validFromMs: item.validFromMs,
196
+ validUntilMs: item.validUntilMs,
197
+ versionHash: item.versionHash,
198
+ };
199
+ }
200
+ function isUnsupportedDirFsync(err) {
201
+ const code = err.code;
202
+ return code === "EPERM" || code === "EISDIR" || code === "EINVAL" || code === "ENOTSUP" || code === "ENOSYS";
203
+ }
204
+ async function mkdirDurable(dir) {
205
+ const created = [];
206
+ let current = resolve(dir);
207
+ while (!existsSync(current)) {
208
+ created.push(current);
209
+ const parent = dirname(current);
210
+ if (parent === current)
211
+ break;
212
+ current = parent;
213
+ }
214
+ await mkdir(dir, { recursive: true, mode: 0o700 });
215
+ for (const path of created)
216
+ await fsyncDir(path);
217
+ await fsyncDir(current);
218
+ }
219
+ async function writeFileDurable(finalPath, payload) {
220
+ const dir = dirname(finalPath);
221
+ await mkdirDurable(dir);
222
+ const tmp = `${finalPath}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
223
+ const fh = await open(tmp, "w", 0o600);
224
+ try {
225
+ await fh.writeFile(payload, "utf8");
226
+ await fh.sync();
227
+ }
228
+ finally {
229
+ await fh.close();
230
+ }
231
+ await rename(tmp, finalPath);
232
+ try {
233
+ await chmod(finalPath, 0o600);
234
+ }
235
+ catch {
236
+ // Windows may refuse chmod; the file is already written.
237
+ }
238
+ await fsyncDir(dir);
239
+ }
240
+ async function fsyncDir(dir) {
241
+ try {
242
+ const fh = await open(dir, "r");
243
+ try {
244
+ await fh.sync();
245
+ }
246
+ finally {
247
+ await fh.close();
248
+ }
249
+ }
250
+ catch (err) {
251
+ if (isUnsupportedDirFsync(err))
252
+ return;
253
+ throw err;
254
+ }
255
+ }
256
+ function fsyncDirSync(dir) {
257
+ try {
258
+ const fd = openSync(dir, "r");
259
+ try {
260
+ fsyncSync(fd);
261
+ }
262
+ finally {
263
+ closeSync(fd);
264
+ }
265
+ }
266
+ catch (err) {
267
+ if (isUnsupportedDirFsync(err))
268
+ return;
269
+ throw err;
270
+ }
271
+ }
272
+ function mkdirDurableSync(dir) {
273
+ const created = [];
274
+ let current = resolve(dir);
275
+ while (!existsSync(current)) {
276
+ created.push(current);
277
+ const parent = dirname(current);
278
+ if (parent === current)
279
+ break;
280
+ current = parent;
281
+ }
282
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
283
+ for (const path of created)
284
+ fsyncDirSync(path);
285
+ fsyncDirSync(current);
286
+ }
287
+ function writeFileDurableSync(finalPath, payload) {
288
+ const dir = dirname(finalPath);
289
+ mkdirDurableSync(dir);
290
+ const tmp = `${finalPath}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
291
+ const fd = openSync(tmp, "w", 0o600);
292
+ try {
293
+ writeSync(fd, payload, 0, "utf8");
294
+ fsyncSync(fd);
295
+ }
296
+ finally {
297
+ closeSync(fd);
298
+ }
299
+ renameSync(tmp, finalPath);
300
+ try {
301
+ chmodSync(finalPath, 0o600);
302
+ }
303
+ catch {
304
+ // Windows may refuse chmod; the file is already written.
305
+ }
306
+ fsyncDirSync(dir);
307
+ }
308
+ function encodeHeadLine(payload, privateKeyPem) {
309
+ return `${JSON.stringify({ payload, sig: signPayload(payload, privateKeyPem) })}\n`;
310
+ }
311
+ function persistHeadSync(opts) {
312
+ const payload = {
313
+ v: 1,
314
+ stateDirHash: memoryStateDirHash(opts.stateDir),
315
+ seq: opts.seq,
316
+ lastHash: opts.lastHash,
317
+ ts: Date.now(),
318
+ };
319
+ writeFileDurableSync(memoryHeadPath(opts.stateDir, opts.headDir), encodeHeadLine(payload, opts.privateKeyPem));
320
+ }
321
+ function readVerifiedHead(path, publicKeyPem, expectedStateDirHash) {
322
+ if (!existsSync(path))
323
+ return { kind: "missing" };
324
+ try {
325
+ if (!statSync(path).isFile())
326
+ return { kind: "invalid" };
327
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
328
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || !closedKeys(parsed, LINE_KEYS)) {
329
+ return { kind: "invalid" };
330
+ }
331
+ const row = parsed;
332
+ if (typeof row.sig !== "string" || !isHeadPayload(row.payload))
333
+ return { kind: "invalid" };
334
+ if (!verifyPayload(row.payload, row.sig, publicKeyPem))
335
+ return { kind: "invalid" };
336
+ if (row.payload.stateDirHash !== expectedStateDirHash)
337
+ return { kind: "invalid" };
338
+ return { kind: "ok", payload: row.payload };
339
+ }
340
+ catch {
341
+ return { kind: "invalid" };
342
+ }
343
+ }
344
+ async function appendLineDurable(path, line) {
345
+ const existed = existsSync(path);
346
+ const fh = await open(path, "a", 0o600);
347
+ let writeStarted = false;
348
+ let firstErr;
349
+ try {
350
+ writeStarted = true;
351
+ await fh.writeFile(line, "utf8");
352
+ await fh.sync();
353
+ }
354
+ catch (err) {
355
+ firstErr = err;
356
+ }
357
+ try {
358
+ await fh.close();
359
+ }
360
+ catch (err) {
361
+ firstErr ??= err;
362
+ }
363
+ if (writeStarted && firstErr)
364
+ throw new UncertainAppendError();
365
+ if (firstErr)
366
+ throw firstErr;
367
+ if (!existed) {
368
+ try {
369
+ await fsyncDir(dirname(path));
370
+ }
371
+ catch {
372
+ throw new UncertainAppendError();
373
+ }
374
+ }
375
+ }
376
+ function* readCommitLines(path) {
377
+ const fd = openSync(path, "r");
378
+ try {
379
+ const buf = Buffer.alloc(64 * 1024);
380
+ let acc = "";
381
+ for (;;) {
382
+ const n = readSync(fd, buf, 0, buf.length, null);
383
+ if (n === 0)
384
+ break;
385
+ acc += buf.toString("utf8", 0, n);
386
+ let idx = acc.indexOf("\n");
387
+ while (idx !== -1) {
388
+ let line = acc.slice(0, idx);
389
+ acc = acc.slice(idx + 1);
390
+ if (line.endsWith("\r"))
391
+ line = line.slice(0, -1);
392
+ yield line;
393
+ idx = acc.indexOf("\n");
394
+ }
395
+ }
396
+ if (acc.length > 0)
397
+ yield acc.endsWith("\r") ? acc.slice(0, -1) : acc;
398
+ }
399
+ finally {
400
+ closeSync(fd);
401
+ }
402
+ }
403
+ function indexKey(tenantKey, id) {
404
+ return `${tenantKey}|${id}`;
405
+ }
406
+ function fileExistsUnder(root, ...parts) {
407
+ const path = guardedJoin(root, ...parts);
408
+ if (path === null)
409
+ return false;
410
+ try {
411
+ return statSync(path).isFile();
412
+ }
413
+ catch {
414
+ return false;
415
+ }
416
+ }
417
+ function dirHasJson(root, ...parts) {
418
+ const path = guardedJoin(root, ...parts);
419
+ if (path === null)
420
+ return false;
421
+ try {
422
+ if (!statSync(path).isDirectory())
423
+ return false;
424
+ return readdirSync(path).some((name) => name.endsWith(".json"));
425
+ }
426
+ catch {
427
+ return false;
428
+ }
429
+ }
430
+ export class MemoryStore {
431
+ stateDir;
432
+ headDir;
433
+ publicKeyPem;
434
+ privateKeyPem;
435
+ historyUnavailable;
436
+ index = new Map();
437
+ lastSeq = 0;
438
+ lastHash = null;
439
+ constructor(opts) {
440
+ this.stateDir = opts.stateDir;
441
+ this.headDir = opts.headDir;
442
+ this.publicKeyPem = opts.publicKeyPem;
443
+ this.privateKeyPem = opts.privateKeyPem;
444
+ this.historyUnavailable = opts.historyUnavailable;
445
+ this.index = opts.index;
446
+ this.lastSeq = opts.lastSeq;
447
+ this.lastHash = opts.lastHash;
448
+ }
449
+ async persistHead(seq, lastHash) {
450
+ const payload = {
451
+ v: 1,
452
+ stateDirHash: memoryStateDirHash(this.stateDir),
453
+ seq,
454
+ lastHash,
455
+ ts: Date.now(),
456
+ };
457
+ await writeFileDurable(memoryHeadPath(this.stateDir, this.headDir), encodeHeadLine(payload, this.privateKeyPem));
458
+ }
459
+ rememberDecisionSnapshot(_tenantKey, _object) { }
460
+ withTenantLock(tenantKey, fn) {
461
+ return withLock(tenantMemoryLockKey(this.stateDir, tenantKey), fn);
462
+ }
463
+ /** The signed commit tip, when the store has one. Omitted from an alarm when absent. */
464
+ memoryHead() {
465
+ if (this.lastSeq < 1 || this.lastHash === null)
466
+ return undefined;
467
+ return { seq: this.lastSeq, lastHash: this.lastHash };
468
+ }
469
+ lookup(tenantKey, id) {
470
+ return this.index.get(indexKey(tenantKey, id));
471
+ }
472
+ idHeldByTenant(id, tenantKey) {
473
+ if (!ID_RE.test(id))
474
+ return false;
475
+ if (this.index.has(indexKey(tenantKey, id)))
476
+ return true;
477
+ return this.objectPresent(tenantKey, id);
478
+ }
479
+ idVisibleForOtherTenant(id, selfKey) {
480
+ if (!ID_RE.test(id))
481
+ return false;
482
+ for (const key of this.index.keys()) {
483
+ const sepAt = key.indexOf("|");
484
+ if (sepAt <= 0)
485
+ continue;
486
+ const tk = key.slice(0, sepAt);
487
+ const storedId = key.slice(sepAt + 1);
488
+ if (tk !== selfKey && storedId === id)
489
+ return true;
490
+ }
491
+ const tenantsRoot = resolve(this.stateDir, "tenants");
492
+ if (!existsSync(tenantsRoot))
493
+ return false;
494
+ let names;
495
+ try {
496
+ names = readdirSync(tenantsRoot);
497
+ }
498
+ catch {
499
+ return false;
500
+ }
501
+ for (const name of names) {
502
+ if (name === selfKey)
503
+ continue;
504
+ if (this.objectPresent(name, id))
505
+ return true;
506
+ }
507
+ return false;
508
+ }
509
+ objectPresent(tenantKey, id) {
510
+ const memoryDir = guardedJoin(this.stateDir, "tenants", tenantKey, "memory");
511
+ if (memoryDir === null)
512
+ return false;
513
+ if (fileExistsUnder(memoryDir, `${id}.json`))
514
+ return true;
515
+ return dirHasJson(memoryDir, id);
516
+ }
517
+ verifiedRead(tenantKey, id) {
518
+ if (this.historyUnavailable) {
519
+ return { kind: "integrity", reason: "memory-integrity-history-unavailable" };
520
+ }
521
+ const committed = this.lookup(tenantKey, id);
522
+ if (committed) {
523
+ const path = resolveObjectPath(this.stateDir, committed.objectPath);
524
+ if (path === null)
525
+ return { kind: "integrity", reason: "memory-integrity-mismatch" };
526
+ let raw;
527
+ try {
528
+ raw = readFileSync(path, "utf8");
529
+ }
530
+ catch (err) {
531
+ if (err.code === "ENOENT") {
532
+ return { kind: "integrity", reason: "memory-integrity-missing" };
533
+ }
534
+ return { kind: "integrity", reason: "memory-integrity-mismatch" };
535
+ }
536
+ const object = parseMemoryObject(raw);
537
+ if (object === null)
538
+ return { kind: "integrity", reason: "memory-integrity-mismatch" };
539
+ let versionHash;
540
+ try {
541
+ versionHash = memoryVersionHash(object);
542
+ }
543
+ catch {
544
+ return { kind: "integrity", reason: "memory-integrity-mismatch" };
545
+ }
546
+ if (object.id !== id ||
547
+ object.tenantKey !== tenantKey ||
548
+ object.revision !== committed.revision ||
549
+ object.versionHash !== versionHash ||
550
+ versionHash !== committed.versionHash) {
551
+ return { kind: "integrity", reason: "memory-integrity-mismatch" };
552
+ }
553
+ return { kind: "ok", object, versionHash };
554
+ }
555
+ if (this.objectPresent(tenantKey, id)) {
556
+ return { kind: "integrity", reason: "memory-integrity-unattested" };
557
+ }
558
+ return { kind: "not-found" };
559
+ }
560
+ async put(opts) {
561
+ if (this.historyUnavailable) {
562
+ return { ok: false, error: "memory-integrity-history-unavailable" };
563
+ }
564
+ const commitLock = `memory-commits:${storeKey(this.stateDir)}`;
565
+ return this.withTenantLock(opts.tenantKey, async () => {
566
+ const current = this.lookup(opts.tenantKey, opts.id);
567
+ const revision = current ? current.revision + 1 : 1;
568
+ const versionHash = memoryVersionHash({
569
+ tenantKey: opts.tenantKey,
570
+ id: opts.id,
571
+ revision,
572
+ body: opts.body,
573
+ source: opts.source,
574
+ validFromMs: opts.validFromMs,
575
+ validUntilMs: opts.validUntilMs,
576
+ });
577
+ const object = {
578
+ id: opts.id,
579
+ revision,
580
+ tenantKey: opts.tenantKey,
581
+ body: opts.body,
582
+ source: opts.source,
583
+ validFromMs: opts.validFromMs,
584
+ validUntilMs: opts.validUntilMs,
585
+ versionHash,
586
+ };
587
+ const objectPath = relativeObjectPath(opts.tenantKey, opts.id, revision);
588
+ const abs = resolveObjectPath(this.stateDir, objectPath);
589
+ if (abs === null)
590
+ throw new Error("memory-object-path");
591
+ const payload = `${JSON.stringify(object)}\n`;
592
+ const used = await this.currentUsageBytes(opts.tenantKey, opts.id);
593
+ if (used + Buffer.byteLength(payload) > opts.quotaBytes) {
594
+ return { ok: false, error: "memory-quota" };
595
+ }
596
+ await writeFileDurable(abs, payload);
597
+ await withLock(commitLock, async () => {
598
+ if (this.historyUnavailable)
599
+ return;
600
+ const commit = {
601
+ v: 1,
602
+ seq: this.lastSeq + 1,
603
+ tenantKey: opts.tenantKey,
604
+ id: opts.id,
605
+ revision,
606
+ versionHash,
607
+ objectPath,
608
+ putRef: opts.putRef,
609
+ prevCommitHash: this.lastHash,
610
+ ts: Date.now(),
611
+ };
612
+ const line = `${JSON.stringify({ payload: commit, sig: signPayload(commit, this.privateKeyPem) })}\n`;
613
+ try {
614
+ await appendLineDurable(join(this.stateDir, MEMORY_COMMITS_FILE), line);
615
+ }
616
+ catch (err) {
617
+ if (err instanceof UncertainAppendError) {
618
+ this.historyUnavailable = true;
619
+ return;
620
+ }
621
+ throw err;
622
+ }
623
+ const nextHash = sha256Canonical(commit);
624
+ try {
625
+ await this.persistHead(commit.seq, nextHash);
626
+ this.lastSeq = commit.seq;
627
+ this.lastHash = nextHash;
628
+ this.index.set(indexKey(opts.tenantKey, opts.id), { revision, versionHash, objectPath });
629
+ }
630
+ catch {
631
+ this.historyUnavailable = true;
632
+ }
633
+ });
634
+ if (this.historyUnavailable) {
635
+ return { ok: false, error: "memory-integrity-history-unavailable" };
636
+ }
637
+ if (current) {
638
+ const old = resolveObjectPath(this.stateDir, current.objectPath);
639
+ if (old !== null && old !== abs) {
640
+ try {
641
+ await unlink(old);
642
+ }
643
+ catch (err) {
644
+ if (err.code !== "ENOENT")
645
+ throw err;
646
+ }
647
+ }
648
+ }
649
+ return { ok: true, id: opts.id, revision, versionHash };
650
+ });
651
+ }
652
+ async reattestLegacy(opts) {
653
+ if (this.historyUnavailable)
654
+ throw new Error("memory-history-unavailable");
655
+ if (this.lookup(opts.tenantKey, opts.id))
656
+ return { skipped: true };
657
+ const result = await this.put({
658
+ tenantKey: opts.tenantKey,
659
+ id: opts.id,
660
+ body: opts.body,
661
+ source: opts.source,
662
+ validFromMs: opts.validFromMs,
663
+ validUntilMs: opts.validUntilMs,
664
+ putRef: "verax.memory.reattest",
665
+ quotaBytes: Number.MAX_SAFE_INTEGER,
666
+ });
667
+ if (!result.ok)
668
+ throw new Error("memory-quota");
669
+ try {
670
+ await unlink(opts.legacyPath);
671
+ }
672
+ catch (err) {
673
+ if (err.code !== "ENOENT")
674
+ throw err;
675
+ }
676
+ return result;
677
+ }
678
+ async currentUsageBytes(tenantKey, excludeId) {
679
+ let used = 0;
680
+ for (const [key, entry] of this.index) {
681
+ const sepAt = key.indexOf("|");
682
+ if (sepAt <= 0)
683
+ continue;
684
+ const tk = key.slice(0, sepAt);
685
+ const id = key.slice(sepAt + 1);
686
+ if (tk !== tenantKey || id === excludeId)
687
+ continue;
688
+ const path = resolveObjectPath(this.stateDir, entry.objectPath);
689
+ if (path === null)
690
+ continue;
691
+ try {
692
+ const info = await stat(path);
693
+ if (info.isFile())
694
+ used += info.size;
695
+ }
696
+ catch (err) {
697
+ if (err.code !== "ENOENT")
698
+ throw err;
699
+ }
700
+ }
701
+ return used;
702
+ }
703
+ }
704
+ function openLoadedStore(opts, loaded) {
705
+ const store = new MemoryStore({
706
+ stateDir: resolve(opts.stateDir),
707
+ headDir: opts.headDir,
708
+ publicKeyPem: opts.publicKeyPem,
709
+ privateKeyPem: opts.privateKeyPem,
710
+ historyUnavailable: loaded.historyUnavailable,
711
+ index: loaded.index,
712
+ lastSeq: loaded.lastSeq,
713
+ lastHash: loaded.lastHash,
714
+ });
715
+ return store;
716
+ }
717
+ function unavailableStore(opts) {
718
+ return openLoadedStore(opts, { historyUnavailable: true, index: new Map(), lastSeq: 0, lastHash: null });
719
+ }
720
+ function bindHead(opts, loaded) {
721
+ if (loaded.historyUnavailable)
722
+ return unavailableStore(opts);
723
+ const stateDir = resolve(opts.stateDir);
724
+ const headPath = memoryHeadPath(stateDir, opts.headDir);
725
+ const expectedHash = memoryStateDirHash(stateDir);
726
+ const head = readVerifiedHead(headPath, opts.publicKeyPem, expectedHash);
727
+ if (head.kind === "invalid")
728
+ return unavailableStore(opts);
729
+ if (head.kind === "missing") {
730
+ if (loaded.lastSeq > 0) {
731
+ process.stderr.write(`memory-head-missing: the commit chain has ${loaded.lastSeq} lines but no memory head; run "verax memory rehead ${stateDir}" with the body stopped to trust the chain as it is now\n`);
732
+ return unavailableStore(opts);
733
+ }
734
+ persistHeadSync({
735
+ stateDir,
736
+ headDir: opts.headDir,
737
+ privateKeyPem: opts.privateKeyPem,
738
+ seq: loaded.lastSeq,
739
+ lastHash: loaded.lastHash,
740
+ });
741
+ return openLoadedStore(opts, loaded);
742
+ }
743
+ if (loaded.lastSeq < head.payload.seq)
744
+ return unavailableStore(opts);
745
+ if (head.payload.seq > 0) {
746
+ const atHead = loaded.hashBySeq.get(head.payload.seq);
747
+ if (atHead !== head.payload.lastHash)
748
+ return unavailableStore(opts);
749
+ }
750
+ if (loaded.lastSeq > head.payload.seq) {
751
+ persistHeadSync({
752
+ stateDir,
753
+ headDir: opts.headDir,
754
+ privateKeyPem: opts.privateKeyPem,
755
+ seq: loaded.lastSeq,
756
+ lastHash: loaded.lastHash,
757
+ });
758
+ }
759
+ return openLoadedStore(opts, loaded);
760
+ }
761
+ export function publishMemoryStore(store) {
762
+ stores.set(storeKey(store.stateDir), store);
763
+ return store;
764
+ }
765
+ /** Same-process memory gate when the halt switch file cannot be written. */
766
+ export function markHistoryUnavailable(stateDir) {
767
+ const store = stores.get(storeKey(stateDir));
768
+ if (store)
769
+ store.historyUnavailable = true;
770
+ }
771
+ function emptyChain() {
772
+ return {
773
+ historyUnavailable: false,
774
+ index: new Map(),
775
+ lastSeq: 0,
776
+ lastHash: null,
777
+ hashBySeq: new Map(),
778
+ };
779
+ }
780
+ function loadCommitChain(stateDir, publicKeyPem) {
781
+ const path = join(stateDir, MEMORY_COMMITS_FILE);
782
+ const unavailable = {
783
+ historyUnavailable: true,
784
+ index: new Map(),
785
+ lastSeq: 0,
786
+ lastHash: null,
787
+ hashBySeq: new Map(),
788
+ };
789
+ if (!existsSync(path))
790
+ return emptyChain();
791
+ try {
792
+ if (!statSync(path).isFile())
793
+ return unavailable;
794
+ const index = new Map();
795
+ const hashBySeq = new Map();
796
+ let lastSeq = 0;
797
+ let lastHash = null;
798
+ for (const line of readCommitLines(path)) {
799
+ if (line.trim() === "")
800
+ continue;
801
+ let parsed;
802
+ try {
803
+ parsed = JSON.parse(line);
804
+ }
805
+ catch {
806
+ return unavailable;
807
+ }
808
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || !closedKeys(parsed, LINE_KEYS)) {
809
+ return unavailable;
810
+ }
811
+ const row = parsed;
812
+ if (typeof row.sig !== "string" || !isCommitPayload(row.payload)) {
813
+ return unavailable;
814
+ }
815
+ if (!verifyPayload(row.payload, row.sig, publicKeyPem)) {
816
+ return unavailable;
817
+ }
818
+ if (row.payload.seq !== lastSeq + 1 || row.payload.prevCommitHash !== lastHash) {
819
+ return unavailable;
820
+ }
821
+ if (resolveObjectPath(stateDir, row.payload.objectPath) === null) {
822
+ return unavailable;
823
+ }
824
+ lastSeq = row.payload.seq;
825
+ lastHash = sha256Canonical(row.payload);
826
+ hashBySeq.set(lastSeq, lastHash);
827
+ index.set(indexKey(row.payload.tenantKey, row.payload.id), {
828
+ revision: row.payload.revision,
829
+ versionHash: row.payload.versionHash,
830
+ objectPath: row.payload.objectPath,
831
+ });
832
+ }
833
+ return { historyUnavailable: false, index, lastSeq, lastHash, hashBySeq };
834
+ }
835
+ catch {
836
+ return unavailable;
837
+ }
838
+ }
839
+ export function reheadMemoryFromChain(opts) {
840
+ const loaded = loadCommitChain(opts.stateDir, opts.publicKeyPem);
841
+ if (loaded.historyUnavailable)
842
+ return { ok: false };
843
+ const stateDir = resolve(opts.stateDir);
844
+ persistHeadSync({
845
+ stateDir,
846
+ headDir: resolveHeadDir(stateDir, undefined, opts.headDir),
847
+ privateKeyPem: opts.privateKeyPem,
848
+ seq: loaded.lastSeq,
849
+ lastHash: loaded.lastHash,
850
+ });
851
+ return { ok: true, seq: loaded.lastSeq, lastHash: loaded.lastHash };
852
+ }
853
+ export function openMemoryStoreSync(opts) {
854
+ const bound = {
855
+ stateDir: opts.stateDir,
856
+ headDir: resolveHeadDir(opts.stateDir, undefined, opts.headDir),
857
+ publicKeyPem: opts.publicKeyPem,
858
+ privateKeyPem: opts.privateKeyPem,
859
+ };
860
+ const loaded = loadCommitChain(opts.stateDir, opts.publicKeyPem);
861
+ if (loaded.historyUnavailable)
862
+ return unavailableStore(bound);
863
+ return bindHead(bound, loaded);
864
+ }
865
+ export function memoryStoreFor(stateDir, keys) {
866
+ const existing = stores.get(storeKey(stateDir));
867
+ if (existing)
868
+ return existing;
869
+ if (!keys) {
870
+ throw new Error("memory-store-unopened");
871
+ }
872
+ return publishMemoryStore(openMemoryStoreSync({ stateDir, publicKeyPem: keys.publicKeyPem, privateKeyPem: keys.privateKeyPem }));
873
+ }
874
+ export function listLegacyMemoryFiles(stateDir) {
875
+ const out = [];
876
+ const tenantsRoot = resolve(stateDir, "tenants");
877
+ if (!existsSync(tenantsRoot))
878
+ return out;
879
+ let tenants;
880
+ try {
881
+ tenants = readdirSync(tenantsRoot);
882
+ }
883
+ catch {
884
+ return out;
885
+ }
886
+ for (const tenantKey of tenants) {
887
+ const memoryDir = guardedJoin(tenantsRoot, tenantKey, "memory");
888
+ if (memoryDir === null || !existsSync(memoryDir))
889
+ continue;
890
+ let names;
891
+ try {
892
+ names = readdirSync(memoryDir);
893
+ }
894
+ catch {
895
+ continue;
896
+ }
897
+ for (const name of names) {
898
+ if (!name.endsWith(".json"))
899
+ continue;
900
+ const id = name.slice(0, -".json".length);
901
+ if (!ID_RE.test(id))
902
+ continue;
903
+ const path = guardedJoin(memoryDir, name);
904
+ if (path === null)
905
+ continue;
906
+ try {
907
+ if (!statSync(path).isFile())
908
+ continue;
909
+ }
910
+ catch {
911
+ continue;
912
+ }
913
+ out.push({ tenantKey, id, path });
914
+ }
915
+ }
916
+ return out;
917
+ }