@serfab/cadre-core 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +255 -255
  2. package/dist/announce-addrs.d.ts +49 -0
  3. package/dist/announce-addrs.js +78 -0
  4. package/dist/announce-addrs.js.map +1 -0
  5. package/dist/cadre-node.d.ts +484 -58
  6. package/dist/cadre-node.js +953 -182
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/control-cohort.d.ts +26 -0
  9. package/dist/control-cohort.js +26 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +222 -125
  12. package/dist/control-database.js +356 -266
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +8 -7
  15. package/dist/control-formation-recorder.js +8 -7
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +103 -0
  18. package/dist/control-read-retry.js +145 -0
  19. package/dist/control-read-retry.js.map +1 -0
  20. package/dist/control-retry.d.ts +101 -0
  21. package/dist/control-retry.js +108 -0
  22. package/dist/control-retry.js.map +1 -0
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +805 -774
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +65 -31
  27. package/dist/control-write-retry.js +33 -103
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +17 -15
  30. package/dist/delegate-admission.js +17 -15
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/index.d.ts +7 -5
  33. package/dist/index.js +18 -9
  34. package/dist/index.js.map +1 -1
  35. package/dist/membership-connection-gater.d.ts +211 -25
  36. package/dist/membership-connection-gater.js +309 -29
  37. package/dist/membership-connection-gater.js.map +1 -1
  38. package/dist/peer-addr-book.d.ts +92 -0
  39. package/dist/peer-addr-book.js +220 -0
  40. package/dist/peer-addr-book.js.map +1 -0
  41. package/dist/peer-record.d.ts +26 -0
  42. package/dist/peer-record.js +32 -0
  43. package/dist/peer-record.js.map +1 -1
  44. package/dist/relay-addrs.d.ts +76 -26
  45. package/dist/relay-addrs.js +115 -27
  46. package/dist/relay-addrs.js.map +1 -1
  47. package/dist/relay-reservation.d.ts +20 -15
  48. package/dist/relay-reservation.js +18 -14
  49. package/dist/relay-reservation.js.map +1 -1
  50. package/dist/seed-bootstrap.d.ts +7 -0
  51. package/dist/seed-bootstrap.js +15 -13
  52. package/dist/seed-bootstrap.js.map +1 -1
  53. package/dist/strand-addr-protocol.js +16 -0
  54. package/dist/strand-addr-protocol.js.map +1 -1
  55. package/dist/strand-backfill.js +13 -4
  56. package/dist/strand-backfill.js.map +1 -1
  57. package/dist/strand-cohort.d.ts +4 -37
  58. package/dist/strand-cohort.js +4 -15
  59. package/dist/strand-cohort.js.map +1 -1
  60. package/dist/strand-database.d.ts +11 -16
  61. package/dist/strand-database.js +19 -7
  62. package/dist/strand-database.js.map +1 -1
  63. package/dist/strand-formation-manager.d.ts +18 -17
  64. package/dist/strand-formation-manager.js +25 -27
  65. package/dist/strand-formation-manager.js.map +1 -1
  66. package/dist/strand-formation-protocol.d.ts +7 -7
  67. package/dist/strand-formation-protocol.js +8 -8
  68. package/dist/strand-formation-protocol.js.map +1 -1
  69. package/dist/strand-instance-manager.d.ts +53 -21
  70. package/dist/strand-instance-manager.js +128 -37
  71. package/dist/strand-instance-manager.js.map +1 -1
  72. package/dist/strand-membership-writer.d.ts +113 -19
  73. package/dist/strand-membership-writer.js +219 -51
  74. package/dist/strand-membership-writer.js.map +1 -1
  75. package/dist/strand-solicitation.d.ts +3 -3
  76. package/dist/strand-solicitation.js +4 -5
  77. package/dist/strand-solicitation.js.map +1 -1
  78. package/dist/strand-wake-protocol.d.ts +47 -2
  79. package/dist/strand-wake-protocol.js +76 -6
  80. package/dist/strand-wake-protocol.js.map +1 -1
  81. package/dist/types.d.ts +107 -54
  82. package/dist/types.js.map +1 -1
  83. package/package.json +8 -7
  84. package/src/announce-addrs.ts +93 -0
  85. package/src/arachnode-stub.ts +159 -159
  86. package/src/bootstrap-peer-store-file.ts +44 -44
  87. package/src/bootstrap-peer-store.ts +172 -172
  88. package/src/cadre-node.ts +1026 -194
  89. package/src/canonical-json.ts +30 -30
  90. package/src/control-authorization.ts +114 -114
  91. package/src/control-cohort.ts +130 -103
  92. package/src/control-database.ts +376 -298
  93. package/src/control-formation-recorder.ts +305 -304
  94. package/src/control-read-retry.ts +167 -0
  95. package/src/control-retry.ts +190 -0
  96. package/src/control-schema.ts +817 -786
  97. package/src/control-stream.ts +205 -205
  98. package/src/control-write-retry.ts +383 -473
  99. package/src/delegate-admission.ts +304 -302
  100. package/src/device-token.ts +94 -94
  101. package/src/diagnostics/connection-path.ts +277 -277
  102. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  103. package/src/ed25519-key.ts +134 -134
  104. package/src/enrollment.ts +199 -199
  105. package/src/file-durable-slot.ts +61 -61
  106. package/src/formation-approval.ts +604 -604
  107. package/src/fs-atomic.ts +107 -107
  108. package/src/hibernation-manager.ts +437 -437
  109. package/src/identity-key.ts +109 -109
  110. package/src/index.ts +435 -406
  111. package/src/key-store-file.ts +132 -132
  112. package/src/key-store.ts +99 -99
  113. package/src/membership-connection-gater.ts +368 -39
  114. package/src/node-local-snapshot.ts +260 -260
  115. package/src/peer-addr-book.ts +250 -0
  116. package/src/peer-authorization.ts +259 -259
  117. package/src/peer-record.ts +197 -164
  118. package/src/push-credentials.ts +84 -84
  119. package/src/push-node.ts +64 -64
  120. package/src/push-notifier-apns.ts +247 -247
  121. package/src/push-notifier-fcm.ts +220 -220
  122. package/src/push-notifier-shared.ts +28 -28
  123. package/src/push-notifier.ts +52 -52
  124. package/src/relay-addrs.ts +134 -27
  125. package/src/relay-reservation.ts +22 -17
  126. package/src/seed-bootstrap.ts +15 -15
  127. package/src/seed-trust-policy.ts +140 -140
  128. package/src/strand-addr-protocol.ts +458 -441
  129. package/src/strand-backfill.ts +28 -5
  130. package/src/strand-cohort.ts +38 -77
  131. package/src/strand-database.ts +202 -204
  132. package/src/strand-formation-manager.ts +26 -28
  133. package/src/strand-formation-protocol.ts +692 -692
  134. package/src/strand-instance-manager.ts +636 -553
  135. package/src/strand-member-key.ts +39 -39
  136. package/src/strand-member-registry.ts +182 -182
  137. package/src/strand-membership-writer.ts +1627 -1430
  138. package/src/strand-solicitation.ts +471 -472
  139. package/src/strand-transport-key.ts +58 -58
  140. package/src/strand-wake-payload.ts +32 -32
  141. package/src/strand-wake-protocol.ts +400 -314
  142. package/src/strand-watcher.ts +314 -314
  143. package/src/trusted-owner-store-file.ts +41 -41
  144. package/src/trusted-owner-store.ts +171 -171
  145. package/src/types.ts +1354 -1303
