@minca/core 0.1.8 → 0.1.10

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 (157) hide show
  1. package/README.md +1 -1
  2. package/dist/files/file-id.d.ts +51 -0
  3. package/dist/files/file-id.d.ts.map +1 -0
  4. package/dist/files/file-id.js +97 -0
  5. package/dist/files/file-id.js.map +1 -0
  6. package/dist/files/seal.d.ts +20 -0
  7. package/dist/files/seal.d.ts.map +1 -0
  8. package/dist/files/seal.js +77 -0
  9. package/dist/files/seal.js.map +1 -0
  10. package/dist/files/space-files.d.ts +51 -0
  11. package/dist/files/space-files.d.ts.map +1 -0
  12. package/dist/files/space-files.js +476 -0
  13. package/dist/files/space-files.js.map +1 -0
  14. package/dist/identity/abilities.d.ts +3 -3
  15. package/dist/identity/abilities.d.ts.map +1 -1
  16. package/dist/identity/abilities.js +9 -11
  17. package/dist/identity/abilities.js.map +1 -1
  18. package/dist/identity/root-signer.d.ts +0 -5
  19. package/dist/identity/root-signer.d.ts.map +1 -1
  20. package/dist/identity/root-signer.js +0 -1
  21. package/dist/identity/root-signer.js.map +1 -1
  22. package/dist/index.d.ts +5 -4
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/node/api.d.ts +5 -1
  27. package/dist/node/api.d.ts.map +1 -1
  28. package/dist/node/api.js +10 -2
  29. package/dist/node/api.js.map +1 -1
  30. package/dist/node/carrier.d.ts +17 -2
  31. package/dist/node/carrier.d.ts.map +1 -1
  32. package/dist/node/carrier.js +26 -4
  33. package/dist/node/carrier.js.map +1 -1
  34. package/dist/node/copy.d.ts +0 -4
  35. package/dist/node/copy.d.ts.map +1 -1
  36. package/dist/node/copy.js +26 -0
  37. package/dist/node/copy.js.map +1 -1
  38. package/dist/node/host.d.ts +66 -1
  39. package/dist/node/host.d.ts.map +1 -1
  40. package/dist/node/host.js +571 -5
  41. package/dist/node/host.js.map +1 -1
  42. package/dist/node/index.d.ts +2 -2
  43. package/dist/node/index.d.ts.map +1 -1
  44. package/dist/node/index.js +1 -1
  45. package/dist/node/index.js.map +1 -1
  46. package/dist/node/node.d.ts.map +1 -1
  47. package/dist/node/node.js +328 -269
  48. package/dist/node/node.js.map +1 -1
  49. package/dist/node/remote.d.ts +6 -5
  50. package/dist/node/remote.d.ts.map +1 -1
  51. package/dist/node/remote.js +141 -194
  52. package/dist/node/remote.js.map +1 -1
  53. package/dist/node/space-runtime.d.ts +9 -0
  54. package/dist/node/space-runtime.d.ts.map +1 -1
  55. package/dist/node/space-runtime.js +194 -98
  56. package/dist/node/space-runtime.js.map +1 -1
  57. package/dist/node/stores.d.ts +44 -8
  58. package/dist/node/stores.d.ts.map +1 -1
  59. package/dist/node/stores.js +44 -7
  60. package/dist/node/stores.js.map +1 -1
  61. package/dist/node/types.d.ts +77 -10
  62. package/dist/node/types.d.ts.map +1 -1
  63. package/dist/node/usage.d.ts +54 -0
  64. package/dist/node/usage.d.ts.map +1 -0
  65. package/dist/node/usage.js +201 -0
  66. package/dist/node/usage.js.map +1 -0
  67. package/dist/node/worker.d.ts +1 -1
  68. package/dist/node/worker.d.ts.map +1 -1
  69. package/dist/node/worker.js +10 -6
  70. package/dist/node/worker.js.map +1 -1
  71. package/dist/schema/version.d.ts +5 -0
  72. package/dist/schema/version.d.ts.map +1 -1
  73. package/dist/schema/version.js +1 -0
  74. package/dist/schema/version.js.map +1 -1
  75. package/dist/schemas/fragments.d.ts +23 -2
  76. package/dist/schemas/fragments.d.ts.map +1 -1
  77. package/dist/schemas/fragments.js +5 -2
  78. package/dist/schemas/fragments.js.map +1 -1
  79. package/dist/schemas/library/annotations.d.ts +24 -0
  80. package/dist/schemas/library/annotations.d.ts.map +1 -1
  81. package/dist/schemas/library/community.d.ts +24 -0
  82. package/dist/schemas/library/community.d.ts.map +1 -1
  83. package/dist/schemas/library/life.d.ts +72 -0
  84. package/dist/schemas/library/life.d.ts.map +1 -1
  85. package/dist/schemas/library/media.d.ts +144 -0
  86. package/dist/schemas/library/media.d.ts.map +1 -1
  87. package/dist/schemas/library/money.d.ts +24 -0
  88. package/dist/schemas/library/money.d.ts.map +1 -1
  89. package/dist/schemas/library/publishing.d.ts +96 -0
  90. package/dist/schemas/library/publishing.d.ts.map +1 -1
  91. package/dist/schemas/library/social.d.ts +72 -0
  92. package/dist/schemas/library/social.d.ts.map +1 -1
  93. package/dist/session/auth.d.ts +20 -0
  94. package/dist/session/auth.d.ts.map +1 -1
  95. package/dist/session/auth.js +88 -64
  96. package/dist/session/auth.js.map +1 -1
  97. package/dist/session/connect.d.ts +50 -8
  98. package/dist/session/connect.d.ts.map +1 -1
  99. package/dist/session/connect.js +91 -27
  100. package/dist/session/connect.js.map +1 -1
  101. package/dist/session/connection.d.ts +39 -6
  102. package/dist/session/connection.d.ts.map +1 -1
  103. package/dist/session/connection.js +107 -38
  104. package/dist/session/connection.js.map +1 -1
  105. package/dist/session/hosting.d.ts +88 -28
  106. package/dist/session/hosting.d.ts.map +1 -1
  107. package/dist/session/hosting.js +137 -6
  108. package/dist/session/hosting.js.map +1 -1
  109. package/dist/session/index.d.ts +5 -5
  110. package/dist/session/index.d.ts.map +1 -1
  111. package/dist/session/index.js +2 -2
  112. package/dist/session/index.js.map +1 -1
  113. package/dist/session/places.d.ts +2 -0
  114. package/dist/session/places.d.ts.map +1 -1
  115. package/dist/session/places.js +8 -2
  116. package/dist/session/places.js.map +1 -1
  117. package/dist/space/account-registry.d.ts +27 -4
  118. package/dist/space/account-registry.d.ts.map +1 -1
  119. package/dist/space/account-registry.js +25 -3
  120. package/dist/space/account-registry.js.map +1 -1
  121. package/dist/space/roles.d.ts +59 -140
  122. package/dist/space/roles.d.ts.map +1 -1
  123. package/dist/space/roles.js +328 -427
  124. package/dist/space/roles.js.map +1 -1
  125. package/dist/storage/blob/directory.d.ts +14 -0
  126. package/dist/storage/blob/directory.d.ts.map +1 -0
  127. package/dist/storage/blob/directory.js +80 -0
  128. package/dist/storage/blob/directory.js.map +1 -0
  129. package/dist/storage/folder-adapter.d.ts +22 -0
  130. package/dist/storage/folder-adapter.d.ts.map +1 -1
  131. package/dist/storage/folder-adapter.js +5 -5
  132. package/dist/storage/folder-adapter.js.map +1 -1
  133. package/dist/storage/mirror.d.ts +9 -2
  134. package/dist/storage/mirror.d.ts.map +1 -1
  135. package/dist/storage/mirror.js +60 -35
  136. package/dist/storage/mirror.js.map +1 -1
  137. package/dist/storage/segment.d.ts +7 -2
  138. package/dist/storage/segment.d.ts.map +1 -1
  139. package/dist/storage/segment.js +25 -3
  140. package/dist/storage/segment.js.map +1 -1
  141. package/dist/sync/sync-engine.d.ts +2 -0
  142. package/dist/sync/sync-engine.d.ts.map +1 -1
  143. package/dist/sync/sync-engine.js +5 -0
  144. package/dist/sync/sync-engine.js.map +1 -1
  145. package/dist/sync/sync-messages.d.ts +24 -0
  146. package/dist/sync/sync-messages.d.ts.map +1 -1
  147. package/dist/sync/sync-messages.js.map +1 -1
  148. package/docs/actions.md +3 -3
  149. package/docs/agents.md +2 -2
  150. package/docs/blueprints-and-guides.md +20 -1
  151. package/docs/bots.md +1 -1
  152. package/docs/node.md +138 -75
  153. package/docs/sign-in.md +16 -9
  154. package/docs/spaces.md +18 -10
  155. package/docs/standard-library.md +16 -20
  156. package/docs/storage.md +121 -16
  157. package/package.json +1 -1
