@loro-dev/roost 0.1.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -0
  3. package/dist/codec.d.ts +66 -0
  4. package/dist/codec.js +275 -0
  5. package/dist/crypto.d.ts +21 -0
  6. package/dist/crypto.js +103 -0
  7. package/dist/durable-framing.d.ts +44 -0
  8. package/dist/durable-framing.js +207 -0
  9. package/dist/framing.d.ts +28 -0
  10. package/dist/framing.js +144 -0
  11. package/dist/history-publication.d.ts +58 -0
  12. package/dist/history-publication.js +234 -0
  13. package/dist/identity.d.ts +14 -0
  14. package/dist/identity.js +62 -0
  15. package/dist/inbox.d.ts +69 -0
  16. package/dist/inbox.js +262 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +6 -0
  19. package/dist/indexeddb.d.ts +38 -0
  20. package/dist/indexeddb.js +299 -0
  21. package/dist/json.d.ts +23 -0
  22. package/dist/json.js +221 -0
  23. package/dist/lody-history.d.ts +397 -0
  24. package/dist/lody-history.js +1559 -0
  25. package/dist/projection.d.ts +53 -0
  26. package/dist/projection.js +543 -0
  27. package/dist/replay.d.ts +63 -0
  28. package/dist/replay.js +201 -0
  29. package/dist/sender.d.ts +26 -0
  30. package/dist/sender.js +67 -0
  31. package/dist/store.d.ts +384 -0
  32. package/dist/store.js +1437 -0
  33. package/dist/sync/coverage.d.ts +276 -0
  34. package/dist/sync/coverage.js +1084 -0
  35. package/dist/sync/crypto.d.ts +64 -0
  36. package/dist/sync/crypto.js +155 -0
  37. package/dist/sync/execute.d.ts +142 -0
  38. package/dist/sync/execute.js +321 -0
  39. package/dist/sync/history.d.ts +214 -0
  40. package/dist/sync/history.js +786 -0
  41. package/dist/sync/index.d.ts +17 -0
  42. package/dist/sync/index.js +9 -0
  43. package/dist/sync/link.d.ts +192 -0
  44. package/dist/sync/link.js +663 -0
  45. package/dist/sync/mod.d.ts +24 -0
  46. package/dist/sync/mod.js +15 -0
  47. package/dist/sync/policy.d.ts +62 -0
  48. package/dist/sync/policy.js +128 -0
  49. package/dist/sync/registry.d.ts +129 -0
  50. package/dist/sync/registry.js +333 -0
  51. package/dist/sync/transport.d.ts +91 -0
  52. package/dist/sync/transport.js +162 -0
  53. package/dist/sync/work.d.ts +351 -0
  54. package/dist/sync/work.js +1344 -0
  55. package/package.json +47 -0