@@ -1,260 +1,260 @@
1
- /**
2
- * Shared machinery for the node's **node-local** records — the small,
3
- * NEVER-replicated, per-party sets a node keeps for itself and never sources
4
- * from shared group state:
5
- *
6
- * - the trusted-owner anchor (`trusted-owner-store.ts`),
7
- * - the cold-start bootstrap-peer store (`bootstrap-peer-store.ts`).
8
- *
9
- * Both are the same mechanism with a different payload: a
10
- * `{ version, partyId, <entries> }` envelope, snapshot-written whole on every
11
- * change, loaded under one fail-safe-but-not-fail-silent policy. The only part
12
- * that differs per platform is WHERE the bytes are kept — Node writes a file,
13
- * a browser writes IndexedDB, React Native writes SecureStore or its LevelDB
14
- * KV, NativeScript writes SQLite. That difference is the whole of
15
- * {@link DurableSlot}, which the embedding app supplies; everything else lives
16
- * here.
17
- *
18
- * This module is cross-platform (no `node:` imports), so it is safe in the
19
- * package's default entry — the Node-only `FileDurableSlot`
20
- * (`file-durable-slot.ts`) is what stays behind the `*-store-file` subpaths.
21
- */
22
- import debug from 'debug';
23
-
24
- const log = debug('sereus:cadre:node-local-snapshot');
25
-
26
- /**
27
- * A single durable text slot, supplied by the embedding app. The only
28
- * platform-specific part of a persistent node-local store.
29
- */
30
- export interface DurableSlot {
31
- /**
32
- * The slot's persisted text, or `undefined` when it was never written.
33
- *
34
- * MUST throw (not return `undefined`) when the slot exists but cannot be
35
- * read. That distinction is load-bearing: `undefined` means "cold start,
36
- * nothing was ever here", and callers snapshot-write the whole record, so a
37
- * failed read reported as `undefined` silently converts a recoverable error
38
- * (permissions, a blocked database upgrade, an I/O fault) into destruction
39
- * of a still-intact record on the next save.
40
- */
41
- load(): Promise<string | undefined>;
42
- /**
43
- * Durably replace the slot's text. Callers snapshot-write the whole record,
44
- * so an implementation never needs to merge.
45
- */
46
- save(text: string): Promise<void>;
47
- }
48
-
49
- /** Envelope version. Guards future migrations; an unknown version loads empty. */
50
- const ENVELOPE_VERSION = 1;
51
-
52
- /**
53
- * What one unusable entry means for its siblings — the single intentional
54
- * difference between the two records:
55
- *
56
- * - `'discard-all'` (the trusted-owner anchor): a record that cannot be read
57
- * in full is not an anchor. Trusting a *subset* of the keys a file claims is
58
- * a silent, security-relevant downgrade, so the whole record is discarded
59
- * and the node trusts no one until re-seeded out of band.
60
- * - `'drop-entry'` (the bootstrap-peer store): the record is a best-effort
61
- * retry list and nothing in it is trust-bearing, so one junk entry must not
62
- * discard a stranded node's only remaining way back into its party.
63
- */
64
- export type UnusableEntryPolicy = 'discard-all' | 'drop-entry';
65
-
66
- /** What a particular node-local record persists, and how it validates it. */
67
- export interface NodeLocalSnapshotSpec<E> {
68
- /** Human name of the record, used in load errors and logs. */
69
- readonly label: string;
70
- /** Envelope property holding the `key -> entry` record (`owners`, `peers`). */
71
- readonly payloadKey: string;
72
- /** See {@link UnusableEntryPolicy}. */
73
- readonly unusableEntry: UnusableEntryPolicy;
74
- /**
75
- * Validate one persisted entry, returning the value to hold in memory
76
- * (copied, so later mutation of the parsed JSON cannot reach it) or
77
- * `undefined` when the entry is unusable.
78
- */
79
- readonly acceptEntry: (key: string, entry: unknown) => E | undefined;
80
- }
81
-
82
- /**
83
- * A loaded node-local record over a {@link DurableSlot}: an in-memory
84
- * `key -> entry` map plus a serialised full-snapshot write chain.
85
- *
86
- * NOTE: writes are serialised in-process only. Two processes (or two browser
87
- * tabs) sharing ONE slot for ONE party would each snapshot-write their own
88
- * view, so the loser's entries are dropped. Fine for every backend today —
89
- * each node gets its own directory / origin database — but a single slot
90
- * backing two concurrent nodes of one party needs a lock or a merge-on-write,
91
- * not a snapshot replace.
92
- */
93
- export class NodeLocalSnapshot<E> {
94
- /**
95
- * Serialises persists: every {@link put} snapshot-writes the full entry set,
96
- * so chaining writes keeps them ordered and the last landed snapshot
97
- * complete.
98
- */
99
- private writeChain: Promise<void> = Promise.resolve();
100
-
101
- private constructor(
102
- private readonly slot: DurableSlot,
103
- readonly partyId: string,
104
- private readonly spec: NodeLocalSnapshotSpec<E>,
105
- private readonly entries: Map<string, E>
106
- ) {}
107
-
108
- /**
109
- * Load (or cold-start) the party's record from `slot`. Failure policy, per
110
- * the trust model of the anchor this was first written for: only a real,
111
- * well-formed, matching-party record yields entries.
112
- *
113
- * A *decidable* non-record — slot never written, unparsable JSON, unknown
114
- * envelope shape, `partyId` mismatch (a slot reused for a different party
115
- * must not leak into this one) — yields an EMPTY record, the safe direction:
116
- * the node holds nothing until it is re-seeded, rather than acting on stale
117
- * or foreign state.
118
- *
119
- * A slot that is *present but unreadable* ({@link DurableSlot.load} threw)
120
- * is NOT decidable and **throws** instead — mirroring `FileKeyStore.get`.
121
- * Loading empty there would both hide a real misconfiguration and let the
122
- * next {@link put} snapshot-write silently destroy a still-intact record.
123
- */
124
- static async open<E>(
125
- slot: DurableSlot,
126
- partyId: string,
127
- spec: NodeLocalSnapshotSpec<E>
128
- ): Promise<NodeLocalSnapshot<E>> {
129
- return new NodeLocalSnapshot(slot, partyId, spec, await loadEntries(slot, partyId, spec));
130
- }
131
-
132
- has(key: string): boolean {
133
- return this.entries.has(key);
134
- }
135
-
136
- /** Fresh copy of the keys — a snapshot decoupled from later {@link put} calls. */
137
- keySnapshot(): Set<string> {
138
- return new Set(this.entries.keys());
139
- }
140
-
141
- /**
142
- * Fresh copy of the `key -> entry` map — a snapshot decoupled from later
143
- * {@link put} calls. The entries themselves need no copy: {@link put}
144
- * REPLACES an entry rather than mutating it in place.
145
- */
146
- entrySnapshot(): Map<string, E> {
147
- return new Map(this.entries);
148
- }
149
-
150
- /**
151
- * Add or replace an entry: the in-memory map updates SYNCHRONOUSLY (so a
152
- * synchronous caller may consult the store the moment this returns), then
153
- * the full snapshot is persisted. A persist failure rejects the returned
154
- * promise but leaves the entry in memory — this session's decision stands,
155
- * and any later successful {@link put} re-lands the complete set.
156
- */
157
- put(key: string, entry: E): Promise<void> {
158
- this.entries.set(key, entry);
159
- const persist = this.writeChain.then(() => this.persistSnapshot());
160
- // The chain itself must survive a failed persist (the next put retries the
161
- // full snapshot); the caller still observes the rejection via `persist`.
162
- this.writeChain = persist.catch((error) => {
163
- log('%s: persist failed for party %s: %o', this.spec.label, this.partyId, error);
164
- });
165
- return persist;
166
- }
167
-
168
- private async persistSnapshot(): Promise<void> {
169
- const envelope: Record<string, unknown> = {
170
- version: ENVELOPE_VERSION,
171
- partyId: this.partyId,
172
- [this.spec.payloadKey]: Object.fromEntries(this.entries),
173
- };
174
- await this.slot.save(JSON.stringify(envelope, null, '\t'));
175
- }
176
- }
177
-
178
- /** Read + validate the slot's text into the initial entry map (see {@link NodeLocalSnapshot.open}). */
179
- async function loadEntries<E>(
180
- slot: DurableSlot,
181
- partyId: string,
182
- spec: NodeLocalSnapshotSpec<E>
183
- ): Promise<Map<string, E>> {
184
- const entries = new Map<string, E>();
185
- let text: string | undefined;
186
- try {
187
- text = await slot.load();
188
- } catch (error) {
189
- // Present but unreadable: the one non-decidable case, and the one that must
190
- // not cold-start empty (see NodeLocalSnapshot.open). The slot's own text is
191
- // folded into the message, not left only on `cause`: the operator-facing
192
- // print sites (e.g. `cadre-cli start`) log `error.message` alone, and the
193
- // slot is what knows the platform detail worth acting on (which file, which
194
- // database).
195
- throw new Error(
196
- `failed to read the ${spec.label} for party ${partyId}: ${error instanceof Error ? error.message : String(error)}`,
197
- { cause: error }
198
- );
199
- }
200
- if (text === undefined) return entries;
201
-
202
- let parsed: unknown;
203
- try {
204
- parsed = JSON.parse(text);
205
- } catch (error) {
206
- log('%s: corrupt slot for party %s (cold start): %o', spec.label, partyId, error);
207
- return entries;
208
- }
209
-
210
- const payload = envelopePayload(parsed, partyId, spec.payloadKey);
211
- if (!payload) {
212
- log('%s: slot for party %s has an unknown shape or a foreign partyId (cold start)', spec.label, partyId);
213
- return entries;
214
- }
215
-
216
- for (const [key, raw] of Object.entries(payload)) {
217
- const entry = spec.acceptEntry(key, raw);
218
- if (entry === undefined) {
219
- if (spec.unusableEntry === 'discard-all') {
220
- log('%s: unusable entry for %s discards the whole record (party %s, cold start)', spec.label, key, partyId);
221
- return new Map();
222
- }
223
- log('%s: dropping unusable entry for %s (party %s)', spec.label, key, partyId);
224
- continue;
225
- }
226
- entries.set(key, entry);
227
- }
228
- log('%s: loaded %d entr(ies) for party %s', spec.label, entries.size, partyId);
229
- return entries;
230
- }
231
-
232
- /**
233
- * The envelope's `key -> entry` record, or undefined on any envelope mismatch —
234
- * wrong version, wrong (or absent) `partyId`, missing or non-record payload.
235
- * Individual entries are judged separately by
236
- * {@link NodeLocalSnapshotSpec.acceptEntry}, because one bad entry does not
237
- * always mean a bad record.
238
- */
239
- function envelopePayload(
240
- value: unknown,
241
- partyId: string,
242
- payloadKey: string
243
- ): Record<string, unknown> | undefined {
244
- if (!isRecord(value)) return undefined;
245
- // A non-string partyId cannot equal the requested one, so this covers both
246
- // "malformed partyId" and "another party's record".
247
- if (value.version !== ENVELOPE_VERSION || value.partyId !== partyId) return undefined;
248
- const payload = value[payloadKey];
249
- return isRecord(payload) ? payload : undefined;
250
- }
251
-
252
- /**
253
- * A plain JSON object usable as a `key -> value` record. Arrays are excluded
254
- * explicitly: they are `typeof 'object'`, so an array payload would otherwise
255
- * reach `acceptEntry` once per numeric index — the entries all get rejected in
256
- * the end, but by accident rather than by decision, and noisily.
257
- */
258
- function isRecord(value: unknown): value is Record<string, unknown> {
259
- return typeof value === 'object' && value !== null && !Array.isArray(value);
260
- }
1
+ /**
2
+ * Shared machinery for the node's **node-local** records — the small,
3
+ * NEVER-replicated, per-party sets a node keeps for itself and never sources
4
+ * from shared group state:
5
+ *
6
+ * - the trusted-owner anchor (`trusted-owner-store.ts`),
7
+ * - the cold-start bootstrap-peer store (`bootstrap-peer-store.ts`).
8
+ *
9
+ * Both are the same mechanism with a different payload: a
10
+ * `{ version, partyId, <entries> }` envelope, snapshot-written whole on every
11
+ * change, loaded under one fail-safe-but-not-fail-silent policy. The only part
12
+ * that differs per platform is WHERE the bytes are kept — Node writes a file,
13
+ * a browser writes IndexedDB, React Native writes SecureStore or its LevelDB
14
+ * KV, NativeScript writes SQLite. That difference is the whole of
15
+ * {@link DurableSlot}, which the embedding app supplies; everything else lives
16
+ * here.
17
+ *
18
+ * This module is cross-platform (no `node:` imports), so it is safe in the
19
+ * package's default entry — the Node-only `FileDurableSlot`
20
+ * (`file-durable-slot.ts`) is what stays behind the `*-store-file` subpaths.
21
+ */
22
+ import debug from 'debug';
23
+
24
+ const log = debug('sereus:cadre:node-local-snapshot');
25
+
26
+ /**
27
+ * A single durable text slot, supplied by the embedding app. The only
28
+ * platform-specific part of a persistent node-local store.
29
+ */
30
+ export interface DurableSlot {
31
+ /**
32
+ * The slot's persisted text, or `undefined` when it was never written.
33
+ *
34
+ * MUST throw (not return `undefined`) when the slot exists but cannot be
35
+ * read. That distinction is load-bearing: `undefined` means "cold start,
36
+ * nothing was ever here", and callers snapshot-write the whole record, so a
37
+ * failed read reported as `undefined` silently converts a recoverable error
38
+ * (permissions, a blocked database upgrade, an I/O fault) into destruction
39
+ * of a still-intact record on the next save.
40
+ */
41
+ load(): Promise<string | undefined>;
42
+ /**
43
+ * Durably replace the slot's text. Callers snapshot-write the whole record,
44
+ * so an implementation never needs to merge.
45
+ */
46
+ save(text: string): Promise<void>;
47
+ }
48
+
49
+ /** Envelope version. Guards future migrations; an unknown version loads empty. */
50
+ const ENVELOPE_VERSION = 1;
51
+
52
+ /**
53
+ * What one unusable entry means for its siblings — the single intentional
54
+ * difference between the two records:
55
+ *
56
+ * - `'discard-all'` (the trusted-owner anchor): a record that cannot be read
57
+ * in full is not an anchor. Trusting a *subset* of the keys a file claims is
58
+ * a silent, security-relevant downgrade, so the whole record is discarded
59
+ * and the node trusts no one until re-seeded out of band.
60
+ * - `'drop-entry'` (the bootstrap-peer store): the record is a best-effort
61
+ * retry list and nothing in it is trust-bearing, so one junk entry must not
62
+ * discard a stranded node's only remaining way back into its party.
63
+ */
64
+ export type UnusableEntryPolicy = 'discard-all' | 'drop-entry';
65
+
66
+ /** What a particular node-local record persists, and how it validates it. */
67
+ export interface NodeLocalSnapshotSpec<E> {
68
+ /** Human name of the record, used in load errors and logs. */
69
+ readonly label: string;
70
+ /** Envelope property holding the `key -> entry` record (`owners`, `peers`). */
71
+ readonly payloadKey: string;
72
+ /** See {@link UnusableEntryPolicy}. */
73
+ readonly unusableEntry: UnusableEntryPolicy;
74
+ /**
75
+ * Validate one persisted entry, returning the value to hold in memory
76
+ * (copied, so later mutation of the parsed JSON cannot reach it) or
77
+ * `undefined` when the entry is unusable.
78
+ */
79
+ readonly acceptEntry: (key: string, entry: unknown) => E | undefined;
80
+ }
81
+
82
+ /**
83
+ * A loaded node-local record over a {@link DurableSlot}: an in-memory
84
+ * `key -> entry` map plus a serialised full-snapshot write chain.
85
+ *
86
+ * NOTE: writes are serialised in-process only. Two processes (or two browser
87
+ * tabs) sharing ONE slot for ONE party would each snapshot-write their own
88
+ * view, so the loser's entries are dropped. Fine for every backend today —
89
+ * each node gets its own directory / origin database — but a single slot
90
+ * backing two concurrent nodes of one party needs a lock or a merge-on-write,
91
+ * not a snapshot replace.
92
+ */
93
+ export class NodeLocalSnapshot<E> {
94
+ /**
95
+ * Serialises persists: every {@link put} snapshot-writes the full entry set,
96
+ * so chaining writes keeps them ordered and the last landed snapshot
97
+ * complete.
98
+ */
99
+ private writeChain: Promise<void> = Promise.resolve();
100
+
101
+ private constructor(
102
+ private readonly slot: DurableSlot,
103
+ readonly partyId: string,
104
+ private readonly spec: NodeLocalSnapshotSpec<E>,
105
+ private readonly entries: Map<string, E>
106
+ ) {}
107
+
108
+ /**
109
+ * Load (or cold-start) the party's record from `slot`. Failure policy, per
110
+ * the trust model of the anchor this was first written for: only a real,
111
+ * well-formed, matching-party record yields entries.
112
+ *
113
+ * A *decidable* non-record — slot never written, unparsable JSON, unknown
114
+ * envelope shape, `partyId` mismatch (a slot reused for a different party
115
+ * must not leak into this one) — yields an EMPTY record, the safe direction:
116
+ * the node holds nothing until it is re-seeded, rather than acting on stale
117
+ * or foreign state.
118
+ *
119
+ * A slot that is *present but unreadable* ({@link DurableSlot.load} threw)
120
+ * is NOT decidable and **throws** instead — mirroring `FileKeyStore.get`.
121
+ * Loading empty there would both hide a real misconfiguration and let the
122
+ * next {@link put} snapshot-write silently destroy a still-intact record.
123
+ */
124
+ static async open<E>(
125
+ slot: DurableSlot,
126
+ partyId: string,
127
+ spec: NodeLocalSnapshotSpec<E>
128
+ ): Promise<NodeLocalSnapshot<E>> {
129
+ return new NodeLocalSnapshot(slot, partyId, spec, await loadEntries(slot, partyId, spec));
130
+ }
131
+
132
+ has(key: string): boolean {
133
+ return this.entries.has(key);
134
+ }
135
+
136
+ /** Fresh copy of the keys — a snapshot decoupled from later {@link put} calls. */
137
+ keySnapshot(): Set<string> {
138
+ return new Set(this.entries.keys());
139
+ }
140
+
141
+ /**
142
+ * Fresh copy of the `key -> entry` map — a snapshot decoupled from later
143
+ * {@link put} calls. The entries themselves need no copy: {@link put}
144
+ * REPLACES an entry rather than mutating it in place.
145
+ */
146
+ entrySnapshot(): Map<string, E> {
147
+ return new Map(this.entries);
148
+ }
149
+
150
+ /**
151
+ * Add or replace an entry: the in-memory map updates SYNCHRONOUSLY (so a
152
+ * synchronous caller may consult the store the moment this returns), then
153
+ * the full snapshot is persisted. A persist failure rejects the returned
154
+ * promise but leaves the entry in memory — this session's decision stands,
155
+ * and any later successful {@link put} re-lands the complete set.
156
+ */
157
+ put(key: string, entry: E): Promise<void> {
158
+ this.entries.set(key, entry);
159
+ const persist = this.writeChain.then(() => this.persistSnapshot());
160
+ // The chain itself must survive a failed persist (the next put retries the
161
+ // full snapshot); the caller still observes the rejection via `persist`.
162
+ this.writeChain = persist.catch((error) => {
163
+ log('%s: persist failed for party %s: %o', this.spec.label, this.partyId, error);
164
+ });
165
+ return persist;
166
+ }
167
+
168
+ private async persistSnapshot(): Promise<void> {
169
+ const envelope: Record<string, unknown> = {
170
+ version: ENVELOPE_VERSION,
171
+ partyId: this.partyId,
172
+ [this.spec.payloadKey]: Object.fromEntries(this.entries),
173
+ };
174
+ await this.slot.save(JSON.stringify(envelope, null, '\t'));
175
+ }
176
+ }
177
+
178
+ /** Read + validate the slot's text into the initial entry map (see {@link NodeLocalSnapshot.open}). */
179
+ async function loadEntries<E>(
180
+ slot: DurableSlot,
181
+ partyId: string,
182
+ spec: NodeLocalSnapshotSpec<E>
183
+ ): Promise<Map<string, E>> {
184
+ const entries = new Map<string, E>();
185
+ let text: string | undefined;
186
+ try {
187
+ text = await slot.load();
188
+ } catch (error) {
189
+ // Present but unreadable: the one non-decidable case, and the one that must
190
+ // not cold-start empty (see NodeLocalSnapshot.open). The slot's own text is
191
+ // folded into the message, not left only on `cause`: the operator-facing
192
+ // print sites (e.g. `cadre-cli start`) log `error.message` alone, and the
193
+ // slot is what knows the platform detail worth acting on (which file, which
194
+ // database).
195
+ throw new Error(
196
+ `failed to read the ${spec.label} for party ${partyId}: ${error instanceof Error ? error.message : String(error)}`,
197
+ { cause: error }
198
+ );
199
+ }
200
+ if (text === undefined) return entries;
201
+
202
+ let parsed: unknown;
203
+ try {
204
+ parsed = JSON.parse(text);
205
+ } catch (error) {
206
+ log('%s: corrupt slot for party %s (cold start): %o', spec.label, partyId, error);
207
+ return entries;
208
+ }
209
+
210
+ const payload = envelopePayload(parsed, partyId, spec.payloadKey);
211
+ if (!payload) {
212
+ log('%s: slot for party %s has an unknown shape or a foreign partyId (cold start)', spec.label, partyId);
213
+ return entries;
214
+ }
215
+
216
+ for (const [key, raw] of Object.entries(payload)) {
217
+ const entry = spec.acceptEntry(key, raw);
218
+ if (entry === undefined) {
219
+ if (spec.unusableEntry === 'discard-all') {
220
+ log('%s: unusable entry for %s discards the whole record (party %s, cold start)', spec.label, key, partyId);
221
+ return new Map();
222
+ }
223
+ log('%s: dropping unusable entry for %s (party %s)', spec.label, key, partyId);
224
+ continue;
225
+ }
226
+ entries.set(key, entry);
227
+ }
228
+ log('%s: loaded %d entr(ies) for party %s', spec.label, entries.size, partyId);
229
+ return entries;
230
+ }
231
+
232
+ /**
233
+ * The envelope's `key -> entry` record, or undefined on any envelope mismatch —
234
+ * wrong version, wrong (or absent) `partyId`, missing or non-record payload.
235
+ * Individual entries are judged separately by
236
+ * {@link NodeLocalSnapshotSpec.acceptEntry}, because one bad entry does not
237
+ * always mean a bad record.
238
+ */
239
+ function envelopePayload(
240
+ value: unknown,
241
+ partyId: string,
242
+ payloadKey: string
243
+ ): Record<string, unknown> | undefined {
244
+ if (!isRecord(value)) return undefined;
245
+ // A non-string partyId cannot equal the requested one, so this covers both
246
+ // "malformed partyId" and "another party's record".
247
+ if (value.version !== ENVELOPE_VERSION || value.partyId !== partyId) return undefined;
248
+ const payload = value[payloadKey];
249
+ return isRecord(payload) ? payload : undefined;
250
+ }
251
+
252
+ /**
253
+ * A plain JSON object usable as a `key -> value` record. Arrays are excluded
254
+ * explicitly: they are `typeof 'object'`, so an array payload would otherwise
255
+ * reach `acceptEntry` once per numeric index — the entries all get rejected in
256
+ * the end, but by accident rather than by decision, and noisily.
257
+ */
258
+ function isRecord(value: unknown): value is Record<string, unknown> {
259
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
260
+ }