@agentshouse/mdruntime-adapter 0.1.0-c29c7d612b2d0 → 0.1.0-c2c26e195d3bc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/read.js CHANGED
@@ -1,4 +1,12 @@
1
- import { readPosition, roomVersion } from './version.js';
1
+ import { DECIMAL, readPosition, roomVersion } from './version.js';
2
+ const REVISION_FILE = /^fr_([0-9a-z]+)\.[0-9a-z]+\.[0-9a-z]$/u;
3
+ export function identities(revisions) {
4
+ const fileIds = Object.fromEntries(Object.entries(revisions).flatMap(([path, revision]) => {
5
+ const file = REVISION_FILE.exec(revision)?.[1];
6
+ return file === undefined ? [] : [[path, file]];
7
+ }));
8
+ return Object.keys(fileIds).length === 0 ? {} : { fileIds };
9
+ }
2
10
  export function authorityRoot(handle) {
3
11
  return `/rooms/${handle}`;
4
12
  }
@@ -92,6 +100,7 @@ function parseFile(value, mode) {
92
100
  path: file.path,
93
101
  revision: file.revision,
94
102
  version: file.revision,
103
+ ...(typeof file.sha256 === 'string' ? { sha256: file.sha256 } : {}),
95
104
  ...headed(head),
96
105
  ...binaried(binary),
97
106
  };
@@ -132,13 +141,26 @@ function parseScope(value, mode) {
132
141
  }
133
142
  return { anchor: manifest.anchor, ...at, files, contents };
134
143
  }
144
+ function parseCut(value) {
145
+ if (value === undefined)
146
+ return undefined;
147
+ if (typeof value !== 'object' || value === null)
148
+ return null;
149
+ const { position, log_epoch: logEpoch } = value;
150
+ if (typeof position !== 'string' || typeof logEpoch !== 'string')
151
+ return null;
152
+ return { position, log_epoch: logEpoch };
153
+ }
135
154
  function parseCursor(value) {
136
155
  if (typeof value !== 'object' || value === null)
137
156
  return null;
138
- const { room, path } = value;
157
+ const { room, path, cut } = value;
139
158
  if (typeof room !== 'string' || (path !== null && typeof path !== 'string'))
140
159
  return null;
141
- return { room, path };
160
+ const parsed = parseCut(cut);
161
+ if (parsed === null)
162
+ return null;
163
+ return { room, path, ...(parsed === undefined ? {} : { cut: parsed }) };
142
164
  }
143
165
  export function parseEnvelope(body) {
144
166
  if (typeof body !== 'object' || body === null)
@@ -234,10 +256,60 @@ export function parseEnumeration(body, mode) {
234
256
  return null;
235
257
  changes.push(mapped);
236
258
  }
237
- authorities.push({ authority: held.authority, ...at, changes });
259
+ const next = held.next === undefined ? undefined : readPage(held.next);
260
+ if (next === null)
261
+ return null;
262
+ authorities.push({
263
+ authority: held.authority,
264
+ ...at,
265
+ changes,
266
+ ...(next === undefined ? {} : { next }),
267
+ });
238
268
  }
239
269
  return { authorities };
240
270
  }
