@graview/ship 0.1.49 → 0.1.51

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 (60) hide show
  1. package/README.md +5 -5
  2. package/dist/browser-adapter.d.ts +1 -1
  3. package/dist/browser-adapter.d.ts.map +1 -1
  4. package/dist/browser-adapter.js +23 -6
  5. package/dist/browser-adapter.js.map +1 -1
  6. package/dist/browser.d.ts +2 -0
  7. package/dist/browser.d.ts.map +1 -1
  8. package/dist/browser.js +1 -0
  9. package/dist/browser.js.map +1 -1
  10. package/dist/cursor.d.ts +22 -0
  11. package/dist/cursor.d.ts.map +1 -0
  12. package/dist/cursor.js +13 -0
  13. package/dist/cursor.js.map +1 -0
  14. package/dist/file-adapter.d.ts.map +1 -1
  15. package/dist/file-adapter.js +44 -3
  16. package/dist/file-adapter.js.map +1 -1
  17. package/dist/handler.d.ts +20 -6
  18. package/dist/handler.d.ts.map +1 -1
  19. package/dist/handler.js +33 -11
  20. package/dist/handler.js.map +1 -1
  21. package/dist/index.d.ts +5 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +4 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/live-protocol.d.ts +32 -4
  26. package/dist/live-protocol.d.ts.map +1 -1
  27. package/dist/live-protocol.js +262 -40
  28. package/dist/live-protocol.js.map +1 -1
  29. package/dist/live.d.ts +28 -11
  30. package/dist/live.d.ts.map +1 -1
  31. package/dist/live.js +6 -3
  32. package/dist/live.js.map +1 -1
  33. package/dist/open-store.d.ts +3 -1
  34. package/dist/open-store.d.ts.map +1 -1
  35. package/dist/open-store.js +28 -7
  36. package/dist/open-store.js.map +1 -1
  37. package/dist/remote-typing.d.ts +127 -0
  38. package/dist/remote-typing.d.ts.map +1 -0
  39. package/dist/remote-typing.js +205 -0
  40. package/dist/remote-typing.js.map +1 -0
  41. package/dist/remote.d.ts +12 -0
  42. package/dist/remote.d.ts.map +1 -1
  43. package/dist/remote.js +114 -19
  44. package/dist/remote.js.map +1 -1
  45. package/dist/runtime.d.ts +4 -1
  46. package/dist/runtime.d.ts.map +1 -1
  47. package/dist/runtime.js +3 -0
  48. package/dist/runtime.js.map +1 -1
  49. package/dist/serve.d.ts +4 -2
  50. package/dist/serve.d.ts.map +1 -1
  51. package/dist/serve.js +2 -0
  52. package/dist/serve.js.map +1 -1
  53. package/dist/snapshot.d.ts +3 -0
  54. package/dist/snapshot.d.ts.map +1 -1
  55. package/dist/snapshot.js +20 -5
  56. package/dist/snapshot.js.map +1 -1
  57. package/dist/steps.d.ts.map +1 -1
  58. package/dist/steps.js +5 -2
  59. package/dist/steps.js.map +1 -1
  60. package/package.json +2 -2
@@ -1,8 +1,10 @@
1
1
  import { lowerFirst } from "@graview/core/words";
2
- import { FieldRevisions, InvalidArguments, UnknownMutationError, hidesFrom, hueFor, isUnset, namesUnseen, participantKey, redact, seatLens, sha256Hex, seenBy, seesId, refusalOf, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, withInverse, } from "@graview/core";
2
+ import { FieldRevisions, InvalidArguments, UnknownMutationError, hidesFrom, hueFor, isUnset, namesUnseen, participantKey, redact, seatLens, sha256Hex, seenBy, seesId, refusalOf, applySplice, TYPE_TEXT, UNSET, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, withInverse, } from "@graview/core";
3
3
  // What a seat is served keeps the fields its sight keeps (Roadmap f-field-sight): the protocol judges them.
4
4
  import "@graview/core/field-sight";
5
+ import "@graview/core/publishing";
5
6
  import { argumentWords } from "@graview/core/words";
7
+ import { cursorAt, seqAt } from "./cursor.js";
6
8
  import { bytesOf, conflictSentence, LIVE_WIRE } from "./live.js";
7
9
  /** The longest `cid` a socket's call or undo may name: it is kept in `held` while the call is busy. */
8
10
  const MAX_CID = 64;