@@ -38,42 +38,23 @@ import { commandCovers } from '../identity/ucan.js';
38
38
  import { canonicalize } from '../schema/version.js';
39
39
  import { isObject } from '../utils/guards.js';
40
40
  import { COLLECTION_DEFINE, grantFits, grantShape, KEY_CHANGE, MEMBER_REMOVE, ROLE_ASSIGN, ROLE_DEFINE, ROLE_UNASSIGN, SPACE_KEEPERS, SPACE_RELAYS, SPACE_SUCCEED, } from './grants.js';
41
- /** A role's definitions */
42
41
  export const ROLE_COLLECTION = 'sys.role';
43
42
  /** Assigning a role to an account, and taking it away */
44
43
  export const ASSIGN_COLLECTION = 'sys.assign';
45
- /** Removing an account from the space */
46
44
  export const REMOVE_COLLECTION = 'sys.remove';
47
45
  export const INVITE_COLLECTION = 'sys.invite';
48
46
  export const REVOKE_COLLECTION = 'sys.revoke';
49
47
  /** Collection definitions are part of the access history too: what a version must keep to */
50
48
  export const DEFINITION_COLLECTION = 'sys.collection';
51
- /**
52
- * A private space's key changes: the new key's id and public read key. The
53
- * key itself travels sealed to each member (`sys.box`); this record only says
54
- * which key is current, so a peer without any key can still check readers.
55
- */
49
+ /** Which of a private space's keys is current; the key itself travels sealed to each member (`sys.box`) */
56
50
  export const KEY_COLLECTION = 'sys.key';
57
- /**
58
- * Where the space's members meet: the relays it names, so two people whose
59
- * apps use different relays still find each other. Like a Nostr relay list,
60
- * but the space's, and changed only by someone granted `/space/relays`.
61
- */
51
+ /** The relays the space's members meet at, so people whose apps use different relays still find each other */
62
52
  export const RELAYS_COLLECTION = 'sys.relays';
63
- /**
64
- * Who keeps the space whole: nodes that hold every record of it — a host, an
65
- * extension — and how many copies a write should reach before a node that
66
- * holds only part of the space lets go of it.
67
- */
53
+ /** Nodes that hold the whole space, and how many a write should reach before a partial node lets go of it */
68
54
  export const KEEPERS_COLLECTION = 'sys.keepers';
69
- /**
70
- * A writer's log forked: two versions one key signed at one place in its line
71
- * for one collection of this space (02 §4.10). The record carries both, so
72
- * every peer checks the proof for itself, and the key's versions in that
73
- * collection from that place on stop counting.
74
- */
55
+ /** A fork proof: two versions one key signed at one place in its line (02 §4.10), checked by every peer */
75
56
  export const FORK_COLLECTION = 'sys.fork';
76
- /** A founder stepping down: it stays, with the roles it holds, and is a founder no more */
57
+ /** A founder stepping down: it keeps its roles, and is a founder no more */
77
58
  export const STEPDOWN_COLLECTION = 'sys.stepdown';
78
59
  /** A space that succeeds this one, by its id. It changes nothing here. */
79
60
  export const SUCCEED_COLLECTION = 'sys.succeed';
@@ -81,21 +62,28 @@ export const SUCCEED_COLLECTION = 'sys.succeed';
81
62
  export const STRONG_REMOVE = 'strong-remove/1';
82
63
  /** Every resolver this peer knows. A space naming another is not judged here. */
83
64
  export const RESOLVERS = new Set([STRONG_REMOVE]);
65
+ const accessKind = (collection, prefix, clear = true) => Object.freeze({ collection, prefix, clear });
66
+ /**
67
+ * Each kind of change: its collection, where its line is counted too; its record keys' prefix; and
68
+ * whether a private space keeps it in the clear, so a peer without the key can still judge who may
69
+ * do what. Collection definitions stay sealed: only readers need their rules.
70
+ */
71
+ export const ACCESS_KINDS = Object.freeze({
72
+ role: accessKind(ROLE_COLLECTION, 'role:'),
73
+ assign: accessKind(ASSIGN_COLLECTION, 'assign:'),
74
+ remove: accessKind(REMOVE_COLLECTION, 'remove:'),
75
+ invite: accessKind(INVITE_COLLECTION, 'invite:'),
76
+ revoke: accessKind(REVOKE_COLLECTION, 'revoke:'),
77
+ definition: accessKind(DEFINITION_COLLECTION, 'collection:', false),
78
+ key: accessKind(KEY_COLLECTION, 'key:'),
79
+ relays: accessKind(RELAYS_COLLECTION, 'relays:'),
80
+ keepers: accessKind(KEEPERS_COLLECTION, 'keepers:'),
81
+ fork: accessKind(FORK_COLLECTION, 'fork:'),
82
+ stepdown: accessKind(STEPDOWN_COLLECTION, 'stepdown:'),
83
+ succeed: accessKind(SUCCEED_COLLECTION, 'succeed:'),
84
+ });
84
85
  /** Every collection whose records are part of the access history */
85
- export const ACCESS_COLLECTIONS = new Set([
86
- ROLE_COLLECTION,
87
- ASSIGN_COLLECTION,
88
- REMOVE_COLLECTION,
89
- INVITE_COLLECTION,
90
- REVOKE_COLLECTION,
91
- DEFINITION_COLLECTION,
92
- KEY_COLLECTION,
93
- RELAYS_COLLECTION,
94
- KEEPERS_COLLECTION,
95
- FORK_COLLECTION,
96
- STEPDOWN_COLLECTION,
97
- SUCCEED_COLLECTION,
98
- ]);
86
+ export const ACCESS_COLLECTIONS = new Set(Object.values(ACCESS_KINDS).map(({ collection }) => collection));
99
87
  /** How many keepers a space may name */
100
88
  export const MAX_KEEPERS = 16;
101
89
  /** Why a list of keepers can't be a space's, or null */
@@ -226,81 +214,60 @@ export function may(state, did, cmd, args, options = {}) {
226
214
  const known = cache.get(key);
227
215
  if (known !== undefined)
228
216
  return known;
229
- const answer = roles.some((role) => roleMay(state, role, cmd, args, !!options.opaque, new Set()));
217
+ const opaque = !!options.opaque;
218
+ const answer = roles.some((role) => roleHolds(state, role, (grant) => grantFits(grant, cmd, args, opaque), (view, by) => may(view, by, cmd, args, { opaque })));
230
219
  cache.set(key, answer);
231
220
  return answer;
232
221
  }