package/dist/store.js ADDED
@@ -0,0 +1,1437 @@
1
+ import { blake3 } from '@noble/hashes/blake3.js';
2
+ import { assembleFrames, decodeFrame, encodeFrame, splitBatch, MAX_BATCH, MAX_FRAME, MAX_UPDATES } from './codec.js';
3
+ import { decodeUtf8, encodeUtf8, U64_MAX } from './json.js';
4
+ import { checkTurnId, nextTurnId } from './identity.js';
5
+ import { isValidOwner, nodeHash, verifySealSignature } from './crypto.js';
6
+ import { Projection, ProjectionError, decodeLayout, encodeLayout } from './projection.js';
7
+ export class StoreError extends Error {
8
+ code;
9
+ constructor(code, message = code, options) {
10
+ super(message, options);
11
+ this.code = code;
12
+ this.name = 'StoreError';
13
+ }
14
+ }
15
+ const invalid = (message) => new StoreError('invalid', message);
16
+ const corrupt = (message) => new StoreError('corrupt', message);
17
+ const empty = new Uint8Array();
18
+ const ALL = Number.MAX_SAFE_INTEGER;
19
+ function compare(a, b) {
20
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
21
+ if (a[i] !== b[i])
22
+ return a[i] - b[i];
23
+ return a.length - b.length;
24
+ }
25
+ function equal(a, b) { return compare(a, b) === 0; }
26
+ function cat(...parts) {
27
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
28
+ let n = 0;
29
+ for (const p of parts) {
30
+ out.set(p, n);
31
+ n += p.length;
32
+ }
33
+ return out;
34
+ }
35
+ function hex(b) { return Array.from(b, v => v.toString(16).padStart(2, '0')).join(''); }
36
+ function uuid(b) { const s = hex(b); return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`; }
37
+ function u64(n) {
38
+ if (typeof n !== 'bigint' || n < 0n || n > U64_MAX)
39
+ throw invalid('u64 required');
40
+ return n;
41
+ }
42
+ function key64(n) { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, u64(n)); return b; }
43
+ function read64(b) {
44
+ if (b.length !== 8)
45
+ throw corrupt('invalid u64');
46
+ return new DataView(b.buffer, b.byteOffset, 8).getBigUint64(0);
47
+ }
48
+ function limit(n) {
49
+ if (!Number.isSafeInteger(n) || n < 0)
50
+ throw invalid('non-negative safe limit required');
51
+ return n;
52
+ }
53
+ function idCopy(id) {
54
+ try {
55
+ checkTurnId(id);
56
+ return id.slice();
57
+ }
58
+ catch (e) {
59
+ throw invalid(String(e));
60
+ }
61
+ }
62
+ function namespace(s) {
63
+ const b = syntax(() => encodeUtf8(s));
64
+ if (!b.length || b.length > 4096)
65
+ throw invalid('namespace size');
66
+ return s;
67
+ }
68
+ function endPrefix(b) {
69
+ const out = b.slice();
70
+ for (let i = out.length - 1; i >= 0; i--)
71
+ if (out[i] !== 255) {
72
+ out[i] = out[i] + 1;
73
+ return out.slice(0, i + 1);
74
+ }
75
+ return undefined;
76
+ }
77
+ function updateKey(id, seq) { return cat(id, key64(seq)); }
78
+ function syntax(fn) {
79
+ try {
80
+ return fn();
81
+ }
82
+ catch (e) {
83
+ if (e instanceof StoreError)
84
+ throw e;
85
+ throw invalid(e instanceof Error ? e.message : String(e));
86
+ }
87
+ }
88
+ function semantic(e) {
89
+ if (e instanceof ProjectionError)
90
+ return invalid(e.message);
91
+ if (e instanceof StoreError && e.code !== 'corrupt' && e.code !== 'closed')
92
+ return e;
93
+ return undefined;
94
+ }
95
+ function varSize(n) {
96
+ let size = 1;
97
+ while (n >= 128) {
98
+ size++;
99
+ n = Math.floor(n / 128);
100
+ }
101
+ return size;
102
+ }
103
+ const PENDING_QUOTA_REASON = 'pending quota exceeded; retry after resolving dependencies';
104
+ /** Maximum rows per reverse keyset header page. Mirror of MAX_PAGE_HEADERS in
105
+ * src/store.rs; keep both languages in sync (1000). */
106
+ export const MAX_PAGE_HEADERS = 1000;
107
+ /** Internal replay classification; public import status and reason remain unchanged. */
108
+ export function _isRetryableImportStatus(status) {
109
+ return status.kind === 'rejected' && status.reason === PENDING_QUOTA_REASON;
110
+ }
111
+ /** Exact Rust serde_json TurnSnapshot budget; content is accounted by Projection. */
112
+ function turnBytes(h) {
113
+ const metadata = `{"id":${JSON.stringify(uuid(h.turnId))},"owner":${JSON.stringify([...h.owner])},"parents":[${h.parents.map(p => `{"id":${JSON.stringify(uuid(p.id))},"hash":${JSON.stringify([...p.hash])}}`).join(',')}],"content":null,"next_seq":${h.nextSeq},"sealed":${h.sealed === null ? 'null' : JSON.stringify([...h.sealed])},"hash_verified":${h.hashVerified},"body_verified":${h.bodyVerified}}`;
114
+ return encodeUtf8(metadata).length - 4 + h.layout.root.bytes;
115
+ }
116
+ function encodeHeader(h, legacy = false) {
117
+ const tail = legacy ? [h.hashVerified, [...encodeLayout(h.layout)]] : [h.bodyVerified, h.hashVerified, [...encodeLayout(h.layout)]];
118
+ return encodeUtf8(JSON.stringify([1, [...h.turnId], [...h.owner], h.parents.map(p => [[...p.id], [...p.hash]]), h.nextSeq.toString(), h.sealed === null ? null : [...h.sealed], ...tail]));
119
+ }
120
+ function decodeHeader(bytes, id) {
121
+ try {
122
+ const a = JSON.parse(decodeUtf8(bytes));
123
+ const fixed = (v, n) => {
124
+ if (!Array.isArray(v) || v.length !== n || v.some(x => !Number.isInteger(x) || x < 0 || x > 255))
125
+ throw Error();
126
+ return Uint8Array.from(v);
127
+ };
128
+ const legacy = Array.isArray(a) && a.length === 8;
129
+ if (!Array.isArray(a) || (a.length !== 8 && a.length !== 9) || a[0] !== 1 || typeof a[4] !== 'string' || !/^(0|[1-9][0-9]*)$/.test(a[4]) || typeof a[6] !== 'boolean' || !Array.isArray(a[3]))
130
+ throw Error();
131
+ if (!legacy && typeof a[7] !== 'boolean')
132
+ throw Error();
133
+ const turnId = fixed(a[1], 16);
134
+ checkTurnId(turnId);
135
+ if (!equal(id, turnId))
136
+ throw Error();
137
+ const owner = fixed(a[2], 32);
138
+ if (!isValidOwner(owner))
139
+ throw Error();
140
+ const parents = a[3].map((p) => {
141
+ if (!Array.isArray(p) || p.length !== 2)
142
+ throw Error();
143
+ return { id: fixed(p[0], 16), hash: fixed(p[1], 32) };
144
+ });
145
+ let prior;
146
+ for (const p of parents) {
147
+ checkTurnId(p.id);
148
+ if (compare(p.id, id) >= 0 || (prior && compare(prior, p.id) >= 0))
149
+ throw Error();
150
+ prior = p.id;
151
+ }
152
+ // A record written before `bodyVerified` existed: a chain-verified
153
+ // turn was body-verified by construction, so the old meaning holds.
154
+ const layoutField = legacy ? a[7] : a[8];
155
+ const h = { turnId, owner, parents, nextSeq: u64(BigInt(a[4])), sealed: a[5] === null ? null : fixed(a[5], 32), bodyVerified: a[6], hashVerified: legacy ? a[6] : a[7], layout: decodeLayout(fixed(layoutField, layoutField.length)) };
156
+ if (h.nextSeq === 0n || (h.hashVerified && h.sealed === null) || turnBytes(h) > MAX_FRAME || !equal(bytes, encodeHeader(h, legacy)))
157
+ throw Error();
158
+ return h;
159
+ }
160
+ catch (e) {
161
+ throw new StoreError('corrupt', 'corrupt Turn header', { cause: e });
162
+ }
163
+ }
164
+ function encodeEvent(e) { return encodeUtf8(JSON.stringify(e.kind === 'changed' ? ['changed', [...e.update.turnId], e.update.seq.toString(), e.origin] : e.kind === 'indexChanged' ? ['indexChanged', e.table, [...e.key]] : ['rejected', [...e.digest], e.reason])); }
165
+ function decodeEvent(b) {
166
+ try {
167
+ const a = JSON.parse(decodeUtf8(b));
168
+ let e;
169
+ if (a[0] === 'changed' && (a[3] === 'local' || a[3] === 'remote'))
170
+ e = { kind: 'changed', update: { turnId: idCopy(Uint8Array.from(a[1])), seq: u64(BigInt(a[2])) }, origin: a[3] };
171
+ else if (a[0] === 'rejected' && a[1].length === 32 && typeof a[2] === 'string')
172
+ e = { kind: 'rejected', digest: Uint8Array.from(a[1]), reason: a[2] };
173
+ else if (a[0] === 'indexChanged' && typeof a[1] === 'string' && Array.isArray(a[2]))
174
+ e = { kind: 'indexChanged', table: appTable(a[1]), key: Uint8Array.from(a[2]) };
175
+ else
176
+ throw Error();
177
+ if (!equal(encodeEvent(e), b))
178
+ throw Error();
179
+ return e;
180
+ }
181
+ catch (e) {
182
+ throw corrupt('corrupt event');
183
+ }
184
+ }
185
+ export class Store {
186
+ storage;
187
+ allows;
188
+ #closed = false;
189
+ #callback = false;
190
+ #pending = new Set();
191
+ #subscriptions = new Map();
192
+ options;
193
+ constructor(storage, allows, options) {
194
+ this.storage = storage;
195
+ this.allows = allows;
196
+ if (typeof allows !== 'function' || typeof options?.clock !== 'function' || typeof options?.randomBytes !== 'function')
197
+ throw invalid('explicit authorizer, clock and randomBytes required');
198
+ if (options.verifyHashIntegrity !== undefined && typeof options.verifyHashIntegrity !== 'boolean')
199
+ throw invalid('verifyHashIntegrity must be boolean');
200
+ this.options = Object.freeze({ ...options, verifyHashIntegrity: options.verifyHashIntegrity ?? true });
201
+ }
202
+ check() {
203
+ if (this.#closed)
204
+ throw new StoreError('closed');
205
+ if (this.#callback)
206
+ throw invalid('host callback cannot reenter Store');
207
+ }
208
+ host(fn) {
209
+ if (this.#callback)
210
+ throw invalid('host callback cannot reenter Store');
211
+ this.#callback = true;
212
+ try {
213
+ const value = fn();
214
+ if (value !== null && (typeof value === 'object' || typeof value === 'function') && 'then' in value) {
215
+ void Promise.resolve(value).catch(() => { });
216
+ throw invalid('host callback must be synchronous');
217
+ }
218
+ return value;
219
+ }
220
+ finally {
221
+ this.#callback = false;
222
+ }
223
+ }
224
+ authorize(stream, owner) {
225
+ const value = this.host(() => this.allows(stream, owner.slice()));
226
+ if (typeof value !== 'boolean')
227
+ throw invalid('authorizer must return boolean');
228
+ return value;
229
+ }
230
+ stream(id) { this.check(); return new Stream(this, namespace(id)); }
231
+ run(write, stream, program, notify) {
232
+ this.check();
233
+ const p = this.storage.transact(write, program);
234
+ this.#pending.add(p);
235
+ void p.then(result => {
236
+ this.#pending.delete(p);
237
+ if (write && !this.#closed && (!notify || notify(result)))
238
+ for (const sub of this.#subscriptions.get(stream) ?? [])
239
+ sub.signal();
240
+ }, () => this.#pending.delete(p));
241
+ return p;
242
+ }
243
+ subscribe(stream) {
244
+ this.check();
245
+ let set = this.#subscriptions.get(stream);
246
+ if (!set) {
247
+ set = new Set();
248
+ this.#subscriptions.set(stream, set);
249
+ }
250
+ const sub = new ChangeSubscription(() => {
251
+ set.delete(sub);
252
+ if (set.size === 0)
253
+ this.#subscriptions.delete(stream);
254
+ });
255
+ set.add(sub);
256
+ return sub;
257
+ }
258
+ close() {
259
+ if (this.#callback)
260
+ throw invalid('host callback cannot reenter Store');
261
+ this.#closed = true;
262
+ for (const set of this.#subscriptions.values())
263
+ for (const sub of [...set])
264
+ sub.close();
265
+ return Promise.allSettled([...this.#pending]).then(() => { });
266
+ }
267
+ }
268
+ export class ChangeSubscription {
269
+ release;
270
+ #hint = true;
271
+ #closed = false;
272
+ #waiters = [];
273
+ constructor(release) {
274
+ this.release = release;
275
+ }
276
+ signal() {
277
+ if (this.#closed)
278
+ return;
279
+ if (this.#waiters.length) {
280
+ const waiters = this.#waiters.splice(0);
281
+ for (const resolve of waiters)
282
+ resolve(true);
283
+ }
284
+ else
285
+ this.#hint = true;
286
+ }
287
+ drain() { const hint = this.#hint; this.#hint = false; return hint; }
288
+ wait() {
289
+ if (this.#closed)
290
+ return Promise.resolve(false);
291
+ if (this.drain())
292
+ return Promise.resolve(true);
293
+ return new Promise(resolve => this.#waiters.push(resolve));
294
+ }
295
+ close() {
296
+ if (this.#closed)
297
+ return;
298
+ this.#closed = true;
299
+ this.#hint = false;
300
+ this.release();
301
+ for (const resolve of this.#waiters.splice(0))
302
+ resolve(false);
303
+ }
304
+ }
305
+ function appTable(table) {
306
+ if (table.length > 64 || !(table.startsWith('lody_') || table.startsWith('app_')) || !/^[a-z0-9_]+$/.test(table))
307
+ throw invalid('index table');
308
+ return table;
309
+ }
310
+ export class Stream {
311
+ store;
312
+ id;
313
+ constructor(store, id) {
314
+ this.store = store;
315
+ this.id = id;
316
+ }
317
+ space(table) { return `roost-ts-v1:${encodeUtf8(this.id).length}:${this.id}:${table}`; }
318
+ /** Unsigned, local derived state. Only actual selected changes emit events. */
319
+ async compareAndWriteIndex(expected, changes, options) {
320
+ if (expected.length > 1001 || changes.length > 1001 || (options?.eventKeys?.length ?? 0) > 1001)
321
+ throw invalid('index batch too large');
322
+ const copy = (row) => ({ table: appTable(row.table), key: row.key.slice(), value: row.value?.slice() ?? null });
323
+ const reads = expected.map(copy), writes = changes.map(copy), s = this;
324
+ const events = new Map((options?.eventKeys ?? []).map(k => [`${appTable(k.table)}:${hex(k.key)}`, { table: k.table, key: k.key.slice() }]));
325
+ const result = await s.store.run(true, s.id, function* (tx) {
326
+ for (const row of reads) {
327
+ const actual = (yield* tx.get(s.space(row.table), row.key)) ?? null;
328
+ if (actual === null ? row.value !== null : row.value === null || !equal(actual, row.value))
329
+ return { committed: false, notify: false };
330
+ }
331
+ const previous = new Map();
332
+ for (const [id, key] of events) {
333
+ if (!writes.some(row => row.table === key.table && equal(row.key, key.key)))
334
+ throw invalid('event key is not changed by index batch');
335
+ previous.set(id, yield* tx.get(s.space(key.table), key.key));
336
+ }
337
+ for (const row of writes) {
338
+ if (row.value === null)
339
+ yield* tx.delete(s.space(row.table), row.key);
340
+ else
341
+ yield* tx.put(s.space(row.table), row.key, row.value);
342
+ }
343
+ let notify = false;
344
+ for (const [id, key] of events) {
345
+ const before = previous.get(id), after = yield* tx.get(s.space(key.table), key.key);
346
+ if (before === undefined ? after !== undefined : after === undefined || !equal(before, after)) {
347
+ yield* s.append(tx, 'events', encodeEvent({ kind: 'indexChanged', table: key.table, key: key.key }));
348
+ notify = true;
349
+ }
350
+ }
351
+ return { committed: true, notify };
352
+ }, result => result.notify);
353
+ return result.committed;
354
+ }
355
+ async scanIndex(table, start, limit) {
356
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1001)
357
+ throw invalid('index scan limit');
358
+ const space = this.space(appTable(table)), copied = start.slice();
359
+ const rows = await this.store.run(false, this.id, function* (tx) { return yield* tx.scan(space, copied, undefined, limit); });
360
+ return rows.map(([key, value]) => ({ key, value }));
361
+ }
362
+ async scanIndexReverse(table, end, limit) {
363
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1001)
364
+ throw invalid('index scan limit');
365
+ const space = this.space(appTable(table)), copied = end ? end.slice() : undefined;
366
+ const rows = await this.store.run(false, this.id, function* (tx) { return yield* tx.scanReverse(space, copied, limit); });
367
+ return rows.map(([key, value]) => ({ key, value }));
368
+ }
369
+ writer(identity) { this.store.check(); return new Writer(this, identity); }
370
+ *header(tx, id) { const b = yield* tx.get(this.space('turns'), id); return b === undefined ? undefined : decodeHeader(b, id); }
371
+ *counter(tx, name) { const b = yield* tx.get(this.space('meta'), encodeUtf8(name)); return b === undefined ? 0n : read64(b); }
372
+ *append(tx, table, value) {
373
+ const old = yield* this.counter(tx, table);
374
+ if (old === U64_MAX)
375
+ throw corrupt('cursor overflow');
376
+ const next = old + 1n;
377
+ yield* tx.put(this.space(table), key64(next), value);
378
+ yield* tx.put(this.space('meta'), encodeUtf8(table), key64(next));
379
+ return next;
380
+ }
381
+ *reject(tx, raw, e) { yield* this.append(tx, 'events', encodeEvent({ kind: 'rejected', digest: blake3(raw), reason: e.message })); }
382
+ *observe(tx, id) {
383
+ const k = encodeUtf8('max_id'), prior = yield* tx.get(this.space('meta'), k);
384
+ if (prior) {
385
+ try {
386
+ checkTurnId(prior);
387
+ }
388
+ catch {
389
+ throw corrupt('invalid maximum ID');
390
+ }
391
+ }
392
+ if (!prior || compare(prior, id) < 0)
393
+ yield* tx.put(this.space('meta'), k, id);
394
+ }
395
+ *turn(tx, id) {
396
+ const h = yield* this.header(tx, id);
397
+ if (!h)
398
+ return undefined;
399
+ return yield* this.turnFromHeader(tx, id, h);
400
+ }
401
+ *turnFromHeader(tx, id, h) {
402
+ const p = new Projection(tx, this.space('projection'), id, h.layout);
403
+ const { layout, ...rest } = h;
404
+ return { ...rest, content: yield* p.read(layout.root) };
405
+ }
406
+ *ancestors(tx, parents) {
407
+ const stack = [...parents], verified = new Set();
408
+ while (stack.length) {
409
+ const ref = stack.pop(), key = hex(ref.id) + hex(ref.hash);
410
+ if (verified.has(key))
411
+ continue;
412
+ const h = yield* this.header(tx, ref.id);
413
+ if (!h)
414
+ throw new StoreError('pending');
415
+ if (!h.sealed || !equal(h.sealed, ref.hash))
416
+ throw invalid('parent hash mismatch');
417
+ if (!h.hashVerified) {
418
+ const p = new Projection(tx, this.space('projection'), h.turnId, h.layout), content = yield* p.read(h.layout.root);
419
+ if (!equal(nodeHash(this.id, h.turnId, h.owner, h.parents, content), ref.hash))
420
+ throw invalid('ancestor hash mismatch');
421
+ stack.push(...h.parents);
422
+ }
423
+ verified.add(key);
424
+ }
425
+ }
426
+ /** N3: the local-seal chain check — like `ancestors` but returns
427
+ * `false` instead of throwing on a missing ancestor (a partial
428
+ * boundary): the reply seals cryptographically regardless, and
429
+ * `hashVerified` says honestly whether the whole chain is locally
430
+ * verified. A conflicting claim (hash mismatch on a present turn)
431
+ * stays a typed error. Mirror of `chain_fully_verified` in
432
+ * src/store.rs. */
433
+ /** N017 P1-A: recompute one stored turn's body and compare it with its
434
+ * persisted seal hash. `false` means the local bytes contradict the
435
+ * admitted seal (only reachable when an earlier import skipped hash
436
+ * recomputation): the caller must not promote the turn. Mirror of
437
+ * `body_matches_seal` in src/store.rs. */
438
+ *bodyMatchesSeal(tx, h) {
439
+ if (h.sealed === null)
440
+ return false;
441
+ const p = new Projection(tx, this.space('projection'), h.turnId, h.layout), content = yield* p.read(h.layout.root);
442
+ return equal(nodeHash(this.id, h.turnId, h.owner, h.parents, content), h.sealed);
443
+ }
444
+ *chainFullyVerified(tx, parents) {
445
+ const stack = [...parents], verified = new Set();
446
+ while (stack.length) {
447
+ const ref = stack.pop(), key = hex(ref.id) + hex(ref.hash);
448
+ if (verified.has(key))
449
+ continue;
450
+ const h = yield* this.header(tx, ref.id);
451
+ if (!h)
452
+ return false;
453
+ if (!h.sealed || !equal(h.sealed, ref.hash))
454
+ throw invalid('parent hash mismatch');
455
+ if (!h.hashVerified) {
456
+ const p = new Projection(tx, this.space('projection'), h.turnId, h.layout), content = yield* p.read(h.layout.root);
457
+ if (!equal(nodeHash(this.id, h.turnId, h.owner, h.parents, content), ref.hash))
458
+ throw invalid('ancestor hash mismatch');
459
+ stack.push(...h.parents);
460
+ }
461
+ verified.add(key);
462
+ }
463
+ return true;
464
+ }
465
+ /** Semantic preparation performs no persistent writes. The returned program must not be caught as a frame rejection. */
466
+ *prepare(tx, u, raw, origin, admission = 'full', conflicts = []) {
467
+ const key = updateKey(u.turnId, u.seq), pending = yield* tx.get(this.space('pending'), key);
468
+ if (pending && !equal(pending, raw))
469
+ throw new StoreError('conflict');
470
+ let h = yield* this.header(tx, u.turnId);
471
+ const op = u.operation;
472
+ if (op.kind === 'create') {
473
+ if (h)
474
+ throw new StoreError('conflict');
475
+ if (u.seq !== 0n)
476
+ throw invalid('create sequence must be zero');
477
+ let prior;
478
+ for (const ref of op.parents) {
479
+ syntax(() => checkTurnId(ref.id));
480
+ if (compare(ref.id, u.turnId) >= 0 || (prior && compare(prior, ref.id) >= 0))
481
+ throw invalid('parents must be sorted unique and older');
482
+ prior = ref.id;
483
+ if (admission === 'full') {
484
+ const parent = yield* this.header(tx, ref.id);
485
+ if (!parent?.sealed)
486
+ throw new StoreError('pending');
487
+ if (!equal(parent.sealed, ref.hash))
488
+ throw invalid('parent hash mismatch');
489
+ }
490
+ // Partial admission (N3): parents are DECLARED references
491
+ // (their turns need not be local); the turn's seal binds
492
+ // id+hash cryptographically, and the backfill reconcile
493
+ // checks the claim when the parent arrives.
494
+ }
495
+ }
496
+ else if (!h)
497
+ throw new StoreError('pending');
498
+ if (h && !equal(h.owner, u.owner))
499
+ throw new StoreError('unauthorized', 'owner mismatch');
500
+ if (h?.sealed)
501
+ throw new StoreError('sealed');
502
+ const next = h?.nextSeq ?? 0n;
503
+ if (u.seq > next)
504
+ throw new StoreError('pending');
505
+ if (u.seq < next)
506
+ throw new StoreError('stale');
507
+ const p = new Projection(tx, this.space('projection'), u.turnId, h?.layout);
508
+ let root = h ? h.layout.root : yield* p.build(op.kind === 'create' ? op.content : null);
509
+ if (!h)
510
+ h = { turnId: u.turnId, owner: u.owner, parents: op.kind === 'create' ? op.parents : [], nextSeq: 0n, sealed: null, hashVerified: false, bodyVerified: false, layout: p.layout(root) };
511
+ if (op.kind === 'edit')
512
+ root = yield* p.edit(root, op.op);
513
+ if (op.kind === 'seal') {
514
+ if (origin === 'local' || this.store.options.verifyHashIntegrity) {
515
+ const content = yield* p.read(root);
516
+ if (!equal(nodeHash(this.id, u.turnId, u.owner, h.parents, content), op.hash))
517
+ throw invalid('seal hash mismatch');
518
+ // The body really matches the sealed hash: this turn is now
519
+ // self-verified regardless of how far its ancestry is known.
520
+ h.bodyVerified = true;
521
+ if (origin === 'local') {
522
+ // N3 reply path: verify the chain as far as locally
523
+ // possible. `hashVerified` is set only when every
524
+ // ancestor is locally verified — a partial boundary
525
+ // stops at `false`, honestly; a conflicting claim stays
526
+ // a typed error.
527
+ h.hashVerified = yield* this.chainFullyVerified(tx, h.parents);
528
+ }
529
+ else if (admission === 'full') {
530
+ yield* this.ancestors(tx, h.parents);
531
+ h.hashVerified = true;
532
+ }
533
+ else {
534
+ // This turn only; a parentless turn's chain is
535
+ // trivially complete, anything more is unknown and
536
+ // never claimed.
537
+ h.hashVerified = h.parents.length === 0;
538
+ }
539
+ }
540
+ h.sealed = op.hash;
541
+ }
542
+ if (next === U64_MAX)
543
+ throw invalid('sequence overflow');
544
+ h.nextSeq = next + 1n;
545
+ h.layout = p.layout(root);
546
+ if (root.depth > 127)
547
+ throw invalid('json too deep');
548
+ if (turnBytes(h) > MAX_FRAME)
549
+ throw invalid('turn exceeds prototype size limit');
550
+ const encoded = encodeHeader(h), s = this;
551
+ const declaredParents = op.kind === 'create' && admission === 'partial' ? op.parents : undefined;
552
+ return (function* () {
553
+ yield* p.flush();
554
+ // N3: a partial Create persists its declared parents (the claim
555
+ // later arrivals reconcile against).
556
+ if (declaredParents?.length) {
557
+ const record = encodeUtf8(JSON.stringify([1, declaredParents.map(ref => [hex(ref.id), hex(ref.hash)])]));
558
+ yield* tx.put(s.space('partial_v1'), u.turnId, record);
559
+ for (const ref of declaredParents)
560
+ yield* tx.put(s.space('partial_parents'), cat(ref.id, u.turnId), ref.hash);
561
+ }
562
+ // N3 backfill reconcile: this seal may be a parent children
563
+ // declared — every claim is checked, mismatches are persistent
564
+ // diagnostics, never silent.
565
+ if (op.kind === 'seal')
566
+ for (const [indexKey, declared] of yield* tx.scan(s.space('partial_parents'), u.turnId, endPrefix(u.turnId), ALL)) {
567
+ if (indexKey.length !== 32 || declared.length !== 32)
568
+ throw corrupt('corrupt partial parent index');
569
+ if (!equal(declared, op.hash)) {
570
+ yield* tx.put(s.space('partial_conflicts'), indexKey, declared);
571
+ conflicts.push({ child: indexKey.slice(16), parent: u.turnId.slice(), declared: declared.slice(), actual: op.hash.slice() });
572
+ }
573
+ }
574
+ yield* tx.put(s.space('turns'), u.turnId, encoded);
575
+ yield* tx.put(s.space('updates'), key, raw);
576
+ yield* s.removePending(tx, key);
577
+ yield* s.observe(tx, u.turnId);
578
+ yield* s.append(tx, 'events', encodeEvent({ kind: 'changed', update: { turnId: u.turnId, seq: u.seq }, origin }));
579
+ if (origin === 'local')
580
+ yield* s.append(tx, 'outbox', raw);
581
+ })();
582
+ }
583
+ *indexParents(tx, u, insert) {
584
+ if (u.operation.kind === 'create')
585
+ for (const p of u.operation.parents) {
586
+ const k = cat(p.id, u.turnId);
587
+ if (insert)
588
+ yield* tx.put(this.space('parent_waiters'), k, empty);
589
+ else
590
+ yield* tx.delete(this.space('parent_waiters'), k);
591
+ }
592
+ }
593
+ *insertPending(tx, u, raw) { const total = yield* this.counter(tx, 'pending_bytes'); yield* tx.put(this.space('pending'), updateKey(u.turnId, u.seq), raw); yield* this.indexParents(tx, u, true); yield* tx.put(this.space('meta'), encodeUtf8('pending_bytes'), key64(total + BigInt(raw.length))); }
594
+ *removePending(tx, key) {
595
+ const raw = yield* tx.get(this.space('pending'), key);
596
+ if (!raw)
597
+ return;
598
+ const total = yield* this.counter(tx, 'pending_bytes');
599
+ if (total < BigInt(raw.length))
600
+ throw corrupt('pending byte underflow');
601
+ const u = this.persistedUpdate(raw, key);
602
+ yield* this.indexParents(tx, u, false);
603
+ yield* tx.delete(this.space('pending'), key);
604
+ yield* tx.put(this.space('meta'), encodeUtf8('pending_bytes'), key64(total - BigInt(raw.length)));
605
+ }
606
+ persistedUpdate(raw, key) {
607
+ try {
608
+ const u = decodeFrame(raw);
609
+ if (!equal(updateKey(u.turnId, u.seq), key))
610
+ throw Error();
611
+ return u;
612
+ }
613
+ catch (e) {
614
+ throw corrupt('corrupt pending update');
615
+ }
616
+ }
617
+ *drain(tx, seeds, applied, admission = 'full', conflicts = []) {
618
+ const queue = [], queued = new Set();
619
+ const push = (id) => {
620
+ const k = hex(id);
621
+ if (!queued.has(k)) {
622
+ queued.add(k);
623
+ queue.push(id);
624
+ }
625
+ };
626
+ seeds.forEach(push);
627
+ for (let at = 0; at < queue.length; at++) {
628
+ const id = queue[at];
629
+ queued.delete(hex(id));
630
+ const h = yield* this.header(tx, id);
631
+ if (h?.sealed) {
632
+ for (const [key] of yield* tx.scan(this.space('parent_waiters'), id, endPrefix(id), ALL)) {
633
+ if (key.length !== 32)
634
+ throw corrupt('corrupt waiter');
635
+ push(key.slice(16));
636
+ }
637
+ for (const [key, raw] of yield* tx.scan(this.space('pending'), id, endPrefix(id), ALL)) {
638
+ yield* this.removePending(tx, key);
639
+ yield* this.reject(tx, raw, new StoreError('sealed'));
640
+ }
641
+ continue;
642
+ }
643
+ const seq = h?.nextSeq ?? 0n, key = updateKey(id, seq), raw = yield* tx.get(this.space('pending'), key);
644
+ if (!raw)
645
+ continue;
646
+ const u = this.persistedUpdate(raw, key);
647
+ const allowed = this.store.authorize(this.id, u.owner);
648
+ let persist, error;
649
+ if (!allowed)
650
+ error = new StoreError('unauthorized');
651
+ else
652
+ try {
653
+ persist = yield* this.prepare(tx, u, raw, 'remote', admission, conflicts);
654
+ }
655
+ catch (e) {
656
+ error = semantic(e);
657
+ if (!error)
658
+ throw e;
659
+ }
660
+ if (persist) {
661
+ yield* persist;
662
+ applied.push({ turnId: id, seq });
663
+ push(id);
664
+ }
665
+ else if (error?.code !== 'pending') {
666
+ yield* this.removePending(tx, key);
667
+ yield* this.reject(tx, raw, error);
668
+ }
669
+ }
670
+ }
671
+ async importBatch(bytes) {
672
+ return this.importInner(bytes, 'full');
673
+ }
674
+ /** N3 partial-replica admission (the reverse-history intake): frames
675
+ * are decoded, signature-verified and authorized exactly like the
676
+ * complete path, but a Create's parents are recorded as declared
677
+ * references (their turns need not be local — the seal's hash binds
678
+ * them cryptographically, and the backfill reconcile checks the claim
679
+ * when the parent arrives) and a Seal verifies this turn's content
680
+ * hash and signature only, never the ancestor chain. Levels are
681
+ * honest: nothing here sets `hashVerified` for a turn with parents.
682
+ * Mirror of `import_partial_batch` in src/store.rs. */
683
+ async importPartialBatch(bytes) {
684
+ return this.importInner(bytes, 'partial');
685
+ }
686
+ async importInner(bytes, admission) {
687
+ this.store.check();
688
+ const copy = bytes.slice();
689
+ let frames;
690
+ try {
691
+ frames = splitBatch(copy);
692
+ }
693
+ catch (e) {
694
+ const error = invalid(e instanceof Error ? e.message : String(e));
695
+ await this.store.run(true, this.id, tx => this.reject(tx, copy, error));
696
+ throw error;
697
+ }
698
+ const checked = frames.map(raw => {
699
+ let u;
700
+ try {
701
+ u = decodeFrame(raw);
702
+ checkTurnId(u.turnId);
703
+ if (!isValidOwner(u.owner))
704
+ throw Error('invalid owner');
705
+ if (u.operation.kind === 'seal' && !verifySealSignature(u.owner, u.operation.hash, u.signature))
706
+ throw Error('invalid seal signature');
707
+ }
708
+ catch (e) {
709
+ return invalid(e instanceof Error ? e.message : String(e));
710
+ }
711
+ return this.store.authorize(this.id, u.owner) ? u : new StoreError('unauthorized');
712
+ });
713
+ const s = this;
714
+ return this.store.run(true, this.id, function* (tx) {
715
+ const statuses = [], applied = [], conflicts = [];
716
+ for (let i = 0; i < frames.length; i++) {
717
+ const raw = frames[i], u = checked[i];
718
+ if (u instanceof StoreError) {
719
+ yield* s.reject(tx, raw, u);
720
+ statuses.push({ kind: 'rejected', reason: u.message });
721
+ continue;
722
+ }
723
+ const key = updateKey(u.turnId, u.seq), existing = yield* tx.get(s.space('updates'), key), pending = yield* tx.get(s.space('pending'), key), old = existing ?? pending;
724
+ if (old) {
725
+ if (equal(old, raw)) {
726
+ // N3 upgrade: a seal admitted partially (its chain
727
+ // never verified) is chain-verified NOW by the
728
+ // complete path when the ancestors are local — the
729
+ // real recursive check, never a label flip. Still
730
+ // missing ancestors simply keep the honest level.
731
+ if (admission === 'full' && existing && u.operation.kind === 'seal') {
732
+ const head = yield* s.header(tx, u.turnId);
733
+ if (head?.sealed && (!head.bodyVerified || !head.hashVerified)) {
734
+ // N017 P1-A: the chain check says nothing about
735
+ // THIS turn's stored body. A body admitted with
736
+ // hash recomputation off never matched the
737
+ // sealed hash, so it is re-verified here and
738
+ // only what that check proved is recorded.
739
+ let changed = false;
740
+ if (!head.bodyVerified && (yield* s.bodyMatchesSeal(tx, head))) {
741
+ head.bodyVerified = true;
742
+ changed = true;
743
+ }
744
+ if (head.bodyVerified && !head.hashVerified) {
745
+ try {
746
+ yield* s.ancestors(tx, head.parents);
747
+ head.hashVerified = true;
748
+ changed = true;
749
+ }
750
+ catch (e) {
751
+ if (!(e instanceof StoreError && e.code === 'pending'))
752
+ throw e;
753
+ }
754
+ }
755
+ if (changed) {
756
+ yield* tx.put(s.space('turns'), u.turnId, encodeHeader(head));
757
+ // A verification upgrade must wake local projections,
758
+ // although the wire operation remains a duplicate.
759
+ yield* s.append(tx, 'events', encodeEvent({ kind: 'changed', update: { turnId: u.turnId, seq: u.seq }, origin: 'remote' }));
760
+ }
761
+ }
762
+ }
763
+ statuses.push({ kind: existing ? 'duplicate' : 'pending' });
764
+ }
765
+ else {
766
+ const e = new StoreError('conflict');
767
+ yield* s.reject(tx, raw, e);
768
+ statuses.push({ kind: 'rejected', reason: e.message });
769
+ }
770
+ continue;
771
+ }
772
+ let persist, error;
773
+ try {
774
+ persist = yield* s.prepare(tx, u, raw, 'remote', admission, conflicts);
775
+ }
776
+ catch (e) {
777
+ error = semantic(e);
778
+ if (!error)
779
+ throw e;
780
+ }
781
+ if (persist) {
782
+ yield* persist;
783
+ statuses.push({ kind: 'applied' });
784
+ applied.push({ turnId: u.turnId, seq: u.seq });
785
+ }
786
+ // Pending admission quota: this reuse of MAX_BATCH (64 MiB, defined in
787
+ // ts/src/codec.ts) is the same contract value as PENDING_QUOTA_BYTES in
788
+ // src/store.rs; any change must be made in both languages together.
789
+ else if (error?.code === 'pending' && (yield* s.counter(tx, 'pending_bytes')) + BigInt(raw.length) <= BigInt(MAX_BATCH)) {
790
+ yield* s.insertPending(tx, u, raw);
791
+ yield* s.observe(tx, u.turnId);
792
+ statuses.push({ kind: 'pending' });
793
+ }
794
+ else {
795
+ if (error?.code === 'pending')
796
+ error = invalid(PENDING_QUOTA_REASON);
797
+ yield* s.reject(tx, raw, error);
798
+ statuses.push({ kind: 'rejected', reason: error.message });
799
+ }
800
+ }
801
+ yield* s.drain(tx, applied.map(u => u.turnId), applied, admission, conflicts);
802
+ const done = new Set(applied.map(u => hex(updateKey(u.turnId, u.seq))));
803
+ for (let i = 0; i < statuses.length; i++) {
804
+ const u = checked[i];
805
+ if (statuses[i].kind !== 'pending' || u instanceof StoreError)
806
+ continue;
807
+ const key = updateKey(u.turnId, u.seq);
808
+ if (done.has(hex(key)))
809
+ statuses[i] = { kind: 'applied' };
810
+ else if (!(yield* tx.get(s.space('pending'), key)))
811
+ statuses[i] = { kind: 'rejected', reason: 'dependency resolution rejected update; see events' };
812
+ }
813
+ return { statuses, applied, conflicts };
814
+ });
815
+ }
816
+ /** The verification level of one turn (N3, Spec §88): the display
817
+ * layer's contract. `ancestorsVerified` is exactly the existing
818
+ * `hashVerified` meaning; `selfVerified` requires this turn's stored
819
+ * body to have been checked against its seal (`bodyVerified` — a seal
820
+ * whose hash recomputation was skipped proves only the signature over
821
+ * the declared hash); stored-but-unsealed-or-unchecked is `provisional`;
822
+ * no record is `notRetrieved`. Mirror of `verification` in
823
+ * src/store.rs. */
824
+ async verification(id) {
825
+ const copied = idCopy(id), s = this;
826
+ const result = await this.store.run(false, this.id, function* (tx) {
827
+ return yield* s.headerResult(tx, copied);
828
+ });
829
+ const level = (turn) => turn.hashVerified ? 'ancestorsVerified' : turn.bodyVerified ? 'selfVerified' : 'provisional';
830
+ if (result.kind === 'found')
831
+ return level(result.turn);
832
+ if (result.kind === 'incomplete' && result.prefix)
833
+ return level(result.prefix);
834
+ return 'notRetrieved';
835
+ }
836
+ *readResultWithTurn(tx, id, turn) {
837
+ // A sealed turn cannot retain same-turn pending updates: sealing drains
838
+ // and rejects them, while admission rejects new updates after the seal.
839
+ const rows = turn?.sealed ? [] : yield* tx.scan(this.space('pending'), id, endPrefix(id), 1);
840
+ return rows.length ? { kind: 'incomplete', turnId: id, prefix: turn ?? null } : turn ? { kind: 'found', turn } : { kind: 'notFound', turnId: id };
841
+ }
842
+ *readResult(tx, id) { return yield* this.readResultWithTurn(tx, id, yield* this.turn(tx, id)); }
843
+ async readTurn(id) { const copied = idCopy(id); return this.store.run(false, this.id, tx => this.readResult(tx, copied)); }
844
+ async readTurns(ids) {
845
+ const copies = ids.map(idCopy), s = this;
846
+ return this.store.run(false, this.id, function* (tx) {
847
+ const out = [];
848
+ for (const id of copies)
849
+ out.push(yield* s.readResult(tx, id));
850
+ return out;
851
+ });
852
+ }
853
+ async scanTurns(query) {
854
+ const start = query.start ? idCopy(query.start) : empty, end = query.end ? idCopy(query.end) : undefined, n = limit(query.limit), s = this;
855
+ return this.store.run(false, this.id, function* (tx) {
856
+ const out = [];
857
+ for (const [id, value] of yield* tx.scan(s.space('turns'), start, end, n)) {
858
+ const turn = yield* s.turnFromHeader(tx, id, decodeHeader(value, id));
859
+ out.push(yield* s.readResultWithTurn(tx, id, turn));
860
+ }
861
+ return out;
862
+ });
863
+ }
864
+ readStream() { return this.scanTurns({ limit: ALL }); }
865
+ /** The header-level tri-state read, mirroring `readResult` without ever
866
+ * materializing content (G026): the header row plus the one-row pending
867
+ * probe only. */
868
+ *headerResult(tx, id) { return yield* this.headerResultWithHeader(tx, id, yield* this.header(tx, id)); }
869
+ *headerResultWithHeader(tx, id, header) {
870
+ // Mirror the Rust fast path: sealed turns cannot have pending rows.
871
+ const rows = header?.sealed ? [] : yield* tx.scan(this.space('pending'), id, endPrefix(id), 1);
872
+ const h = header ? { turnId: header.turnId, owner: header.owner, parents: header.parents, nextSeq: header.nextSeq, sealed: header.sealed, hashVerified: header.hashVerified, bodyVerified: header.bodyVerified } : null;
873
+ return rows.length ? { kind: 'incomplete', turnId: id, prefix: h } : h ? { kind: 'found', turn: h } : { kind: 'notFound', turnId: id };
874
+ }
875
+ /** One Turn's header with the same tri-state as `readTurn`, never reading
876
+ * content (discovery and other metadata-only consumers must not pay for
877
+ * the projection). */
878
+ async readTurnHeader(id) { const copied = idCopy(id); return this.store.run(false, this.id, tx => this.headerResult(tx, copied)); }
879
+ /** Forward keyset page of Turn headers in ascending TurnID order,
880
+ * strictly newer than `after` (exclusive — the same keyset discipline as
881
+ * `turnHeadersBefore`, mirrored). `after === undefined` pages from the
882
+ * beginning. `n === 0` returns empty; larger `n` clamps to
883
+ * MAX_PAGE_HEADERS (the clamp bounds RETURNED rows, so a full page never
884
+ * ends a continuation early). Each row carries the tri-state; the content
885
+ * projection is never read. */
886
+ async turnHeadersAfter(after, n) {
887
+ const capped = Math.min(limit(n), MAX_PAGE_HEADERS);
888
+ if (capped === 0)
889
+ return [];
890
+ const s = this;
891
+ return this.store.run(false, this.id, function* (tx) {
892
+ // The scan start is inclusive at the storage layer: one extra row
893
+ // covers the `after` row itself, which is dropped below.
894
+ const begin = after ? idCopy(after) : empty;
895
+ const out = [];
896
+ for (const [key, value] of yield* tx.scan(s.space('turns'), begin, undefined, capped + (after === undefined ? 0 : 1))) {
897
+ if (after !== undefined && compare(key, after) === 0)
898
+ continue;
899
+ out.push(yield* s.headerResultWithHeader(tx, key, decodeHeader(value, key)));
900
+ if (out.length >= capped)
901
+ break;
902
+ }
903
+ return out;
904
+ });
905
+ }
906
+ /** One reverse keyset page of lightweight headers. A single bounded
907
+ * scanReverse decodes each returned per-turn row in place; content lives
908
+ * in projection blocks and is never read for a header page. */
909
+ *pageHeaders(tx, end, n) {
910
+ const rows = yield* tx.scanReverse(this.space('turns'), end, n);
911
+ return rows.map(([key, value]) => {
912
+ const h = decodeHeader(value, key);
913
+ return { turnId: h.turnId, owner: h.owner, parents: h.parents, nextSeq: h.nextSeq, sealed: h.sealed, hashVerified: h.hashVerified, bodyVerified: h.bodyVerified };
914
+ });
915
+ }
916
+ /** Newest `n` Turn headers in descending TurnID order; `n === 0` returns
917
+ * empty, larger `n` clamps to MAX_PAGE_HEADERS. Pages are per-request
918
+ * snapshots: re-fetch after change notifications (subscribeChanges). */
919
+ async latestTurnHeaders(n) {
920
+ const capped = Math.min(limit(n), MAX_PAGE_HEADERS);
921
+ if (capped === 0)
922
+ return [];
923
+ const s = this;
924
+ return this.store.run(false, this.id, function* (tx) { return yield* s.pageHeaders(tx, undefined, capped); });
925
+ }
926
+ /** Keyset page of headers strictly older than `before` (exclusive) in
927
+ * descending TurnID order; `before` need not exist. A late-arriving older
928
+ * Turn lands in its byte-order position on the next request; pages are not
929
+ * live-merged. */
930
+ async turnHeadersBefore(before, n) {
931
+ const end = idCopy(before), capped = Math.min(limit(n), MAX_PAGE_HEADERS);
932
+ if (capped === 0)
933
+ return [];
934
+ const s = this;
935
+ return this.store.run(false, this.id, function* (tx) { return yield* s.pageHeaders(tx, end, capped); });
936
+ }
937
+ async readValue(id, path) {
938
+ const copied = idCopy(id), p = structuredClone(path), s = this;
939
+ return this.store.run(false, this.id, function* (tx) {
940
+ const h = yield* s.header(tx, copied);
941
+ if (!h)
942
+ throw new StoreError('pending');
943
+ const projection = new Projection(tx, s.space('projection'), copied, h.layout);
944
+ try {
945
+ return { value: yield* projection.read(yield* projection.resolve(h.layout.root, p)), nextSeq: h.nextSeq };
946
+ }
947
+ catch (e) {
948
+ throw semantic(e) ?? e;
949
+ }
950
+ });
951
+ }
952
+ async readText(id, path, start, end) {
953
+ const copied = idCopy(id), p = structuredClone(path), s = this;
954
+ u64(start);
955
+ u64(end);
956
+ return this.store.run(false, this.id, function* (tx) {
957
+ const h = yield* s.header(tx, copied);
958
+ if (!h)
959
+ throw new StoreError('pending');
960
+ const projection = new Projection(tx, s.space('projection'), copied, h.layout);
961
+ try {
962
+ return { text: yield* projection.readText(h.layout.root, p, start, end), nextSeq: h.nextSeq };
963
+ }
964
+ catch (e) {
965
+ throw semantic(e) ?? e;
966
+ }
967
+ });
968
+ }
969
+ snapshot() {
970
+ const s = this;
971
+ return this.store.run(false, this.id, function* (tx) {
972
+ const turns = [];
973
+ for (const [id, value] of yield* tx.scan(s.space('turns'), empty, undefined, ALL)) {
974
+ const turn = yield* s.turnFromHeader(tx, id, decodeHeader(value, id));
975
+ turns.push(yield* s.readResultWithTurn(tx, id, turn));
976
+ }
977
+ return { turns, eventCursor: yield* s.counter(tx, 'events') };
978
+ });
979
+ }
980
+ async eventsAfter(after, n) {
981
+ u64(after);
982
+ limit(n);
983
+ const s = this;
984
+ return this.store.run(false, this.id, function* (tx) {
985
+ if (after === U64_MAX)
986
+ return [];
987
+ return (yield* tx.scan(s.space('events'), key64(after + 1n), undefined, n)).map(([k, v]) => ({ cursor: read64(k), event: decodeEvent(v) }));
988
+ });
989
+ }
990
+ async pendingTurns(after, n) {
991
+ limit(n);
992
+ const copied = after ? idCopy(after) : undefined, s = this;
993
+ return this.store.run(false, this.id, function* (tx) {
994
+ const ids = [];
995
+ let start = copied ? endPrefix(copied) : empty;
996
+ while (start && ids.length < n) {
997
+ const row = (yield* tx.scan(s.space('pending'), start, undefined, 1))[0];
998
+ if (!row)
999
+ break;
1000
+ if (row[0].length !== 24)
1001
+ throw corrupt('invalid pending key');
1002
+ const id = idCopy(row[0].slice(0, 16));
1003
+ ids.push(id);
1004
+ start = endPrefix(id);
1005
+ }
1006
+ return ids;
1007
+ });
1008
+ }
1009
+ async missingDependencies(ids) {
1010
+ const copies = ids.map(idCopy), s = this;
1011
+ return this.store.run(false, this.id, function* (tx) {
1012
+ const out = [];
1013
+ for (const turnId of copies) {
1014
+ const h = yield* s.header(tx, turnId), nextSeq = h?.nextSeq ?? 0n, sequences = [], parents = [];
1015
+ let cursor = nextSeq;
1016
+ for (const [key, raw] of yield* tx.scan(s.space('pending'), turnId, endPrefix(turnId), ALL)) {
1017
+ const u = s.persistedUpdate(raw, key);
1018
+ if (u.seq > cursor)
1019
+ sequences.push({ start: cursor, end: u.seq });
1020
+ cursor = u.seq === U64_MAX ? U64_MAX : u.seq + 1n;
1021
+ if (u.operation.kind === 'create')
1022
+ for (const p of u.operation.parents)
1023
+ if (!(yield* s.header(tx, p.id))?.sealed)
1024
+ parents.push(p);
1025
+ }
1026
+ out.push({ turnId, nextSeq, sequences, parents });
1027
+ }
1028
+ return out;
1029
+ });
1030
+ }
1031
+ async exportUpdates(id, fromSeq, n) {
1032
+ const copied = idCopy(id);
1033
+ u64(fromSeq);
1034
+ limit(n);
1035
+ if (n === 0 || n > MAX_UPDATES)
1036
+ throw invalid('export count limit');
1037
+ const s = this, frames = await this.store.run(false, this.id, function* (tx) { return (yield* tx.scan(s.space('updates'), updateKey(copied, fromSeq), endPrefix(copied), n)).map(([, v]) => v); });
1038
+ return syntax(() => assembleFrames(frames));
1039
+ }
1040
+ async exportTurns(ids) {
1041
+ const copies = ids.map(idCopy), s = this;
1042
+ const frames = await this.store.run(false, this.id, function* (tx) {
1043
+ const out = [];
1044
+ let size = 0;
1045
+ for (const id of copies)
1046
+ for (const [, raw] of yield* tx.scan(s.space('updates'), id, endPrefix(id), MAX_UPDATES + 1)) {
1047
+ size += raw.length + varSize(raw.length);
1048
+ out.push(raw);
1049
+ if (out.length > MAX_UPDATES || 4 + varSize(out.length) + size > MAX_BATCH)
1050
+ throw invalid('export batch ceiling');
1051
+ }
1052
+ return out;
1053
+ });
1054
+ return syntax(() => assembleFrames(frames));
1055
+ }
1056
+ subscribeChanges() { return this.store.subscribe(this.id); }
1057
+ async watch() {
1058
+ const subscription = this.subscribeChanges();
1059
+ try {
1060
+ return { snapshot: await this.snapshot(), subscription };
1061
+ }
1062
+ catch (e) {
1063
+ subscription.close();
1064
+ throw e;
1065
+ }
1066
+ }
1067
+ subscribeOutgoing(consumer) { this.store.check(); return new OutgoingSubscription(this, namespace(consumer)); }
1068
+ }
1069
+ export class Writer {
1070
+ stream;
1071
+ identity;
1072
+ constructor(stream, identity) {
1073
+ this.stream = stream;
1074
+ this.identity = identity;
1075
+ }
1076
+ create(parents, content) { return this.writeBatch([{ kind: 'create', parents, content }]); }
1077
+ edit(turnId, expectedNextSeq, ops) { return this.writeBatch([{ kind: 'edit', turnId, expectedNextSeq, ops }]); }
1078
+ seal(turnId, expectedNextSeq) { return this.writeBatch([{ kind: 'seal', turnId, expectedNextSeq }]); }
1079
+ async writeBatch(writes, indexPuts, expectedEventCursor) {
1080
+ return this.writeBatchInternal(writes, expectedEventCursor === undefined ? undefined : u64(expectedEventCursor), indexPuts);
1081
+ }
1082
+ /** Local retry identity, scoped to this stream and signer. Receipt and Create
1083
+ * commit together; this is not cross-author business-key deduplication. */
1084
+ async createOnce(key, parents, content, expectedEventCursor) {
1085
+ if (!(key instanceof Uint8Array) || key.length === 0 || key.length > 4096)
1086
+ throw invalid('createOnce key size');
1087
+ const result = await this.writeBatchInternal([{ kind: 'createOnce', key: key.slice(), parents, content }], expectedEventCursor === undefined ? undefined : u64(expectedEventCursor));
1088
+ return { turnId: result.updates[0].turnId, created: result.created };
1089
+ }
1090
+ async writeBatchInternal(writes, expectedEventCursor, indexPuts) {
1091
+ const s = this.stream, identity = this.identity;
1092
+ s.store.check();
1093
+ // Own the event payload and row before this operation queues for IDB.
1094
+ const puts = (indexPuts ?? []).map(put => {
1095
+ if (put.emitEvent !== undefined && typeof put.emitEvent !== 'boolean')
1096
+ throw invalid('index emitEvent');
1097
+ return { ...put, table: appTable(put.table), key: put.key.slice(), value: put.value.slice(), onceKey: put.onceKey?.slice() };
1098
+ });
1099
+ const owner = identity.owner(), expanded = [], dummy = new Uint8Array(16);
1100
+ dummy[6] = 0x70;
1101
+ dummy[8] = 0x80;
1102
+ const onceDigestOf = (parents, content) => blake3(encodeFrame({ turnId: dummy, seq: 0n, owner,
1103
+ operation: { kind: 'create', parents: [...parents].sort((a, b) => compare(a.id, b.id)), content } }));
1104
+ // Roundtrip caller values before opening/queueing IDB; this both validates and owns all nested data.
1105
+ for (const w of writes) {
1106
+ if (w.kind === 'create' || w.kind === 'createOnce') {
1107
+ const u = syntax(() => decodeFrame(encodeFrame({ turnId: dummy, seq: 0n, owner, operation: { kind: 'create', parents: w.parents, content: w.content } })));
1108
+ if (u.operation.kind !== 'create')
1109
+ throw invalid('create');
1110
+ if (w.kind === 'createOnce') {
1111
+ if (!(w.key instanceof Uint8Array) || w.key.length === 0 || w.key.length > 4096)
1112
+ throw invalid('createOnce key size');
1113
+ expanded.push({ kind: 'createOnce', key: w.key.slice(), parents: u.operation.parents, content: u.operation.content });
1114
+ }
1115
+ else
1116
+ expanded.push(u.operation);
1117
+ }
1118
+ else if (w.kind === 'edit' || w.kind === 'editOnce') {
1119
+ if (!w.ops.length)
1120
+ throw invalid('empty edit');
1121
+ const seq = u64(w.expectedNextSeq);
1122
+ const turnId = w.kind === 'edit' ? idCopy(w.turnId) : undefined;
1123
+ const key = w.kind === 'editOnce' ? w.key.slice() : undefined;
1124
+ for (let i = 0; i < w.ops.length; i++) {
1125
+ const n = u64(seq + BigInt(i));
1126
+ const frameId = turnId ?? dummy;
1127
+ const u = syntax(() => decodeFrame(encodeFrame({ turnId: frameId, seq: n, owner, operation: { kind: 'edit', op: w.ops[i] } })));
1128
+ if (u.operation.kind !== 'edit')
1129
+ throw invalid('edit');
1130
+ if (w.kind === 'editOnce')
1131
+ expanded.push({ kind: 'editOnce', key: key, expectedNextSeq: n, ops: [u.operation.op] });
1132
+ else
1133
+ expanded.push({ kind: 'edit', turnId: turnId, expectedNextSeq: n, ops: [u.operation.op] });
1134
+ if (expanded.length > MAX_UPDATES)
1135
+ throw invalid('write batch too large');
1136
+ }
1137
+ }
1138
+ else if (w.kind === 'seal')
1139
+ expanded.push({ kind: 'seal', turnId: idCopy(w.turnId), expectedNextSeq: u64(w.expectedNextSeq) });
1140
+ else if (w.kind === 'sealOnce') {
1141
+ if (!(w.key instanceof Uint8Array) || w.key.length === 0 || w.key.length > 4096)
1142
+ throw invalid('createOnce key size');
1143
+ expanded.push({ kind: 'sealOnce', key: w.key.slice(), expectedNextSeq: u64(w.expectedNextSeq) });
1144
+ }
1145
+ else
1146
+ throw invalid('write kind');
1147
+ if (expanded.length > MAX_UPDATES)
1148
+ throw invalid('write batch too large');
1149
+ }
1150
+ if (!s.store.authorize(s.id, owner))
1151
+ throw new StoreError('unauthorized');
1152
+ return s.store.run(true, s.id, function* (tx) {
1153
+ if (expectedEventCursor !== undefined && (yield* s.counter(tx, 'events')) !== expectedEventCursor)
1154
+ throw new StoreError('stale', 'history changed during discovery');
1155
+ const onceIds = new Map();
1156
+ const resolveOnce = function* (key) {
1157
+ const hit = onceIds.get(hex(key));
1158
+ if (hit)
1159
+ return hit.slice();
1160
+ const prior = yield* tx.get(s.space('create_once_v1'), cat(owner, key));
1161
+ if (!prior || prior.length !== 49 || prior[0] !== 1)
1162
+ throw invalid('createOnce key missing');
1163
+ return idCopy(prior.slice(33));
1164
+ };
1165
+ const applyUpdate = function* (u) {
1166
+ const raw = syntax(() => encodeFrame(u));
1167
+ syntax(() => decodeFrame(raw));
1168
+ let persist;
1169
+ try {
1170
+ persist = yield* s.prepare(tx, u, raw, 'local');
1171
+ }
1172
+ catch (e) {
1173
+ throw semantic(e) ?? e;
1174
+ }
1175
+ yield* persist;
1176
+ return { turnId: u.turnId, seq: u.seq };
1177
+ };
1178
+ const applyCreate = function* (parents, content) {
1179
+ const seen = yield* tx.get(s.space('meta'), encodeUtf8('max_id'));
1180
+ if (seen) {
1181
+ try {
1182
+ checkTurnId(seen);
1183
+ }
1184
+ catch {
1185
+ throw corrupt('invalid maximum ID');
1186
+ }
1187
+ }
1188
+ const id = nextTurnId(s.store.host(s.store.options.clock), seen ?? null, () => s.store.host(s.store.options.randomBytes));
1189
+ return { turnId: id, seq: 0n, owner, operation: { kind: 'create', parents: [...parents].sort((a, b) => compare(a.id, b.id)), content } };
1190
+ };
1191
+ const applyEditOrSeal = function* (turnId, expectedNextSeq, kind, ops) {
1192
+ const h = yield* s.header(tx, turnId);
1193
+ if (!h)
1194
+ throw new StoreError('pending');
1195
+ if (h.nextSeq !== expectedNextSeq)
1196
+ throw new StoreError('stale');
1197
+ if (kind === 'edit')
1198
+ return { turnId, seq: expectedNextSeq, owner, operation: { kind: 'edit', op: ops[0] } };
1199
+ const p = new Projection(tx, s.space('projection'), turnId, h.layout), content = yield* p.read(h.layout.root), hash = nodeHash(s.id, turnId, h.owner, h.parents, content);
1200
+ return { turnId, seq: expectedNextSeq, owner, operation: { kind: 'seal', hash }, signature: identity.signHash(hash) };
1201
+ };
1202
+ const updates = [];
1203
+ const applied = [];
1204
+ let created = false;
1205
+ for (const w of expanded) {
1206
+ if (w.kind === 'createOnce') {
1207
+ const receiptKey = cat(owner, w.key), digest = onceDigestOf(w.parents, w.content);
1208
+ const prior = yield* tx.get(s.space('create_once_v1'), receiptKey);
1209
+ if (prior) {
1210
+ if (prior.length !== 49 || prior[0] !== 1)
1211
+ throw corrupt('invalid createOnce receipt');
1212
+ const id = idCopy(prior.slice(33));
1213
+ if (!equal(prior.slice(1, 33), digest))
1214
+ throw new StoreError('conflict', 'createOnce input changed');
1215
+ if (!(yield* s.header(tx, id)))
1216
+ throw corrupt('createOnce receipt has no Turn');
1217
+ onceIds.set(hex(w.key), id);
1218
+ updates.push({ turnId: id, seq: 0n });
1219
+ continue;
1220
+ }
1221
+ const u = yield* applyCreate(w.parents, w.content);
1222
+ updates.push(yield* applyUpdate(u));
1223
+ applied.push(u.turnId);
1224
+ onceIds.set(hex(w.key), u.turnId);
1225
+ yield* tx.put(s.space('create_once_v1'), receiptKey, cat(new Uint8Array([1]), digest, u.turnId));
1226
+ created = true;
1227
+ continue;
1228
+ }
1229
+ let turnId;
1230
+ if (w.kind === 'editOnce' || w.kind === 'sealOnce')
1231
+ turnId = yield* resolveOnce(w.key);
1232
+ else if (w.kind === 'create') {
1233
+ const u = yield* applyCreate(w.parents, w.content);
1234
+ updates.push(yield* applyUpdate(u));
1235
+ applied.push(u.turnId);
1236
+ continue;
1237
+ }
1238
+ else
1239
+ turnId = w.turnId;
1240
+ const u = yield* applyEditOrSeal(turnId, w.expectedNextSeq, w.kind === 'seal' || w.kind === 'sealOnce' ? 'seal' : 'edit', w.kind === 'edit' || w.kind === 'editOnce' ? w.ops : undefined);
1241
+ updates.push(yield* applyUpdate(u));
1242
+ applied.push(u.turnId);
1243
+ }
1244
+ yield* s.drain(tx, applied, []);
1245
+ for (const put of puts) {
1246
+ let key = put.key.slice(), value = put.value.slice();
1247
+ if (put.onceKey) {
1248
+ const id = yield* resolveOnce(put.onceKey);
1249
+ if (!key.length)
1250
+ key = id.slice();
1251
+ if (!value.length)
1252
+ value = id.slice();
1253
+ }
1254
+ const space = s.space(put.table);
1255
+ const prior = put.emitEvent ? yield* tx.get(space, key) : undefined;
1256
+ yield* tx.put(space, key, value);
1257
+ if (put.emitEvent && (!prior || !equal(prior, value)))
1258
+ yield* s.append(tx, 'events', encodeEvent({ kind: 'indexChanged', table: put.table, key }));
1259
+ }
1260
+ return { updates, created };
1261
+ });
1262
+ }
1263
+ }
1264
+ const receipts = new WeakMap();
1265
+ const preparedReceipts = new WeakMap();
1266
+ const senderMetaSpace = 'sender_pending_meta_v1';
1267
+ const senderBytesSpace = 'sender_pending_bytes_v1';
1268
+ function encodeSenderMetadata(m) {
1269
+ return encodeUtf8(JSON.stringify([1, m.from.toString(), m.through.toString(), m.count, [...m.digest]]));
1270
+ }
1271
+ function decodeSenderMetadata(bytes, raw) {
1272
+ try {
1273
+ const a = JSON.parse(decodeUtf8(bytes));
1274
+ if (!Array.isArray(a) || a.length !== 5 || a[0] !== 1 ||
1275
+ typeof a[1] !== 'string' || !/^(0|[1-9][0-9]*)$/.test(a[1]) ||
1276
+ typeof a[2] !== 'string' || !/^(0|[1-9][0-9]*)$/.test(a[2]) ||
1277
+ !Number.isSafeInteger(a[3]) || a[3] < 1 || a[3] > MAX_UPDATES ||
1278
+ !Array.isArray(a[4]) || a[4].length !== 32 || a[4].some((v) => typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > 255))
1279
+ throw Error();
1280
+ const m = { from: u64(BigInt(a[1])), through: u64(BigInt(a[2])), count: a[3], digest: Uint8Array.from(a[4]) };
1281
+ if (m.through <= m.from || m.through - m.from !== BigInt(m.count) ||
1282
+ splitBatch(raw).length !== m.count || !equal(blake3(raw), m.digest) || !equal(encodeSenderMetadata(m), bytes))
1283
+ throw Error();
1284
+ return m;
1285
+ }
1286
+ catch (cause) {
1287
+ throw new StoreError('corrupt', 'corrupt sender pending record', { cause });
1288
+ }
1289
+ }
1290
+ function preparedReceipt(outgoing, raw, metadata, receipt) {
1291
+ const original = receipt ?? Object.freeze({});
1292
+ if (!receipt)
1293
+ receipts.set(original, { store: outgoing.stream.store, stream: outgoing.stream.id, consumer: outgoing.consumer, from: metadata.from, through: metadata.through });
1294
+ // raw is owned by the read/candidate path and is never exposed directly.
1295
+ const token = Object.freeze({ bytes: () => raw.slice() });
1296
+ preparedReceipts.set(token, { receipt: original, metadata, bytes: raw });
1297
+ return token;
1298
+ }
1299
+ function preparedLimits(token, limits) {
1300
+ const value = preparedReceipts.get(token);
1301
+ if (!value)
1302
+ throw invalid('invalid prepared receipt');
1303
+ if (value.metadata.count > limits.maxUpdates || value.bytes.length > Math.min(limits.maxBytes, MAX_BATCH))
1304
+ throw invalid('pending batch exceeds batch limits');
1305
+ }
1306
+ export class OutgoingSubscription {
1307
+ stream;
1308
+ consumer;
1309
+ constructor(stream, consumer) {
1310
+ this.stream = stream;
1311
+ this.consumer = consumer;
1312
+ }
1313
+ async nextBatch(options) {
1314
+ const count = limit(options.maxUpdates), budget = Math.min(limit(options.maxBytes), MAX_BATCH);
1315
+ if (count === 0 || count > MAX_UPDATES)
1316
+ throw invalid('batch count limit');
1317
+ const s = this.stream, consumer = this.consumer;
1318
+ const selected = await s.store.run(false, s.id, function* (tx) {
1319
+ const old = yield* tx.get(s.space('consumers'), encodeUtf8(consumer)), from = old ? read64(old) : 0n;
1320
+ if (from === U64_MAX)
1321
+ return null;
1322
+ const frames = [];
1323
+ let through = from, size = 0;
1324
+ for (const [key, raw] of yield* tx.scan(s.space('outbox'), key64(from + 1n), undefined, count)) {
1325
+ const next = size + varSize(raw.length) + raw.length;
1326
+ if (4 + varSize(frames.length + 1) + next > budget) {
1327
+ if (!frames.length)
1328
+ throw invalid('next frame exceeds batch byte limit');
1329
+ break;
1330
+ }
1331
+ frames.push(raw);
1332
+ size = next;
1333
+ through = read64(key);
1334
+ }
1335
+ return frames.length ? { frames, from, through } : null;
1336
+ });
1337
+ if (!selected)
1338
+ return null;
1339
+ const receipt = Object.freeze({});
1340
+ receipts.set(receipt, { store: s.store, stream: s.id, consumer, from: selected.from, through: selected.through });
1341
+ return { updates: assembleFrames(selected.frames), receipt };
1342
+ }
1343
+ *consumerCursor(tx) {
1344
+ const raw = yield* tx.get(this.stream.space('consumers'), encodeUtf8(this.consumer));
1345
+ return raw === undefined ? 0n : read64(raw);
1346
+ }
1347
+ *readDurablePending(tx) {
1348
+ const s = this.stream, key = encodeUtf8(this.consumer);
1349
+ const meta = yield* tx.get(s.space(senderMetaSpace), key);
1350
+ const raw = yield* tx.get(s.space(senderBytesSpace), key);
1351
+ if (meta === undefined && raw === undefined)
1352
+ return undefined;
1353
+ if (meta === undefined || raw === undefined)
1354
+ throw corrupt('corrupt sender pending record');
1355
+ return preparedReceipt(this, raw, decodeSenderMetadata(meta, raw));
1356
+ }
1357
+ /** @internal Pins exact bytes before transport. Does not call a host or confirm delivery. */
1358
+ async _durablePrepare(options) {
1359
+ const limits = { maxUpdates: limit(options.maxUpdates), maxBytes: limit(options.maxBytes) };
1360
+ if (limits.maxUpdates === 0 || limits.maxUpdates > MAX_UPDATES)
1361
+ throw invalid('batch count limit');
1362
+ const outgoing = this, s = this.stream;
1363
+ const existing = await s.store.run(false, s.id, function* (tx) {
1364
+ const pending = yield* outgoing.readDurablePending(tx);
1365
+ if (pending) {
1366
+ if (preparedReceipts.get(pending).metadata.from !== (yield* outgoing.consumerCursor(tx)))
1367
+ throw invalid('stale durable consumer cursor');
1368
+ preparedLimits(pending, limits);
1369
+ }
1370
+ return pending;
1371
+ });
1372
+ if (existing)
1373
+ return existing;
1374
+ // Selection and assembly reuse the established precise prefix contract.
1375
+ const candidate = await this.nextBatch(limits);
1376
+ if (!candidate)
1377
+ return null;
1378
+ const receipt = receipts.get(candidate.receipt);
1379
+ const metadata = { from: receipt.from, through: receipt.through, count: Number(receipt.through - receipt.from), digest: blake3(candidate.updates) };
1380
+ if (metadata.count < 1 || metadata.count > MAX_UPDATES || !Number.isSafeInteger(metadata.count))
1381
+ throw corrupt('pending range overflow');
1382
+ const encoded = encodeSenderMetadata(metadata);
1383
+ const winner = await s.store.run(true, s.id, function* (tx) {
1384
+ const current = yield* outgoing.consumerCursor(tx), pending = yield* outgoing.readDurablePending(tx);
1385
+ if (pending) {
1386
+ if (preparedReceipts.get(pending).metadata.from !== current)
1387
+ throw invalid('stale durable consumer cursor');
1388
+ preparedLimits(pending, limits);
1389
+ return pending;
1390
+ }
1391
+ if (current !== metadata.from)
1392
+ throw invalid('stale durable consumer cursor');
1393
+ yield* tx.put(s.space(senderMetaSpace), encodeUtf8(outgoing.consumer), encoded);
1394
+ yield* tx.put(s.space(senderBytesSpace), encodeUtf8(outgoing.consumer), candidate.updates);
1395
+ return undefined;
1396
+ });
1397
+ return winner ?? preparedReceipt(this, candidate.updates, metadata, candidate.receipt);
1398
+ }
1399
+ /** @internal Confirms only a genuine prepared token bound to this Store/stream/consumer. */
1400
+ async _durableConfirm(token) {
1401
+ const expected = preparedReceipts.get(token), s = this.stream, outgoing = this;
1402
+ const receipt = expected && receipts.get(expected.receipt);
1403
+ if (!expected || !receipt || receipt.store !== s.store || receipt.stream !== s.id || receipt.consumer !== this.consumer)
1404
+ throw invalid('receipt scope mismatch');
1405
+ return s.store.run(true, s.id, function* (tx) {
1406
+ const current = yield* outgoing.consumerCursor(tx);
1407
+ // Validate paired state even for a late confirmation; never repair corruption.
1408
+ const pending = yield* outgoing.readDurablePending(tx);
1409
+ if (receipt.through <= current)
1410
+ return;
1411
+ if (!pending)
1412
+ throw invalid('durable pending batch missing');
1413
+ const actual = preparedReceipts.get(pending).metadata;
1414
+ if (current !== receipt.from || actual.from !== receipt.from || actual.through !== receipt.through || !equal(actual.digest, expected.metadata.digest))
1415
+ throw invalid('stale durable delivery receipt');
1416
+ const key = encodeUtf8(outgoing.consumer);
1417
+ yield* tx.put(s.space('consumers'), key, key64(receipt.through));
1418
+ yield* tx.delete(s.space(senderMetaSpace), key);
1419
+ yield* tx.delete(s.space(senderBytesSpace), key);
1420
+ });
1421
+ }
1422
+ async ack(receipt) {
1423
+ const s = this.stream, outgoing = this, r = receipts.get(receipt);
1424
+ if (!r || r.store !== s.store || r.stream !== s.id || r.consumer !== this.consumer)
1425
+ throw invalid('receipt scope mismatch');
1426
+ return s.store.run(true, s.id, function* (tx) {
1427
+ const key = encodeUtf8(r.consumer), b = yield* tx.get(s.space('consumers'), key), current = b ? read64(b) : 0n;
1428
+ if (current >= r.through)
1429
+ return;
1430
+ if (yield* outgoing.readDurablePending(tx))
1431
+ throw invalid('durable pending batch requires sender confirmation');
1432
+ if (current !== r.from)
1433
+ throw invalid('stale delivery receipt');
1434
+ yield* tx.put(s.space('consumers'), key, key64(r.through));
1435
+ });
1436
+ }
1437
+ }