@serfab/cadre-host 1.14.0 → 1.16.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 (107) hide show
  1. package/README.md +19 -4
  2. package/dist/bin/host.js +32 -20
  3. package/dist/bin/host.js.map +1 -1
  4. package/dist/bin/nat-output.d.ts +5 -0
  5. package/dist/bin/nat-output.js +12 -1
  6. package/dist/bin/nat-output.js.map +1 -1
  7. package/dist/bin/ui-access.d.ts +22 -0
  8. package/dist/bin/ui-access.js +44 -0
  9. package/dist/bin/ui-access.js.map +1 -0
  10. package/dist/hosted/claim-details.d.ts +25 -3
  11. package/dist/hosted/claim-details.js +31 -37
  12. package/dist/hosted/claim-details.js.map +1 -1
  13. package/dist/hosted/hosted-node-service.d.ts +7 -0
  14. package/dist/hosted/hosted-node-service.js +16 -4
  15. package/dist/hosted/hosted-node-service.js.map +1 -1
  16. package/dist/hosted/hosted-node-watcher.d.ts +16 -4
  17. package/dist/hosted/hosted-node-watcher.js +45 -9
  18. package/dist/hosted/hosted-node-watcher.js.map +1 -1
  19. package/dist/hosted/node-status.d.ts +19 -3
  20. package/dist/hosted/node-status.js +21 -5
  21. package/dist/hosted/node-status.js.map +1 -1
  22. package/dist/hosted/types.d.ts +12 -5
  23. package/dist/hosted/types.js.map +1 -1
  24. package/dist/installer/config.d.ts +23 -0
  25. package/dist/installer/config.js +46 -0
  26. package/dist/installer/config.js.map +1 -1
  27. package/dist/installer/index.d.ts +2 -0
  28. package/dist/installer/index.js +7 -16
  29. package/dist/installer/index.js.map +1 -1
  30. package/dist/installer/wizard.d.ts +12 -2
  31. package/dist/installer/wizard.js +15 -7
  32. package/dist/installer/wizard.js.map +1 -1
  33. package/dist/nat/index.d.ts +2 -1
  34. package/dist/nat/index.js +1 -0
  35. package/dist/nat/index.js.map +1 -1
  36. package/dist/nat/nat-service.d.ts +22 -5
  37. package/dist/nat/nat-service.js +75 -26
  38. package/dist/nat/nat-service.js.map +1 -1
  39. package/dist/nat/nat-store.js +11 -0
  40. package/dist/nat/nat-store.js.map +1 -1
  41. package/dist/nat/network-mode.d.ts +19 -0
  42. package/dist/nat/network-mode.js +32 -0
  43. package/dist/nat/network-mode.js.map +1 -0
  44. package/dist/nat/reachability.d.ts +5 -4
  45. package/dist/nat/reachability.js +19 -6
  46. package/dist/nat/reachability.js.map +1 -1
  47. package/dist/nat/types.d.ts +26 -6
  48. package/dist/nat/types.js.map +1 -1
  49. package/dist/orchestrator/host-process-orchestrator.d.ts +3 -3
  50. package/dist/orchestrator/host-process-orchestrator.js +6 -15
  51. package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
  52. package/dist/package-version.d.ts +1 -0
  53. package/dist/package-version.js +4 -0
  54. package/dist/package-version.js.map +1 -0
  55. package/dist/server/routes/settings.d.ts +1 -0
  56. package/dist/server/routes/settings.js +15 -1
  57. package/dist/server/routes/settings.js.map +1 -1
  58. package/dist/server/routes/status.js +2 -32
  59. package/dist/server/routes/status.js.map +1 -1
  60. package/dist/ui/assets/index-BHd8CWZA.css +1 -0
  61. package/dist/ui/assets/index-Ccr2GjPT.js +23 -0
  62. package/dist/ui/assets/{index-4FWuU8ye.js.map → index-Ccr2GjPT.js.map} +1 -1
  63. package/dist/ui/index.html +2 -2
  64. package/package.json +4 -5
  65. package/src/__tests__/cli.smoke.test.ts +1 -1
  66. package/src/__tests__/orchestrator-claim-secret.test.ts +1 -2
  67. package/src/__tests__/orchestrator-env-scrub.test.ts +160 -163
  68. package/src/__tests__/orchestrator-handle-contract.ts +1 -1
  69. package/src/__tests__/orchestrator-node-identity.test.ts +0 -5
  70. package/src/__tests__/orchestrator-push.test.ts +3 -3
  71. package/src/__tests__/orchestrator.test.ts +3 -5
  72. package/src/__tests__/ui-access.test.ts +30 -0
  73. package/src/bin/host.ts +30 -20
  74. package/src/bin/nat-output.ts +12 -1
  75. package/src/bin/ui-access.ts +50 -0
  76. package/src/hosted/__tests__/fake-orchestrator.test.ts +0 -1
  77. package/src/hosted/__tests__/fake-orchestrator.ts +263 -265
  78. package/src/hosted/__tests__/hosted-node-service.test.ts +708 -609
  79. package/src/hosted/__tests__/hosted-node-supervisor.test.ts +475 -474
  80. package/src/hosted/claim-details.ts +44 -37
  81. package/src/hosted/hosted-node-service.ts +23 -4
  82. package/src/hosted/hosted-node-watcher.ts +288 -250
  83. package/src/hosted/node-status.ts +31 -5
  84. package/src/hosted/types.ts +160 -153
  85. package/src/installer/__tests__/installer.smoke.test.ts +184 -182
  86. package/src/installer/__tests__/wizard.test.ts +76 -56
  87. package/src/installer/config.ts +66 -0
  88. package/src/installer/index.ts +252 -259
  89. package/src/installer/wizard.ts +101 -87
  90. package/src/nat/__tests__/nat-service.test.ts +608 -540
  91. package/src/nat/__tests__/nat-store.test.ts +130 -127
  92. package/src/nat/__tests__/network-mode.test.ts +38 -0
  93. package/src/nat/index.ts +91 -87
  94. package/src/nat/nat-service.ts +79 -26
  95. package/src/nat/nat-store.ts +249 -237
  96. package/src/nat/network-mode.ts +36 -0
  97. package/src/nat/reachability.ts +155 -143
  98. package/src/nat/types.ts +232 -209
  99. package/src/orchestrator/host-process-orchestrator.ts +1089 -1098
  100. package/src/package-version.ts +4 -0
  101. package/src/server/__tests__/fakes.ts +41 -40
  102. package/src/server/__tests__/hosted-nodes-route.test.ts +161 -160
  103. package/src/server/__tests__/settings-route.test.ts +31 -0
  104. package/src/server/routes/settings.ts +128 -115
  105. package/src/server/routes/status.ts +72 -102
  106. package/dist/ui/assets/index-4FWuU8ye.js +0 -19
  107. package/dist/ui/assets/index-Di9Q4d01.css +0 -1