233
- /** Whether a role's grants let its members invoke a command with these arguments */
234
- function roleMay(state, role, cmd, args, opaque, visiting) {
222
+ /** A role as its rival definitions leave it: what they all hold, and the authors whose power bounds it */
223
+ function effectiveRole(state, role) {
224
+ const heads = state.roles.get(role);
225
+ if (!heads?.length)
226
+ return null;
227
+ const [first, ...rivals] = heads;
228
+ return {
229
+ grants: first.grants.filter((grant) => rivals.every((rival) => rival.grants.some((other) => grantShape(other) === grantShape(grant)))),
230
+ nests: first.nests.filter((nested) => rivals.every((rival) => rival.nests.includes(nested))),
231
+ authors: heads.flatMap(({ view, by }) => (view === null || by === null ? [] : [{ view, by }])),
232
+ };
233
+ }
234
+ /** Whether a role, or one it nests, holds a grant that `fits`, as far as each definition's author did */
235
+ function roleHolds(state, role, fits, authorHolds, visiting = new Set()) {
235
236
  if (visiting.has(role))
236
237
  return false;
237
- const heads = state.roles.get(role);
238
- if (!heads || heads.length === 0)
238
+ const found = effectiveRole(state, role);
239
+ if (!found)
239
240
  return false;
240
- const [first, ...rivals] = heads;
241
- // What every current definition holds: a grant by its command and policy, a nesting by its role.
242
- const delegated = first.grants.some((grant) => grantFits(grant, cmd, args, opaque) &&
243
- rivals.every((rival) => rival.grants.some((other) => grantShape(other) === grantShape(grant))));
244
241
  const inner = new Set(visiting).add(role);
245
- const held = delegated ||
246
- first.nests.some((nested) => nested !== role &&
247
- rivals.every((rival) => rival.nests.includes(nested)) &&
248
- roleMay(state, nested, cmd, args, opaque, inner));
242
+ const held = found.grants.some(fits) ||
243
+ found.nests.some((nested) => nested !== role && roleHolds(state, nested, fits, authorHolds, inner));
249
244
  // Each definition holds only what its author could do itself, as of it.
250
- return (held &&
251
- heads.every((head) => head.view === null || head.by === null || may(head.view, head.by, cmd, args, { opaque })));
245
+ return held && found.authors.every(({ view, by }) => authorHolds(view, by));
252
246
  }
253
247
  /**
254
- * Whether an account holds every grant a role gives, each as wide or wider:
255
- * what it may hand on to a bot or an agent of its own without handing on more
256
- * than it holds. A grant is as wide when its command covers the other's and
257
- * every statement of its policy is among the other's, held through the
258
- * account's roles as {@link may} holds it (rivals sharing it, attenuated by
259
- * each definition's author). A founder holds every grant. Only the policies'
260
- * words are compared, so it may say no where the policies would in fact
261
- * allow; never yes where they wouldn't.
248
+ * Whether an account holds every grant a role gives, each as wide or wider (its command covering,
249
+ * its policy's statements among the other's): what it may hand a bot of its own. Only the policies'
250
+ * words are compared, so it may say no where they would allow; never yes where they wouldn't.
262
251
  */
263
252
  export function holdsRole(state, did, role) {
264
253
  return grantsOfRole(state, role, new Set()).every((grant) => holdsGrant(state, did, grant));
265
254
  }
266
255
  /** What a role gives its members, as grants: its current definitions' shared ones, and its nested roles' */
267
256
  function grantsOfRole(state, role, visiting) {
268
- const heads = state.roles.get(role);
269
- if (!heads?.length || visiting.has(role))
257
+ const found = effectiveRole(state, role);
258
+ if (!found || visiting.has(role))
270
259
  return [];
271
- const [first, ...rivals] = heads;
272
260
  const inner = new Set(visiting).add(role);
273
- return [
274
- ...first.grants.filter((grant) => rivals.every((rival) => rival.grants.some((other) => grantShape(other) === grantShape(grant)))),
275
- ...first.nests
276
- .filter((nested) => rivals.every((rival) => rival.nests.includes(nested)))
277
- .flatMap((nested) => grantsOfRole(state, nested, inner)),
278
- ];
261
+ return [...found.grants, ...found.nests.flatMap((nested) => grantsOfRole(state, nested, inner))];
279
262
  }
280
263
  /** Whether an account holds a grant as wide as `wanted` or wider, in a state */
281
264
  function holdsGrant(state, did, wanted) {
282
265
  if (state.founders.has(did))
283
266
  return true;
284
- return rolesOf(state, did).some((role) => roleHoldsGrant(state, role, wanted, new Set()));
285
- }
286
- function roleHoldsGrant(state, role, wanted, visiting) {
287
- if (visiting.has(role))
288
- return false;
289
- const heads = state.roles.get(role);
290
- if (!heads || heads.length === 0)
291
- return false;
292
- const [first, ...rivals] = heads;
293
267
  const statements = new Set(wanted.pol.map((statement) => canonicalize(statement)));
294
268
  const widens = (grant) => commandCovers(grant.cmd, wanted.cmd) &&
295
269
  grant.pol.every((statement) => statements.has(canonicalize(statement)));
296
- const inner = new Set(visiting).add(role);
297
- const held = first.grants.some((grant) => widens(grant) &&
298
- rivals.every((rival) => rival.grants.some((other) => grantShape(other) === grantShape(grant)))) ||
299
- first.nests.some((nested) => nested !== role &&
300
- rivals.every((rival) => rival.nests.includes(nested)) &&
301
- roleHoldsGrant(state, nested, wanted, inner));
302
- return (held &&
303
- heads.every((head) => head.view === null || head.by === null || holdsGrant(head.view, head.by, wanted)));
270
+ return rolesOf(state, did).some((role) => roleHolds(state, role, widens, (view, by) => holdsGrant(view, by, wanted)));
304
271
  }
305
272
  /** The arguments of a command about another account: `{ role?, self, roles }` */
306
273
  const targetArgs = (state, invoker, target, role) => ({
@@ -319,11 +286,8 @@ function anyMaySucceed(state) {
319
286
  return found;
320
287
  }
321
288
  /**
322
- * Why a change is not allowed in a state, or null when it is: its author
323
- * held a grant for its command with these arguments, or it is one of the
324
- * few things anyone may do for themselves (leave a role, leave the space,
325
- * step down as a founder), or it names a successor where no one holds
326
- * `/space/succeed`.
289
+ * Why a change is not allowed in a state, or null: its author holds the grant, or it is one of the
290
+ * few things anyone may do for themselves, or it names a successor where no one holds the grant.
327
291
  */
328
292
  export function refusal(event, state) {
329
293
  const root = event.root;
@@ -452,23 +416,65 @@ export function refusal(event, state) {
452
416
  : 'Its author may not change who keeps the space';
453
417
  }
454
418
  }
455
- /**
456
- * The account a change takes from, in its own view: a removal of a member,
457
- * or an unassignment of a role it holds, its own leaving included. Null when
458
- * it takes nothing: it is no reduction.
459
- */
419
+ const NO_CUTOFF = new Map();
420
+ /** Whether a reduction reaches its key's changes whatever either saw */
421
+ const reachesBack = (reduction) => reduction.reach.kind === 'key' || reduction.reach.kind === 'line';
422
+ /** What a change takes, in its own view: null when it takes nothing, and is no reduction */
460
423
  function reductionOf(event, view) {
461
- if (event.kind === 'remove')
462
- return isMember(view, event.did) ? event.did : null;
463
- if (event.kind === 'stepdown')
464
- return view.founders.has(event.did) ? event.did : null;
465
- if (event.kind === 'assign' && !event.assigned)
466
- return rolesOf(view, event.did).includes(event.role) ? event.did : null;
467
- return null;
424
+ const of = (reach, cutoff = event.cutoff) => ({ id: event.id, reach, cutoff });
425
+ const account = (holds, did) => (holds ? of({ kind: 'account', root: did }) : null);
426
+ switch (event.kind) {
427
+ case 'remove':
428
+ return account(isMember(view, event.did), event.did);
429
+ case 'stepdown':
430
+ return account(view.founders.has(event.did), event.did);
431
+ case 'assign':
432
+ return account(!event.assigned && rolesOf(view, event.did).includes(event.role), event.did);
433
+ case 'invite':
434
+ return event.open ? null : of({ kind: 'invite', invite: event.inviteKey });
435
+ case 'revoke':
436
+ return of({ kind: 'key', root: event.root, key: event.target });
437
+ // A fork proof carries no cutoff: its place is where it starts to reach.
438
+ case 'fork':
439
+ return of({ kind: 'line', key: event.writer, collection: event.collection, from: event.from }, NO_CUTOFF);
440
+ default:
441
+ return null;
442
+ }
468
443
  }
469
- /** The people whose reading a change may end */
470
- function affected(event) {
471
- return event.kind === 'assign' || event.kind === 'remove' || event.kind === 'stepdown' ? [event.did] : [];
444
+ /** Whether a reduction reaches a change or a record that its cutoff doesn't cover */
445
+ function reaches(reduction, subject) {
446
+ const { writer, collection, line } = subject;
447
+ if (writer !== undefined &&
448
+ collection !== undefined &&
449
+ line !== undefined &&
450
+ (reduction.cutoff.get(writer)?.get(collection) ?? -1) >= line)
451
+ return false;
452
+ const reach = reduction.reach;
453
+ switch (reach.kind) {
454
+ // A removal or an unassignment reaches everything its account did: what an action needed is
455
+ // judged in a view its author chooses, so it can't decide what a strike leaves.
456
+ case 'account':
457
+ return subject.root === reach.root;
458
+ case 'key':
459
+ return subject.root === reach.root && writer === reach.key;
460
+ case 'line':
461
+ return writer === reach.key && collection === reach.collection && (line ?? 0) >= reach.from;
462
+ case 'invite':
463
+ return subject.viaInvite === reach.invite;
464
+ }
465
+ }
466
+ /** Adds a valid reduction to what judging looks up: by the account or key it reaches, and each line's lowest fork */
467
+ function indexReduction(taken, forks, reduction) {
468
+ const reach = reduction.reach;
469
+ if (reach.kind === 'line') {
470
+ const line = lineOf(reach.key, reach.collection);
471
+ if (reach.from < (forks.get(line)?.reach.from ?? Infinity))
472
+ forks.set(line, { ...reduction, reach });
473
+ }
474
+ else if (reach.kind !== 'invite') {
475
+ const who = reach.kind === 'key' ? reach.key : reach.root;
476
+ taken.set(who, [...(taken.get(who) ?? []), reduction]);
477
+ }
472
478
  }
473
479
  /** A role's definition from a change, judged in `view` */
474
480
  function definitionFrom(event, view) {
@@ -533,10 +539,10 @@ function change(event, state, view) {
533
539
  state.definitions.delete(event.name);
534
540
  return;
535
541
  }
536
- const existing = state.definitions.get(event.name);
542
+ const definedBy = state.definitions.get(event.name)?.definedBy;
537
543
  state.definitions.set(event.name, {
538
544
  event: event.id,
539
- definedBy: existing ? existing.definedBy : event.root,
545
+ definedBy: definedBy !== undefined ? definedBy : event.root,
540
546
  });
541
547
  return;
542
548
  }
@@ -563,26 +569,25 @@ function change(event, state, view) {
563
569
  // changes that didn't see each other, the one that gives least.
564
570
  /** A key's line for one collection, as a map key */
565
571
  const lineOf = (writer, collection) => `${writer}\n${collection}`;
566
- /** The kind's collection: where a change's place in its key's line is counted */
567
- const KIND_COLLECTION = {
568
- role: ROLE_COLLECTION,
569
- assign: ASSIGN_COLLECTION,
570
- remove: REMOVE_COLLECTION,
571
- invite: INVITE_COLLECTION,
572
- revoke: REVOKE_COLLECTION,
573
- definition: DEFINITION_COLLECTION,
574
- key: KEY_COLLECTION,
575
- relays: RELAYS_COLLECTION,
576
- keepers: KEEPERS_COLLECTION,
577
- fork: FORK_COLLECTION,
578
- stepdown: STEPDOWN_COLLECTION,
579
- succeed: SUCCEED_COLLECTION,
580
- };
581
- function seenOf(prefix, extra, order, index) {
572
+ /** What a change names in `seen`, once each, leaving out the space itself */
573
+ const parentsOf = (event, genesisId) => [
574
+ ...new Set(event.seen.filter((parent) => parent !== genesisId)),
575
+ ];
576
+ /** What a change saw, from what its parents saw, placed by `order` and `index` */
577
+ function seenOf(parents, saw, order, index) {
578
+ let prefix = 0;
579
+ for (const parent of parents)
580
+ prefix = Math.max(prefix, saw.get(parent).prefix);
581
+ const extra = new Set();
582
+ for (const parent of parents)
583
+ for (const n of [...saw.get(parent).extra, index.get(parent)])
584
+ if (n >= prefix)
585
+ extra.add(n);
586
+ while (extra.delete(prefix))
587
+ prefix++;
582
588
  return {
583
589
  prefix,
584
590
  extra,
585
- size: prefix + extra.size,
586
591
  placeOf: (id) => index.get(id),
587
592
  has(id) {
588
593
  const i = index.get(id);
@@ -597,14 +602,8 @@ function seenOf(prefix, extra, order, index) {
597
602
  };
598
603
  }
599
604
  const byId = (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
600
- /**
601
- * The state a set of changes gives, merged: no order, only what saw what.
602
- * Rival definitions of a role all stand, and hold what they share; an
603
- * unassignment beats an assignment; an assignment counts only if it saw every
604
- * removal of its account; a closed invite beats an open one, and open ones
605
- * for different roles close it.
606
- */
607
- function merge(genesis, events, saw, lostReaders, defViews) {
605
+ /** The state a set of changes gives, merged: no order, only what saw what (spec 03 §4.4) */
606
+ function merge(genesis, events, saw, defViews) {
608
607
  const state = startState(genesis);
609
608
  const byKey = new Map();
610
609
  for (const event of events) {
@@ -613,10 +612,7 @@ function merge(genesis, events, saw, lostReaders, defViews) {
613
612
  continue;
614
613
  (byKey.get(event.key) ?? byKey.set(event.key, []).get(event.key)).push(event);
615
614
  }
616
- /**
617
- * The latest on a key: those no other on it saw. One pass: a change was seen by another if its
618
- * place is below that one's prefix, or among its exceptions.
619
- */
615
+ // The latest on a key, those no other on it saw, in one pass: below another's prefix, or among its exceptions.
620
616
  const latest = (group) => {
621
617
  if (group.length <= 1)
622
618
  return group;
@@ -725,15 +721,15 @@ function merge(genesis, events, saw, lostReaders, defViews) {
725
721
  if (event.kind === 'key')
726
722
  state.keys.push({ keyId: event.keyId, readKey: event.readKey, event: event.id });
727
723
  }
728
- // Due: someone lost reading in a change the current key had not seen. They may hold it.
729
- if (state.keys.length > 0) {
730
- const seenByKey = currentKey ? (saw.get(currentKey.id) ?? new Set()) : new Set();
731
- state.keyDue = events.some((event) => (lostReaders.get(event.id)?.length ?? 0) > 0 && !seenByKey.has(event.id) && event !== currentKey);
732
- }
733
724
  return state;
734
725
  }
735
- /** A state with one change applied on top: the change saw all of it, so it is the latest on its record */
736
- function applied(state, event, genesisId) {
726
+ /**
727
+ * A state with one change applied on top: the change saw all of it, so it is
728
+ * the latest on its record. Who defined a collection is worked out among the
729
+ * changes `counted`.
730
+ */
731
+ function applied(state, event, r, counted) {
732
+ const genesisId = r.genesis.id;
737
733
  const next = {
738
734
  ...state,
739
735
  founders: new Set(state.founders),
@@ -747,7 +743,6 @@ function applied(state, event, genesisId) {
747
743
  };
748
744
  change(event, next, state);
749
745
  if (event.kind === 'key') {
750
- next.keyDue = false;
751
746
  // The keys before it in the order a merge gives: the space's own first, the rest by id.
752
747
  const earlier = next.keys.slice(0, -1);
753
748
  const own = earlier.filter((key) => key.event === genesisId);
@@ -756,6 +751,13 @@ function applied(state, event, genesisId) {
756
751
  .sort((a, b) => (a.event < b.event ? -1 : a.event > b.event ? 1 : 0));
757
752
  next.keys = [...own, ...rest, next.keys.at(-1)];
758
753
  }
754
+ if (event.kind === 'definition' && !event.deleted) {
755
+ const group = [...r.saw.get(event.id)]
756
+ .filter((other) => counted.has(other) && r.byId.get(other).key === event.key)
757
+ .map((other) => r.byId.get(other))
758
+ .concat(event);
759
+ next.definitions.set(event.name, { event: event.id, definedBy: definerOf(event, group, r.saw) });
760
+ }
759
761
  return next;
760
762
  }
761
763
  /**
@@ -813,11 +815,7 @@ function firstsOf(win, group, saw) {
813
815
  (event === win || removals.every((removal) => saw.get(event.id)?.has(removal.id))));
814
816
  return life.filter((event) => !life.some((other) => other !== event && saw.get(event.id)?.has(other.id)));
815
817
  }
816
- /**
817
- * The strongly connected components of a graph (Tarjan's, without
818
- * recursion: a long history must not overflow the stack), listed so that
819
- * every component comes after those with an edge into it.
820
- */
818
+ /** A graph's strongly connected components, each after those with an edge into it (Tarjan's, without recursion: a long history must not overflow the stack) */
821
819
  function componentsOf(nodes, edges) {
822
820
  let counter = 0;
823
821
  const indices = new Map();
@@ -826,26 +824,25 @@ function componentsOf(nodes, edges) {
826
824
  const onStack = new Set();
827
825
  const found = [];
828
826
  const of = new Map();
827
+ const work = [];
828
+ const visit = (id) => {
829
+ indices.set(id, counter);
830
+ low.set(id, counter++);
831
+ stack.push(id);
832
+ onStack.add(id);
833
+ work.push({ id, next: 0 });
834
+ };
829
835
  for (const root of nodes) {
830
836
  if (indices.has(root))
831
837
  continue;
832
- const work = [{ id: root, next: 0 }];
833
- indices.set(root, counter);
834
- low.set(root, counter++);
835
- stack.push(root);
836
- onStack.add(root);
838
+ visit(root);
837
839
  while (work.length > 0) {
838
840
  const frame = work.at(-1);
839
841
  const out = edges.get(frame.id) ?? [];
840
842
  if (frame.next < out.length) {
841
843
  const next = out[frame.next++];
842
- if (!indices.has(next)) {
843
- indices.set(next, counter);
844
- low.set(next, counter++);
845
- stack.push(next);
846
- onStack.add(next);
847
- work.push({ id: next, next: 0 });
848
- }
844
+ if (!indices.has(next))
845
+ visit(next);
849
846
  else if (onStack.has(next))
850
847
  low.set(frame.id, Math.min(low.get(frame.id), indices.get(next)));
851
848
  continue;
@@ -901,7 +898,7 @@ export function replayAccess(genesis, events) {
901
898
  const children = new Map();
902
899
  const pending = new Map();
903
900
  for (const event of placeable) {
904
- const parents = [...new Set(event.seen.filter((p) => p !== genesis.id))];
901
+ const parents = parentsOf(event, genesis.id);
905
902
  pending.set(event.id, parents.length);
906
903
  for (const parent of parents)
907
904
  (children.get(parent) ?? children.set(parent, []).get(parent)).push(event.id);
@@ -926,136 +923,70 @@ export function replayAccess(genesis, events) {
926
923
  const index = new Map(order.map((id, i) => [id, i]));
927
924
  const saw = new Map();
928
925
  for (const id of order) {
929
- const parents = [...new Set(byIdMap.get(id).seen.filter((parent) => parent !== genesis.id))];
930
- let prefix = 0;
931
- for (const parent of parents)
932
- prefix = Math.max(prefix, saw.get(parent).prefix);
933
- const extra = new Set();
934
- for (const parent of parents)
935
- for (const n of [...saw.get(parent).extra, index.get(parent)])
936
- if (n >= prefix)
937
- extra.add(n);
938
- while (extra.delete(prefix))
939
- prefix++;
940
- saw.set(id, seenOf(prefix, extra, order, index));
926
+ saw.set(id, seenOf(parentsOf(byIdMap.get(id), genesis.id), saw, order, index));
941
927
  }
942
928
  // In order, ancestors first: each change's own view (the allowed changes it saw), whether it is
943
929
  // allowed there, what it takes, and the strikes it is part of.
944
- const lostReaders = new Map();
930
+ const tookReading = new Set();
945
931
  const refused = new Map();
946
932
  const allowedIds = new Set();
947
- const scopes = new Map();
948
933
  const strikes = new Map();
949
934
  const afterOf = new Map();
950
935
  const defViews = new Map();
951
- const keyWide = (event) => event.kind === 'revoke' || event.kind === 'fork';
952
- const covers = (reduction, event) => (!keyWide(reduction) && saw.get(reduction.id).has(event.id)) ||
953
- (event.line !== undefined &&
954
- (reduction.cutoff.get(event.author)?.get(KIND_COLLECTION[event.kind]) ?? -1) >= event.line);
955
- const reaches = (reduction, event) => {
956
- if (reduction.kind === 'revoke')
957
- return event.root === reduction.root && event.author === reduction.target;
958
- if (reduction.kind === 'fork')
959
- return (event.author === reduction.writer &&
960
- KIND_COLLECTION[event.kind] === reduction.collection &&
961
- (event.line ?? 0) >= reduction.from);
962
- // Closing an invite strikes joins through it that the close had not seen.
963
- if (reduction.kind === 'invite')
964
- return !reduction.open && event.kind === 'assign' && event.viaInvite === reduction.inviteKey;
965
- // A removal or an unassignment reaches everything its account did: what an action needed is
966
- // judged in a view its author chooses, so it can't decide what a strike leaves.
967
- return scopes.get(reduction.id) === event.root;
968
- };
969
- // Revokes and fork proofs are never struck: every allowed one applies.
970
- const reachedBy = (reduction, event) => reduction.id !== event.id &&
971
- !keyWide(event) &&
972
- (keyWide(reduction) || !saw.get(event.id).has(reduction.id)) &&
973
- !covers(reduction, event) &&
974
- reaches(reduction, event);
975
- // A stepping down is never struck (`invalidWithin`): founder status can't be given again. One a
976
- // revoke or a fork proof reaches ends founder status and does nothing more (below).
977
- const strikesOn = (reduction, event) => !(keyWide(reduction) && event.kind === 'stepdown') && reachedBy(reduction, event);
978
- const reductionIds = [];
979
- const allowedView = viewsAlong(byIdMap, saw, genesis, (id) => allowedIds.has(id), afterOf, lostReaders, defViews);
936
+ /** The allowed reductions, in order */
937
+ const taking = new Map();
938
+ const strike = (by, id) => (strikes.get(by) ?? strikes.set(by, []).get(by)).push(id);
939
+ const allowedView = viewsAlong({ genesis, saw, byId: byIdMap }, (id) => allowedIds.has(id), afterOf, defViews);
980
940
  for (const id of order) {
981
941
  const event = byIdMap.get(id);
982
- const view = allowedView(event);
983
- const reason = refusal(event, view);
984
- if (reason) {
985
- refused.set(id, reason);
942
+ const result = step(event, allowedView(event), { genesis, saw, byId: byIdMap, allowedIds, taking });
943
+ if (typeof result === 'string') {
944
+ refused.set(id, result);
986
945
  continue;
987
946
  }
988
947
  allowedIds.add(id);
989
- const after = stepped(view, event, genesis, saw, byIdMap, allowedIds);
990
- const scope = reductionOf(event, view);
991
- if (scope)
992
- scopes.set(id, scope);
993
- const lost = affected(event).filter((did) => isMember(view, did) && !isMember(after, did));
994
- if (lost.length > 0)
995
- lostReaders.set(id, lost);
996
- if (lost.length > 0 && after.keys.length > 0 && event.kind !== 'key')
997
- after.keyDue = true;
998
- afterOf.set(id, after);
948
+ afterOf.set(id, result.after);
949
+ if (result.tookReading)
950
+ tookReading.add(id);
999
951
  // Strikes it is part of, with the allowed changes before it.
1000
- if (scope || keyWide(event) || (event.kind === 'invite' && !event.open))
1001
- reductionIds.push(id);
1002
- for (const r of reductionIds)
1003
- if (r !== id && strikesOn(byIdMap.get(r), event))
1004
- (strikes.get(r) ?? strikes.set(r, []).get(r)).push(id);
1005
- if (reductionIds.at(-1) === id)
1006
- for (const other of order) {
1007
- if (other === id)
1008
- break;
1009
- if (allowedIds.has(other) && strikesOn(event, byIdMap.get(other)))
1010
- (strikes.get(id) ?? strikes.set(id, []).get(id)).push(other);
1011
- }
952
+ for (const by of result.reachedBy)
953
+ if (strikesOn(by, event, saw))
954
+ strike(by.id, id);
955
+ const reduction = result.reduction;
956
+ if (!reduction)
957
+ continue;
958
+ taking.set(id, reduction);
959
+ for (const other of order) {
960
+ if (other === id)
961
+ break;
962
+ if (allowedIds.has(other) && strikesOn(reduction, byIdMap.get(other), saw))
963
+ strike(id, other);
964
+ }
1012
965
  }
1013
966
  // A stepping down its key's revoke or fork proof reaches only ends founder status: it strikes
1014
967
  // nothing, and withdraws nothing, as a reduction would.
1015
- const keyWideIds = reductionIds.filter((r) => keyWide(byIdMap.get(r)));
968
+ const back = [...taking.values()].filter(reachesBack);
1016
969
  for (const id of order) {
1017
970
  const event = byIdMap.get(id);
1018
971
  if (event.kind !== 'stepdown' || !allowedIds.has(id))
1019
972
  continue;
1020
- if (keyWideIds.some((r) => reachedBy(byIdMap.get(r), event))) {
973
+ if (back.some((reduction) => reachedBy(reduction, event, saw))) {
1021
974
  strikes.delete(id);
1022
- scopes.delete(id);
975
+ taking.delete(id);
1023
976
  }
1024
977
  }
1025
- const within = validWithin(order, {
1026
- genesis,
1027
- byId: byIdMap,
1028
- saw,
1029
- allowedIds,
1030
- strikes,
1031
- lostReaders,
1032
- defViews,
1033
- });
978
+ const within = validWithin(order, { genesis, byId: byIdMap, saw, allowedIds, strikes, defViews });
1034
979
  const valid = within.valid;
1035
980
  const struck = new Map();
1036
981
  for (const id of order)
1037
982
  if (allowedIds.has(id) && !valid.has(id))
1038
983
  struck.set(id, STRUCK);
1039
- const reductions = new Map();
1040
- const revokes = new Map();
984
+ const taken = new Map();
1041
985
  const forks = new Map();
1042
986
  for (const id of order) {
1043
- if (!valid.has(id))
1044
- continue;
1045
- const event = byIdMap.get(id);
1046
- const scope = scopes.get(id);
1047
- if (scope)
1048
- (reductions.get(scope) ?? reductions.set(scope, []).get(scope)).push(id);
1049
- if (event.kind === 'revoke')
1050
- (revokes.get(event.target) ?? revokes.set(event.target, []).get(event.target)).push({
1051
- event: id,
1052
- root: event.root,
1053
- });
1054
- if (event.kind === 'fork') {
1055
- const line = lineOf(event.writer, event.collection);
1056
- if (event.from < (forks.get(line)?.from ?? Infinity))
1057
- forks.set(line, { event: id, writer: event.writer, collection: event.collection, from: event.from });
1058
- }
987
+ const reduction = valid.has(id) && taking.get(id);
988
+ if (reduction)
989
+ indexReduction(taken, forks, reduction);
1059
990
  }
1060
991
  const named = new Set([...genesis.founders, ...Object.keys(genesis.assigned ?? {})]);
1061
992
  const invites = new Set();
@@ -1065,14 +996,18 @@ export function replayAccess(genesis, events) {
1065
996
  if (event.kind === 'invite')
1066
997
  invites.add(event.inviteKey);
1067
998
  }
1068
- const state = merge(genesis, order.filter((id) => valid.has(id)).map((id) => byIdMap.get(id)), saw, lostReaders, within.defViews);
999
+ const state = merge(genesis, order.filter((id) => valid.has(id)).map((id) => byIdMap.get(id)), saw, within.defViews);
1000
+ // Due: someone lost reading in a valid change the current key had not seen. They may hold it.
1001
+ const keyEvent = state.keys.at(-1)?.event;
1002
+ const sawByKey = keyEvent === undefined ? undefined : saw.get(keyEvent);
1003
+ state.keyDue =
1004
+ keyEvent !== undefined &&
1005
+ order.some((id) => valid.has(id) && tookReading.has(id) && id !== keyEvent && !sawByKey?.has(id));
1069
1006
  // Due, too, when someone who held the current key reads no more, however that came about: two
1070
1007
  // changes together can take reading where neither did alone. Whoever could read as the key was
1071
1008
  // made held it, and so did whoever came to read after, by a change the key had not seen.
1072
- if (state.keys.length > 0 && !state.keyDue) {
1073
- const keyEvent = state.keys.at(-1).event;
1009
+ if (keyEvent !== undefined && !state.keyDue) {
1074
1010
  const atKey = keyEvent === genesis.id ? startState(genesis) : afterOf.get(keyEvent);
1075
- const sawByKey = keyEvent === genesis.id ? null : saw.get(keyEvent);
1076
1011
  const now = readers(state);
1077
1012
  const held = new Set(atKey ? readers(atKey) : []);
1078
1013
  for (const id of order) {
@@ -1092,53 +1027,68 @@ export function replayAccess(genesis, events) {
1092
1027
  waiting,
1093
1028
  order,
1094
1029
  saw,
1095
- ancestry: saw,
1096
1030
  index,
1097
1031
  refused,
1098
1032
  valid,
1099
1033
  struck,
1100
- reductions,
1101
- revokes,
1034
+ taking,
1035
+ taken,
1102
1036
  forks,
1103
1037
  state,
1104
1038
  named,
1105
1039
  invites,
1106
1040
  views: new Map(),
1107
1041
  allowedIds,
1108
- lostReaders,
1109
1042
  defViews,
1110
1043
  validDefViews: within.defViews,
1111
1044
  strikes,
1112
1045
  });
1113
1046
  }
1114
- /** A state with one change on top, and who defined it when it defines a collection */
1115
- function stepped(view, event, genesis, saw, byIdMap, counted) {
1116
- const after = applied(view, event, genesis.id);
1117
- if (event.kind === 'definition' && !event.deleted) {
1118
- const group = [...saw.get(event.id)]
1119
- .filter((other) => counted.has(other) && byIdMap.get(other).key === event.key)
1120
- .map((other) => byIdMap.get(other))
1121
- .concat(event);
1122
- after.definitions.set(event.name, { event: event.id, definedBy: definerOf(event, group, saw) });
1123
- }
1124
- return after;
1047
+ // Revokes and fork proofs are never struck: every allowed one applies.
1048
+ const reachedBy = (reduction, event, saw) => reduction.id !== event.id &&
1049
+ event.kind !== 'revoke' &&
1050
+ event.kind !== 'fork' &&
1051
+ (reachesBack(reduction) ||
1052
+ (!saw.get(event.id).has(reduction.id) && !saw.get(reduction.id).has(event.id))) &&
1053
+ reaches(reduction, { ...event, writer: event.author, collection: ACCESS_KINDS[event.kind].collection });
1054
+ // A stepping down is never struck (`validWithin`): founder status can't be given again. One a
1055
+ // revoke or a fork proof reaches ends founder status and does nothing more.
1056
+ const strikesOn = (reduction, event, saw) => !(reachesBack(reduction) && event.kind === 'stepdown') && reachedBy(reduction, event, saw);
1057
+ /**
1058
+ * One change judged in its own view, as replaying and extending both do: why it is refused, or the
1059
+ * state it leaves, what it takes, whether it took reading, and the reductions before it that reach it.
1060
+ */
1061
+ function step(event, view, r) {
1062
+ const reason = refusal(event, view);
1063
+ if (reason)
1064
+ return reason;
1065
+ const after = applied(view, event, r, r.allowedIds);
1066
+ const reduction = reductionOf(event, view);
1067
+ // Only a removal, an unassignment or a stepping down can take reading, and only from a member.
1068
+ const reach = reduction?.reach;
1069
+ return {
1070
+ after,
1071
+ reduction,
1072
+ tookReading: reach?.kind === 'account' && !isMember(after, reach.root),
1073
+ reachedBy: [...r.taking.values()].filter((reduction) => reachedBy(reduction, event, r.saw)),
1074
+ };
1125
1075
  }
1126
1076
  /**
1127
1077
  * Each change's view over the changes `counts` keeps among what it saw. Along a chain, the one
1128
1078
  * before's view, with it on top when kept; where branches meet, a merge. Asked in order. A role
1129
1079
  * definition's view is kept in `defViews`, where its grants are judged.
1130
1080
  */
1131
- function viewsAlong(byIdMap, saw, genesis, counts, afterOf, lostReaders, defViews) {
1081
+ function viewsAlong({ genesis, saw, byId }, counts, afterOf, defViews) {
1132
1082
  const viewOf = new Map();
1133
1083
  return (event) => {
1134
- const parents = [...new Set(event.seen.filter((parent) => parent !== genesis.id))];
1084
+ const parents = parentsOf(event, genesis.id);
1135
1085
  let view;
1136
1086
  if (parents.length === 0)
1137
1087
  view = startState(genesis);
1138
1088
  else if (parents.length === 1)
1139
1089
  view = counts(parents[0]) ? afterOf.get(parents[0]) : viewOf.get(parents[0]);
1140
1090
  else
1141
- view = merge(genesis, [...saw.get(event.id)].filter(counts).map((other) => byIdMap.get(other)), saw, lostReaders, defViews);
1091
+ view = merge(genesis, [...saw.get(event.id)].filter(counts).map((other) => byId.get(other)), saw, defViews);
1142
1092
  viewOf.set(event.id, view);
1143
1093
  if (event.kind === 'role')
1144
1094
  defViews.set(event.id, view);
@@ -1146,22 +1096,42 @@ function viewsAlong(byIdMap, saw, genesis, counts, afterOf, lostReaders, defView
1146
1096
  };
1147
1097
  }
1148
1098
  /**
1149
- * The valid changes among `cut` (in replay order, closed under what they saw), and the views
1150
- * their role definitions are judged in. First the strikes: an allowed change is struck by a valid
1151
- * one from another component of the strikes inside the cut. Then, ancestors first, a change stays
1152
- * valid only if the valid changes it saw still give its author the power: so a struck grant gives
1153
- * none, to anything downstream, and a struck definition is dropped before anything resting on it
1154
- * is judged.
1099
+ * The valid changes among `cut` (in replay order, closed under what they saw), and the views their
1100
+ * role definitions are judged in. First the strikes: an allowed change is struck by an unstruck one
1101
+ * from another component of the strikes inside the cut, visited strikers first. Then, ancestors
1102
+ * first, a change stays valid only if the valid changes it saw still give its author the power.
1155
1103
  */
1156
1104
  function validWithin(cut, r) {
1157
- // A stepping down is never struck: founder status can't be given back.
1158
- const invalid = invalidWithin(cut, r.allowedIds, r.strikes, (id) => r.byId.get(id)?.kind === 'stepdown');
1159
- const valid = new Set(cut.filter((id) => !invalid.has(id)));
1105
+ const inCut = new Set(cut);
1106
+ const out = new Set(cut.filter((id) => !r.allowedIds.has(id)));
1107
+ const edges = new Map();
1108
+ for (const [from, targets] of r.strikes) {
1109
+ if (!inCut.has(from) || !r.allowedIds.has(from))
1110
+ continue;
1111
+ const kept = targets.filter((to) => inCut.has(to) && r.allowedIds.has(to));
1112
+ if (kept.length > 0)
1113
+ edges.set(from, kept);
1114
+ }
1115
+ if (edges.size > 0) {
1116
+ const nodes = [...new Set([...edges.keys(), ...[...edges.values()].flat()])].sort();
1117
+ const { of, list } = componentsOf(nodes, edges);
1118
+ const strikers = new Map();
1119
+ for (const [from, targets] of edges)
1120
+ for (const to of targets)
1121
+ if (of.get(from) !== of.get(to))
1122
+ (strikers.get(to) ?? strikers.set(to, []).get(to)).push(from);
1123
+ // A stepping down is never struck: founder status can't be given back.
1124
+ for (const members of list)
1125
+ for (const id of members)
1126
+ if (r.byId.get(id)?.kind !== 'stepdown' && (strikers.get(id) ?? []).some((from) => !out.has(from)))
1127
+ out.add(id);
1128
+ }
1129
+ const valid = new Set(cut.filter((id) => !out.has(id)));
1160
1130
  if (cut.every((id) => !r.allowedIds.has(id) || valid.has(id)))
1161
1131
  return { valid, defViews: r.defViews };
1162
1132
  const afterOf = new Map();
1163
1133
  const defViews = new Map();
1164
- const viewOf = viewsAlong(r.byId, r.saw, r.genesis, (id) => valid.has(id), afterOf, r.lostReaders, defViews);
1134
+ const viewOf = viewsAlong(r, (id) => valid.has(id), afterOf, defViews);
1165
1135
  for (const id of cut) {
1166
1136
  const event = r.byId.get(id);
1167
1137
  const view = viewOf(event);
@@ -1171,48 +1141,14 @@ function validWithin(cut, r) {
1171
1141
  valid.delete(id);
1172
1142
  continue;
1173
1143
  }
1174
- afterOf.set(id, stepped(view, event, r.genesis, r.saw, r.byId, valid));
1144
+ afterOf.set(id, applied(view, event, r, valid));
1175
1145
  }
1176
1146
  return { valid, defViews };
1177
1147
  }
1178
1148
  /**
1179
- * The allowed changes among `cut` that are not valid there: struck by a
1180
- * valid change in it, components of the strikes inside it visited so that
1181
- * strikes come before what they strike, and strikes within one component not
1182
- * counting. With refused changes, what a view leaves out.
1183
- */
1184
- function invalidWithin(cut, allowedIds, strikes, immune) {
1185
- const inCut = new Set(cut);
1186
- const out = new Set([...inCut].filter((id) => !allowedIds.has(id)));
1187
- const edges = new Map();
1188
- for (const [from, targets] of strikes) {
1189
- if (!inCut.has(from) || !allowedIds.has(from))
1190
- continue;
1191
- const kept = targets.filter((to) => inCut.has(to) && allowedIds.has(to));
1192
- if (kept.length > 0)
1193
- edges.set(from, kept);
1194
- }
1195
- if (edges.size === 0)
1196
- return out;
1197
- const nodes = [...new Set([...edges.keys(), ...[...edges.values()].flat()])].sort();
1198
- const { of, list } = componentsOf(nodes, edges);
1199
- const strikers = new Map();
1200
- for (const [from, targets] of edges)
1201
- for (const to of targets)
1202
- if (of.get(from) !== of.get(to))
1203
- (strikers.get(to) ?? strikers.set(to, []).get(to)).push(from);
1204
- for (const members of list)
1205
- for (const id of members)
1206
- if (!immune(id) && (strikers.get(id) ?? []).some((from) => !out.has(from)))
1207
- out.add(id);
1208
- return out;
1209
- }
1210
- /**
1211
- * The replay with one more change that saw every change placed, or null for
1212
- * any other: then only replaying whole can say. Such a change can't be struck
1213
- * by a reduction (it saw every one) and strikes nothing (it saw everything),
1214
- * so it is valid exactly when it is allowed and no revoke or fork reaches it,
1215
- * its view is every allowed change, and it is the latest on its record.
1149
+ * The replay with one more change that saw every change placed, or null for any other. Such a change
1150
+ * strikes nothing and only a revoke or fork can strike it; its view is every allowed change, and it
1151
+ * is the latest on its record.
1216
1152
  */
1217
1153
  function extended(r, event) {
1218
1154
  const { genesis } = r;
@@ -1223,25 +1159,15 @@ function extended(r, event) {
1223
1159
  // whether a key change is due rests on everyone who held the key. Both are worked out whole.
1224
1160
  if (r.struck.size > 0 || r.state.keyDue)
1225
1161
  return null;
1226
- const parents = [...new Set(event.seen.filter((parent) => parent !== genesis.id))];
1227
- if (parents.some((parent) => !r.ancestry.has(parent)))
1228
- return null;
1229
- let prefix = 0;
1230
- for (const parent of parents)
1231
- prefix = Math.max(prefix, r.ancestry.get(parent).prefix);
1232
- const extra = new Set();
1233
- for (const parent of parents)
1234
- for (const n of [...r.ancestry.get(parent).extra, r.index.get(parent)])
1235
- if (n >= prefix)
1236
- extra.add(n);
1237
- while (extra.delete(prefix))
1238
- prefix++;
1239
- if (prefix !== r.order.length || extra.size > 0 || r.waiting.size > 0)
1162
+ const parents = parentsOf(event, genesis.id);
1163
+ if (parents.some((parent) => !r.saw.has(parent)))
1240
1164
  return null;
1241
1165
  const order = [...r.order, event.id];
1242
1166
  const index = new Map(r.index).set(event.id, r.order.length);
1243
- const mine = seenOf(prefix, extra, order, index);
1244
- const ancestry = new Map(r.ancestry).set(event.id, mine);
1167
+ const mine = seenOf(parents, r.saw, order, index);
1168
+ if (mine.prefix !== r.order.length || mine.extra.size > 0 || r.waiting.size > 0)
1169
+ return null;
1170
+ const saw = new Map(r.saw).set(event.id, mine);
1245
1171
  const byIdMap = new Map(r.byId).set(event.id, event);
1246
1172
  const named = new Set(r.named);
1247
1173
  if (event.kind === 'assign' && event.assigned)
@@ -1258,68 +1184,48 @@ function extended(r, event) {
1258
1184
  byId: byIdMap,
1259
1185
  waiting: r.waiting,
1260
1186
  order,
1261
- saw: ancestry,
1262
- ancestry,
1187
+ saw,
1263
1188
  index,
1264
1189
  named,
1265
1190
  invites,
1266
1191
  views: new Map(),
1267
1192
  defViews,
1268
1193
  };
1269
- const reason = refusal(event, view);
1270
- if (reason)
1271
- return { ...r, ...base, refused: new Map(r.refused).set(event.id, reason) };
1272
- const after = applied(view, event, genesis.id);
1273
- const scope = reductionOf(event, view);
1274
- const lost = affected(event).filter((did) => isMember(view, did) && !isMember(after, did));
1275
- // Valid, besides allowed: no revoke or fork of its key reaches it, whatever it saw.
1276
- const uncovered = (reduction) => (r.byId.get(reduction).cutoff.get(event.author)?.get(KIND_COLLECTION[event.kind]) ?? -1) <
1277
- (event.line ?? 0);
1278
- const fork = r.forks.get(lineOf(event.author, KIND_COLLECTION[event.kind]));
1279
- const strikers = [
1280
- ...(r.revokes.get(event.author) ?? [])
1281
- .filter((revoke) => revoke.root === event.root && uncovered(revoke.event))
1282
- .map((revoke) => revoke.event),
1283
- ...(fork && (event.line ?? 0) >= fork.from ? [fork.event] : []),
1284
- ];
1194
+ const result = step(event, view, { ...r, saw, byId: byIdMap });
1195
+ if (typeof result === 'string')
1196
+ return { ...r, ...base, refused: new Map(r.refused).set(event.id, result) };
1197
+ // Valid, besides allowed, when no revoke or fork of its key reaches it, whatever it saw: no other
1198
+ // reduction can, since it saw them all.
1199
+ const strikers = result.reachedBy;
1285
1200
  // A stepping down its key's revoke reaches ends founder status and does nothing else: only a whole replay says.
1286
1201
  if (strikers.length > 0 && event.kind === 'stepdown')
1287
1202
  return null;
1203
+ const taking = result.reduction ? new Map(r.taking).set(event.id, result.reduction) : r.taking;
1204
+ const allowedIds = new Set(r.allowedIds).add(event.id);
1288
1205
  if (strikers.length > 0) {
1289
1206
  const strikes = new Map(r.strikes);
1290
- for (const by of strikers)
1291
- strikes.set(by, [...(strikes.get(by) ?? []), event.id]);
1292
- return {
1293
- ...r,
1294
- ...base,
1295
- strikes,
1296
- struck: new Map(r.struck).set(event.id, STRUCK),
1297
- allowedIds: new Set(r.allowedIds).add(event.id),
1298
- lostReaders: lost.length > 0 ? new Map(r.lostReaders).set(event.id, lost) : r.lostReaders,
1299
- };
1300
- }
1301
- const state = applied(r.state, event, genesis.id);
1302
- if (event.kind === 'definition' && !event.deleted) {
1303
- // Who defined it, by the same rule a merge uses: among the valid changes, which here are the allowed ones.
1304
- const group = [...r.byId.values()]
1305
- .filter((other) => other.key === event.key && r.valid.has(other.id))
1306
- .concat(event);
1307
- state.definitions.set(event.name, { event: event.id, definedBy: definerOf(event, group, ancestry) });
1207
+ for (const { id } of strikers)
1208
+ strikes.set(id, [...(strikes.get(id) ?? []), event.id]);
1209
+ return { ...r, ...base, strikes, struck: new Map(r.struck).set(event.id, STRUCK), allowedIds, taking };
1308
1210
  }
1309
- if (lost.length > 0 && state.keys.length > 0 && event.kind !== 'key')
1310
- state.keyDue = true;
1311
- const reductions = new Map(r.reductions);
1312
- if (scope)
1313
- reductions.set(scope, [...(reductions.get(scope) ?? []), event.id]);
1211
+ // Its view is every allowed change, and those are the valid ones: it is the state with it on top.
1212
+ const state = result.after;
1213
+ // Due once it takes reading from someone: the key saw everything else, and no one else lost it.
1214
+ state.keyDue = result.tookReading && state.keys.length > 0 && event.kind !== 'key';
1215
+ const taken = new Map(r.taken);
1216
+ const forks = new Map(r.forks);
1217
+ if (result.reduction)
1218
+ indexReduction(taken, forks, result.reduction);
1314
1219
  return {
1315
1220
  ...r,
1316
1221
  ...base,
1317
1222
  validDefViews,
1318
1223
  valid: new Set(r.valid).add(event.id),
1319
- allowedIds: new Set(r.allowedIds).add(event.id),
1320
- lostReaders: lost.length > 0 ? new Map(r.lostReaders).set(event.id, lost) : r.lostReaders,
1224
+ allowedIds,
1225
+ taking,
1321
1226
  state,
1322
- reductions,
1227
+ taken,
1228
+ forks,
1323
1229
  };
1324
1230
  }
1325
1231
  function historyOf(r) {
@@ -1339,25 +1245,20 @@ function historyOf(r) {
1339
1245
  };
1340
1246
  const inOrder = (ids) => [...ids].sort((a, b) => r.index.get(a) - r.index.get(b));
1341
1247
  const idsKey = (ids) => [...new Set(ids)].sort().join(',');
1342
- /** The merge of what `ids` name and saw, counting those of them in `among` */
1343
- const stateOf = (ids, among) => merge(genesis, inOrder(cutOf(ids))
1344
- .filter((id) => among.valid.has(id))
1345
- .map((id) => r.byId.get(id)), r.saw, r.lostReaders, among.defViews);
1346
- const cached = (key, make) => {
1248
+ /** The merge of what `ids` name and saw, counting the changes valid in all, or among what `within` names and saw */
1249
+ const at = (ids, within) => {
1250
+ const key = `${idsKey(ids)}|${within ? idsKey(within) : '*'}`;
1347
1251
  const known = r.views.get(key);
1348
1252
  if (known)
1349
1253
  return known;
1350
- const view = make();
1254
+ const among = within
1255
+ ? validWithin(inOrder(cutOf([...ids, ...within])), r)
1256
+ : { valid: r.valid, defViews: r.validDefViews };
1257
+ const counted = inOrder(cutOf(ids)).flatMap((id) => (among.valid.has(id) ? [r.byId.get(id)] : []));
1258
+ const view = merge(genesis, counted, r.saw, among.defViews);
1351
1259
  r.views.set(key, view);
1352
1260
  return view;
1353
1261
  };
1354
- /** Valid in the whole history, or among what `within` names and saw */
1355
- const at = (ids, within) => cached(`at:${idsKey(ids)}|${within ? idsKey(within) : '*'}`, () => stateOf(ids, within
1356
- ? validWithin(inOrder(cutOf([...ids, ...within])), r)
1357
- : { valid: r.valid, defViews: r.validDefViews }));
1358
- /** Valid among what `ids` name and saw alone */
1359
- const seenAs = (ids) => cached(`seen:${idsKey(ids)}`, () => stateOf(ids, validWithin(inOrder(cutOf(ids)), r)));
1360
- const index = new Map(r.order.map((id, i) => [id, i]));
1361
1262
  const changesState = (id) => !['revoke', 'fork'].includes(r.byId.get(id).kind);
1362
1263
  let heads = null;
1363
1264
  const history = Object.freeze({
@@ -1366,7 +1267,7 @@ function historyOf(r) {
1366
1267
  if (r.waiting.has(id))
1367
1268
  return { status: 'waiting' };
1368
1269
  if (r.valid.has(id))
1369
- return { status: 'applied', index: index.get(id) };
1270
+ return { status: 'applied', index: r.index.get(id) };
1370
1271
  const reason = r.refused.get(id) ?? r.struck.get(id);
1371
1272
  return reason ? { status: 'dropped', reason } : null;
1372
1273
  },
@@ -1381,7 +1282,7 @@ function historyOf(r) {
1381
1282
  const all = history.heads();
1382
1283
  if (all.length <= max)
1383
1284
  return all;
1384
- const recent = [...all].sort((a, b) => index.get(b) - index.get(a));
1285
+ const recent = [...all].sort((a, b) => r.index.get(b) - r.index.get(a));
1385
1286
  const sawOrIs = (head, id) => head === id || r.saw.get(head).has(id);
1386
1287
  const chosen = [];
1387
1288
  for (const key of keys) {
@@ -1402,35 +1303,29 @@ function historyOf(r) {
1402
1303
  return seen(ids) && (!within || seen(within)) ? at(ids, within) : null;
1403
1304
  },
1404
1305
  seenAs(ids) {
1405
- return seen(ids) ? seenAs(ids) : null;
1306
+ return seen(ids) ? at(ids, ids) : null;
1406
1307
  },
1407
1308
  judge(record, needs, within) {
1408
1309
  if (!seen(record.seen) || (within && !seen(within)))
1409
1310
  return { ok: false, reason: 'Access changes it depends on have not arrived yet', later: true };
1410
1311
  // For a cited version, only what the citer had seen can take it away (02 §7.6).
1411
1312
  const known = within ? cutOf(within) : null;
1412
- const counts = (event) => !known || known.has(event);
1413
- const covered = (event) => record.writer !== undefined &&
1414
- record.collection !== undefined &&
1415
- record.line !== undefined &&
1416
- (r.byId.get(event).cutoff.get(record.writer)?.get(record.collection) ?? -1) >= record.line;
1417
- if (record.writer !== undefined) {
1418
- for (const revoke of r.revokes.get(record.writer) ?? [])
1419
- if (revoke.root === record.root && counts(revoke.event) && !covered(revoke.event))
1420
- return { ok: false, reason: 'The key that signed it was revoked', withdrawn: true };
1421
- }
1313
+ const takes = (reduction) => (!known || known.has(reduction.id)) && reaches(reduction, record);
1314
+ const signed = record.writer === undefined ? [] : (r.taken.get(record.writer) ?? []);
1315
+ if (signed.some((reduction) => reduction.reach.kind === 'key' && takes(reduction)))
1316
+ return { ok: false, reason: 'The key that signed it was revoked', withdrawn: true };
1422
1317
  const fork = record.writer === undefined || record.collection === undefined
1423
1318
  ? undefined
1424
1319
  : r.forks.get(lineOf(record.writer, record.collection));
1425
- if (fork && (record.line ?? 0) >= fork.from && counts(fork.event))
1320
+ if (fork && takes(fork))
1426
1321
  return { ok: false, reason: 'Its writer’s log forked at or before it', withdrawn: true };
1427
- if (!needs(seenAs(record.seen)))
1322
+ if (!needs(at(record.seen, record.seen)))
1428
1323
  return { ok: false, reason: 'Its author was not allowed to, as of what it had seen' };
1429
1324
  // What it had not seen of its author's standing: a removal or an unassignment takes everything.
1430
1325
  const cut = cutOf(record.seen);
1431
- for (const reduction of r.reductions.get(record.root) ?? [])
1432
- if (!cut.has(reduction) && counts(reduction) && !covered(reduction))
1433
- return { ok: false, reason: "Its author's access was taken away", withdrawn: true };
1326
+ const reduced = (reduction) => reduction.reach.kind === 'account' && !cut.has(reduction.id) && takes(reduction);
1327
+ if ((r.taken.get(record.root) ?? []).some(reduced))
1328
+ return { ok: false, reason: "Its author's access was taken away", withdrawn: true };
1434
1329
  // What it saw counts only as far as it stands: a struck change gives nothing, even cited.
1435
1330
  if (!needs(at(record.seen, within)))
1436
1331
  return {
@@ -1440,12 +1335,18 @@ function historyOf(r) {
1440
1335
  };
1441
1336
  return { ok: true };
1442
1337
  },
1443
- revoked: (key, root) => (r.revokes.get(key) ?? []).filter((revoke) => revoke.root === root).map((revoke) => revoke.event),
1338
+ revoked: (key, root) => (r.taken.get(key) ?? [])
1339
+ .filter(({ reach }) => reach.kind === 'key' && reach.root === root)
1340
+ .map((revoke) => revoke.id),
1444
1341
  forked: (writer, collection) => {
1445
1342
  const fork = r.forks.get(lineOf(writer, collection));
1446
- return fork ? { event: fork.event, from: fork.from } : null;
1343
+ return fork ? { event: fork.id, from: fork.reach.from } : null;
1447
1344
  },
1448
- forks: () => [...r.forks.values()].map(({ writer, collection, from }) => ({ writer, collection, from })),
1345
+ forks: () => [...r.forks.values()].map(({ reach }) => ({
1346
+ writer: reach.key,
1347
+ collection: reach.collection,
1348
+ from: reach.from,
1349
+ })),
1449
1350
  named: (did) => r.named.has(did),
1450
1351
  knownInvite: (key) => r.invites.has(key),
1451
1352
  extend(event) {