@serfab/cadre-core 0.10.0 → 0.11.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 (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -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
+ }