@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
@@ -0,0 +1,1559 @@
1
+ /** Experimental application adapter; not yet wired into Lody's runtime. */
2
+ import { blake3 } from '@noble/hashes/blake3.js';
3
+ import { decodeBatch, decodeFrame, encodeFrame } from './codec.js';
4
+ import { decodeUtf8, encodeUtf8, encodeJson, decodeJson, MAX_JSON_DEPTH } from './json.js';
5
+ import { StoreError } from './store.js';
6
+ import { catchUpPublications, PUBLICATION_OBJECTS, PUBLICATION_DONE, PUBLICATION_CURSOR, checkPublicationRefs, publicationValue } from './history-publication.js';
7
+ const equal = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
8
+ const invalid = (message) => new StoreError('invalid', message);
9
+ function text(v) { if (typeof v !== 'string' || !v.length || encodeUtf8(v).length > 1024)
10
+ throw invalid('history identity size'); return v; }
11
+ function knownKind(kind) {
12
+ return kind === 'message' || kind === 'permission_response' || kind === 'dispatch_intent' || kind === 'batch_receipt' || kind === 'publication';
13
+ }
14
+ function keyOf(v) {
15
+ if (!knownKind(v.kind))
16
+ throw invalid('history kind');
17
+ return encodeUtf8(JSON.stringify([v.kind, text(v.businessId), text(v.segmentId)]));
18
+ }
19
+ function attachment(a) {
20
+ if (!/^[0-9a-f]{64}$/.test(a.sha256) || typeof a.size !== 'bigint' || a.size < 0n)
21
+ throw invalid('attachment identity');
22
+ return new Map([['attachmentId', text(a.attachmentId)], ['sha256', a.sha256], ['name', text(a.name)], ['size', { kind: 'u64', value: a.size }]]);
23
+ }
24
+ function envelope(v, publish = false) {
25
+ keyOf(v);
26
+ const body = new Map([['lodyHistory', new Map([['version', '1'], ['kind', v.kind], ['businessId', v.businessId], ['segmentId', v.segmentId]])], ['content', v.content], ['attachments', (v.attachments ?? []).map(attachment)]]);
27
+ if (v.kind === 'message')
28
+ body.set('lodyPublication', publish ? 'direct' : 'private');
29
+ return body;
30
+ }
31
+ function identityOf(content) {
32
+ if (!(content instanceof Map))
33
+ return;
34
+ const meta = content.get('lodyHistory');
35
+ if (!(meta instanceof Map) || meta.get('version') !== '1')
36
+ return;
37
+ const kind = meta.get('kind'), businessId = meta.get('businessId'), segmentId = meta.get('segmentId');
38
+ if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
39
+ throw invalid('history envelope');
40
+ const value = { kind, businessId, segmentId };
41
+ keyOf(value);
42
+ return value;
43
+ }
44
+ function canonicalCreate(owner, parents, content) {
45
+ const turnId = new Uint8Array(16);
46
+ turnId[6] = 0x70;
47
+ turnId[8] = 0x80;
48
+ const ordered = [...parents].sort((a, b) => { for (let i = 0; i < 16; i++)
49
+ if (a.id[i] !== b.id[i])
50
+ return a.id[i] - b.id[i]; return 0; });
51
+ return encodeFrame({ turnId, seq: 0n, owner, operation: { kind: 'create', parents: ordered, content } });
52
+ }
53
+ // Publication can be explicitly promoted later without changing the identity
54
+ // of the original application input. Old envelopes have no marker and retain
55
+ // exactly their previous digest. This is an application retry digest, not a seal.
56
+ function createDigest(owner, parents, content) {
57
+ if (content instanceof Map && (content.get('lodyPublication') === 'direct' || content.get('lodyPublication') === 'private')) {
58
+ content = new Map(content);
59
+ content.delete('lodyPublication');
60
+ }
61
+ return blake3(canonicalCreate(owner, parents, content));
62
+ }
63
+ function publicationObject(owner, parents, content) {
64
+ const id = identityOf(content);
65
+ if (!id)
66
+ return;
67
+ return { key: decodeUtf8(keyOf(id)), owner: hexBytes(owner), digest: hexBytes(createDigest(owner, parents, content)), kind: id.kind,
68
+ direct: id.kind === 'message' && content instanceof Map && content.get('lodyPublication') === 'direct' };
69
+ }
70
+ function binding(raw) {
71
+ try {
72
+ const b = JSON.parse(decodeUtf8(raw));
73
+ const fixed = (a, n) => Array.isArray(a) && a.length === n && a.every(v => Number.isInteger(v) && v >= 0 && v <= 255);
74
+ if (b.version !== 1 || !fixed(b.turnId, 16) || !fixed(b.owner, 32) || !fixed(b.digest, 32))
75
+ throw Error();
76
+ return b;
77
+ }
78
+ catch (cause) {
79
+ throw new StoreError('corrupt', 'invalid history binding', { cause });
80
+ }
81
+ }
82
+ /** A business message may contain append-only execution segments. A new segment
83
+ * never replaces an older signature. Dispatch/Flock and locations are host-owned. */
84
+ export class LodyHistory {
85
+ stream;
86
+ identity;
87
+ constructor(stream, identity) {
88
+ this.stream = stream;
89
+ this.identity = identity;
90
+ }
91
+ get space() { return this.stream.space('lody_history_bindings_v1'); }
92
+ get cursorSpace() { return this.stream.space('lody_history_index_v1'); }
93
+ async indexPage(limit = 128) {
94
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
95
+ throw invalid('index page limit');
96
+ const stream = this.stream, space = this.space, cursorSpace = this.cursorSpace, key = new Uint8Array();
97
+ const from = await stream.store.run(false, stream.id, function* (tx) { return (yield* tx.get(cursorSpace, key)) ?? encodeUtf8('0'); });
98
+ const after = BigInt(decodeUtf8(from));
99
+ const events = await stream.eventsAfter(after, limit);
100
+ if (!events.length)
101
+ return false; // A read must not write a cursor and wake itself.
102
+ const rows = [];
103
+ const objects = [];
104
+ const invalidTurns = [];
105
+ for (const record of events) {
106
+ if (record.event.kind !== 'changed' || record.event.update.seq !== 0n)
107
+ continue;
108
+ const [u] = decodeBatch(await stream.exportUpdates(record.event.update.turnId, 0n, 1));
109
+ if (!u || u.operation.kind !== 'create')
110
+ throw new StoreError('corrupt', 'history create event has no operation');
111
+ let id;
112
+ try {
113
+ id = identityOf(u.operation.content);
114
+ }
115
+ catch (error) {
116
+ if (!(error instanceof StoreError) || error.code !== 'invalid')
117
+ throw error;
118
+ invalidTurns.push(u.turnId);
119
+ }
120
+ if (!id) {
121
+ objects.push({ key: u.turnId, value: encodeUtf8('null') });
122
+ continue;
123
+ }
124
+ rows.push({ key: keyOf(id), value: { version: 1, turnId: [...u.turnId], owner: [...u.owner], digest: [...createDigest(u.owner, u.operation.parents, u.operation.content)] } });
125
+ objects.push({ key: u.turnId, value: encodeUtf8(JSON.stringify(publicationObject(u.owner, u.operation.parents, u.operation.content))) });
126
+ }
127
+ const through = events.at(-1)?.cursor ?? after;
128
+ const committed = await stream.store.run(true, stream.id, function* (tx) {
129
+ const actual = (yield* tx.get(cursorSpace, key)) ?? encodeUtf8('0');
130
+ if (!equal(actual, from))
131
+ return false;
132
+ for (const id of invalidTurns)
133
+ yield* tx.put(stream.space('lody_history_invalid_v1'), id, encodeUtf8('invalid_envelope'));
134
+ for (const row of objects)
135
+ yield* tx.put(stream.space(PUBLICATION_OBJECTS), row.key, row.value);
136
+ for (const row of rows) {
137
+ const prior = yield* tx.get(space, row.key);
138
+ const old = prior && binding(prior);
139
+ if (old && (old.conflict || !equal(Uint8Array.from(old.turnId), Uint8Array.from(row.value.turnId))))
140
+ row.value.conflict = true;
141
+ yield* tx.put(space, row.key, encodeUtf8(JSON.stringify(row.value)));
142
+ }
143
+ yield* tx.put(cursorSpace, key, encodeUtf8(through.toString()));
144
+ return true;
145
+ });
146
+ return !committed || events.length === limit;
147
+ }
148
+ catchUpIndex() { return catchUpHistory(this); }
149
+ async invalidMessages(limit = 100) {
150
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
151
+ throw invalid('diagnostic limit');
152
+ await this.catchUpIndex();
153
+ const space = this.stream.space('lody_history_invalid_v1');
154
+ return this.stream.store.run(false, this.stream.id, function* (tx) { return (yield* tx.scan(space, new Uint8Array(), undefined, limit)).map(([turnId]) => ({ turnId, reason: 'invalid_envelope' })); });
155
+ }
156
+ async lookup(input) {
157
+ await this.catchUpIndex();
158
+ const key = keyOf(input), space = this.space;
159
+ const raw = await this.stream.store.run(false, this.stream.id, function* (tx) { return yield* tx.get(space, key); });
160
+ if (!raw)
161
+ return;
162
+ const b = binding(raw);
163
+ if (b.conflict)
164
+ throw new StoreError('conflict', 'multiple Turns claim one history segment');
165
+ return this.stream.readTurn(Uint8Array.from(b.turnId));
166
+ }
167
+ async accept(input, options) {
168
+ // Own every input before the first await. The original Create fingerprint is
169
+ // stable even after edits; a retry must not compare against the current body.
170
+ const key = keyOf(input), owner = this.identity.owner();
171
+ const rawInput = canonicalCreate(owner, input.parents, envelope(input, options?.publish !== false)), fingerprint = createDigest(owner, input.parents, envelope(input));
172
+ const copied = decodeFrame(rawInput);
173
+ if (copied.operation.kind !== 'create')
174
+ throw invalid('create');
175
+ for (let attempt = 0; attempt < 4; attempt++) {
176
+ await this.catchUpIndex();
177
+ const space = this.space, cursorSpace = this.cursorSpace;
178
+ const snapshot = await this.stream.store.run(false, this.stream.id, function* (tx) {
179
+ return { raw: yield* tx.get(space, key), cursor: BigInt(decodeUtf8((yield* tx.get(cursorSpace, new Uint8Array())) ?? encodeUtf8('0'))) };
180
+ });
181
+ if (snapshot.raw) {
182
+ const b = binding(snapshot.raw);
183
+ if (b.conflict || !equal(Uint8Array.from(b.owner), owner) || !equal(Uint8Array.from(b.digest), fingerprint))
184
+ throw new StoreError('conflict', 'history segment input changed');
185
+ const existing = { turnId: Uint8Array.from(b.turnId), created: false };
186
+ await maybePublishAccept(this, input, options, existing.turnId);
187
+ return existing;
188
+ }
189
+ try {
190
+ const result = await this.stream.writer(this.identity).createOnce(key, copied.operation.parents, copied.operation.content, snapshot.cursor);
191
+ await this.catchUpIndex();
192
+ await maybePublishAccept(this, input, options, result.turnId);
193
+ return result;
194
+ }
195
+ catch (error) {
196
+ if (!(error instanceof StoreError) || error.code !== 'stale')
197
+ throw error;
198
+ }
199
+ }
200
+ throw new StoreError('stale', 'history discovery retry budget exhausted');
201
+ }
202
+ append(id, expectedNextSeq, ops) {
203
+ return this.stream.writer(this.identity).edit(id, expectedNextSeq, ops.map(op => ({ ...op, path: [{ key: 'content' }, ...op.path] })));
204
+ }
205
+ finish(id, expectedNextSeq) { return this.stream.writer(this.identity).seal(id, expectedNextSeq); }
206
+ async respondPermission(input) {
207
+ const result = await this.accept({ businessId: text(input.requestId), segmentId: 'response', kind: 'permission_response', parents: input.parents,
208
+ content: new Map([['assistantBusinessId', text(input.assistantBusinessId)], ['outcome', input.outcome]]) });
209
+ const before = await this.stream.readTurnHeader(result.turnId);
210
+ if (before.kind !== 'found')
211
+ throw invalid('permission response missing');
212
+ if (!before.turn.sealed) {
213
+ try {
214
+ await this.finish(result.turnId, 1n);
215
+ }
216
+ catch (error) {
217
+ const after = await this.stream.readTurnHeader(result.turnId);
218
+ if (!(error instanceof StoreError) || error.code !== 'stale' || after.kind !== 'found' || !after.turn.sealed)
219
+ throw error;
220
+ }
221
+ }
222
+ return result;
223
+ }
224
+ async attachments(id, resolve) {
225
+ const result = await this.stream.readTurn(id);
226
+ if (result.kind !== 'found' || !(result.turn.content instanceof Map))
227
+ throw invalid('missing message');
228
+ const refs = result.turn.content.get('attachments');
229
+ if (!Array.isArray(refs))
230
+ throw invalid('invalid attachments');
231
+ const identities = refs.map(ref => {
232
+ if (!(ref instanceof Map))
233
+ throw invalid('invalid attachment');
234
+ const size = ref.get('size');
235
+ if (!size || typeof size !== 'object' || !('kind' in size) || size.kind !== 'u64')
236
+ throw invalid('invalid attachment size');
237
+ const value = { attachmentId: ref.get('attachmentId'), sha256: ref.get('sha256'), name: ref.get('name'), size: size.value };
238
+ attachment(value);
239
+ return value;
240
+ });
241
+ // readTurn has completed its transaction before any host Promise is invoked.
242
+ return Promise.all(identities.map(async (value) => ({ identity: value, location: await resolve(value) })));
243
+ }
244
+ async commitHistoryBatch(batchId, commands) {
245
+ return commitBatch(this, batchId, commands);
246
+ }
247
+ recoverPendingBatches() { return recoverBatches(this); }
248
+ /** A consumer-owned cache. Call refresh on change hints (or host polling). */
249
+ createMessageView(limit = 40) { return new HistoryMessageView(this, limit); }
250
+ async readProjectedMessagesById(ids) {
251
+ const copied = uniqueIds(ids);
252
+ return (await stableRead(this, async () => hydratePublished(this, await publishedById(this, copied)))).value;
253
+ }
254
+ async readProjectedMessages() { return projectedMessages(this); }
255
+ async readProjectedMessagePage(input = {}) {
256
+ return projectedMessagePage(this, input);
257
+ }
258
+ async readProjectedEntries() {
259
+ return (await projectedMessages(this)).map((row) => ({ ...row, entry: toApplicationJson(row.content) }));
260
+ }
261
+ async observedEventCursor() {
262
+ await this.catchUpIndex();
263
+ const stream = this.stream, space = this.cursorSpace;
264
+ return stream.store.run(false, stream.id, function* (tx) { return processedCursor((yield* tx.get(space, new Uint8Array())) ?? null); });
265
+ }
266
+ async indexedBindings() {
267
+ const space = this.space, stream = this.stream, out = [];
268
+ let start = new Uint8Array();
269
+ for (;;) {
270
+ const page = await stream.store.run(false, stream.id, function* (tx) { return yield* tx.scan(space, start, undefined, 128); });
271
+ if (!page.length)
272
+ break;
273
+ for (const [key, value] of page) {
274
+ const identity = identityFromKey(decodeUtf8(key));
275
+ if (identity)
276
+ out.push({ identity, binding: binding(value) });
277
+ }
278
+ if (page.length < 128)
279
+ break;
280
+ const last = page[page.length - 1][0];
281
+ const next = new Uint8Array(last.length + 1);
282
+ next.set(last);
283
+ start = next;
284
+ }
285
+ return out;
286
+ }
287
+ }
288
+ const NODE_BINDINGS = 'lody_history_bindings_v1';
289
+ const NODE_CURSOR = { table: 'lody_history_index_v1', key: new Uint8Array() };
290
+ const NODE_INVALID = 'lody_history_invalid_v1';
291
+ const NODE_RECEIPTS = 'lody_history_receipt_ids_v1';
292
+ const NODE_PENDING = 'lody_history_pending_batches_v1';
293
+ function processedCursor(raw) {
294
+ if (raw === null)
295
+ return 0n;
296
+ const value = decodeUtf8(raw);
297
+ if (!/^(0|[1-9][0-9]*)$/.test(value) || BigInt(value) > (1n << 64n) - 1n)
298
+ throw new StoreError('corrupt', 'invalid history index cursor');
299
+ return BigInt(value);
300
+ }
301
+ function afterIndexKey(key) {
302
+ const next = new Uint8Array(key.length + 1);
303
+ next.set(key);
304
+ return next;
305
+ }
306
+ export class NodeLodyHistory {
307
+ stream;
308
+ owner;
309
+ constructor(stream, owner) {
310
+ this.stream = stream;
311
+ this.owner = owner;
312
+ this.owner = owner.slice();
313
+ }
314
+ /** One bounded local event page. The cursor belongs to this database's
315
+ * event journal, including P2P imports and pending operations when applied.
316
+ * All computation is outside the owner transaction; its cursor CAS rejects
317
+ * a stale page together with every derived change. */
318
+ async indexPage(limit = 128) {
319
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 128)
320
+ throw invalid('index page limit');
321
+ const [from] = await this.stream.readIndex([NODE_CURSOR]);
322
+ const events = await this.stream.eventsAfter(processedCursor(from), BigInt(limit));
323
+ if (!events.length)
324
+ return false;
325
+ const changes = [];
326
+ const rows = [];
327
+ const touched = new Map();
328
+ const receipts = new Map();
329
+ for (const record of events) {
330
+ const update = record.event.update;
331
+ if (record.event.kind !== 'changed' || !update)
332
+ continue;
333
+ touched.set(hexBytes(update.turnId), update.turnId);
334
+ if (update.seq !== 0n)
335
+ continue;
336
+ const [u] = decodeBatch(await this.stream.exportUpdates(update.turnId, 0n, 1n));
337
+ if (!u || u.operation.kind !== 'create')
338
+ throw new StoreError('corrupt', 'history create event has no operation');
339
+ let id;
340
+ try {
341
+ id = identityOf(u.operation.content);
342
+ }
343
+ catch (error) {
344
+ if (!(error instanceof StoreError) || error.code !== 'invalid')
345
+ throw error;
346
+ changes.push({ table: NODE_INVALID, key: u.turnId, value: encodeUtf8('invalid_envelope') });
347
+ }
348
+ if (!id) {
349
+ changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8('null') });
350
+ continue;
351
+ }
352
+ const key = keyOf(id);
353
+ rows.push({ key, value: { version: 1, turnId: [...u.turnId], owner: [...u.owner], digest: [...createDigest(u.owner, u.operation.parents, u.operation.content)] } });
354
+ changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8(JSON.stringify(publicationObject(u.owner, u.operation.parents, u.operation.content))) });
355
+ if (id.kind === 'batch_receipt') {
356
+ receipts.set(hexBytes(u.turnId), { id: u.turnId, key });
357
+ changes.push({ table: NODE_RECEIPTS, key: u.turnId, value: key });
358
+ }
359
+ }
360
+ const previous = await this.stream.readIndex(rows.map(row => ({ table: NODE_BINDINGS, key: row.key })));
361
+ const merged = new Map();
362
+ for (let i = 0; i < rows.length; i++) {
363
+ const row = rows[i], key = decodeUtf8(row.key);
364
+ const old = merged.get(key) ?? (previous[i] === null ? undefined : binding(previous[i]));
365
+ if (old && (old.conflict || !equal(Uint8Array.from(old.turnId), Uint8Array.from(row.value.turnId))))
366
+ row.value.conflict = true;
367
+ merged.set(key, row.value);
368
+ changes.push({ table: NODE_BINDINGS, key: row.key, value: encodeUtf8(JSON.stringify(row.value)) });
369
+ }
370
+ // Only touched receipts are inspected. The pending index lets normal
371
+ // startup avoid enumerating every completed receipt / business binding.
372
+ const ids = [...touched.values()];
373
+ const known = await this.stream.readIndex(ids.map(key => ({ table: NODE_RECEIPTS, key })));
374
+ for (let i = 0; i < ids.length; i++)
375
+ if (known[i] !== null)
376
+ receipts.set(hexBytes(ids[i]), { id: ids[i], key: known[i] });
377
+ for (const receipt of receipts.values()) {
378
+ const header = await this.stream.readTurnHeader(receipt.id);
379
+ const prefix = header.kind === 'found' ? header.turn : header.kind === 'incomplete' ? header.prefix : undefined;
380
+ if (!prefix)
381
+ throw new StoreError('corrupt', 'indexed receipt missing');
382
+ let pending = !prefix.sealed;
383
+ if (pending) {
384
+ try {
385
+ const state = await this.stream.readValue(receipt.id, [{ key: 'content' }, { key: 'status' }]);
386
+ const status = decodeJson(encodeUtf8(state.contentJson));
387
+ pending = status !== 'failed' && status !== 'committed';
388
+ }
389
+ catch (error) {
390
+ // A peer can send a recognized receipt identity with no status yet.
391
+ // Keep it discoverable; missing application fields must not stop the
392
+ // whole stream's binding index. Storage failures still abort the page.
393
+ if (errorCode(error) !== 'invalid')
394
+ throw error;
395
+ }
396
+ }
397
+ changes.push({ table: NODE_PENDING, key: receipt.id, value: pending ? receipt.key : null });
398
+ }
399
+ changes.push({ ...NODE_CURSOR, value: encodeUtf8(events.at(-1).cursor.toString()) });
400
+ const committed = await this.stream.compareAndWriteIndex([{ ...NODE_CURSOR, value: from }], changes);
401
+ return !committed || events.length === limit;
402
+ }
403
+ catchUpIndex() { return catchUpHistory(this); }
404
+ async invalidMessages(limit = 100) {
405
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
406
+ throw invalid('diagnostic limit');
407
+ await this.catchUpIndex();
408
+ return (await this.stream.scanIndex(NODE_INVALID, new Uint8Array(), BigInt(limit))).map(row => ({ turnId: row.key, reason: 'invalid_envelope' }));
409
+ }
410
+ async lookup(input) {
411
+ const key = keyOf(input);
412
+ await this.catchUpIndex();
413
+ const [raw] = await this.stream.readIndex([{ table: NODE_BINDINGS, key }]);
414
+ const b = raw === null ? undefined : binding(raw);
415
+ if (b?.conflict)
416
+ throw new StoreError('conflict', 'multiple Turns claim one history segment');
417
+ return b ? this.stream.readTurn(Uint8Array.from(b.turnId)) : undefined;
418
+ }
419
+ acceptJson(input) {
420
+ return this.accept({ ...input, kind: 'message', content: decodeJson(encodeUtf8(input.contentJson)) });
421
+ }
422
+ async read(id) {
423
+ const result = await this.stream.readTurn(id);
424
+ if (result.kind !== 'found')
425
+ return result;
426
+ const body = decodeJson(encodeUtf8(result.turn.contentJson));
427
+ if (!(body instanceof Map) || !identityOf(body) || !body.has('content'))
428
+ throw invalid('history envelope');
429
+ return { ...result, turn: { ...result.turn, contentJson: decodeUtf8(encodeJson(body.get('content'))) } };
430
+ }
431
+ async append(id, seq, ops) {
432
+ await this.stream.edit(id, seq, ops.map(op => ({ ...op, path: [{ key: 'content' }, ...op.path] })));
433
+ }
434
+ async finish(id, seq) { await this.stream.seal(id, seq); }
435
+ async accept(input, options) {
436
+ const key = keyOf(input), raw = canonicalCreate(this.owner, input.parents, envelope(input, options?.publish !== false)), digest = createDigest(this.owner, input.parents, envelope(input));
437
+ const copied = decodeFrame(raw);
438
+ if (copied.operation.kind !== 'create')
439
+ throw invalid('create');
440
+ for (let attempt = 0; attempt < 4; attempt++) {
441
+ await this.catchUpIndex();
442
+ const [rawBinding, rawCursor] = await this.stream.readIndex([{ table: NODE_BINDINGS, key }, NODE_CURSOR]);
443
+ const cursor = processedCursor(rawCursor), prior = rawBinding === null ? undefined : binding(rawBinding);
444
+ if (prior) {
445
+ if (prior.conflict || !equal(Uint8Array.from(prior.owner), this.owner) || !equal(Uint8Array.from(prior.digest), digest))
446
+ throw new StoreError('conflict', 'history segment input changed');
447
+ const existing = { turnId: Uint8Array.from(prior.turnId), created: false };
448
+ await maybePublishAccept(this, input, options, existing.turnId);
449
+ return existing;
450
+ }
451
+ try {
452
+ const result = await this.stream.createOnce(key, copied.operation.parents, decodeUtf8(encodeJson(copied.operation.content)), { expectedEventCursor: cursor });
453
+ await this.catchUpIndex();
454
+ await maybePublishAccept(this, input, options, result.turnId);
455
+ return result;
456
+ }
457
+ catch (error) {
458
+ if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 'stale')
459
+ throw error;
460
+ }
461
+ }
462
+ throw new StoreError('stale', 'history discovery retry budget exhausted');
463
+ }
464
+ async respondPermission(input) {
465
+ const result = await this.accept({ businessId: text(input.requestId), segmentId: 'response', kind: 'permission_response', parents: input.parents,
466
+ content: new Map([['assistantBusinessId', text(input.assistantBusinessId)], ['outcome', input.outcome]]) });
467
+ const before = await this.stream.readTurn(result.turnId);
468
+ if (before.kind !== 'found')
469
+ throw invalid('permission response missing');
470
+ if (!before.turn.sealed) {
471
+ try {
472
+ await this.finish(result.turnId, 1n);
473
+ }
474
+ catch (error) {
475
+ const after = await this.stream.readTurn(result.turnId);
476
+ if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 'stale' || after.kind !== 'found' || !after.turn.sealed)
477
+ throw error;
478
+ }
479
+ }
480
+ return result;
481
+ }
482
+ async commitHistoryBatch(batchId, commands) {
483
+ return commitBatch(this, batchId, commands);
484
+ }
485
+ recoverPendingBatches() { return recoverBatches(this); }
486
+ /** A consumer-owned cache. Call refresh on change hints (or host polling). */
487
+ createMessageView(limit = 40) { return new HistoryMessageView(this, limit); }
488
+ async readProjectedMessagesById(ids) {
489
+ const copied = uniqueIds(ids);
490
+ return (await stableRead(this, async () => hydratePublished(this, await publishedById(this, copied)))).value;
491
+ }
492
+ async readProjectedMessages() { return projectedMessages(this); }
493
+ async readProjectedMessagePage(input = {}) {
494
+ return projectedMessagePage(this, input);
495
+ }
496
+ async readProjectedEntries() {
497
+ return (await projectedMessages(this)).map((row) => ({ ...row, entry: toApplicationJson(row.content) }));
498
+ }
499
+ async observedEventCursor() {
500
+ await this.catchUpIndex();
501
+ const [raw] = await this.stream.readIndex([NODE_CURSOR]);
502
+ return processedCursor(raw);
503
+ }
504
+ async indexedBindings() {
505
+ const out = [];
506
+ let start = new Uint8Array();
507
+ for (;;) {
508
+ const page = await this.stream.scanIndex(NODE_BINDINGS, start, 128n);
509
+ for (const row of page) {
510
+ const identity = identityFromKey(decodeUtf8(row.key));
511
+ if (identity)
512
+ out.push({ identity, binding: binding(row.value) });
513
+ }
514
+ if (page.length < 128)
515
+ break;
516
+ start = afterIndexKey(page.at(-1).key);
517
+ }
518
+ return out;
519
+ }
520
+ async *pendingBatchBindings() {
521
+ let start = new Uint8Array();
522
+ for (;;) {
523
+ const page = await this.stream.scanIndex(NODE_PENDING, start, 128n);
524
+ const values = await this.stream.readIndex(page.map(row => ({ table: NODE_BINDINGS, key: row.value })));
525
+ for (let i = 0; i < page.length; i++) {
526
+ const identity = identityFromKey(decodeUtf8(page[i].value));
527
+ if (!identity || values[i] === null)
528
+ throw new StoreError('corrupt', 'pending receipt binding missing');
529
+ yield { identity, binding: binding(values[i]) };
530
+ }
531
+ if (page.length < 128)
532
+ return;
533
+ start = afterIndexKey(page.at(-1).key);
534
+ }
535
+ }
536
+ }
537
+ async function publicationField(host, id, path) {
538
+ if (host instanceof LodyHistory)
539
+ return (await host.stream.readValue(id, path)).value;
540
+ return decodeJson(encodeUtf8((await host.stream.readValue(id, path)).contentJson));
541
+ }
542
+ async function readPublicationManifest(host, id, object) {
543
+ try {
544
+ if (await publicationField(host, id, [{ key: 'content' }, { key: 'status' }]) !== 'committed')
545
+ return;
546
+ // Read this subtree once, then persist only compact references while waiting.
547
+ // Old receipts stored full snapshots here; new receipts are membership-only.
548
+ const published = await publicationField(host, id, [{ key: 'content' }, { key: 'published' }]);
549
+ const legacy = Array.isArray(published);
550
+ const list = legacy ? published : published instanceof Map && published.get('version') === '2' ? published.get('messages') : undefined;
551
+ if (!Array.isArray(list) || list.length > 64)
552
+ throw invalid('publication manifest');
553
+ let commands = [];
554
+ if (legacy) {
555
+ if (object.kind !== 'batch_receipt')
556
+ throw invalid('legacy publication kind');
557
+ const encoded = await publicationField(host, id, [{ key: 'content' }, { key: 'commands' }]);
558
+ if (!Array.isArray(encoded) || encoded.length > 64)
559
+ throw invalid('legacy publication commands');
560
+ commands = decodeCommands(encoded);
561
+ const identity = identityFromKey(object.key);
562
+ const digest = await publicationField(host, id, [{ key: 'content' }, { key: 'digest' }]);
563
+ const applied = await publicationField(host, id, [{ key: 'content' }, { key: 'applied' }]);
564
+ if (!identity || digest !== hexBytes(commandDigest(identity.businessId, commands)) || seqOf(applied) !== BigInt(commands.length))
565
+ throw invalid('legacy publication command digest');
566
+ }
567
+ return checkPublicationRefs(list.map(value => {
568
+ const row = asMap(value, 'publication message');
569
+ const businessId = row.get('businessId'), segmentId = row.get('segmentId'), sealed = row.get('sealed');
570
+ const nextSeq = legacy ? seqOf(row.get('nextSeq')).toString() : row.get('nextSeq');
571
+ let digest = row.get('digest');
572
+ const turnId = row.get('turnId');
573
+ if (typeof businessId !== 'string' || typeof segmentId !== 'string' || typeof sealed !== 'boolean' || typeof nextSeq !== 'string' ||
574
+ (digest !== undefined && typeof digest !== 'string') || (turnId !== undefined && typeof turnId !== 'string'))
575
+ throw invalid('publication message');
576
+ // Legacy atomic CreateOnce batches had no allocated ID in this snapshot.
577
+ // Pin these to the signed command's original Create, not just its identity.
578
+ const target = legacy && turnId === '0'.repeat(32) ? undefined : turnId;
579
+ if (legacy) {
580
+ const matching = commands.filter(command => 'identity' in command && command.identity.kind === 'message' && command.identity.businessId === businessId && command.identity.segmentId === segmentId);
581
+ if (!matching.length)
582
+ throw invalid('legacy publication has no command');
583
+ const accept = matching.find(command => command.type === 'accept');
584
+ if (accept?.type === 'accept')
585
+ digest = hexBytes(createDigest(unhexBytes(object.owner, 32), accept.parents, envelope({ ...accept.identity, parents: accept.parents, content: accept.content, attachments: accept.attachments })));
586
+ if (target === undefined && !digest)
587
+ throw invalid('legacy publication has no Create');
588
+ }
589
+ if (!legacy && digest === undefined)
590
+ throw invalid('publication Create digest');
591
+ return { businessId, segmentId, nextSeq, sealed, ...(digest !== undefined ? { digest } : {}), ...(target !== undefined ? { turnId: target } : {}) };
592
+ }));
593
+ }
594
+ catch (error) {
595
+ if (errorCode(error) === 'invalid')
596
+ throw invalid('invalid publication manifest');
597
+ throw error;
598
+ }
599
+ }
600
+ function publicationPort(host) {
601
+ return {
602
+ readIndex: keys => indexValues(host, keys),
603
+ scanIndex: (table, start, limit) => host instanceof LodyHistory ? host.stream.scanIndex(table, start, limit) : host.stream.scanIndex(table, start, BigInt(limit)),
604
+ commit: (expected, changes, eventKeys) => host.stream.compareAndWriteIndex(expected, changes, { eventKeys }),
605
+ events: (after, limit) => localEvents(host, after, limit),
606
+ discover: async (id) => {
607
+ const bytes = host instanceof LodyHistory ? await host.stream.exportUpdates(id, 0n, 1) : await host.stream.exportUpdates(id, 0n, 1n);
608
+ const [update] = decodeBatch(bytes);
609
+ if (!update || update.operation.kind !== 'create')
610
+ throw new StoreError('corrupt', 'publication Create missing');
611
+ try {
612
+ return publicationObject(update.owner, update.operation.parents, update.operation.content);
613
+ }
614
+ catch (error) {
615
+ if (errorCode(error) !== 'invalid')
616
+ throw error;
617
+ return;
618
+ }
619
+ },
620
+ header: async (id) => {
621
+ const read = await host.stream.readTurnHeader(id);
622
+ return read.kind === 'found' ? read.turn : read.kind === 'incomplete' ? read.prefix ?? undefined : undefined;
623
+ },
624
+ status: async (id) => {
625
+ try {
626
+ return await publicationField(host, id, [{ key: 'content' }, { key: 'status' }]);
627
+ }
628
+ catch (error) {
629
+ if (errorCode(error) !== 'invalid')
630
+ throw error;
631
+ return;
632
+ }
633
+ },
634
+ manifest: (id, object) => readPublicationManifest(host, id, object),
635
+ };
636
+ }
637
+ const historyCatchups = new WeakMap();
638
+ function catchUpHistory(host) {
639
+ const pending = historyCatchups.get(host);
640
+ if (pending)
641
+ return pending;
642
+ const task = (async () => {
643
+ for (;;) {
644
+ while (await host.indexPage()) { /* binding rows and local cursor commit together */ }
645
+ await catchUpPublications(publicationPort(host));
646
+ const [rawBinding, rawPublication] = await indexValues(host, [NODE_CURSOR, PUBLICATION_CURSOR]);
647
+ const through = processedCursor(rawBinding);
648
+ if (through === processedCursor(rawPublication) && !(await localEvents(host, through, 1)).length)
649
+ return;
650
+ }
651
+ })();
652
+ historyCatchups.set(host, task);
653
+ void task.finally(() => { if (historyCatchups.get(host) === task)
654
+ historyCatchups.delete(host); }).catch(() => { });
655
+ return task;
656
+ }
657
+ function commandDigest(batchId, commands) {
658
+ const body = commands.map((command) => {
659
+ if (command.type === 'accept') {
660
+ return { type: command.type, identity: command.identity, content: decodeUtf8(encodeJson(command.content)), parents: command.parents.map((p) => ({ id: [...p.id], hash: [...p.hash] })), attachments: command.attachments ?? [] };
661
+ }
662
+ if (command.type === 'setContent') {
663
+ return { type: command.type, identity: command.identity, expectedNextSeq: command.expectedNextSeq.toString(), content: decodeUtf8(encodeJson(command.content)) };
664
+ }
665
+ if (command.type === 'finish') {
666
+ return { type: command.type, identity: command.identity, expectedNextSeq: command.expectedNextSeq.toString() };
667
+ }
668
+ if (command.type === 'permission') {
669
+ return { type: command.type, requestId: command.requestId, assistantBusinessId: command.assistantBusinessId, outcome: decodeUtf8(encodeJson(command.outcome)), parents: command.parents.map((p) => ({ id: [...p.id], hash: [...p.hash] })) };
670
+ }
671
+ return { type: command.type, latestUserMsgId: command.latestUserMsgId, state: command.state };
672
+ });
673
+ return blake3(encodeJson(fromApplicationJson({ batchId, body })));
674
+ }
675
+ function identityFromKey(key) {
676
+ try {
677
+ const parsed = JSON.parse(key);
678
+ if (!Array.isArray(parsed) || parsed.length !== 3 || typeof parsed[0] !== 'string' || typeof parsed[1] !== 'string' || typeof parsed[2] !== 'string')
679
+ return;
680
+ if (!knownKind(parsed[0]))
681
+ return;
682
+ const identity = { kind: parsed[0], businessId: parsed[1], segmentId: parsed[2] };
683
+ keyOf(identity);
684
+ return identity;
685
+ }
686
+ catch {
687
+ return;
688
+ }
689
+ }
690
+ function hexBytes(value) { return Array.from(value, (b) => b.toString(16).padStart(2, '0')).join(''); }
691
+ function unhexBytes(text, size) {
692
+ if (!/^(?:[0-9a-f]{2})*$/.test(text) || text.length !== size * 2)
693
+ throw invalid('command bytes');
694
+ const out = new Uint8Array(size);
695
+ for (let i = 0; i < size; i++)
696
+ out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
697
+ return out;
698
+ }
699
+ function compareBytes(a, b) {
700
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
701
+ if (a[i] !== b[i])
702
+ return a[i] - b[i];
703
+ return a.length - b.length;
704
+ }
705
+ function errorCode(error) {
706
+ if (error instanceof StoreError)
707
+ return error.code;
708
+ if (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string')
709
+ return error.code;
710
+ }
711
+ function isSemanticFailure(code) {
712
+ return code === 'stale' || code === 'conflict' || code === 'invalid' || code === 'sealed' || code === 'corrupt';
713
+ }
714
+ function asMap(value, label) {
715
+ if (!(value instanceof Map))
716
+ throw invalid(label);
717
+ return value;
718
+ }
719
+ function identityValue(id) {
720
+ return new Map([['kind', id.kind], ['businessId', id.businessId], ['segmentId', id.segmentId]]);
721
+ }
722
+ function parentValue(parent) {
723
+ return new Map([['id', hexBytes(parent.id)], ['hash', hexBytes(parent.hash)]]);
724
+ }
725
+ function decodeIdentity(value) {
726
+ const row = asMap(value, 'command identity');
727
+ const kind = row.get('kind'), businessId = row.get('businessId'), segmentId = row.get('segmentId');
728
+ if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
729
+ throw invalid('command identity');
730
+ const identity = { kind, businessId, segmentId };
731
+ keyOf(identity);
732
+ return identity;
733
+ }
734
+ function decodeParent(value) {
735
+ const row = asMap(value, 'command parent');
736
+ const id = row.get('id'), hash = row.get('hash');
737
+ if (typeof id !== 'string' || typeof hash !== 'string')
738
+ throw invalid('command parent');
739
+ return { id: unhexBytes(id, 16), hash: unhexBytes(hash, 32) };
740
+ }
741
+ function seqOf(value) {
742
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value instanceof Map || value.kind !== 'u64')
743
+ throw invalid('command seq');
744
+ return value.value;
745
+ }
746
+ function decodeAttachment(value) {
747
+ const row = asMap(value, 'attachment');
748
+ const size = row.get('size');
749
+ if (!size || typeof size !== 'object' || Array.isArray(size) || size instanceof Map || size.kind !== 'u64')
750
+ throw invalid('attachment');
751
+ const attachmentId = row.get('attachmentId'), sha256 = row.get('sha256'), name = row.get('name');
752
+ if (typeof attachmentId !== 'string' || typeof sha256 !== 'string' || typeof name !== 'string')
753
+ throw invalid('attachment');
754
+ const parsed = { attachmentId, sha256, name, size: size.value };
755
+ attachment(parsed);
756
+ return parsed;
757
+ }
758
+ function encodeCommands(commands) {
759
+ return commands.map((command) => {
760
+ const row = new Map([['type', command.type]]);
761
+ if (command.type === 'accept') {
762
+ row.set('identity', identityValue(command.identity));
763
+ row.set('parents', command.parents.map(parentValue));
764
+ row.set('content', command.content);
765
+ row.set('attachments', (command.attachments ?? []).map(attachment));
766
+ return row;
767
+ }
768
+ if (command.type === 'setContent') {
769
+ row.set('identity', identityValue(command.identity));
770
+ row.set('expectedNextSeq', { kind: 'u64', value: command.expectedNextSeq });
771
+ row.set('content', command.content);
772
+ return row;
773
+ }
774
+ if (command.type === 'finish') {
775
+ row.set('identity', identityValue(command.identity));
776
+ row.set('expectedNextSeq', { kind: 'u64', value: command.expectedNextSeq });
777
+ return row;
778
+ }
779
+ if (command.type === 'permission') {
780
+ row.set('requestId', command.requestId);
781
+ row.set('assistantBusinessId', command.assistantBusinessId);
782
+ row.set('outcome', command.outcome);
783
+ row.set('parents', command.parents.map(parentValue));
784
+ return row;
785
+ }
786
+ row.set('latestUserMsgId', command.latestUserMsgId);
787
+ row.set('state', command.state);
788
+ return row;
789
+ });
790
+ }
791
+ function decodeCommands(value) {
792
+ if (!Array.isArray(value))
793
+ throw invalid('batch commands');
794
+ return value.map((item) => {
795
+ const row = asMap(item, 'batch command');
796
+ const type = row.get('type');
797
+ if (type === 'accept') {
798
+ const content = row.get('content'), parents = row.get('parents'), attachments = row.get('attachments');
799
+ if (content === undefined || !Array.isArray(parents))
800
+ throw invalid('batch command');
801
+ return { type, identity: decodeIdentity(row.get('identity')), parents: parents.map(decodeParent), content, attachments: Array.isArray(attachments) ? attachments.map(decodeAttachment) : undefined };
802
+ }
803
+ if (type === 'setContent') {
804
+ const content = row.get('content');
805
+ if (content === undefined)
806
+ throw invalid('batch command');
807
+ return { type, identity: decodeIdentity(row.get('identity')), expectedNextSeq: seqOf(row.get('expectedNextSeq')), content };
808
+ }
809
+ if (type === 'finish')
810
+ return { type, identity: decodeIdentity(row.get('identity')), expectedNextSeq: seqOf(row.get('expectedNextSeq')) };
811
+ if (type === 'permission') {
812
+ const requestId = row.get('requestId'), assistantBusinessId = row.get('assistantBusinessId'), outcome = row.get('outcome'), parents = row.get('parents');
813
+ if (typeof requestId !== 'string' || typeof assistantBusinessId !== 'string' || outcome === undefined || !Array.isArray(parents))
814
+ throw invalid('batch command');
815
+ return { type, requestId, assistantBusinessId, outcome, parents: parents.map(decodeParent) };
816
+ }
817
+ const latestUserMsgId = row.get('latestUserMsgId'), state = row.get('state');
818
+ if (type !== 'dispatch' || typeof latestUserMsgId !== 'string' || (state !== 'pending' && state !== 'published'))
819
+ throw invalid('batch command');
820
+ return { type, latestUserMsgId, state };
821
+ });
822
+ }
823
+ function turnEnvelope(result) {
824
+ if (result.kind !== 'found')
825
+ return;
826
+ const body = 'contentJson' in result.turn ? decodeJson(encodeUtf8(result.turn.contentJson)) : result.turn.content;
827
+ return body instanceof Map ? body : undefined;
828
+ }
829
+ async function readFound(host, id) {
830
+ const result = await host.lookup(id);
831
+ if (!result || result.kind !== 'found')
832
+ return;
833
+ const envelope = turnEnvelope(result);
834
+ if (!envelope)
835
+ return;
836
+ return { turnId: result.turn.turnId.slice(), nextSeq: result.turn.nextSeq, sealed: !!result.turn.sealed, inner: envelope.get('content') };
837
+ }
838
+ function encodeProjected(row) {
839
+ return new Map([['businessId', row.businessId], ['segmentId', row.segmentId], ['turnId', hexBytes(row.turnId)], ['nextSeq', { kind: 'u64', value: row.nextSeq }], ['sealed', row.sealed], ['content', row.content]]);
840
+ }
841
+ // Membership is durable; content and revision belong to the Turn. Legacy v1
842
+ // rows containing full snapshots remain readable, without a migration scan.
843
+ function projectedValue(row) {
844
+ return encodeJson(new Map([['version', '2'], ['businessId', row.businessId], ['segmentId', row.segmentId]]));
845
+ }
846
+ function publishedIdentity(raw, id) {
847
+ const row = asMap(decodeJson(raw), 'published identity');
848
+ if (id.length !== 16 || (row.has('version') && row.get('version') !== '2'))
849
+ throw invalid('published identity');
850
+ const businessId = row.get('businessId'), segmentId = row.get('segmentId');
851
+ if (typeof businessId !== 'string' || typeof segmentId !== 'string')
852
+ throw invalid('published identity');
853
+ return { businessId: text(businessId), segmentId: text(segmentId), turnId: id.slice() };
854
+ }
855
+ function messageKey(businessId, segmentId) { return decodeUtf8(keyOf({ kind: 'message', businessId, segmentId })); }
856
+ async function writeIndexed(host, writes, puts, expectedEventCursor) {
857
+ if (!writes.length && !puts.length)
858
+ return;
859
+ if (host instanceof LodyHistory) {
860
+ await host.stream.writer(host.identity).writeBatch(writes.map((w) => {
861
+ if (w.kind === 'createOnce')
862
+ return { kind: 'createOnce', key: w.key, parents: w.parents, content: w.content };
863
+ if (w.kind === 'seal')
864
+ return { kind: 'seal', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq };
865
+ if (w.kind === 'sealOnce')
866
+ return { kind: 'sealOnce', key: w.key, expectedNextSeq: w.expectedNextSeq };
867
+ if (w.kind === 'editOnce')
868
+ return { kind: 'editOnce', key: w.key, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: [{ key: 'content' }], value: w.value }] };
869
+ if (w.kind === 'editPath')
870
+ return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: w.path, value: w.value }] };
871
+ return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: [{ key: 'content' }], value: w.value }] };
872
+ }), puts, expectedEventCursor);
873
+ return;
874
+ }
875
+ await host.stream.writeBatch(writes.map((w) => {
876
+ if (w.kind === 'createOnce')
877
+ return { kind: 'createOnce', key: w.key, parents: w.parents, contentJson: decodeUtf8(encodeJson(w.content)) };
878
+ if (w.kind === 'seal')
879
+ return { kind: 'seal', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq };
880
+ if (w.kind === 'sealOnce')
881
+ return { kind: 'sealOnce', key: w.key, expectedNextSeq: w.expectedNextSeq };
882
+ if (w.kind === 'editOnce')
883
+ return { kind: 'editOnce', key: w.key, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: [{ key: 'content' }], contentJson: decodeUtf8(encodeJson(w.value)) }] };
884
+ if (w.kind === 'editPath')
885
+ return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: w.path, contentJson: decodeUtf8(encodeJson(w.value)) }] };
886
+ return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: [{ key: 'content' }], contentJson: decodeUtf8(encodeJson(w.value)) }] };
887
+ }), { indexPuts: puts, expectedEventCursor });
888
+ }
889
+ async function maybePublishAccept(host, input, options, turnId) {
890
+ if (options?.publish === false || input.kind !== 'message')
891
+ return;
892
+ const [raw] = await indexValues(host, [{ table: PUBLICATION_OBJECTS, key: turnId }]);
893
+ if (!raw)
894
+ throw new StoreError('corrupt', 'publication source missing');
895
+ const object = JSON.parse(decodeUtf8(raw));
896
+ if (object.direct)
897
+ return; // catchUpIndex has already published the Create marker.
898
+ const [, businessId, segmentId] = JSON.parse(object.key);
899
+ const target = { businessId: businessId, segmentId: segmentId, turnId };
900
+ const proof = await host.accept({ kind: 'publication', businessId: hexBytes(turnId), segmentId: 'v1', parents: [], content: new Map([
901
+ ['status', 'committed'], ['published', publicationValue([{ businessId: target.businessId, segmentId: target.segmentId, turnId: hexBytes(turnId), digest: object.digest, nextSeq: '1', sealed: false }])],
902
+ ]) }, { publish: false });
903
+ for (let attempt = 0; attempt < 4; attempt++) {
904
+ const header = await publicationPort(host).header(proof.turnId);
905
+ if (!header)
906
+ throw new StoreError('corrupt', 'publication proof missing');
907
+ try {
908
+ await writeIndexed(host, header.sealed ? [] : [{ kind: 'seal', turnId: proof.turnId, expectedNextSeq: header.nextSeq }], [
909
+ ...await putsForPublished(host, [target]), { table: PUBLICATION_DONE, key: proof.turnId, value: encodeUtf8('1') },
910
+ ]);
911
+ return;
912
+ }
913
+ catch (error) {
914
+ if (errorCode(error) !== 'stale' && errorCode(error) !== 'sealed')
915
+ throw error;
916
+ }
917
+ }
918
+ throw new StoreError('stale', 'publication retry budget exhausted');
919
+ }
920
+ async function putsForPublished(host, rows) {
921
+ const puts = [];
922
+ for (const row of rows) {
923
+ const idKey = keyOf({ kind: 'message', businessId: row.businessId, segmentId: row.segmentId });
924
+ if (row.onceKey) {
925
+ puts.push({ table: 'lody_history_published_id_v1', key: idKey, value: new Uint8Array(), onceKey: row.onceKey });
926
+ puts.push({ table: 'lody_history_published_v1', key: new Uint8Array(), value: projectedValue(row), onceKey: row.onceKey, emitEvent: true });
927
+ continue;
928
+ }
929
+ const prior = await publishedId(host, { kind: 'message', businessId: row.businessId, segmentId: row.segmentId });
930
+ if (prior && !equal(prior, row.turnId))
931
+ throw new StoreError('conflict', 'published identity changed');
932
+ const key = row.turnId;
933
+ puts.push({ table: 'lody_history_published_id_v1', key: idKey, value: key.slice() });
934
+ puts.push({ table: 'lody_history_published_v1', key: key.slice(), value: projectedValue(row), emitEvent: true });
935
+ }
936
+ return puts;
937
+ }
938
+ async function scanPublished(host, input) {
939
+ const table = 'lody_history_published_v1';
940
+ if (host instanceof LodyHistory) {
941
+ return input.reverse
942
+ ? host.stream.scanIndexReverse(table, input.end ?? null, input.limit)
943
+ : host.stream.scanIndex(table, input.start ?? new Uint8Array(), input.limit);
944
+ }
945
+ if (input.reverse) {
946
+ const scan = host.stream.scanIndexReverse;
947
+ if (!scan)
948
+ throw invalid('projection reverse scan');
949
+ return scan.call(host.stream, table, input.end ?? null, BigInt(input.limit));
950
+ }
951
+ return host.stream.scanIndex(table, input.start ?? new Uint8Array(), BigInt(input.limit));
952
+ }
953
+ function pageInput(input) {
954
+ const limit = input.limit ?? 100;
955
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
956
+ throw invalid('projection page limit');
957
+ if (input.after && (input.before || input.latest))
958
+ throw invalid('projection cursor');
959
+ if (input.after && input.after.length !== 16)
960
+ throw invalid('projection cursor');
961
+ if (input.before && input.before.length !== 16)
962
+ throw invalid('projection cursor');
963
+ return { ...input, after: input.after?.slice(), before: input.before?.slice(), limit };
964
+ }
965
+ async function publishedMembers(host, input) {
966
+ const { limit, after, before, latest } = pageInput(input), reverse = !!(latest || before);
967
+ const page = await scanPublished(host, reverse
968
+ ? { reverse: true, end: before ?? null, limit: limit + 1 }
969
+ : { start: after ? afterIndexKey(after) : new Uint8Array(), limit: limit + 1 });
970
+ const members = page.slice(0, limit).map(row => publishedIdentity(row.value, row.key));
971
+ if (reverse)
972
+ members.reverse();
973
+ return { members, hasMore: page.length > limit, cursor: (reverse ? members[0] : members.at(-1))?.turnId.slice() ?? null };
974
+ }
975
+ async function publishedPage(host, input) {
976
+ const { members, ...page } = await publishedMembers(host, input);
977
+ return { ...page, messages: await hydratePublished(host, members) };
978
+ }
979
+ function uniqueIds(ids) {
980
+ if (ids.length > 1000)
981
+ throw invalid('projection id limit');
982
+ const unique = new Map();
983
+ for (const id of ids) {
984
+ if (id.length !== 16)
985
+ throw invalid('projection id');
986
+ unique.set(hexBytes(id), id.slice());
987
+ }
988
+ return [...unique.values()];
989
+ }
990
+ async function indexValues(host, keys) {
991
+ if (!keys.length)
992
+ return [];
993
+ if (host instanceof NodeLodyHistory)
994
+ return host.stream.readIndex(keys);
995
+ const stream = host.stream;
996
+ return stream.store.run(false, stream.id, function* (tx) {
997
+ const values = [];
998
+ for (const key of keys)
999
+ values.push((yield* tx.get(stream.space(key.table), key.key)) ?? null);
1000
+ return values;
1001
+ });
1002
+ }
1003
+ async function publishedById(host, ids) {
1004
+ const out = [];
1005
+ for (let offset = 0; offset < ids.length; offset += 1000) {
1006
+ const page = ids.slice(offset, offset + 1000);
1007
+ const values = await indexValues(host, page.map(key => ({ table: 'lody_history_published_v1', key })));
1008
+ for (let i = 0; i < page.length; i++)
1009
+ if (values[i] !== null)
1010
+ out.push(publishedIdentity(values[i], page[i]));
1011
+ }
1012
+ return out;
1013
+ }
1014
+ async function hydratePublished(host, members) {
1015
+ const rows = [];
1016
+ for (let offset = 0; offset < members.length; offset += 1000) {
1017
+ const page = members.slice(offset, offset + 1000);
1018
+ const results = await host.stream.readTurns(page.map(row => row.turnId));
1019
+ if (results.length !== page.length)
1020
+ throw new StoreError('corrupt', 'published bodies missing');
1021
+ for (let i = 0; i < page.length; i++) {
1022
+ const result = results[i], turn = result.kind === 'found' ? result.turn : result.kind === 'incomplete' ? result.prefix : null;
1023
+ // Pending successors do not erase an already applied, published prefix.
1024
+ if (!turn || !equal(turn.turnId, page[i].turnId))
1025
+ throw new StoreError('corrupt', 'published Turn missing');
1026
+ const body = 'contentJson' in turn ? decodeJson(encodeUtf8(turn.contentJson)) : turn.content;
1027
+ if (!(body instanceof Map) || !body.has('content'))
1028
+ throw invalid('history envelope');
1029
+ rows.push({ ...page[i], content: body.get('content'), nextSeq: turn.nextSeq, sealed: !!turn.sealed });
1030
+ }
1031
+ }
1032
+ return rows;
1033
+ }
1034
+ async function publishedId(host, identity) {
1035
+ const [id] = await indexValues(host, [{ table: 'lody_history_published_id_v1', key: keyOf(identity) }]);
1036
+ return id ?? undefined;
1037
+ }
1038
+ async function lookupPublished(host, identity) {
1039
+ return (await stableRead(host, async () => {
1040
+ const id = await publishedId(host, identity);
1041
+ return id ? (await hydratePublished(host, await publishedById(host, [id])))[0] : undefined;
1042
+ })).value;
1043
+ }
1044
+ async function localEvents(host, after, limit) {
1045
+ return host instanceof LodyHistory ? host.stream.eventsAfter(after, limit) : host.stream.eventsAfter(after, BigInt(limit));
1046
+ }
1047
+ /** Index and body reads may be separate transactions/RPCs. The durable local
1048
+ * journal fences both, including publication-only commits. No wall-clock IDs. */
1049
+ async function stableRead(host, read) {
1050
+ for (let attempt = 0; attempt < 4; attempt++) {
1051
+ const cursor = await host.observedEventCursor();
1052
+ const value = await read(cursor);
1053
+ if (!(await localEvents(host, cursor, 1)).length)
1054
+ return { value, cursor };
1055
+ }
1056
+ throw new StoreError('stale', 'history read retry budget exhausted');
1057
+ }
1058
+ async function captureBases(host, commands) {
1059
+ const seen = new Set(), bases = [];
1060
+ for (const command of commands) {
1061
+ if ((command.type !== 'setContent' && command.type !== 'finish') || command.identity.kind !== 'message')
1062
+ continue;
1063
+ const key = messageKey(command.identity.businessId, command.identity.segmentId);
1064
+ if (seen.has(key))
1065
+ continue;
1066
+ seen.add(key);
1067
+ const published = await lookupPublished(host, command.identity);
1068
+ if (published) {
1069
+ bases.push(published);
1070
+ continue;
1071
+ }
1072
+ const found = await readFound(host, command.identity);
1073
+ if (found?.inner !== undefined)
1074
+ bases.push({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed });
1075
+ }
1076
+ return bases;
1077
+ }
1078
+ async function messageEndStates(host, commands) {
1079
+ const seen = new Set(), rows = [];
1080
+ for (const command of commands) {
1081
+ if (!('identity' in command) || command.identity.kind !== 'message')
1082
+ continue;
1083
+ const key = messageKey(command.identity.businessId, command.identity.segmentId);
1084
+ if (seen.has(key))
1085
+ continue;
1086
+ seen.add(key);
1087
+ const found = await readFound(host, command.identity);
1088
+ if (found?.inner !== undefined)
1089
+ rows.push({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed });
1090
+ }
1091
+ return rows;
1092
+ }
1093
+ async function patchReceipt(host, identity, path, value) {
1094
+ const found = await readFound(host, identity);
1095
+ if (!found || found.sealed)
1096
+ throw invalid('batch receipt not writable');
1097
+ if (host instanceof LodyHistory)
1098
+ await host.append(found.turnId, found.nextSeq, [{ kind: 'set', path, value }]);
1099
+ else
1100
+ await host.append(found.turnId, found.nextSeq, [{ kind: 'set', path, contentJson: decodeUtf8(encodeJson(value)) }]);
1101
+ }
1102
+ async function markFailed(host, identity, code) {
1103
+ const found = await readFound(host, identity);
1104
+ if (!found || found.sealed)
1105
+ return;
1106
+ try {
1107
+ await patchReceipt(host, identity, [{ key: 'status' }], 'failed');
1108
+ await patchReceipt(host, identity, [{ key: 'error' }], code);
1109
+ const next = await readFound(host, identity);
1110
+ if (next && !next.sealed)
1111
+ await host.finish(next.turnId, next.nextSeq);
1112
+ }
1113
+ catch { /* failed marker is best-effort so later batches can proceed */ }
1114
+ }
1115
+ function permissionIdentity(requestId) {
1116
+ return { kind: 'permission_response', businessId: text(requestId), segmentId: 'response' };
1117
+ }
1118
+ function dispatchIdentity(latestUserMsgId, state) {
1119
+ return { kind: 'dispatch_intent', businessId: `dispatch:${latestUserMsgId}`, segmentId: state };
1120
+ }
1121
+ async function finalizeReceipt(host, identity) {
1122
+ for (let attempt = 0; attempt < 4; attempt++) {
1123
+ const found = await readFound(host, identity);
1124
+ if (!found)
1125
+ throw invalid('batch receipt missing after apply');
1126
+ if (found.sealed)
1127
+ return found.nextSeq;
1128
+ const status = found.inner instanceof Map ? found.inner.get('status') : undefined;
1129
+ try {
1130
+ if (status !== 'committed')
1131
+ await patchReceipt(host, identity, [{ key: 'status' }], 'committed');
1132
+ else
1133
+ await host.finish(found.turnId, found.nextSeq);
1134
+ }
1135
+ catch (error) {
1136
+ const code = errorCode(error);
1137
+ if (code !== 'stale' && code !== 'sealed')
1138
+ throw error;
1139
+ }
1140
+ }
1141
+ const done = await readFound(host, identity);
1142
+ if (done?.sealed)
1143
+ return done.nextSeq;
1144
+ throw new StoreError('stale', 'batch receipt not committed');
1145
+ }
1146
+ function plannedMessage(id, found, planned) {
1147
+ const prior = planned.get(messageKey(id.businessId, id.segmentId));
1148
+ if (prior)
1149
+ return prior;
1150
+ if (found?.inner === undefined)
1151
+ return;
1152
+ return { businessId: id.businessId, segmentId: id.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed };
1153
+ }
1154
+ async function collectBatchWrites(host, identity, commands, applied) {
1155
+ const writes = [];
1156
+ const planned = new Map();
1157
+ const remember = (row) => { planned.set(messageKey(row.businessId, row.segmentId), row); };
1158
+ for (let index = 0; index < commands.length; index++) {
1159
+ const command = commands[index];
1160
+ if (index < applied) {
1161
+ if (command.type === 'accept' && command.identity.kind === 'message') {
1162
+ const found = await readFound(host, command.identity);
1163
+ if (found?.inner !== undefined)
1164
+ remember({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed });
1165
+ }
1166
+ continue;
1167
+ }
1168
+ if (command.type === 'accept') {
1169
+ const input = { ...command.identity, parents: command.parents, content: command.content, attachments: command.attachments };
1170
+ const found = await readFound(host, command.identity);
1171
+ if (found)
1172
+ await host.accept(input, { publish: false });
1173
+ else
1174
+ writes.push({ kind: 'createOnce', key: keyOf(command.identity), parents: command.parents, content: envelope(input) });
1175
+ if (command.identity.kind === 'message') {
1176
+ remember(found?.inner !== undefined
1177
+ ? { businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed }
1178
+ : { businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: new Uint8Array(16), content: command.content, nextSeq: 1n, sealed: false, onceKey: keyOf(command.identity) });
1179
+ }
1180
+ continue;
1181
+ }
1182
+ if (command.type === 'setContent' || command.type === 'finish') {
1183
+ const found = await readFound(host, command.identity);
1184
+ const current = plannedMessage(command.identity, found, planned);
1185
+ if (!current)
1186
+ throw invalid(command.type === 'finish' ? 'batch finish missing' : 'batch target missing');
1187
+ if (current.nextSeq !== command.expectedNextSeq)
1188
+ throw new StoreError(current.sealed ? 'sealed' : 'stale', 'batch target revision changed');
1189
+ if (command.type === 'setContent') {
1190
+ if (current.sealed)
1191
+ throw new StoreError('sealed', 'batch setContent target sealed');
1192
+ if (current.onceKey)
1193
+ writes.push({ kind: 'editOnce', key: current.onceKey, expectedNextSeq: command.expectedNextSeq, value: command.content });
1194
+ else
1195
+ writes.push({ kind: 'edit', turnId: current.turnId, expectedNextSeq: command.expectedNextSeq, value: command.content });
1196
+ remember({ ...current, content: command.content, nextSeq: command.expectedNextSeq + 1n, sealed: false });
1197
+ }
1198
+ else {
1199
+ if (current.onceKey)
1200
+ writes.push({ kind: 'sealOnce', key: current.onceKey, expectedNextSeq: command.expectedNextSeq });
1201
+ else
1202
+ writes.push({ kind: 'seal', turnId: current.turnId, expectedNextSeq: command.expectedNextSeq });
1203
+ remember({ ...current, nextSeq: command.expectedNextSeq + 1n, sealed: true });
1204
+ }
1205
+ continue;
1206
+ }
1207
+ if (command.type === 'permission') {
1208
+ const id = permissionIdentity(command.requestId);
1209
+ const input = { ...id, parents: command.parents, content: new Map([['assistantBusinessId', text(command.assistantBusinessId)], ['outcome', command.outcome]]) };
1210
+ const found = await readFound(host, id);
1211
+ if (found)
1212
+ await host.accept(input, { publish: false });
1213
+ else
1214
+ writes.push({ kind: 'createOnce', key: keyOf(id), parents: command.parents, content: envelope(input) });
1215
+ if (!found || !found.sealed)
1216
+ writes.push({ kind: 'sealOnce', key: keyOf(id), expectedNextSeq: found?.nextSeq ?? 1n });
1217
+ continue;
1218
+ }
1219
+ const id = dispatchIdentity(command.latestUserMsgId, command.state);
1220
+ const input = { ...id, parents: [], content: new Map([['latestUserMsgId', command.latestUserMsgId], ['state', command.state]]) };
1221
+ const found = await readFound(host, id);
1222
+ if (found)
1223
+ await host.accept(input, { publish: false });
1224
+ else
1225
+ writes.push({ kind: 'createOnce', key: keyOf(id), parents: [], content: envelope(input) });
1226
+ }
1227
+ const receipt = await readFound(host, identity);
1228
+ if (!receipt)
1229
+ throw invalid('batch receipt missing');
1230
+ const unique = [...planned.values()];
1231
+ const puts = await putsForPublished(host, unique);
1232
+ const refs = [];
1233
+ for (const row of unique) {
1234
+ const id = { kind: 'message', businessId: row.businessId, segmentId: row.segmentId };
1235
+ const [raw] = await indexValues(host, [{ table: NODE_BINDINGS, key: keyOf(id) }]);
1236
+ const original = raw ? binding(raw) : undefined;
1237
+ const command = commands.find(c => c.type === 'accept' && equal(keyOf(c.identity), keyOf(id)));
1238
+ const owner = host instanceof LodyHistory ? host.identity.owner() : host.owner;
1239
+ const digest = original ? hexBytes(Uint8Array.from(original.digest)) : command?.type === 'accept' ? hexBytes(createDigest(owner, command.parents, envelope({ ...command.identity, parents: command.parents, content: command.content, attachments: command.attachments }))) : undefined;
1240
+ if (!digest)
1241
+ throw invalid('publication input missing');
1242
+ refs.push({ businessId: row.businessId, segmentId: row.segmentId, digest, nextSeq: row.nextSeq.toString(), sealed: row.sealed, ...(row.onceKey ? {} : { turnId: hexBytes(row.turnId) }) });
1243
+ }
1244
+ puts.push({ table: PUBLICATION_DONE, key: receipt.turnId, value: encodeUtf8('1') });
1245
+ writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq, path: [{ key: 'content' }, { key: 'applied' }], value: { kind: 'u64', value: BigInt(commands.length) } });
1246
+ writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 1n, path: [{ key: 'content' }, { key: 'published' }], value: publicationValue(refs) });
1247
+ writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 2n, path: [{ key: 'content' }, { key: 'status' }], value: 'committed' });
1248
+ writes.push({ kind: 'seal', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 3n });
1249
+ return { writes, puts };
1250
+ }
1251
+ async function runBatchCommands(host, identity, commands, applied) {
1252
+ let lastStale;
1253
+ for (let attempt = 0; attempt < 4; attempt++) {
1254
+ try {
1255
+ // Bind the plan to the indexed history it was prepared from. Fetching
1256
+ // a newer cursor after planning could bless a now-stale absence read
1257
+ // when a peer created the same business identity in the meantime.
1258
+ const cursor = await host.observedEventCursor();
1259
+ const { writes, puts } = await collectBatchWrites(host, identity, commands, applied);
1260
+ await writeIndexed(host, writes, puts, cursor);
1261
+ return;
1262
+ }
1263
+ catch (error) {
1264
+ if (errorCode(error) !== 'stale')
1265
+ throw error;
1266
+ lastStale = error;
1267
+ await host.catchUpIndex();
1268
+ }
1269
+ }
1270
+ throw lastStale ?? new StoreError('stale', 'batch apply retry budget exhausted');
1271
+ }
1272
+ async function commitBatch(host, batchId, commands) {
1273
+ if (!batchId.length || encodeUtf8(batchId).length > 1024)
1274
+ throw invalid('batch id');
1275
+ if (!commands.length || commands.length > 64)
1276
+ throw invalid('batch size');
1277
+ await host.catchUpIndex();
1278
+ const digest = commandDigest(batchId, commands);
1279
+ const identity = { kind: 'batch_receipt', businessId: batchId, segmentId: 'v1' };
1280
+ let existing = await readFound(host, identity);
1281
+ let created = false;
1282
+ if (!existing) {
1283
+ const bases = await captureBases(host, commands);
1284
+ const receiptContent = new Map([['status', 'pending'], ['digest', hexBytes(digest)], ['commands', encodeCommands(commands)], ['bases', bases.map(encodeProjected)], ['applied', { kind: 'u64', value: 0n }]]);
1285
+ const receipt = await host.accept({ ...identity, parents: [], content: receiptContent }, { publish: false });
1286
+ created = receipt.created;
1287
+ existing = await readFound(host, identity);
1288
+ }
1289
+ if (!existing)
1290
+ throw invalid('batch receipt missing');
1291
+ const stored = existing.inner instanceof Map ? existing.inner.get('digest') : undefined;
1292
+ if (stored !== hexBytes(digest))
1293
+ throw new StoreError('conflict', 'batch commands changed');
1294
+ const status = existing.inner instanceof Map ? existing.inner.get('status') : undefined;
1295
+ if (status === 'committed')
1296
+ return { batchId, created: false, revision: existing.nextSeq };
1297
+ if (status === 'failed')
1298
+ throw new StoreError('invalid', 'batch previously failed');
1299
+ const applied = existing.inner instanceof Map && existing.inner.get('applied') !== undefined ? Number(seqOf(existing.inner.get('applied'))) : 0;
1300
+ try {
1301
+ await runBatchCommands(host, identity, commands, applied);
1302
+ return { batchId, created, revision: await finalizeReceipt(host, identity) };
1303
+ }
1304
+ catch (error) {
1305
+ const code = errorCode(error);
1306
+ if (isSemanticFailure(code))
1307
+ await markFailed(host, identity, code);
1308
+ throw error;
1309
+ }
1310
+ }
1311
+ async function recoverBatches(host) {
1312
+ await host.catchUpIndex();
1313
+ const rows = pendingBatchRows(host);
1314
+ for await (const row of rows) {
1315
+ if (row.identity.kind !== 'batch_receipt' || row.binding.conflict)
1316
+ continue;
1317
+ const owner = host instanceof LodyHistory ? host.identity.owner() : host.owner;
1318
+ if (!equal(Uint8Array.from(row.binding.owner), owner))
1319
+ continue;
1320
+ const found = await readFound(host, row.identity);
1321
+ if (!found || found.sealed)
1322
+ continue;
1323
+ if (!(found.inner instanceof Map))
1324
+ continue;
1325
+ const status = found.inner.get('status');
1326
+ if (status === 'failed' || status === 'committed')
1327
+ continue;
1328
+ const digest = found.inner.get('digest'), encoded = found.inner.get('commands');
1329
+ if (typeof digest !== 'string' || encoded === undefined) {
1330
+ await markFailed(host, row.identity, 'invalid');
1331
+ continue;
1332
+ }
1333
+ try {
1334
+ const commands = decodeCommands(encoded);
1335
+ if (hexBytes(commandDigest(row.identity.businessId, commands)) !== digest)
1336
+ throw new StoreError('corrupt', 'pending batch digest mismatch');
1337
+ const applied = found.inner.get('applied') !== undefined ? Number(seqOf(found.inner.get('applied'))) : 0;
1338
+ await runBatchCommands(host, row.identity, commands, applied);
1339
+ await finalizeReceipt(host, row.identity);
1340
+ }
1341
+ catch (error) {
1342
+ const code = errorCode(error);
1343
+ if (isSemanticFailure(code))
1344
+ await markFailed(host, row.identity, code);
1345
+ }
1346
+ }
1347
+ }
1348
+ async function* pendingBatchRows(host) {
1349
+ const port = publicationPort(host);
1350
+ let start = new Uint8Array();
1351
+ for (;;) {
1352
+ const page = await port.scanIndex(NODE_PENDING, start, 128);
1353
+ const values = await indexValues(host, page.map(row => ({ table: NODE_BINDINGS, key: row.value })));
1354
+ for (let i = 0; i < page.length; i++) {
1355
+ const identity = identityFromKey(decodeUtf8(page[i].value));
1356
+ if (!identity || values[i] === null)
1357
+ throw new StoreError('corrupt', 'pending receipt binding missing');
1358
+ yield { identity, binding: binding(values[i]) };
1359
+ }
1360
+ if (page.length < 128)
1361
+ return;
1362
+ start = afterIndexKey(page.at(-1).key);
1363
+ }
1364
+ }
1365
+ async function projectedMessagePage(host, input) {
1366
+ const copied = pageInput(input);
1367
+ return (await stableRead(host, () => publishedPage(host, copied))).value;
1368
+ }
1369
+ async function projectedMessages(host) {
1370
+ return (await stableRead(host, async () => {
1371
+ const out = [];
1372
+ let after;
1373
+ for (;;) {
1374
+ const page = await publishedPage(host, { after, limit: 1000 });
1375
+ out.push(...page.messages);
1376
+ if (!page.hasMore || !page.cursor)
1377
+ return out;
1378
+ after = page.cursor;
1379
+ }
1380
+ })).value;
1381
+ }
1382
+ /** Loaded latest window plus any explicitly loaded older pages. Refresh consumes
1383
+ * local events and reads only affected published bodies, never the whole page.
1384
+ * A view is stream-local and consumer-owned; recreate it after closing the host. */
1385
+ export class HistoryMessageView {
1386
+ host;
1387
+ limit;
1388
+ state;
1389
+ queue = Promise.resolve();
1390
+ closed = false;
1391
+ constructor(host, limit = 40) {
1392
+ this.host = host;
1393
+ this.limit = limit;
1394
+ pageInput({ limit });
1395
+ }
1396
+ get snapshot() { return this.state; }
1397
+ initialize() { return this.enqueue(false); }
1398
+ refresh() { return this.enqueue(false); }
1399
+ loadOlder() { return this.enqueue(true); }
1400
+ dispose() { this.closed = true; }
1401
+ enqueue(older) {
1402
+ const result = this.queue.then(async () => {
1403
+ if (this.closed)
1404
+ throw new StoreError('closed', 'history view disposed');
1405
+ const next = await this.read(older);
1406
+ if (this.closed)
1407
+ throw new StoreError('closed', 'history view disposed');
1408
+ // Only successful, serialized reads advance the consumer cursor and cache.
1409
+ this.state = next;
1410
+ return next;
1411
+ });
1412
+ this.queue = result.catch(() => { });
1413
+ return result;
1414
+ }
1415
+ async read(older) {
1416
+ const previous = this.state;
1417
+ const { value, cursor } = await stableRead(this.host, async (through) => {
1418
+ if (!previous) {
1419
+ const page = await publishedPage(this.host, { latest: true, limit: this.limit });
1420
+ return { messages: page.messages, changed: page.messages, hasMoreOlder: page.hasMore };
1421
+ }
1422
+ let hasMoreOlder = previous.hasMoreOlder;
1423
+ const members = new Map();
1424
+ let boundary = hasMoreOlder ? previous.messages[0]?.turnId : undefined;
1425
+ if (older && hasMoreOlder && boundary) {
1426
+ const page = await publishedMembers(this.host, { before: boundary, limit: this.limit });
1427
+ for (const row of page.members)
1428
+ members.set(hexBytes(row.turnId), row);
1429
+ hasMoreOlder = page.hasMore;
1430
+ boundary = hasMoreOlder ? page.members[0]?.turnId ?? boundary : undefined;
1431
+ }
1432
+ const candidates = new Map();
1433
+ let after = previous.eventCursor;
1434
+ while (after < through) {
1435
+ const events = await localEvents(this.host, after, 128);
1436
+ if (!events.length)
1437
+ throw new StoreError('corrupt', 'history event gap');
1438
+ for (const record of events) {
1439
+ if (record.cursor > through)
1440
+ break;
1441
+ after = record.cursor;
1442
+ const event = record.event;
1443
+ const id = event.kind === 'changed' && 'update' in event ? event.update?.turnId
1444
+ : event.kind === 'indexChanged' && 'table' in event && event.table === 'lody_history_published_v1' && 'key' in event ? event.key : undefined;
1445
+ if (id && (!boundary || hexBytes(id) >= hexBytes(boundary)))
1446
+ candidates.set(hexBytes(id), id);
1447
+ }
1448
+ }
1449
+ // Members from the older page are already selected; do not fetch their index twice.
1450
+ const ids = [...candidates].filter(([key]) => !members.has(key)).map(([, id]) => id);
1451
+ for (const row of await publishedById(this.host, ids))
1452
+ members.set(hexBytes(row.turnId), row);
1453
+ const current = new Map(previous.messages.map(row => [hexBytes(row.turnId), row]));
1454
+ const changed = [];
1455
+ for (const row of await hydratePublished(this.host, [...members.values()])) {
1456
+ const key = hexBytes(row.turnId), old = current.get(key);
1457
+ if (old && row.nextSeq < old.nextSeq)
1458
+ throw new StoreError('corrupt', 'history revision regressed');
1459
+ if (!old || row.nextSeq !== old.nextSeq || row.sealed !== old.sealed) {
1460
+ current.set(key, row);
1461
+ changed.push(row);
1462
+ }
1463
+ }
1464
+ const messages = changed.length ? [...current.values()].sort((a, b) => hexBytes(a.turnId).localeCompare(hexBytes(b.turnId))) : previous.messages;
1465
+ return { messages, changed, hasMoreOlder };
1466
+ });
1467
+ return { ...value, eventCursor: cursor };
1468
+ }
1469
+ }
1470
+ /** Application conversion only: safe integers use integer tags; every other
1471
+ * finite JS number keeps its actual IEEE value as f64, including -0. This cannot
1472
+ * recover precision already lost before the caller supplied a Number. */
1473
+ export function fromApplicationJson(input) {
1474
+ const active = new Set();
1475
+ function visit(value, depth) {
1476
+ if (value === null || typeof value === 'boolean')
1477
+ return value;
1478
+ if (typeof value === 'string') {
1479
+ encodeUtf8(value);
1480
+ return value;
1481
+ }
1482
+ if (typeof value === 'number') {
1483
+ if (!Number.isFinite(value))
1484
+ throw invalid('nonfinite application number');
1485
+ return Number.isSafeInteger(value) && !Object.is(value, -0)
1486
+ ? { kind: value >= 0 ? 'u64' : 'i64', value: BigInt(value) } : { kind: 'f64', value };
1487
+ }
1488
+ if (typeof value === 'bigint') {
1489
+ if (value < -(1n << 63n) || value > (1n << 64n) - 1n)
1490
+ throw invalid('application integer range');
1491
+ return { kind: value >= 0n ? 'u64' : 'i64', value };
1492
+ }
1493
+ if (typeof value !== 'object')
1494
+ throw invalid('non-JSON application value');
1495
+ if (depth >= MAX_JSON_DEPTH || active.has(value))
1496
+ throw invalid('application JSON depth or cycle');
1497
+ const array = Array.isArray(value), prototype = Object.getPrototypeOf(value);
1498
+ if ((array && prototype !== Array.prototype) || (!array && prototype !== Object.prototype && prototype !== null))
1499
+ throw invalid('non-JSON application object');
1500
+ const keys = Reflect.ownKeys(value), descriptors = Object.getOwnPropertyDescriptors(value);
1501
+ for (const key of keys) {
1502
+ if (typeof key !== 'string')
1503
+ throw invalid('application symbol property');
1504
+ if (array && key === 'length')
1505
+ continue;
1506
+ const d = descriptors[key];
1507
+ if (!d.enumerable || !('value' in d))
1508
+ throw invalid('application accessor or hidden property');
1509
+ encodeUtf8(key);
1510
+ }
1511
+ active.add(value);
1512
+ try {
1513
+ if (array) {
1514
+ if (keys.length !== value.length + 1)
1515
+ throw invalid('application sparse or extended array');
1516
+ const result = [];
1517
+ for (let i = 0; i < value.length; i++) {
1518
+ const d = descriptors[String(i)];
1519
+ if (!d || !('value' in d))
1520
+ throw invalid('application sparse array');
1521
+ result.push(visit(d.value, depth + 1));
1522
+ }
1523
+ return result;
1524
+ }
1525
+ const result = new Map();
1526
+ for (const key of keys)
1527
+ result.set(key, visit(descriptors[key].value, depth + 1));
1528
+ return result;
1529
+ }
1530
+ finally {
1531
+ active.delete(value);
1532
+ }
1533
+ }
1534
+ const result = visit(input, 0);
1535
+ encodeJson(result);
1536
+ return result;
1537
+ }
1538
+ /** Integer tags outside the safe range return bigint, never a rounded Number. */
1539
+ export function toApplicationJson(input) {
1540
+ // Validate the existing lossless contract before recursive conversion.
1541
+ encodeJson(input);
1542
+ function visit(value) {
1543
+ if (value === null || typeof value !== 'object')
1544
+ return value;
1545
+ if (Array.isArray(value))
1546
+ return value.map(visit);
1547
+ if (value instanceof Map) {
1548
+ const result = {};
1549
+ for (const [key, item] of value)
1550
+ Object.defineProperty(result, key, { value: visit(item), enumerable: true, configurable: true, writable: true });
1551
+ return result;
1552
+ }
1553
+ if (value.kind === 'f64')
1554
+ return value.value;
1555
+ return value.value >= BigInt(Number.MIN_SAFE_INTEGER) && value.value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value.value) : value.value;
1556
+ }
1557
+ return visit(input);
1558
+ }
1559
+ export function applicationJsonText(input) { return decodeUtf8(encodeJson(fromApplicationJson(input))); }