@@ -21,24 +23,106 @@ class NotAdmitted extends Error {
21
23
  * inverse off the op, so it is sent the inverse written out — the bytes
22
24
  * format 1 cost, and nothing it would misread.
23
25
  */
24
- export function opsFor(opFormat, ops) {
25
- return opFormat !== undefined && opFormat >= 2 ? ops : ops.map(withInverse);
26
+ export function opsFor(opFormat, ops, store) {
27
+ const read = store && (opFormat ?? 1) < 3 ? wholeSplices(store, ops) : ops;
28
+ return opFormat !== undefined && opFormat >= 2 ? read : read.map(withInverse);
29
+ }
30
+ /**
31
+ * A SPLICE AS A READER BEFORE OP FORMAT 3 READS IT (Roadmap f-collab-text,
32
+ * phase 3): a `patch-node` of the field's whole text before and after it,
33
+ * as every op before typing together wrote one. A reader that did not say
34
+ * it reads format 3 has never met a `splice-text` and would refuse it; it
35
+ * is sent the same change whole and its copy folds to the same text. The
36
+ * text each splice stood on is read by walking back from the field's value
37
+ * now over the log's ops since — at a broadcast that is the op just
38
+ * landed, in a catch-up as far as the oldest op asked about. An op that is
39
+ * not in the store's log at its seq is sent as it is.
40
+ */
41
+ function wholeSplices(store, ops) {
42
+ const spliced = ops.filter((op) => op.primitives.some((one) => one.op === "splice-text"));
43
+ if (spliced.length === 0)
44
+ return ops;
45
+ const key = (id, field) => `${id}\u0000${field}`;
46
+ const texts = new Map();
47
+ for (const op of spliced)
48
+ for (const one of op.primitives)
49
+ if (one.op === "splice-text")
50
+ texts.set(key(one.id, one.field), store.graph.getNode(one.id)?.[one.field]);
51
+ const wanted = new Set(spliced.map((op) => op.seq));
52
+ const first = Math.max(store.log.horizon, Math.min(...wanted));
53
+ const log = store.log.all();
54
+ /** Each wanted op's splices, by field, in order: the text before and after each. */
55
+ const whole = new Map();
56
+ for (let seq = store.log.length - 1; seq >= first; seq--) {
57
+ const op = log[seq - store.log.horizon];
58
+ for (let at = op.primitives.length - 1; at >= 0; at--) {
59
+ const one = op.primitives[at];
60
+ if (one.op === "splice-text") {
61
+ const field = key(one.id, one.field);
62
+ if (!texts.has(field))
63
+ continue;
64
+ const after = texts.get(field);
65
+ let before;
66
+ try {
67
+ before = typeof after === "string" ? applySplice(after, { at: one.at, removed: one.inserted, inserted: one.removed }) : undefined;
68
+ }
69
+ catch {
70
+ before = undefined;
71
+ }
72
+ texts.set(field, before);
73
+ if (!wanted.has(seq))
74
+ continue;
75
+ let byField = whole.get(seq);
76
+ if (!byField)
77
+ whole.set(seq, (byField = new Map()));
78
+ byField.set(field, [{ before, after }, ...(byField.get(field) ?? [])]);
79
+ }
80
+ else if (one.op === "patch-node") {
81
+ for (const field of Object.keys(one.after))
82
+ if (texts.has(key(one.id, field)))
83
+ texts.set(key(one.id, field), one.before[field]);
84
+ }
85
+ else if (one.op === "add-node" || one.op === "remove-node") {
86
+ for (const [field] of texts)
87
+ if (field.startsWith(`${one.node.id}\u0000`))
88
+ texts.set(field, one.op === "add-node" ? undefined : one.node[field.slice(one.node.id.length + 1)]);
89
+ }
90
+ }
91
+ }
92
+ return ops.map((op) => {
93
+ const byField = whole.get(op.seq);
94
+ if (!byField || log[op.seq - store.log.horizon]?.id !== op.id)
95
+ return op;
96
+ const taken = new Map();
97
+ const primitives = op.primitives.map((one) => {
98
+ if (one.op !== "splice-text")
99
+ return one;
100
+ const field = key(one.id, one.field);
101
+ const at = taken.get(field) ?? 0;
102
+ taken.set(field, at + 1);
103
+ const said = byField.get(field)?.[at];
104
+ if (!said || typeof said.after !== "string")
105
+ return one;
106
+ return { op: "patch-node", id: one.id, before: { [one.field]: typeof said.before === "string" ? said.before : UNSET }, after: { [one.field]: said.after } };
107
+ });
108
+ return { ...op, primitives };
109
+ });
26
110
  }
27
111
  /** The op format a request says it reads: `?opFormat=<n>` on its URL; nothing when it says none. */
28
112
  export function opFormatOf(url) {
29
113
  const said = Number((typeof url === "string" ? new URL(url, "http://graview.invalid") : url).searchParams.get("opFormat"));
30
114
  return Number.isInteger(said) && said > 0 ? said : undefined;
31
115
  }
32
- /** A live message as a socket of this op format reads it: its ops, and a welcome's log, bare or with their inverses. */
33
- function readableBy(opFormat, message) {
34
- if (opFormat !== undefined && opFormat >= 2)
116
+ /** A live message as a socket of this op format reads it: its ops, and a welcome's log, bare or with their inverses, and its splices whole before format 3. */
117
+ function readableBy(opFormat, message, store) {
118
+ if (opFormat !== undefined && opFormat >= 3)
35
119
  return message;
36
120
  if (message.t === "welcome") {
37
- const state = message.state ? { state: { ...message.state, log: opsFor(opFormat, message.state.log) } } : {};
38
- return { ...message, ops: opsFor(opFormat, message.ops), ...state };
121
+ const state = message.state ? { state: { ...message.state, log: opsFor(opFormat, message.state.log, store) } } : {};
122
+ return { ...message, ops: opsFor(opFormat, message.ops, store), ...state };
39
123
  }
40
124
  if (message.t === "ops" || message.t === "ack")
41
- return { ...message, ops: opsFor(opFormat, message.ops) };
125
+ return { ...message, ops: opsFor(opFormat, message.ops, store) };
42
126
  return message;
43
127
  }
44
128
  /** A client's claim of what its change came through: a short string, or none. */
@@ -77,13 +161,24 @@ const forWhom = (author) => author.onBehalfOf?.id ? { onBehalfOf: author.onBehal
77
161
  * given, the claimed key is not read at all.
78
162
  */
79
163
  export function presenceFrom(told, seat, now = new Date(), participant) {
80
- const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, held: _held, at: _at, ...said } = told;
164
+ const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, held: _held, at: _at, caret: claimedCaret, ...said } = told;
165
+ const caret = caretOf(claimedCaret);
81
166
  // The session is what follows the seat's own `kind:id:` — an id may hold a colon (`shopper:bethan`).
82
167
  const own = `${seat.kind}:${seat.id ?? ""}:`;
83
168
  const session = claimed.startsWith(own) ? claimed.slice(own.length) : (claimed.split(":").at(-1) ?? "");
84
169
  const key = participant ?? (seat.id ? participantKey({ kind: seat.kind, id: seat.id, session }) : claimed);
85
170
  const name = seat.name ?? claimedName;
86
- return { ...said, participant: key, kind: seat.kind, ...(name ? { name } : {}), ...forWhom(seat), at: now.toISOString() };
171
+ return { ...said, participant: key, kind: seat.kind, ...(name ? { name } : {}), ...forWhom(seat), ...(caret ? { caret } : {}), at: now.toISOString() };
172
+ }
173
+ /** A caret as a client said it (Roadmap f-collab-text), kept only when it is one: a record, a field, and three counts. */
174
+ function caretOf(said) {
175
+ if (typeof said !== "object" || said === null)
176
+ return undefined;
177
+ const { node, field, anchor, head, rev } = said;
178
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
179
+ if (typeof node !== "string" || typeof field !== "string" || node.length > 512 || field.length > 512 || !count(anchor) || !count(head) || !count(rev))
180
+ return undefined;
181
+ return { node, field, anchor, head, rev };
87
182
  }
88
183
  /**
89
184
  * A VISITOR WITHOUT A SOCKET, as a host announces it (FR-47): an agent
@@ -145,7 +240,7 @@ const mintSession = () => globalThis.crypto.randomUUID().slice(0, 8);
145
240
  * where they stand or what they hover when that names a record the seat
146
241
  * may not see. A participant whose id is no record is shown as they are.
147
242
  */
148
- export function presenceSeenBy(who, sees) {
243
+ export function presenceSeenBy(who, sees, seesField) {
149
244
  const names = (value) => value.split(/[/?#=&,;]/).every((part) => part === "" || sees(decodeURIComponent(part)));
150
245
  return who
151
246
  .filter((presence) => {
@@ -155,7 +250,7 @@ export function presenceSeenBy(who, sees) {
155
250
  })
156
251
  .map((presence) => {
157
252
  // An agent is shown; for whom it acts is not, to a seat that may not see that person (FR-47).
158
- const { onBehalfOf, onBehalfOfName, ...rest } = presence;
253
+ const { onBehalfOf, onBehalfOfName, caret, ...rest } = presence;
159
254
  const forWhom = onBehalfOf !== undefined && sees(onBehalfOf) ? { onBehalfOf, ...(onBehalfOfName !== undefined ? { onBehalfOfName } : {}) } : {};
160
255
  return {
161
256
  ...rest,
@@ -163,6 +258,8 @@ export function presenceSeenBy(who, sees) {
163
258
  stop: names(presence.stop) ? presence.stop : "",
164
259
  ...(typeof presence.over === "string" && !sees(presence.over) ? { over: null } : {}),
165
260
  ...(presence.robot?.at && !sees(presence.robot.at) ? { robot: { ...presence.robot, at: null } } : {}),
261
+ // A caret in a field the seat may not see is not said at all: where somebody types says what is there (Roadmap f-collab-text).
262
+ ...(caret && sees(caret.node) && (seesField?.(caret.node, caret.field) ?? true) ? { caret } : {}),
166
263
  };
167
264
  });
168
265
  }
@@ -303,12 +400,55 @@ export function wireOf(store, withheldKey) {
303
400
  }
304
401
  return revisions;
305
402
  };
403
+ /*
404
+ * A KEYSTROKE TYPED AGAINST TEXT BEHIND THE HORIZON (Roadmap f-collab-text,
405
+ * phase 3): the log no longer holds what was typed between the text its
406
+ * sender read and now, so it cannot be carried over it. A conflict, not a
407
+ * refusal: the person keeps theirs, or puts the text they had over it
408
+ * whole. A compaction keeps the horizon behind every open socket
409
+ * (`floor`), so only a client that was away meets this.
410
+ */
411
+ const typedBehind = (author, calls) => {
412
+ const floor = store.log.horizon - 1;
413
+ const out = [];
414
+ for (const call of calls) {
415
+ if (call?.name !== TYPE_TEXT || !call.args)
416
+ continue;
417
+ const { node, field, rev } = call.args;
418
+ if (typeof node !== "string" || typeof field !== "string" || typeof rev !== "number" || rev >= floor)
419
+ continue;
420
+ const lens = sighted(author) ? seatLens(store, author) : undefined;
421
+ if (lens && (!lens.shows(node) || keptField(lens, node, field)))
422
+ continue;
423
+ const at = current().of(node, field);
424
+ const wrote = at >= store.log.horizon ? store.log.opsFrom(at)[0] : undefined;
425
+ const seen = wrote && lens ? redact([wrote], lens)[0] : wrote;
426
+ out.push({
427
+ node,
428
+ field,
429
+ theirs: (lens ? seenBy(store, author) : store).graph.getNode(node)?.[field],
430
+ yours: undefined,
431
+ by: seen?.author.name ?? seen?.author.id ?? "Someone",
432
+ rev: at,
433
+ saw: rev,
434
+ });
435
+ }
436
+ return out;
437
+ };
438
+ // Where a seat is served through: the head in a live app, without judging its sight; what was published, for a reader of one that publishes.
439
+ const servedTo = (principal) => (store.publishing?.mode === "on-publish" ? seenBy(store, principal).servedSeq : store.log.length);
306
440
  return {
307
441
  store,
308
442
  lastSeq: () => store.log.length - 1,
309
443
  sighted,
310
444
  shown,
311
- since: (principal, seq) => shown(principal, store.log.opsFrom(Math.max(0, Math.floor(seq) + 1))),
445
+ servedSeq: servedTo,
446
+ since: (principal, seq) => {
447
+ const served = servedTo(principal);
448
+ return shown(principal, store.log.opsFrom(Math.max(0, Math.floor(seq) + 1)).filter((op) => op.seq < served));
449
+ },
450
+ behind: (principal, seq) => Number.isFinite(seq) && (Math.floor(seq) + 1 < store.log.horizon || (Math.floor(seq) >= servedTo(principal) && servedTo(principal) < store.log.length)),
451
+ servedOf: (principal) => (store.publishing?.mode === "on-publish" ? { servedThrough: cursorAt(servedTo(principal) - 1) } : {}),
312
452
  seenFor: (principal) => seenBy(store, principal),
313
453
  seenLog(principal) {
314
454
  const log = seenBy(store, principal).log.all();
@@ -322,7 +462,10 @@ export function wireOf(store, withheldKey) {
322
462
  // A visitor whose announced time has passed is never told of, though a host may still hold it.
323
463
  const now = Date.now();
324
464
  const standing = who.filter((presence) => presence.until === undefined || now < Date.parse(presence.until));
325
- return sighted(principal) ? presenceSeenBy(standing, seesId(store, principal)) : standing;
465
+ if (!sighted(principal))
466
+ return standing;
467
+ const lens = seatLens(store, principal);
468
+ return presenceSeenBy(standing, seesId(store, principal), (node, field) => !keptField(lens, node, field));
326
469
  },
327
470
  claim(batch, seat) {
328
471
  if (batch === undefined || batch === null || batch === "")
@@ -359,11 +502,22 @@ export function wireOf(store, withheldKey) {
359
502
  horizonOf: () => (store.log.horizon > 0 ? { horizon: store.log.horizon } : {}),
360
503
  enabledModules: () => [...store.modules.enabled].sort(),
361
504
  conflictsOf(author, calls, base, via) {
505
+ const behind = typedBehind(author, calls);
506
+ if (behind.length > 0)
507
+ return behind;
362
508
  if (!Array.isArray(base) || base.length === 0)
363
509
  return [];
364
510
  const lens = sighted(author) ? seatLens(store, author) : undefined;
365
- // A record the seat is not served is not there to have moved: the call itself is refused for naming it.
366
- const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" && (!lens || (lens.shows(entry.node) && !keptField(lens, entry.node, entry.field))));
511
+ /*
512
+ * A record the seat is not served is not there to have moved: the call itself is refused for naming it.
513
+ * A field typed together is never stale: a whole write over it is merged with what was typed since (`ApplyOptions.base`).
514
+ */
515
+ const claimed = base.filter((entry) => entry &&
516
+ typeof entry.node === "string" &&
517
+ typeof entry.field === "string" &&
518
+ typeof entry.rev === "number" &&
519
+ !store.collaborative(entry.node, entry.field) &&
520
+ (!lens || (lens.shows(entry.node) && !keptField(lens, entry.node, entry.field))));
367
521
  const revs = current();
368
522
  const stale = revs.stale(claimed);
369
523
  if (stale.length === 0)
@@ -408,7 +562,7 @@ export function wireOf(store, withheldKey) {
408
562
  },
409
563
  };
410
564
  }
411
- const say = (peer, message) => sayText(peer, JSON.stringify(readableBy(peer.opFormat, message)));
565
+ const sayTo = (peer, message, store) => sayText(peer, JSON.stringify(readableBy(peer.opFormat, message, store)));
412
566
  const sayText = (peer, text) => {
413
567
  try {
414
568
  peer.send(text);
@@ -436,7 +590,7 @@ const SEAT_LOST_CODE = 4000;
436
590
  /** The host lost this socket's seat: told to open again, closed when it can be, and served nothing more. */
437
591
  const lost = (peer) => {
438
592
  delete peer.cursor;
439
- say(peer, { t: "error", reopen: true, sentence: SEAT_LOST });
593
+ sayTo(peer, { t: "error", reopen: true, sentence: SEAT_LOST });
440
594
  try {
441
595
  peer.close?.(SEAT_LOST_CODE, "Seat no longer known: open it again.");
442
596
  }
@@ -451,6 +605,9 @@ const lost = (peer) => {
451
605
  export function liveProtocol(options) {
452
606
  const { store } = options;
453
607
  const wire = wireOf(store, options.withheldKey);
608
+ /** The store, as what a reader before op format 3 is sent is read from: each splice whole (`opsFor`). */
609
+ const served = store;
610
+ const say = (peer, message) => sayTo(peer, message, served);
454
611
  /**
455
612
  * The log an open carries for this seat (`openTail`): the latest ops and
456
613
  * the seq they begin at, or the whole log and the store's own horizon.
@@ -547,7 +704,7 @@ export function liveProtocol(options) {
547
704
  }
548
705
  // The ops handed in, when they are the whole of what this peer is missing; the log otherwise.
549
706
  const after = (ops && ops.length > 0 && ops[0].seq <= from && ops.at(-1).seq >= last ? ops.filter((op) => op.seq >= from) : store.log.opsFrom(from)).filter((op) => op.seq <= last);
550
- const text = after.length > 0 ? JSON.stringify({ t: "ops", seq: last, ops: opsFor(peer.opFormat, wire.shown(seat, after)) }) : "";
707
+ const text = after.length > 0 ? JSON.stringify({ t: "ops", seq: cursorAt(last), ops: opsFor(peer.opFormat, wire.shown(seat, after), served) }) : "";
551
708
  if (key !== undefined)
552
709
  sight.texts.set(key, text);
553
710
  if (text.length > 0)
@@ -556,7 +713,38 @@ export function liveProtocol(options) {
556
713
  /** Every op this socket has not been sent, down it now, as its seat sees them — up to the first that is not durable. */
557
714
  const catchUp = (peer, ops, known, sight) => {
558
715
  const held = heldFrom();
559
- sendUpTo(peer, held === undefined ? wire.lastSeq() : Math.min(wire.lastSeq(), held - 1), ops, known, sight);
716
+ const seat = known ?? principalOf(peer, sight);
717
+ if (!seat)
718
+ return;
719
+ // Up to where the seat is served: a reader of an app that publishes waits for the publish, and is taken back with an undone one (Roadmap f-publishing-lifecycle).
720
+ const last = wire.servedSeq(seat) - 1;
721
+ if (peer.cursor !== undefined && peer.cursor > last && last < wire.lastSeq())
722
+ return reset(peer, seat);
723
+ sendUpTo(peer, held === undefined ? last : Math.min(last, held - 1), ops, seat, sight);
724
+ };
725
+ /**
726
+ * A SOCKET THAT CANNOT BE CAUGHT UP OP BY OP IS SENT THE WHOLE STATE: one
727
+ * that resumes behind the compaction horizon, whose ops before it are in
728
+ * no answer, or a reader that holds ops past where it is now served (a
729
+ * publish taken back). A `welcome` with `state`, its cursor where the
730
+ * state ends — never the ops after the horizon as if those before had
731
+ * been sent.
732
+ */
733
+ const reset = (peer, seat, said = {}) => {
734
+ peer.cursor = wire.servedSeq(seat) - 1;
735
+ const seen = wire.seenFor(seat);
736
+ say(peer, {
737
+ t: "welcome",
738
+ protocol: WIRE_PROTOCOL,
739
+ wire: LIVE_WIRE,
740
+ version: options.version ?? 1,
741
+ ...said,
742
+ ...(peer.participant ? { participant: peer.participant } : {}),
743
+ seq: cursorAt(peer.cursor),
744
+ ops: [],
745
+ ...wire.servedOf(seat),
746
+ state: { version: options.version ?? 1, snapshot: seen.snapshot(), ...openedLog(seat), migrated: [...(options.migrated ?? [])], enabledModules: wire.enabledModules() },
747
+ });
560
748
  };
561
749
  /** The host's hold, in its sentence, or nothing: the app takes changes (FR-66). */
562
750
  const heldNow = () => {
@@ -594,7 +782,19 @@ export function liveProtocol(options) {
594
782
  throw new NotAdmitted(answer);
595
783
  }
596
784
  : undefined;
597
- const applying = { author: seat, via, ...(change.intent ? { intent: change.intent } : {}), batch, ...(admitting ? { admit: admitting } : {}), ...(change.lineage !== undefined ? { lineage: change.lineage } : {}) };
785
+ // What the caller read, so a whole write over a field typed together merges with what was typed since (Roadmap f-collab-text).
786
+ const base = Array.isArray(change.base)
787
+ ? change.base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number")
788
+ : [];
789
+ const applying = {
790
+ author: seat,
791
+ via,
792
+ ...(change.intent ? { intent: change.intent } : {}),
793
+ batch,
794
+ ...(admitting ? { admit: admitting } : {}),
795
+ ...(change.lineage !== undefined ? { lineage: change.lineage } : {}),
796
+ ...(base.length > 0 ? { base } : {}),
797
+ };
598
798
  result = change.t === "undo" ? store.undo(change.batches, applying) : store.applyAll(change.calls, applying);
599
799
  }
600
800
  catch (error) {
@@ -636,7 +836,7 @@ export function liveProtocol(options) {
636
836
  const sayLimited = (peer, cid, limited) => {
637
837
  if ("refuse" in limited) {
638
838
  delete peer.held;
639
- say(peer, { t: "refused", cid, reason: "limit", sentence: limited.refuse });
839
+ say(peer, { t: "refused", cid, reason: limited.reason ?? "limit", sentence: limited.refuse });
640
840
  }
641
841
  else if ("unavailable" in limited) {
642
842
  // Not for a while, and no wait to name: refused `unavailable`, which the client keeps and sends again, backing off.
@@ -650,10 +850,12 @@ export function liveProtocol(options) {
650
850
  }
651
851
  return { cursor: peer.cursor };
652
852
  };
653
- /** The same word over HTTP: 413 `limit`, 503 `unavailable`, or 429 with `Retry-After`. */
853
+ /** The same word over HTTP: 413 `limit` (401 `unauthenticated`, 403 `quota`), 503 `unavailable`, or 429 with `Retry-After`. */
654
854
  const limitedReply = (limited, said) => {
655
- if ("refuse" in limited)
656
- return reply(413, { error: limited.refuse, refused: true, reason: "limit", ...said });
855
+ if ("refuse" in limited) {
856
+ const reason = limited.reason ?? "limit";
857
+ return reply(reason === "quota" ? 403 : reason === "unauthenticated" ? 401 : 413, { error: limited.refuse, refused: true, reason, ...said });
858
+ }
657
859
  if ("unavailable" in limited)
658
860
  return reply(503, { error: limited.unavailable, refused: true, reason: "unavailable", ...said });
659
861
  const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
@@ -670,7 +872,7 @@ export function liveProtocol(options) {
670
872
  */
671
873
  const landing = await land(seat, via, change, bytes, (own) => {
672
874
  if (own.length === 0 || heldFrom(own[0].seq) === undefined)
673
- peer.cursor = wire.lastSeq();
875
+ peer.cursor = Math.min(wire.lastSeq(), wire.servedSeq(seat) - 1);
674
876
  });
675
877
  // What it would do is over the host's caps: nothing was kept.
676
878
  if (landing.limited)
@@ -696,11 +898,12 @@ export function liveProtocol(options) {
696
898
  const acked = (peer, seat, cid, batch, own, saved) => {
697
899
  const first = own[0]?.seq;
698
900
  if (first !== undefined) {
699
- sendUpTo(peer, first - 1, undefined, seat);
700
- peer.cursor = Math.max(peer.cursor, own.at(-1).seq);
901
+ sendUpTo(peer, Math.min(first - 1, wire.servedSeq(seat) - 1), undefined, seat);
902
+ // A reader of an app that publishes is acked its own, and its cursor stays where it is served (Roadmap f-publishing-lifecycle).
903
+ peer.cursor = Math.max(peer.cursor, Math.min(own.at(-1).seq, wire.servedSeq(seat) - 1));
701
904
  }
702
905
  const ops = wire.shown(seat, own);
703
- say(peer, { t: "ack", cid, seq: ops.at(-1)?.seq ?? peer.cursor, batch, ops });
906
+ say(peer, { t: "ack", cid, seq: cursorAt(ops.at(-1)?.seq ?? peer.cursor), batch, ops });
704
907
  return { cursor: peer.cursor, ...(saved && saved.length > 0 ? { landed: saved } : {}) };
705
908
  };
706
909
  /** The host's build a socket — or a route's request — is served by (FR-44): its own, else the protocol's word for it. */
@@ -775,8 +978,11 @@ export function liveProtocol(options) {
775
978
  peer.opFormat = message.opFormat;
776
979
  else
777
980
  delete peer.opFormat;
778
- const seq = typeof message.seq === "number" && Number.isFinite(message.seq) ? message.seq : undefined;
779
- peer.cursor = wire.lastSeq();
981
+ const asked = seqAt(message.seq);
982
+ // Behind the horizon, or past where the seat is served: the whole state, never a skip (`behind`).
983
+ // A page that read nothing (-1) is behind a horizon past 0 as any other is: what it never read is not in the log to send.
984
+ const seq = asked !== undefined && wire.behind(seat, asked) ? undefined : asked;
985
+ peer.cursor = wire.servedSeq(seat) - 1;
780
986
  // Its own key, built from the seat, so the client can leave itself out of who is here (FR-47).
781
987
  peer.participant ??= participantKey({ kind: seat.kind, ...(seat.id ? { id: seat.id } : {}), session: mintSession() });
782
988
  const participant = peer.participant;
@@ -788,8 +994,9 @@ export function liveProtocol(options) {
788
994
  say(peer, {
789
995
  t: "welcome",
790
996
  ...said,
791
- seq: peer.cursor,
997
+ seq: cursorAt(peer.cursor),
792
998
  ops: [],
999
+ ...wire.servedOf(seat),
793
1000
  state: {
794
1001
  version: options.version ?? 1,
795
1002
  snapshot: seen.snapshot(),
@@ -804,7 +1011,7 @@ export function liveProtocol(options) {
804
1011
  const held = heldFrom();
805
1012
  if (held !== undefined)
806
1013
  peer.cursor = Math.max(Math.floor(seq), held - 1);
807
- say(peer, { t: "welcome", ...said, seq: peer.cursor, ops: wire.since(seat, seq).filter((op) => op.seq <= peer.cursor) });
1014
+ say(peer, { t: "welcome", ...said, seq: cursorAt(peer.cursor), ops: wire.since(seat, seq).filter((op) => op.seq <= peer.cursor), ...wire.servedOf(seat) });
808
1015
  }
809
1016
  const others = heldBySockets(who, [peer, ...peers]).filter((presence) => presence.participant !== peer.participant);
810
1017
  if (others.length > 0)
@@ -853,7 +1060,7 @@ export function liveProtocol(options) {
853
1060
  return acked(peer, seat, cid, message.batch, claim.answered, flushed.saved);
854
1061
  }
855
1062
  catchUp(peer, undefined, seat);
856
- say(peer, { t: "ack", cid, seq: claim.answered.at(-1).seq, batch: message.batch, ops: wire.shown(seat, claim.answered) });
1063
+ say(peer, { t: "ack", cid, seq: cursorAt(claim.answered.at(-1).seq), batch: message.batch, ops: wire.shown(seat, claim.answered) });
857
1064
  return { cursor: peer.cursor };
858
1065
  }
859
1066
  /*
@@ -970,9 +1177,9 @@ export function liveProtocol(options) {
970
1177
  const flushed = await durable([]);
971
1178
  if (!("saved" in flushed))
972
1179
  return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
973
- return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered)), batch: change.batch, ...said }), landed: flushed.saved };
1180
+ return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered), served), batch: change.batch, ...said }), landed: flushed.saved };
974
1181
  }
975
- return reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered)), batch: change.batch, ...said });
1182
+ return reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered), served), batch: change.batch, ...said });
976
1183
  }
977
1184
  /*
978
1185
  * THE HOST'S LIMITS, BEFORE ANYTHING IS JUDGED. Busy is 429 and the
@@ -1003,7 +1210,7 @@ export function liveProtocol(options) {
1003
1210
  if (!landing.saved)
1004
1211
  return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
1005
1212
  // An act may make what its own seat may not see: that op goes back withheld, as it would on a poll.
1006
- return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, landing.result.ops)), batch: landing.result.batch, ...said }), landed: landing.saved };
1213
+ return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, landing.result.ops), served), batch: landing.result.batch, ...said }), landed: landing.saved };
1007
1214
  },
1008
1215
  state(asked) {
1009
1216
  const seen = wire.seenFor(asked.seat);
@@ -1012,13 +1219,21 @@ export function liveProtocol(options) {
1012
1219
  ...answering(asked),
1013
1220
  snapshot: seen.snapshot(),
1014
1221
  ...opened,
1015
- log: opsFor(asked.opFormat, opened.log),
1222
+ log: opsFor(asked.opFormat, opened.log, served),
1223
+ cursor: cursorAt(opened.log.at(-1)?.seq ?? (opened.horizon ?? 0) - 1),
1224
+ ...wire.servedOf(asked.seat),
1016
1225
  migrated: [...(options.migrated ?? [])],
1017
1226
  enabledModules: wire.enabledModules(),
1018
1227
  });
1019
1228
  },
1020
1229
  since(seq, asked) {
1021
- return reply(200, { ops: opsFor(asked.opFormat, wire.since(asked.seat, seq)), ...answering(asked) });
1230
+ const ops = wire.since(asked.seat, seq);
1231
+ const cursor = cursorAt(ops.at(-1)?.seq ?? seq);
1232
+ // A client the ops cannot catch up — behind the horizon, or past where it is now served — is told to take the state.
1233
+ // (The ops after the horizon still come, so a client that predates `reset` sees the gap and takes the state as it did.)
1234
+ if (wire.behind(asked.seat, seq))
1235
+ return reply(200, { ops: opsFor(asked.opFormat, ops, served), cursor, reset: true, ...wire.horizonOf(), ...wire.servedOf(asked.seat), ...answering(asked) });
1236
+ return reply(200, { ops: opsFor(asked.opFormat, ops, served), cursor, ...wire.servedOf(asked.seat), ...answering(asked) });
1022
1237
  },
1023
1238
  declared(peers) {
1024
1239
  for (const peer of peers) {
@@ -1035,6 +1250,13 @@ export function liveProtocol(options) {
1035
1250
  if (peer.cursor !== undefined)
1036
1251
  sayText(peer, text);
1037
1252
  },
1253
+ floor(peers) {
1254
+ let lowest;
1255
+ for (const peer of peers)
1256
+ if (peer.cursor !== undefined && (lowest === undefined || peer.cursor < lowest))
1257
+ lowest = peer.cursor;
1258
+ return lowest === undefined ? undefined : lowest + 1;
1259
+ },
1038
1260
  };
1039
1261
  }
1040
1262
  /** Whether a field of a record is one the seat's sight keeps from it (Roadmap f-field-sight): when it was last written is not the seat's to learn either. */