271
+ function readPage(held) {
272
+ if (typeof held !== 'object' || held === null)
273
+ return null;
274
+ const { after, through, read } = held;
275
+ if (typeof after !== 'string' || !DECIMAL.test(after))
276
+ return null;
277
+ if (typeof through !== 'string' || !DECIMAL.test(through))
278
+ return null;
279
+ if (typeof read !== 'number' || !Number.isSafeInteger(read) || read < 0)
280
+ return null;
281
+ return { after, through, read };
282
+ }
283
+ function advances(asked, next) {
284
+ const moved = BigInt(next.through) - BigInt(asked.through);
285
+ return moved > 0n || (moved === 0n && next.after === asked.after && next.read > asked.read);
286
+ }
287
+ export async function wholeView(first, more) {
288
+ const changes = new Map(first.changes.map((change) => [change.path, change]));
289
+ let view = first;
290
+ while (view.next !== undefined) {
291
+ const asked = view.next;
292
+ const page = await more(asked);
293
+ if ('kind' in page)
294
+ return page;
295
+ if (page.position !== asked.through ||
296
+ page.logEpoch !== first.logEpoch ||
297
+ (page.next !== undefined && !advances(asked, page.next))) {
298
+ return { kind: 'transport-uncertainty' };
299
+ }
300
+ for (const change of page.changes) {
301
+ changes.delete(change.path);
302
+ changes.set(change.path, change);
303
+ }
304
+ view = page;
305
+ }
306
+ return {
307
+ authority: first.authority,
308
+ position: view.position,
309
+ logEpoch: first.logEpoch,
310
+ changes: [...changes.values()],
311
+ };
312
+ }
241
313
  export function advancedScope(scope, view) {
242
314
  const files = new Map(scope.files.map((file) => [file.path, file]));
243
315
  const contents = new Map(scope.contents.map((entry) => [entry.path, entry.content]));
@@ -289,6 +361,7 @@ export function bootstrapOf(scope) {
289
361
  roomVersion: roomVersion(scope),
290
362
  documents,
291
363
  revisions,
364
+ ...identities(revisions),
292
365
  changes,
293
366
  binaryFiles,
294
367
  };
@@ -332,6 +405,7 @@ export function refreshFrom(view, fromRoomVersion) {
332
405
  roomVersion: roomVersion(view),
333
406
  documents,
334
407
  revisions,
408
+ ...identities(revisions),
335
409
  changes,
336
410
  binaryFiles,
337
411
  removals: removals.sort(),
package/dist/site.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import type { Adapter } from '@agentshouse/mdruntime';
2
2
  import { type HouseSiteTransport } from './transport.js';
3
- export declare function createSiteAdapter(transport: HouseSiteTransport): Adapter;
3
+ export declare function createSiteAdapter(transport: HouseSiteTransport, snapshot?: boolean): Adapter;
4
4
  //# sourceMappingURL=site.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"site.d.ts","sourceRoot":"","sources":["../src/site.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EAOR,MAAM,wBAAwB,CAAC;AAyBhC,OAAO,EAOL,KAAK,kBAAkB,EACxB,MAAM,gBAAgB,CAAC;AAmCxB,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,kBAAkB,GAAG,OAAO,CAqPxE"}
1
+ {"version":3,"file":"site.d.ts","sourceRoot":"","sources":["../src/site.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EAOR,MAAM,wBAAwB,CAAC;AA2BhC,OAAO,EAOL,KAAK,kBAAkB,EACxB,MAAM,gBAAgB,CAAC;AAmCxB,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,kBAAkB,EAAE,QAAQ,UAAQ,GAAG,OAAO,CA+Q1F"}
package/dist/site.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { actionOutcome, SITE_SUBMIT } from './actions.js';
2
2
  import { mapDiscovery, parseSiteDiscovery, siteCapabilities, siteTracked, } from './discovery.js';
3
3
  import { partModels, streamedModels, viewModels } from './model.js';
4
- import { advancedScope, bootstrapOf, parseEnumeration, parseSiteBootstrap, refreshFrom, siteBootstrapNext, siteBootstrapOffset, viewOf, } from './read.js';
4
+ import { advancedScope, bootstrapOf, parseEnumeration, parseSiteBootstrap, refreshFrom, siteBootstrapNext, siteBootstrapOffset, viewOf, wholeView, } from './read.js';
5
5
  import { sha256Hex } from './digest.js';
6
6
  import { classifyDoor, classifyRead, discoveryFailure } from './refusal.js';
7
7
  import { houseNotifications } from './stream.js';
@@ -23,21 +23,35 @@ function siteRoom(tracked) {
23
23
  function settled(refused) {
24
24
  return refused.kind === 'beyond-horizon' ? UNCERTAIN : refused;
25
25
  }
26
- export function createSiteAdapter(transport) {
26
+ export function createSiteAdapter(transport, snapshot = false) {
27
27
  const notifications = houseNotifications(transport, 'site');
28
28
  const tracked = new Map();
29
29
  function published(referrer) {
30
30
  const named = houseReferrer(referrer, tracked);
31
31
  return named === null || !tracked.has(named.locator) ? null : named;
32
32
  }
33
- async function enumeration(entry, from) {
33
+ async function enumerated(entry, from, page) {
34
34
  const answer = await transport.door(SITE_DOOR_ENUMERATE, {
35
- positions: [presented(entry.authority, from)],
35
+ positions: [
36
+ page === undefined
37
+ ? presented(entry.authority, from)
38
+ : {
39
+ ...presented(entry.authority, { position: page.after, logEpoch: from.logEpoch }),
40
+ page: { through: page.through, read: page.read },
41
+ },
42
+ ],
36
43
  });
37
44
  const classified = classifyRead(answer.status, answer.body, entry.locator);
38
45
  if (classified !== null)
39
46
  return classified;
40
- return parseEnumeration(answer.body, 'site') ?? UNCERTAIN;
47
+ const found = parseEnumeration(answer.body, 'site');
48
+ if (found === null)
49
+ return UNCERTAIN;
50
+ return viewOf(found, entry) ?? { kind: 'room-not-readable', locator: entry.locator };
51
+ }
52
+ async function enumeration(entry, from) {
53
+ const first = await enumerated(entry, from);
54
+ return 'kind' in first ? first : wholeView(first, (page) => enumerated(entry, from, page));
41
55
  }
42
56
  async function bootstrapPart(entry, after, offset) {
43
57
  const query = [
@@ -96,12 +110,9 @@ export function createSiteAdapter(transport) {
96
110
  if (after !== null || next !== null || roomVersion(scope) === roomVersion(entry)) {
97
111
  return { scope, next };
98
112
  }
99
- const found = await enumeration(entry, scope);
100
- if ('kind' in found)
101
- return { failure: settled(found) };
102
- const view = viewOf(found, entry);
103
- if (view === undefined)
104
- return { failure: { kind: 'room-not-readable', locator: entry.locator } };
113
+ const view = await enumeration(entry, scope);
114
+ if ('kind' in view)
115
+ return { failure: settled(view) };
105
116
  return { scope: advancedScope(scope, view), next: null };
106
117
  }
107
118
  async function refreshed(entry, fromRoomVersion) {
@@ -113,12 +124,9 @@ export function createSiteAdapter(transport) {
113
124
  const models = await streamedModels(streamed.schemas, entry, 'site');
114
125
  return models === undefined ? streamed.page : { ...streamed.page, models };
115
126
  }
116
- const found = await enumeration(entry, from);
117
- if ('kind' in found)
118
- return found;
119
- const view = viewOf(found, entry);
120
- if (view === undefined)
121
- return { kind: 'room-not-readable', locator: entry.locator };
127
+ const view = await enumeration(entry, from);
128
+ if ('kind' in view)
129
+ return view;
122
130
  notifications.reach(entry.authority, view);
123
131
  const answer = refreshFrom(view, fromRoomVersion);
124
132
  if (answer.kind !== 'net-advancement')
@@ -128,6 +136,7 @@ export function createSiteAdapter(transport) {
128
136
  }
129
137
  return {
130
138
  localSaves: true,
139
+ exhaustiveDiscovery: true,
131
140
  async authorize() {
132
141
  return {};
133
142
  },
@@ -175,6 +184,11 @@ export function createSiteAdapter(transport) {
175
184
  return { kind: 'room-not-readable', locator: request.locator };
176
185
  if (request.pageToken !== undefined)
177
186
  return UNCERTAIN;
187
+ if (snapshot) {
188
+ return request.fromRoomVersion === roomVersion(entry)
189
+ ? { kind: 'still-current' }
190
+ : { kind: 'beyond-horizon' };
191
+ }
178
192
  return refreshed(entry, request.fromRoomVersion);
179
193
  },
180
194
  async mutate() {
@@ -228,20 +242,27 @@ export function createSiteAdapter(transport) {
228
242
  return UNCERTAIN;
229
243
  return actionOutcome(await transport.door(SITE_DOOR_SUBMIT, request.input), SITE_SUBMIT);
230
244
  },
231
- roomStream: {
232
- hold(rooms) {
233
- notifications.send(rooms.flatMap((room) => {
234
- const entry = tracked.get(room.locator);
235
- const at = logPosition(room.roomVersion);
236
- if (entry === undefined || at === null)
237
- return [];
238
- notifications.reach(entry.authority, at);
239
- return [presented(entry.authority, at)];
240
- }));
245
+ roomStream: snapshot
246
+ ? undefined
247
+ : {
248
+ hold(rooms) {
249
+ notifications.send(rooms.flatMap((room) => {
250
+ const entry = tracked.get(room.locator);
251
+ const at = logPosition(room.roomVersion);
252
+ if (entry === undefined || at === null)
253
+ return [];
254
+ notifications.reach(entry.authority, at);
255
+ return [presented(entry.authority, at)];
256
+ }), null);
257
+ },
258
+ reopen: notifications.reopen,
259
+ observe: notifications.observe,
260
+ published(locator, roomVersion) {
261
+ const at = logPosition(roomVersion);
262
+ if (at !== null)
263
+ notifications.published(locator, at);
264
+ },
241
265
  },
242
- reopen: notifications.reopen,
243
- observe: notifications.observe,
244
- },
245
266
  serviceMode: notifications.serviceMode,
246
267
  };
247
268
  }
package/dist/stream.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { ConversationStream, RefreshPage, RoomStreamEvent, ServiceModeSignal } from '@agentshouse/mdruntime';
1
+ import type { ConversationStream, RefreshPage, RoomStreamEvent, ServiceModeSignal, StreamReceipts } from '@agentshouse/mdruntime';
2
2
  import type { TrackedAuthority } from './discovery.js';
3
- import type { HouseDoor, HouseHeldRoom, HouseMode, HouseStreamEntry } from './transport.js';
3
+ import type { HouseDemand, HouseDoor, HouseHeldRoom, HouseMode, HouseStreamEntry } from './transport.js';
4
4
  import { type LogPosition } from './version.js';
5
5
  export type HeldRevision = (path: string, revision: string) => boolean;
6
6
  export type StreamedAdvancement = {
@@ -10,8 +10,9 @@ export type StreamedAdvancement = {
10
10
  };
11
11
  export type HouseNotifications = {
12
12
  runtime: string;
13
- observe(notify: (event: RoomStreamEvent) => void): () => void;
14
- send(rooms: readonly HouseHeldRoom[]): void;
13
+ observe(notify: (event: RoomStreamEvent) => void, receipts: StreamReceipts): () => void;
14
+ send(rooms: readonly HouseHeldRoom[], demand: HouseDemand | null): void;
15
+ published(locator: string, at: LogPosition): void;
15
16
  reopen(): void;
16
17
  track(authorities: readonly TrackedAuthority[]): void;
17
18
  reach(authority: string, at: LogPosition): void;
@@ -1 +1 @@
1
- {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,kBAAkB,EAElB,WAAW,EACX,eAAe,EAEf,iBAAiB,EAElB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,KAAK,EACV,SAAS,EACT,aAAa,EAEb,SAAS,EAET,gBAAgB,EAEjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAe,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAwB7D,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;AAEvE,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,SAAS,gBAAgB,EAAE,CAAC;IACrC,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;CAChD,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IAC9D,IAAI,CAAC,KAAK,EAAE,SAAS,aAAa,EAAE,GAAG,IAAI,CAAC;IAC5C,MAAM,IAAI,IAAI,CAAC;IACf,KAAK,CAAC,WAAW,EAAE,SAAS,gBAAgB,EAAE,GAAG,IAAI,CAAC;IACtD,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD,OAAO,CACL,OAAO,EAAE,gBAAgB,EACzB,IAAI,EAAE,WAAW,EACjB,KAAK,CAAC,EAAE,YAAY,GACnB,mBAAmB,GAAG,IAAI,CAAC;IAC9B,aAAa,EAAE,kBAAkB,CAAC;IAClC,WAAW,EAAE,iBAAiB,CAAC;CAChC,CAAC;AA0DF,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,GAAG,kBAAkB,CAoX5F"}
1
+ {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,kBAAkB,EAElB,WAAW,EACX,eAAe,EAEf,iBAAiB,EACjB,cAAc,EAEf,MAAM,wBAAwB,CAAC;AAGhC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,KAAK,EACV,WAAW,EACX,SAAS,EACT,aAAa,EAEb,SAAS,EAET,gBAAgB,EAEjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAe,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AA0C7D,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;AAEvE,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,SAAS,gBAAgB,EAAE,CAAC;IACrC,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;CAChD,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,EAAE,QAAQ,EAAE,cAAc,GAAG,MAAM,IAAI,CAAC;IACxF,IAAI,CAAC,KAAK,EAAE,SAAS,aAAa,EAAE,EAAE,MAAM,EAAE,WAAW,GAAG,IAAI,GAAG,IAAI,CAAC;IACxE,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,GAAG,IAAI,CAAC;IAClD,MAAM,IAAI,IAAI,CAAC;IACf,KAAK,CAAC,WAAW,EAAE,SAAS,gBAAgB,EAAE,GAAG,IAAI,CAAC;IACtD,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,GAAG,IAAI,CAAC;IAChD,OAAO,CACL,OAAO,EAAE,gBAAgB,EACzB,IAAI,EAAE,WAAW,EACjB,KAAK,CAAC,EAAE,YAAY,GACnB,mBAAmB,GAAG,IAAI,CAAC;IAC9B,aAAa,EAAE,kBAAkB,CAAC;IAClC,WAAW,EAAE,iBAAiB,CAAC;CAChC,CAAC;AAkFF,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,GAAG,kBAAkB,CAohB5F"}
package/dist/stream.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { acceptedMessage } from './actions.js';
2
2
  import { sha256Hex } from './digest.js';
3
- import { binaryFileOf, headChange } from './read.js';
3
+ import { binaryFileOf, headChange, identities } from './read.js';
4
4
  import { roomVersion } from './version.js';
5
5
  const HELD_FRAMES_MAX = 256;
6
6
  function turnOperation(frame) {
@@ -53,7 +53,9 @@ function assembled(entries) {
53
53
  async function verified(entries) {
54
54
  try {
55
55
  for (const entry of entries) {
56
- if ((await sha256Hex(entry.text ?? '')) !== entry.sha256)
56
+ if (entry.text === undefined || entry.sha256 === undefined)
57
+ continue;
58
+ if ((await sha256Hex(entry.text)) !== entry.sha256)
57
59
  return false;
58
60
  }
59
61
  return true;
@@ -62,10 +64,34 @@ async function verified(entries) {
62
64
  return false;
63
65
  }
64
66
  }
67
+ function resumed(kept, frame) {
68
+ const last = frame.entries.at(-1);
69
+ const point = { parts: frame.index + 1, from: frame.from, target: frame.target };
70
+ if (last?.continued !== true)
71
+ return { ...point, handled: frame.handled, piece: null };
72
+ const text = last.text?.length ?? 0;
73
+ if (last.kind !== 'piece') {
74
+ return last.sha256 === undefined
75
+ ? kept.resume
76
+ : { ...point, handled: frame.handled, piece: { sha256: last.sha256, offset: text } };
77
+ }
78
+ const piece = kept.resume?.piece ?? null;
79
+ if (piece === null)
80
+ return kept.resume;
81
+ const pieces = frame.entries.reduce((sum, entry) => sum + (entry.kind === 'piece' ? (entry.text?.length ?? 0) : 0), 0);
82
+ return {
83
+ ...point,
84
+ handled: frame.handled,
85
+ piece: { sha256: piece.sha256, offset: piece.offset + pieces },
86
+ };
87
+ }
65
88
  export function houseNotifications(transport, mode) {
66
89
  const stream = transport.stream;
67
90
  const lines = new Map();
68
- const staged = new Map();
91
+ const kept = new Map();
92
+ let receipts = null;
93
+ let loaded = Promise.resolve();
94
+ let acknowledging = null;
69
95
  let receiving = Promise.resolve();
70
96
  let verifying = 0;
71
97
  const locators = new Map();
@@ -93,7 +119,7 @@ export function houseNotifications(transport, mode) {
93
119
  }
94
120
  function reopened(next) {
95
121
  opening = next;
96
- staged.clear();
122
+ acknowledging = next;
97
123
  const gapped = new Set([...replicated, ...live]);
98
124
  live.clear();
99
125
  for (const conversation of gapped)
@@ -155,46 +181,162 @@ export function houseNotifications(transport, mode) {
155
181
  if (line !== undefined)
156
182
  lines.set(authority, { ...line, frames: [] });
157
183
  }
158
- function stage(frame) {
159
- const held = staged.get(frame.authority);
160
- if (frame.index === 0) {
161
- staged.set(frame.authority, { carry: frame.carry, parts: 1, entries: [...frame.entries] });
184
+ async function forget(carries) {
185
+ const held = carries.filter((carry) => kept.delete(carry));
186
+ if (held.length > 0)
187
+ await receipts?.drop(held).catch(() => { });
188
+ }
189
+ async function lost(authority, carry) {
190
+ interrupt(authority);
191
+ await forget([carry]);
192
+ }
193
+ async function stage(frame, via) {
194
+ await loaded;
195
+ const port = receipts;
196
+ if (port === null)
162
197
  return;
163
- }
164
- if (held?.carry !== frame.carry || held.parts !== frame.index) {
165
- staged.delete(frame.authority);
198
+ const held = kept.get(frame.carry);
199
+ if (held === undefined && frame.index !== 0) {
166
200
  interrupt(frame.authority);
167
201
  return;
168
202
  }
169
- held.parts += 1;
170
- held.entries.push(...frame.entries);
203
+ if (held !== undefined &&
204
+ (held.fenced !== null || frame.index > held.parts || frame.index < (held.resume?.parts ?? 0))) {
205
+ await lost(frame.authority, frame.carry);
206
+ return;
207
+ }
208
+ if (held === undefined) {
209
+ await forget([...kept.values()]
210
+ .filter((other) => other.authority === frame.authority && other.fenced === null)
211
+ .map((other) => other.carry));
212
+ }
213
+ const start = held ?? {
214
+ authority: frame.authority,
215
+ carry: frame.carry,
216
+ logEpoch: lines.get(frame.authority)?.logEpoch ?? null,
217
+ after: frame.after,
218
+ parts: 0,
219
+ resume: null,
220
+ fenced: null,
221
+ };
222
+ const next = { ...start, parts: frame.index + 1, resume: resumed(start, frame) };
223
+ const part = { entries: frame.entries };
224
+ try {
225
+ await port.keep(frame.carry, next, { index: frame.index, value: part });
226
+ }
227
+ catch {
228
+ await lost(frame.authority, frame.carry);
229
+ return;
230
+ }
231
+ kept.set(frame.carry, next);
232
+ via?.received(frame.authority, frame.carry, frame.index);
171
233
  }
172
- function carried(frame) {
173
- const held = staged.get(frame.authority);
174
- staged.delete(frame.authority);
175
- const parts = frame.parts === 0
176
- ? []
177
- : held?.carry === frame.carry && held.parts === frame.parts
178
- ? held.entries
179
- : null;
180
- const entries = parts === null ? null : assembled(parts);
234
+ async function keptEntries(carry, parts) {
235
+ if (parts === 0)
236
+ return [];
237
+ if (receipts === null)
238
+ return null;
239
+ const read = (await receipts.parts(carry, parts));
240
+ if (read.length !== parts)
241
+ return null;
242
+ const entries = assembled(read.flatMap((part) => part.entries));
243
+ return entries !== null && (await verified(entries)) ? entries : null;
244
+ }
245
+ async function carried(frame) {
246
+ await loaded;
247
+ const held = kept.get(frame.carry);
248
+ if (frame.parts > 0 && held?.parts !== frame.parts) {
249
+ await lost(frame.authority, frame.carry);
250
+ return;
251
+ }
252
+ const entries = await keptEntries(frame.carry, frame.parts).catch(() => null);
181
253
  if (entries === null) {
182
- interrupt(frame.authority);
254
+ await lost(frame.authority, frame.carry);
183
255
  return;
184
256
  }
185
- const digested = entries.filter((entry) => entry.text !== undefined && entry.sha256 !== undefined);
186
- if (digested.length === 0) {
187
- publish(frame, entries);
257
+ const fenced = {
258
+ ...(held ?? {
259
+ authority: frame.authority,
260
+ carry: frame.carry,
261
+ logEpoch: frame.log_epoch,
262
+ after: frame.after,
263
+ parts: 0,
264
+ resume: null,
265
+ }),
266
+ after: frame.after,
267
+ fenced: { position: frame.position, logEpoch: frame.log_epoch },
268
+ };
269
+ try {
270
+ await receipts?.keep(frame.carry, fenced);
271
+ }
272
+ catch {
273
+ await lost(frame.authority, frame.carry);
188
274
  return;
189
275
  }
190
- return verified(digested).then((whole) => {
191
- if (whole)
192
- publish(frame, entries);
193
- else
194
- interrupt(frame.authority);
195
- });
276
+ kept.set(frame.carry, fenced);
277
+ publish(frame, entries);
278
+ }
279
+ async function load(port) {
280
+ try {
281
+ for (const { key, head } of await port.heads())
282
+ kept.set(key, head);
283
+ }
284
+ catch {
285
+ kept.clear();
286
+ }
196
287
  }
197
- function handle(frame) {
288
+ async function restored(room) {
289
+ const line = lines.get(room.authority);
290
+ let at = room.position;
291
+ const chain = [];
292
+ for (;;) {
293
+ const next = [...kept.values()].find((carry) => carry.authority === room.authority &&
294
+ carry.after === at &&
295
+ carry.fenced?.logEpoch === room.log_epoch);
296
+ if (next?.fenced == null)
297
+ break;
298
+ const entries = await keptEntries(next.carry, next.parts).catch(() => null);
299
+ if (entries === null)
300
+ break;
301
+ chain.push({ carry: next, entries });
302
+ at = next.fenced.position;
303
+ }
304
+ const partial = [...kept.values()].find((carry) => carry.authority === room.authority &&
305
+ carry.fenced === null &&
306
+ carry.logEpoch === room.log_epoch &&
307
+ carry.after === at &&
308
+ carry.resume !== null &&
309
+ carry.resume.parts > 0);
310
+ const stale = [...kept.values()].filter((carry) => carry.authority === room.authority &&
311
+ carry !== partial &&
312
+ !chain.some((link) => link.carry === carry));
313
+ await forget(stale.map((carry) => carry.carry));
314
+ if (line !== undefined && line.logEpoch === room.log_epoch && chain.length > 0) {
315
+ const frames = chain.map(({ carry, entries }) => ({
316
+ after: BigInt(carry.after),
317
+ position: BigInt(carry.fenced.position),
318
+ entries,
319
+ }));
320
+ lines.set(room.authority, { ...line, frames: [...line.frames, ...frames] });
321
+ }
322
+ return {
323
+ ...room,
324
+ position: at,
325
+ ...(partial?.resume == null
326
+ ? {}
327
+ : {
328
+ carry: {
329
+ id: partial.carry,
330
+ parts: partial.resume.parts,
331
+ from: partial.resume.from,
332
+ target: partial.resume.target,
333
+ handled: partial.resume.handled,
334
+ ...(partial.resume.piece === null ? {} : { piece: partial.resume.piece }),
335
+ },
336
+ }),
337
+ };
338
+ }
339
+ function handle(frame, via) {
198
340
  if (frame.type === 'signal') {
199
341
  const mode = frame.service_mode;
200
342
  if (mode !== 'open' && mode !== 'write-halted')
@@ -231,10 +373,8 @@ export function houseNotifications(transport, mode) {
231
373
  converse(frame);
232
374
  return;
233
375
  }
234
- if (frame.type === 'part') {
235
- stage(frame);
236
- return;
237
- }
376
+ if (frame.type === 'part')
377
+ return stage(frame, via);
238
378
  if (frame.type === 'carried')
239
379
  return carried(frame);
240
380
  }
@@ -262,8 +402,9 @@ export function houseNotifications(transport, mode) {
262
402
  announce(frame.authority, { position: frame.position, logEpoch: frame.log_epoch });
263
403
  }
264
404
  stream.observe((frame) => {
405
+ const via = acknowledging;
265
406
  if (verifying === 0) {
266
- const handled = handle(frame);
407
+ const handled = handle(frame, via);
267
408
  if (handled === undefined)
268
409
  return;
269
410
  verifying += 1;
@@ -274,7 +415,7 @@ export function houseNotifications(transport, mode) {
274
415
  }
275
416
  verifying += 1;
276
417
  receiving = receiving
277
- .then(() => handle(frame))
418
+ .then(() => handle(frame, via))
278
419
  .finally(() => {
279
420
  verifying -= 1;
280
421
  });
@@ -282,7 +423,7 @@ export function houseNotifications(transport, mode) {
282
423
  stream.opened(reopened);
283
424
  stream.closed((revoked) => {
284
425
  opening = null;
285
- staged.clear();
426
+ acknowledging = null;
286
427
  emit({ kind: 'closed', revoked });
287
428
  });
288
429
  return {
@@ -306,8 +447,12 @@ export function houseNotifications(transport, mode) {
306
447
  };
307
448
  },
308
449
  },
309
- observe(notify) {
450
+ observe(notify, port) {
310
451
  observers.add(notify);
452
+ if (receipts === null) {
453
+ receipts = port;
454
+ loaded = load(port);
455
+ }
311
456
  if (opening !== null) {
312
457
  queueMicrotask(() => {
313
458
  if (observers.has(notify))
@@ -318,7 +463,7 @@ export function houseNotifications(transport, mode) {
318
463
  observers.delete(notify);
319
464
  };
320
465
  },
321
- send(rooms) {
466
+ send(rooms, demand) {
322
467
  for (const room of rooms) {
323
468
  const line = lines.get(room.authority);
324
469
  const held = position(room.position);
@@ -328,7 +473,30 @@ export function houseNotifications(transport, mode) {
328
473
  }
329
474
  const current = opening;
330
475
  opening = null;
331
- current?.hold(rooms, runtime);
476
+ if (current === null)
477
+ return;
478
+ void loaded
479
+ .then(() => Promise.all(rooms.map(restored)))
480
+ .then((presented) => {
481
+ current.hold(presented, runtime, demand);
482
+ for (const [index, room] of presented.entries()) {
483
+ if (room.position === rooms[index].position)
484
+ continue;
485
+ announce(room.authority, { position: room.position, logEpoch: room.log_epoch });
486
+ }
487
+ });
488
+ },
489
+ published(locator, at) {
490
+ const authority = [...locators].find(([, held]) => held.includes(locator))?.[0];
491
+ const reached = position(at.position);
492
+ if (authority === undefined || reached === null)
493
+ return;
494
+ void forget([...kept.values()]
495
+ .filter((carry) => carry.authority === authority &&
496
+ carry.fenced !== null &&
497
+ carry.fenced.logEpoch === at.logEpoch &&
498
+ BigInt(carry.fenced.position) <= reached)
499
+ .map((carry) => carry.carry));
332
500
  },
333
501
  reopen() {
334
502
  const current = opening;
@@ -347,6 +515,9 @@ export function houseNotifications(transport, mode) {
347
515
  if (!locators.has(authority))
348
516
  lines.delete(authority);
349
517
  }
518
+ void loaded.then(() => forget([...kept.values()]
519
+ .filter((carry) => !locators.has(carry.authority))
520
+ .map((carry) => carry.carry)));
350
521
  },
351
522
  reach(authority, at) {
352
523
  const line = lines.get(authority);
@@ -430,6 +601,7 @@ export function houseNotifications(transport, mode) {
430
601
  roomVersion: roomVersion({ position: last.position.toString(), logEpoch: line.logEpoch }),
431
602
  documents,
432
603
  revisions,
604
+ ...identities(revisions),
433
605
  changes,
434
606
  binaryFiles,
435
607
  removals: removals.sort(),