@@ -1,474 +1,475 @@
1
- /**
2
- * HostedNodeSupervisor unit tests — the component that notices a hosted node is
3
- * no longer running and calls `HostedNodeService.respawn`, backs off between
4
- * attempts, and eventually gives up.
5
- *
6
- * Exercised against the shared `FakeOrchestrator` (no real child processes), a
7
- * real on-disk `HostedNodeStore`, and an injected clock — so backoff and the
8
- * healthy-reset window are asserted without any wall-clock waiting.
9
- *
10
- * What is NOT covered here: that a really-respawned child rejoins its cadre.
11
- * That is the cross-package `cadre-host-join-by-qr` integration scenario.
12
- */
13
-
14
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
15
- import { mkdtempSync, rmSync } from 'node:fs';
16
- import { tmpdir } from 'node:os';
17
- import { join } from 'node:path';
18
-
19
- import { HostedNodeService } from '../hosted-node-service.js';
20
- import { HostedNodeStore } from '../hosted-node-store.js';
21
- import {
22
- HostedNodeSupervisor,
23
- HOSTED_NODE_RESPAWN_HEALTHY_MS,
24
- HOSTED_NODE_RESPAWN_MAX_ATTEMPTS,
25
- } from '../hosted-node-supervisor.js';
26
- import type { HostedNode, HostedNodeChange, HostedNodeView } from '../types.js';
27
- import { HostedNodeError } from '../types.js';
28
- import { FakeOrchestrator } from './fake-orchestrator.js';
29
- import { encodedTestInvitation } from './test-invitation.js';
30
-
31
- let tmpRoot: string;
32
-
33
- beforeEach(() => {
34
- tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-hosted-sup-'));
35
- });
36
-
37
- afterEach(() => {
38
- try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
39
- });
40
-
41
- /** Everything one test needs, sharing a single mutable clock. */
42
- interface Harness {
43
- orch: FakeOrchestrator;
44
- store: HostedNodeStore;
45
- service: HostedNodeService;
46
- supervisor: HostedNodeSupervisor;
47
- changes: HostedNodeChange[];
48
- /** Move the shared clock forward. */
49
- advance: (ms: number) => void;
50
- nowMs: () => number;
51
- /** Start one node waiting to be claimed. */
52
- join: () => Promise<HostedNodeView>;
53
- }
54
-
55
- const START_MS = Date.parse('2026-01-01T00:00:00.000Z');
56
-
57
- function makeHarness(store?: HostedNodeStore): Harness {
58
- let nowMs = START_MS;
59
- const now = (): Date => new Date(nowMs);
60
-
61
- const orch = new FakeOrchestrator();
62
- const theStore = store ?? new HostedNodeStore(join(tmpRoot, 'hosted'));
63
- const service = new HostedNodeService({
64
- orchestrator: orch,
65
- store: theStore,
66
- addresses: { publicAddressesFor: () => [], getStatus: () => ({ nodes: [] }) },
67
- now,
68
- });
69
- const changes: HostedNodeChange[] = [];
70
- service.onChange((c) => changes.push(c));
71
- const supervisor = new HostedNodeSupervisor({ service, store: theStore, orchestrator: orch, now });
72
-
73
- return {
74
- orch,
75
- store: theStore,
76
- service,
77
- supervisor,
78
- changes,
79
- advance: (ms) => { nowMs += ms; },
80
- nowMs: () => nowMs,
81
- join: () => service.join(),
82
- };
83
- }
84
-
85
- /** Mark a record claimed without going through the (fetch-driven) status watcher. */
86
- function markJoined(store: HostedNodeStore, id: string): void {
87
- store.put({ ...requireNode(store, id), status: 'joined', partyId: 'party-P', ownerKey: 'owner' });
88
- }
89
-
90
- function requireNode(store: HostedNodeStore, id: string): HostedNode {
91
- const node = store.get(id);
92
- if (!node) throw new Error(`no hosted node ${id}`);
93
- return node;
94
- }
95
-
96
- function dockerIdOf(node: { dockerId?: string }): string {
97
- if (!node.dockerId) throw new Error('hosted node has no dockerId');
98
- return node.dockerId;
99
- }
100
-
101
- /** Let queued fire-and-forget passes run. */
102
- function flush(): Promise<void> {
103
- return new Promise((res) => setTimeout(res, 5));
104
- }
105
-
106
- /** A store whose every read fails — a malformed `hosted-nodes.json` on disk. */
107
- class UnreadableStore extends HostedNodeStore {
108
- override list(): HostedNode[] {
109
- throw new HostedNodeError('storage_error', 'hosted-nodes file is not valid JSON');
110
- }
111
- }
112
-
113
- describe('HostedNodeSupervisor.reconcile', () => {
114
- it('respawns a joined-but-stopped node, keeping its status and swapping its handle', async () => {
115
- const h = makeHarness();
116
- const view = await h.join();
117
- markJoined(h.store, view.id);
118
- h.orch.crash(dockerIdOf(view));
119
-
120
- const respawned = await h.supervisor.reconcile();
121
-
122
- expect(respawned).toEqual([view.id]);
123
- const stored = requireNode(h.store, view.id);
124
- expect(stored.dockerId).toBe('dock_2');
125
- expect(stored.status).toBe('joined');
126
- expect(h.orch.createCalls).toHaveLength(2);
127
- });
128
-
129
- it('respawns an unclaimed node whose handle is dead with the record\'s secret, on the previous handle\'s ports', async () => {
130
- const h = makeHarness();
131
- const view = await h.join();
132
- const { join: joinedBy } = requireNode(h.store, view.id);
133
- const secret = joinedBy.kind === 'claim' ? joinedBy.secret : undefined;
134
- const portsBefore = h.orch.getNode(view.id)!.ports;
135
- // A host restart that found the child dead: the handle is there, the process is not.
136
- h.orch.crash(dockerIdOf(view));
137
-
138
- await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
139
-
140
- // The QR code already shown names this secret and these ports, so both must hold.
141
- expect(h.orch.createCalls[1]).toMatchObject({ containerId: view.id, partyId: 'unclaimed', claimSecret: secret });
142
- expect(h.orch.getNode(view.id)!.ports).toEqual(portsBefore);
143
- expect(requireNode(h.store, view.id)).toMatchObject({ status: 'unclaimed', dockerId: 'dock_2' });
144
- });
145
-
146
- it('respawns a joining invitation node with its invitation, and a joined one without it', async () => {
147
- const h = makeHarness();
148
- const invitation = encodedTestInvitation('party-P');
149
- const view = await h.service.join({ invitation });
150
- h.orch.crash(dockerIdOf(view));
151
-
152
- await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
153
- // Still joining: the child redeems again, and a member answers a node that already got in as accepted.
154
- expect(h.orch.createCalls[1]).toMatchObject({ containerId: view.id, partyId: 'party-P', invitation });
155
-
156
- // Joined: a member whose rows are in its own database, and whose invitation may since have expired.
157
- h.store.put({ ...requireNode(h.store, view.id), status: 'joined' });
158
- h.orch.crash(dockerIdOf(requireNode(h.store, view.id)));
159
- h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS);
160
-
161
- await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
162
- expect(h.orch.createCalls[2]).toEqual({ containerId: view.id, partyId: 'party-P', bootstrapNodes: [], profile: 'storage' });
163
- });
164
-
165
- it('leaves a running node alone', async () => {
166
- const h = makeHarness();
167
- const view = await h.join();
168
- markJoined(h.store, view.id);
169
-
170
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
171
- expect(h.orch.createCalls).toHaveLength(1);
172
- });
173
-
174
- it('never respawns a node the host gave up on', async () => {
175
- const h = makeHarness();
176
- const view = await h.join();
177
- h.store.put({ ...requireNode(h.store, view.id), status: 'error', error: 'gave up' });
178
- h.orch.crash(dockerIdOf(view));
179
-
180
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
181
- expect(h.orch.createCalls).toHaveLength(1);
182
- });
183
-
184
- it('honours the backoff window, then attempts again once the clock passes it', async () => {
185
- const h = makeHarness();
186
- const view = await h.join();
187
- markJoined(h.store, view.id);
188
- h.orch.crash(dockerIdOf(view));
189
- h.orch.failCreate = true;
190
-
191
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
192
- expect(h.orch.createCalls).toHaveLength(2);
193
- expect(requireNode(h.store, view.id).respawn?.attempts).toBe(1);
194
-
195
- // attempts = 1 → base * 2^1 = 10s. One second later is still too soon.
196
- h.advance(1_000);
197
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
198
- expect(h.orch.createCalls).toHaveLength(2);
199
- expect(requireNode(h.store, view.id).respawn?.attempts).toBe(1);
200
-
201
- h.advance(10_000);
202
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
203
- expect(h.orch.createCalls).toHaveLength(3);
204
- expect(requireNode(h.store, view.id).respawn?.attempts).toBe(2);
205
- });
206
-
207
- it('gives up after the attempt cap: record → error, child stopped but not reclaimed, change published', async () => {
208
- const h = makeHarness();
209
- const view = await h.join();
210
- markJoined(h.store, view.id);
211
- h.orch.crash(dockerIdOf(view));
212
- h.orch.failCreate = true;
213
- h.changes.length = 0;
214
-
215
- for (let i = 0; i < HOSTED_NODE_RESPAWN_MAX_ATTEMPTS; i++) {
216
- await h.supervisor.reconcile();
217
- // Well past the longest backoff, so every pass gets to attempt.
218
- h.advance(10 * 60_000);
219
- }
220
-
221
- const stored = requireNode(h.store, view.id);
222
- expect(stored.status).toBe('error');
223
- expect(stored.respawn?.attempts).toBe(HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
224
- expect(stored.error).toContain(`${HOSTED_NODE_RESPAWN_MAX_ATTEMPTS} attempts`);
225
- expect(stored.error).toContain('spawn boom');
226
- // The workdir holds the identity key the node's cadre approved — the
227
- // give-up path stops the child but must never reclaim it.
228
- //
229
- // Doubles as the standing guard on `FakeOrchestrator`'s drop being
230
- // success-only (mirroring `restoreDroppedHandles`): every create here fails,
231
- // so a fake that dropped the prior handle regardless would leave `giveUp`
232
- // with nothing to stop, and this line fails with
233
- // `expected [] to include 'dock_1'`.
234
- expect(h.orch.stopped).toContain(view.dockerId);
235
- expect(h.orch.removed).toEqual([]);
236
- expect(h.changes).toEqual([{ kind: 'changed', id: view.id }]);
237
-
238
- // `error` is terminal: no further attempts.
239
- const createsAtGiveUp = h.orch.createCalls.length;
240
- h.advance(10 * 60_000);
241
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
242
- expect(h.orch.createCalls).toHaveLength(createsAtGiveUp);
243
- });
244
-
245
- // A spawn that succeeds and then dies at once (a crash on boot, a port clash)
246
- // never throws out of `respawn`, so a give-up checked only on a throw would
247
- // respawn such a node forever.
248
- it('gives up on a node whose every respawn spawns but does not stay up', async () => {
249
- const h = makeHarness();
250
- const view = await h.join();
251
- markJoined(h.store, view.id);
252
- h.orch.crash(dockerIdOf(view));
253
- h.orch.onSpawned = (dockerId) => { h.orch.crash(dockerId); };
254
-
255
- for (let i = 0; i < HOSTED_NODE_RESPAWN_MAX_ATTEMPTS; i++) {
256
- await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
257
- // Well past the longest backoff, so every pass gets to act.
258
- h.advance(10 * 60_000);
259
- }
260
- expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
261
- expect(requireNode(h.store, view.id).status).toBe('joined');
262
-
263
- // The budget is spent and the last respawn died too: this pass gives up
264
- // instead of spawning again.
265
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
266
- const stored = requireNode(h.store, view.id);
267
- expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
268
- expect(stored.status).toBe('error');
269
- expect(stored.respawn?.attempts).toBe(HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
270
- expect(stored.error).toContain('did not stay running');
271
- // The child the record names is stopped, never reclaimed.
272
- expect(h.orch.stopped).toEqual([stored.dockerId]);
273
- expect(h.orch.removed).toEqual([]);
274
-
275
- h.advance(10 * 60_000);
276
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
277
- expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
278
- });
279
-
280
- it('refills the attempt budget once a respawned node has stayed up', async () => {
281
- const h = makeHarness();
282
- const view = await h.join();
283
- h.store.put({
284
- ...requireNode(h.store, view.id),
285
- status: 'joined',
286
- respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
287
- });
288
-
289
- // Still inside the healthy window — the crash loop's count stands.
290
- h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS - 1_000);
291
- await h.supervisor.reconcile();
292
- expect(requireNode(h.store, view.id).respawn?.attempts).toBe(3);
293
-
294
- h.advance(2_000);
295
- await h.supervisor.reconcile();
296
- expect(requireNode(h.store, view.id).respawn?.attempts).toBe(0);
297
- });
298
-
299
- it('leaves a still-spawning record alone — join owns that child', async () => {
300
- const h = makeHarness();
301
- // A handle written by a join that has not yet flipped to unclaimed.
302
- // Respawning it here would race that join and strand the record.
303
- h.store.put({
304
- id: 'hn_inflight', join: { kind: 'claim', secret: 's' }, partyId: 'unclaimed', profile: 'storage',
305
- status: 'spawning', dockerId: 'dock_inflight',
306
- createdAt: new Date(START_MS).toISOString(), updatedAt: new Date(START_MS).toISOString(),
307
- });
308
-
309
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
310
- expect(h.orch.createCalls).toEqual([]);
311
- expect(requireNode(h.store, 'hn_inflight').status).toBe('spawning');
312
- });
313
-
314
- it('skips a record that has no orchestrator handle yet', async () => {
315
- const h = makeHarness();
316
- h.store.put({
317
- id: 'hn_nohandle', join: { kind: 'claim', secret: 's' }, partyId: 'unclaimed', profile: 'storage',
318
- status: 'unclaimed',
319
- createdAt: new Date(START_MS).toISOString(), updatedAt: new Date(START_MS).toISOString(),
320
- });
321
-
322
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
323
- expect(h.orch.createCalls).toEqual([]);
324
- });
325
-
326
- it('does not undo a claim that lands while the pass is mid-flight', async () => {
327
- const h = makeHarness();
328
- const view = await h.join();
329
- h.store.put({
330
- ...requireNode(h.store, view.id),
331
- respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
332
- });
333
- h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS + 1_000);
334
-
335
- // The watcher's claim write lands between the pass's store snapshot and the
336
- // budget-refill write — the refill must merge, not replay a stale row.
337
- h.orch.onIsRunning = () => {
338
- h.orch.onIsRunning = undefined;
339
- markJoined(h.store, view.id);
340
- };
341
-
342
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
343
- const stored = requireNode(h.store, view.id);
344
- expect(stored.status).toBe('joined');
345
- expect(stored.partyId).toBe('party-P');
346
- expect(stored.respawn?.attempts).toBe(0);
347
- });
348
-
349
- it('leaves a record removed mid-attempt alone instead of recreating it as error', async () => {
350
- const h = makeHarness();
351
- const view = await h.join();
352
- h.store.put({
353
- ...requireNode(h.store, view.id),
354
- status: 'joined',
355
- // One attempt short of the cap (at the cap, the pass would give up before
356
- // attempting), and long past the longest backoff — so the next failure
357
- // lands straight in the give-up path.
358
- respawn: {
359
- attempts: HOSTED_NODE_RESPAWN_MAX_ATTEMPTS - 1,
360
- lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
361
- },
362
- });
363
- h.orch.crash(dockerIdOf(view));
364
- h.orch.failCreate = true;
365
- // The admin removes the node while the respawn's spawn is in flight.
366
- h.orch.onCreate = () => { h.store.remove(view.id); };
367
-
368
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
369
-
370
- expect(h.store.get(view.id)).toBeUndefined();
371
- expect(h.orch.stopped).toEqual([]);
372
- });
373
-
374
- it('does not count a respawn abandoned mid-spawn as a failed attempt', async () => {
375
- const h = makeHarness();
376
- const view = await h.join();
377
- markJoined(h.store, view.id);
378
- h.orch.crash(dockerIdOf(view));
379
- // The admin removes the node while the respawn's spawn is in flight.
380
- h.orch.createDelayMs = 20;
381
- let removed: Promise<void> | undefined;
382
- h.orch.onCreate = () => { removed ??= h.service.remove(view.id); };
383
-
384
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
385
- await removed;
386
-
387
- // Nothing threw, so no attempt was persisted and give-up never ran; the
388
- // abandoned child is stopped and reclaimed, not left holding ports.
389
- expect(h.store.get(view.id)).toBeUndefined();
390
- expect(h.orch.stopped).toContain('dock_2');
391
- expect(h.orch.removed).toContain('dock_2');
392
- });
393
-
394
- it('survives a pass over a store it cannot read', async () => {
395
- const h = makeHarness(new UnreadableStore(join(tmpRoot, 'hosted')));
396
-
397
- await expect(h.supervisor.reconcile()).resolves.toEqual([]);
398
- expect(h.orch.createCalls).toEqual([]);
399
- });
400
-
401
- it('serializes overlapping passes so one id is never double-spawned', async () => {
402
- const h = makeHarness();
403
- const view = await h.join();
404
- markJoined(h.store, view.id);
405
- h.orch.crash(dockerIdOf(view));
406
- h.orch.createDelayMs = 20;
407
-
408
- const [first, second] = await Promise.all([
409
- h.supervisor.reconcile(),
410
- h.supervisor.reconcile(),
411
- ]);
412
-
413
- // Whichever pass wins the tail respawns; the other then finds it running.
414
- expect([...first, ...second]).toEqual([view.id]);
415
- // The original join plus exactly one respawn.
416
- expect(h.orch.createCalls).toHaveLength(2);
417
- });
418
- });
419
-
420
- describe('HostedNodeSupervisor.restart', () => {
421
- it('stops and respawns a running node without spending its respawn budget', async () => {
422
- const h = makeHarness();
423
- const view = await h.join();
424
- const respawn = { attempts: 2, lastAttemptAt: new Date(h.nowMs()).toISOString() };
425
- const before: HostedNode = { ...requireNode(h.store, view.id), status: 'joined', partyId: 'party-P', respawn };
426
- h.store.put(before);
427
- h.advance(60_000);
428
-
429
- await h.supervisor.restart(view.id);
430
-
431
- expect(h.orch.stopped).toEqual([view.dockerId]);
432
- const after = requireNode(h.store, view.id);
433
- expect(after).toMatchObject({ status: 'joined', dockerId: 'dock_2', respawn, updatedAt: before.updatedAt });
434
- });
435
- });
436
-
437
- describe('HostedNodeSupervisor start/stop', () => {
438
- it('sweeps at startup and again on a child exit', async () => {
439
- const h = makeHarness();
440
- const view = await h.join();
441
- markJoined(h.store, view.id);
442
- h.orch.crash(dockerIdOf(view));
443
-
444
- h.supervisor.start();
445
- try {
446
- // Queued behind the startup pass, so awaiting it proves that pass ran.
447
- await h.supervisor.reconcile();
448
- expect(requireNode(h.store, view.id).dockerId).toBe('dock_2');
449
-
450
- // Now the exit-event trigger, with no manual reconcile in between.
451
- h.advance(60_000);
452
- h.orch.crash('dock_2');
453
- await flush();
454
- expect(requireNode(h.store, view.id).dockerId).toBe('dock_3');
455
- } finally {
456
- h.supervisor.stop();
457
- }
458
- });
459
-
460
- it('stops reacting to exits after stop()', async () => {
461
- const h = makeHarness();
462
- const view = await h.join();
463
- markJoined(h.store, view.id);
464
-
465
- h.supervisor.start();
466
- await h.supervisor.reconcile();
467
- h.supervisor.stop();
468
-
469
- h.orch.crash(dockerIdOf(view));
470
- await flush();
471
- // The exit listener is gone, so the crash goes unnoticed until the next start.
472
- expect(requireNode(h.store, view.id).dockerId).toBe(view.dockerId);
473
- });
474
- });
1
+ /**
2
+ * HostedNodeSupervisor unit tests — the component that notices a hosted node is
3
+ * no longer running and calls `HostedNodeService.respawn`, backs off between
4
+ * attempts, and eventually gives up.
5
+ *
6
+ * Exercised against the shared `FakeOrchestrator` (no real child processes), a
7
+ * real on-disk `HostedNodeStore`, and an injected clock — so backoff and the
8
+ * healthy-reset window are asserted without any wall-clock waiting.
9
+ *
10
+ * What is NOT covered here: that a really-respawned child rejoins its cadre.
11
+ * That is the cross-package `cadre-host-join-by-qr` integration scenario.
12
+ */
13
+
14
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
15
+ import { mkdtempSync, rmSync } from 'node:fs';
16
+ import { tmpdir } from 'node:os';
17
+ import { join } from 'node:path';
18
+
19
+ import { HostedNodeService } from '../hosted-node-service.js';
20
+ import { HostedNodeStore } from '../hosted-node-store.js';
21
+ import {
22
+ HostedNodeSupervisor,
23
+ HOSTED_NODE_RESPAWN_HEALTHY_MS,
24
+ HOSTED_NODE_RESPAWN_MAX_ATTEMPTS,
25
+ } from '../hosted-node-supervisor.js';
26
+ import type { HostedNode, HostedNodeChange, HostedNodeView } from '../types.js';
27
+ import { HostedNodeError } from '../types.js';
28
+ import { FakeOrchestrator } from './fake-orchestrator.js';
29
+ import { encodedTestInvitation } from './test-invitation.js';
30
+
31
+ let tmpRoot: string;
32
+
33
+ beforeEach(() => {
34
+ tmpRoot = mkdtempSync(join(tmpdir(), 'cadre-host-hosted-sup-'));
35
+ });
36
+
37
+ afterEach(() => {
38
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* ignore */ }
39
+ });
40
+
41
+ /** Everything one test needs, sharing a single mutable clock. */
42
+ interface Harness {
43
+ orch: FakeOrchestrator;
44
+ store: HostedNodeStore;
45
+ service: HostedNodeService;
46
+ supervisor: HostedNodeSupervisor;
47
+ changes: HostedNodeChange[];
48
+ /** Move the shared clock forward. */
49
+ advance: (ms: number) => void;
50
+ nowMs: () => number;
51
+ /** Start one node waiting to be claimed. */
52
+ join: () => Promise<HostedNodeView>;
53
+ }
54
+
55
+ const START_MS = Date.parse('2026-01-01T00:00:00.000Z');
56
+
57
+ function makeHarness(store?: HostedNodeStore): Harness {
58
+ let nowMs = START_MS;
59
+ const now = (): Date => new Date(nowMs);
60
+
61
+ const orch = new FakeOrchestrator();
62
+ const theStore = store ?? new HostedNodeStore(join(tmpRoot, 'hosted'));
63
+ const service = new HostedNodeService({
64
+ orchestrator: orch,
65
+ store: theStore,
66
+ addresses: { publicAddressesFor: () => [], getStatus: () => ({ nodes: [], gateway: { lanAddress: null }, network: { mode: 'lan' } }) },
67
+ primaryLan: async () => undefined,
68
+ now,
69
+ });
70
+ const changes: HostedNodeChange[] = [];
71
+ service.onChange((c) => changes.push(c));
72
+ const supervisor = new HostedNodeSupervisor({ service, store: theStore, orchestrator: orch, now });
73
+
74
+ return {
75
+ orch,
76
+ store: theStore,
77
+ service,
78
+ supervisor,
79
+ changes,
80
+ advance: (ms) => { nowMs += ms; },
81
+ nowMs: () => nowMs,
82
+ join: () => service.join(),
83
+ };
84
+ }
85
+
86
+ /** Mark a record claimed without going through the (fetch-driven) status watcher. */
87
+ function markJoined(store: HostedNodeStore, id: string): void {
88
+ store.put({ ...requireNode(store, id), status: 'joined', partyId: 'party-P', ownerKey: 'owner' });
89
+ }
90
+
91
+ function requireNode(store: HostedNodeStore, id: string): HostedNode {
92
+ const node = store.get(id);
93
+ if (!node) throw new Error(`no hosted node ${id}`);
94
+ return node;
95
+ }
96
+
97
+ function dockerIdOf(node: { dockerId?: string }): string {
98
+ if (!node.dockerId) throw new Error('hosted node has no dockerId');
99
+ return node.dockerId;
100
+ }
101
+
102
+ /** Let queued fire-and-forget passes run. */
103
+ function flush(): Promise<void> {
104
+ return new Promise((res) => setTimeout(res, 5));
105
+ }
106
+
107
+ /** A store whose every read fails — a malformed `hosted-nodes.json` on disk. */
108
+ class UnreadableStore extends HostedNodeStore {
109
+ override list(): HostedNode[] {
110
+ throw new HostedNodeError('storage_error', 'hosted-nodes file is not valid JSON');
111
+ }
112
+ }
113
+
114
+ describe('HostedNodeSupervisor.reconcile', () => {
115
+ it('respawns a joined-but-stopped node, keeping its status and swapping its handle', async () => {
116
+ const h = makeHarness();
117
+ const view = await h.join();
118
+ markJoined(h.store, view.id);
119
+ h.orch.crash(dockerIdOf(view));
120
+
121
+ const respawned = await h.supervisor.reconcile();
122
+
123
+ expect(respawned).toEqual([view.id]);
124
+ const stored = requireNode(h.store, view.id);
125
+ expect(stored.dockerId).toBe('dock_2');
126
+ expect(stored.status).toBe('joined');
127
+ expect(h.orch.createCalls).toHaveLength(2);
128
+ });
129
+
130
+ it('respawns an unclaimed node whose handle is dead with the record\'s secret, on the previous handle\'s ports', async () => {
131
+ const h = makeHarness();
132
+ const view = await h.join();
133
+ const { join: joinedBy } = requireNode(h.store, view.id);
134
+ const secret = joinedBy.kind === 'claim' ? joinedBy.secret : undefined;
135
+ const portsBefore = h.orch.getNode(view.id)!.ports;
136
+ // A host restart that found the child dead: the handle is there, the process is not.
137
+ h.orch.crash(dockerIdOf(view));
138
+
139
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
140
+
141
+ // The QR code already shown names this secret and these ports, so both must hold.
142
+ expect(h.orch.createCalls[1]).toMatchObject({ containerId: view.id, partyId: 'unclaimed', claimSecret: secret });
143
+ expect(h.orch.getNode(view.id)!.ports).toEqual(portsBefore);
144
+ expect(requireNode(h.store, view.id)).toMatchObject({ status: 'unclaimed', dockerId: 'dock_2' });
145
+ });
146
+
147
+ it('respawns a joining invitation node with its invitation, and a joined one without it', async () => {
148
+ const h = makeHarness();
149
+ const invitation = encodedTestInvitation('party-P');
150
+ const view = await h.service.join({ invitation });
151
+ h.orch.crash(dockerIdOf(view));
152
+
153
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
154
+ // Still joining: the child redeems again, and a member answers a node that already got in as accepted.
155
+ expect(h.orch.createCalls[1]).toMatchObject({ containerId: view.id, partyId: 'party-P', invitation });
156
+
157
+ // Joined: a member whose rows are in its own database, and whose invitation may since have expired.
158
+ h.store.put({ ...requireNode(h.store, view.id), status: 'joined' });
159
+ h.orch.crash(dockerIdOf(requireNode(h.store, view.id)));
160
+ h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS);
161
+
162
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
163
+ expect(h.orch.createCalls[2]).toEqual({ containerId: view.id, partyId: 'party-P', profile: 'storage' });
164
+ });
165
+
166
+ it('leaves a running node alone', async () => {
167
+ const h = makeHarness();
168
+ const view = await h.join();
169
+ markJoined(h.store, view.id);
170
+
171
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
172
+ expect(h.orch.createCalls).toHaveLength(1);
173
+ });
174
+
175
+ it('never respawns a node the host gave up on', async () => {
176
+ const h = makeHarness();
177
+ const view = await h.join();
178
+ h.store.put({ ...requireNode(h.store, view.id), status: 'error', error: 'gave up' });
179
+ h.orch.crash(dockerIdOf(view));
180
+
181
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
182
+ expect(h.orch.createCalls).toHaveLength(1);
183
+ });
184
+
185
+ it('honours the backoff window, then attempts again once the clock passes it', async () => {
186
+ const h = makeHarness();
187
+ const view = await h.join();
188
+ markJoined(h.store, view.id);
189
+ h.orch.crash(dockerIdOf(view));
190
+ h.orch.failCreate = true;
191
+
192
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
193
+ expect(h.orch.createCalls).toHaveLength(2);
194
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(1);
195
+
196
+ // attempts = 1 → base * 2^1 = 10s. One second later is still too soon.
197
+ h.advance(1_000);
198
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
199
+ expect(h.orch.createCalls).toHaveLength(2);
200
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(1);
201
+
202
+ h.advance(10_000);
203
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
204
+ expect(h.orch.createCalls).toHaveLength(3);
205
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(2);
206
+ });
207
+
208
+ it('gives up after the attempt cap: record → error, child stopped but not reclaimed, change published', async () => {
209
+ const h = makeHarness();
210
+ const view = await h.join();
211
+ markJoined(h.store, view.id);
212
+ h.orch.crash(dockerIdOf(view));
213
+ h.orch.failCreate = true;
214
+ h.changes.length = 0;
215
+
216
+ for (let i = 0; i < HOSTED_NODE_RESPAWN_MAX_ATTEMPTS; i++) {
217
+ await h.supervisor.reconcile();
218
+ // Well past the longest backoff, so every pass gets to attempt.
219
+ h.advance(10 * 60_000);
220
+ }
221
+
222
+ const stored = requireNode(h.store, view.id);
223
+ expect(stored.status).toBe('error');
224
+ expect(stored.respawn?.attempts).toBe(HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
225
+ expect(stored.error).toContain(`${HOSTED_NODE_RESPAWN_MAX_ATTEMPTS} attempts`);
226
+ expect(stored.error).toContain('spawn boom');
227
+ // The workdir holds the identity key the node's cadre approved — the
228
+ // give-up path stops the child but must never reclaim it.
229
+ //
230
+ // Doubles as the standing guard on `FakeOrchestrator`'s drop being
231
+ // success-only (mirroring `restoreDroppedHandles`): every create here fails,
232
+ // so a fake that dropped the prior handle regardless would leave `giveUp`
233
+ // with nothing to stop, and this line fails with
234
+ // `expected [] to include 'dock_1'`.
235
+ expect(h.orch.stopped).toContain(view.dockerId);
236
+ expect(h.orch.removed).toEqual([]);
237
+ expect(h.changes).toEqual([{ kind: 'changed', id: view.id }]);
238
+
239
+ // `error` is terminal: no further attempts.
240
+ const createsAtGiveUp = h.orch.createCalls.length;
241
+ h.advance(10 * 60_000);
242
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
243
+ expect(h.orch.createCalls).toHaveLength(createsAtGiveUp);
244
+ });
245
+
246
+ // A spawn that succeeds and then dies at once (a crash on boot, a port clash)
247
+ // never throws out of `respawn`, so a give-up checked only on a throw would
248
+ // respawn such a node forever.
249
+ it('gives up on a node whose every respawn spawns but does not stay up', async () => {
250
+ const h = makeHarness();
251
+ const view = await h.join();
252
+ markJoined(h.store, view.id);
253
+ h.orch.crash(dockerIdOf(view));
254
+ h.orch.onSpawned = (dockerId) => { h.orch.crash(dockerId); };
255
+
256
+ for (let i = 0; i < HOSTED_NODE_RESPAWN_MAX_ATTEMPTS; i++) {
257
+ await expect(h.supervisor.reconcile()).resolves.toEqual([view.id]);
258
+ // Well past the longest backoff, so every pass gets to act.
259
+ h.advance(10 * 60_000);
260
+ }
261
+ expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
262
+ expect(requireNode(h.store, view.id).status).toBe('joined');
263
+
264
+ // The budget is spent and the last respawn died too: this pass gives up
265
+ // instead of spawning again.
266
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
267
+ const stored = requireNode(h.store, view.id);
268
+ expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
269
+ expect(stored.status).toBe('error');
270
+ expect(stored.respawn?.attempts).toBe(HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
271
+ expect(stored.error).toContain('did not stay running');
272
+ // The child the record names is stopped, never reclaimed.
273
+ expect(h.orch.stopped).toEqual([stored.dockerId]);
274
+ expect(h.orch.removed).toEqual([]);
275
+
276
+ h.advance(10 * 60_000);
277
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
278
+ expect(h.orch.createCalls).toHaveLength(1 + HOSTED_NODE_RESPAWN_MAX_ATTEMPTS);
279
+ });
280
+
281
+ it('refills the attempt budget once a respawned node has stayed up', async () => {
282
+ const h = makeHarness();
283
+ const view = await h.join();
284
+ h.store.put({
285
+ ...requireNode(h.store, view.id),
286
+ status: 'joined',
287
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
288
+ });
289
+
290
+ // Still inside the healthy window — the crash loop's count stands.
291
+ h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS - 1_000);
292
+ await h.supervisor.reconcile();
293
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(3);
294
+
295
+ h.advance(2_000);
296
+ await h.supervisor.reconcile();
297
+ expect(requireNode(h.store, view.id).respawn?.attempts).toBe(0);
298
+ });
299
+
300
+ it('leaves a still-spawning record alone — join owns that child', async () => {
301
+ const h = makeHarness();
302
+ // A handle written by a join that has not yet flipped to unclaimed.
303
+ // Respawning it here would race that join and strand the record.
304
+ h.store.put({
305
+ id: 'hn_inflight', join: { kind: 'claim', secret: 's' }, partyId: 'unclaimed', profile: 'storage',
306
+ status: 'spawning', dockerId: 'dock_inflight',
307
+ createdAt: new Date(START_MS).toISOString(), updatedAt: new Date(START_MS).toISOString(),
308
+ });
309
+
310
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
311
+ expect(h.orch.createCalls).toEqual([]);
312
+ expect(requireNode(h.store, 'hn_inflight').status).toBe('spawning');
313
+ });
314
+
315
+ it('skips a record that has no orchestrator handle yet', async () => {
316
+ const h = makeHarness();
317
+ h.store.put({
318
+ id: 'hn_nohandle', join: { kind: 'claim', secret: 's' }, partyId: 'unclaimed', profile: 'storage',
319
+ status: 'unclaimed',
320
+ createdAt: new Date(START_MS).toISOString(), updatedAt: new Date(START_MS).toISOString(),
321
+ });
322
+
323
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
324
+ expect(h.orch.createCalls).toEqual([]);
325
+ });
326
+
327
+ it('does not undo a claim that lands while the pass is mid-flight', async () => {
328
+ const h = makeHarness();
329
+ const view = await h.join();
330
+ h.store.put({
331
+ ...requireNode(h.store, view.id),
332
+ respawn: { attempts: 3, lastAttemptAt: new Date(h.nowMs()).toISOString() },
333
+ });
334
+ h.advance(HOSTED_NODE_RESPAWN_HEALTHY_MS + 1_000);
335
+
336
+ // The watcher's claim write lands between the pass's store snapshot and the
337
+ // budget-refill write — the refill must merge, not replay a stale row.
338
+ h.orch.onIsRunning = () => {
339
+ h.orch.onIsRunning = undefined;
340
+ markJoined(h.store, view.id);
341
+ };
342
+
343
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
344
+ const stored = requireNode(h.store, view.id);
345
+ expect(stored.status).toBe('joined');
346
+ expect(stored.partyId).toBe('party-P');
347
+ expect(stored.respawn?.attempts).toBe(0);
348
+ });
349
+
350
+ it('leaves a record removed mid-attempt alone instead of recreating it as error', async () => {
351
+ const h = makeHarness();
352
+ const view = await h.join();
353
+ h.store.put({
354
+ ...requireNode(h.store, view.id),
355
+ status: 'joined',
356
+ // One attempt short of the cap (at the cap, the pass would give up before
357
+ // attempting), and long past the longest backoff — so the next failure
358
+ // lands straight in the give-up path.
359
+ respawn: {
360
+ attempts: HOSTED_NODE_RESPAWN_MAX_ATTEMPTS - 1,
361
+ lastAttemptAt: new Date(h.nowMs() - 10 * 60_000).toISOString(),
362
+ },
363
+ });
364
+ h.orch.crash(dockerIdOf(view));
365
+ h.orch.failCreate = true;
366
+ // The admin removes the node while the respawn's spawn is in flight.
367
+ h.orch.onCreate = () => { h.store.remove(view.id); };
368
+
369
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
370
+
371
+ expect(h.store.get(view.id)).toBeUndefined();
372
+ expect(h.orch.stopped).toEqual([]);
373
+ });
374
+
375
+ it('does not count a respawn abandoned mid-spawn as a failed attempt', async () => {
376
+ const h = makeHarness();
377
+ const view = await h.join();
378
+ markJoined(h.store, view.id);
379
+ h.orch.crash(dockerIdOf(view));
380
+ // The admin removes the node while the respawn's spawn is in flight.
381
+ h.orch.createDelayMs = 20;
382
+ let removed: Promise<void> | undefined;
383
+ h.orch.onCreate = () => { removed ??= h.service.remove(view.id); };
384
+
385
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
386
+ await removed;
387
+
388
+ // Nothing threw, so no attempt was persisted and give-up never ran; the
389
+ // abandoned child is stopped and reclaimed, not left holding ports.
390
+ expect(h.store.get(view.id)).toBeUndefined();
391
+ expect(h.orch.stopped).toContain('dock_2');
392
+ expect(h.orch.removed).toContain('dock_2');
393
+ });
394
+
395
+ it('survives a pass over a store it cannot read', async () => {
396
+ const h = makeHarness(new UnreadableStore(join(tmpRoot, 'hosted')));
397
+
398
+ await expect(h.supervisor.reconcile()).resolves.toEqual([]);
399
+ expect(h.orch.createCalls).toEqual([]);
400
+ });
401
+
402
+ it('serializes overlapping passes so one id is never double-spawned', async () => {
403
+ const h = makeHarness();
404
+ const view = await h.join();
405
+ markJoined(h.store, view.id);
406
+ h.orch.crash(dockerIdOf(view));
407
+ h.orch.createDelayMs = 20;
408
+
409
+ const [first, second] = await Promise.all([
410
+ h.supervisor.reconcile(),
411
+ h.supervisor.reconcile(),
412
+ ]);
413
+
414
+ // Whichever pass wins the tail respawns; the other then finds it running.
415
+ expect([...first, ...second]).toEqual([view.id]);
416
+ // The original join plus exactly one respawn.
417
+ expect(h.orch.createCalls).toHaveLength(2);
418
+ });
419
+ });
420
+
421
+ describe('HostedNodeSupervisor.restart', () => {
422
+ it('stops and respawns a running node without spending its respawn budget', async () => {
423
+ const h = makeHarness();
424
+ const view = await h.join();
425
+ const respawn = { attempts: 2, lastAttemptAt: new Date(h.nowMs()).toISOString() };
426
+ const before: HostedNode = { ...requireNode(h.store, view.id), status: 'joined', partyId: 'party-P', respawn };
427
+ h.store.put(before);
428
+ h.advance(60_000);
429
+
430
+ await h.supervisor.restart(view.id);
431
+
432
+ expect(h.orch.stopped).toEqual([view.dockerId]);
433
+ const after = requireNode(h.store, view.id);
434
+ expect(after).toMatchObject({ status: 'joined', dockerId: 'dock_2', respawn, updatedAt: before.updatedAt });
435
+ });
436
+ });
437
+
438
+ describe('HostedNodeSupervisor start/stop', () => {
439
+ it('sweeps at startup and again on a child exit', async () => {
440
+ const h = makeHarness();
441
+ const view = await h.join();
442
+ markJoined(h.store, view.id);
443
+ h.orch.crash(dockerIdOf(view));
444
+
445
+ h.supervisor.start();
446
+ try {
447
+ // Queued behind the startup pass, so awaiting it proves that pass ran.
448
+ await h.supervisor.reconcile();
449
+ expect(requireNode(h.store, view.id).dockerId).toBe('dock_2');
450
+
451
+ // Now the exit-event trigger, with no manual reconcile in between.
452
+ h.advance(60_000);
453
+ h.orch.crash('dock_2');
454
+ await flush();
455
+ expect(requireNode(h.store, view.id).dockerId).toBe('dock_3');
456
+ } finally {
457
+ h.supervisor.stop();
458
+ }
459
+ });
460
+
461
+ it('stops reacting to exits after stop()', async () => {
462
+ const h = makeHarness();
463
+ const view = await h.join();
464
+ markJoined(h.store, view.id);
465
+
466
+ h.supervisor.start();
467
+ await h.supervisor.reconcile();
468
+ h.supervisor.stop();
469
+
470
+ h.orch.crash(dockerIdOf(view));
471
+ await flush();
472
+ // The exit listener is gone, so the crash goes unnoticed until the next start.
473
+ expect(requireNode(h.store, view.id).dockerId).toBe(view.dockerId);
474
+ });
475
+ });